1 30 package com.genimen.djeneric.util; 31 32 import java.io.ByteArrayInputStream ; 33 import java.io.ByteArrayOutputStream ; 34 import java.io.IOException ; 35 import java.io.InputStream ; 36 import java.util.ArrayList ; 37 import java.util.HashMap ; 38 import java.util.Iterator ; 39 import java.util.jar.JarEntry ; 40 import java.util.jar.JarInputStream ; 41 42 import com.genimen.djeneric.structure.ResourceDefinition; 43 44 public class DjResourceClassLoader extends ClassLoader 45 { 46 private HashMap _resources; private ArrayList _extraJars = new ArrayList (); 48 49 public DjResourceClassLoader(HashMap resources) 50 { 51 this._resources = resources; 52 Iterator it = resources.keySet().iterator(); 53 while (it.hasNext()) 54 { 55 String path = (String ) it.next(); 56 if (path.startsWith("/jars/")) 57 { 58 _extraJars.add(resources.get(path)); 59 } 60 } 61 } 62 63 protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException 73 { 74 77 Class c = findLoadedClass(name); 78 79 if (c == null) 80 { 81 try 82 { 83 c = findSystemClass(name); 84 } 85 catch (ClassNotFoundException e) 86 { 87 } 91 } 92 93 if (c == null) 94 { 95 ResourceDefinition res = (ResourceDefinition) _resources.get(name); 96 if (res != null) 97 { 98 byte data[] = res.getBytes(); 99 100 c = defineClass(name, data, 0, data.length); 102 } 103 else 104 { 105 String fileName = name.replace('.', '/') + ".class"; 106 byte data[] = getBytesFromResourceJars(fileName); 107 108 if (data != null) c = defineClass(name, data, 0, data.length); 109 } 110 111 if (c == null) throw new ClassNotFoundException (name); 112 } 113 114 if (resolve) resolveClass(c); 116 117 return c; 118 } 119 120 public InputStream getResourceAsStream(String name) 121 { 122 byte[] data = null; 123 124 ResourceDefinition res = (ResourceDefinition) _resources.get(name); 125 if (res != null) 126 { 127 data = res.getBytes(); 128 } 129 else 130 { 131 data = getBytesFromResourceJars(name); 132 } 133 134 if (data == null) return null; 135 return new ByteArrayInputStream (data); 136 137 } 138 139 private byte[] getBytesFromResourceJars(String fileName) 140 { 141 142 try 143 { 144 Iterator it = _extraJars.iterator(); 145 byte[] data = null; 146 147 while (it.hasNext() && data == null) 148 { 149 ResourceDefinition def = (ResourceDefinition) it.next(); 150 if (def.isJar()) 151 { 152 ByteArrayInputStream bis = new ByteArrayInputStream (def.getBytes()); 153 JarInputStream jis = new JarInputStream (bis); 154 JarEntry entry; 155 156 while ((entry = jis.getNextJarEntry()) != null && data == null) 157 { 158 if (fileName.equals(entry.getName())) 159 { 160 ByteArrayOutputStream bos = new ByteArrayOutputStream (2000); 161 DjFileUtil.copy(jis, bos); 162 data = bos.toByteArray(); 163 164 } 165 } 166 } 167 } 168 return data; 169 } 170 catch (IOException e) 171 { 172 DjLogger.log(e); 173 return null; 174 } 175 } 176 } | Popular Tags |