Mapping CSV data to customized fileds - java

I am new to Java Spring boot and I am trying to read data from a CSV file and then pass this data to my UI via REST.
I am using OpenCSV to parse my file. Here is my sample line in my file
firstname, lastname, card details.
card details consists of card number and expiry date. So my example text looks like:
joe, keller, 123456 22-2-1999.
The output from my rest end point should be:
{
"firstname": "joe",
"lastname" : "keller",
"card number" : "123456",
"expiry date" : 22-2-1999
}
I currently read the file using CsvToBeanBuilder and I seem to get stuck with mapping the final line to two different items.

Because the last column contains 2 fields - card number and expiry date, you cannot directly use CsvToBeanBuilder to read CSV file and convert it to your POJO. A alternative way is shown as follows:
First, I assume that you have already a POJO looks like:
class CreditCardInfo {
private String firstname;
private String lastname;
private String cardNumber;
private String expiryDate;
//general getters and setters
//toString()
}
Then you can use CSVReader.readNext() to read each line into a string array. And for the 3-rd column in CSV file you can separate it into 2 fields by empty space(" "): "123456" and "22-2-1999" with String.trim() for ignoring leading space. Therefore, you can store these fields to cardNumber and expiryDate of the POJO CreditCardInfo, respectively.
Code snippet
try (
Reader reader = Files.newBufferedReader(Paths.get("So58792579.csv"));
CSVReader csvReader = new CSVReader(reader);
) {
String[] nextRecord;
while ((nextRecord = csvReader.readNext()) != null) {
CreditCardInfo creditCardInfo = new CreditCardInfo();
creditCardInfo.setFirstname(nextRecord[0]);
creditCardInfo.setLastname(nextRecord[1].trim()); //trim() for ignoring leading space
creditCardInfo.setCardNumber(nextRecord[2].trim().split(" ")[0]);
creditCardInfo.setExpiryDate(nextRecord[2].trim().split(" ")[1]);
System.out.println(creditCardInfo.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
Console output
CreditCardInfo [firstname=joe, lastname=keller, cardNumber=123456, expiryDate=22-2-1999]

Related

how to define value object for file in java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I wrote a program that creates 3 files with .txt format and writes some data's into them.
Now I am asked to define a value object for these files, And override the toString method, And then when I read the files Set them in to Value objects.
Now I'm completely confused and do not know where to start.
Thank you in advance for your help
If you want to create objects from text files first what are you going to do is read the file. There are many available classes in the Java API that can be used to read files: BufferedReader, FileReader etc.
The number of objects you will create will depend on the number of lines in the file. For example if you have a file with the following content
PersonName1,PersonSurname1,20
PersonName2,PersonSurname2,22
PersonName3,PersonSurname3,23
Let's say that these lines represent name, surname, and age of some users
What you need to do first is create a class that will represent this object, as we see in the text file the object will contain three parameters , so you create a class with three atribbutes
public class Person {
private String name;
private String surname;
private Integer age;
public Person(String name, String surname, Integer age) {
this.name = name;
this.surname = surname;
this.age = age;
}
#Override
public String toString() {
return "NAME : " + name + " : " + surname;
}
Now comes the reading part , for reading the file we will use BufferedReader, we read every line of the file by splitting the line by commas(,) for every iteration
String [] parameters = line.split(",");
This array of String now will represent our user attributes so we access it
String name = parameters[0];
String surname = parameters[1];
Integer age = Integer.parseInt(parameters[2]);
And now we create an object of Person every iteration and we add it to the list
Person p = new Person(name,surname,age);
list.add(p);
Example
BufferedReader bufferedReader = new BufferedReader(new FileReader("test.txt"));
List<Person> list = new ArrayList<>();
String line = null;
while((line = bufferedReader.readLine())!=null){
try {
String[] parameters = line.split(",");
if(parameters.length == 3) {
String name = parameters[0];
String surname = parameters[1];
Integer age = Integer.parseInt(parameters[2]);
Person p = new Person(name, surname, age);
list.add(p);
}
}catch (NumberFormatException e){
}
}
System.out.println("Object created from the file");
list.stream().forEach(System.out::println);
OUTPUT
NAME : PersonName1 : PersonSurname1
NAME : PersonName2 : PersonSurname2
NAME : PersonName3 : PersonSurname3

Android read text file and store into variable based on first word

I am doing a reading text file practice where I read and store the data into a string array object. One ArrayList data should have photo, title, website, and date. The text file looks like this:
photo:android_pie
title:Android Pie: Everything you need to know about Android 9
website:https://www.androidcentral.com/pie
date:20-08-2018
photo:oppo
title:OPPO Find X display
website:https://www.androidpit.com/oppo-find-x-display-review
date:25-08-2018
photo:android_pie2
title:Android 9 Pie: What Are App Actions & How To Use Them
website:https://www.androidheadlines.com/2018/08/android-9-pie-what-are-app-
actions-how-to-use-them.html
date:16-09-2018
I am trying to split and store them into a string array, which is an instance of my object class:
private List<ItemObjects> itemList;
and this is the constructor of my object class:
public ItemObjects(String photo, String name, String link, String date) {
this.photo = photo;
this.name = name;
this.link = link;
this.date = date;
}
I tried this but the ":" separator doesnt separate it like I want it to:
while ((sItems = bufferedReader.readLine()) != null) {
if (!sItems.equals("")) {
String[] tmpItemArr = sItems.split("\\:");
listViewItems.add(new ItemObjects(tmpItemArr[0], tmpItemArr[1], tmpItemArr[2], tmpItemArr[3]));
}
}
What is the best way of doing this? I have tried using for loop which stops at third line and adds the next one as new data. There are several online ways of doing it but some are very complicated and I am having trouble understanding it.
The problem is your understanding of using both the split function and the BufferReader.
By using readline function you are reading only one line so your split will split the first line only, you need to read the 4 first lines then add the item.
int count = 0;
String[] tmpItemArr = new String[4];
while ((sItems = bufferedReader.readLine()) != null) {
if (!sItems.equals("")) {
tmpItemArr[count] = sItems.split(":")[1];
count++;
if (count > 3) {
listViewItems.add(new ItemObjects(tmpItemArr[0], tmpItemArr[1], tmpItemArr[2], tmpItemArr[3]));
count = 0;
}
}
}

NullPointerException when setting variables to objects in ArrayList

I have an ArrayList containing Movie objects which I produced from a List containing File objects using this method:
// returns a list containing movie objects with correct names
private static ArrayList<Movie> createMovieObjs(Collection<File> videoFiles) {
ArrayList<Movie> movieArrayList = new ArrayList<>();
Matcher matcher;
for (File file : videoFiles) {
matcher = Movie.NAME_PATTERN.matcher(file.getName());
while (matcher.find()) {
String movieName = matcher.group(1).replaceAll("\\.", " ");
Movie movie = new Movie(movieName);
if (!movieArrayList.contains(movie)) {
movieArrayList.add(movie);
}
}
}
return movieArrayList;
}
Everything works fine in above code, getting correct ArrayList.
Then I want to parse info for each Movie object in this ArrayList and set that info to that Movie object:
// want to parse genre, release year and imdbrating for every Movie object
for (Movie movie : movieArrayList) {
try {
movie.imdbParser();
} catch (IOException e) {
System.out.println("Parsing failed: " + e);
}
}
Here is Movie.imdbParser which uses Movie.createXmlLink (createXmlLink works fine on its own, so thas imdbParser - tested both):
private String createXmlLink() {
StringBuilder sb = new StringBuilder(XML_PART_ONE);
// need to replace spaces in movie names to "+" - api works that way
String namePassedToXml = this.title.replaceAll(" ", "+");
sb.append(namePassedToXml);
sb.append(XML_PART_TWO);
return sb.toString();
}
// parses IMDB page and sets releaseDate, genre and imdbRating in Movie objects
public void imdbParser() throws IOException {
String xmlLink = createXmlLink();
// using "new Url..." because my xml is on the web, not on my disk
Document doc = Jsoup.parse(new URL(xmlLink).openStream(), "UTF-8", "", Parser.xmlParser());
Element movieFromXml = doc.select("movie").first();
// using array to extract only last genre name - usually the most substantive one
String[] genreArray = movieFromXml.attr("genre").split(", ");
this.genre = genreArray[genreArray.length - 1];
this.imdbRating = Float.parseFloat(movieFromXml.attr("imdbRating"));
// using array to extract only year of release
String[] dateArray = movieFromXml.attr("released").split(" ");
this.releaseYear = Integer.parseInt(dateArray[2]);
}
Problems seems to be with accessing Movie objects, it doesn't create good XMLLink so when it tries to access genre in XML it throws NPE.
My error:
Exception in thread "main" java.lang.NullPointerException
at com.michal.Movie.imdbParser(Movie.java:79)
at com.michal.Main.main(Main.java:52)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Movie.java:79 is:
String[] genreArray = movieFromXml.attr("genre").split(", ");
and Main.java:52 is:
movie.imdbParser();
A lot of errors such as this are caused by the data not being as you expect. Often when dealing with a lot of data then sometimes it can be just a single record that does not "conform"!
You say that this line is causing you problems;
String[] genreArray = movieFromXml.attr("genre").split(", ");
So split the line down and debug your application to find the issue. If you can't debug then export the results to a log file.
Check that movieFromXml is not NULL.
Check that movieFromXml contains a "genre" attribute as you expect
Check that the data in the attribute can be split as you expect, and produces a valid output.
Often, it is good to view the data being retrieved prior to this call. I often find it useful to dump the data out to file and then load it in an external viewer to check that it is how I expect.
When you make a chain of calling method like this: movieFromXml.attr("genre").split(", "), you have to make sure that each of the preceding element is not null. In this case, you have to make sure that movieFromXml is not null and movieFromXml.attr("genre") is not null.

Java - Parse delimited file and find column datatypes

Is it possible to parse a delimited file and find column datatypes? e.g
Delimited file:
Email,FirstName,DOB,Age,CreateDate
test#test1.com,Test User1,20/01/2001,24,23/02/2015 14:06:45
test#test2.com,Test User2,14/02/2001,24,23/02/2015 14:06:45
test#test3.com,Test User3,15/01/2001,24,23/02/2015 14:06:45
test#test4.com,Test User4,23/05/2001,24,23/02/2015 14:06:45
Output:
Email datatype: email
FirstName datatype: Text
DOB datatype: date
Age datatype: int
CreateDate datatype: Timestamp
The purpose of this is to read a delimited file and construct a table creation query on the fly and insert data into that table.
I tried using apache validator, I believe we need to parse the complete file in order to determine each column data type.
EDIT: The code that I've tried:
CSVReader csvReader = new CSVReader(new FileReader(fileName),',');
String[] row = null;
int[] colLength=(int[]) null;
int colCount = 0;
String[] colDataType = null;
String[] colHeaders = null;
String[] header = csvReader.readNext();
if (header != null) {
colCount = header.length;
}
colLength = new int[colCount];
colDataType = new String[colCount];
colHeaders = new String[colCount];
for (int i=0;i<colCount;i++){
colHeaders[i]=header[i];
}
int templength=0;
String tempType = null;
IntegerValidator intValidator = new IntegerValidator();
DateValidator dateValidator = new DateValidator();
TimeValidator timeValidator = new TimeValidator();
while((row = csvReader.readNext()) != null) {
for(int i=0;i<colCount;i++) {
templength = row[i].length();
colLength[i] = templength > colLength[i] ? templength : colLength[i];
if(colHeaders[i].equalsIgnoreCase("email")){
logger.info("Col "+i+" is Email");
} else if(intValidator.isValid(row[i])){
tempType="Integer";
logger.info("Col "+i+" is Integer");
} else if(timeValidator.isValid(row[i])){
tempType="Time";
logger.info("Col "+i+" is Time");
} else if(dateValidator.isValid(row[i])){
tempType="Date";
logger.info("Col "+i+" is Date");
} else {
tempType="Text";
logger.info("Col "+i+" is Text");
}
logger.info(row[i].length()+"");
}
Not sure if this is the best way of doing this, any pointers in the right direction would be of help
If you wish to write this yourself rather than use a third party library then probably the easiest mechanism is to define a regular expression for each data type and then check if all fields satisfy it. Here's some sample code to get you started (using Java 8).
public enum DataType {
DATETIME("dd/dd/dddd dd:dd:dd"),
DATE("dd/dd/dddd",
EMAIL("\\w+#\\w+"),
TEXT(".*");
private final Predicate<String> tester;
DateType(String regexp) {
tester = Pattern.compile(regexp).asPredicate();
}
public static Optional<DataType> getTypeOfField(String[] fieldValues) {
return Arrays.stream(values())
.filter(dt -> Arrays.stream(fieldValues).allMatch(dt.tester)
.findFirst();
}
}
Note that this relies on the order of the enum values (e.g. testing for datetime before date).
Yes it is possible and you do have to parse the entire file first. Have a set of rules for each data type. Iterate over every row in the column. Start of with every column having every data type and cancel of data types if a row in that column violates a rule of that data type. After iterating the column check what data type is left for the column. Eg. Lets say we have two data types integer and text... rules for integer... well it must only contain numbers 0-9 and may begin with '-'. Text can be anything.
Our column:
345
-1ab
123
The integer data type would be removed by the second row so it would be text. If row two was just -1 then you would be left with integer and text so it would be integer because text would never be removed as our rule says text can be anything... you dont have to check for text basically if you left with no other data type the answer is text. Hope this answers your question
I have slight similar kind of logic needed for my project. Searched lot but did not get right solution. For me i need to pass string object to the method that should return datatype of the obj. finally i found post from #sprinter, it looks similar to my logic but i need to pass string instead of string array.
Modified the code for my need and posted below.
public enum DataType {
DATE("dd/dd/dddd"),
EMAIL("#gmail"),
NUMBER("[0-9]+"),
STRING("^[A-Za-z0-9? ,_-]+$");
private final String regEx;
public String getRegEx() {
return regEx;
}
DataType(String regEx) {
this.regEx = regEx;
}
public static Optional<DataType> getTypeOfField(String str) {
return Arrays.stream(DataType.values())
.filter(dt -> {
return Pattern.compile(dt.getRegEx()).matcher(str).matches();
})
.findFirst();
}
}
For example:
Optional<DataType> dataType = getTypeOfField("Bharathiraja");
System.out.println(dataType);
System.out.println(dataType .get());
Output:
Optional[STRING]
STRING
Please note, regular exp pattern is vary based on requirements, so modify the pattern as per your need don't take as it is.
Happy Coding !

How to Bind a Model to a SWT Text but showing only one field in the text

I have a Remote File Model which has fields as file name, file path, and connection IP,connection port etc for the remote directory.I want to show only the file path in a Text.
I am using JFace Data binding for binding the model to SWT Text but I am able to bind only 1 field to it.
Please help me to bind the Complete model to the Text and showing only one field.
Also tell me if it is possible or not or there is some other way.
If I understand you correctly you want to show multiple model fields in one SWT Text widget? You can do it in the following way:
class FileModel {
private String name;
private String filePath;
private String ip;
// other fields, getters and setters
public String getFileSummary() {
return name + " : " + filePath + " : " + ip;
}
public void setFileSummary(String summary) {
// ignore
}
}
Then you can bind it like this:
FileModel model;
new DataBindingContext().bindValue(SWTObservables.observeText(text, SWT.Modify),
BeansObservables.observeValue(model, "fileSummary"), new UpdateValueStrategy(), new UpdateValueStrategy());
The idea is that while specifying "fileSummary" field name to bind in your model, JFace will look for getter and setter for that field, so you don't actually need a field itself.
In getter you can provided required info and you could even parse some special format in setter and assign those to related fields, something like this:
public void setFileSummary(String summary) {
// todo: implement in a smart way;)
String[] parts = summary.split(" : ");
name = parts[0];
filePath = parts[1];
ip = parts[2];
}

Categories

Resources