URLClassLoader ClassNotFoundException

V

visionset

I'm loading Jars dynamically at runtime. I've got them and saved them
alongside the main one that's currently executing. I've obtained valid URLs
for them through Class.getResource(). I've created a new URLClassLoader
with those URLs. Now I try to do Class.forName with my new ClassLoader and I
get CNFEx. I thought this was supposed to be the way to effectively update
the classpath?
Class.forName("my.package.MyClass", true, myUrlClassLoader);

URLs are of this form

::file:/D:/workspace/foo/bar.jar

Any ideas what may be going on here?

TIA
 
A

Andreas Wollschlaeger

visionset said:
I'm loading Jars dynamically at runtime. I've got them and saved them
alongside the main one that's currently executing. I've obtained valid URLs
for them through Class.getResource(). I've created a new URLClassLoader
with those URLs. Now I try to do Class.forName with my new ClassLoader and I
get CNFEx. I thought this was supposed to be the way to effectively update
the classpath?
Class.forName("my.package.MyClass", true, myUrlClassLoader);

URLs are of this form

::file:/D:/workspace/foo/bar.jar

Any ideas what may be going on here?

TIA

One possible cause is that "my.package.MyClass" is known to your parent
(system) classloader, so this one is used to resolve the Class.forName()
call. Of course the remaining classes are unknown (because they are
known only by your URLClassLoader).
Is it "my.package.MyClass" that cannot be resolved or another, different
class? If "my.package.MyClass" can be resolved, you should try something
like

Class c = Class.forName("my.package.MyClass", true, myUrlClassLoader);
System.out.println(c.getClassLoader());

and compare with your other classloaders to see which one really loaded
your class!

HTH, otherwise post some stack trace here

Cheers
Andreas
 
V

visionset

....
One possible cause is that "my.package.MyClass" is known to your parent
(system) classloader, so this one is used to resolve the Class.forName()
call. Of course the remaining classes are unknown (because they are known
only by your URLClassLoader).
Is it "my.package.MyClass" that cannot be resolved

Thanks Andreas but yes, the forName call for that class throws the CNFEx

So it isn't being resolved by any accessible class loader.

The Jars are valid and work fine when accessed normally though the default
classloading
 
V

visionset

fails at forName() or loader.loadClass()

adding resource: jar:file:///myJar.jar!/
runMainApp() with loader: java.net.URLClassLoader@13f3045
java.lang.ClassNotFoundException: stitch.view.Run
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at stitch.run.Runner.runMainApp(Runner.java:50)
at stitch.run.Runner.main(Runner.java:24)

I've tried URLs in both jar: XXXX !/ and plain file: format
And tried to use a parent loader from various sources such as:
Thread.currentThread().getContextClassLoader()



TIA
 
A

Andreas Wollschlaeger

visionset said:
fails at forName() or loader.loadClass()

adding resource: jar:file:///myJar.jar!/
runMainApp() with loader: java.net.URLClassLoader@13f3045
java.lang.ClassNotFoundException: stitch.view.Run
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at stitch.run.Runner.runMainApp(Runner.java:50)
at stitch.run.Runner.main(Runner.java:24)

I've tried URLs in both jar: XXXX !/ and plain file: format
And tried to use a parent loader from various sources such as:
Thread.currentThread().getContextClassLoader()



TIA

Well, i suppose the proper URLS should look like "file:///c:/foo/bar.jar".
Admittedly, im not 100% sure about the syntax, since i usually use File
objects to construct the URLS, something like:

File foo = new File("c:/foo/bar.jar");
if (!foo.exists()) throw new RuntimeException();
URL[] urls = {
foo.toURL()
};
ClassLoader cl = new URLClassLoader(urls);

Maybe try it that way, or post some lines of code how you construct your
URLS :)

Cheers
Andreas
 
V

visionset

Andreas Wollschlaeger said:
visionset said:
fails at forName() or loader.loadClass()

adding resource: jar:file:///myJar.jar!/
runMainApp() with loader: java.net.URLClassLoader@13f3045
java.lang.ClassNotFoundException: stitch.view.Run
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at stitch.run.Runner.runMainApp(Runner.java:50)
at stitch.run.Runner.main(Runner.java:24)

I've tried URLs in both jar: XXXX !/ and plain file: format
And tried to use a parent loader from various sources such as:
Thread.currentThread().getContextClassLoader()



TIA

Well, i suppose the proper URLS should look like "file:///c:/foo/bar.jar".
Admittedly, im not 100% sure about the syntax, since i usually use File
objects to construct the URLS, something like:

File foo = new File("c:/foo/bar.jar");
if (!foo.exists()) throw new RuntimeException();
URL[] urls = {
foo.toURL()
};
ClassLoader cl = new URLClassLoader(urls);

Maybe try it that way, or post some lines of code how you construct your
URLS :)

I don't think the URL is the problem, I think it is the class loader or how
I'm using it.

I'm creating URLs like this
URL resource = getClass().getResource("/" + myJarName);

But I've tried all sorts of configurations, so I reckon I've covered that
aspect.

