I'm trying to marshall an object and replace some invarvalid char's after that. In this processes, the completed xml is not getting generated. I can only see 1024 chars in all the generated files.
package com.test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.util.Scanner;
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamResult;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.apache.log4j.Logger;
import org.xml.sax.SAXException;
import com.sun.xml.bind.marshaller.NamespacePrefixMapper;
public class MessageParserComponent {
private static final Logger LOGGER = Logger.getLogger(MessageParserComponent.class);
public File marshalIXml(final Object obj, final String xsdSchema,
final String xmlFileName, final JAXBContext ctx) {
File xml = new File(xmlFileName);
try {
xml.createNewFile();
Marshaller marshaller = null;
marshaller = ctx.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
Boolean.TRUE);
marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION,
"http://www.db.com/tf " + xsdSchema);
marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper",
new NamespacePrefixMapper() {
#Override
public String getPreferredPrefix(String arg0, String arg1,
boolean arg2) {
return "tf";
}
});
marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION,
"http://www.db.com/tf " + xsdSchema);
marshaller.setSchema(getSchema(xsdSchema));
marshaller.marshal(obj, new StreamResult(xml));
xml = replaceInvalidChar('\u0007', '\n', xml);
xml = replaceInvalidString("ns2", "xsi", xml);
} catch (IOException e) {
LOGGER.error(e);
} catch (JAXBException e) {
LOGGER.error(e);
} catch (SAXException e) {
LOGGER.error(e);
}
return xml;
}
private Schema getSchema(String xsdSchema) throws SAXException {
SchemaFactory fact = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = fact.newSchema(this.getClass().getClassLoader()
.getResource(xsdSchema));
return schema;
}
private static File replaceInvalidString(String Target, String Dest,
File Source) throws IOException {
String xml_string;
xml_string = new Scanner(Source).useDelimiter("\\Z").next();
xml_string = xml_string.replace(Target, Dest);
FileOutputStream fi = new FileOutputStream(Source);
fi.write(xml_string.getBytes());
return Source;
}
public static File replaceInvalidChar(char Target, char Dest, File Source)
throws IOException {
String xml_string;
xml_string = new Scanner(Source).useDelimiter("\\Z").next();
xml_string = xml_string.replace(Target, Dest);
FileOutputStream fi = new FileOutputStream(Source);
fi.write(xml_string.getBytes());
return Source;
}
}
Is there a limit for string replacement?
Am I creating the file in a wrong way?
Note:
I'm storing file in UNIX log folder
I have java 6, JAXB 2.2
Any sort of help is highly appreciated.
Just check whether you annotated your object with jaxb annotations correctly.
And why are you setting Marshaller properties? do you want to use external schema to marshall your object? instead why don't you let jaxb to take care of all those things (if your objects are available in same workspace).
This sample program may be helpful to you.
http://www.mkyong.com/java/jaxb-hello-world-example/
and check this on too..
JAXB Marshaller : StringWriter output has a truncated tag value
truncated-tag-value
When you open a FileOutputStream you are responsible for closing. You should change your code to include the close() call.
FileOutputStream fi = new FileOutputStream(Source);
fi.write(xml_string.getBytes());
fi.close();
The issue was with the scanner, which is trying to find the EOF and not spooling the entire file. This is not happening in local development environment. Where as in the UNIX server, where my application is deployed the "end of input" is different, which caused this issue.
File f1 = new File(path);
StringBuilder f2 = new StringBuilder();
Scanner scanner = new Scanner(f1).useDelimiter("\\Z");
while (scanner.hasNext()) {
f2.append(scanner.next());
This completed the trick.
I do not know about the performance part of the scanner (taking only 1024 chars)when compared to other Buttered readers.
Any other solution which improves performance is highly appriciated.
Related
I want to read the data from multiple XML files based on the XSD document and the structure of one XML file will not be the same as to another but will follow the xsd schema. Also, the xmls are nested xmls.Can someone help me with it so that I can use the already created utility and add the attributes to it? I need a XML parser which parses each xml file(They are different) based on the xsd schema and returns me a list of the map so that the data can be matched with the DB data.
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class Test {
public static void main(String[] args) {
Customer customer = new Customer();
try {
File file = new File("SalesPoslog20200225104558676.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(customer, file);
jaxbMarshaller.marshal(customer, System.out);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Customer {
int organizationID;
int retailStoreID;
int workstationID;
int tillID;
int sequenceNumber;
public int organizationID() {
return organizationID;
}
#XmlElement
public void RetailStoreID(int retailStoreID) {
this.retailStoreID = retailStoreID;
}
public int workstationID() {
return workstationID;
}
#XmlAttribute
public void RetailStoreId(int RetailStoreId) {
this.retailStoreID = retailStoreID;
}
}
I am trying to use a model that is built on java. Here is the model main class:
package madamira;
import edu.columbia.ccls.madamira.MADAMIRAWrapper;
import edu.columbia.ccls.madamira.configuration.MadamiraInput;
import edu.columbia.ccls.madamira.configuration.MadamiraOutput;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.File;
import java.util.concurrent.ExecutionException;
/**
* An example class that shows how MADAMIRA can be called through its API.
*
*/
public class madamira {
// MADAMIRA namespace as defined by its XML schema
private static final String MADAMIRA_NS = "edu.columbia.ccls.madamira.configuration";
private static final String INPUT_FILE = "~/Users/user/Desktop/comp_ling/ACL_arabic_parser/udpipe-master/src/MADAMIRA-release-20170403-2.1/padt_sents.xml";
private static final String OUTPUT_FILE = "~/Users/user/Desktop/comp_ling/ACL_arabic_parser/udpipe-master/src/MADAMIRA-release-20170403-2.1/sampleOutputFile.xml";
public static void main(String [] args) {
final MADAMIRAWrapper wrapper = new MADAMIRAWrapper();
JAXBContext jc = null;
try {
jc = JAXBContext.newInstance(MADAMIRA_NS);
Unmarshaller unmarshaller = jc.createUnmarshaller();
// The structure of the MadamiraInput object is exactly similar to the
// madamira_input element in the XML
final MadamiraInput input = (MadamiraInput)unmarshaller.unmarshal(
new File( INPUT_FILE ) );
{
int numSents = input.getInDoc().getInSeg().size();
String outputAnalysis = input.getMadamiraConfiguration().
getOverallVars().getOutputAnalyses();
String outputEncoding = input.getMadamiraConfiguration().
getOverallVars().getOutputEncoding();
System.out.println("processing " + numSents +
" sentences for analysis type = " + outputAnalysis +
" and output encoding = " + outputEncoding);
}
// The structure of the MadamiraOutput object is exactly similar to the
// madamira_output element in the XML
final MadamiraOutput output = wrapper.processString(input);
{
int numSents = output.getOutDoc().getOutSeg().size();
System.out.println("processed output contains "+numSents+" sentences...");
}
jc.createMarshaller().marshal(output, new File(OUTPUT_FILE));
} catch (JAXBException ex) {
System.out.println("Error marshalling or unmarshalling data: "
+ ex.getMessage());
} catch (InterruptedException ex) {
System.out.println("MADAMIRA thread interrupted: "
+ex.getMessage());
} catch (ExecutionException ex) {
System.out.println("Unable to retrieve result of task. " +
"MADAMIRA task may have been aborted: "+ex.getCause());
}
wrapper.shutdown();
}
}
I am getting this error:
Unable to read form brown file resources/paths in resources dir. resources/paths
Error marshalling or unmarshalling data: null
I am not sure what the problem is. could you guys help? I think the problem has to do with some missing or clashing dependencies.
By the way, I am using Java "11.0.2" 2019-01-15 LTS and running the model in eclipse.
thank you
I wrote following code to fetch the results in form of XML responses and write some of its content to the a file from Java. This is done by receiving an XML-response for about 700,000 queries to a public database.
However, before the code can write to the file, it is either stopped by some random exception (from the server) at a random position in code. I tried writing to the file from the For-loop itself, but was not able to. So I tried to store the chunks from received responses into Java HashMap and write the HashMap to the file in a single call. But before the code receives all the responses in the for-loop and stores them into a HashMap, it stops with some exception (maybe at the 15000th iteration!!). Is there any other efficient way to write to the file in Java when one requires such iterations to fetch the data?
The local file that I use for this code is here.
My code is,
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
public class random {
static FileWriter fileWriter;
static PrintWriter writer;
public static void main(String[] args) {
// Hashmap to store the MeSH values for each PMID
Map<String, String> universalMeSHMap = new HashMap<String, String>();
try {
// FileWriter for MeSH terms
fileWriter = new FileWriter("/home/user/eclipse-workspace/pmidtomeshConverter/src/main/resources/outputFiles/pmidMESH.txt", true);
writer = new PrintWriter(fileWriter);
// Read the PMIDS from this file
String filePath = "file_attached_to_Post.txt";
String line = null;
BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
String[] pmidsAll = null;
int x = 0;
try {
//print first 2 lines or all if file has less than 2 lines
while(((line = bufferedReader.readLine()) != null) && x < 1) {
pmidsAll = line.split(",");
x++;
}
}
finally {
bufferedReader.close();
}
// List of strings containing the PMIDs
List<String> pmidList = Arrays.asList(pmidsAll);
// Iterate through the list of PMIDs to fetch the XML files from PubMed using eUtilities API service from PubMed
for (int i = 0; i < pmidList.size(); i++) {
String baseURL = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&retmode=xml&rettype=abstract&id=";
// Process to get the PMIDs
String indPMID_p0 = pmidList.get(i).toString().replace("[", "");
String indPMID_p1 = indPMID_p0.replace("]", "");
String indPMID_p2 = indPMID_p1.replace("\\", "");
String indPMID_p3 = indPMID_p2.replace("\"", "");
// Fetch XML response from the eUtilities into a document object
Document doc = parseXML(new URL(baseURL + indPMID_p3));
// Convert the retrieved XMl into a Java String
String xmlString = xml2String(doc); // Converts xml from doc into a string
// Convert the Java String into a JSON Object
JSONObject jsonWithMeSH = XML.toJSONObject(xmlString); // Converts the xml-string into JSON
// -------------------------------------------------------------------
// Getting the MeSH terms from a JSON Object
// -------------------------------------------------------------------
JSONObject ind_MeSH = jsonWithMeSH.getJSONObject("PubmedArticleSet").getJSONObject("PubmedArticle").getJSONObject("MedlineCitation");
// List to store multiple MeSH types
List<String> list_MeSH = new ArrayList<String>();
if (ind_MeSH.has("MeshHeadingList")) {
for (int j = 0; j < ind_MeSH.getJSONObject("MeshHeadingList").getJSONArray("MeshHeading").length(); j++) {
list_MeSH.add(ind_MeSH.getJSONObject("MeshHeadingList").getJSONArray("MeshHeading").getJSONObject(j).getJSONObject("DescriptorName").get("content").toString());
}
} else {
list_MeSH.add("null");
}
universalMeSHMap.put(indPMID_p3, String.join("\t", list_MeSH));
writer.write(indPMID_p3 + ":" + String.join("\t", list_MeSH) + "\n");
System.out.println("Completed iteration for " + i + " PMID");
}
// Write to the file here
for (Map.Entry<String,String> entry : universalMeSHMap.entrySet()) {
writer.append(entry.getKey() + ":" + entry.getValue() + "\n");
}
System.out.print("Completed writing the file");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
writer.flush();
writer_pubtype.flush();
writer.close();
writer_pubtype.close();
}
}
private static String xml2String(Document doc) throws TransformerException {
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.METHOD, "xml");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", Integer.toString(2));
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc.getDocumentElement());
trans.transform(source, result);
String xmlString = sw.toString();
return xmlString;
}
private static Document parseXML(URL url) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse((url).openStream());
doc.getDocumentElement().normalize();
return doc;
}
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
}
This is what it prints on the Console before the exception.
Completed iteration for 0 PMID
Completed iteration for 1 PMID
Completed iteration for 2 PMID
Completed iteration for 3 PMID
Completed iteration for 4 PMID
Completed iteration for 5 PMID
And it writes until the below given exception appears...
So at any random point in the loop, I get the exception below.
java.io.FileNotFoundException: https://dtd.nlm.nih.gov/ncbi/pubmed/out/pubmed_190101.dtd
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1890)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:263)
at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(XMLEntityManager.java:647)
at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.startEntity(XMLEntityManager.java:1304)
at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.startDTDEntity(XMLEntityManager.java:1270)
at com.sun.org.apache.xerces.internal.impl.XMLDTDScannerImpl.setInputSource(XMLDTDScannerImpl.java:264)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$DTDDriver.dispatch(XMLDocumentScannerImpl.java:1161)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$DTDDriver.next(XMLDocumentScannerImpl.java:1045)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:959)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:602)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:505)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:842)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:771)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:243)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:339)
at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:121)
at pmidtomeshConverter.Convert2MeSH.parseXML(Convert2MeSH.java:240)
at pmidtomeshConverter.Convert2MeSH.main(Convert2MeSH.java:121)
You want your parser to ignore DTD when parsing them.
Use this feature :
dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
See Xerces documentation for other features.
There is no need to use a Map; just write directly to the file. For better performance use a BufferedWriter.
I would also check that there is no rate limit or anything of that nature on the server side (you can guess that from the error you're getting). Save the response in a separate file when parsing or downloading fails, that way you will be able to diagnose the issue better.
I would also invest some time into implementing a restart mechanism, such that you can restart the process from the last failed location instead of starting from the beginning every time. It can be as simple as providing a skip counter as input to skip the first N requests.
You should re-use the DocumentBuilderFactory so that it doesn't load the same DTD every time. Additionally you may want to disable DTD validation altogether (unless you want only valid documents, in which case it's good to catch that exception and dump the bad XML to a separate file for review).
private static DocumentBuilderFactory dbf;
public static void main(String[] args) {
dbf = DocumentBuilderFactory.newInstance();
dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
dbf.setFeature("http://xml.org/sax/features/validation", false);
...
}
private static Document parseXML(URL url) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse((url).openStream());
doc.getDocumentElement().normalize();
return doc;
}
I try to unmarshal a String using this code:
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAnyAttribute;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.namespace.QName;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.io.IOUtils;
import org.xml.sax.InputSource;
#XmlRootElement(name="Grid")
public class Marshal {
#XmlAttribute(name="Reload", required = false)
public int reload;
#XmlElementWrapper(name="Changes")
#XmlElement(name="I")
public List<XmlAttributeHolder> rowList = new ArrayList<XmlAttributeHolder>();
public static void main(String[] args) {
try {
JAXBContext jc = JAXBContext.newInstance(Marshal.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
// à€
String xmlString = "<Grid><IO/><Changes><I id=\"0\" Changed=\"1\" STT=\"à€\"/></Changes></Grid>";
InputStream inputStream = IOUtils.toInputStream(xmlString);
InputSource is = new InputSource(inputStream);
is.setEncoding("ISO-8859-1");
Marshal obj = (Marshal) unmarshaller.unmarshal(is);
System.out.println(xmlString);
for (int i=0;i<obj.rowList.size();i++) {
XmlAttributeHolder xah = obj.rowList.get(i);
System.out.println(xah.getAttrMap());
for (String formValue:xah.getAttrMap().values()) {
System.out.println(StringEscapeUtils.unescapeXml(formValue));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static class XmlAttributeHolder {
#XmlAnyAttribute
public Map<QName, String> attrMap = new HashMap<QName, String>();
public void addAttribute(String name, String value) {
attrMap.put(QName.valueOf(name), value);
}
public String getAttribute(String name) {
return attrMap.get(QName.valueOf(name));
}
public Map<QName, String> getAttrMap() {
return attrMap;
}
}
}
I try to run this code in Java 1.6 windows and gives the correct answer:
0
1
à€
When I try to run this code in IBM java 1.6 CentOS gives the wrong answer:
0
1
à €
Why the unmarshalling instruction doesn't convert correctly the à (even èéìòù...)?
If your input is actually a String I'd recommend passing that directly to the Unmarshaller, wrapped in a StringReader instead of trying to produce an InputStream from it. It's less error prone.
Try this (see code snippet below). Then you don't have to worry about whether your code specifies the correct encoding or does the character to byte conversion correctly for that encoding.
String xmlString = "<Grid><IO/><Changes><I id=\"0\" Changed=\"1\" STT=\"à€\"/></Changes></Grid>";
InputSource is = new InputSource(new StringReader(xmlString));
Marshal obj = (Marshal) unmarshaller.unmarshal(is);
I am trying to take the contents of an ArrayList and put them into an XML file. Does anyone have a quick,clean and easy solution to this rather that having to use streams and handle exceptions?
For more information, Here is the code I have currently I am getting problem with it, one of which its not creating the file.
package ie.wit.io;
import ie.wit.abs.Device;
import ie.wit.abs.Device;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
public class FileHandler
{
private FileOutputStream outByteStream;
private ObjectOutputStream OOStream;
private FileInputStream inByteStream;
private ObjectInputStream OIStream;
private File aFile;
public void setUpFile()
{
aFile = new File("data.xml");
}
public boolean isFileEmpty()
{
return (aFile.length() <= 0);
}
public void writeToFile(ArrayList<Device> team)
{
try
{
outByteStream = new FileOutputStream(aFile);
OOStream = new ObjectOutputStream(outByteStream);
OOStream.writeObject(team);
outByteStream.close();
OOStream.close();
}
catch(IOException e)
{
JOptionPane.showMessageDialog(null,"I/O Error" + e + "\nPlease Contact your Administrator :-)");
}
}
currentClass)
public ArrayList<Device> readFromFile()
{
ArrayList<Device> temp = null;
try
{
inByteStream = new FileInputStream(aFile);
OIStream = new ObjectInputStream(inByteStream);
if(!this.isFileEmpty())
temp = (ArrayList<Device>)OIStream.readObject();
inByteStream.close();
OIStream.close();
}
catch(IOException e)
{
JOptionPane.showMessageDialog(null,"I/O Error" + e + "\nPlease Contact your Administrator :-)");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,"General Error" + e + "\nPlease Contact your Administrator :-)");
}
return temp;
}
}
There are many libraries to do that task.
Here is what I'm doing so far. Edit as per your requirement.
protected String getDocmentsAsString(List<News> documentsListByIndex) {
if(documentsListByIndex.size()>0){
try {
XStream xstream = new XStream(new JsonHierarchicalStreamDriver());
xstream.setMode(XStream.NO_REFERENCES);
xstream.alias("news", News.class);
return xstream.toXML(documentsListByIndex);
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
Im using http://x-stream.github.io/json-tutorial.html
You can use a StringBuilder and generate the XML yourself.. It depends on how many items you want to convert. The fastest way is just pushing out the XML data using a StringBuilder.
I recommend to:
create a XSD
generate JAXB Java classes (e.g. using a Maven Plugin)
create instances of the JAXB Java classes and fill up the data
marshal the JAXB Java classes to XML