1 28 29 33 package net.sf.jasperreports.engine.design; 34 35 import java.io.Serializable ; 36 import java.util.Map ; 37 38 import org.apache.commons.collections.ReferenceMap; 39 40 import net.sf.jasperreports.engine.JRException; 41 import net.sf.jasperreports.engine.fill.JREvaluator; 42 import net.sf.jasperreports.engine.util.JRClassLoader; 43 44 45 49 public abstract class JRAbstractJavaCompiler extends JRAbstractCompiler 50 { 51 52 private static ThreadLocal classFromBytesRef = new ThreadLocal (); 55 56 57 private static Object CLASS_CACHE_NULL_KEY = new Object (); 58 private static Map classCache = new ReferenceMap(ReferenceMap.WEAK, ReferenceMap.SOFT); 59 60 61 protected JRAbstractJavaCompiler(boolean needsSourceFiles) 62 { 63 super(needsSourceFiles); 64 } 65 66 67 protected JREvaluator loadEvaluator(Serializable compileData, String className) throws JRException 68 { 69 JREvaluator evaluator = null; 70 71 try 72 { 73 Class clazz = getClassFromCache(className); 74 if (clazz == null) 75 { 76 clazz = JRClassLoader.loadClassFromBytes(className, (byte[]) compileData); 77 putClassInCache(className, clazz); 78 } 79 80 classFromBytesRef.set(clazz); 82 83 evaluator = (JREvaluator) clazz.newInstance(); 84 } 85 catch (Exception e) 86 { 87 throw new JRException("Error loading expression class : " + className, e); 88 } 89 90 return evaluator; 91 } 92 93 94 protected static Object classCacheKey() 95 { 96 ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); 97 Object key = contextClassLoader == null ? CLASS_CACHE_NULL_KEY : contextClassLoader; 98 return key; 99 } 100 101 102 protected static synchronized Class getClassFromCache(String className) 103 { 104 Object key = classCacheKey(); 105 Map contextMap = (Map ) classCache.get(key); 106 Class cachedClass = null; 107 if (contextMap != null) 108 { 109 cachedClass = (Class ) contextMap.get(className); 110 } 111 return cachedClass; 112 } 113 114 115 protected static synchronized void putClassInCache(String className, Class loadedClass) 116 { 117 Object key = classCacheKey(); 118 Map contextMap = (Map ) classCache.get(key); 119 if (contextMap == null) 120 { 121 contextMap = new ReferenceMap(ReferenceMap.HARD, ReferenceMap.SOFT); 122 classCache.put(key, contextMap); 123 } 124 contextMap.put(className, loadedClass); 125 } 126 } 127 | Popular Tags |