Getting exception in dynamic jaxb - java

I am getting following exception , i need to create dynamic xml from xsd for which I am following the eclipse link documentation:
Exception in thread "main" java.util.ServiceConfigurationError: com.sun.tools.xjc.Plugin: Provider org.eclipse.persistence.jaxb.plugins.BeanValidationPlugin could not be instantiated
at java.util.ServiceLoader.fail(ServiceLoader.java:232)
at java.util.ServiceLoader.access$100(ServiceLoader.java:185)
at java.util.ServiceLoader$LazyIterator.nextService(ServiceLoader.java:384)
at java.util.ServiceLoader$LazyIterator.next(ServiceLoader.java:404)
at java.util.ServiceLoader$1.next(ServiceLoader.java:480)
at com.sun.tools.xjc.Options.findServices(Options.java:910)
at com.sun.tools.xjc.Options.getAllPlugins(Options.java:351)
at com.sun.tools.xjc.reader.AbstractExtensionBindingChecker.<init>(AbstractExtensionBindingChecker.java:94)
at com.sun.tools.xjc.reader.ExtensionBindingChecker.<init>(ExtensionBindingChecker.java:77)
at com.sun.tools.xjc.ModelLoader$XMLSchemaParser.parse(ModelLoader.java:257)
at com.sun.xml.xsom.impl.parser.NGCCRuntimeEx.parseEntity(NGCCRuntimeEx.java:337)
at com.sun.xml.xsom.impl.parser.ParserContext.parse(ParserContext.java:124)
at com.sun.xml.xsom.impl.parser.ParserContext.<init>(ParserContext.java:96)
at com.sun.xml.xsom.parser.XSOMParser.<init>(XSOMParser.java:125)
at com.sun.tools.xjc.ModelLoader.createXSOMParser(ModelLoader.java:420)
at com.sun.tools.xjc.ModelLoader.createXSOMParser(ModelLoader.java:428)
at com.sun.tools.xjc.ModelLoader.createXSOM(ModelLoader.java:509)
at com.sun.tools.xjc.api.impl.s2j.SchemaCompilerImpl.bind(SchemaCompilerImpl.java:236)
at com.sun.tools.xjc.api.impl.s2j.SchemaCompilerImpl.bind(SchemaCompilerImpl.java:85)
at org.eclipse.persistence.jaxb.dynamic.metadata.SchemaMetadata.getJavaModelInput(SchemaMetadata.java:155)
at org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext$SchemaContextInput.createContextState(DynamicJAXBContext.java:349)
at org.eclipse.persistence.jaxb.JAXBContext.<init>(JAXBContext.java:196)
at org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext.<init>(DynamicJAXBContext.java:84)
at org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContextFactory.createContextFromXSD(DynamicJAXBContextFactory.java:279)
at com.accenture.App.main(App.java:21)
Caused by: java.lang.NoClassDefFoundError: com/sun/tools/xjc/model/CPropertyVisitor2
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2671)
at java.lang.Class.getConstructor0(Class.java:3075)
at java.lang.Class.newInstance(Class.java:412)
at java.util.ServiceLoader$LazyIterator.nextService(ServiceLoader.java:380)
... 22 more
Caused by: java.lang.ClassNotFoundException: com.sun.tools.xjc.model.CPropertyVisitor2
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 27 more
My Main class code is :
package com.accenture;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import javax.xml.bind.JAXBException;
import org.eclipse.persistence.dynamic.DynamicEntity;
import org.eclipse.persistence.internal.oxm.Marshaller;
import org.eclipse.persistence.jaxb.JAXBContext;
import org.eclipse.persistence.jaxb.JAXBMarshaller;
import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContextFactory;
public class App {
public static void main(String[] args) throws JAXBException, FileNotFoundException {
System.out.println("Hello World!");
System.setProperty("com.sun.tools.xjc.api.impl.s2j.SchemaCompilerImpl.noCorrectnessCheck", "true");
FileInputStream xsdInputStream = new FileInputStream("src/main/java/com/accenture/customer.xsd");
DynamicJAXBContext jaxbContext = DynamicJAXBContextFactory.createContextFromXSD(xsdInputStream,
new MyEntityResolver(), null, null);
DynamicEntity customer = jaxbContext.newDynamicEntity("org.example.Customer");
customer.set("name", "Jane Doe");
DynamicEntity address = jaxbContext.newDynamicEntity("org.example.Address");
address.set("street", "1 Any Street").set("city", "Any Town");
customer.set("address", address);
JAXBMarshaller marshaller = jaxbContext.createMarshaller();
marshaller.marshal(customer, System.out);
}
}
Entity resolver code is :
package com.accenture;
import java.io.File;
import java.io.IOException;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
class MyEntityResolver implements EntityResolver {
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
// Imported schemas are located in ext\appdata\xsd\
// Grab only the filename part from the full path
String filename = new File(systemId).getName();
// Now prepend the correct path
String correctedId = "src/main/java/com/accenture/" + filename;
InputSource is = new InputSource(ClassLoader.getSystemResourceAsStream(correctedId));
is.setSystemId(correctedId);
return is;
}
}
My aim is to create an XML dynamically from referencing an XSD. Easiest way i found was eclipse link but it is giving me error, can someone please guide me how to correct this or any other simpler way to achieve this.
Thanks.

