Java: Error marshalling or unmarshalling data: null - java

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

Related

How can I compile a Java class stored in a string, or using it's path with a given input?

I'm trying to make my own pretty print for java files, similar to JDoodle. How can I compile a java class, given either it's location as a string, or its content as a string, as well as do it given a text file for std inputs, all the while recording the output as a seperate string. Sorry if this seems troublesome. Any help is appreciated!
EDIT: I do know about the java.tools.ToolProvider and Tool, but even if it is the solution, I don't know what to do with it, as the documentation is too confusing for me, or too sparse.
OK, I got an answer. I used Eclipse's compiler(cause I dont have JDK in my school laptop) to compile and used processbuilder to run the produced .class file, redirected the output using redirectOutput to a file which I read to get the output. Thanks- Here is the code.
/*PRETTYPRINT*/
/*
* Code to HTML
* Uses highlightjs in order to create a html form for your code, you can also give inputs and outputs
* */
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
public class PrettyPrint {
public static void main(String[] args) throws FileNotFoundException{
String javaFile = readFile(args[0]);
String commandLine = readFile(args[1]);
String output = readFile(args[2]);
String html = "<!DOCTYPE html>\n"
+"<html>\n"
+"<head>"
+"<link rel=\"stylesheet\" href=\"highlightjs/styles/a11y-dark.css\" media= \"all\">\r\n"
+"<script src=\"highlightjs/highlight.pack.js\"></script>\r\n"
+"<script>hljs.initHighlightingOnLoad();</script>"
+"<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.debug.js\" integrity=\"sha384-NaWTHo/8YCBYJ59830LTz/P4aQZK1sS0SneOgAvhsIl3zBu8r9RevNg5lHCHAuQ/\" crossorigin=\"anonymous\"></script>\r\n"
+"<script src=\"https://cdn.jsdelivr.net/npm/html2canvas#1.0.0-rc.5/dist/html2canvas.min.js\"></script>"
+"<meta charset=\"utf-8\">"
+"<style>code{overflow-x: visible;}body{background-color:#888888;color:#444444;}h1{text-align:center;color:#444444;}</style>"
+"</head>"
+"<body style=\"font-family: 'Consolas';\">\n"
+"<h1 style=\"text-align: center\">Java Code</h1>"
+"<pre><code class=\"java\" style=\"overflow-x:visible\">"
+toHTML(javaFile)
+"</code></pre>"
+"<br>\n"
+"<h1>Inputs</h1>"
+"<pre><code class = \"nohighlight hljs\" style=\"overflow-x:visible\">"
+toHTML(commandLine)
+"</code></pre>"
+"<br>\n"
+"<h1>Output</h1>"
+"<pre><code class = \"nohighlight hljs\" style=\"overflow-x:visible\">"
+toHTML(output)
+"</code></pre>"
+"</body>\n"
+"<script>"
+"console.log(document.body.innerHTML);"
//+String.format("function print(){const filename='%s';html2canvas(document.body).then(canvas=>{let pdf = new jsPDF('p','mm', 'a4');pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, 1000, 1000);pdf.save(filename);});}print();",args[3].substring(args[3].lastIndexOf('/')+1, args[3].length()-4)+"pdf")
+ "</script>"
+"</html>\n";
//System.out.println(html);
try {
File file = new File("output.html");
PrintWriter fileWriter = new PrintWriter(file);
fileWriter.print(html);
fileWriter.close();
} catch(IOException e) {
e.printStackTrace();
}
}
public static String toHTML(String str) {
String html = str;
html = html.replace("&","&");
html = html.replace("\"", """);
html = html.replace("\'", "&apos;");
html = html.replace("<", "<");
html = html.replace(">", ">");
//html = html.replace("\n", "<br>");
html = html.replace("\t", "  ");
html+= "<br>";
return html;
}
public static String readFile(String filePath)
{
String content = "";
try
{
content = new String ( Files.readAllBytes( Paths.get(filePath) ) );
}
catch (IOException e)
{
e.printStackTrace();
}
return content;
}
}
/**PROCESSBUILDEREXAMPLE**/
import java.io.*;
import org.eclipse.jdt.core.compiler.CompilationProgress;
import org.eclipse.jdt.core.compiler.batch.BatchCompiler;
public class ProcessBuilderExample {
private static String JAVA_FILE_LOCATION;
public static void main(String args[]) throws IOException{
JAVA_FILE_LOCATION = args[0];
CompilationProgress progress = null;
BatchCompiler.compile(String.format("-classpath rt.jar %s",args[0]), new PrintWriter(System.out), new PrintWriter(System.err), progress);
Process process = new ProcessBuilder("java", "-cp",
JAVA_FILE_LOCATION.substring(0,JAVA_FILE_LOCATION.lastIndexOf("\\")),
JAVA_FILE_LOCATION.substring(JAVA_FILE_LOCATION.lastIndexOf("\\")+1,JAVA_FILE_LOCATION.length()-5))
.redirectInput(new File(args[1]))
.redirectOutput(new File(args[2])).start();
try {
process.waitFor();
PrettyPrint.main(args);
} catch(Exception e) {
e.printStackTrace();
}
}
}
Keep these 2 in the same folder and run processbuilderexample with 3 arguments. The code's loc, the input file's loc, and the output file to write to.

Reading XSD from URL using Java

Objective : I want to read a WSDL and print the services in the WSDL, complex types and Complex type definitions.
Worked : I've used WSDL4J for reading WSDL and successfully able to print the services and their parameters (complex types). Now I want to read the complex type definitions which is available in XSD. I'm unable to read XSD .Is ther any way to do it ?
I'm getting XSModel as null
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import javax.wsdl.BindingOperation;
import javax.wsdl.Definition;
import javax.wsdl.WSDLException;
import javax.wsdl.xml.WSDLReader;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import com.ibm.wsdl.BindingImpl;
import com.ibm.wsdl.xml.WSDLReaderImpl;
import com.sun.org.apache.xerces.internal.impl.xs.XSImplementationImpl;
import com.sun.org.apache.xerces.internal.xs.XSLoader;
import com.sun.org.apache.xerces.internal.xs.XSModel;
public class WSDLDetails {
public static void main(String[] args) {
try {
String wsdlURL = "https://abc.xyz.com/webservice/MessagingSevice?WSDL";
String xsdURL = "https://abc.xyz.com/webservice/MessagingSevice?xsd=1";
java.lang.System.setProperty("https.protocols", "TLSv1.2");
getAllBindingOperation(wsdlURL);
readXSD(xsdURL);
} catch (Exception e) {
e.printStackTrace();
}
}
public static List<String> getAllBindingOperation(String wsdlUrl) {
List<BindingOperation> operationList = new ArrayList();
List<String> nameList = new ArrayList();
try {
WSDLReader reader = new WSDLReaderImpl();
reader.setFeature("javax.wsdl.verbose", false);
Definition definition = reader.readWSDL(wsdlUrl.toString());
Map<String, BindingImpl> defMap = definition.getAllBindings();
Collection<BindingImpl> collection = defMap.values();
for (BindingImpl binding : collection) {
operationList.addAll(binding.getBindingOperations());
}
for (BindingOperation operation:operationList) {
nameList.add(operation.getName());
System.out.println("Name :: " + operation.getName());
System.out.println("Request :: " + operation.getBindingInput());
System.out.println("Response :: " + operation.getBindingOutput());
}
} catch (WSDLException e) {
System.out.println("get wsdl operation fail.");
e.printStackTrace();
}
return nameList;
}
public static void readXSD(String xsdURL) {
try {
System.setProperty(DOMImplementationRegistry.PROPERTY, "com.sun.org.apache.xerces.internal.dom.DOMXSImplementationSourceImpl");
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
com.sun.org.apache.xerces.internal.impl.xs.XSImplementationImpl impl = (XSImplementationImpl) registry.getDOMImplementation("XS-Loader");
XSLoader schemaLoader = impl.createXSLoader(null);
XSModel model = schemaLoader.loadURI(xsdURL);
System.out.println(model);
} catch (Exception e) {
e.printStackTrace();
}
}
You can use xsd2java plugin with maven
https://github.com/qaware/xsd2java-gradle-plugin
Here is an example showing how to retrieve the XSModel from an XSD URL, and print the complex types declared therein.
import org.apache.xerces.impl.xs.XMLSchemaLoader;
import org.apache.xerces.impl.xs.XSComplexTypeDecl;
import org.apache.xerces.impl.xs.XSElementDecl;
import org.apache.xerces.xs.XSConstants;
import org.apache.xerces.xs.XSModel;
import org.apache.xerces.xs.XSNamedMap;
import org.apache.xerces.xs.XSTypeDefinition;
public class Test {
public static void main(String[] args) {
try {
String xsdURL = "http://fsharp.github.io/FSharp.Data/data/po.xsd";
XMLSchemaLoader xsLoader = new XMLSchemaLoader();
XSModel xsModel = xsLoader.loadURI(xsdURL);
// print global element declarations
System.out.println("\nGlobal Element Declarations:");
XSNamedMap globalElemDecls = xsModel.getComponents(XSConstants.ELEMENT_DECLARATION);
globalElemDecls.forEach((k,v) -> System.out.println((XSElementDecl) v));
// print global complex type declarations
System.out.println("\nGlobal Complex Type Declarations:");
XSNamedMap globalComplexTypeDecls = xsModel.getComponents(XSTypeDefinition.COMPLEX_TYPE);
globalComplexTypeDecls.forEach((k,v) -> System.out.println((XSComplexTypeDecl) v));
} catch (Exception e) {
e.printStackTrace();
}
}
}
If you got null at xsLoader.loadURI(xsdURL), it is likely there are some flaws in the given XSD file. For example, "White spaces are required between publicId and systemId". You might need to fix these flaws first.

I am not able to update ontology model

I have made an Ontologu in Protege and imported in Eclipse.My ontology already 10 instances and i want to add more instances.The following piece of code adds instances to existing class (Noun) of ontology. After excecution it do not update ontology model and shows same number of instances.
public static void main(String[] args) throws OWLException, IOException{
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
File file = new File("D:\\word.owl");{
OntModel model=ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM_RULE_INF);
System.out.println("Model is called successfully");
OWLOntology ont = manager.loadOntologyFromOntologyDocument(file);
System.out.println("Loaded ontology: " + ont);
String SOURCE = ("D:\\word.owl");
String NS = SOURCE;
OntModel base = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM_RULE_INF);
base.read( SOURCE, "" );
OntModel inf =ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM_RULE_INF, base );
OntClass Noun = base.getOntClass( NS + "Noun" );
Individual jack = base.createIndividual( NS + "Jack", Noun );
Individual Helley = base.createIndividual( NS + "Helley", Noun );
manager.saveOntology(ont);
System.out.println("Number of individuals: " + ont.getIndividualsInSignature().size());
}
}
}
Output
Model is called successfully
Loaded ontology:
Number of individuals: 10
I dont use that API but I can see your issue.
At the start of your code you create an OWLOntology object:
OWLOntology ont = manager.loadOntologyFromOntologyDocument(file);
And here is the issue, you do not alter ont anywhere in your code, so when you call the line below, it will only show/save the same 10 individuals that you loaded from file at the beginning of your code:
manager.saveOntology(ont);
System.out.println("Number of individuals: " + ont.getIndividualsInSignature().size());
So to fix this you need to somehow modify ont to include the new Individual before using the above lines.
This works:
import java.io.FileWriter;
import java.io.InputStream;
import org.apache.jena.ontology.Individual;
import org.apache.jena.ontology.OntClass;
import org.apache.jena.ontology.OntModel;
import org.apache.jena.ontology.OntModelSpec;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.util.FileManager;
import org.apache.jena.vocabulary.RDF;
public class Mgt {
public static void main(String[] args) throws Exception {
String namespace = "http://www.semanticweb.org/Word#";
String file = "word.owl";
OntModel jenaModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM_RULE_INF);
InputStream in = FileManager.get().open(file);
jenaModel.read(in, null);
OntClass Noun = jenaModel.getOntClass(namespace + "Noun");
Individual Organization = Noun.createIndividual(namespace + "Organization");
jenaModel.add(Organization, RDF.type, Noun);
FileWriter out = new FileWriter("word.out.owl");
jenaModel.getWriter("RDF/XML-ABBREV").write(jenaModel, out, namespace);
out.close();
}
}
Note that namespace is not related to the file name.
Updated Code It gives Exception in thread "main" java.lang.NullPointerException
at Mgt.main(Mgt.java:29)
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import org.apache.jena.ontology.Individual;
import org.apache.jena.ontology.OntClass;
import org.apache.jena.ontology.OntModel;
import org.apache.jena.ontology.OntModelSpec;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.util.FileManager;
public class Mgt {
static OntModel jenaModel = null;
public static void main(String[] args) throws Exception{
String file =("D:\\word.owl");
jenaModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM_RULE_INF);
InputStream in = FileManager.get().open(file);
try
{
jenaModel.read(in, null);
}
catch (Exception e)
{
e.printStackTrace();
}
System.out.println("Ontology " + file + " loaded.");
OntClass Noun = jenaModel.getOntClass( "http://www.semanticweb.org/Word#Noun" );
Individual Organization = Noun.createIndividual(file + "Organization");
FileWriter out = null;
try {
// XML format - long and verbose
out = new FileWriter( file);
jenaModel.write( out, "RDF/XML" );
}
finally {
if (out != null) {
try {out.close();
} catch (IOException ignore) {}
}
}
}
}

can't predicted the class with Weka (using java code )

i'm trying my files test1.txt and test1.model with this code belwo, my class are {Business,Friends,Spam}
when the function classify() compile , it dose not predicted any class . i'm new with Weka so i have found that the type of the class is wrong , so i have tried other type but it cause the same output ans the classify() dose not compiled in the right way. can anyone please tell me what's the problem ?
the output show like this
run:
===== Loaded text data: D:\test\test1.txt =====
hello this is a test
===== Loaded model: D:\test\test1.model =====
===== Instance created with reference dataset =====
#relation 'Test relation'
#attribute class {Business,Friends,Spam}
#attribute text string
#data
?,' hello this is a test '
Problem found when classifying the text
BUILD SUCCESSFUL (total time: 2 seconds)
with this code
package sentimentclassifier;
import weka.core.*;
import weka.core.FastVector;
import weka.classifiers.meta.FilteredClassifier;
import java.util.List;
import java.util.ArrayList;
import java.io.*;
public class SentimentClassifier {
/**
String text;
/**
* Object that stores the instance.
*/
Instances instances;
/**
* Object that stores the classifier.
*/
FilteredClassifier classifier;
private String text;
/**
* This method loads the text to be classified.
* #param fileName The name of the file that stores the text.
*/
public void load(String fileName) {
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line;
text = "";
while ((line = reader.readLine()) != null) {
text = text + " " + line;
}
System.out.println("===== Loaded text data: " + fileName + " =====");
reader.close();
System.out.println(text);
}
catch (IOException e) {
System.out.println("Problem found when reading: " + fileName);
}
}
/**
* This method loads the model to be used as classifier.
* #param fileName The name of the file that stores the text.
*/
public void loadModel(String fileName) {
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(fileName));
Object tmp = in.readObject();
classifier = (FilteredClassifier) tmp;
in.close();
System.out.println("===== Loaded model: " + fileName + " =====");
}
catch (Exception e) {
// Given the cast, a ClassNotFoundException must be caught along with the IOException
System.out.println("Problem found when reading: " + fileName);
}
}
/**
* This method creates the instance to be classified, from the text that has been read.
*/
public void makeInstance() {
FastVector fvNominalVal = new FastVector(3);
fvNominalVal.addElement("Business");
fvNominalVal.addElement("Friends");
fvNominalVal.addElement("Spam");
Attribute attribute1 = new Attribute("class", fvNominalVal);
Attribute attribute2 = new Attribute("text",(FastVector) null);
//==========================================
// Create list of instances with one element
FastVector fvWekaAttributes = new FastVector(2);
fvWekaAttributes.addElement(attribute1);
fvWekaAttributes.addElement(attribute2);
instances = new Instances("Test relation", fvWekaAttributes, 1);
// Set class index
instances.setClassIndex(0);
// Create and add the instance
DenseInstance instance = new DenseInstance(2);
instance.setValue(attribute2, text);
// Another way to do it:
// instance.setValue((Attribute)fvWekaAttributes.elementAt(1), text);
instances.add(instance);
System.out.println("===== Instance created with reference dataset =====");
System.out.println(instances);
}
/**
* This method performs the classification of the instance.
* Output is done at the command-line.
*/
public void classify() {
try {
double pred = classifier.classifyInstance(instances.instance(2));
System.out.println("===== Classified instance =====");
System.out.println("Class predicted: " + instances.classAttribute().value((int) pred));
}
catch (Exception e) {
System.out.println("Problem found when classifying the text");
}
}
public static void main(String[] args) {
SentimentClassifier classifier;
classifier = new SentimentClassifier();
classifier.load("D:\\test\\test1.txt");
classifier.loadModel("D:\\test\\test1.model");
classifier.makeInstance();
classifier.classify();
}
}

XML is not completely spooled into file after marshalling

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.

Categories

Resources