Location is always null when reading an event - java

So I'm working on a Ticketing System but for some reason I can't seem to get a location in my events.
The TicketingSystem class has some hashmaps where I add my data to.
It also has reader methods the one I'm having trouble with is readEvents().
public TicketSystem() {
queueService = new QueueService();
users = new HashMap<>();
locations = new HashMap<>();
events = new HashMap<>();
readData();
}
public void addLocation(Venue location) {
locations.put(location.getId(), location);
}
public void addEvent(Event event) {
events.put(event.getId(), event);
}
public static Event getEvent(String eventId) {
return events.get(eventId);
}
public static Venue getLocation(String locationId) {
return locations.get(locationId);
}
public void readLocations() {
try (BufferedReader reader = new BufferedReader(new FileReader("venuedata.txt"))) {
String line = "";
VenueMapper mapper = new VenueMapper();
while ((line = reader.readLine()) != null) {
Venue venue = mapper.map(line.split(";"));
locations.put(venue.getId(), venue);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void readEvents() {
try (BufferedReader reader = new BufferedReader(new FileReader("eventdata.txt"))) {
String line = "";
EventMapper mapper = new EventMapper();
while ((line = reader.readLine()) != null) {
Event event = mapper.map(line.split(";"));
events.put(event.getId(), event);
reader.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void readData() {
readEvents();
readLocations();
}
With an EventMapper class which reads data from a text file through the TicketingSystem class split by ";" data[5] is my locationId.
#Override
public Event map(String[] data) {
String dateAndTime = data[1];
StringBuilder date = new StringBuilder(dateAndTime.substring(0, 8));
StringBuilder time = new StringBuilder(dateAndTime.substring(8));
return new Event(data[0], data[2], date.toString(), time.toString(), data[3], Double.parseDouble(data[4]), data[5]);
}
}
This is my event class which contains the constructor I'm using returning the event in the EventMapper class
public Event(String id, String name, String date, String time, String description,
double price, String locationId) {
this(name, LocalDate.parse(date, DateTimeFormatter.ofPattern("ddMMyyyy")),
LocalTime.parse(time, DateTimeFormatter.ofPattern("HHmm")), description, price);
this.id = id;
*setLocation(TicketSystem.getLocation(locationId));*
}
public void setLocation(Venue location) {
this.location = location;
}
Everytime I debug there's data in the locations list but for some reason my events aren't picking up the locations I'm trying to get.

Related

How to compare the content (header) of a file with the defined variables in java and update in database?

I want the system to read the csv file in order to analyse the headers and rows of the csv file. The headers of csv file should match with the variables of ProductDetail.java. If the headers matches with these variables, then insert the rows that were read into the database under those headers.
ProductDetail.java
public class ProductDetail {
String street;
String city;
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
ReadFile.java
public class ReadFile {
public static void main(String[] args) {
FileReader input = null;
BufferedReader br = null;
try {
input = new FileReader("uploadedFile.csv");
br = new BufferedReader(input);
String str;
while ((str = br.readLine()) != null) {
System.out.println(str);
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
input.close();
br.close();
}
catch (IOException x) {
x.printStackTrace();
}
}
}
}
I have started the project, but now I am quite stuck on how read the columns & rows and match with those predefined headers that are set in ProductDetail.java. It would be great if you can help me on this.
With SuperCSV, you can do that to validate that headers of the csv matches with the expected header.
Generally, the expected header is fixed. So, you should write them as constant.
public static void main(String[] args) throws IOException {
CsvBeanReader csvBeanReader = null;
try {
// your csv file
String csvFile = null;
csvBeanReader = new CsvBeanReader(csvFile), CsvPreference.EXCEL_NORTH_EUROPE_PREFERENCE);
final String[] headersArray = csvBeanReader.getHeader(true);
List<String> headers = Arrays.asList(headersArray);
List<String> expectedHeaders = Arrays.asList("street", "city");
if (!expectedHeaders.equals(headers)) {
return;
}
final CellProcessor[] processors = new CellProcessor[] { new NotNull(), new NotNull() };
List<ProductDetail> productDetails = new ArrayList<>();
ProductDetail productDetail = null;
while ((productDetail = csvBeanReader.read(ProductDetail.class, headersArray, processors)) != null) {
productDetails.add(productDetail);
}
// save products in your DB
}
finally {
try {
csvBeanReader.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Read CSV link this. CSV is comma separated file, if you read CSV, and use comma as delimiter and map first row of CSV(Use string comparison if columns order change in future)with database column name and you are done.

parse CSV using BaneUtilBean

I am trying to parse a csv and map the fields to a POJO class. However I can see that the mapping is not achieved correctly.
I am trying to map the header from a POJO file to the csv.
public class CarCSVFileInputBean {
private long Id;
private String shortName;
private String Name;
private String Type;
private String Environment;
//getter and setters
}
Can someone please take a look at my code:
public class carCSVUtil {
private static Log log = LogFactory.getLog(carCSVUtil.class);
private static final List<String> fileHeaderFields = new ArrayList<String>();
private static final String UTF8CHARSET = "UTF-8";
static {
for (Field f : carCSVFileInputBean.class.getDeclaredFields()) {
fileHeaderFields.add(f.getName());
}
}
public static List<carCSVFileInputBean> getCSVInputList(InputStream inputStream) {
CSVReader reader = null;
List<carCSVFileInputBean> csvList = null;
carCSVFileInputBean inputRecord = null;
String[] header = null;
String[] row = null;
try {
reader = new CSVReader(new InputStreamReader(inputStream, UTF8CHARSET));
csvList = new ArrayList<carCSVFileInputBean>();
header = reader.readNext();
boolean isEmptyLine = true;
while ((row = reader.readNext()) != null) {
isEmptyLine = true;
if (!(row.length == 1 && StringUtils.isBlank(row[0]))) { // not an empty line, not even containing ','
inputRecord = new carCSVFileInputBean();
isEmptyLine = populateFields(inputRecord, header, row);
if (!isEmptyLine)
csvList.add(inputRecord);
}
}
} catch (IOException e) {
log.debug("IOException while accessing carCSVFileInputBean: " + e);
return null;
} catch (IllegalAccessException e) {
log.debug("IllegalAccessException while accessing carCSVFileInputBean: " + e);
return null;
} catch (InvocationTargetException e) {
log.debug("InvocationTargetException while copying carCSVFileInputBean properties: " + e);
return null;
} catch (Exception e) {
log.debug("Exception while parsing CSV file: " + e);
return null;
} finally {
try {
if (reader != null)
reader.close();
} catch (IOException ioe) {}
}
return csvList;
}
protected static boolean populateFields(carCSVFileInputBean inputRecord, String[] header, String[] row) throws IllegalAccessException, InvocationTargetException {
boolean isEmptyLine = true;
for (int i = 0; i < row.length; i++) {
String val = row[i];
if (!StringUtils.isBlank(val)) {
BeanUtilsBean.getInstance().copyProperty(inputRecord, header[i], val);
isEmptyLine = false;
}
}
return isEmptyLine;
}
}
I found the solution - the headers in the csv file are expected to begin with a lowercase.

Reading string value from a text file to java arraylist in Java

I want to read string value by splitting | include white space from text file and store to Account class.This is my function for read text file.
public ArrayList<Account> loadAccount(String fn) throws IOException{
ArrayList<Account> account = new ArrayList<Account>();
Scanner infile = new Scanner(new InputStreamReader (new FileInputStream(fn)));
while(infile.hasNextLine()){
String accountNo = infile.nextLine();
String legencyNo = infile.nextLine();
Account c = new Account(accountNo, legencyNo);
account.add(c);
}
infile.close();
return account;
}
This is Account class.
public class Account {
private int id;
private String accountNo;
private String legencyNo;
}
This is AccountInformation.txt.
Account Number | Legacy Key | Description
80000001|7001111|
80000002| |
80000003|7001234|Testing
Update: This is my readFile class.Now, It's ok.I'm using StringUtils.
public static List<Account> readFile() {
String file = "C:\\Dev\\JBoss\\UpdateAccountNumber\\source\\AccountInformation.txt";
BufferedReader br = null;
String line = "";
String splitter = "\\|";
List<Account> accountList = new ArrayList<Account>();
try {
br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
String[] accounts = org.apache.commons.lang3.StringUtils.split(line, splitter);
String accountNo = "",legencyNo="";
for(int i = 0;i<accounts.length;i++){
if (i == 0){
accountNo = (accounts[0] == null) ? "" : accounts[0];
}
if (i==1){
legencyNo = (accounts[1] == null) ? "" : accounts[1];
}
}
Account a = new Account(accountNo,legencyNo);
accountList.add(a);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return accountList;
}
Just try as. Which mean split string include space .
String[] accounts = line.split(splitter, -1);
Fixed code:
Account class:
class Account
{
private int id;
private String accountNo;
private String legencyNo;
public Account(String accountNo, String legencyNo)
{
this.accountNo = accountNo;
this.legencyNo = legencyNo;
}
#Override
public String toString()
{
return this.accountNo + " " + this.legencyNo;
}
}
Test class:
public class Test
{
public static List<Account> readFile()
{
String file = "C:\\workspace\\practise\\test.txt";
BufferedReader br = null;
String line = "";
String splitter = "\\|";
List<Account> accountList = new ArrayList<Account>();
try
{
br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null)
{
Account a = null;
String[] accounts = line.split(splitter);
if (accounts.length > 1)
{
a = new Account(accounts[0], accounts[1]);
} else
{
a=new Account(accounts[0], "");
}
accountList.add(a);
}
} catch (Exception e)
{
e.printStackTrace();
} finally
{
if (br != null)
{
try
{
br.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
return accountList;
}
public static void main(String[] args)
{
List<Account> acct = readFile();
for (Account account : acct)
{
System.out.println(account);
}
}
}
Test file:
Account Number|Legacy Key|Description
80000001|7001111|
80000002||
80000003|7001234|Testing
The problem in above code was that when you split in second record there is only one string present i.e 80000002, so you are trying to use accounts[1], but accounts length itself is 1 so you will have to handle with if clause on accounts.length. you can try above code its working. From next time i would suggest you to run your code in debug mode to check where you are getting exception.
If i understood your problem correctly, you need to change your loop
while(infile.hasNextLine()){
String line= infile.nextLine();
String[] tokens = line.split("\\|");
Account c = new Account(tokens[0], tokens[1]);
account.add(c);
}
There are two reasons for that,
First, your all data required are in single line 80000001|7001111|, so calling nextLine will bring you next row rather than data which you required
Second, it might cause you exception, as you are checking is next line exist, and ther you try to read two lines, which will obviousky fail if you have only one line

Android JSON Parser "User cannot be resolved to a type"

public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public List readJsonStream(InputStream in) throws IOException {
JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
try {
return readMessagesArray(reader);
} finally {
reader.close();
}
}
public List readMessagesArray(JsonReader reader) throws IOException {
List messages = new ArrayList();
reader.beginArray();
while (reader.hasNext()) {
messages.add(readMessage(reader));
}
reader.endArray();
return messages;
}
public Message readMessage(JsonReader reader) throws IOException {
long id = -1;
String text = null;
User user = null;
List geo = null;
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if(name.equals("id")) {
id = reader.nextLong();
} else if (name.equals("text")) {
text = reader.nextString();
} else if (name.equals("geo") && reader.peek() != JsonToken.NULL) {
geo = readDoublesArray(reader);
} else if (name.equals("user")) {
user = readUser(reader);
} else {
reader.skipValue();
}
}
reader.endObject();
return new Message(id, text, user, geo);
}
public List readDoublesArray(JsonReader reader)throws IOException {
List doubles = new ArrayList();
reader.beginArray();
return doubles;
}
public User readUser(JsonReader reader) throws IOException {
String username = null;
int followersCount = -1;
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if(name.equals("name")) {
username = reader.nextString();
} else if (name.equals("followers_count")) {
followersCount = reader.nextInt();
} else {
reader.skipValue();
}
}
reader.endObject();
return new User(username, followersCount);
}}
I'm using the exact example from http://developer.android.com/reference/android/util/JsonReader.html. However, there is a problem with "User cannot be resolved to a type".
'User' class in the given example is just to show how it may work. You may substitute it with something like this:
public class User{
String name;
int followers_count;
public User(String name, int followers_count){
this.name=name;
this.followers_count=followers_count;
}
}

How to use String.split with a text file to add to a simple array

My goal is to read in a text file and add each element to a simple array (the elements are separated by a comma). The last method readData() is the one I can't figure out.
My code so far :
public class VersionChooser {
private Scanner scan;
private StockManager aManager = new StockManager("StockManager");
public VersionChooser() {
this.scan = new Scanner(System.in);
}
public void chooseVersion() {
this.readData();
this.runTextOption();
}
private void runTextOption() {
StockTUI tui = new StockTUI(this.aManager);
}
public StockManager readData() {
String fileName;
System.out.println("Enter the name of the file to be used");
fileName = this.scan.nextLine();
System.out.println(fileName);
try (final BufferedReader br = Files.newBufferedReader(new File("fileName").toPath(),
StandardCharsets.UTF_16)) {
for (String line; (line = br.readLine()) != null;) {
final String[] data = line.split(",");
StockRecord record = new StockRecord(data[0], Double.valueOf(data[4]));
this.aManager.getStockList().add(record);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return null;
}
}
StockRecord :
public class StockRecord {
private String date;
private double closingPrice;
public StockRecord(String date, double closingPrice) {
this.date = date;
this.closingPrice = closingPrice;
}
public String getDate() {
return this.date;
}
public double getClosingPrice() {
return this.closingPrice;
}
public String toString() {
return "On " + this.date + " this stock had a closing price of $"
+ this.closingPrice;
}
}
Step1 : Read the file line by line.
Step2: Split the line by ","
Step3 : Construct the String[] to StockRecord.
try (final BufferedReader br = Files.newBufferedReader(new File("stock.txt").toPath(),
StandardCharsets.UTF_8)) {
List<StockRecord> stocks = new ArrayList<StockRecord>();
br.readLine() ; // to avoid first line
for (String line; (line = br.readLine()) != null;) { // first step
final String[] data = line.split(","); // second step
StockRecord record = new StockRecord(data[0], Double.valueOf(data[1]));
stocks.add(record); // third step
}
} catch (IOException e) {
e.printStackTrace();
}
Your stockRecord doesn't has all records. and for demo purpose i did assumed 2 element is closing price . change accordingly

Categories