Tuesday, 24 January 2017

Solution for secure-processing org.xml.sax.SAXNotRecognizedException causing java.lang.IllegalStateException running inside Tomcat



Xerces impl is the main culprit here. Remove it. Jdk has inbuilt jaxb parser, you don't need this.

so, if that dependency is coming from a parent project in case of maven use a exclusion tab in case you can't directly remove it.

     <exclusion>
            <groupId>xerces</groupId> 
            <artifactId>xercesImpl</artifactId>
     </exclusion>

The reason this problem is so hard to detect is because, when you usually write a jaxb unmarshalling code

you will do a unmarshalling on a try block and then catch jaxb exception and then do whatever with the error.

But this culprit parser of a jar (xercesimpl) throws a runtime exception in the middle causing error to not get logged and will be only be detected after careful debugging. Look at the code snippet below

try {
JAXBContext context = JAXBContext.newInstance(YourClass.class);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            YourClass object = (YourClass)unmarshaller.unmarshal(new StringReader("SomeXmlInString"));


}

catch (JAXBException e){
e.printStackTrace();

}

Here xercesImpl causes the unmarshaller to use some other sax parser (instead of the regular jaxb parser) causing it to throw different exception which won't be caught in our catch block which is expecting a jaxbexception or one of its subclasses.