1 package alt.jiapi.util; 2 3 import java.io.File ; 4 import java.io.FilenameFilter ; 5 import java.util.HashMap ; 6 import java.util.StringTokenizer ; 7 8 import alt.jiapi.Instrumentor; 9 import alt.jiapi.instrumentor.Strategy; 10 11 14 public class SymbolMap { 15 private HashMap map; 16 17 20 public static void main(String [] args) { 21 SymbolMap sm = new SymbolMap("alt.jiapi.instrumentor"); 22 System.out.println(sm); 23 } 24 25 26 public SymbolMap() { 27 map = new HashMap (); 28 } 29 30 39 public SymbolMap(String pkg) { 40 this(); 41 42 addPackage(pkg); 43 } 44 45 public void addPackage(String pkg) { 46 String classPath = System.getProperty("java.class.path"); 47 StringTokenizer st = new StringTokenizer (classPath,File.pathSeparator); 48 49 while(st.hasMoreTokens()) { 50 String pathItem = st.nextToken(); 51 resolveClassPathItem(pathItem, pkg); 52 } 53 } 54 55 public void addSymbol(String name, String value) { 56 if(value == null) { 57 throw new NullPointerException ("value is null"); 58 } 59 60 map.put(name, value); 61 } 62 63 public String getSymbol(String name) { 64 return (String )map.get(name); 65 } 66 67 68 private void resolveClassPathItem(String item, String pkg) { 69 File f = new File (item); 70 if (!f.exists()) { 71 return; 72 } 73 74 StringTokenizer st = new StringTokenizer (pkg, "."); 75 if (f.isDirectory()) { 76 String dir = item; 77 while(st.hasMoreTokens()) { 78 String s = st.nextToken(); 79 dir += File.separator + s; 80 f = new File (dir); 81 if (!f.exists()) { 82 return; 83 } 84 } 85 86 if (!f.isDirectory()) { 87 return; 88 } 89 90 String [] fileNames = f.list(new Filter (".class")); 91 Class instrumentorClass = Instrumentor.class; 92 Class strategyClass = Strategy.class; 93 94 for(int i = 0; i < fileNames.length; i++) { 95 String fileName = fileNames[i].substring(0, fileNames[i].lastIndexOf('.')); 96 97 Class c = null; 98 try { 99 c = Class.forName(pkg + "." + fileName); 100 } 101 catch (Exception e) { 102 e.printStackTrace(); 103 continue; 104 } 105 106 if (instrumentorClass.isAssignableFrom(c)) { 107 map.put(fileName, pkg + "." + fileName); 108 } 109 if (strategyClass.isAssignableFrom(c)) { 110 map.put(fileName, pkg + "." + fileName); 111 } 112 } 113 } 114 } 115 116 private class Filter implements FilenameFilter { 117 private String suffix; 118 public Filter(String suffix) { 119 this.suffix = suffix; 120 } 121 122 public boolean accept(File dir, String name) { 123 if (name.endsWith(suffix)) { 124 return true; 125 } 126 127 return false; 128 } 129 } 130 131 132 public String toString() { 133 return map.toString(); 134 } 135 } 136 137 138 | Popular Tags |