Basically If I don't get a MalformedURLEx I expect it to work.

To cover the usage one more time to make sure I'm not doing anything daft.

I have one Jar that exists, it has Main and Class-Path entries the latter
just with . on it.

I run this Jars main() and download some other Jars and put them alongside.

Then in the same JVM I create my own class loader with valid local URLs of
those downloaded resources.

I use this classloader to load a class and here it fails with a CNFEx.



-

Mike W
 
A

Andreas Wollschlaeger

visionset said:
Andreas Wollschlaeger said:
visionset said:
HTH, otherwise post some stack trace here
fails at forName() or loader.loadClass()

adding resource: jar:file:///myJar.jar!/
runMainApp() with loader: java.net.URLClassLoader@13f3045
java.lang.ClassNotFoundException: stitch.view.Run
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at stitch.run.Runner.runMainApp(Runner.java:50)
at stitch.run.Runner.main(Runner.java:24)

I've tried URLs in both jar: XXXX !/ and plain file: format
And tried to use a parent loader from various sources such as:
Thread.currentThread().getContextClassLoader()



TIA
Well, i suppose the proper URLS should look like "file:///c:/foo/bar.jar".
Admittedly, im not 100% sure about the syntax, since i usually use File
objects to construct the URLS, something like:

File foo = new File("c:/foo/bar.jar");
if (!foo.exists()) throw new RuntimeException();
URL[] urls = {
foo.toURL()
};
ClassLoader cl = new URLClassLoader(urls);

Maybe try it that way, or post some lines of code how you construct your
URLS :)

I don't think the URL is the problem, I think it is the class loader or how
I'm using it.

I'm creating URLs like this
URL resource = getClass().getResource("/" + myJarName);

But I've tried all sorts of configurations, so I reckon I've covered that
aspect.

Basically If I don't get a MalformedURLEx I expect it to work.

To cover the usage one more time to make sure I'm not doing anything daft.

I have one Jar that exists, it has Main and Class-Path entries the latter
just with . on it.

I run this Jars main() and download some other Jars and put them alongside.

Then in the same JVM I create my own class loader with valid local URLs of
those downloaded resources.

I use this classloader to load a class and here it fails with a CNFEx.



-

Mike W

Well, this sounds pretty sound, and is quite similar to some bootstrap
loader i wrote lately.
Did you pass the parent classloader to your homegrown classloader?
Otherwise you might be in trouble if some class cannot be loaded because
it cannot resolve its reference to some class from the java runtime.

Here is a snippet of code from something similar i wrote a while ago:

//
// Build a new ClassLoader using the given URLs, replace
current Classloader
//
ClassLoader oldCL = Thread.currentThread().getContextClassLoader();
ClassLoader newCL = new URLClassLoader(myClasspathURLs, oldCL);
Thread.currentThread().setContextClassLoader(newCL);
System.out.println("Successfully replaced ClassLoader");

and then used

Class fooClass = newCL.loadClass(appClass);

along with some reflection wizardry to launch my application.

Maybe its also worth a try to launch your application using the
"-verbose" switch, sometimes this gives a better hint why a class cannot
be loaded....

Cheers
Andreas
 
V

visionset

Andreas Wollschlaeger said:
Well, this sounds pretty sound, and is quite similar to some bootstrap
loader i wrote lately.
Did you pass the parent classloader to your homegrown classloader?
Yep

Otherwise you might be in trouble if some class cannot be loaded because
it cannot resolve its reference to some class from the java runtime.

Here is a snippet of code from something similar i wrote a while ago:

//
// Build a new ClassLoader using the given URLs, replace current
Classloader
//
ClassLoader oldCL =
Thread.currentThread().getContextClassLoader();
ClassLoader newCL = new URLClassLoader(myClasspathURLs, oldCL);
Thread.currentThread().setContextClassLoader(newCL);
System.out.println("Successfully replaced ClassLoader");

and then used

Class fooClass = newCL.loadClass(appClass);

along with some reflection wizardry to launch my application.

Almost identical to mine, but above don't work either :-(
Maybe its also worth a try to launch your application using the "-verbose"
switch, sometimes this gives a better hint why a class cannot be
loaded....

Yielded nothing useful.

