1 package net.sf.mmapps.applications.developer.modules;
2
3 import java.io.*;
4 import java.lang.reflect.Method;
5 import java.util.jar.*;
6 import org.apache.commons.logging.*;
7 /***
8 * minimalistic class loader for 1 jar
9 * @author Kees Jongenburger
10 */
11 public class DeveloperClassLoader extends ClassLoader {
12 private static Log log = LogFactory.getLog(DeveloperClassLoader.class);
13
14
15 /***
16 */
17 private JarFile jf = null;
18
19 /***
20 */
21 public DeveloperClassLoader(JarFile jarfile) {
22 jf = jarfile;
23 }
24
25 public Class loadClass(String classname) throws ClassNotFoundException {
26 try {
27
28 Class c = findLoadedClass(classname);
29
30
31
32
33
34 if (c == null) {
35 try {
36 c = findSystemClass(classname);
37 }
38 catch (Exception e) { }
39 }
40
41 if (c == null) {
42 StringBuffer sb = new StringBuffer();
43 char[] chars = classname.toCharArray();
44 for (int x =0 ; x < chars.length ; x++){
45 if (chars[x] == '.'){
46 sb.append("/");
47 } else {
48 sb.append(chars[x]);
49 }
50 }
51 JarEntry je = jf.getJarEntry(sb.toString() + ".class");
52 if (je != null){
53 int entrylength = (int)je.getSize();
54 DataInputStream di = new DataInputStream(jf.getInputStream(je));
55 byte[] classbytes = new byte[entrylength];
56 di.readFully(classbytes);
57 di.close();
58 c = defineClass(classname, classbytes, 0, entrylength);
59 }
60 }
61 return c;
62 }
63 catch (Exception e) {
64 throw new ClassNotFoundException(e.toString());
65 }
66 }
67
68 public java.net.URL getResource(String name) {
69 JarEntry je = jf.getJarEntry(name);
70 if (je != null){
71 try {
72 java.net.URL url = new java.net.URL("jar:file:" + jf.getName() + "!/" + name);
73 log.info(url.toString());
74 return url;
75 } catch (Exception e){
76 log.warn("error while loading jar file from classloader" + e.getMessage() , e);
77 };
78 }
79 return null;
80 }
81
82 public InputStream getResourceAsStream(String name){
83 JarEntry je = jf.getJarEntry(name);
84 if (je != null){
85 try {
86 return jf.getInputStream(je);
87 } catch (Exception e){
88 log.warn("error while getting an input stream from a class loader " + e.getMessage(),e);
89 };
90 }
91 return null;
92 }
93
94 public static void main(String[] argv) throws Exception{
95 File file = new File("MMDeveloper.jar");
96 JarFile jarFile = new JarFile(file);
97 DeveloperClassLoader classLoader = new DeveloperClassLoader(jarFile);
98
99 Class clazz = classLoader.loadClass("net.sf.mmapps.applications.developer.Developer");
100 Method m = clazz.getMethod("getInstance",new Class[]{});
101 m.invoke(null,new Object[]{});
102 }
103 }