List of usage examples for javax.script CompiledScript eval
public Object eval() throws ScriptException
CompiledScript
object. From source file:CompilableDemo.java
public static void main(String[] args) throws Exception { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("js"); Compilable jsCompile = (Compilable) engine; CompiledScript script = jsCompile.compile("function hi () {print ('www.java2s.com !'); }; hi ();"); for (int i = 0; i < 5; i++) { script.eval(); }/*from w w w. j ava 2 s . c o m*/ }
From source file:CompileTest.java
public static void main(String args[]) { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("javascript"); engine.put("counter", 0); if (engine instanceof Compilable) { Compilable compEngine = (Compilable) engine; try {//from ww w.j av a2 s . c o m CompiledScript script = compEngine .compile("function count(){counter=counter+1;return counter;}; count();"); System.out.println(script.eval()); System.out.println(script.eval()); System.out.println(script.eval()); } catch (ScriptException e) { System.err.println(e); } } else { System.err.println("Engine can't compile code"); } }
From source file:TestCompilationSpeed.java
public static void main(String[] args) throws Exception { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); String fact = "function fact (n){if (n == 0)return 1; else return n*fact (n-1);};"; long time = System.currentTimeMillis(); for (int i = 0; i < MAX_ITERATIONS; i++) engine.eval(fact);//from w ww . ja v a2s . com System.out.println(System.currentTimeMillis() - time); Compilable compilable = null; if (engine instanceof Compilable) { compilable = (Compilable) engine; CompiledScript script = compilable.compile(fact); time = System.currentTimeMillis(); for (int i = 0; i < MAX_ITERATIONS; i++) script.eval(); System.out.println(System.currentTimeMillis() - time); } }
From source file:org.red5.server.script.rhino.RhinoScriptUtils.java
/** * Create a new Rhino-scripted object from the given script source. * /*from ww w. j av a 2 s. c om*/ * @param scriptSource * the script source text * @param interfaces * the interfaces that the scripted Java object is supposed to * implement * @param extendedClass * @return the scripted Java object * @throws ScriptCompilationException * in case of Rhino parsing failure * @throws java.io.IOException */ @SuppressWarnings("rawtypes") public static Object createRhinoObject(String scriptSource, Class[] interfaces, Class extendedClass) throws ScriptCompilationException, IOException, Exception { if (log.isDebugEnabled()) { log.debug("Script Engine Manager: " + mgr.getClass().getName()); } ScriptEngine engine = mgr.getEngineByExtension("js"); if (null == engine) { log.warn("Javascript is not supported in this build"); } // set engine scope namespace Bindings nameSpace = engine.getBindings(ScriptContext.ENGINE_SCOPE); // add the logger to the script nameSpace.put("log", log); // compile the wrapper script CompiledScript wrapper = ((Compilable) engine).compile(jsWrapper); nameSpace.put("Wrapper", wrapper); // get the function name ie. class name / ctor String funcName = RhinoScriptUtils.getFunctionName(scriptSource); if (log.isDebugEnabled()) { log.debug("New script: " + funcName); } // set the 'filename' nameSpace.put(ScriptEngine.FILENAME, funcName); if (null != interfaces) { nameSpace.put("interfaces", interfaces); } if (null != extendedClass) { if (log.isDebugEnabled()) { log.debug("Extended: " + extendedClass.getName()); } nameSpace.put("supa", extendedClass.newInstance()); } // // compile the script CompiledScript script = ((Compilable) engine).compile(scriptSource); // eval the script with the associated namespace Object o = null; try { o = script.eval(); } catch (Exception e) { log.error("Problem evaluating script", e); } if (log.isDebugEnabled()) { log.debug("Result of script call: " + o); } // script didnt return anything we can use so try the wrapper if (null == o) { wrapper.eval(); } else { wrapper.eval(); o = ((Invocable) engine).invokeFunction("Wrapper", new Object[] { engine.get(funcName) }); if (log.isDebugEnabled()) { log.debug("Result of invokeFunction: " + o); } } return Proxy.newProxyInstance(ClassUtils.getDefaultClassLoader(), interfaces, new RhinoObjectInvocationHandler(engine, o)); }
From source file:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutorTest.java
@Test public void shouldCompileScript() throws Exception { final GremlinExecutor gremlinExecutor = GremlinExecutor.build().create(); final CompiledScript script = gremlinExecutor.compile("1+1").get(); assertEquals(2, script.eval()); gremlinExecutor.close();// ww w . ja va 2 s .c o m }
From source file:org.unitime.timetable.server.script.ScriptExecution.java
@Override protected void execute() throws Exception { org.hibernate.Session hibSession = ScriptDAO.getInstance().getSession(); Transaction tx = hibSession.beginTransaction(); try {//from ww w . j a va 2 s . com setStatus("Starting up...", 3); Script script = ScriptDAO.getInstance().get(iRequest.getScriptId(), hibSession); ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName(script.getEngine()); engine.put("hibSession", hibSession); engine.put("session", SessionDAO.getInstance().get(getSessionId())); engine.put("log", this); incProgress(); engine.getContext().setWriter(new Writer() { @Override public void write(char[] cbuf, int off, int len) throws IOException { String line = String.valueOf(cbuf, off, len); if (line.endsWith("\n")) line = line.substring(0, line.length() - 1); if (!line.isEmpty()) info(line); } @Override public void flush() throws IOException { } @Override public void close() throws IOException { } }); engine.getContext().setErrorWriter(new Writer() { @Override public void write(char[] cbuf, int off, int len) throws IOException { String line = String.valueOf(cbuf, off, len); if (line.endsWith("\n")) line = line.substring(0, line.length() - 1); if (!line.isEmpty()) warn(line); } @Override public void flush() throws IOException { } @Override public void close() throws IOException { } }); incProgress(); debug("Engine: " + engine.getFactory().getEngineName() + " (ver. " + engine.getFactory().getEngineVersion() + ")"); debug("Language: " + engine.getFactory().getLanguageName() + " (ver. " + engine.getFactory().getLanguageVersion() + ")"); for (ScriptParameter parameter : script.getParameters()) { String value = iRequest.getParameters().get(parameter.getName()); if ("file".equals(parameter.getType()) && iFile != null) { debug(parameter.getName() + ": " + iFile.getName() + " (" + iFile.getSize() + " bytes)"); engine.put(parameter.getName(), iFile); continue; } if (value == null) value = parameter.getDefaultValue(); if (value == null) { engine.put(parameter.getName(), null); continue; } debug(parameter.getName() + ": " + value); if (parameter.getType().equalsIgnoreCase("boolean")) { engine.put(parameter.getName(), "true".equalsIgnoreCase(value)); } else if (parameter.getType().equalsIgnoreCase("long")) { engine.put(parameter.getName(), Long.valueOf(value)); } else if (parameter.getType().equalsIgnoreCase("int") || parameter.getType().equalsIgnoreCase("integer")) { engine.put(parameter.getName(), Integer.valueOf(value)); } else if (parameter.getType().equalsIgnoreCase("double")) { engine.put(parameter.getName(), Double.valueOf(value)); } else if (parameter.getType().equalsIgnoreCase("float")) { engine.put(parameter.getName(), Float.valueOf(value)); } else if (parameter.getType().equalsIgnoreCase("short")) { engine.put(parameter.getName(), Short.valueOf(value)); } else if (parameter.getType().equalsIgnoreCase("byte")) { engine.put(parameter.getName(), Byte.valueOf(value)); } else if (parameter.getType().equalsIgnoreCase("department")) { engine.put(parameter.getName(), DepartmentDAO.getInstance().get(Long.valueOf(value), hibSession)); } else if (parameter.getType().equalsIgnoreCase("departments")) { List<Department> departments = new ArrayList<Department>(); for (String id : value.split(",")) if (!id.isEmpty()) departments.add(DepartmentDAO.getInstance().get(Long.valueOf(id), hibSession)); engine.put(parameter.getName(), departments); } else if (parameter.getType().equalsIgnoreCase("subject")) { engine.put(parameter.getName(), SubjectAreaDAO.getInstance().get(Long.valueOf(value), hibSession)); } else if (parameter.getType().equalsIgnoreCase("subjects")) { List<SubjectArea> subjects = new ArrayList<SubjectArea>(); for (String id : value.split(",")) if (!id.isEmpty()) subjects.add(SubjectAreaDAO.getInstance().get(Long.valueOf(id), hibSession)); engine.put(parameter.getName(), subjects); } else if (parameter.getType().equalsIgnoreCase("building")) { engine.put(parameter.getName(), BuildingDAO.getInstance().get(Long.valueOf(value), hibSession)); } else if (parameter.getType().equalsIgnoreCase("buildings")) { List<Building> buildings = new ArrayList<Building>(); for (String id : value.split(",")) if (!id.isEmpty()) buildings.add(BuildingDAO.getInstance().get(Long.valueOf(id), hibSession)); engine.put(parameter.getName(), buildings); } else if (parameter.getType().equalsIgnoreCase("room")) { engine.put(parameter.getName(), RoomDAO.getInstance().get(Long.valueOf(value), hibSession)); } else if (parameter.getType().equalsIgnoreCase("rooms")) { List<Room> rooms = new ArrayList<Room>(); for (String id : value.split(",")) if (!id.isEmpty()) rooms.add(RoomDAO.getInstance().get(Long.valueOf(id), hibSession)); engine.put(parameter.getName(), rooms); } else if (parameter.getType().equalsIgnoreCase("location")) { engine.put(parameter.getName(), LocationDAO.getInstance().get(Long.valueOf(value), hibSession)); } else if (parameter.getType().equalsIgnoreCase("locations")) { List<Location> locations = new ArrayList<Location>(); for (String id : value.split(",")) if (!id.isEmpty()) locations.add(LocationDAO.getInstance().get(Long.valueOf(id), hibSession)); engine.put(parameter.getName(), locations); } else { engine.put(parameter.getName(), value); } } incProgress(); if (engine instanceof Compilable) { setStatus("Compiling script...", 1); CompiledScript compiled = ((Compilable) engine).compile(script.getScript()); incProgress(); setStatus("Running script...", 100); compiled.eval(); } else { setStatus("Running script...", 100); engine.eval(script.getScript()); } hibSession.flush(); tx.commit(); setStatus("All done.", 1); incProgress(); } catch (Exception e) { tx.rollback(); error("Execution failed: " + e.getMessage(), e); } finally { hibSession.close(); } }
From source file:velo.scripting.ScriptingManager.java
public static void main(String[] args) throws FactoryException { //ScriptingManager sm = new ScriptingManager(); //ScriptEngine se = sm.getScriptEngine("groovy"); ScriptEngine se = ScriptingManager.getScriptEngine("groovy"); OperationContext oc = new OperationContext(); se.put("name", "moshe"); se.put("cntx", oc); //String a = "<?xml version=\"1.0\"?><j:jelly trim=\"false\" xmlns:j=\"jelly:core\" xmlns:x=\"jelly:xml\" xmlns:html=\"jelly:html\"><html><head><title>${name}'s Page</title></head></html></j:jelly>"; //String a = "def a = new Date(); println(a.getClass().getName()); def myArr = new Date[1]; myArr[0] = a; println(myArr.getClass().getName()); cntx.addVar('myArr',myArr);"; String a = "def a = new Date(); a.getClass().getName(); def myArr = new Date[1]; myArr[0] = a; myArr.getClass().getName(); cntx.addVar('myArr',myArr);"; //Sadly it seems that invoking via se.eval and script.eval almost return the same times, thought it should be much more effecient :/ try {/*from w ww . j av a 2 s . c om*/ //groovy //se.eval("println(name);"); StopWatch sw = new StopWatch(); sw.start(); for (int i = 0; i < 100000; i++) { se.eval(a); } sw.stop(); System.out.println("time in seconds: '" + sw.getTime() / 1000 + "'"); sw.reset(); sw.start(); CompiledScript script = ((Compilable) se).compile(a); for (int i = 0; i < 100000; i++) { script.eval(); } sw.stop(); System.out.println("time in seconds: '" + sw.getTime() / 1000 + "'"); OperationContext getOc = (OperationContext) se.get("cntx"); Date[] arrOfDate = (Date[]) getOc.get("myArr"); //System.out.println(arrOfDate); } catch (ScriptException e) { System.out.println("ERROR: " + e); } }