I hope I don't have to go down the Runtime exec route but it's looking that
way :-(

Heres the code for what its worth to anyone 'au fait' with this kind of
thing who may shed light.

Compilable if you take out the utils.Log.ln() logging
import static utils.Log.ln;

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.BufferedReader;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.MalformedURLException;

import java.net.URL;

import java.net.URLClassLoader;

import java.net.URLConnection;

import java.util.ArrayList;

import java.util.Date;

import java.util.List;

import java.util.prefs.Preferences;


public class VersionUpdater {


private Preferences preferences;

private Date lastUpdated;


private List<URL> localJars;


private static final String

RESOURCES_KEY = "stitch-update-resource-url",

LAST_UPDATE_KEY = "stitch-last-update-time";


public VersionUpdater() throws Exception {


localJars = new ArrayList<URL>();

preferences = Preferences.systemRoot();

lastUpdated = getLastUpdate();

ln("Last updated: " + lastUpdated);

}


// pass in fallback resource

public boolean update(String updateResource) throws Exception {


boolean updated = false;


URL localUrl = getResourceAsUrl(updateResource);


// read the remote urls

List<URL> remoteUrls = readRemoteUrls(localUrl);


// iterate the urls and save each ones content

boolean first = true;

for (URL url : remoteUrls) {

if (first) {

saveResourceAsUrl(url);

first = false;

} else {

if (updateResource(url)) updated = true;

}

}

saveLastUpdate();


return updated;

}


public ClassLoader createClassLoader(ClassLoader parent) {

URLClassLoader loader = new URLClassLoader(

localJars.toArray(new URL[localJars.size()]), parent);


return loader;

}


private Date getLastUpdate() {

Long longTime = preferences.getLong(LAST_UPDATE_KEY, 0);

return new Date(longTime);

}


private void saveLastUpdate() {

Long longTime = new Date().getTime();

preferences.putLong(LAST_UPDATE_KEY, longTime);

}


private URL getResourceAsUrl(String url) throws MalformedURLException {


url = preferences.get(RESOURCES_KEY, url);

return new URL(url);

}


private void saveResourceAsUrl(URL url) {

preferences.put(RESOURCES_KEY, url.toExternalForm());

}


private List<URL> readRemoteUrls(URL url) throws IOException {


URLConnection connection = url.openConnection();

BufferedReader br = new BufferedReader(

new InputStreamReader(connection.getInputStream()));

return readUrls(br);

}


private List<URL> readUrls(BufferedReader reader) throws IOException {


List<URL> urls = new ArrayList<URL>();

String line;

while ((line = reader.readLine()) != null) {

try {

URL url = new URL(line.trim());

urls.add(url);

}

catch (MalformedURLException ex) {}

}

reader.close();

return urls;

}


private boolean updateResource(URL url) throws Exception {


boolean isUpdated;


URLConnection connection = url.openConnection();


Date modTime = new Date(connection.getLastModified()); // zero is possible


ln("Resource: " + url + " - updated: " + modTime);


String urlPath = url.getPath();

int idx = urlPath.lastIndexOf('/');

String name = urlPath.substring(idx+1);


URL resource = getClass().getResource("/" + name);


// if the servers version is more recent than last update time

// or we don't have any copy of the resource

if (modTime.after(lastUpdated) || resource == null) {


ln("Saving resource: " + name + " create? " + (resource == null));


BufferedOutputStream bos =

new BufferedOutputStream(new FileOutputStream(name));


BufferedInputStream bis = new BufferedInputStream(

connection.getInputStream());


byte [] buf = new byte[1028];

int i = 0;

while((i = bis.read(buf)) != -1) bos.write(buf, 0, i);


bos.flush();

bis.close();

bos.close();


resource = getClass().getResource("/" + name);


URLConnection c = resource.openConnection();


ln ("lasy mod chcks access: " + c.getLastModified());


isUpdated = true;


} else isUpdated = false;


//resource = new URL("jar:file:///" + name + "!/");


//ln(new File(name).getCanonicalPath());


ln("adding resource: " + resource);


if (resource != null) localJars.add(resource);


return isUpdated;

}

}

import static utils.Log.ln;

import java.net.URLClassLoader;

import javax.swing.JOptionPane;


public class Runner {


private static final String RESOURCE =
"http://foo/bar/update-resources.txt";


public static void main(String[] args) {


if (!runMainApp(null)) {


try {

VersionUpdater updater = new VersionUpdater();

updater.update(RESOURCE);


ClassLoader oldCl = Thread.currentThread().getContextClassLoader();

ClassLoader loader = updater.createClassLoader(oldCl);

Thread.currentThread().setContextClassLoader(loader);


runMainApp(loader);

}

catch (Exception ex) {


JOptionPane.showMessageDialog(null,

"An error occurred whilst attempting software update.\n" +

ex.getClass().getName() + "\n" +

ex.getLocalizedMessage(),

"Update Error", JOptionPane.ERROR_MESSAGE);


ex.printStackTrace();

}

}

}


private static boolean runMainApp(ClassLoader loader) {


ln("runMainApp() with loader: " + loader);


if (loader == null) loader = Runner.class.getClassLoader();


//MyClassLoader ucl = ((MyClassLoader)loader);


try {

//Class.forName("stitch.view.StitchFrame", true, loader);


Class c = loader.loadClass("stitch.view.Run");


c.newInstance();


}

catch (Exception ex) {

ex.printStackTrace();

return false;

}



return true;

}

}
 
V

visionset

Andreas Wollschlaeger said:
Well, this sounds pretty sound, and is quite similar to some bootstrap
loader i wrote lately.

Thanks Andreas, I've got it working now.
The things I changed were to do all the Classloader config 1st thing in the
main and to help this subclassed URLClassLoader to enable post instantiation
additions to the URLs in its search path.

public static void main(String[] args) {



ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();

loader = new MyClassLoader(oldLoader );

Thread.currentThread().setContextClassLoader(loader);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top