Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

org.xml.sax.SAXParseException: Premature end of file for *VALID* XML

People also ask

What does Premature end of file mean?

Premature end of file indicates your XML file was not complete, since your are using URL connection here, I suspect network issues. Best way to solve this issue is to capture this XML file using wireshark or TCP monitor kind of tools and then check if it is complete. – NiranjanBhat.

What is SAXParseException in Java?

public class SAXParseException extends SAXException. Encapsulate an XML parse error or warning. This module, both source code and documentation, is in the Public Domain, and comes with NO WARRANTY.


It is a problem with Java InputStream. When the stream is read once the file offset position counter is moved to the end of file. On the subsequent read by using the same stream you'll get this error. So you have to close and reopen the stream again or call inputStream.reset() to reset the offset counter to its initial position.


This is resolved. The problem was elsewhere. Another code in cron job was truncating XML to 0 length file. I have taken care of that.


This exception only happens if you are parsing an empty String/empty byte array.

below is a snippet on how to reproduce it:

String xml = ""; // <-- deliberately an empty string.
ByteArrayInputStream xmlStream = new java.io.ByteArrayInputStream(xml.getBytes());
Unmarshaller u = JAXBContext.newInstance(...)
u.setSchema(...);
u.unmarshal( xmlStream ); // <-- here it will fail

Please make sure that you are not consuming your inputstream anywhere before parsing. Sample code is following: the respose below is httpresponse(i.e. response) and main content is contain inside StringEntity (i.e. getEntity())in form of inputStream(i.e. getContent()).

InputStream rescontent = response.getEntity().getContent();
tsResponse=(TsResponse) transformer.convertFromXMLToObject(rescontent );

If input stream is not closed properly then this exception may happen. make sure : If inputstream used is not used "Before" in some way then where you are intended to read. i.e if read 2nd time from same input stream in single operation then 2nd call will get this exception. Also make sure to close input stream in finally block or something like that.