1 16 package scriptella.driver.janino; 17 18 import org.codehaus.janino.Scanner; 19 import org.codehaus.janino.ScriptEvaluator; 20 import scriptella.spi.Resource; 21 import scriptella.util.ExceptionUtils; 22 import scriptella.util.IOUtils; 23 24 import java.io.BufferedReader ; 25 import java.io.IOException ; 26 import java.io.Reader ; 27 import java.util.IdentityHashMap ; 28 import java.util.Map ; 29 30 36 final class CodeCompiler { 37 private static final Class [] THROWN_EXCEPTIONS = new Class []{Exception .class}; 39 private Map <Resource, Object > objectCache = new IdentityHashMap <Resource, Object >(); 41 42 public JaninoScript compileScript(final Resource resource) { 43 return (JaninoScript) compile(resource, false); 44 } 45 46 public JaninoQuery compileQuery(final Resource resource) { 47 return (JaninoQuery) compile(resource, true); 48 } 49 50 private Object compile(final Resource content, final boolean query) { 51 Object ctx = objectCache.get(content); 52 if (ctx == null) { 53 ScriptEvaluator evaluator = new ScriptEvaluator(); 54 evaluator.setThrownExceptions(THROWN_EXCEPTIONS); 56 evaluator.setParentClassLoader(getClass().getClassLoader()); 57 Class <?> type = query ? JaninoQuery.class : JaninoScript.class; 58 evaluator.setExtendedType(type); 59 evaluator.setStaticMethod(false); 60 evaluator.setMethodName("execute"); 61 evaluator.setClassName(type.getName()+"_Generated"); 62 63 Reader r = null; 64 try { 65 r = content.open(); 66 evaluator.cook(content.toString(), r); 67 } catch (Exception e) { 68 throw guestErrorStatement(new JaninoProviderException("Compilation failed", e), content); 69 } finally { 70 IOUtils.closeSilently(r); 71 } 72 Class <?> cl = evaluator.getMethod().getDeclaringClass(); 73 try { 74 ctx = cl.newInstance(); 75 } catch (Exception e) { 76 throw new JaninoProviderException("Unable to instantiate compiled class", e); 77 } 78 objectCache.put(content, ctx); 79 } 80 return ctx; 81 } 82 83 86 private static JaninoProviderException guestErrorStatement(JaninoProviderException pe, Resource r) { 87 Throwable cause = pe.getCause(); 88 if (cause instanceof Scanner.LocatedException) { 89 Scanner.LocatedException le = (Scanner.LocatedException) cause; 90 if (le.getLocation() != null) { 91 String line = getLine(r, le.getLocation().getLineNumber()); 92 pe.setErrorStatement(line); 93 } 94 } 95 return pe; 96 } 97 98 static String getLine(Resource resource, int line) { 99 BufferedReader r = null; 100 try { 101 r = new BufferedReader (resource.open()); 102 for (int i = 0; i < line - 1; i++) { 103 if (r.readLine() == null) { 104 return null; 105 } 106 } 107 return r.readLine(); 108 } catch (IOException e) { 109 ExceptionUtils.ignoreThrowable(e); 110 } finally { 111 IOUtils.closeSilently(r); 112 } 113 return null; 114 115 } 116 117 118 } 119 | Popular Tags |