Tuesday, July 12, 2005

Java Xml and schemas growing paings

I've just spent the morning stumped on a problem I had working before. I was trying to validate an Xml doc against a schema but kept getting the following.

Exception in thread "main" java.lang.ClassCastException
at org.apache.xerces.impl.xs.XMLSchemaLoader.processExternalHints(XMLSchemaLoader.java:567)
at org.apache.xerces.impl.xs.XMLSchemaValidator.reset(XMLSchemaValidator.java:1345)
at org.apache.xerces.parsers.BasicParserConfiguration.reset(BasicParserConfiguration.java:543)
at org.apache.xerces.parsers.DTDConfiguration.reset(DTDConfiguration.java:640)
at org.apache.xerces.parsers.DTDConfiguration.parse(DTDConfiguration.java:512)
at org.apache.xerces.parsers.DTDConfiguration.parse(DTDConfiguration.java:595)
at org.apache.xerces.parsers.XMLParser.parse(XMLParser.java:152)
at org.apache.xerces.parsers.DOMParser.parse(DOMParser.java:253)
at Utils.validate(Utils.java:70)
at XmlTest.main(XmlTest.java:29)

Some investigation on the internet turned up some red herrings

  • Problem with new version of xerces. I tried older version same problem

  • Problem with JDOM. (this is the api I normally use since it is far more intuitive than the basic jaxp or xerces classes). Re doing it in pure xerces didn't help.

  • Bug in xerces.

In the end (as is often the case) I took a break from it, and I had a hunch over lunch.

The problem is jdk 1.4. It includes some xml classes by default, and you need to override these to get xerces to work correctly.

This is done with the java.endorsed.dirs
property. Set this to be the dir where your xerces is stored and Voilia it works.


C:\dev\sandbox>java -Djava.endorsed.dirs=\apps\xerces-1_4_3\ -cp classes;\apps\xerces-1_4_3\xerces.jar XmlTest

Check out this article on Endorsed Dirs

Just be careful as well. By default <java-home>\lib\endorsed is the deafult endorsed dir and this may override it. This probably works (I'm just too lazy to bother testing it).

C:\dev\sandbox>java -Djava.endorsed.dirs=\apps\xerces-1_4_3\;%JAVA_HOME%\lib\endorsed -cp classes;\apps\xerces-1_4_3\xerces.jar XmlTest

Alternatively copy all such jars into the default endorsed dir \lib\endorsed.

Hopefully now by putting this up here, maybe I can save someone else a frustrating half day.

Let me know if I do.

No comments: