1 29 30 package com.caucho.ant.jaxb; 31 32 import java.io.*; 33 34 import java.util.*; 35 36 import java.net.URL ; 37 38 import com.caucho.util.*; 39 import com.caucho.vfs.*; 40 41 42 48 public class GreedyClassLoader extends java.net.URLClassLoader 49 { 50 private final static URL [] NULL_URL_ARRAY = new URL [0]; 51 52 private ClassLoader _parent; 53 private Hashtable<String ,Class > _classes = new Hashtable<String ,Class >(); 54 private ByteBuffer _buffer = new ByteBuffer(); 55 private HashMap<File,String > _problemFiles = new HashMap<File,String >(); 56 57 public GreedyClassLoader(ClassLoader parent) 58 { 59 super(NULL_URL_ARRAY); 60 _parent = parent; 61 } 62 63 public Class <?> loadClass(String name) 64 throws ClassNotFoundException 65 { 66 if (_classes.containsKey(name)) 67 return _classes.get(name); 68 69 return _parent.loadClass(name); 70 } 71 72 public Class <?> loadClassFile(File file, String packagePrefix) 73 throws IOException 74 { 75 String name = file.getName(); 76 String className = name.substring(0, name.length() - ".class".length()); 77 78 _buffer.clear(); 79 _buffer.ensureCapacity((int) file.length()); 80 81 Path path = Vfs.lookup(file.getPath()); 82 ReadStream rs = path.openRead(); 83 84 try { 85 rs.readAll(_buffer.getBuffer(), 0, (int) file.length()); 86 87 Class cl = defineClass(packagePrefix + "." + className, 88 _buffer.getBuffer(), 0, (int) file.length()); 89 90 if (packagePrefix == null) 91 _classes.put(className, cl); 92 else 93 _classes.put(packagePrefix + "." + className, cl); 94 95 return cl; 96 } 97 finally { 98 rs.close(); 99 } 100 } 101 102 public void loadClassFiles(File root) 103 throws IOException 104 { 105 loadClassFiles(root, null); 106 107 int startSize; 108 109 do { 112 startSize = _problemFiles.size(); 113 114 Iterator<Map.Entry<File,String >> i = _problemFiles.entrySet().iterator(); 115 116 while (i.hasNext()) { 117 try { 118 Map.Entry<File,String > problem = i.next(); 119 120 loadClassFile(problem.getKey(), problem.getValue()); 121 122 i.remove(); 123 } 124 catch (NoClassDefFoundError e) { 125 } 126 } 127 } 128 while (_problemFiles.size() < startSize); 129 } 130 131 public void loadClassFiles(File root, String packagePrefix) 132 throws IOException 133 { 134 if (root.isDirectory()) { 135 for (File child : root.listFiles()) { 136 143 if (packagePrefix == null) 144 loadClassFiles(child, ""); 145 else if ("".equals(packagePrefix)) 146 loadClassFiles(child, root.getName()); 147 else 148 loadClassFiles(child, packagePrefix + "." + root.getName()); 149 } 150 } 151 else { 152 if (root.getPath().endsWith(".class")) { 153 try { 154 loadClassFile(root, packagePrefix); 155 } 156 catch (NoClassDefFoundError e) { 157 _problemFiles.put(root, packagePrefix); 158 } 159 } 160 } 161 } 162 163 public Class [] getLoadedClasses() 164 { 165 return _classes.values().toArray(new Class [0]); 166 } 167 } 168 | Popular Tags |