We need to add the following jars and it will work:
1. jaxb-core_2.2.11.v201407311112.jar
2. jaxb-xjc_2.2.11.v201407311112.jar

Related

error about jsoup_ java.lang.NoClassDefFoundError: org/jsoup/Jsoup

I'm trying a simple crawling with jsoup in eclipse.
I downloaded jsoup jar files(jsoup-1.13.1.jar, jsoup-1.13.1-javadoc.jar, jsoup-1.13.1-sources.jar) also added them in the java build path/libaries
But I get some error messages about jsoup...
Exception in thread "main" java.lang.NoClassDefFoundError: org/jsoup/Jsoup
at square.example.main(example.java:12)
Caused by: java.lang.ClassNotFoundException: org.jsoup.Jsoup
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:606)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:168)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
... 1 more
This is my code!
package square;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
public class example{
public static void main(String[] args) throws Exception{
String articleURL = "http://www.imaeil.com/sub_news/sub_news_view.php?news_id=20000&yy=2015";
Document doc = Jsoup.connect(articleURL).get(); //error!
Elements ele = doc.select("div#_article");
String str = ele.text();
System.out.println(str);
}
}
image

Getting error while trying to copy a picture in doc file

I am getting below error while trying to copy a pic in a do file through selenium.
This is the error which I am getting -
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlException
at LeadFreeTest.docCapture.main(docCapture.java:17)
Caused by: java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlException
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 1 more
Below is code
package LeadFreeTest;
import java.io.*;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class docCapture {
#SuppressWarnings("resource")
public static void main(String[] args) throws IOException, InvalidFormatException
{
XWPFDocument docx = new XWPFDocument();
XWPFParagraph par = docx.createParagraph();
XWPFRun run = par.createRun();
run.setText("Hello, World. This is my first java generated docx-file. Have fun.");
run.setFontSize(13);
InputStream pic = new FileInputStream("C:\\Naveeen\\TestScreenShot\\LoginPage.png");
//byte [] picbytes = IOUtils.toByteArray(pic);
//run.addPicture(picbytes, Document.PICTURE_TYPE_JPEG);
run.addPicture(pic, Document.PICTURE_TYPE_JPEG, "3", 0, 0);
FileOutputStream out = new FileOutputStream("C:\\Naveeen\\TestScreenShot\\LoginPage.doc");
docx.write(out);
out.close();
pic.close();
}
}
You need to add the XML beans dependency to your classpath hense the
ClassNotFoundException: org.apache.xmlbeans.XmlException
The library is usually called xmlbeans-x.x.x.jar
You can find it here.

