KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > hudson > remoting > DummyClassLoader


1 package hudson.remoting;
2
3 import org.objectweb.asm.ClassReader;
4 import org.objectweb.asm.ClassWriter;
5
6 import java.io.IOException JavaDoc;
7 import java.io.InputStream JavaDoc;
8 import java.io.File JavaDoc;
9 import java.io.OutputStream JavaDoc;
10 import java.io.FileOutputStream JavaDoc;
11 import java.net.URL JavaDoc;
12
13 /**
14  * Used to load a dummy class <tt>hudson.remoting.test.TestCallable</tt>
15  * out of nowhere, to test {@link RemoteClassLoader}.
16  *
17  * @author Kohsuke Kawaguchi
18  */

19 class DummyClassLoader extends ClassLoader JavaDoc {
20     public DummyClassLoader(ClassLoader JavaDoc parent) {
21         super(parent);
22     }
23
24
25     protected Class JavaDoc<?> findClass(String JavaDoc name) throws ClassNotFoundException JavaDoc {
26         if(name.equals("hudson.remoting.test.TestCallable")) {
27             // rename a class
28
try {
29                 byte[] bytes = loadTransformedClassImage(name);
30                 return defineClass(name,bytes,0,bytes.length);
31             } catch (IOException JavaDoc e) {
32                 throw new ClassNotFoundException JavaDoc("Bytecode manipulation failed",e);
33             }
34         }
35
36         return super.findClass(name);
37     }
38
39     private byte[] loadTransformedClassImage(final String JavaDoc name) throws IOException JavaDoc {
40         InputStream JavaDoc in = getResourceAsStream("hudson/remoting/TestCallable.class");
41
42         // rename a class
43
ClassReader cr = new ClassReader(in);
44         ClassWriter w = new ClassWriter(cr,true) {
45             public void visit(int version, int access, String JavaDoc _name, String JavaDoc sig, String JavaDoc superName, String JavaDoc[] interfaces) {
46                 super.visit(version, access, name.replace('.','/'), sig, superName, interfaces);
47             }
48         };
49         cr.accept(w,false);
50
51         return w.toByteArray();
52     }
53
54
55     protected URL JavaDoc findResource(String JavaDoc name) {
56         if(name.equals("hudson/remoting/test/TestCallable.class")) {
57             try {
58                 File JavaDoc f = File.createTempFile("rmiTest","class");
59                 OutputStream JavaDoc os = new FileOutputStream JavaDoc(f);
60                 os.write(loadTransformedClassImage("hudson.remoting.test.TestCallable"));
61                 os.close();
62                 f.deleteOnExit();
63                 return f.toURL();
64             } catch (IOException JavaDoc e) {
65                 return null;
66             }
67         }
68         return super.findResource(name);
69     }
70 }
71
Popular Tags