I have created an application which takes user input from textfields and stores it in an XML file. The user can then reload these inputs back into a text field on the click of a button.
The issue I'm having is that the most recent version of the XML file is not being used - for example when I start the application and save new inputs the load function doesn't load the input even though the XML file has the data in it. When I close and then restart the application the load functionality works using the data from the last session. If I try adding new inputs the load button will just cycle through the data from the last session, not using the new points.
So my question is why isn't the current state of the XML file being read?
Save to XML Code:
ArrayList<SavedPosition> posList = new ArrayList<SavedPosition>();
String SAVEDPOS_XML = "savedPos.xml";
save.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
SavedPosition saved = new SavedPosition();
saved.setPosition1(mediaPlayerComponent.getMediaPlayer().getTime());
saved.setPosition2(mediaPlayerComponent2.getMediaPlayer().getTime());
saved.setNBehaviour(textArea.getText());
saved.setABehaviour(textArea1.getText());
saved.setGap(textArea2.getText());
saved.setForces(textArea3.getText());
saved.setFindings(textArea2.getText());
posList.add(saved);
SavedPositions savedPos = new SavedPositions();
savedPos.setSavedPositions(posList);
try {
// create JAXB context and instantiate marshaller
JAXBContext context = JAXBContext.newInstance(SavedPositions.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
//print
m.marshal(savedPos, System.out);
//write to file
m.marshal(savedPos, new File(SAVEDPOS_XML));
} catch (JAXBException ex) {
Logger.getLogger(DoubleViewer.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
XML to Object code:
public class XmlToObject {
public static ArrayList<ArrayList<String>> main() {
ArrayList<ArrayList<String>> obj1 = new ArrayList<ArrayList<String>>();
ArrayList<ArrayList<String>> obj = new ArrayList<ArrayList<String>>();
try{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document d = db.parse("savedPos.xml");
XPath xp = XPathFactory.newInstance().newXPath();
NodeList nl = (NodeList) xp.compile("//savedPosition").evaluate(d, XPathConstants.NODESET);
System.out.println("number of saved positions " + nl.getLength());
for (int i = 0; i < nl.getLength(); i++){
String a = (xp.compile("./NBehaviour").evaluate(nl.item(i)));
String b = (xp.compile("./ABehaviour").evaluate(nl.item(i)));
String c = (xp.compile("./gap").evaluate(nl.item(i)));
String d1 = (xp.compile("./forces").evaluate(nl.item(i)));
String e = (xp.compile("./findings").evaluate(nl.item(i)));
String f = (xp.compile("./position1").evaluate(nl.item(i)));
String g = (xp.compile("./position2").evaluate(nl.item(i)));
ArrayList<String> savedPosition = new ArrayList<String>();
savedPosition.add(a);
savedPosition.add(b);
savedPosition.add(c);
savedPosition.add(d1);
savedPosition.add(e);
savedPosition.add(f);
savedPosition.add(g);
obj.add(savedPosition);
}
return obj;
}catch(Exception l){
System.out.println(l.getMessage());
}
return obj1;
}
}
Load button code:
List<ArrayList<String>> obj = XmlToObject.main();
int a = obj.size();
load.addActionListener(new ActionListener() {
int displayedPositionIndex = 0;
public void actionPerformed(ActionEvent e) {
displayedPositionIndex++;
if(displayedPositionIndex >= obj.size()) {
displayedPositionIndex = 0; // to loop back to first after last position
}
setPosition(displayedPositionIndex);
}
private void setPosition(int index) {
List<String> positionData = obj.get(index);
textArea.setText(positionData.get(0));
textArea1.setText(positionData.get(1));
textArea2.setText(positionData.get(2));
textArea3.setText(positionData.get(3));
textArea4.setText(positionData.get(4));
Long position = Long.valueOf(positionData.get(5));
mediaPlayerComponent.getMediaPlayer().setTime(position);
mediaPlayerComponent2.getMediaPlayer().setPosition(Float.parseFloat(positionData.get(6)));
}
});
Related
I'm trying to create XML report, that can be opened as xls table.
I have following output:
<Report>
<test>
<string>4.419</string>
<string>4.256</string>
</test>
</Report>
from this code:
/**
* declare arrays
*/
// ArrayList<String> test = new ArrayList<String>();
ArrayList<String> stats = new ArrayList<String>();
// ArrayList<String> count = new ArrayList<String>();
/**
*return array list with loading times
*/
public ArrayList launch() {
for (int i = 0; i < 2; i++) {
// ui.off();
// ui.on();
device.pressHome();
ui.openProgramInMenu("ON");
long TStart = System.currentTimeMillis();
ui.detectContactList();
long TStop = System.currentTimeMillis();
float res = TStop - TStart;
res /= 1000;
ui.log("[loading time]: " + res);
// ui.off();
test.add(i, "Loading time");
stats.add(i, Float.toString(res));
count.add(i, Integer.toString(i));
}
System.out.println(stats);
}
where rep.class has code:
public class ReportSettings {
public List<String> test = new ArrayList<String>();
public List<String> count = new ArrayList<String>();
public List<String> stats = new ArrayList<String>();
/**
* Test method
*/
public static void main(String[] args) {
ReportSettings rep = new ReportSettings();
rep.saveXML("report/data.xml");
// System.out.println(rep.test);
// rep = rep.loadXML("report/data.xml");
// System.out.println(rep.home);
System.out.println(rep.getXML());
}
public void createReport() {
ReportSettings rep = new ReportSettings();
rep.saveXML("report/data.xml");
}
public String getXML() {
XStream xstream = new XStream();
xstream.alias("Report", ReportSettings.class);
xstream.autodetectAnnotations(true);
return xstream.toXML(this);
}
public void saveXML(String filename) {
if (!filename.contains(".xml")) {
System.out.println("Error in saveReport syntax");
return;
}
String xml = this.getXML();
File f = new File(filename);
try {
FileOutputStream fo = new FileOutputStream(f);
fo.write(xml.getBytes());
fo.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
public ReportSettings loadXML(String filename) {
if (!filename.endsWith(".xml")) {
System.out.println("Error in loadReport syntax!");
throw new RuntimeException("Error in loadReport syntax!");
}
File f = new File(filename);
XStream xstream = new XStream(new DomDriver());
xstream.alias("Report", ReportSettings.class);
xstream.autodetectAnnotations(true);
ReportSettings ort = (ReportSettings)xstream.fromXML(f);
return ort;
}
}
Finally I want to create table from 3 ArrayList, where {stats, count, test}*i. /n
How can I use Xstream.alias to change <strings> to <somethingAnother> in the XML file? I need to change them to stringOne and stringTwo as example.
You can use the ClassAliasMapper in Xstream to give the items in your collection a different tag when serializing to XML.
You add a block like this (for each collection: stats, count, test):
ClassAliasingMapper statsMapper = new ClassAliasingMapper(xstream.getMapper());
mapper.addClassAlias("somethingAnother", String.class);
xstream.registerLocalConverter(
InteractionSession.class,
"stats",
new CollectionConverter(mapper)
);
Good day ppl.
I have class:
public class XmlModifier {
private DocumentBuilderFactory docFactory = null;
private DocumentBuilder docBuilder = null;
private Document document = null;
private TransformerFactory transformFactory = null;
private Transformer transform = null;
private DOMSource source = null;
private StreamResult streamRes = null;
private boolean exepDocBuilderAlarm = true;
public XmlModifier() {
this.docFactory = DocumentBuilderFactory.newInstance();
try {
this.docBuilder = docFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
this.exepDocBuilderAlarm = false;
e.printStackTrace();
}
}
public void prepareXMLMessage(File file, String userName, String userPassword, String reqId, Integer NUMBER_OF_MSG_SENDS) {
if (exepDocBuilderAlarm != false) {
try {
document = docBuilder.parse(file);
setElementValues("si:sourceInfo", addElementsToArray("si:reqId,si:reqTag"), addElementsToArray(reqId + "," + reqId), NUMBER_OF_MSG_SENDS);
setElementValues("usr:user", addElementsToArray("usr:id,usr:password"), addElementsToArray(userName + "," + userPassword), NUMBER_OF_MSG_SENDS);
setElementValues("meth:method", addElementsToArray("meth:id,meth:tag"), addElementsToArray(reqId + "," + reqId), NUMBER_OF_MSG_SENDS);
setElementValues("tb:tradeField", addElementsToArray("tb:value"), addElementsToArray(reqId), NUMBER_OF_MSG_SENDS);
this.transformFactory = TransformerFactory.newInstance();
this.transform = transformFactory.newTransformer();
this.source = new DOMSource(document);
this.streamRes = new StreamResult(file);
this.transform.transform(source, streamRes);
System.out.println("Done to execute XmlModifier");
} catch (Exception e) {
e.printStackTrace();
} finally {
this.docFactory = null;
this.docBuilder = null;
this.transformFactory = null;
this.transform = null;
this.source = null;
this.streamRes = null;
}
}
}
private void setElementValues(String rootElement, String[] childElements, String[] childElementsValues, Integer msgIDIncrement) {
Node nodeRootElement = document.getElementsByTagName(rootElement).item(0);
NodeList childElementlist = nodeRootElement.getChildNodes();
for (int i = 0; i < childElements.length; i++) {
for (int z = 0; z < childElementlist.getLength(); z++) {
Node node = childElementlist.item(z);
if (childElements[i].equals(node.getNodeName())) {
node.setTextContent(childElementsValues[i]);
}
}
}
}
private String[] addElementsToArray(String elements) {
String[] theArray = null;
theArray = elements.split(",");
return theArray;
}
}
On input I have xml which is not well formed sometimes. The problem of DOM parser is that in my point of view DOM parser parsing whole xml from the beggining which my have special symbols like < > & " ' is not good for me.
How can I on input to prepareXMLMessage(..) provide xml with < > & " ', then in prepareXMLMessage(..) parse it with no problems(change some values inside elements) and than as output provide xml with < > & " ' back???
Thank you for help.
I am trying to Parse the below XML file and create an JTree based on it.
<OBJECTS>
<WINDOW NAME = "WINDOW 01" URL = "URL 01">
<PAGE NAME = "PAGE 01" URL = "PAGE URL 01">
</PAGE>
</WINDOW>
</OBJECTS>
The "WINDOW 01" is getting added to the root node "Object List", but the "PAGE 01" node is not getting displayed under the "WINDOW 01" node. The source code used is given below. Please Help!!!
public class DataNode extends DefaultMutableTreeNode {
private static final long serialVersionUID = 1L;
public String ObjectType, ObjectName, URL, ElementType;
public DefaultMutableTreeNode node;
public DataNode(DefaultMutableTreeNode node, Element element) {
this.node = node;
this.ObjectType = element.getTagName();
this.ObjectName = element.getAttribute("NAME");
this.URL = element.getAttribute("URL");
this.ElementType = element.getAttribute("TYPE");
}
public DataNode(Element element) {
this.node = new DefaultMutableTreeNode("OBJECT");
this.ObjectType = element.getTagName();
this.ObjectName = "Object List";
this.URL = "";
this.ElementType = "";
}
#Override
public String toString() {
return this.ObjectName;
}
}
This is the main class. No errors or warnings are displayed on compiling.
public class MyOwn {
private JFrame contentsFrame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MyOwn window = new MyOwn();
window.contentsFrame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public MyOwn() {
contentsFrame = new JFrame();
contentsFrame.setTitle("My JTree");
contentsFrame.setBounds(100, 100, 549, 738);
contentsFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTree objectListTree = new JTree(convertXMLtoTree("G:/Collection.xml"));
objectListTree.setAlignmentY(Component.TOP_ALIGNMENT);
objectListTree.setAlignmentX(Component.LEFT_ALIGNMENT);
contentsFrame.getContentPane().add(new JScrollPane(objectListTree));
}
private DefaultMutableTreeNode convertXMLtoTree(String Path) {
NodeList nWindow, nPage;
DefaultMutableTreeNode dRoot, dWindow, dPage;
DataNode xRoot, xWindow, xPage;
try {
File fXmlFile = new File(Path);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
xRoot = new DataNode(doc.getDocumentElement());
dRoot = new DefaultMutableTreeNode(xRoot);
nWindow = doc.getDocumentElement().getElementsByTagName("WINDOW");
for (int i = 0; i < nWindow.getLength(); i++) {
dWindow = new DefaultMutableTreeNode(((Element)(nWindow.item(i))).getAttribute("NAME"));
xWindow = new DataNode(dWindow, (Element)(nWindow.item(i)));
dRoot.add(xWindow);
nPage = ((Element)(nWindow.item(i))).getElementsByTagName("PAGE");
for (int j = 0; j < nPage.getLength(); j++) {
dPage = new DefaultMutableTreeNode(((Element)(nPage.item(j))).getAttribute("NAME"));
xPage = new DataNode(dPage, (Element)(nPage.item(j)));
dWindow.add(xPage);
}
}
return dRoot;
} catch (Exception e) {
return null;
}
}
}
Add your custom DefaultMutableTreeNode DataNode to child node for WINDOW 01 rather than the dWindow which never gets added to the JTree. Replace
dWindow.add(xPage);
with
xWindow.add(xPage);
I'm modifying an app that loads data dynamically from an XML file that contains a quiz and displays questions and replies. The change consists in the fact that i want to load a single(hardcoded for now) file instead of using a JFileChooser.
Here's the relevant code working before(undefined variables are class attributes but i won't post the whole class declaration):
public ClassConstructor()
{
JMenuItem load = new JMenuItem("Load");
...
}
load.addActionListener(new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
if(status == UNSAVED_CHANGES)
if(JOptionPane.showConfirmDialog(gThis , "There are unsaved changes. Continue?" , "Unsaved changes" , JOptionPane.OK_CANCEL_OPTION) == 2)
return;
int returnVal = filePick.showOpenDialog(new JPanel());
if(returnVal == JFileChooser.APPROVE_OPTION)
{
try
{
load(filePick.getSelectedFile().getCanonicalPath());
pathname = filePick.getSelectedFile().getCanonicalPath();
}
catch(IOException f)
{
System.out.println(f);
}
setupQuestion("q1");
openingLabel.setText(theBase.getDocumentElement().getAttribute("opening"));
status = FILE_LOADED;
}
}
}
);
private static void load(String fileName)
{
System.out.println(fileName);
try
{
DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();
dbf.setValidating(true);
DocumentBuilder db = dbf.newDocumentBuilder();
db.setErrorHandler(new DefaultHandler());
theBase = db.parse(fileName);
idno = Integer.parseInt(((Element)(theBase.getElementsByTagName("base").item(0))).getAttribute("idno"));
System.out.println(idno);
lastName = fileName;
status = FILE_LOADED;
}
catch(IOException e)
{
System.out.println(e);
}
catch(ParserConfigurationException p)
{
System.out.println(p);
}
catch(SAXException s)
{
System.out.println(s);
}
}
public static void setupQuestion(String qid)
{
linkids = new Vector();
links = new Vector();
qdata = new Vector();
Element e = theBase.getElementById(qid);
question.setText(e.getAttribute("value"));
int items = 0;
NodeList nl = e.getChildNodes();
for(int i=0; i < nl.getLength(); i++)
{
if(nl.item(i).getNodeType() == Node.ELEMENT_NODE)
{
items++;
qdata.add(((Element)nl.item(i)).getAttribute("content") );
linkids.add(((Element)nl.item(i)).getAttribute("link"));
links.add((Element)nl.item(i));
}
}
replies.setListData(qdata);
thisq = qid;
}
And now for the code that doesn't work:
public ClassConstructor()
{
//JMenuItem load = new JMenuItem("Load");
load("C:\\file.xml");
pathname = "C:\\file.xml";
setupQuestion("q1");
openingLabel.setText(theBase.getDocumentElement().getAttribute("opening"));
}
// i've dropped load.addActionListener() but rest of the code has no changes
Also, the exception:
Exception in thread "main" java.lang.NullPointerException
and it occurs at question.setText(e.getAttribute("value")); on calling setupQuestion("q1");.
Edit: Interestingly enough System.out.println(fileName); gets printed before the Exception is thrown and System.out.println(idno); is printed after it. Actually on restarting the IDE both echos appear after the exception is thrown.
I've been stuck on this for quite some time. Any help is much appreciated.
Found the culprit. I guess I haven't mentioned everything. I've forgot to allocate memory for question and replies. I am so ashamed.
I'm having an xml which i parse and get the data from between the nodes. However this data is surrounded by html tags. i create another xml and put this data in it. Now i have to get parse it again to get the proper html syntax.
Kindly help.
public class XMLfunctions {
public final static Document XMLfromString(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
System.out.println("XML parse error: " + e.getMessage());
return null;
} catch (SAXException e) {
System.out.println("Wrong XML file structure: " + e.getMessage());
return null;
} catch (IOException e) {
System.out.println("I/O exeption: " + e.getMessage());
return null;
}
return doc;
}
/** Returns element value
* #param elem element (it is XML tag)
* #return Element value otherwise empty String
*/
public final static String getElementValue( Node elem ) {
Node kid;
if( elem != null){
if (elem.hasChildNodes()){
for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
if( kid.getNodeType() == Node.TEXT_NODE ){
return kid.getNodeValue();
}
}
}
}
return "";
}
/*Start Parsing Body */
public static String getBodyXML(String id){
String line = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://192.168.1.44:9090/solr/core0/select/?q=content_id:"+id+"&version=2.2&start=0&rows=10&indent=on");
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
line = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
} catch (MalformedURLException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
} catch (IOException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
}
String st= ParseXMLBodyNode(line,"doc");
return st;
}
public static String ParseXMLBodyNode(String str,String node){
String xmlRecords = str;
String results = "";
String[] result = new String [1];
StringBuffer sb = new StringBuffer();
StringBuffer text = new StringBuffer();
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlRecords));
Document doc = db.parse(is);
NodeList indiatimes1 = doc.getElementsByTagName(node);
sb.append("<results count=");
sb.append("\"1\"");
sb.append(">\r\n");
for (int i = 0; i < indiatimes1.getLength(); i++) {
Node node1 = indiatimes1.item(i);
if (node1.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node1;
NodeList nodelist = element.getElementsByTagName("str");
Element element1 = (Element) nodelist.item(0);
NodeList title = element1.getChildNodes();
title.getLength();
for(int j=0; j<title.getLength();j++){
text.append(title.item(j).getNodeValue());
}
System.out.print((title.item(0)).getNodeValue());
sb.append("<result>");
sb.append("<news>");
String tmpText = html2text(text.toString());
//sb.append("<![CDATA[<body>");
sb.append(tmpText);
//sb.append("</body>]]>");
sb.append("</news>");
sb.append("</result>\r\n");
result[i] = title.item(0).getNodeValue();
}
}
sb.append("</results>");
} catch (Exception e) {
System.out.println("Exception........"+results );
e.printStackTrace();
}
return sb.toString();
}
public static String html2text(String html) {
String pText = Jsoup.clean(html, Whitelist.basic());
return pText;
}
My class which inititates the process
public class NewsDetails extends ListActivity{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
/*}
#Override
protected void onStart() {*/
super.onStart();
Intent myIntent = getIntent();
String id = myIntent.getStringExtra("content_id");
String title = myIntent.getStringExtra("title");
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
String xml = XMLfunctions.getBodyXML(id);
Document doc = XMLfunctions.XMLfromString(xml);
int numResults = XMLfunctions.numResults(doc);
if((numResults <= 0)){
Toast.makeText(NewsDetails.this, "No Result Found", Toast.LENGTH_LONG).show();
finish();
}
NodeList nodes = doc.getElementsByTagName("result");
for (int i = 0; i < nodes.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("title", title);
Element e = (Element)nodes.item(i);
map.put("news", XMLfunctions.getValue(e, "news"));
mylist.add(map);
}
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.list_item, new String[] { "title", "news" }, new int[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
}
Sample xml which i get after converting from jsoup
<results count="1">
<result>
<news>
<ul><li><p>as part of its growth plan,</p></li><li><p>in a bid to achieve the target</p></li><li><p>it is pointed out that most of ccl's production came from opencast mines and only 2 mt from underground (ug) mines. ccl is now trying to increase the share underground production. the board of ccl has, thus, approved the introduction of continuous mine in chiru ug at a cost of about rs 145 crore to raise this mine's production from 2 mt to 8 mt per annum.</p></li><li><p>mr ritolia said that.</p></li></ul>
</news>
</result>
</results>
I want to extract the content between the news tags. This xml is fed to XMLfromString(String xml) function in XMLFunctions class which then returns only "<" and rest of the body is left.
I'm not able to get the body with html tags to provide formatting.
One option is to use XML CDATA section as:
<result>
<news><![CDATA[
<ul><li><p>as part of its growth plan,</p></li><li><p>in a bid to achieve the target</p></li><li><p>it is pointed out that most of ccl's production came from opencast mines and only 2 mt from underground (ug) mines. ccl is now trying to increase the share underground production. the board of ccl has, thus, approved the introduction of continuous mine in chiru ug at a cost of about rs 145 crore to raise this mine's production from 2 mt to 8 mt per annum.</p></li><li><p>mr ritolia said that.</p></li></ul>
]]>
</news>
</result>
</results>
Then your parser will not treat HTML tags as XML and allow you access to raw content of the element. The other option is to encode the HTML tags i.e. convert all < into <, > into >, & into & etc. For more on encoding see here