I have included my code above. I have a buffered reader, which I am attempting to use to read textfiles.
I need Review + Restaurant otherwise I get review values printed as "null"
#Override
public Repository load(String filename) {
Repository repository = new Repository();
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
//ArrayList <Review> review=new ArrayList<>();
String[] revs;
String line = br.readLine();
while(line!=null){
revs=line.split(Character.toString(DELIMITER));
int id = Integer.valueOf(revs[0]);
String name= stripQuotes(revs[1]);
String location = stripQuotes(revs[2]);
Restaurant restaurant = new Restaurant(id, name,location);
int noreview=Integer.parseInt(revs[3]);
for (int i=0; i<noreview; i++) {
line = br.readLine();
revs=line.split(Character.toString(DELIMITER));
String reviewer = stripQuotes(revs[4]);
int rating= Integer.parseInt(revs[5]);
Review review = new Review (reviewer, rating);
repository.add(restaurant);
repository.add(review);
}
}
br.close();
} catch (IOException ex) {
Logger.getLogger(DAOTextImpl.class.getName()).log(Level.SEVERE, null, ex);
}
return repository;
}
Related
I have an application that reads csv files in a folder and then reads those csv files and put them in a databse but I am not able to figure out how to populate database as soon as I run my spring boot program
my FlightService.java
package com.package.service;
#Service
public class FlightService{
File dir = new File("C:\\Users\\Akhil\\Desktop\\assignmentFour\\CSV");
static FlightDao flightDao = (FlightDao) AppContextUtil.context.getBean("flightDao");
public void readCSV() {
File files[] = dir.listFiles();
ArrayList<String> listofFileNames = new ArrayList<String>();
for (File file : files) {
Airline airline = FlightController.readFile(file);
flightDao.saveAirline(airline);
}
}
}
FlightController.java
package com.package.controller;
public class FlightController {
public static final SimpleDateFormat dateformat = new SimpleDateFormat("dd-MM-yyyy");
public static Airline readFile(File file) {
BufferedReader reader = null;
Airline aObj = new Airline();
aObj.setName(file.getName());
HashSet<Flight> flight_Set = new HashSet<Flight>();
try {
reader = new BufferedReader(new FileReader(file));
String line = reader.readLine();
line = reader.readLine();
while (line != null) {
Flight f = manipulateLine(line,aObj);
line = reader.readLine();
flight_Set.add(f);
}
} catch (Exception e) {
System.err.println("Could Not Read the File");
} finally {
if (reader != null) {
try {
reader.close();
} catch (Exception e) {
System.err.println("Could Not Close the File");
}
}
}
aObj.setFlights(flight_Set);
return aObj;
}
private static Flight manipulateLine(String line, Airline aObj) {
StringTokenizer st = new StringTokenizer(line, "|");
String flightNo = st.nextToken();
String depLoc = st.nextToken();
String arrLoc = st.nextToken();
String validTillDate = st.nextToken();
Date validTill = new Date();
try {
validTill = dateformat.parse(validTillDate);
} catch (ParseException e) {
System.err.print("Date not in appropriate(dd-MM-yyyy) format");
}
int flightTime = Integer.parseInt(st.nextToken());
Double flightDuration = Double.parseDouble(st.nextToken());
int fare = Integer.parseInt(st.nextToken());
String avail = st.nextToken();
Boolean seatAvailability;
if (avail.charAt(0) == 'Y')
seatAvailability = true;
else
seatAvailability = false;
String flightClass = st.nextToken();
return new Flight(flightNo, depLoc, arrLoc, fare, validTill,
flightTime, flightDuration, seatAvailability, flightClass,aObj);
}
}
For url
package com.package.controller;
#Controller
public class FlightCont {
#RequestMapping(value ="/flightSearch" , method=RequestMethod.POST)
public ModelAndView flightSearch(#Valid #ModelAttribute("flightDetails")FlightDetailsEntered flightDetails,BindingResult result){
ModelAndView modelAndView =new ModelAndView("flightSearch");
if(result.hasErrors())
{
System.err.println(result);
return modelAndView ;
}
List<Flight> listOfMatchingFlights= flightDetails.getListOfMatchingFlights();
modelAndView = new ModelAndView("flightList");
modelAndView.addObject("list", listOfMatchingFlights);
return modelAndView ;
}
}
As I run the program i am getting this error
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'flightService' defined in file [C:\Users\Akhil\Desktop\project\target\classes\com\package\service\FlightService.class]: Instantiation of bean failed; nested exception is java.lang.ExceptionInInitializerError
I don't know what I am doing wrong here any suggestions would be really helpful
You can keep file in classpath(src/main/resources) and load the file as mentioned below,
package com.package.service;
#Service
public class FlightService{
public void readCSV() {
InputStream stream = readerFile("CSV.txt");
try (BufferedReader br = new BufferedReader(new InputStreamReader(stream))) {
String line = br.readLine();
System.out.println(line);
} catch (IOException e) {
//do nothing
}
}
private InputStream readerFile(String fileName) {
return getClass().getClassLoader().getResourceAsStream(fileName);
}
}
I am working on a java project using hibernate. I have a csv file that contains more than 200 data. I've successfully retrieved data from csv file. Now I have to insert those data to the table.
The problem is only the last row is being added to the table. Other rows are not being inserted.
The schema of the table is given below:
INSERT INTO `attendence_table`
(`serial_no` int auto-increment,
`employee_id` varchar2,
`in_time` varchar2,
`out_time` varchar2,
`attend_date` date)
The Attendence class is given below:
#Entity
#Table(name = "attendence_table")
public class Attendence {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "serial_no")
private int id;
#Column(name = "employee_id")
private String employee_id;
#Column(name = "in_time")
private String inTime;
#Column(name = "out_time")
private String outTime;
#Column(name = "attend_date")
private String date;
public String getEmployee_id() {
return employee_id;
}
public void setEmployee_id(String employee_id) {
this.employee_id = employee_id;
}
public String getInTime() {
return inTime;
}
public void setInTime(String inTime) {
this.inTime = inTime;
}
public String getOutTime() {
return outTime;
}
public void setOutTime(String outTime) {
this.outTime = outTime;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
The insert function is given below:
private static SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
public static void hibernateInsertAttendenceSession(List<Attendence> collection) {
Session session = sessionFactory.openSession();
session.beginTransaction();
for (Attendence obj : collection) {
session.save(obj);
System.out.println("Object Added");
}
session.getTransaction().commit();
session.close();
}
For your convenience, I'm also adding the glimpse of the csv file:
Test_company,TestId001,Test Name,2018/03/22,08:53:15,17:50:40
Test_company,TestId001,Test Name,2018/03/25,08:51:02,17:55:18
Test_company,TestId001,Test Name,2018/03/27,08:50:16,18:03:47
Test_company,TestId001,Test Name,2018/03/28,08:48:07,18:46:42
Test_company,TestId001,Test Name,2018/03/29,08:56:16,20:14:16
Thanks in advance for giving your valuable time to help me with this issue.
You are saving the reference of the Attendence object, while you're modifying it's content everytime.
You should probably instantiate an Attendence Object every time you attempt saving it.
for (Attendence obj : collection) {
Attendence newRef = new Attendence(obj);
session.save(newRef);
System.out.println("Object Added");
}
Sorry, My issue was in different place. Thank you all for your help. While retrieving data from csv file, there was a little error which created the issue. Thank you all for your time :)
In the readfromcsv function, previously I did the following:
public static void readFromExcel(String path) {
ArrayList<Attendence> attendences = new ArrayList<Attendence>();
String csvFile = path;
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
Attendence attendenceLine=new Attendence();
try {
br = new BufferedReader(new FileReader(csvFile));
//Attendence attendenceLine = new Attendence();
line = br.readLine();
while ((line = br.readLine()) != null) {
String[] data = line.split(cvsSplitBy);
if (data.length == 6) {
attendenceLine.setEmployee_id(data[1]);
attendenceLine.setDate(data[3]);
attendenceLine.setInTime(data[4]);
attendenceLine.setOutTime(data[5]);
}
else{
attendenceLine.setEmployee_id(data[1]);
attendenceLine.setDate(data[3]);
attendenceLine.setInTime("no punch");
attendenceLine.setOutTime("no punch");
}
attendences.add(attendenceLine);
}
for(Attendence attendence: attendences){
HibernateOperation.hibernateInsertOneAttendenceSession(attendence);
}
//HibernateOperation.hibernateInsertAttendenceSession(attendences);
} catch (FileNotFoundException ex) {
Logger.getLogger(AddToDatabaseOperation.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(AddToDatabaseOperation.class.getName()).log(Level.SEVERE, null, ex);
}
}
Here the attendenceLine String Variable was only having the last row as a reference value. Thats why for every iteration, I need to create the object again. I did the following to solve the issue.
public static void readFromExcel(String path) {
ArrayList<Attendence> attendences = new ArrayList<Attendence>();
String csvFile = path;
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
//Attendence attendenceLine = new Attendence();
line = br.readLine();
while ((line = br.readLine()) != null) {
String[] data = line.split(cvsSplitBy);
Attendence attendenceLine=new Attendence();
if (data.length == 6) {
attendenceLine.setEmployee_id(data[1]);
attendenceLine.setDate(data[3]);
attendenceLine.setInTime(data[4]);
attendenceLine.setOutTime(data[5]);
}
else{
attendenceLine.setEmployee_id(data[1]);
attendenceLine.setDate(data[3]);
attendenceLine.setInTime("no punch");
attendenceLine.setOutTime("no punch");
}
attendences.add(attendenceLine);
}
for(Attendence attendence: attendences){
HibernateOperation.hibernateInsertOneAttendenceSession(attendence);
}
//HibernateOperation.hibernateInsertAttendenceSession(attendences);
} catch (FileNotFoundException ex) {
Logger.getLogger(AddToDatabaseOperation.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(AddToDatabaseOperation.class.getName()).log(Level.SEVERE, null, ex);
}
}
Please call new class and add all filed to this new class and save new class.
It will work.
for (Attendence obj : collection) {
Attendence newRef = new Attendence();
newRef.setSerialNo(obj.getSerialNo())
// set newRef to obj of all column......
session.save(newRef);
System.out.println("Object Added");
}
Just wondering what I have done wrong here I'm getting an error in the method setLine() which is:
error: incompatible types: String[] cannot be converted to State[]
Im not too sure on what to do to fix it since I need the line to be split and stored in that state array so I can determine whether if it is a state or location when reading from a csv file.
public static void readFile(String inFilename)
{
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
int stateCount = 0, locationCount = 0;
String line;
try
{
fileStrm = new FileInputStream(inFilename);
rdr = new InputStreamReader(fileStrm);
bufRdr = new BufferedReader(rdr);
line = bufRdr.readLine();
while (line != null)
{
if (line.startsWith("STATE"))
{
stateCount++;
}
else if (line.startsWith("LOCATION"))
{
locationCount++;
}
line = bufRdr.readLine();
}
fileStrm.close();
State[] state = new State[stateCount];
Location[] location = new Location[locationCount];
}
catch (IOException e)
{
if (fileStrm != null)
{
try { fileStrm.close(); } catch (IOException ex2) { }
}
System.out.println("Error in file processing: " + e.getMessage());
}
}
public static void processLine(String csvRow)
{
String thisToken = null;
StringTokenizer strTok;
strTok = new StringTokenizer(csvRow, ":");
while (strTok.hasMoreTokens())
{
thisToken = strTok.nextToken();
System.out.print(thisToken + " ");
}
System.out.println("");
}
public static void setLine(State[] state, Location[] location, int stateCount, int locationCount, String line)
{
int i;
state = new State[stateCount];
state = line.split("="); <--- ERROR
for( i = 0; i < stateCount; i++)
{
}
}
public static void writeOneRow(String inFilename)
{
FileOutputStream fileStrm = null;
PrintWriter pw;
try
{
fileStrm = new FileOutputStream(inFilename);
pw = new PrintWriter(fileStrm);
pw.println();
pw.close();
}
catch (IOException e)
{
if (fileStrm != null)
{
try
{
fileStrm.close();
}
catch (IOException ex2)
{}
}
System.out.println("Error in writing to file: " + e.getMessage());
}
}
This error occurs, as it just says 'String[] cannot be converted to State[]'. That is like you wanted to store an Integer into a String, it's the same, because the types don't have a relation to each other (parent -> child).
So if you want to solve your problem you need a method which converts the String[] into a State[]. Something like this:
private State[] toStateArray(String[] strings){
final State[] states = new State[strings.length];
for(int i = strings.length-1; i >= 0; i--){
states[i] = new State(strings[i]); // here you have to decide how to convert String to State
}
return states;
}
I have a list of names in the form of a CSV and I am up for google searching those names using java. But the problem that i am facing is that when i initially run the code i am able to search the query but in the middle of the code the code starts to throw 503 exceptions and when i again run the code it starts throwing 503 exceptions from the very beginning.Here is the code that i am using.
public class ExtractInformation
{
static String firstname,middlename,lastname;
public static final int PAGE_NUMBERS = 10;
public static void readCSV()
{
boolean first = true;
try
{
String splitBy = ",";
BufferedReader br = new BufferedReader(new FileReader("E:\\KOLDump\\names.csv"));
String line = null;
String site = null;
while((line=br.readLine())!=null)
{
if(first)
{
first = false;
continue;
}
String[] b = line.split(splitBy);
firstname = b[0];
middlename = b[1];
lastname = b[2];
String name = null;
if(middlename == null || middlename.length() == 0)
{
name = firstname+" "+lastname+" OR "+lastname+" "+firstname.charAt(0);
}
else
{
name = firstname+" "+lastname+" OR "+lastname+" "+firstname.charAt(0)+" OR "+firstname+" "+middlename.charAt(0)+". "+lastname;
}
BufferedReader brs = new BufferedReader(new FileReader("E:\\KOLDump\\site.csv"));
while((site = brs.readLine()) != null)
{
if(first)
{
first = false;
continue;
}
String [] s = site.split(splitBy);
String siteName = s[0];
siteName = (siteName.replace("www.", ""));
siteName = (siteName.replace("http://", ""));
getDataFromGoogle(name.trim(), siteName.trim());
}
brs.close();
}
//br.close();
}
catch(Exception e)
{
System.out.println("unable to read file...some problem in the csv");
}
}
public static void main(String[] args)
{
readCSV();
}
private static void getDataFromGoogle(String query,String siteName)
{
Set<String> result = new HashSet<String>();
String request = "http://www.google.co.in/search?q="+query+" "+siteName;
try
{
Document doc = Jsoup.connect(request).userAgent("Chrome").timeout(10000).get();
Element query_results = doc.getElementById("ires");
Elements gees = query_results.getElementsByClass("g");
for(Element gee : gees)
{
Element h3 = gee.getElementsByTag("h3").get(0);
String annotation = h3.getElementsByTag("a").get(0).attr("href");
if(annotation.split("q=",2)[1].contains(siteName))
{
System.out.println(annotation.split("q=",2)[1]);
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
any suggestions on how to remove this exceptions from the code would really be helpful.
If you wait a little do the 503's go away? If so, then you're probably being rate-limited by Google. https://support.google.com/gsa/answer/2686272?hl=en
You may need to put some kind of delay between requests.
i have a frame that contain a button and textfield.
my porpuse is read ID number frome textfield and when clicked on button, my table should display that ID with its name and mark.
my "UserSearchFile.txt" is this:
12 joe 120
14 ted 220
19 alex 560
22 julia 668
my jButton6ActionPerformed whole code is this:
int idS=Integer.parseInt(jTextField2.getText());
final Vector data = new Vector();
final Vector column = new Vector();
File f=new File("D:\\UserSearchFile.txt");
try{
FileReader fr=new FileReader(f);
BufferedReader br1=new BufferedReader(fr);
String s;
while ((s = br1.readLine()) != null) {
String[] st = s.split(" ");
String id = st[0];
String name = st[1];
String mark = st[2];
if (id.equals(String.valueOf(idS))) {
try {
String line2;
FileInputStream fis = new FileInputStream("D:\\UserSearchFile.txt");
BufferedReader br2 = new BufferedReader(new InputStreamReader(fis));
StringTokenizer st1 = new StringTokenizer(br2.readLine(), " ");
while (st1.hasMoreTokens())
column.addElement(st1.nextToken());
while ((line2 = br2.readLine()) != null) {
StringTokenizer st2 = new StringTokenizer(line2, " ");
while (st2.hasMoreTokens())
data.addElement(st2.nextToken());
}
br2.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (IOException ex) {
Logger.getLogger(MainFrame1.class.getName()).log(Level.SEVERE, null, ex);
}
jTable1.setModel(new AbstractTableModel() {
public int getRowCount() {
return data.size() / getColumnCount();
}
public int getColumnCount() {
return column.size();
}
public Object getValueAt(int rowIndex, int columnIndex) {
return (String) data.elementAt((rowIndex * getColumnCount())
+ columnIndex);
}
});
jTable1.setVisible(true);
please help me and tell me how to write cleany and simple.
Start by using meaningful names for your variables and methods. jTable1, br1, br2 and jButton6ActionPerformed are not acceptable names.
Then try to split a complex method into 2 or three operations, themselves split into 2 or three operations, etc. Each operation should be a method call. For example:
private void readButtonClicked() {
String id = idTextField.getText();
Student student = findStudentWithId(id);
showStudentInGUI(student);
}
private Student findStudentWithId(String id) {
List<String> lines = readLinesInFile();
List<Student> students = transformLinesIntoStudents(lines);
Student studentWithId = findStudentWithId(students, id);
}
private Student findStudentWithId(List<Student> students, String id) {
for (Student student : students) {
if (student.getId().equals(id)) {
return student;
}
}
return null;
}
private List<Student> transformLinesIntoStudents(List<String> lines) {
List<Student> students = new ArrayList<Student>(lines.size());
for (String line : lines) {
students.add(parseStudentLine(line);
}
return students;
}
...