Java JaxB Unmarshaller giving org.xml.sax.SAXParseException Premature end of file

private Course unmarshalCourse(InputStream is) throws CourseServiceException, IOException{
        Course c=null;
        try{
            JAXBContext jc = JAXBContext.newInstance( "com.sakai.domain" );
            Unmarshaller u = jc.createUnmarshaller();
            String theString = IOUtils.toString(is, "UTF-8"); 
            log.debug("---------xml"+theString);
            Object value = u.unmarshal(is);

            c=(Course)value;
            log.debug("---------course"+c);
        }catch(JAXBException e){
            //je.printStackTrace();
            throw new CourseServiceException(e, Error.CONFIG);
        }
        return c;
    }

Im getting input stream as a xml.when i try to unmarshal it following error is triggered.please help.

[org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Premature end of file.] com.course.logic.CourseServiceException: javax.xml.bind.UnmarshalException – with linked exception: [org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Premature end of file.]

Answer

The problem is caused by the way you use the InputStream is.

String theString = IOUtils.toString(is, "UTF-8"); 
log.debug("---------xml"+theString);
Object value = u.unmarshal(is);

First you consume all of the InputStream by reading it with IOUtils.toString(is, "UTF-8"). Of course, after that you are at end of stream. Then you try to continue reading from this stream by u.unmarshal(is). No surprise, you get an exception with Premature end of file now.

To fix this, do not unmarshal from InputStream is. but unmarshal from String theString:

String theString = IOUtils.toString(is, "UTF-8"); 
log.debug("---------xml"+theString);
Object value = u.unmarshal(new StringReader(theString));

Leave a Reply

Your email address will not be published. Required fields are marked *