Tuesday, June 13, 2006

What version of xerces have I got?

xerces version print classpath parser

This is kind of related to the previous two posts. With XML parsing + classpath issues it's often useful to know not only what version of Xerces you're using but also where it's been loaded from.

This is based on the equivalently useful site of Java Almanac - Determining from Where a Class Was Loaded. The point they make about the system classloader is crucial: "It is not possible to determine the location of classes loaded by the system class loader in the same way since the class' code source is null."

If your Xerces is the one loaded by the system, then this may explain some unusual behaviour if your web application expects to ship with it's own version.

  public static String getXercesDetails() {
       // no hard-writed references to the version class because it might be unavailable
       Class c;
       Method m;
       Object obj;

       try {
           c = Class.forName("org.apache.xerces.impl.Version");
           m = c.getDeclaredMethod("getVersion", new Class[] {});
           if (Modifier.isStatic(m.getModifiers())) {
               // Xerces 2.x
               obj = null;
           } else {
               // Xerces 2.1.x
               obj = c.newInstance();
           ProtectionDomain pDomain = c.getProtectionDomain();
           CodeSource cSource = pDomain.getCodeSource();
           String loc = "?";
           if (cSource != null) {
               loc = cSource.getLocation().toString();
           } else {
               // CodeSource is null, Xerces loaded by system class loaded.
               loc = "(system classloader? sun.boot.class.path = " + System.getProperty("sun.boot.class.path") + ")";
           return ((String) m.invoke(obj, new Object[] {})) + " from " + loc;
       } catch (Exception e) {
           return "unkown (" + e.getMessage() + ")";

Xerces (and Xalan) in the endorsed directory can cause some nasty issues for applications that expect to use their own version. See the JBoss Issue: JBAS-2073

No comments: