1 22 package org.jboss.test.classloader; 23 24 import java.io.IOException ; 25 import java.net.URL ; 26 import java.util.ArrayList ; 27 import java.util.Enumeration ; 28 import java.util.List ; 29 30 import org.jboss.util.collection.Iterators; 31 32 38 public class FilteringClassLoader extends ClassLoader 39 { 40 41 private String [] packages; 42 43 44 private String [] paths; 45 46 47 private String [] urls; 48 49 55 public FilteringClassLoader(ClassLoader parent, String [] packages) 56 { 57 super(parent); 58 if (packages == null) 59 throw new IllegalArgumentException ("Null packages"); 60 this.packages = packages; 61 62 paths = new String [packages.length]; 64 for (int i = 0; i < packages.length; ++i) 65 paths[i] = packages[i].replace('.', '/'); 66 67 try 69 { 70 Enumeration <URL > enumeration = super.getResources(""); 71 List <URL > rootURLs = new ArrayList <URL >(); 72 while (enumeration.hasMoreElements()) 73 rootURLs.add(enumeration.nextElement()); 74 urls = new String [paths.length * rootURLs.size()]; 75 int i = 0; 76 for (String path : paths) 77 { 78 for (URL rootURL : rootURLs) 79 urls[i++] = new URL (rootURL, path).toString(); 80 } 81 } 82 catch (Exception e) 83 { 84 throw new RuntimeException ("Error determining classloader urls", e); 85 } 86 } 87 88 @Override 89 protected synchronized Class <?> loadClass(String name, boolean resolve) throws ClassNotFoundException 90 { 91 for (String pkg : packages) 92 { 93 if (name.startsWith(pkg)) 94 throw new ClassNotFoundException ("Class not found (filtered): " + name); 95 } 96 return super.loadClass(name, resolve); 97 } 98 99 @Override 100 public URL getResource(String name) 101 { 102 for (String path : paths) 103 { 104 if (name.startsWith(path)) 105 return null; 106 } 107 return super.getResource(name); 108 } 109 110 @SuppressWarnings ("unchecked") 111 @Override 112 public Enumeration <URL > getResources(String name) throws IOException 113 { 114 Enumeration <URL > unfiltered = super.getResources(name); 115 List <URL > filtered = new ArrayList <URL >(); 116 while (unfiltered.hasMoreElements()) 117 { 118 URL next = unfiltered.nextElement(); 119 boolean ignore =false; 120 for (String url : urls) 121 { 122 if (next.toString().startsWith(url)) 123 ignore = true; 124 } 125 if (ignore == false) 126 filtered.add(next); 127 } 128 return Iterators.toEnumeration(filtered.iterator()); 129 } 130 } 131 | Popular Tags |