1 22 package org.jboss.util.loading; 23 24 import java.security.AccessController ; 25 import java.security.PrivilegedAction ; 26 27 43 public class ContextClassLoaderSwitcher 44 extends ContextClassLoader 45 { 46 49 public static final RuntimePermission SETCONTEXTCLASSLOADER = new RuntimePermission ("setContextClassLoader"); 50 51 54 public static final NewInstance INSTANTIATOR = new NewInstance(); 55 56 60 private ContextClassLoaderSwitcher() 61 { 62 super(); 63 SecurityManager manager = System.getSecurityManager(); 64 if (manager != null) 65 manager.checkPermission(SETCONTEXTCLASSLOADER); 66 } 67 68 73 public void setContextClassLoader(final ClassLoader cl) 74 { 75 setContextClassLoader(Thread.currentThread(), cl); 76 } 77 78 84 public void setContextClassLoader(final Thread thread, final ClassLoader cl) 85 { 86 AccessController.doPrivileged(new PrivilegedAction () 87 { 88 public Object run() 89 { 90 thread.setContextClassLoader(cl); 91 return null; 92 } 93 }); 94 } 95 96 101 public SwitchContext getSwitchContext() 102 { 103 return new SwitchContext(); 104 } 105 106 112 public SwitchContext getSwitchContext(final ClassLoader cl) 113 { 114 return new SwitchContext(cl); 115 } 116 117 126 public SwitchContext getSwitchContext(final Class clazz) 127 { 128 return new SwitchContext(clazz.getClassLoader()); 129 } 130 131 135 public class SwitchContext 136 { 137 140 private ClassLoader origCL; 141 142 145 private ClassLoader currentCL; 146 147 150 private Thread currentThread; 151 152 private SwitchContext() 153 { 154 currentThread = Thread.currentThread(); 155 origCL = getContextClassLoader(currentThread); 156 currentCL = origCL; 157 } 158 159 private SwitchContext(ClassLoader cl) 160 { 161 this(); 162 setClassLoader(cl); 163 } 164 165 168 public Thread getThread() 169 { 170 return currentThread; 171 } 172 173 176 public ClassLoader getOriginalClassLoader() 177 { 178 return origCL; 179 } 180 181 185 public ClassLoader getCurrentClassLoader() 186 { 187 return currentCL; 188 } 189 190 198 public void setClassLoader(ClassLoader cl) 199 { 200 if (cl != null && cl != currentCL) 201 { 202 setContextClassLoader(currentThread, cl); 203 currentCL = cl; 204 } 205 } 206 207 211 public void reset() 212 { 213 if (currentCL != null && currentCL != origCL) 214 setContextClassLoader(currentThread, origCL); 215 } 216 217 222 public void forceReset() 223 { 224 setContextClassLoader(currentThread, origCL); 225 } 226 } 227 228 private static class NewInstance 229 implements PrivilegedAction 230 { 231 public Object run() 232 { 233 return new ContextClassLoaderSwitcher(); 234 } 235 } 236 } 237 | Popular Tags |