Loading jar at runtime using custom classloader

Hi,
I'm trying to load a jar file to an application running inside weblogic at runtime.
I followed the example that was posted at
http://dev2dev.bea.com/cs/user/blog?file=/blog/jcscoobyrs/archive/2005/05/realworld_use_f.html
and did the following:
URLClassLoader loader = null;
URL[] urls = {new URL("file:///" + "C:/Program Files/aaa/WEB-INF/lib/ImportTest3.jar")};
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
ClassLoader loader = new URLClassLoader(urls, classLoader);
Thread.currentThread().setContextClassLoader(loader);
Class customClass = Class.forName(className, true, loader);
customCode = customClass.newInstance();
Thread.currentThread().setContextClassLoader(classLoader);
everything works fine when I access my application once.
But when I'm trying to do the same again, everything fails.
Any ideas?
Thanks!

When you say everything fails - can you clarify the failure? Can you paste the stacktrace? Is it a ClassNotFoundException?

Similar Messages

  • How to load an applet using custom classloader ?

    Hi All,
    How to load an applet using custom classloader rather than using default browsers classloader i.e AppletClassLoader usually ?
    Regards,
    Kumar.

    I would guess that that would require two applets.
    The first does nothing but create the custom class loader and then load the second applet.

  • Complie time using custom classloader for decryption.

    I need to decrypt several class during compile time, but my custom classloader could load everything except my encrypted classes.
    Here is my sample code and how I test it.
    Test.java:
    public class Test {
         public Test(){
              System.out.println("test");
         public void hello(){
              System.out.println("hello");
    Test1.java
    public class Test1 extends java.lang.Test{
         public Test1(){
              System.out.println("test1");
         public static void main(String[] args){
              new Test1().hello();
    #EncryptedClassLoader will print out the class name it trying to load, for example: "load class: java.lang.System"
    1. Compile Test.java file and have it encrypted, make it into a jar file - test.jar.
    2. Compile Test1.java file and try to run Test1.class with encrypted Test.class file using :
    C:\lib>java -Djava.system.class.loader=EncryptedClassLoader -classpath c:\lib;c:\lib\tools.jar;c:\lib\test.jar Test1
    Gives the output:
    load class: java.lang.System
    load class: java.nio.charset.Charset
    load class: java.lang.String
    load class: Test1
    load class: Test
    load class: sun.security.provider.Sun
    load class: sun.security.rsa.SunRsaSign
    load class: com.sun.net.ssl.internal.ssl.Provider
    load class: com.sun.crypto.provider.SunJCE
    load class: java.lang.Object
    load class: java.io.PrintStream
    test
    test1
    hello
    So now I'm sure there's no problem with my EncryptedClassLoader
    3. Try to compile Test1.java with the encrypted Test.class in test.jar(These's no Test.java file in the same folder) by using:
    C:\lib>javac -J-Djava.system.class.loader=EncryptedClassLoader -J-classpath -J.;c:\lib;c:\lib\tools.jar;c:\lib\test.jar Test1.java
    Give the output:
    .............. (loading several system classes)
    load class: com.sun.tools.javac.util.Position
    Test1.java:4: cannot find symbol
    symbol: class Test
    public class Test1 extends Test{
    ^
    load class: java.lang.Long
    load class: java.io.DataInputStream
    load class: com.sun.tools.javac.jvm.ClassReader$AnnotationCompleter
    load class: com.sun.tools.javac.jvm.ClassReader$AnnotationDeproxy
    load class: com.sun.tools.javac.jvm.ClassReader$ProxyVisitor
    load class: com.sun.tools.javac.code.Types$SubstFcn
    load class: com.sun.tools.javac.code.BoundKind
    load class: java.lang.StringBuffer
    Test1.java:12: cannot find symbol
    symbol : method hello()
    location: class Test1
    new Test1().hello();
    ^
    2 errors
    ---> from the output I found that Test.class never visited/loaded by my EncryptedClassLoader
    Though I set EncryptedClassLoader as the default system classloader but it seems to load everything except my encrypted class.
    Does anyone know why it works like this??
    Thank you in advanced,
    Alex.
    null

    I don't know why he was specifying the javac classpath like that instead of using javac's -classpath option.
    But this whole business of decrypting class loades is pretty much a waste of time. It adds a layer of comfort but it's not really what I would call secure. At some point the unencrypted bytes have to appear in memory and from that point the classes are no longer secure.
    The best protection against software piracy is not anti-decompilation techniques but time-to-market and pricing your product so that buying it is cheaper than reverse-engineering it.

  • Using custom ClassLoader

    Is there a way to make my custom ClassLoader the default ClassLoader for my program?
    ie. Can I just set up my program to use my ClassLoader whenever it needs to access class files?
    Geoff.

    Hi,
    The main class is always loaded by the boot strap class loader(also called System ClassLoader). You can't change it. After that all the classes are loaded by the classloader of the loading class. i.e.
    If class A is loading class B, then class B's classloader will be the classloader of class A.
    So, basically you need to write a classloader, and a wrapper class for your main class like:
    public class WrapperClass
        public void main(String[] args) throws Exception
           MyClassLoader myClassLoader = new MyClassLoader();
           Class mainClass = myClassLoader.loadClass("MainClass");
           Method mainMethod = mainClass.getMethod("main", new Class[] {args.getClass()});
           mainMethod.invoke(null, args);
    }then rest of the classes including MainClass are loaded by the MyClassLoader. If you need help you writing ClassLoader please reply back.
    Hope this helps.

  • Annotation-Processing Using Custom ClassLoader Fails

    Hi,
    I have the following problem concerning annotations.
    I am using Jaxb2 to marshal some classes and Jaxb relies heavily on processing annotation information contained in them.
    If I put the Jaxb JAR's directly in the classpath everything works fine.
    However, if I use a custom URLClassLoader to load all the Jaxb-related classes the annotation processing fails thus making Jaxb believe that the objects can't be marshaled.
    Note that the classes to marshal containing the annotations to read are loaded with a different ClassLoader which is higher in the hierarchy.
    I tracked down the problems to the class RuntimeInlineAnnotationReader of the Jaxb API which simply calls Class.getAnnotion(..).
    When searching for this bug I also found the bug report 5015623 which relates to this problem. But it is rather outdated, so I hope that there are some better solutions than just ignoring it.
    I wouldn't like having the Jaxb JARs on the global classpath 'cause they are used in only one class out of 100 and thats not worth the possible conflicts with other 3rd party libs.
    Best regards,
    beebop

    No problem, I will give you some details about my architecture.
    First of all I encapsulated the code which uses the Jaxb-API in one class, say Foo, which implements the interface FooInterface.
    Secondly I load the Foo class in another class, Bar, using my derivation of URLClassLoader, called MyClassLoader. Then I use the interface to marshal an object gen of type GenClass where GenClass was generated using xjc:
    class Bar {
      void method(URL[] urls, GenClass gen) {
        ClassLoader parent = Bar.class.getClassLoader();
        ClassLoader myCL = new MyClassLoader(urls,parent);
        Class clazz = myCL.loadClass("Foo");
        FooInterface foo = (FooInterface)clazz.newInstance();
        foo.marshal(gen);
    }So my class loader will be a child of the current class loader. The delegation model of class loading is reversed in MyClassLoader so that first the urls will be checked and then, if the class was not found, the parent class loader.
    Note that GenClass and its ObjectFactory which acutally contain the annotations Jaxb needs will be loaded by the current class loader, not my own. All classes of the Jaxb-API will be loaded by MyClassLoader. If I try to marshal gen, the annotations of the ObjectFactory corresponding to GenClass won't be readable causing the Class.getAnnotation(...) method called in the class RuntimeInlineAnnotationReader to return null.
    If I don't use my own class loader, say
    FooInterface foo = new Foo();everything works fine and the annotations of the ObjectFactory are loaded correctly.
    I observed the different behaviour by stepping through the classes and methods around JaxbContext.newInstance(...).
    MyClassLoader is not that different from URLClassLoader, only the loadClass method is overridden to change the delegation behaviour. Thats why I suspect an error in the annotations framework and not in my class loader but I may be mistaken.
    Best regards,
    beebop

  • JAXB 1.0 Final: jaxb.properties not found when using custom classloader

    JDK 1.3.1 is being used.
    The scenario:
    1) jaxb jar files, jaxb generated files and application files loaded in default class loader works, however
    2) jaxb jar files, jaxb generated files and application files loaded in a custom class loader generate the following exception:
    javax.xml.bind.JAXBException: Unable to locate jaxb.properties for package XXX
    To demonstrate here are two sample applications: a Launcher app whose job it is to start apps and a sample App1 application who needs JAXB.
    If launch is placed into a jar file named launch.jar and App1 is placed into a jar file named app1.jar (with a JAXB generated package), and both jar files are placed in a directory containing all the JAXB 1.0 jar files (dom, sax, namespace, etc) and the system is started with the following:
    jre\bin\java -cp launch.jar; testLaunch.launch
    the exception occurs.
    By way of comparison, if App1 is started directly with the following:
    jre\bin\java -cp app1.jar;jax-qname.jar;jaxb-xjc.jar;jaxb-ri.jar;jaxb-libs.jar;jaxb-api.jar;dom.jar;sax.jar;jaxp-api.jar;xercesImpl.jar;namespace.jar;ant.jar;xalan.jar testApp.app1
    the exception does not occur.
    Any help would be greatly appreciated.
    package testLaunch;
    import java.net.*;
    import java.io.*;
    public class launch extends javax.swing.JFrame
        private static URLClassLoader app1ClassLoader_; 
        private static Class  app1EntryClass_ = null;
        private static final String app1MainClassName_ = "testApp.app1";
        private Object appObj_ = null;
         static public void main(String args[])
              try {
                System.out.println("Launch Main");               
                new launch();          
                  System.exit(0);
              catch (Throwable t) {
                   t.printStackTrace();
                   System.exit(1);
         public launch()
            if (app1ClassLoader_== null)
                loadAppClassLoader();
            try{
                if (app1EntryClass_ == null)
                    app1EntryClass_ = app1ClassLoader_.loadClass(app1MainClassName_);
                if (app1EntryClass_ == null)
                    System.out.println(app1MainClassName_ + " was not found");
                else
                    appObj_ = app1EntryClass_.newInstance();
            catch(ClassNotFoundException x){
                x.printStackTrace();
            catch(Exception x){
                x.printStackTrace();
        private static void loadAppClassLoader()
            String jarPath = jarPath = System.getProperty("user.dir");
            System.out.println("jar path is: " + jarPath);
            try{
                File jarfile1 = new File(jarPath+File.separator+"app1.jar");
                File jarfile2 = new File(jarPath+File.separator+"dom.jar");
                File jarfile3 = new File(jarPath+File.separator+"jaxp-api.jar");
                File jarfile4 = new File(jarPath+File.separator+"jaxb-api.jar");
                File jarfile5 = new File(jarPath+File.separator+"jaxb-xjc.jar");
                File jarfile6 = new File(jarPath+File.separator+"jaxb-ri.jar");
                File jarfile7 = new File(jarPath+File.separator+"jaxb-libs.jar");
                File jarfile8 = new File(jarPath+File.separator+"jax-qname.jar");
                File jarfile9 = new File(jarPath+File.separator+"sax.jar");
                File jarfile10 = new File(jarPath+File.separator+"xercesImpl.jar");
                File jarfile11 = new File(jarPath+File.separator+"namespace.jar");
                File jarfile12 = new File(jarPath+File.separator+"xalan.jar");
                File jarfile13 = new File(jarPath+File.separator+"ant.jar");
                if (!jarfile1.exists())
                    System.out.println("**ERROR " + jarfile1 + " does not exist!");
                app1ClassLoader_ = new URLClassLoader( new URL[]{jarfile1.toURL(),
                                                                jarfile2.toURL(),
                                                                jarfile3.toURL(),
                                                                jarfile4.toURL(),
                                                                jarfile5.toURL(),
                                                                jarfile6.toURL(),
                                                                jarfile7.toURL(),
                                                                jarfile8.toURL(),
                                                                jarfile9.toURL(),
                                                                jarfile10.toURL(),
                                                                jarfile11.toURL(),
                                                                jarfile12.toURL(),
                                                                jarfile13.toURL()} );
            catch(Exception x){
                x.printStackTrace();
                return;
    package testApp;
    import javax.xml.bind.*; // JAXB classes
    import myGeneratedJAXBFiles;
    public class app1 extends javax.swing.JFrame
         static public void main(String args[])
              try {
                System.out.println("App1 Main");               
                new app1();           
                  System.exit(0);
              catch (Throwable t) {
                   t.printStackTrace();
                   System.exit(1);
         public app1()
            try
                JAXBContext jc_ = JAXBContext.newInstance( "myGeneratedJAXBFiles" );
                System.out.println("Successfully loaded JAXB Context");          
            catch (JAXBException jbe)
                jbe.printStackTrace();

    I'm doing something very similar. In fact my launcher is also stored in launcher.jar. It will start any application on the classpath and load dependencies jars located in the specified directory.
    The first thing you must do is specify the classloader when constructing the jaxb context:
    JAXBContext jc = JAXBContext.newInstance(xmlPackage, getClass().getClassLoader());
    After this I was still raning into the "jaxb.properties not found" exception in some situations. Basically if the class using the jaxb files is located in the same jar as jaxb.properties everything worked fine. However if the class using the jaxb objects was located in a different jar it did not work.
    I had to add the following early in the execution of the application that load the plugins to get things working correctly:
    Thread.currentThread().setContextClassLoader(jarDirClassLoader);
    As far as I can tell JAXB using the Context class loader to find the jaxb.properties file.
    I'm using JAXB 1.1
    I hope this helps!

  • Can't use custom ClassLoader with ObjectInputStream

    Hi all,
    I want to transmit an object whose class is unknown to the receiver and whose class may not be loaded. Of course when the inputstream's readObject method tries to receive this class, it fails with a ClassNotFoundException. I have a custom FileClassLoader to dynamically load classes, this is tested and works.
    I can dynamically load this class and prove that the class was loaded by calling class.newInstance() from the loader.loadClass method. But then when I try to read that same class from the input stream, it says ClassNotFoundException!
    The code snippet looks like this:
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    FileClassLoader loader = new FileClassLoader(classFolder);
    Class L = loader.loadClass(className); // no .class at end
    System.out.println("New Instance "+L.newInstance().toString()); // works
    ObjectInputStream eventStream = ... // stream from a socket
    eventStream.readObject(); // throws class not found exception!
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    The only thing I can think is that the input stream only looks for classes loaded by the system classloader, could that be true? What other possibilities are there?
    If this is more appropriate for another forum just let me know and I'll post it there.
    Thanks in advance for any helpful hints anybody has!

    I was thinking of something along the lines of
    ObjectInputStream eventStream = (ObjectInputStream)Class.forName("java.io.ObjectInputStream", true, loader).newInstance();Of course, you would really have to get the proper Constructor for the class - and that just gets too long and stupid. Besides, I actually tried my suggestion, and it didn't work. I also tried setting the ContextClassLoader for the current thread (and creating a new thread with the ContextClassLoader set to "loader"). None of that works. Just setting the ContextClassLoader does not make the thread use it implicitly, it's apparently just a way to pass another ClassLoader to a thread, but it still needs to be used explicitly in a Class.forName call.
    I did, however, try David's suggestions of overriding resolveClass in ObjectInputStream. That worked fine! Here's what I created:
    import java.net.URLClassLoader;
    import java.io.InputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectStreamClass;
    import java.io.StreamCorruptedException;
    public class MyObjectInputStream extends java.io.ObjectInputStream
        URLClassLoader myLoader = null;
        public MyObjectInputStream(URLClassLoader newLoader, InputStream theStream) throws IOException, StreamCorruptedException
            super(theStream);
            myLoader = newLoader;
        protected Class resolveClass(ObjectStreamClass osc) throws IOException, ClassNotFoundException
            System.out.println("Hey, I'm in my resolveClass");
            Class theClass = null;
            try
                theClass = Class.forName(osc.getName(), true, myLoader);
            catch (Exception e)
                System.err.println("An Error in my ResolveClass:");
                e.printStackTrace();
            return theClass;
    }You then just create your ObjectInputStream with
    ObjectInputStream eventStream = new MyObjectInputStream(loader, theSocket.getInputStream());

  • Java Mapping - add external jar for runtime use

    Hi,
    I have implemented a java mapping which executes an XSLT transformation on the input XML. This way I can control (I hope) what XSLT processor is used, as I want to use the SAXON XSLT processor. The java mapping executes fine locally in NWDS.
    But when executed runtime I get the following error in default_trace and the message stops in Integration Engine:
    javax.xml.transform.TransformerFactoryConfigurationError: Provider net.sf.saxon.TransformerFactoryImpl not found
    In my java mapping I have set the following:
    System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
    The TransformerFactoryImpl class is implemented in saxon9.jar.
    Where do I store the saxon9.jar on the server so that it will find it during execution?
    Any hints are most welcome!
    Br,
    Kenneth

    Hi Kenneth,
                          First of all java mapping procedure has the capacity to transform XML using SAX or DOM parser directly. I am not sure as to why you need "SAXON XSLT processor" for the purpose.
                           Now coming to your question  "Where do I store the saxon9.jar on the server so that it will find it during execution?"
    In NWDS import the jar file saxon9.jar within your package, where you have written the source code. This you can do using File->import ->(ZIP or jar file).    Before you import slect the package or folder where you want to import the jar file. Once jar file import is complete execute the code once, see if its running properly. Then choose file->export and select all *.java and *.class files in your package. Save this under one filename say package.jar.
    Finally import this jar file in PI server by usual methods.
    Hope this solves your problem
    regards
    Anupam

  • Using custom classloader with javac

    There is an interesting thread going on at http://forums.java.net/jive/thread.jspa?threadID=13417&tstart=0.
    Since this forum seems to be more active than that forum, I wonder if anyone has an answer to my last post on that thread (post number 4 by garyh)?
    Thanks for any help.

    Please ignore this post.
    It was submitted before I finished writing it.
    Sorry,
    zganon

  • The struggle of creating a Custom ClassLoader for Native libraries

    Hello Everyone,
    I'm having a really hard time writing and using my own ClassLoader in a Java Applet.
    Context :
    As the this link shows - http://codethesis.com/tutorial.php?id=1 - loading and especially unloading native libraries through Java requires defining our own ClassLoader, and use it to instantiate a class loading a library. When the class using native libraries has finished execution, setting all references to the classloader and calling the garbage collector will cause the native library to be unloaded. The class to load within the custom classloader is thus read byte after byte from the jar and defined using the Classloader.defineClass(..) function. So that's what I did. But I've got two problems.
    Problem 1 :
    On one single machine over 15 tested, the magic number of a given class read from the Jar using Applet.class.getResourceAsStream(classname) takes a value different from CAFEBABE and the defineClass function then throws an "Incompatible magic value" exception (see below). The workaround I found is to force the first 4 bytes of the byte array read from the class with CAFEBABE. But I still would like to understand why it takes a different value on this machine.
    Exception in thread "thread applet-MyApplet.class-1" java.lang.ClassFormatError: Incompatible magic value 409165630 in class file Reader
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at NativeClassLoader.findClass(Unknown Source)
    Problem 2 :
    On windows, the NativeClassLoader works perfectly, but on Linux, I'm getting a java.lang.VerifyError (see below).
    Code is compiled with java 1.6.0_06 on windows XP. I tried to remove everything related to native code (remove .so load), the same error is raised.
    java.lang.VerifyError: (class: Reader, method: <clinit> signature: ()V) Illegal instruction found at offset 1
    at java.lang.Class.getDeclaredConstructors0(Native Method)
    at java.lang.Class.privateGetDeclaredConstructors(Class.java:2389)
    at java.lang.Class.getConstructor0(Class.java:2699)
    at java.lang.Class.newInstance0(Class.java:326)
    at java.lang.Class.newInstance(Class.java:308)
    Code :
    NativeClassReader (custom) :
    public class NativeClassLoader extends ClassLoader {
        //the unique instance of the NativeClassLoader
        private static NativeClassLoader instance;
        private NativeClassLoader () {
            super(NativeClassLoader.class.getClassLoader());
         * Get the Singleton instance of the class
        public static NativeClassLoader getInstance () {
            if (instance == null)
                instance = new NativeClassLoader();
            return instance;
        public static void dispose () {
            instance = null;
         * Load a class using its full java name (prefixed with package)
        public Class findClass (String theName) {
            byte[] b = null;
            try {
                b = loadClassDataFromJar(theName);
                Class clazz = defineClass(theName, b, 0, b.length);
                resolveClass(clazz);
                return clazz;
            } catch (Exception e) {
                return null;
         * Gets the bytes of a class file stored in the current jar using
         * its full class name
        public byte[] loadClassDataFromJar (String theName)
                                     throws Exception {
            String filename = "/" + theName.replace('.', '/') + ".class";
            InputStream is = SawsApplet.class.getResourceAsStream(filename);
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            //compute file size
            Vector vChars = new Vector();
            int c;
            while ((c = br.read()) != -1)
                vChars.add(new Byte((byte) c));
            //fill in byte array with chars read from the buffer
            byte[] buff = new byte[vChars.size()];
            //workaround for a bug on one (some) Vista machine(s)
            //force magic number to CAFEBABE instead of 18635F3E
            if (vChars.size() > 3) {
                buff[0] = (byte) 0xCA;
                buff[1] = (byte) 0xFE;
                buff[2] = (byte) 0xBA;
                buff[3] = (byte) 0xBE;
            for (int i = 4; i < vChars.size(); ++i)
                buff[i] = ((Byte) vChars.get(i)).byteValue();
            return buff;
    }Reader (loading native libary) :
    public class Reader {
       static {
         System.loadLibrary("myLib");
        public static native String getData();
    }Main :
        NativeClassLoader cLoader = NativeClassLoader.getInstance();
        Class clazz = cLoader.findClass("Reader"); // ClassFormatError thrown here
        Object reader = clazz.newInstance(); // VerifyError thrown here
        Method m = clazz.getMethod("getData");
        String s = m.invoke(reader);
        print(s);
        s = null;
        m = null;
        reader = null;
        clazz = null;
        cLoader = null;
        NativeClassLoader.dispose();
        System.gcAny ideas would be really appreciated :-)
    Guillaume

    Are you using the executable exe file and the filename as a parameter in the custom task?
    Andreas Baumgarten | H&D International Group

  • Reloading the same jar at runtime

    Hi Friends,
    I have loaded the jar at runtime using the urlclassloader, but now I want to reload the same jar of different version again.
    Is it possible, if yes ..Could you please explain.
    Thanks in advance,
    Kk

    If your application permits, you can do this:
    1. Create an URLClassLoader with an URL referencing the original version of the JAR;
    2. Create an instance of a class, most probably a Runnable, keeping a reference to it;
    3. Use the object created in 2.
    And when you want to reload the JAR, you set the reference to null, perform any cleanup needed, and repeat those three steps again.
    Something like
    public class MyApplication {
      public static void main(String[] args) throws Exception /* error handling removed for clarity */ {
        URLClassLoader loader = new URLClassLoader(new URL[] {new URL("name.jar"});
        Runnable run = (Runnable) loader.loadClass("com.mypackage.MyApplicationStage2").getConstructor().newInstance();
        run.run();
        System.out.print("Press Enter to reload name.jar, or Ctrl+C to exit: ");
        new BufferedReader(new InputStreamReader(System.in)).readLine();
        run = null;
        loader = new URLClassLoader(new URL[] {new URL("name.jar"});
        Runnable run = (Runnable) loader.loadClass("com.mypackage.MyApplicationStage2").getConstructor().newInstance();
        run.run();
    }And then the class in name.jar could look like this (old, then new):
    package com.mypackage;
    public class MyApplicationStage2 implements Runnable {
      public void run() { System.out.println("Old code"); }
    package com.mypackage;
    public class MyApplicationStage2 implements Runnable {
      public void run() { System.out.println("New code"); }
    }Edited by Looce on Nov 8, 2008 6:00 PM (three steps, not two)

  • Customer ClassLoader:  keeping JWS from loading jars

    I really like the ability of JWS to be able to download jars required for my application to run, but there are several jars that I need the ability to load up via a custom ClassLoader. But because JWS includes all of these jars in the classpath upon application start, the system class loader will take the first class it can find. Because I need to load classes from these jars based upon something a user selects, I need to have control over the codesource for these classes. Does anyone have any ideas on how to tackle this problem? Not include the jars in the jnlp and then download if not cached locally, if that's the case what's the best way to do that? Include in jnlp and be able to load with custom classloader(I dont think this will work)? Any ideas on this would greatly be appreciated.

    Easiest solution to your problem and still being able to use the update mechanism of JWS is to include your JAR-file in another JAR-file that JWS loads, and then write up your own classloader, which tries to fetch your JAR-file from the downloaded JAR-file (if JWS already downloaded it, otherwise JWS will download it).
    The contents of the jws-stub.jar would be something
    of the following ;).
    jws-stub.jar
    --> myjar1.jar
    --> myjar2.jar
    org.myjar.MyJarClassloader
    Then based on your user selecting something you
    can decide which JAR-file you want to load, and thus
    which class.
    Hope this helped,
    Manfred.

  • Replacing JAR files loaded by custom ClassLoader

    Hi all,
    I am trying to create an auto-updater for a stand alone application, which can look for new versions of relevant jar files on the internet and download them. I have code which will look for newly downloaded versions and can replace the old jar file with the new one (using simple File methods). This works fine for when the application is started initially, but as the application is a server and may not manually be started for a long time, I am trying to force the server to restart and reload with the new code.
    if(newCode.exists()) {
         System.out.println("new code!");
         if(oldCode.exists()) {
              oldCode.delete();
         if(code.exists()) {
              if(! code.renameTo(oldCode)) {
                        throw new IOException("Error backing up code file");
         if(! newCode.renameTo(code)) {
              throw new IOException("Error installing new code file");
    }I have looked around the forums a bit, and have come up with using a ClassLoader based on URLClassLoader:
    class ProxyLoader extends URLClassLoader
         public ProxyLoader(String jarFile) throws MalformedURLException {
              super(new URL[] { (new File(jarFile)).toURL() });
         public Class findClass(String name) throws ClassNotFoundException {
              System.out.println("Finding: " + name);
              return super.findClass(name);
    }This seems to work OK, as all the classes from the jar file are loaded by this classloader.
    I have a method which can create an instance of the class loader, and load the server application.
    private boolean startProxy(int port) {
         try {
              pl = new ProxyLoader("proxy.jar");
              Class ptClass = pl.loadClass("proxy.POPThread");
              pt = ptClass.newInstance();
              Method ptStart = ptClass.getMethod("start", new Class[0]);
              ptStart.invoke(pt, new Object[0]);
              return true;
         } catch(Exception e) {
              return false;
    }I also have a method to shut down the server:
    private boolean stopProxy() {
         try {
              Class ptClass = pl.loadClass("proxy.POPThread");
              Method ptInterrupt = ptClass.getMethod("interrupt", new Class[0]);
              ptInterrupt.invoke(pt, new Object[0]);
              return true;
         } catch(Exception e) {
              return false;
    }These appear to be working fine, the problem I have however is when I try to rename the existing jar file (proxy.jar) in order to replace it with a new one (proxy.new), the renameTo method on the File object fails. I am guessing that is because the proxy.jar file is still in use by the JVM. I have tried setting the classloader var to null, but this doesnt seem to have any effect.
    My main question is how can I 'free' the jar file so that it can be replaced with new code? Is it possible? My only otherway of working around this is to have a variable stored in a file pointing at the 'current' code, but the jar file isn't litterally replaced.
    This is a standalone application, which will probably run in a startup script on a server, so webstart isn't really an option.
    TIA
    iklesteve

    I have found this to be true anytime I try to use the renameTo() API to rename a file with a .jar file extension (regardless of the actual file type - i.e. it could be a text file with .jar appended and it will still fail) in the case where the class making the renameTo() call is loaded from another .jar file.
    I run the same exact code after extracting from the .jar, then the rename to the other .jar file is successful. Also, if I rename the .jar file to a ".ja" file, I can successfully rename the jar file even if the code is running with the context of another .jar file.
    Is this some kind of bogus security measure within the JVM or is it a bug?

  • Loading EAR or WAR using a Custom Classloader

    Hi, everybody.
    First of all I'm aware of http://download.oracle.com/docs/cd/E12840_01/wls/docs103/programming/classloading.html
    Is is possible to "insert" a custom classloader in this hierarchy? I need a custom classloader to load special resources for my webapp. This custom classloader can be added right after the system classloader, acting as the parent classloader of my app (ear or war) classloader. Is it doable? How?
    Thanks in advance.
    Best regards,
    Daniel.

    My workaround won't work. The app classloader is accessible but it isn't an URLClassLoader, so i am unable to change its classpath.
    <16/05/2011 18h01min11s BRT> <Notice> <WebLogicServer> <BEA-000365> <Server state changed to STANDBY>
    <16/05/2011 18h01min11s BRT> <Notice> <WebLogicServer> <BEA-000365> <Server state changed to STARTING>
    preStart
    thread cl = weblogic.utils.classloaders.GenericClassLoader@1d5176d finder: weblogic.utils.classloaders.CodeGenClassFinder@330301 annotation: app@
    this cl = weblogic.utils.classloaders.GenericClassLoader@1d5176d finder: weblogic.utils.classloaders.CodeGenClassFinder@330301 annotation: app@
    thread cl instanceof URLClassLoader = false
    this cl instanceof URLClassLoader = false
    === Starting app ===
    sysCl = sun.misc.Launcher$AppClassLoader@13f5d07
    threadCl = weblogic.utils.classloaders.ChangeAwareClassLoader@17df9ec finder: weblogic.utils.classloaders.CodeGenClassFinder@af0e38 annotation: app@test_war
    sysCl = weblogic.utils.classloaders.ChangeAwareClassLoader@17df9ec finder: weblogic.utils.classloaders.CodeGenClassFinder@af0e38 annotation: app@test_war -> weblogic.utils.classloaders.GenericClassLoader@1d5176d finder: weblogic.utils.classloaders.CodeGenClassFinder@330301 annotation: app@ -> weblogic.utils.classloaders.FilteringClassLoader@2096d7 finder: weblogic.utils.classloaders.CodeGenClassFinder@18f12dc annotation: -> weblogic.utils.classloaders.GenericClassLoader@fbf51d finder: weblogic.utils.classloaders.CodeGenClassFinder@1f4b24 annotation: -> sun.misc.Launcher$AppClassLoader@13f5d07 -> sun.misc.Launcher$ExtClassLoader@f4a24a
    threadCl = weblogic.utils.classloaders.ChangeAwareClassLoader@17df9ec finder: weblogic.utils.classloaders.CodeGenClassFinder@af0e38 annotation: app@test_war ->weblogic.utils.classloaders.GenericClassLoader@1d5176d finder: weblogic.utils.classloaders.CodeGenClassFinder@330301 annotation: app@ -> weblogic.utils.classloaders.FilteringClassLoader@2096d7 finder: weblogic.utils.classloaders.CodeGenClassFinder@18f12dc annotation: -> weblogic.utils.classloaders.GenericClassLoader@fbf51d finder: weblogic.utils.classloaders.CodeGenClassFinder@1f4b24 annotation: -> sun.misc.Launcher$AppClassLoader@13f5d07 -> sun.misc.Launcher$ExtClassLoader@f4a24a
    postStart
    thread cl = weblogic.utils.classloaders.GenericClassLoader@1d5176d finder: weblogic.utils.classloaders.CodeGenClassFinder@330301 annotation: app@
    this cl = weblogic.utils.classloaders.GenericClassLoader@1d5176d finder: weblogic.utils.classloaders.CodeGenClassFinder@330301 annotation: app@
    thread cl instanceof URLClassLoader = false
    this cl instanceof URLClassLoader = false
    <16/05/2011 18h01min46s BRT> <Notice> <Log Management> <BEA-170027> <The Serverhas established connection with the Domain level Diagnostic Service successfully.>
    =====================================================================
    http://pastie.org/1912944
    package abc;
    import java.net.URLClassLoader;
    import weblogic.application.ApplicationException;
    import weblogic.application.ApplicationLifecycleListener;
    import weblogic.application.ApplicationLifecycleEvent;
    public class MyAppListener extends ApplicationLifecycleListener {
         @Override
         public void postStart(ApplicationLifecycleEvent evt)
                   throws ApplicationException {
              System.out.println("postStart");
              printClassLoaders();
         @Override
         public void preStart(ApplicationLifecycleEvent evt)
                   throws ApplicationException {
              System.out.println("preStart");
              printClassLoaders();
         protected void printClassLoaders() {
              ClassLoader[] cls = new ClassLoader[] {
                        Thread.currentThread().getContextClassLoader(),
                        getClass().getClassLoader() };
              System.out.println("thread cl = " + cls[0]);
              System.out.println("this cl = " + cls[1]);
              System.out.println("thread cl instanceof URLClassLoader = "
                        + (cls[0] instanceof URLClassLoader));
              System.out.println("this cl instanceof URLClassLoader = "
                        + (cls[1] instanceof URLClassLoader));
    }

  • Detecting when exception was thrown using custom class loader

    Hello all,
    I would like to implement the solution described here - http://stackoverflow.com/questions/75218/how-can-i-detect-when-an-exceptions-been-thrown-globally-in-java - that uses custom class loader in order to detect when an Exeption thrown somewhere in the JVM hosting my app, please note that exceptions might be thrown from 3rd party jars the app is using. So, thanks to help I got from another post, I've managed to code the custom class loader. My question is how can the class loader wrap the original exception, as the methods in ClassLoader deals with classes, not instances. So where should I set the original exception?
    Thanks!
    Edited by: user9355666 on Sep 28, 2010 10:48 PM

    user9355666 wrote:
    I think I'm missing something fundumental, forgive me for being slow...
    This is what I did so far. For the exception wrapper I made a simple class extens Exception that recieve Exception in its ctor and store it. I also subclassed ClassLoader and override its loadClass(). I've registered it as the system classloader. My thinking was to check in that point that if the requested class is instance of Exception and if yes, returning my wrapper class wrapping this exception. But, since loadClass() return class, how can I set in the wrapper the original exception?
    In addition, let's say 2 different places in the code throws NPE, to my understanding the classloader will load NPE only once, so how throwing the NPE in the second time can be detected?you are missing a key point. you should creating a custom implementation of the NPE class which hooks into your detection code in its constructor. from that point forward, anytime any NPE (which is your custom class) is constructed, you can detect it.

Maybe you are looking for

  • Getting Error while posting through KB11N : No true sender object entered

    HI Expert, We have stastical internal order defined and same we are using in Asset. Let me explain the scenarion. We created the Purchase requisition with the stastical Internal Order then we did Purchase Order and MIGO -Goods Receipt. Now we realise

  • Firefox crashes after updating 8.0 - how to fix?

    '''My firefox crashes (Cant open) as soon as I updated it to 8.0.''' I have tried safe mode and it still just launches for a half second and shuts down... it doesn't give me enough time to click on anything to troubleshoot. I do not want to delete Fi

  • In my laptop internal bluetooth is disabled by the windows frm device manager, hw can I enable it ?

    I am using hp probook 4530s comes with windows 7 home premium. In my laptop internal bluetooth is disabled by the windows from device manager, how can I enable it ? Please help...... The error is: Windows has stopped this device because it has report

  • Multi-Line Tool Tip

    Greetings<p> I want to have a multi line tool tip generated from database table fields.<p> Currently I'm using #{datasource.currentRow["FieldName1"]}, #{datasource.currentRow["FieldName2"]} etc., but some of the strings in the field are rather long.<

  • Assembling jar with dependent classes

    For efficient Applet use I'd like to copy selectively into a jar my applet classes plus all classes they are dependent on from a set of libraries, thus producing the minimum jar library with which the applets can run (obviously classes which are part