Trouble loading from XML file - java

I have a major problem. We can call this application "boat club system" and its a assignment in a UML course. But the problem that is really bothering me is that i can't load the "Member" Objects back to the Arraylist that is used when Exporting and Importing the objects.
I got some help with this by a friend, but the Importing won't work.
This is the Error i get when trying to import.
Exception in thread "main" java.lang.NullPointerException
at boat.Controller.SystemController.readFromSystem(SystemController.java:288)
at boat.Controller.SystemController.<init>(SystemController.java:26)
at boat.View.Console.<init>(Console.java:17)
at BoatMain.main(BoatMain.java:22)
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:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
The problem is pointed on this specific line:
member.setMemberId(Integer.parseInt(element.get(i).getAttribute("memberId").getValue()));
The link to the whole application.
https://github.com/mjuu/boat/tree/master/src
The System controller class looks like this.
BTW, i am thinking of splitting up this class to more like System controller and Member controller for a more High Cohesion/Low coupling design. But only when i get the Import working correctly..
I don't know why it doesn't work. The member id is a INTEGER at first, but when exported its converted to a String. When imported it converted to a Int again. So I'm wondering if its something wrong there..
Would really appreciate help so i could continue.
System Controller
public void readFromSystem () {
File file = null;
Builder builder = null;
Document doc = null;
try {
file = new File(filePath);
builder = new Builder();
doc = builder.build(file);
Element root = doc.getRootElement();
Elements members = root.getChildElements();
for (int i = 0; i < members.size(); i++) {
Elements element = members.get(i).getChildElements();
Member member = new Member();
member.setMemberId(Integer.parseInt(element.get(i).getAttribute("memberId").getValue()));
member.setPersonId(element.get(0).getValue());
member.setName(element.get(1).getValue());
memberList.add(member);
if (members.get(i).getChildElements().size() == 3) {
Elements boats = element.get(2).getChildElements();
for (int j = 0; j < boats.size(); j++) {
Boat b = new Boat();
b.setBoatId(Integer.parseInt(boats.get(j).getAttribute("boatId").getValue()));
b.setBoatType(Integer.parseInt(boats.get(j).getChildElements().get(1).getValue()));
b.setBoatLength(boats.get(j).getChildElements().get(2).getValue());
}
}
}
} catch (IOException e) {
System.out.print("Could not read from the system");
} catch (nu.xom.ParsingException e) {
System.out.print("Parsing was unsuccessful!");
}
}

Related

Java XML Getting nodes from node list crashes program

