Unable to catch SAXParseException - java

Hi I am using jena to read som rdf file:
InputStream in = FileManager.get().open(adress);
model.read(in, adress);
problem in second row which throw sometimes SAXParseException:
org.xml.sax.SAXParseException: Element or attribute do not match QName production: QName::=(NCName':')?NCName.
com.hp.hpl.jena.shared.JenaException: org.xml.sax.SAXParseException: Element or attribute do not match QName production: QName::=(NCName':')?NCName.
at com.hp.hpl.jena.rdf.model.impl.RDFDefaultErrorHandler.fatalError(RDFDefaultErrorHandler.java:45)
at com.hp.hpl.jena.rdf.arp.impl.ARPSaxErrorHandler.fatalError(ARPSaxErrorHandler.java:35)
at com.hp.hpl.jena.rdf.arp.impl.XMLHandler.warning(XMLHandler.java:225)
at com.hp.hpl.jena.rdf.arp.impl.XMLHandler.fatalError(XMLHandler.java:255)
at org.apache.xerces.util.ErrorHandlerWrapper.fatalError(Unknown Source)
at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
at org.apache.xerces.impl.XMLEntityScanner.scanQName(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanStartElement(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at org.apache.xerces.parsers.DTDConfiguration.parse(Unknown Source)
at org.apache.xerces.parsers.DTDConfiguration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
at com.hp.hpl.jena.rdf.arp.impl.RDFXMLParser.parse(RDFXMLParser.java:142)
at com.hp.hpl.jena.rdf.arp.JenaReader.read(JenaReader.java:158)
at com.hp.hpl.jena.rdf.arp.JenaReader.read(JenaReader.java:145)
at com.hp.hpl.jena.rdf.arp.JenaReader.read(JenaReader.java:215)
at com.hp.hpl.jena.rdf.model.impl.ModelCom.read(ModelCom.java:197)
so I want to do some try catch block. The problem is when I do this, compiler return:
exception org.xml.sax.SAXParseException is never thrown in body of
corresponding try statement
So how I can chatch this exception ? I know that I can catch just Exception but then I cannot be sure where the problem occurs

SAXParserException is a "checked-exception" meaning that the method signature is forced to declare it, if it throws. Obviously, the method you call does not declare it, so you cannot catch it.
It looks like Jena is actually wrapping that exception in an "unchecked-exception" (ie, an exception that extends RuntimeException). This exception is actually JenaException. So you could add a try/catch for a JenaException and then use getCause() to find the original error encoutered by Jena.

You should catch JenaException instead of the SAXParseException. And then try to get the cause that might be the SAXParseException.

If you are looking to handle problems with your RDF XML input, there is a more direct way using the error handler interface to the Jena reader.

Related

Catching Exceptions in lambda expressions

I have the simplest code using Files.walk:
Stream<Path> stream = Files.walk(Paths.get("C:\\"));
stream.forEach(f -> {
System.out.println(f);
});
This code throws
Exception in thread "main" java.io.UncheckedIOException: java.nio.file.AccessDeniedException: C:\Documents and Settings
at java.nio.file.FileTreeIterator.fetchNextIfNeeded(Unknown Source)
at java.nio.file.FileTreeIterator.hasNext(Unknown Source)
at java.util.Iterator.forEachRemaining(Unknown Source)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining (Unknown Source)
at java.util.stream.AbstractPipeline.copyInto(Unknown Source)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown
at java.util.stream.ForEachOps$ForEachOp.evaluateSequential (Unknown Source)
at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(Unknown Source)
at java.util.stream.AbstractPipeline.evaluate(Unknown Source)
at java.util.stream.ReferencePipeline.forEach(Unknown Source)
at devl.test.FindDuplicates.main(FindDuplicates.java:53)
Caused by: java.nio.file.AccessDeniedException: C:\Documents and Settings
at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsDirectoryStream.<init>(Unknown Source)
at sun.nio.fs.WindowsFileSystemProvider.newDirectoryStream (Unknown Source)
at java.nio.file.Files.newDirectoryStream(Unknown Source)
at java.nio.file.FileTreeWalker.visit(Unknown Source)
at java.nio.file.FileTreeWalker.next(Unknown Source)
... 11 more
And the stacktrace points to stream.forEach(f -> {. Adding a try/catch before the code makes it to stop reading the files when the exception is thrown.
The thing is - I want the code to continue reading different files on drive C even though the exception is thrown.
It seems like somehow adding a try/catch inside the foreach would solve it - how do I do it (a try/catch on f -> {, not the System.out.println(f);)?
Please note that I tried to circumvent this by doing
Stream<Path> s = stream.filter(f -> !f.toFile().getAbsolutePath().contains("Documents and Setting"));
s.forEach(f -> {
But the same exception is thrown (even doing stream.filter(f -> false) fails).
EDIT: Please note that I don't want to re-throw an exception (like I was suggested). So using s.forEach(LambdaExceptionUtil.rethrowConsumer(System.out::println)) still fails with the exact stacktrace.
To ignore errors during recursive directory traversal you need to use walkFileTree with a FileVisitor that does error handling.
The stream based convenience wrappers (walk) simply terminate on the first error they encounter, you can't prevent that.
If the listing of directories is what you're after, then why not use DirectoryStreamPaths instead? See the doc here for more: https://docs.oracle.com/javase/7/docs/api/java/nio/file/DirectoryStream.html
Furthere you can use it in conjuction with Java8 and what's more the exception handling is quite good.

Servlet threw load() exception

I know this error has been posted before but I can't understand the stack trace and would love somebodies help.
Basically when I enter the application the getValue("client") is null:
HttpSession validuser = request.getSession();
if (validuser.getValue("client") == null) {
response.sendRedirect("/profile/factfind/includes/session_timeout.jsp");
}
And I'm thinking it's something to do with the following error:
2013-01-09 13:14:35 NamingContextListener[/Tomcat-Standalone/localhost/profile]: Creating JNDI naming context
2013-01-09 13:14:35 StandardManager[/profile]: Seeding random number generator class java.security.SecureRandom
2013-01-09 13:14:35 StandardManager[/profile]: Seeding of random number generator has been completed
2013-01-09 13:14:35 StandardContext[/profile]: Posting standard context attributes
2013-01-09 13:14:35 StandardContext[/profile]: Configuring application event listeners
2013-01-09 13:14:35 StandardContext[/profile]: Sending application start events
2013-01-09 13:14:35 StandardContext[/profile]: Starting filters
2013-01-09 13:14:35 StandardContext[/profile]: Starting completed
2013-01-09 13:14:37 StandardContext[/profile]: Servlet /profile threw load() exception
org.apache.jasper.JasperException: Unable to compile class for JSP
An error occurred at line: -1 in the jsp file: null
Generated servlet error:
[javac] Compiling 1 source file
at org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:85)
at org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:248)
at org.apache.jasper.compiler.Compiler.generateClass(Compiler.java:343)
at org.apache.jasper.compiler.Compiler.compile(Compiler.java:356)
at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:427)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:142)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:240)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:187)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:720)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:888)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:768)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:3484)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:3710)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:777)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:760)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:538)
at org.apache.catalina.core.StandardHostDeployer.addChild(StandardHostDeployer.java:667)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.commons.beanutils.MethodUtils.invokeMethod(MethodUtils.java:216)
at org.apache.commons.digester.SetNextRule.end(SetNextRule.java:217)
at org.apache.commons.digester.Rule.end(Rule.java:253)
at org.apache.commons.digester.Digester.endElement(Digester.java:1222)
at org.apache.xerces.parsers.AbstractSAXParser.endElement(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanEndElement(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.DTDConfiguration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
at org.apache.commons.digester.Digester.parse(Digester.java:1765)
at org.apache.catalina.core.StandardHostDeployer.install(StandardHostDeployer.java:343)
at org.apache.catalina.core.StandardHost.install(StandardHost.java:762)
at org.apache.catalina.startup.HostConfig.deployDescriptors(HostConfig.java:443)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:377)
at org.apache.catalina.startup.HostConfig.start(HostConfig.java:808)
at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:335)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:120)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1156)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:697)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1148)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:311)
at org.apache.catalina.core.StandardService.start(StandardService.java:450)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:2213)
at org.apache.catalina.startup.Catalina.start(Catalina.java:484)
at org.apache.catalina.startup.Catalina.execute(Catalina.java:371)
at org.apache.catalina.startup.Catalina.process(Catalina.java:134)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:151)
The session exists in a different application that then loads "profile" so I'm not too sure what happens when one launches the other.
Any help would be much appreciated. Thanks.
Turns out the fix for me was the same as some forums had suggested. I create a new Tomcat installation in a directory with no spaces (i.e C:\Tomcat4.1) and that worked.
Don't know why or how but it did.
I think that's a problem
org.apache.jasper.JasperException: Unable to compile class for JSP
An error occurred at line: -1 in the jsp file: null
Cleanup your project (or manually remove all .class files) then try to compile from scratch. If error gone - check it should work. If not - you should apparently get this first error gone.
It seems getValue(String) method is deprecated. so try the following code null == validuser.getAttribute(String)

