Java – Exception in thread “main” java.lang.NoClassDefFoundError: org/dom4j/io/SAXReader

dom4jjava

I am trying to compile and run the following class:

import org.dom4j.io.SAXReader;
import org.dom4j.Document;
import org.dom4j.Element;

import java.net.URL;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.util.List;

/**
 * Java client program to demonstrate how to access Hudson remote API.
 *
 * @author Kohsuke Kawaguchi
 * @see http://hudson.gotdns.com/wiki/display/HUDSON/Remote+access+API
 */
public class Main {
    @SuppressWarnings("unchecked")
    public static void main(String[] args) throws Exception {
        // every Hudson model object exposes the .../api/xml, but in this example
        // we'll just take the root object as an example
        URL url = new URL("http://deadlock.netbeans.org/hudson/api/xml");

        // if you are calling security-enabled Hudson and
        // need to invoke operations and APIs that are protected,
        // consult the 'SecuredMain" class
        // in this package for an example using HttpClient.

        // read it into DOM.
        Document dom = new SAXReader().read(url);

        // scan through the job list and print its status
        for( Element job : (List<Element>)dom.getRootElement().elements("job")) {
        //for( Element job : (java.util.List<org.dom4j.Element>)dom.getRootElement().elements("job")) {
            System.out.println(String.format("Name:%s\tStatus:%s",
                job.elementText("name"), job.elementText("color")));
        }
    }
}

I compile it using:

javac -cp /usr/share/java/dom4j.jar Main.java 

But when I am trying to run it, I get an exception:

$ java Main

Exception in thread "main" java.lang.NoClassDefFoundError:
org/dom4j/io/SAXReader at Main.main(Main.java:31) Caused by:
java.lang.ClassNotFoundException: org.dom4j.io.SAXReader at
java.net.URLClassLoader$1.run(URLClassLoader.java:202) at
java.security.AccessController.doPrivileged(Native Method) at
java.net.URLClassLoader.findClass(URLClassLoader.java:190) at
java.lang.ClassLoader.loadClass(ClassLoader.java:306) at
sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at
java.lang.ClassLoader.loadClass(ClassLoader.java:247) … 1 more

If I look at the jar file:

jar tvf /usr/share/java/dom4j.jar | grep SAXReader*

1061 Mon Jan 25 09:34:34 EST 2010
org/dom4j/io/SAXReader$SAXEntityResolver.class 13170 Mon Jan 25
09:34:34 EST 2010 org/dom4j/io/SAXReader.class

The 'missing' classes are present in the JAR. Any idea on how to resolve this?

Best Answer

You need to use the same class path while running as well

java -cp /usr/share/java/dom4j.jar;. Main
Related Topic