1 18 19 package org.apache.tools.ant.util.optional; 20 21 import org.apache.tools.ant.BuildException; 22 23 24 import java.util.Iterator ; 25 import org.apache.tools.ant.util.ScriptRunnerBase; 26 import org.apache.tools.ant.util.ReflectUtil; 27 import org.apache.tools.ant.util.ReflectWrapper; 28 29 33 public class JavaxScriptRunner extends ScriptRunnerBase { 34 private ReflectWrapper engine; 35 36 40 public String getManagerName() { 41 return "javax"; 42 } 43 44 45 public boolean supportsLanguage() { 46 if (engine != null) { 47 return true; 48 } 49 checkLanguage(); 50 ClassLoader origLoader = replaceContextLoader(); 51 try { 52 return createEngine() != null; 53 } catch (Exception ex) { 54 return false; 55 } finally { 56 restoreContextLoader(origLoader); 57 } 58 } 59 60 68 public void executeScript(String execName) throws BuildException { 69 evaluateScript(execName); 70 } 71 72 80 public Object evaluateScript(String execName) throws BuildException { 81 checkLanguage(); 82 ClassLoader origLoader = replaceContextLoader(); 83 try { 84 ReflectWrapper engine = createEngine(); 85 if (engine == null) { 86 throw new BuildException( 87 "Unable to create javax script engine for " 88 + getLanguage()); 89 } 90 for (Iterator i = getBeans().keySet().iterator(); i.hasNext();) { 91 String key = (String ) i.next(); 92 Object value = getBeans().get(key); 93 engine.invoke( 94 "put", String .class, key, Object .class, value); 95 } 96 return engine.invoke("eval", String .class, getScript()); 98 } catch (Exception be) { 99 Throwable t = be; 100 Throwable te = (Throwable ) ReflectUtil.invoke(be, "getCause"); 101 if (te != null) { 102 if (te instanceof BuildException) { 103 throw (BuildException) te; 104 } else { 105 t = te; 106 } 107 } 108 throw new BuildException(t); 109 } finally { 110 restoreContextLoader(origLoader); 111 } 112 } 113 114 private ReflectWrapper createEngine() throws Exception { 115 if (engine != null) { 116 return engine; 117 } 118 ReflectWrapper manager = new ReflectWrapper( 119 getClass().getClassLoader(), "javax.script.ScriptEngineManager"); 120 Object e = manager.invoke( 121 "getEngineByName", String .class, getLanguage()); 122 if (e == null) { 123 return null; 124 } 125 ReflectWrapper ret = new ReflectWrapper(e); 126 if (getKeepEngine()) { 127 this.engine = ret; 128 } 129 return ret; 130 } 131 } 132 | Popular Tags |