EDI Must be a minimum of 1 instances of segment [UNS]

Am newbie to EDI. And i just converted the ORDERS edi file to XML using smooks api. Some of the ORDER example files are working fine in following example. But i got the following exception when i running the following edi file. Am stuck with this. Here is my example and EDI data
package example;
import org.json.JSONObject;
import org.json.XML;
import org.milyn.Smooks;
import org.milyn.SmooksException;
import org.milyn.io.StreamUtils;
import org.milyn.smooks.edi.unedifact.UNEdifactReaderConfigurator;
import org.xml.sax.SAXException;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.StringWriter;
public class Main {
public static int PRETTY_PRINT_INDENT_FACTOR = 4;
protected static String runSmooksTransform() throws IOException, SAXException, SmooksException {
Smooks smooks = new Smooks();
smooks.setReaderConfig(new UNEdifactReaderConfigurator("urn:org.milyn.edi.unedifact:d93a-mapping:*"));
try {
StringWriter writer = new StringWriter();
smooks.filterSource(new StreamSource(new FileInputStream("EDI.edi")), new StreamResult(writer));
return writer.toString();
} finally {
smooks.close();
}
}
public static void main(String[] args) throws IOException, SAXException, SmooksException {
System.out.println("\n\n==============Message In==============");
System.out.println(readInputMessage());
System.out.println("======================================\n");
String messageOut = Main.runSmooksTransform();
System.out.println("==============Message Out=============");
System.out.println(messageOut);
System.out.println("======================================\n\n");
JSONObject xmlJSONObj = XML.toJSONObject(messageOut);
String jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR);
System.out.println(jsonPrettyPrintString);
}
private static String readInputMessage() throws IOException {
return StreamUtils.readStreamAsString(new FileInputStream("EDI.edi"));
}
}
And the exception with Sample EDI Data
Exception in thread "main" org.milyn.SmooksException: Failed to filter source.
at org.milyn.delivery.sax.SmooksSAXFilter.doFilter(SmooksSAXFilter.java:97)
at org.milyn.delivery.sax.SmooksSAXFilter.doFilter(SmooksSAXFilter.java:64)
at org.milyn.Smooks._filter(Smooks.java:526)
at org.milyn.Smooks.filterSource(Smooks.java:482)
at org.milyn.Smooks.filterSource(Smooks.java:456)
at example.Main.runSmooksTransform(Main.java:49)
at example.Main.main(Main.java:63)
Caused by: org.milyn.edisax.EDIParseException: EDI message processing failed [ORDERS][D:93A:UN]. Must be a minimum of 1 instances of segment [UNS]. Currently at segment number 9.
at org.milyn.edisax.EDIParser.mapSegments(EDIParser.java:499)
at org.milyn.edisax.EDIParser.mapSegments(EDIParser.java:450)
at org.milyn.edisax.EDIParser.parse(EDIParser.java:426)
at org.milyn.edisax.EDIParser.parse(EDIParser.java:410)
at org.milyn.edisax.unedifact.handlers.UNHHandler.process(UNHHandler.java:97)
at org.milyn.edisax.unedifact.handlers.UNBHandler.process(UNBHandler.java:75)
at org.milyn.edisax.unedifact.UNEdifactInterchangeParser.parse(UNEdifactInterchangeParser.java:113)
at org.milyn.smooks.edi.unedifact.UNEdifactReader.parse(UNEdifactReader.java:75)
at org.milyn.delivery.sax.SAXParser.parse(SAXParser.java:76)
at org.milyn.delivery.sax.SmooksSAXFilter.doFilter(SmooksSAXFilter.java:86)
... 6 more
Bad source data will cause this.
It looks like smooks is looking for a UNS segment which isn't in your data. The section control is mandatory per the D.93A standard.

Tokenize Thai sentence with ICUTokenizer JAVA

