java.lang.NullPointerException when deserializing - java

public class ViewBooking extends javax.swing.JFrame {
/**
* Creates new form ViewBooking
*/
public ViewBooking() {
initComponents();
}
public void dispBookingInfo(){
Reservation[] reservations = new Reservation[1];
try {
String searchCust = SearchName.getText();
FileInputStream inStream = new FileInputStream(searchCust +
"booking.dat");
ObjectInputStream objectInputFile = new ObjectInputStream(inStream);
reservations[0] = (Reservation) objectInputFile.readObject();
objectInputFile.close();
} catch (Exception e) {
}
JOptionPane.showMessageDialog(null, reservations[0].getDetails());
}
This is my Reservation class
public class Reservation implements Serializable {
private String name;
private String sDate;
private String eDate;
private String noOfDays;
private String roomNo;
private String totalAmt;
Reservation(String name, String sDate, String eDate, String noOfDays,
String totalAmt, String roomNo) {
this.name = name;
this.totalAmt = totalAmt;
this.roomNo = roomNo;
//throw new UnsupportedOperationException("Not supported yet.");
//To change body of generated methods, choose Tools | Templates.
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getsDate() {
return sDate;
}
public void setsDate(String sDate) {
this.sDate = sDate;
}
public String geteDate() {
return eDate;
}
public void seteDate(String eDate) {
this.eDate = eDate;
}
public String getNoOfDays() {
return noOfDays;
}
public void setNoOfDays(String noOfDays) {
this.noOfDays = noOfDays;
}
public String getRoomNo() {
return roomNo;
}
public void setRoomNo(String roomNo) {
this.roomNo = roomNo;
}
public String getTotalAmt() {
return totalAmt;
}
public void setTotalAmt(String totalAmt) {
this.totalAmt = totalAmt;
}
public String getDetails(){
return "Name: " + name + "\n" + "From: " + sDate + " to " + eDate
+ "\n" + "Duration: " + noOfDays + "Room No: " + roomNo
+ "Total amount: RM" + totalAmt;
}
}
I am able to serialize the Reservation object but when i try to deserialize it and read the data, i get a NullPointerException error at this line:
JOptionPane.showMessageDialog(null, reservations[0].getDetails());
What is the problem here?
I have changed my code into the following:
public void dispBookingInfo() throws Exception{
String searchCust = SearchName.getText();
FileInputStream inStream = new FileInputStream(searchCust + " booking.dat");
ObjectInputStream objectInputFile = new ObjectInputStream(inStream);
Reservation[] reservations = new Reservation[1];
try {
if (reservations[0] != null) {
reservations[0] = (Reservation) objectInputFile.readObject();
}
objectInputFile.close();
} catch (Exception e) {
System.out.println("error!");
}
JOptionPane.showMessageDialog(null, reservations[0].getDetails());
}
The NullPointerException error is gone but I still cant retrieve any data. Why is my reservation[0] null?

In your
try {
...
} catch () {
...
}
statement you ignore any exception thrown. Hence it is possible that
reservations[0] = (Reservation) objectInputFile.readObject();
does not initialize reservation[0] at all, which would cause an NullPointerException when accessing:
reservation[0].getDetails();

Here is your problem:
if (reservations[0] != null) {
reservations[0] = (Reservation) objectInputFile.readObject();
}
reservations[0] will always be null at this point because you've only just initialised the array. This stops the call that would populate the data into here, so when you try and access it later on with reservations[0].getDetails() that element is inevitably still null. The null check is completely unneeded, so remove it.
You may also wish to consider defining a serialVersionUID for your class.
To do so, add this as a class variable:
private static final long serialVersionUID = <some_long_number>;
Replace <some_long_number> with any long that you like. Once done, you'll have to re-create your file with a 'new' version of your class, otherwise the version numbers won't match.
If you don't do this, the JVM automatically generates a serialVersionUID for you based upon the class itself, so if you've changed certain things about the class, you may suddenly find that you have problems deserialising older versions of the class.

Related

Any reason why I can't create a class? I'm trying to have a Animal array to hold different animals

I am trying to create a animal array to try and hold the information of different types of animals/owners. Been trying to solve this for 2 hours reading the book but nothing is working. Can anyone point me to the right direction? Also how would I go about importing information from a URL to a array?
import java.net.URL;
import java.math.BigInteger;
import java.net.URL;
import java.net.HttpURLConnection;
import static java.util.Arrays.sort;
public class janesj_Program5 {
public static void main(String[] args) {
Animal[] j = new Animal[1];
storeFile(j);
sort(j);
printArray(j);
}
public static class Animal {
String OwnerName;
int birthYear;
public int billBalance;
String Species;
String feature;
public Animal() {}
public Animal(String OwnerName,int birthYear,int billBalance,String Species,String feature) {
this.OwnerName = OwnerName;
this.birthYear = birthYear;
this.billBalance = billBalance;
this.Species = Species;
this.feature = feature;
}
public int getBalance() {
return billBalance;
}
public String toString() {
return OwnerName + "\t" + birthYear + "\t" + getBalance() + "\t" + Species + "\t" + feature;
}
}
public static void storeFile(Animal[] x) {
String URLString = "http://yoda.kean.edu/~pawang/CPS2231/Program5_veterinarian_input.txt";
try {
java.net.URL url = new java.net.URL(URLString);
int count = 0;
Scanner input = new Scanner(url.openStream());
while(input.hasNext()) {
String line = input.nextLine();
count+= line.length();
x = new Animal[count];
}
}catch(java.net.MalformedURLException ex){
System.out.println("Invalid URL");
}
catch(java.io.IOException ex) {
System.out.println("I/O Errors: no such file");
}
}
public static class sorts extends Animal implements Comparator<Animal> {
public int compare(Animal a, Animal b) {
return a.getBalance() - b.getBalance();
}
}
public static void printArray(Animal[] x) {
System.out.println("\t Veterinarian Services Report \t Page:1");
System.out.println(" ==================================");
System.out.println("No\tOwner Name\tYear\tBalance\tSpecies\tLegs\tFeature");
System.out.println("== ==================== ==== ============ ============ ============");
for(int i = 1; i<=x.length;i++) {
System.out.println(i + " " + x.toString());
}
}
}
As so kindly pointed out by MTilsted you really should have your Animal class within its own .java file.
If you plan to create an array of Animal objects where the data to fill those objects is coming from a data file then you need to realize that arrays are of a fixed size, they can't just grow on a whim (at least not without more coding). You would need to know how may animals are contained within the data file so as to properly size your Animal array. Your in luck, by the look of it your data file contains the number of animals within the first line of the file (which needs to be ignored when reading in the actual animal data).
First, make sure the file actually exist. No sense going through heartache if it's not even there or there is something wrong with the connection to its' location. Once done, you can declare and initialize your Animals array to the proper size so as to handle all the data rows you are about to re-read into the array.
Below is your code to demonstrate how this can be accomplished.
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
public class AnimalCare {
static Animals[] animals; // Declare The Anmimal Array as a class member variable
public static void main(String[] args) {
try {
URL url = new URL("http://yoda.kean.edu/~pawang/CPS2231/Program5_veterinarian_input.txt");
int lines = 0;
// Get the number of lines in file
try (Scanner s = new Scanner(url.openStream())) {
String firstFileLine = "";
while (firstFileLine.equals("")) {
firstFileLine = s.nextLine().trim();
if (!firstFileLine.equals("")) {
lines = Integer.parseInt(firstFileLine);
}
}
}
catch (IOException ex) {
String msg = "";
if (!ex.getMessage().equals(url.toString())) {
msg = "No Network Connection!";
}
else {
msg = "File Not Found! - " + ex.getMessage();
}
System.err.println(msg);
}
// Declare our Animals Array.
animals = new Animals[lines];
// Re-read the data file on network...
try (Scanner s = new Scanner(url.openStream())) {
int i = 0;
String dataLine;
s.nextLine(); // Skip the first line of file!
while (s.hasNextLine()) {
dataLine = s.nextLine().trim();
// Skip blank lines (if any)
if (dataLine.equals("")) {
continue;
}
String[] dataParts = dataLine.split("\\s+");
animals[i] = new Animals(dataParts[0],
Integer.parseInt(dataParts[1]),
Integer.parseInt(dataParts[2]),
dataParts[3],
dataParts[4]);
i++; // Increment i to create the next index value for array
}
// The Animals array is now filled with network file data
}
catch (IOException ex) {
String msg = "";
if (!ex.getMessage().equals(url.toString())) {
msg = "No Network Connection!";
}
else {
msg = "File Not Found! - " + ex.getMessage();
}
System.err.println(msg);
}
}
catch (MalformedURLException ex) {
System.err.println(ex.getMessage());
}
// Display the Animals array within the Console Window...
for (int i = 0; i < animals.length; i++) {
System.out.println(animals[i].toString());
}
}
}
And the Animals Class:
import java.util.Arrays;
public class Animals {
private String OwnerName;
private int birthYear;
private int billBalance;
private String Species;
private String feature;
//----------------- Constructors -------------------
public Animals() { }
public Animals(String OwnerName, int birthYear, int billBalance, String Species, String feature) {
this.OwnerName = OwnerName;
this.birthYear = birthYear;
this.billBalance = billBalance;
this.Species = Species;
this.feature = feature;
}
public Animals(Object[] data) {
if (data.length != 5 || !(data[0] instanceof String) ||
!(data[1] instanceof Integer) || !(data[2] instanceof Integer) ||
!(data[3] instanceof String) || !(data[4] instanceof String)) {
throw new IllegalArgumentException("Error in Animals Constructor data array! "
+ "Insufficiant data or invalid data element!" + System.lineSeparator() +
Arrays.deepToString(data));
}
this.OwnerName = data[0].toString();
this.birthYear = (int) data[1];
this.billBalance = (int) data[2];
this.Species = data[3].toString();
this.feature = data[4].toString();
}
//---------------------------------------------------
public int getBalance() {
return billBalance;
}
public String getOwnerName() {
return OwnerName;
}
public void setOwnerName(String OwnerName) {
this.OwnerName = OwnerName;
}
public int getBirthYear() {
return birthYear;
}
public void setBirthYear(int birthYear) {
this.birthYear = birthYear;
}
public int getBillBalance() {
return billBalance;
}
public void setBillBalance(int billBalance) {
this.billBalance = billBalance;
}
public String getSpecies() {
return Species;
}
public void setSpecies(String Species) {
this.Species = Species;
}
public String getFeature() {
return feature;
}
public void setFeature(String feature) {
this.feature = feature;
}
#Override
public String toString() {
String string = String.format("%-10s %-8d %-8d %-10s %-15s",
OwnerName, birthYear, getBalance(), Species, feature);
return string;
}
}

ManyToOne creates new entry in both tables for every new object

I got City and Weather. Weather should point to the city objects in the database. A city can have multiple weather entries. My problem is that each time I add a weather to my db it creates a new city with the same name but other ID.
Weather Entity;
#Entity
public class Weather implements Serializable{
#Id
#GeneratedValue
private int id;
private static final long serialVersionUID = -3562151396218034738L;
private LocalDateTime timeStamp;
private Float windSpeed;
private Float windDir;
private Float humidity;
private Float temperature;
private String weatherDescription;
#ManyToOne(fetch=FetchType.LAZY, cascade = CascadeType.PERSIST)
#JoinColumn(name="city_id")
private City city;
public Weather(){}
public Weather(LocalDateTime timeStamp, Float windSpeed, Float windDir, Float humidity, Float temperature, String weatherDescription, City city){
this.timeStamp = timeStamp;
this.windSpeed = windSpeed;
this.windDir = windDir;
this.humidity = humidity;
this.temperature = temperature;
this.weatherDescription = weatherDescription;
this.city = city;
}
}
City Entity:
#Entity
public class City implements Serializable {
#Id
#GeneratedValue
private int id;
private static final long serialVersionUID = 1L;
private String cityName;
private String cityPostalcode;
#OneToMany(mappedBy = "city")
private List<Weather> weather;
public City(){}
public City(String cityName, String cityPostalcode){
this.cityName = cityName;
this.cityPostalcode = cityPostalcode;
}
My two methods for adding weather to my db.
#Override
public Weather addWeather(Weather weather) throws Exception {
EntityManager em = JpaUtil.createEntityManager();
try {
em.getTransaction().begin();
em.persist(weather);
em.persist(weather.getCity());
em.getTransaction().commit();
} catch (Exception e) {
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
throw new RuntimeException(e);
} finally {
if (em.isOpen()) {
em.close();
LOG.info("New Weather entry for " + weather.getCity().getCityName());
}
}
return weather;
}
#Override
public List<Weather> addWeatherWithList(List<Weather> weather) throws Exception {
for (int i = 0; i < weather.size() - 1; i++) {
EntityManager em = JpaUtil.createEntityManager();
em.getTransaction().begin();
try {
em.persist(weather.get(i));
em.persist(weather.get(i).getCity());
em.getTransaction().commit();
} catch (Exception e) {
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
throw new RuntimeException(e);
} finally {
if (em.isOpen()) {
em.close();
LOG.info(weather.get(i).toString() + " added to db");
}
}
}
return weather;
}
My table weather:
My table city: (at the moment my weather data only comes from this one city, that's right)
Here a list what I tried so far (all i can remember of at least) and didn't work.
cascade = CascadeType.PERSIST (now I persist both objects, otherwise I get "not marked cascade PERSIST" error)
removing generatedvalue ID's
without OneToMany (inside city) declaration
only using ManyToOne without any specific declarations (like fetchtype)
without join.column
That's all I can remember. If you need further information let me know.
EDIT:
I get my weather data from a webservice.
My WeatherReader:
public class WeatherReader extends RESTReader {
private RESTReader client = new RESTReader();
public List<Weather> getAllWeatherData() {
try {
ObjectMapper mapper = new ObjectMapper();
List<City> citiesToBeCalled = client.deserialize(); // list resulting from deserialization
ArrayList<List<Weather>> allWeatherList = new ArrayList<>();
for (int i = 0; i < 1; i++) { //TODO: replace 1 with citiesToBeCalled.size() to have all cities
String json = client.weatherData(citiesToBeCalled.get(i).getCityName());
List<RawWeatherData> rawWeatherList = Arrays.asList(mapper.readValue(json, RawWeatherData[].class));
List<Weather> weatherList = new ArrayList<>();
for (int j = 0; j < rawWeatherList.size(); j++){
weatherList.add(rawWeatherList.get(j).convertToWeather());
}
allWeatherList.add(weatherList);
}
return allWeatherList.stream().flatMap(x -> x.stream()).collect(Collectors.toList());
} catch (Exception e) {
System.out.println("Error:" + e.getMessage());
return null;
}
}
}
My RestReader.class:
public class RESTReader {
private String masterDataCityFilePath = "t.tmp";
private static final String BASE_URI = "removed because of privacy reasons";
private HttpClient httpClient = HttpClient.newHttpClient();
private String mimeType = "application/json";
//TODO: this is already good and can be used for the CityReader
public String allCitiesAsJson() throws Exception {
HttpRequest req = HttpRequest.newBuilder(URI.create(BASE_URI + "cities")).headers("Accept", mimeType).GET().build();
System.out.println("REQUEST SENT:" + req);
HttpResponse<String> res = httpClient.send(req, HttpResponse.BodyHandlers.ofString());
if (res.statusCode() == 200) {
return res.body().toString();
} else {
throw new Exception("Status-code:" + res.statusCode());
}
}
public String weatherData(String cityname) throws Exception{
String realcityname = cityname.replace(" ", "%20");
HttpRequest req = HttpRequest.newBuilder(URI.create(BASE_URI + realcityname)).headers("Accept", mimeType).GET().build();
System.out.println("REQUEST SENT:" + req);
HttpResponse<String> res = httpClient.send(req, HttpResponse.BodyHandlers.ofString());
if (res.statusCode() == 200) {
return res.body().toString();
} else {
throw new Exception("Status-code:" + res.statusCode());
}
}
public void serialize(List<City> cityList) { //Creating
try {
FileOutputStream fileOut = new FileOutputStream(masterDataCityFilePath); //(MasterdataCities)
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(cityList);
out.close();
fileOut.close();
System.out
.println("Master data file saved under: " + masterDataCityFilePath);
} catch (IOException i) {
System.err.println("There was an error saving the file!");
System.err.println("Wrong directory?");
i.printStackTrace();
}
}
public List<City> deserialize() {
try {
FileInputStream fileIn = new FileInputStream(masterDataCityFilePath);
ObjectInputStream in = new ObjectInputStream(fileIn);
List<City> cityList = (List<City>) in.readObject();
in.close();
System.out
.println("Loaded cities from: " + masterDataCityFilePath);
return cityList;
} catch (IOException | ClassNotFoundException e) {
System.err.println("There was an error loading from:" + masterDataCityFilePath);
System.err.println("Wrong directory?\n");
System.out.println("Directory is: " + masterDataCityFilePath);
e.printStackTrace();
}
return null;
}
public String getMasterDataCityFilePath() {
return masterDataCityFilePath;
}
public void setMasterDataCityFilePath(String masterDataCityFilePath) {
this.masterDataCityFilePath = masterDataCityFilePath;
}
}
EDIT 2:
my convertToWeather();
public Weather convertToWeather(){
try {
Weather weather = new Weather();
weather.setCity(city);
String str = lastUpdateTime;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
weather.setTimeStamp(dateTime);
//assign wind speed
String datacontent[] = data.split("#");
String windSpeedValue[] = datacontent[12].split(":", 2); // specify data content number
if (windSpeedValue[1].equals("unknown")){
weather.setWindSpeed(null);
} else {
weather.setWindSpeed(Float.parseFloat(windSpeedValue[1])); //general just gimme the value specifier
}
//assign wind direction
String windDirValue[] = datacontent[13].split(":", 2); // specify data content number
if (windDirValue[1].equals("unknown")){
weather.setWindDir(null);
} else {
weather.setWindDir(Float.parseFloat(windDirValue[1])); //general just gimme the value specifier
}
//assign humidity
String humidityValue[] = datacontent[11].split(":", 2); // specify data content number
if (humidityValue[1].equals("unknown")){
weather.setHumidity(null);
} else {
weather.setHumidity(Float.parseFloat(humidityValue[1])); //general just gimme the value specifier
}
//assign temperature
String temperatureValue[] = datacontent[9].split(":", 2); // specify data content number
if (temperatureValue[1].equals("unknown")){
weather.setTemperature(null);
} else {
weather.setTemperature(Float.parseFloat(temperatureValue[1])); //general just gimme the value specifier
}
//assign description
String descriptionValue[] = datacontent[8].split(":", 2); // specify data content number
if (descriptionValue[1].equals("unknown")){
weather.setWeatherDescription("unknown");
} else {
weather.setWeatherDescription(descriptionValue[1]); //general just gimme the value specifier
}
return weather;
} catch (Exception e) {
System.out.println("Error:" + e.toString());
return null;
}
}
The problem is simple, for JPA, if your entity does not have any ID then it means that it will do a INSERT if ID is null and UPDATE if ID is not null.
From what I read, your city instance is always a new object or at least, an object not handle in the persistence context.
In your code, you should first check if there is already a named city in your database, if yes attach it this to your weather. If not just insert it (as you would have done in SQL...)
To avoid weird behavior I can also suggest to you to add a unique constraint on the city names.
Let me know if it solve your issue
Remove this piece of code:
#OneToMany(mappedBy = "city")
private List<Weather> weather;
I believe that this mapping in the City class is also writing the data to your db table. For ManyToOne joins, having the mapping one way should suffice. Compare this documents:
https://docs.jboss.org/hibernate/jpa/2.1/api/javax/persistence/ManyToOne.html
and https://docs.jboss.org/hibernate/jpa/2.1/api/javax/persistence/OneToMany.html
Hope it helps.
Show the code in which you create Weather instances, that should be the problem.
The codes shown in your question do not decide how your data will be. Instead, they tell JPA: hey, jpa, please create a new transaction, translate these object state into appropriate SQL INSERT queries and execute them.
So, what decides your data in DB is state of object right before you call EntityManager to persist it.

Stax API XML parsing produces null results

I have been trying to get this over for a while now with little or no success. Right now, I am really out of options. I will appreciate some assistance or pointers towards the right direction.... since I believe I am not doing somethings very well.
After parsing with the code below, I have null values in most of the fields: Result{id=30c26c8a-8bdf-4d4d-8f8d-a19661f16877, name=Andriod_Office_Task, owner =generated.Owner#53d8d10a, comment=, creationTime=2016-09-09T19:30, modificationTime=2016-09-09T19:30:05+02:00, reportId=null, taskid=null, host=null, port=null, nvt=null, scanNVTVersion=null, threat=null, severity=null, description=null}
The parsing methods (other methods are excluded for brevity):
private List<Result> readDocument(XMLStreamReader parser) throws XMLStreamException, DatatypeConfigurationException {
List<Result> results = new ArrayList<>();
while (parser.hasNext()) {
int eventType = parser.next();
switch (eventType) {
case XMLStreamReader.START_ELEMENT:
String elementName = parser.getLocalName();
if (elementName.equals("result"))
results.add(readResult(parser));
break;
case XMLStreamReader.END_ELEMENT:
return results;
}
}
throw new XMLStreamException("Premature end of file");
}
public Result readResult(XMLStreamReader parser) throws XMLStreamException, DatatypeConfigurationException {
Result result = new Result();
result.setId(parser.getAttributeValue(null, "id"));
Report report = new Report();
Task task = new Task();
while (parser.hasNext()) {
int eventType = parser.next();
switch (eventType) {
case XMLStreamReader.START_ELEMENT:
String elementName = parser.getLocalName();
if (elementName.equals("name"))
result.setName(readCharacters(parser));
else if (elementName.equals("host"))
result.setHost(readCharacters(parser));
else if (elementName.equals("owner"))
result.setOwner(readOwner(parser));
else if (elementName.equals("comment"))
result.setComment(readCharacters(parser));
else if (elementName.equals("creation_time"))
result.setCreationTime(readCreationTime(parser));
else if (elementName.equals("modification_time"))
result.setModificationTime(readCharacters(parser));
else if (elementName.equals("report"))
report.setId(readReport(parser));
else if (elementName.equals("task"))
task.setId(readTask(parser));
else if (elementName.equals("user_tags"))
result.setUserTags(readUserTags(parser));
else if (elementName.equals("port"))
result.setPort(readCharacters(parser));
else if (elementName.equals("nvt"))
result.setNvt(readNvt(parser));
else if (elementName.equals("scan_nvt_version"))
result.setScanNVTVersion(readCharacters(parser));
else if (elementName.equals("threat"))
result.setThreat(readCharacters(parser));
else if (elementName.equals("severity"))
result.setSeverity(readCharacters(parser));
else if (elementName.equals("qod"))
result.setQod((Qod) readQod(parser));
else if (elementName.equals("description"))
result.setDescription(readCharacters(parser));
break;
case XMLStreamReader.END_ELEMENT:
}
return result;
}
throw new XMLStreamException("Premature end of file");
}
private String readCharacters(XMLStreamReader reader) throws XMLStreamException {
StringBuilder result = new StringBuilder();
while (reader.hasNext()) {
int eventType = reader.next();
switch (eventType) {
case XMLStreamReader.CHARACTERS:
result.append(reader.getText());
break;
case XMLStreamReader.END_ELEMENT:
return result.toString();
}
}
throw new XMLStreamException("Premature end of file");
}
}
The result class is below :
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
#JsonIgnoreProperties(ignoreUnknown = true)
public class Result {
#XmlAttribute
private String id;
#XmlElement
private String name;
#XmlElement
private Task task;
#XmlElement
private String comment;
#XmlElement(name = "creation_time")
String creationTime;
#XmlElement(name = "modification_time")
private String modificationTime;
// TODO user_tags
#XmlElement
private UserTags userTags;
#XmlElement
private Owner owner;
#XmlElement
private Qod qod;
/**
* // * The report the result belongs to (only when details were requested)
* //
*/
#XmlElementWrapper(name = "report")
#XmlElement(name = "reportId")
private String reportId;
#XmlElement
private String host;
#XmlElement
private String port;
#XmlElement
private NVT nvt;
#XmlElement(name = "scan_nvt_version")
private String scanNVTVersion;
#XmlElement
private String threat;
#XmlElement
private String severity;
#XmlElement
private String description;
public Result() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Task getTask() {
return task;
}
public void setTask(Task task) {
this.task = task;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getCreationTime() {
return creationTime;
}
public void setCreationTime(String creationTime) {
this.creationTime = creationTime;
}
public String getModificationTime() {
return modificationTime;
}
public void setModificationTime(String modificationTime) {
this.modificationTime = modificationTime;
}
public UserTags getUserTags() {
return userTags;
}
public void setUserTags(UserTags userTags) {
this.userTags = userTags;
}
public Qod getQod() {
return qod;
}
public void setQod(Qod qod) {
this.qod = qod;
}
public Owner getOwner() {
return owner;
}
public void setOwner(Owner owner) {
this.owner = owner;
}
public String getReportId() {
return reportId;
}
public void setReportId(String reportId) {
this.reportId = reportId;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public NVT getNvt() {
return nvt;
}
public void setNvt(NVT nvt) {
this.nvt = nvt;
}
public String getScanNVTVersion() {
return scanNVTVersion;
}
public void setScanNVTVersion(String scanNVTVersion) {
this.scanNVTVersion = scanNVTVersion;
}
public String getThreat() {
return threat;
}
public void setThreat(String threat) {
this.threat = threat;
}
public String getSeverity() {
return severity;
}
public void setSeverity(String severity) {
this.severity = severity;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "Result{" + "id=" + id +
", name=" + name + ", owner =" + owner +
", comment=" + comment + ", creationTime=" + creationTime + ", modificationTime=" + modificationTime
+ ", reportId=" + reportId + ", taskid=" + task + ", host=" + host + ", port=" + port + ", nvt=" + nvt
+ ", scanNVTVersion=" + scanNVTVersion + ", threat=" + threat + ", severity=" + severity
+ ", description=" + description + '}';
}
}
<get_results_response status="200" status_text="OK">
<result id="30c26c8a-8bdf-4d4d-8f8d-a19661f16877">
<name>Trace route</name>
<owner>
<name>admin</name>
</owner>
<comment/>
<creation_time>2016-09-09T19:30:05+02:00</creation_time>
<modification_time>2016-09-09T19:30:05+02:00</modification_time>
< id="2a6d7f75-f6b7-40b2-a792-b558fada375b"/>
<task id="e59ac66b-5b59-4756-bace-37bb1106276d">
<name>Andriod_Office_Task</name>
</task>
<user_tags>
<count>0</count>re
</user_tags>
<host>172.16.53.178</host>
<port>general/tcp</port>
<nvt oid="1.3.6.1.4.1.25623.1.0.51662">
<name>Traceroute</name>
<family>General</family>
<cvss_base>0.0</cvss_base>
<cve>NOCVE</cve>
<bid>NOBID</bid>
<xref>NOXREF</xref>
<tags>cvss_base_vector=AV:N/AC:L/Au:N/C:N/I:N/A:N|qod_type=remote_banner|solution=Block unwanted packets from escaping your network.|summary=A traceroute from the scanning server to the target system was
conducted. This traceroute is provided primarily for informational
value only. In the vast majority of cases, it does not represent a
vulnerability. However, if the displayed traceroute contains any
private addresses that should not have been publicly visible, then you
have an issue you need to correct.</tags>
<cert/>
</nvt>
<scan_nvt_version>$Revision: 2837 $</scan_nvt_version>
<threat>Log</threat>
<severity>0.0</severity>
<qod>
<value>80</value>
<type>remote_banner</type>
</qod>
<description>Here is the route from 192.168.14.128 to 172.16.53.178:
192.168.14.128
172.16.53.178</description>
</result>
<filters id="">
<term>first=1 rows=-1 sort=name</term>
<keywords>
<keyword>
<column>first</column>
<relation>=</relation>
<value>1</value>
</keyword>
<keyword>
<column>rows</column>
<relation>=</relation>
<value>-1</value>
</keyword>
<keyword>
<column>sort</column>
<relation>=</relation>
<value>name</value>
</keyword>
</keywords>
</filters>
<sort>
<field>name
<order>ascending</order></field>
</sort>
<results max="-1" start="1"/>
<result_count>3444
<filtered>1</filtered>
<page>1</page></result_count>
</get_results_response>
After some research and attempts with some common xml parsing approaches, I ended up using jackson-dataformat-xml approach. While this might not be the best it gave me what I wanted with much less code. Basically, I had to adapt the annotations in the model classes as below :
#JsonIgnoreProperties(ignoreUnknown=true)
#JacksonXmlRootElement(localName = "results")
public class Results {
#JacksonXmlProperty(localName = "result")
#JacksonXmlElementWrapper(useWrapping = false)
public Result [] result;
public Results() {
}
public Result[] getResult() {
return result;
}
public void setResult(Result[] result) {
this.result = result;
}
#Override
public String toString() {
return "Results [result=" + Arrays.toString(result) + "]";
}
And some adaptations for the parsing class:
public class GetReportsResponseHandler extends DefaultHandler<GetReportsResponse> {
private XmlMapper mapper = new XmlMapper();
public GetReportsResponseHandler() {
super(new GetReportsResponse(), "get_reports_response");
AnnotationIntrospector primary = new JacksonAnnotationIntrospector();
AnnotationIntrospector secondary = new JaxbAnnotationIntrospector();
AnnotationIntrospector pair = new AnnotationIntrospectorPair(primary, secondary);
mapper.setAnnotationIntrospector(pair);
}
#Override
protected void parseStartElement(XMLStreamReader parser) throws XMLStreamException, IOException {
if ("report".equals(parser.getName().toString())){
Report report = mapper.readValue(parser, Report.class);
response.addReport(report);
}

NullPointerException when adding Object to ArrayList

I'm very new to Java and have been trying to set-up an ArrayList CustomerList that takes object Customer, where Customer has attributes from class IAddress. When calling the .add method in my main code however, I am given a NullPointerException error, which I assume is being given because my method isn't receiving anything to add to the ArrayList. I thought it was an issue with the attributes being initialised to empty strings, but when editing them to contain some information, the error still occured.
The ArrayList CustomerList
public class CustomerList {
public ArrayList<Customer> Clients;
public CustomerList() {
Clients = new ArrayList<>();
}
public void add(Customer src) {
Clients.add(src);
}
public void remove(Customer src) {
Clients.remove(src);
}
public void Display(JTextArea jClientsTextArea) {
for (int i = 0; i < Clients.size(); i++) {
Clients.get(i).Display(jClientsTextArea);
}
}
}
Receives Customer from this class
public class Customer {
private String FirstName;
private String Surname;
private IAddress HomeAddress;
public String DOB;
public Customer() {
FirstName = "";
Surname = "";
DOB = "01/01/1900";
HomeAddress = new IAddress();
public void Display(javax.swing.JTextArea jAddressTextArea) {
jAddressTextArea.setLineWrap(true);
jAddressTextArea.append("First Name: " + FirstName + "\n");
jAddressTextArea.append("Surname: " + Surname + "\n");
jAddressTextArea.append("DOB:" + DOB + "\n");
jAddressTextArea.append("Street: " + HomeAddress.getStreet() + "\n");
jAddressTextArea.append("House Name: " + HomeAddress.getHouseName() + "\n");
jAddressTextArea.append("House Number: " + HomeAddress.getHouseNo() + "\n");
jAddressTextArea.append("Area: " + HomeAddress.getArea() + "\n");
jAddressTextArea.append("Postcode: " + HomeAddress.getPostCode() + "\n");
jAddressTextArea.append("Town: " + HomeAddress.getTown() + "\n");
jAddressTextArea.append("Country: " + HomeAddress.getCountry() + "\n");
}
public void Edit(String strfirstname, String strsurname, String strDOB, String strStreet, String strHouseName, String strHouseNo, String strHouseArea, String strPostCode, String strTown, String strCountry) {
FirstName = strfirstname;
Surname = strsurname;
DOB = strDOB;
HomeAddress.setStreet(strStreet);
HomeAddress.setHouseName(strHouseName);
HomeAddress.setHouseNo(strHouseNo);
HomeAddress.setArea(strHouseArea);
HomeAddress.setPostCode(strPostCode);
HomeAddress.setTown(strTown);
HomeAddress.setCountry(strCountry);
}
}
Which receives attributes from IAddress
public class IAddress {
private String Name;
private String Street;
private String HouseNo;
private String HouseName;
private String Area;
private String PostCode;
private String Town;
private String Country;
public IAddress() {
Name = "";
Street = "";
HouseNo = "";
HouseName = "";
Area = "";
PostCode = "";
Town = "";
Country = "";
}
public void setName(String strName) {
Name = strName;
}
public void setStreet(String strStreet) {
Street = strStreet;
}
public void setHouseNo(String strHouseNo) {
HouseNo = strHouseNo;
}
public void setHouseName(String strHouseName) {
HouseName = strHouseName;
}
public void setArea(String strArea) {
Area = strArea;
}
public void setPostCode(String strPostCode) {
PostCode = strPostCode;
}
public void setTown(String strTown) {
Town = strTown;
}
public void setCountry(String strCountry) {
Country = strCountry;
}
}
I've been banging my head against this problem for hours and am ready for it to be something stupidly simple. Thank you.
In your code above the only reason why calling myCustomerList.add(...) could throw is that myCustomerList itself is null. This is because the Clients inside it is initialized in the constructor, and never set to null again. The value of src does not matter as well - the call to Clients.add(src) would succeed even if src is null.
You need to make sure that in your main you do initialize your customer list, like this:
CustomerList list = new CustomerList();

why is classNotFoundException being generated?

Why is my program generating this exception:
Exception in thread "main" java.lang.ClassNotFoundException:
writecoursefile.Course
when the class Course is defined in my code?
I'm not sure what the "writcoursefile" is because that isn't anywhere in my program.
This program is meant to deserialize a .ser file, sort, then print to csv file. I'm only up to the deserialization part though. The class Course was provided by my teacher.
/*
fallListSort Application
Created for CSci 112 by Steve Pesce
last Edited 3/16
*/
package falllistsort;
import java.io.*;
public class FallListSort {
public static void main(String[] args) throws Exception
{
//declare new course array
Course[] fall2014 = new Course[24];
//use fall2014.ser to define fall2014[]
fall2014 = readFromFile();
//Test: print array
for (Course course: fall2014)
{
System.out.println(course.toString());
}
}
public static Course[] readFromFile() throws Exception
{
Course[] course = null; //course object to holde file data
//declare file and object stream variables and initialize to null
FileInputStream fallFile = null;
ObjectInputStream infile = null;
try
{ //File and stream objects
fallFile = new FileInputStream("fall2014.ser");
infile = new ObjectInputStream(fallFile);
//read objects from file
course = (Course[]) infile.readObject();
} catch (IOException exc)
{
exc.printStackTrace();
}finally
{
infile.close();
}
return course;
}// end readfromFile()
public static void writeCSV(Course[] courseArray, int count) throws Exception
{
java.io.File courseCSV = new java.io.File("courses.csv");
java.io.PrintWriter outfile = new java.io.PrintWriter(courseCSV);
}
}
class Course implements Serializable {
private String campus; // the campus on which the course is offered
private String course; // the course number, such as CSCI 111
private String section; // the section number
private String crn; // the CRN for this section
private int credits; // the number od credits for the course
private String time; // the time the course is offered, such as 8:00 to 10:00 A.M.
private String days; // the Days the course is offered, suhc as MW
// constructors
Course() {
}
Course(String course, String section, String crn, int credits) {
this.course = course;
this.section = section;
this.crn = crn;
this.credits = credits;
} // end Course() initalizing
// muatator methods
public void setCampus(String cmp) {
this.campus = cmp;
}// end setCampus()
public void setCourse(String crse) {
this.course = crse;
}// end setCourse()
public void setSection(String sect) {
this.section = sect;
} // end setSection()
public void setCRN(String crn) {
this.crn = crn;
} // end setCRN()
public void setCredits(int cr) {
this.credits = cr;
} // end setCredits()
public void setTime(String tm) {
this.time = tm;
}// end setTime()
public void setDays(String days) {
this.days = days;
}// end setDays()
// accessor methods
public String getCampus() {
return campus;
} // end getCampus()
public String getCourse() {
return course;
} // end Course()
public String getSection() {
return section;
} // end getSection()
public String getCRN() {
return crn;
} // end getCRN()
public int getCredits() {
return credits;
} // end getCredits()
public String getTime() {
return time;
} // end getTime()
public String getDays() {
return days;
} // end getDays()
// method to compare by CRN using the String class compareTo()
public int compareTo(Course other) {
return this.crn.compareTo(other.getCRN());
} // end compareTO()
// method to return properties as a string
public String toString() {
return campus + " "
+ course + " "
+ section + " "
+ crn + " "
+ credits + " "
+ time + " "
+ days;
} // end toString()
// You will need to add a method to return properties as a CSV string on one line
/* public String toCSVString() {
} // end toCSVString()
*/
}// end class Course

Categories