javaxsltentityresolver

Java - xsl transformation -DTD as entity resolver Premature end of file


Java - spring - xsl transformation with dtd as entity resolver.

I have a following method

 private Source resolveDTDEntity(Reader input, final String dtdName) throws ParserConfigurationException, SAXException, IOException {

        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        docBuilderFactory.setValidating(false);
        docBuilderFactory.setNamespaceAware(true);

        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();

        //Satisfying dtd dependency
        docBuilder.setEntityResolver(new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
                if (systemId.contains(dtdName)) {
                    InputStream dtdStream = XslRdcSourceDocTransformer.class
                            .getResourceAsStream("/dtds/" + dtdName);
                    return new InputSource(dtdStream);
                } else {
                    return null;
                }
            }
        });

        //Exception on following line
        return new DOMSource(docBuilder.parse(new ReaderInputStream(input))); 
    }

I gets following exception

StackTrace: org.xml.sax.SAXParseException: Premature end of file.
        at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:239)
        at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:283)
        at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:124)
        at com.service.XslSourceDocTransformer.resolveDTDEntity(XslSourceDocTransformer.java:137)
        at com.service.XslSourceDocTransformer.transform(XslSourceDocTransformer.java:56)
        at com.service.ContentProcessor.process(ContentProcessor.java:127)
        at com.lexisnexis.job.LexisNexisJob.execute(LexisNexisJob.java:67)
        at com.core.job.JobController$JobExecutor.run(JobController.java:367)
        at com.core.job.JobController$JobThread.run(JobController.java:245)
        at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
        at java.lang.Thread.run(Thread.java:619)

Exception: Premature end of file

Solution

  • This error occured "tackTrace: org.xml.sax.SAXParseException: Premature end of file." cuz i was reading multiple xml files from disk and one of them was empty which cause of this error.

    i used following statement

    docBuilder.parse(new InputSource(reader))