I am trying the below code to get all the tokens fro the thai sentence.
It throws exception. Can anyone point me to tokenize thai in JAVA?
import org.apache.lucene.analysis.Analyzer.TokenStreamComponents;
import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.icu.ICUNormalizer2Filter;
import org.apache.lucene.analysis.icu.segmentation.ICUTokenizer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
public class Tokenizer{
public static void main(String[] args) throws IOException {
ICUTokenizer tokenizer = new ICUTokenizer(new StringReader("การที่ได้ต้องแสดงว่างานดี"));
TokenFilter filter = new ICUNormalizer2Filter(tokenizer);
TokenStreamComponents tt = new TokenStreamComponents(tokenizer, filter);
TokenStream ts = tt.getTokenStream();
CharTermAttribute cattr = ts.addAttribute(CharTermAttribute.class);
ts.reset();
while(ts.incrementToken()){
System.out.println(cattr.toString()+"-----");
}
}
}
Exception is as below
Exception in thread "main" java.lang.ExceptionInInitializerError
at org.apache.lucene.analysis.icu.segmentation.ICUTokenizer.<init>(ICUTokenizer.java:72)
at com.tokenizer.tt.main(tt.java:22)
Caused by: java.lang.RuntimeException: java.io.IOException: ICU data file error: Not an ICU data file
at org.apache.lucene.analysis.icu.segmentation.DefaultICUTokenizerConfig.readBreakIterator(DefaultICUTokenizerConfig.java:128)
at org.apache.lucene.analysis.icu.segmentation.DefaultICUTokenizerConfig.<clinit>(DefaultICUTokenizerConfig.java:66)
... 2 more
Caused by: java.io.IOException: ICU data file error: Not an ICU data file
at com.ibm.icu.impl.ICUBinary.readHeader(ICUBinary.java:577)
at com.ibm.icu.text.RBBIDataWrapper.get(RBBIDataWrapper.java:173)
at com.ibm.icu.text.RuleBasedBreakIterator.getInstanceFromCompiledRules(RuleBasedBreakIterator.java:71)
at org.apache.lucene.analysis.icu.segmentation.DefaultICUTokenizerConfig.readBreakIterator(DefaultICUTokenizerConfig.java:123)
... 3 more
Finally figured out how to use ICU4J in a java program
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import org.apache.lucene.analysis.icu.segmentation.ICUTokenizer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
public class icuEstes {
public static void main(String[] args) throws IOException {
Reader reader = new StringReader("การที่ได้ต้องแสดงว่างานดี This is a test ກວ່າດອກ");
ICUTokenizer icut = new ICUTokenizer();
icut.setReader(reader);
icut.addAttribute(CharTermAttribute.class);
icut.reset();
while (icut.incrementToken()) {
System.out.println(icut.toString());
System.out.println(icut.getAttribute(CharTermAttribute.class));
}
icut.close();
}}

Get value from nested tag for XML contain in string