Hello there.
As the title suggests, I currently have an issue in
my program. In the animation loader, I have a method that should
load an animation from a collada file. It gets an Element as an input.
The first thing I do is to collect the animation data. I do this by getting a node list with
NodeList sources = element.getElementsByTagName("source");
And then I iterate through that node list:
for(int i = 0; i < sources.getLength(); i++)
{
// Problem occurs here:
Element sourceElement = (Element) (sources.item(i));
String id = sourceElement.getAttribute("id");
if(id.equals(inputId))
inputSource = FloatArraySource.loadFromElement(sourceElement);
else if(id.equals(outputId))
outputSource = Matrix4fSource.loadFromElement(sourceElement);
else if(id.equals(interpolationId))
interpolationSource = StringArraySource.loadFromElement(sourceElement);
}
The problem occurs on the commented line, and it crashes (only sometimes) with this following exception
Cannot invoke "com.sun.org.apache.xerces.internal.dom.CoreDocumentImpl.changes()" because the return value of "com.sun.org.apache.xerces.internal.dom.NodeImpl.ownerDocument()" is null
I can start the application three times in a row, and it crashes roughly one of four times.
The strangest thing is the fact that it runs perfectly fine in debug mode.
So, I'd be very happy if you could help me out with this issue.
-Budschie
Edit: Some people wanted that I post the full stack trace, so here it is:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "com.sun.org.apache.xerces.internal.dom.CoreDocumentImpl.changes()" because the return value of "com.sun.org.apache.xerces.internal.dom.NodeImpl.ownerDocument()" is null
at java.xml/com.sun.org.apache.xerces.internal.dom.NodeImpl.changes(NodeImpl.java:1887)
at java.xml/com.sun.org.apache.xerces.internal.dom.DeepNodeListImpl.item(DeepNodeListImpl.java:125)
at java.xml/com.sun.org.apache.xerces.internal.dom.DeepNodeListImpl.getLength(DeepNodeListImpl.java:116)
at de.budschie.engine.assets_management.newcollada.AnimationLoader.loadTransformAnimation(AnimationLoader.java:77)
at de.budschie.engine.assets_management.newcollada.AnimationLoader.loadAnimation(AnimationLoader.java:31)
at de.budschie.engine.assets_management.newcollada.ColladaLoader.loadCollada(ColladaLoader.java:60)
at de.budschie.engine.assets_management.DefaultResourceLoader.loadAll(DefaultResourceLoader.java:75)
at de.budschie.engine.main.MainWindow.gameLoop(MainWindow.java:192)
at de.budschie.engine.main.MainWindow.main(MainWindow.java:81)
Another edit:
Here's the way I load my collada files:
Element colladaTag = null;
try
{
colladaTag = getColladaTag(colladaFile);
} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
Element libraryAnimations = (Element) colladaTag.getElementsByTagName("library_animations").item(0);
Element libraryControllers = (Element) colladaTag.getElementsByTagName("library_controllers").item(0);
Element libraryGeometries = (Element) colladaTag.getElementsByTagName("library_geometries").item(0);
NodeList meshesList = null, controllersList = null;
if(libraryGeometries != null)
{
meshesList = libraryGeometries.getElementsByTagName("geometry");
}
if(libraryControllers != null)
{
controllersList = libraryControllers.getElementsByTagName("controller");
}
if(libraryAnimations != null)
{
AnimationLoader.loadAnimation(colladaResult, libraryAnimations);
}
And here's what "getColladaTag()" looks like:
private static Element getColladaTag(String path) throws Exception
{
File file = new File(path);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try
{
DocumentBuilder docBuilder = factory.newDocumentBuilder();
Document doc = docBuilder.parse(file);
return doc.getDocumentElement();
}
catch(IOException | SAXException ex)
{
System.out.println("There is a problem with the file that couldn't be fixed.");
ex.printStackTrace();
}
return null;
}
Another small thing I noticed is that sometimes, the JVM itself crashesbecause of an access violation in the string builder...
Very important edit:Whilest debugging I found out that I can't import com.sun.org.apache.xerces.internal.dom.NodeImpl.
My program doesn't throw a ClassNotFoundException though...
So, could that be a reason why the GC is so confused?
You could change
for(int i = 0; i < sources.getLength(); i++)
{
// Problem occurs here:
Element sourceElement = (Element) (sources.item(i));
to
for ( Element sourceElement : sources )
{
which would remove sources.item(i). You could put System.out.println("Index: " + i): just above this line, which would give an indication of how far you get.
It looks like something is modifying the sources container while you are processing it.
private static <T extends YourColladaDataFormat> T loadColladaFile(String pathToXml) throws Exception {
// loads the XML Document, walks through it and returns your workable data model.
}
And then work with T.

Java: ClassNotFound Classpath issues

Im trying to read some information from a file into some objects. Main method just reads the Information into some string variables then uses those strings to initialize objects. Pretty simple. The objects are stored using a BST.
However, The error Im getting is ClassNotFoundException. Except when I run the java 'file' command, 'file' is spelled and capitalized correctly.
I've been reading that you can change the path that JVM uses when searching for class files.
so I tried:
set CLASSPATH=$CLASSPATH=~/../../BackEnd
but that didn't do anything..
Here is my main file..
import java.util.Scanner;
import java.io.File;
class BackEnd
{
public static void main(String args[]) throws java.io.FileNotFoundException
{
Tree.ServiceTree providers = new Tree.ServiceTree();
String path = "./providers.txt";
Scanner read = new Scanner (new File(path));
read.useDelimiter(",");
String information[] = new String[5];//array of strings used to store info from file, then used to initialize objects
try
{
while(read.hasNext())
{
for(int i = 0; i < 5; ++i)
{
information[i] = read.nextLine();//read in all the info into the array
}
Services.Service newService;//used as dynamic reference to be passed to tree
Services.Service serviceInfo = new Services.Service(information[0], information[1]);//initalizes base class to be passed to derived constructor
switch(information[0])//check type to initalize appropriate object
{
case "Dogwalk":
newService = new Services.Dogwalk(serviceInfo, information[2], information[3]);
case "Groceries":
newService = new Services.Groceries(serviceInfo, information[2], information[3]);
case "Housework":
newService = new Services.Housework(serviceInfo, information[2], information[3]);
}
providers.insert(information[4], newService);
}
read.close();
throw new java.io.FileNotFoundException("File not found...");
}
catch(java.io.FileNotFoundException exception)
{
System.out.println("File not found");
}
//providers.display();
}
}
Figured it out. Error had nothing to do with compilation or class path and was due
to uninitialized variable newService

Converting part of .dox document to html using Apache POI

I use XHTMLConverter to convert .docx to html, to make preview of the document. Is there any way to convert only few pages from original document? I'll be grateful for any help.
You have to parse the complete .docx file. It is not possible to read just parts of it. Otherwise if you want to know how to select a specific page number, im afraid to tell you(at least I believe) that word does not store page numbers therefore there is no function in the libary to accsess a specified page..
(I've read this at another forum, it actually might be false information).
PS: the Excel POI contains a .getSheetAt()method (this might helps you for your research)
But there are also other ways to accsess your pages. For instance you could read the lines of your docx document and search for the pagenumbers(might crash if your text contains those numbers though). Another way would be to search for the header of the site which would be more accurate:
HeaderStories headerStore = new HeaderStories( doc);
String header = headerStore.getHeader(pageNumber);
this should give you the header of the specified page. Same with footer:
HeaderStories headerStore = new HeaderStories( doc);
String footer = headerStore.getFooter(pageNumber);
If this dosen't work. I am not really into that API....
here a little Example for a very sloppy solution:
import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
public class ReadDocFile
{
public static void main(String[] args)
{
File file = null;
WordExtractor extractor = null;
try
{
file = new File("c:\\New.doc");
FileInputStream fis = new FileInputStream(file.getAbsolutePath());
HWPFDocument document = new HWPFDocument(fis);
extractor = new WordExtractor(document);
String[] fileData = extractor.getParagraphText();
for (int i = 0; i < fileData.length; i++)
{
if (fileData[i].equals("headerPageOne")){
int firstLineOfPageOne = i;
}
if (fileData[i]).equals("headerPageTwo"){
int lastLineOfPageOne = i
}
}
}
catch (Exception exep)
{
exep.printStackTrace();
}
}
}
If you go with this i would recommend you to create a String[] with your headers and refractor the for-loop to a seperate getPages() Method. Therefore your loop would look like:
List<String> = new ArrayList<String>(Arrays.asList("header1","header2","header3","header4"));
for (int i = 0; i < fileData.length; i++)
{
//well there should be a loop for "x" too
if (fileData[i].equals(headerArray[x])){
int firstLineOfPageOne = i;
}
if (fileData[i]).equals(headerArray[x+1]){
int lastLineOfPageOne = i
}
}
You could create an Object(int pageStart, int PageStop), wich would be the product of your method.
I hope it helped you :)

Loading and saving files in a text based game (java)

So, i'm trying to save my player data onto a txt file, then load the data from the text from when the game is opened again, but its not working, I get it to save while in the game, but when I close the game, and open it back up its no longer saved, and it has all the default data in the game, and in the file...
Here is the some of the code from the game (Sorry it's in pastebin, I thought i might be too long to just paste it into here.)
Game.java
Save.java
I am in need of some assistance, trying to get it to load from the text document, and when the game opens, not resetting the text document into its default settings.
The issue is in Save.savePlayer()
At the beginning you declare saveInfo to hold the values that the game holds at that point in time. When initially loading they will hold the default values.
int[] saveInfo = { Game.hp, Game.level, Game.mana, Game.expTotal,
Game.goldTotal, Game.arrow, Game.shuriken, Game.bomb,
Game.hpPotion, Game.mpPotion, Game.potion, Game.items };
The variables here:Game.hp=100, Save.saveInfo[0]=100
Then you set all of the game variables to saveInfo at the beginning of Save.savePlayer()
Game.hp = saveInfo[0];
Game.level = saveInfo[1];
Game.mana = saveInfo[2];
Game.expTotal = saveInfo[3];
Game.goldTotal = saveInfo[4];
Game.arrow = saveInfo[5];
Game.shuriken = saveInfo[6];
Game.bomb = saveInfo[7];
Game.hpPotion = saveInfo[8];
Game.mpPotion = saveInfo[9];
Game.potion = saveInfo[10];
Game.items = saveInfo[11];
The variables here:Game.hp=100, Save.saveInfo[0]=100
They don't change because you just set them back to their default values.
Then you load the saved state but you don't do anything with the data. You should be setting the variables after loading here so they're set to the new saveInfo values instead of the old.
for (int i = 0; i < saveInfo.length; i++) {
saveInfo[i] = Integer.parseInt(inputReader.readLine());
}
I think this part is the problem...
private void readPlayer(String filePath) {
File inputFile;
BufferedReader inputReader;
try {
inputFile = new File(filePath);
inputReader = new BufferedReader(new FileReader(inputFile));
Game.hp = saveInfo[0];
Game.level = saveInfo[1];
Game.mana = saveInfo[2];
Game.expTotal = saveInfo[3];
Game.goldTotal = saveInfo[4];
Game.arrow = saveInfo[5];
Game.shuriken = saveInfo[6];
Game.bomb = saveInfo[7];
Game.hpPotion = saveInfo[8];
Game.mpPotion = saveInfo[9];
Game.potion = saveInfo[10];
Game.items = saveInfo[11];
for (int i = 0; i < saveInfo.length; i++) {
saveInfo[i] = Integer.parseInt(inputReader.readLine());
}
inputReader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
put these lines
for (int i = 0; i < saveInfo.length; i++) {
saveInfo[i] = Integer.parseInt(inputReader.readLine());
}
before
Game.hp = saveInfo[0];
Game.level = saveInfo[1];
Game.mana = saveInfo[2];
Game.expTotal = saveInfo[3];
Game.goldTotal = saveInfo[4];
Game.arrow = saveInfo[5];
Game.shuriken = saveInfo[6];
Game.bomb = saveInfo[7];
Game.hpPotion = saveInfo[8];
Game.mpPotion = saveInfo[9];
Game.potion = saveInfo[10];
Game.items = saveInfo[11];
in order to read the file before setting the game values...
If you do not mind it, then using xstream and apache fileutils is an excellent solution and less coding. I am just sharing my thoughts.
import org.apache.commons.io.FileUtils;
import com.thoughtworks.xstream.XStream;
//saving your data
XStream xstream=new XStream(new DOMDriver());
String xml = xstream.toXML(yourGambeObj);
FileUtils.writeStringToFile(new File("yourfilename", xml);
//reading your data
Game gameData=xstream.fromXML(new File("yourfilename"),Game.class);
//now you can use access your methods n attribute. no conversion as you did in serialization.
Please download and add these jars.XStream &
Apache Commons IO
So, I was fiddling around with some things, and I did it! So, the problem was, that i would load it from the save data, then write over it, then load it again, for some reason, it would do the whole Save.java 2 times and just save over it, but I put them all as public static voids and instead of calling the whole Constructor, I call them by individual methods by where and what they need to do, which seem to work great! Thank you all for all your help, it helped a lot!

How to write and retrieve objects arraylist to file?

I have an object arraylist, can someone please help me by telling me the most efficient way to write AND retrieve an object from file?
Thanks.
My attempt
public static void LOLadd(String ab, String cd, int ef) throws IOException {
MyShelf newS = new MyShelf();
newS.Fbooks = ab;
newS.Bbooks = cd;
newS.Cbooks = ef;
InfoList.add(newS);
FileWriter fw;
fw = new FileWriter("UserInfo.out.txt");
PrintWriter outt = new PrintWriter(eh);
for (int i = 0; i <InfoList.size(); i++)
{
String ax = InfoList.get(i).Fbooks;
String ay = InfoList.get(i).Bbooks;
int az = InfoList.get(i).Cbooks;
output.print(ax + " " + ay + " " + az); //Output all the words to file // on the same line
output.println(""); //Make space
}
fw.close();
output.close();
}
My attempt to retrieve file. Also, after retrieving file, how can I read each column of Objects?? For example, if I have ::::: Fictions, Dramas, Plays --- How can I read, get, replace, delete, and add values to Dramas column?
public Object findUsername(String a) throws FileNotFoundException, IOException, ClassNotFoundException
{
ObjectInputStream sc = new ObjectInputStream(new FileInputStream("myShelf.out.txt"));
//ArrayList<Object> List = new ArrayList<Object>();
InfoList = null;
Object obj = (Object) sc.readObject();
InfoList.add((UserInfo) obj);
sc.close();
for (int i=0; i <InfoList.size(); i++) {
if (InfoList.get(i).user.equals(a)){
return "something" + InfoList.get(i);
}
}
return "doesn't exist";
}
public static String lbooksMatching(String b) {
//Retrieve data from file
//...
for (int i=0; i<myShelf.size(); i++) {
if (myShelf.get(i).user.equals (b))
{
return b;
}
else
{
return "dfbgregd";
}
}
return "dfgdfge";
}
public static String matching(String qp) {
for (int i=0; i<myShelf.size(); i++) {
if (myShelf.get(i).pass.equals (qp))
{
return c;
}
else
{
return "Begegne";
}
}
return "Bdfge";
}
Thanks!!!
It seems like you want to serialize an object and persist that serialized form to some kind of storage (in this case a file).
2 important remarks here :
Serialization
Internal java serialization
Java provides automatic serialization which requires that the object be marked by implementing the java.io.Serializable interface. Implementing the interface marks the class as "okay to serialize," and Java then handles serialization internally.
See this post for a code sample on how to serialize /
deserialize an object to/from bytes.
This might nog always be the ideal way to persist an object, as you have no control over the format (handled by java), it's not human readable, and you can versioning issues if your objects change.
Marshalling to JSON or XML
A better way to seralize an object to disk is to use another data format like XML or JSON.
A sample on how to convert an object to/from a JSON structure can be found here.
Important : I would not do the kind of serialization in code like you're doing unless there is a very good reason (that I don't see here). It quickly becomes messy and is subject to change when your objects change. I would opt for a more automated way of serializing. Also, when using a format like JSON / XML, you know that there are tons of APIs available to read/write to that format, so all of that serialization / deserialization logic doesn't need to be implemented by you anymore.
Persistence
Writing your serialized object to a file isn't always a good idea for various reasons (no versioning / concurrency issues / .....).
A better approach is to use a database. If it's a hierarchical database, take a look at Hibernate or JPA to persist your objects with very little code.
If it's a document database like MongoDB, you can persist your JSON serialized representation.
There are tons of resources available on persisting objects to databases in Java. I would suggest checking out JPA, the the standard API for persistence and object/relational mapping .
Here is another basic example, which will give you insight into Arraylist,constructor and writing output to file:
After running this, if you are using IDE go to project folder, there you will file *.txt file.
import java.io.*;
import java.util.List;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ListOfNumbers {
private List<Integer> list;
private static final int SIZE = 10;//whatever size you wish
public ListOfNumbers () {
list = new ArrayList<Integer>(SIZE);
for (int i = 0; i < SIZE; i++) {
list.add(new Integer(i));
}
}
public void writeList() {
PrintWriter out = null;
try {
out = new PrintWriter(new FileWriter("ManOutFile.txt"));
for (int i = 0; i < SIZE; i++) {
out.println("Value at: " + i + " = " + list.get(i));
}
out.close();
} catch (IOException ex) {
Logger.getLogger(ListOfNumbers.class.getName()).log(Level.SEVERE, null, ex);
} finally {
out.close();
}
}
public static void main(String[] args)
{
ListOfNumbers lnum=new ListOfNumbers();
lnum.writeList();
}
}

Categories