Woodstox stax and java stax conflict - java

I'm facing a weird runtime conflict between Woodstox STAX and java 1.6 STAX implementation. Since I'm using CXF,its pulling Woodstox jar as part of its dependency. Here's a sample code I'm using.
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
XMLInputFactory factory = (XMLInputFactory)XMLInputFactory.newInstance();
XMLEventReader reader =
factory.createXMLEventReader(new StringReader(xml));
while (reader.hasNext()){
XMLEvent event = reader.nextEvent();
switch (event.getEventType()){
case XMLEvent.START_ELEMENT :
StartElement se = event.asStartElement();
...........
...........
case XMLEvent.END_ELEMENT :
EndElement endElement = event.asEndElement();
if (event.asEndElement().getName().getLocalPart()==("document"))
// do something
During runtime, I'm getting the following exception.
java.lang.Exception: java.lang.ClassCastException: com.ctc.wstx.evt.CompactStartElement cannot be cast to javax.xml.stream.events.EndElement
when it reaches line EndElement endElement = event.asEndElement();
I'm sort of puzzled why its causing at this point though it doesn't fail in
StartElement se = event.asStartElement();
While debugging, I found that the event objects are part of com.ctc.wstx.evt package and not javax.xml.stream. But not sure why its not failing before.
Any pointer will be highly appreciated.

Well, you have two possible choices from a superficial view:
Use a dependency exclusion to turn off Woodstox. CXF works with the built-in StaX -- give or take the various bugs in the built-in Stax.
Use Woodstox yourself.
However, the specific error here is a bit unlikely. I mostly recommend posting this to the cxf users list, and telling us there exactly what version of CXF you are using.

Looking at the exception, it says basically that one can not cast StartElement to EndElement; it does not seem like an incompatibility between stax implementations but rather a bug somewhere. Which Woodstox version is this?

A break at the end of XMLEvent.START_ELEMENT case should not be missing here otherwise it will just going to continue to the END_ELEMENT case with the first START_ELEMENT event, hence the ClassCastException.
That part of the code have been omitted from the question so I thought I would put this here just in case this simple error might have been overlooked. It's how I got the same exception that led me here anyway when I realised I needed a break ;)

Related

Owl2Java Code generation issue

I'm using the owl2java plugin to generate Java code from an Ontology file. But I'm always getting de same error.
Exception in thread "main" com.hp.hpl.jena.ontology.ConversionException: Cannot convert node http://www.w3.org/2002/07/owl#bottomObjectProperty to TransitiveProperty
at com.hp.hpl.jena.ontology.impl.TransitivePropertyImpl$1.wrap(TransitivePropertyImpl.java:66)
at com.hp.hpl.jena.enhanced.EnhNode.convertTo(EnhNode.java:142)
at com.hp.hpl.jena.enhanced.EnhNode.convertTo(EnhNode.java:22)
at com.hp.hpl.jena.enhanced.Polymorphic.asInternal(Polymorphic.java:54)
at com.hp.hpl.jena.enhanced.EnhNode.viewAs(EnhNode.java:92)
at com.hp.hpl.jena.enhanced.EnhGraph.getNodeAs(EnhGraph.java:135)
at com.hp.hpl.jena.ontology.impl.OntModelImpl$SubjectNodeAs.map1(OntModelImpl.java:3040)
at com.hp.hpl.jena.ontology.impl.OntModelImpl$SubjectNodeAs.map1(OntModelImpl.java:3033)
at com.hp.hpl.jena.util.iterator.Map1Iterator.next(Map1Iterator.java:35)
at com.hp.hpl.jena.util.iterator.WrappedIterator.next(WrappedIterator.java:68)
at com.hp.hpl.jena.util.iterator.UniqueExtendedIterator.nextIfNew(UniqueExtendedIterator.java:61)
at com.hp.hpl.jena.util.iterator.UniqueExtendedIterator.hasNext(UniqueExtendedIterator.java:69)
at com.hp.hpl.jena.util.iterator.NiceIterator.asList(NiceIterator.java:185)
at com.hp.hpl.jena.util.iterator.NiceIterator.toList(NiceIterator.java:159)
at de.incunabulum.owl2java.core.generator.OwlReader.handleProperties(OwlReader.java:862)
at de.incunabulum.owl2java.core.generator.OwlReader.generateJModel(OwlReader.java:457)
at de.incunabulum.owl2java.core.JenaGenerator.generate(JenaGenerator.java:65)
at onto.main.main(main.java:99)
I have no idea about what I'm doing wrong. Any Ideas?
Thanks you a lot.
I looked at the top line on your exception, and see com.hp.hpl.jena.ontology.impl.TransitivePropertyImpl.
Googling for that leads to a version of the source code. It may not be exactly the same version as you're using, but is probably close enough to be informative. Reading the code leads to these questions:
Does your Model have a profile? It must.
Does the profile support Transitivity? It must.
Are you combining Transitive with something else that it's incompatible with?

Why doesn't printStackTrace work in Clojure?

In both the Joy of Clojure and on Alex Miller's Pure Danger Tech blog-post it is recommended that you can print the last stack using something like the following:
(use 'clojure.stacktrace)
(java.util.Date. "foo")
(.printStackTrace *e 5)
But I can't get any of their examples to work, and instead just get
java.lang.NullPointerException: null
Reflector.java:26 clojure.lang.Reflector.invokeInstanceMethod
(Unknown Source) jtown$eval9755.invoke
What's up with this? .printStackTrace seems to be a Java function from the looks of it, so I am not sure why I am bringing clojure.stacktrace into my namespace, in the first place. I read through the clojure.stacktrace API, though, and see an e function, which seems similar too but is not the *e function, which is in core and is supposed to be binding to the last exception, but isn't. Could somebody straighten me out on the best way to check stack-traces?
There are some special vars available when using the REPL and
*e - holds the result of the last exception.
For instance:
core=> (java.util.Date. "foo")
IllegalArgumentException java.util.Date.parse (Date.java:615)
core=> (class *e)
java.lang.IllegalArgumentException
core=> (.printStackTrace *e)
java.lang.IllegalArgumentException
at java.util.Date.parse(Date.java:615)
<not included.....>
You are right, .printStackTrace is the java method that is invoked on the exception class. This is not very straightforward (since its java interop) so clojure.stacktrace namespace has some utilities about working with stack traces
So after
(use 'clojure.stacktrace)
you can use the stacktrace library instead of java interop:
core=> (print-stack-trace *e)
java.lang.IllegalArgumentException: null
at java.util.Date.parse (Date.java:615)
<not included.....>
Obviously in an app, instead of *e, you can do a try - catch and use the related functions as necessary
I use
(.printStackTrace *e *out*)
That seems to work.

Mysterious ANTLR error

All I know is that it's stopping antlr from generating, I apologize. Here's the log file:
(10): internal error: /Bridge/bridge.g : java.lang.IllegalStateException: java.lang.NullPointerException
org.deved.antlride.runtime.AntlrErrorListener$DynamicToken.invokeMethod(AntlrErrorListener.java:59)
org.deved.antlride.runtime.AntlrErrorListener$DynamicToken.getLine(AntlrErrorListener.java:64)
org.deved.antlride.runtime.AntlrErrorListener.report(AntlrErrorListener.java:131)
org.deved.antlride.runtime.AntlrErrorListener.message(AntlrErrorListener.java:115)
org.deved.antlride.runtime.AntlrErrorListener.warning(AntlrErrorListener.java:99)
org.antlr.tool.ErrorManager.grammarWarning(ErrorManager.java:742)
org.antlr.tool.ErrorManager.grammarWarning(ErrorManager.java:757) org.antlr.tool.Grammar.parseAndBuildAST(Grammar.java:655)
org.antlr.Tool.getRootGrammar(Tool.java:626) org.antlr.Tool.process(Tool.java:459)
org.deved.antlride.runtime.Tool2.main(Tool2.java:24)
I got the same error with a simple grammar for logical formulas. For me the problem was, that ANTLR could not find an obvious start rule because I had a recursion on my intended start rule. Adding a new rule pointing to the recursive one did the job (see http://thesoftwarelife.blogspot.com/2008/07/antlr-frustrations.html).
It's a pity that ANTLR IDE does not correctly forward the error message. On the command line i get:
warning(138): Formula.g:0:1: grammar Formula: no start rule (no rule can obviously be followed by EOF)
I had the same problem yesterday. Not sure if my case is identical to yours but it worth a try. I had a rule named annotation like this:
annotation
: AT class declaration?
-> ^(ANNOTATION class declaration?)
;
And I wanted to parse sub annotations in curly braces so I did:
subAnnotation:
: CURLY_START annotation CURLY_END
-> ^(ANNOTATION annotation)
;
This was given me the same error has yours. So, I end up wondering with it is not working. Even if I'm unsure, I think the problem is the recursion of the annotation rule that was causing the error. So, I ended up doing this:
annotationValue:
: CURLY_START subAnnotation CURLY_END
-> ^(ANNOTATION subAnnotation)
;
subAnnotation
: AT class declaration?
-> ^(ANNOTATION class declaration?)
;
This resolved my problem. Like I said, I don't know if this fix can be applied to your problem. Moreover, I thought that ANTLR was able to deal with non-left-recursive rule. Maybe someone with a better knowledge of the tool could confirm it.
I must admit I did not try the suggestion of #BartKiers, maybe it would also solve the problem.
Regards,
Matt

Error while trying to validate XML in Java

I'm trying to validate one xml that I create with a local schema, but some freak error is throwing. My code:
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(true);
factory.setNamespaceAware(true);
SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
factory.setSchema(schemaFactory.newSchema(
new Source[] {new StreamSource("\\.\\schema\\xsd_me_ene_diaria.xsd")}));
And my stack trace is the follow.
java.lang.UnsupportedOperationException: This parser does not support specification "null" version "null"
at javax.xml.parsers.SAXParserFactory.setSchema(Unknown Source)
at SaxValidacao.validateSchema(SaxValidacao.java:36)
The error throws just after setSchema is called.
Some clue or another tip for XML validation in Java?
One thing that sometimes happens is mixing of different versions of the parser. If you use java 5 or higher, try removing references to any external xalan or xerces libraries. (All you need to process xml is included in the standard distribution of java 5)
I found a solution in a CodeWall article, add one line Java code to your codebase.
System.setProperty("javax.xml.parsers.SAXParserFactory","com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl");
Please refer to get more detail: https://coderwall.com/p/kqsrrw/jdom2-this-parser-does-not-support-specification-null-version-null
Can you turn off validation and parse the stream? If yes, it's not likely to be a JAR conflict.
I'm thinking that your issue is access to the schema.
A possible issue is that your JAXP parser is very old and doesn't support setSchema method. Look at the javadoc for SAXParsesrFactory. For setSchema (and many other methods), it says:
Throws:
java.lang.UnsupportedOperationException
- For backward compatibility, when implementations for earlier versions
of JAXP is used, this exception will
be thrown.
Check the parser implementation that you are using and try updating to a newer version.

Problem validating against an XSD with Java5

I'm trying to validate an Atom feed with Java 5 (JRE 1.5.0 update 11). The code I have works without problem in Java 6, but fails when running in Java 5 with a
org.xml.sax.SAXParseException: src-resolve: Cannot resolve the name 'xml:base' to a(n) 'attribute declaration' component.
I think I remember reading something about the version of Xerces bundled with Java 5 having some problems with some schemas, but i cant find the workaround. Is it a known problem ? Do I have some error in my code ?
public static void validate() throws SAXException, IOException {
List<Source> schemas = new ArrayList<Source>();
schemas.add(new StreamSource(AtomValidator.class.getResourceAsStream("/atom.xsd")));
schemas.add(new StreamSource(AtomValidator.class.getResourceAsStream("/dc.xsd")));
// Lookup a factory for the W3C XML Schema language
SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
// Compile the schemas.
Schema schema = factory.newSchema(schemas.toArray(new Source[schemas.size()]));
Validator validator = schema.newValidator();
// load the file to validate
Source source = new StreamSource(AtomValidator.class.getResourceAsStream("/sample-feed.xml"));
// check the document
validator.validate(source);
}
Update : I tried the method below, but I still have the same problem if I use Xerces 2.9.0. I also tried adding xml.xsd to the list of schemas (as xml:base is defined in xml.xsd) but this time I have
Exception in thread "main" org.xml.sax.SAXParseException: schema_reference.4: Failed to read schema document 'null', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.
Update 2: I tried to configure a proxy with the VM arguments -Dhttp.proxyHost=<proxy.host.com> -Dhttp.proxyPort=8080 and now it works. I'll try to post a "real answer" from home.
and sorry, I cant reply as a comment : because of security reasons XHR is disabled from work ...
Indeed, people have been mentioning the Java 5 Sun provided SchemaFactory is giving troubles.
So: did you include Xerces in your project yourself?
After including Xerces, you need to ensure it is being used. If you like to hardcode it (well, as a minimal requirement you'd probably use some application properties file to enable and populate the following code):
String schemaFactoryProperty =
"javax.xml.validation.SchemaFactory:" + XMLConstants.W3C_XML_SCHEMA_NS_URI;
System.setProperty(schemaFactoryProperty,
"org.apache.xerces.jaxp.validation.XMLSchemaFactory");
SchemaFactory factory =
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Or, if you don't want to hardcode, or when your troublesome code would be in some 3rd party library that you cannot change, set it on the java command line or environment options. For example (on one line of course):
set JAVA_OPTS =
"-Djavax.xml.validation.SchemaFactory:http://www.w3.org/2001/XMLSchema
=org.apache.xerces.jaxp.validation.XMLSchemaFactory"
By the way: apart from the Sun included SchemaFactory implementation giving trouble (something like com.sun.org.apache.xerces.internal.jaxp.validation.xs.schemaFactoryImpl), it also seems that the "discovery" of non-JDK implementations fails in that version. If I understand correctly than, normally, just including Xerces would in fact make SchemaFactory#newInstance find that included library, and give it precedence over the Sun implementation. To my knowledge, that fails as well in Java 5, making the above configuration required.
I tried to configure a proxy with the VM arguments -Dhttp.proxyHost=<proxy.host.com> -Dhttp.proxyPort=8080 and now it works.
Ah, I didn't realize that xml.xsd is in fact the one referenced as http://www.w3.org/2001/xml.xsd or something like that. That should teach us to always show some XML and XSD fragments as well. ;-)
So, am I correct to assume that 1.) to fix the Java 5 issue, you still needed to include Xerces and set the system property, and that 2.) you did not have xml.xsd available locally?
Before you found your solution, did you happen to try using getResource rather than getResourceAsStream, to see if the exception would then have showed you some more details?
If you actually did have xml.xsd available (so: if getResource did in fact yield a URL) then I wonder what Xerces was trying to fetch from the internet then. Or maybe you did not add that schema to the list prior to adding your own schemas? The order is important: dependencies must be added first.
For whoever gets tot his question using the search: maybe using a custom EntityResolver could have indicated the source of the problem as well (if only writing something to the log and just returning null to tell Xerces to use the default behavior).
Hmmm, just read your "comment" -- editing does not alert people for new replies, so time to ask your boss for some iPhone or some other gadget that is connected to the net directly ;-)
Well, I assume you added:
schemas.add(
new StreamSource(AtomValidator.class.getResourceAsStream("/xml.xsd")));
If so, is xml.xsd actually to be found on the classpath then? I wonder if the getResourceAsStream did not yield null in your case, and how new StreamSource(null) would act then.
Even if getResourceAsStream did not yield null, the resulting StreamSource would still not know where it was loaded from, which may be a problem when trying to include references. So, what if you use the constructor StreamSource(String systemId) instead:
schemas.add(new StreamSource(AtomValidator.class.getResource("/atom.xsd")));
schemas.add(new StreamSource(AtomValidator.class.getResource("/dc.xsd")));
You might also use StreamSource(InputStream inputStream, String systemId), but I don't see any advantage over the above two lines. However, the documentation explains why passing the systemId in either of the 2 constructors seems good:
This constructor allows the systemID to be set in addition to the input stream, which allows relative URIs to be processed.
Likewise, setSystemId(String systemId) explains a bit:
The system identifier is optional if there is a byte stream or a character stream, but it is still useful to provide one, since the application can use it to resolve relative URIs and can include it in error messages and warnings (the parser will attempt to open a connection to the URI only if there is no byte stream or character stream specified).
If this doesn't work out, then maybe some custom error handler can give you more details:
ErrorHandlerImpl errorHandler = new ErrorHandlerImpl();
validator.setErrorHandler(errorHandler);
:
:
validator.validate(source);
if(errorHandler.hasErrors()){
LOG.error(errorHandler.getMessages());
throw new [..];
}
if(errorHandler.hasWarnings()){
LOG.warn(errorHandler.getMessages());
}
...using the following ErrorHandler to capture the validation errors and continue parsing as far as possible:
import org.xml.sax.helpers.DefaultHandler;
private class ErrorHandlerImpl extends DefaultHandler{
private String messages = "";
private boolean validationError = false;
private boolean validationWarning = false;
public void error(SAXParseException exception) throws SAXException{
messages += "Error: " + exception.getMessage() + "\n";
validationError = true;
}
public void fatalError(SAXParseException exception) throws SAXException{
messages += "Fatal: " + exception.getMessage();
validationError = true;
}
public void warning(SAXParseException exception) throws SAXException{
messages += "Warn: " + exception.getMessage();
validationWarning = true;
}
public boolean hasErrors(){
return validationError;
}
public boolean hasWarnings(){
return validationWarning;
}
public String getMessages(){
return messages;
}
}

Categories

Resources