I'm trying to read value from nested tag from an XML and having trouble with it.
My XML file called NewFile.xml I'm trying read the value in tag4.
<?xml version="1.0"?>
<tag1>
<tag2>
<tag3>
<tag4>read me</tag4>
</tag3>
</tag2>
</tag1>
Here is a main class called Test.java which reads that XML file and coverts it to string and sends it the the method called lookUpValue in reader class.
public class test {
public static void main(String [] args) throws IOException, XPathExpressionException
{
BufferedReader br = new BufferedReader(new FileReader(new File("NewFile.xml")));
String xmlString;
StringBuilder sb = new StringBuilder();
while((xmlString=br.readLine())!= null){
sb.append(xmlString.trim());
}
xmlString = sb.toString();
System.out.print(reader.LookUpValue(xmlString));
br.close();
}
}
Here is the reader class and the method LookupValue:
import java.io.StringReader;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.xml.sax.InputSource;
public class reader{
public static String LookUpValue(String sb) throws XPathExpressionException
{
InputSource source = new InputSource(new StringReader(sb));
XPath xpath = XPathFactory.newInstance().newXPath();
Object customer = xpath.evaluate("/tag1/tag2/tag3", source, XPathConstants.NODE);
String value = xpath.evaluate("tag4", customer);
return ("Value is: " + value);
}
}
My question is how can I read the value inside tag4 right now when I run this program I get the following error.
Exception in thread "main"
javax.xml.transform.TransformerException: Unable to evaluate expression using this context
at com.sun.org.apache.xpath.internal.XPath.execute(XPath.java:363)
at com.sun.org.apache.xpath.internal.jaxp.XPathImpl.eval(XPathImpl.java:213)
at com.sun.org.apache.xpath.internal.jaxp.XPathImpl.evaluate(XPathImpl.java:275)
at com.sun.org.apache.xpath.internal.jaxp.XPathImpl.evaluate(XPathImpl.java:365)
at reader.LookUpValue(LookUpValue.java:21)
at test.main(test.java:26)
Caused by: java.lang.RuntimeException: Unable to evaluate expression using this context
at com.sun.org.apache.xpath.internal.axes.NodeSequence.setRoot(NodeSequence.java:212)
at com.sun.org.apache.xpath.internal.axes.LocPathIterator.execute(LocPathIterator.java:210)
at com.sun.org.apache.xpath.internal.XPath.execute(XPath.java:335)
... 5 more
---------
java.lang.RuntimeException: Unable to evaluate expression using this context
at com.sun.org.apache.xpath.internal.axes.NodeSequence.setRoot(NodeSequence.java:212)
at com.sun.org.apache.xpath.internal.axes.LocPathIterator.execute(LocPathIterator.java:210)
at com.sun.org.apache.xpath.internal.XPath.execute(XPath.java:335)
at com.sun.org.apache.xpath.internal.jaxp.XPathImpl.eval(XPathImpl.java:213)
at com.sun.org.apache.xpath.internal.jaxp.XPathImpl.evaluate(XPathImpl.java:275)
at com.sun.org.apache.xpath.internal.jaxp.XPathImpl.evaluate(XPathImpl.java:365)
at reader.LookUpValue(LookUpValue.java:21)
at test.main(test.java:26)
--------------- linked to ------------------
javax.xml.xpath.XPathExpressionException
at com.sun.org.apache.xpath.internal.jaxp.XPathImpl.evaluate(XPathImpl.java:289)
at com.sun.org.apache.xpath.internal.jaxp.XPathImpl.evaluate(XPathImpl.java:365)
at reader.LookUpValue(LookUpValue.java:21)
at test.main(test.java:26)
Caused by: javax.xml.transform.TransformerException: Unable to evaluate expression using this context
at com.sun.org.apache.xpath.internal.XPath.execute(XPath.java:363)
at com.sun.org.apache.xpath.internal.jaxp.XPathImpl.eval(XPathImpl.java:213)
at com.sun.org.apache.xpath.internal.jaxp.XPathImpl.evaluate(XPathImpl.java:275)
... 3 more
Caused by: java.lang.RuntimeException: Unable to evaluate expression using this context
at com.sun.org.apache.xpath.internal.axes.NodeSequence.setRoot(NodeSequence.java:212)
at com.sun.org.apache.xpath.internal.axes.LocPathIterator.execute(LocPathIterator.java:210)
at com.sun.org.apache.xpath.internal.XPath.execute(XPath.java:335)
... 5 more
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
public class Reader {
public static String lookUpValues(String sb) throws Exception{
DocumentBuilder builder = DocumentBuilderFactory
.newInstance().newDocumentBuilder();
InputSource src = new InputSource();
src.setCharacterStream(new StringReader(sb));
Document doc = builder.parse(src);
String value = doc.getElementsByTagName("tag4").item(0).getTextContent();
return value;
}
}

Categories

Resources