Are multiple calls to java SaxParser.parse(String, Handler) Legal?

I have a java SAX parser which I would like to call multiple times on the same Handler with different XML files. I am using this in conjunction with iText to create a multi-page PDF document where some pages have one XML tag map and other pages have another. For example,
parser.parse("xmlFile1", handler);
parser.parse("xmlFile2", handler);
When I try to do this, I get a java.lang.RuntimeException thrown with the following stacktrace:
DocumentException: java.lang.RuntimeException: The document is not open.
at com.lowagie.text.pdf.PdfWriter.getDirectContent(PdfWriter.java:695)
at com.lowagie.text.pdf.PdfDocument.newPage(Unknown Source)
at com.lowagie.text.pdf.PdfDocument.carriageReturn(Unknown Source)
at com.lowagie.text.pdf.PdfDocument.add(Unknown Source)
at com.lowagie.text.Document.add(Unknown Source)
at myClass.myCode(Unknown Source)
org.apache.xerces.parsers.AbstractSAXParser.endElement(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanEndElement(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
at javax.xml.parsers.SAXParser.parse(SAXParser.java:345)
at javax.xml.parsers.SAXParser.parse(SAXParser.java:223)
at myClass.myCode(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:324)
Does the SaxParser.parse method implicitly call document.close()? Or is there some other problem in my code which I need to isolate and correct?
Reusing the same parser is legal (as long as it is not used concurrently)
The parser triggers an "endDocument". This seems to close the iText document here.. But this is not done by the parser - this is code from your handler.

Axis 1.4 AxisFault Premature end of file

I get this error when I use my autogenerated ServiceBindingStub.java. WebService side is working ok, so this error must be in code, but code is autogenerated, so I cannot know why it doesn't work. Some other calls work fine, but this doesn't. This call included updating, while other working calls are just fetching data from WebService.
AxisFault
faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.userException
faultSubcode:
faultString: org.xml.sax.SAXParseException: Premature end of file.
faultActor:
faultNode:
faultDetail:
{http://xml.apache.org/axis/}stackTrace:org.xml.sax.SAXParseException: Premature end of file.
at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
at org.apache.xerces.util.ErrorHandlerWrapper.fatalError(Unknown Source)
at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)
at org.apache.xerces.impl.XMLVersionDetector.determineDocVersion(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
at javax.xml.parsers.SAXParser.parse(Unknown Source)
at org.apache.axis.encoding.DeserializationContext.parse(DeserializationContext.java:227)
at org.apache.axis.SOAPPart.getAsSOAPEnvelope(SOAPPart.java:696)
at org.apache.axis.Message.getSOAPEnvelope(Message.java:435)
at org.apache.axis.handlers.soap.MustUnderstandChecker.invoke(MustUnderstandChecker.java:62)
at org.apache.axis.client.AxisClient.invoke(AxisClient.java:206)
at org.apache.axis.client.Call.invokeEngine(Call.java:2784)
at org.apache.axis.client.Call.invoke(Call.java:2767)
at org.apache.axis.client.Call.invoke(Call.java:2443)
at org.apache.axis.client.Call.invoke(Call.java:2366)
at org.apache.axis.client.Call.invoke(Call.java:1812)
This happens when service you are connecting to does not return SOAP response, but some text or HTML. Try opening the URL in the browser or use some SOAP debugger like SOAP UI to see what is returned from the service.
I once had the same problem. In my case, I received messages with 'binary data' between tags (imagery). Axis used a fixed size buffer to read the data, once the buffer was full it just proceeded and ran out of sync.
In fact, you should be able to find the tag or part in the xml file by debugging the stub code step by step. No guarantee, that the issue will can be solved easily but it might give you a hint that the (a) stub is not generated correctly or (b) the xml file is just not well-formed or valid against the schema that has been used to generate the stub.
Good luck! (I didn't solve my issue..)
I just had (and solved) this problem, following Superfilin's answer. In the end, the problem turned out to be that I hadn't added a <beanMapping> for one of the classes I was returning in my deployment.wsdd file. Any time the response would have included that class, I'd get a completely empty message body instead.
Even we have faced the same issue. But there are some special characters in the content. We removed those special characters and it worked fine.

UnknownHostException while redirecting queries to google and getting results in JSon object

Loading classifier from D:\PROJECT\classifiers\NERDemo\classifiers\ner-eng-ie.crf-3-all2008.ser.gz ... done [2.0 sec].
Original Query was riot in India.
Parsing Queries and expanding tokens from the Ontologies..
{locations=[India], events=[riot]}
Search query is null
Something went wrong...
java.net.UnknownHostException: ajax.googleapis.com
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at org.girs2.SearchHandler.makeQuery(SearchHandler.java:35)
at org.girs2.GIRS.search(GIRS.java:37)
at org.girs2.GIRS.main(GIRS.java:62)
Exception in thread "main" java.lang.NullPointerException
at org.girs2.GIRS.search(GIRS.java:44)
at org.girs2.GIRS.main(GIRS.java:62)
Looks like you probably have or had a DNS lookup failure. This tells you what happened:
java.net.UnknownHostException: ajax.googleapis.com
If you always get this exception and you can otherwise access this host by name, then I don't know what this could be, but odds are that this was a temporary DNS failure.
What should you do when you get this Exception? Well, if the address is one that you fully expect you should be able to get to -- such as this one -- then when you catch the Exception, you sleep for a while (perhaps 10 or 15 seconds, maybe even 30 or 60 seconds, depending on your application's needs) and try again.
If after several retries -- don't just retry forever! -- you still cannot reach the site, then log a reasonable complaint or otherwise complain that you cannot reach the site and have your application exit.
There's not much you can do when DNS fails except give up or wait and try again.

Categories