List of usage examples for javax.script CompiledScript eval
public Object eval(Bindings bindings) throws ScriptException
CompiledScript
object using the supplied Bindings
of attributes as the ENGINE_SCOPE
of the associated ScriptEngine
during script execution. From source file:org.apache.accumulo.shell.commands.ScriptCommand.java
@Override public int execute(String fullCommand, CommandLine cl, Shell shellState) throws Exception { boolean invoke = false; ScriptEngineManager mgr = new ScriptEngineManager(); if (cl.hasOption(list.getOpt())) { listJSREngineInfo(mgr, shellState); } else if (cl.hasOption(file.getOpt()) || cl.hasOption(script.getOpt())) { String engineName = DEFAULT_ENGINE; if (cl.hasOption(engine.getOpt())) { engineName = cl.getOptionValue(engine.getOpt()); }/* w w w . java 2s.c om*/ ScriptEngine engine = mgr.getEngineByName(engineName); if (null == engine) { shellState.printException(new Exception(engineName + " not found")); return 1; } if (cl.hasOption(object.getOpt()) || cl.hasOption(function.getOpt())) { if (!(engine instanceof Invocable)) { shellState.printException( new Exception(engineName + " does not support invoking functions or methods")); return 1; } invoke = true; } ScriptContext ctx = new SimpleScriptContext(); // Put the following objects into the context so that they // are available to the scripts // TODO: What else should go in here? Bindings b = engine.getBindings(ScriptContext.ENGINE_SCOPE); b.put("connection", shellState.getConnector()); List<Object> argValues = new ArrayList<Object>(); if (cl.hasOption(args.getOpt())) { String[] argList = cl.getOptionValue(args.getOpt()).split(","); for (String arg : argList) { String[] parts = arg.split("="); if (parts.length == 0) { continue; } else if (parts.length == 1) { b.put(parts[0], null); argValues.add(null); } else if (parts.length == 2) { b.put(parts[0], parts[1]); argValues.add(parts[1]); } } } ctx.setBindings(b, ScriptContext.ENGINE_SCOPE); Object[] argArray = argValues.toArray(new Object[argValues.size()]); Writer writer = null; if (cl.hasOption(out.getOpt())) { File f = new File(cl.getOptionValue(out.getOpt())); writer = new FileWriter(f); ctx.setWriter(writer); } if (cl.hasOption(file.getOpt())) { File f = new File(cl.getOptionValue(file.getOpt())); if (!f.exists()) { if (null != writer) { writer.close(); } shellState.printException(new Exception(f.getAbsolutePath() + " not found")); return 1; } Reader reader = new FileReader(f); try { engine.eval(reader, ctx); if (invoke) { this.invokeFunctionOrMethod(shellState, engine, cl, argArray); } } catch (ScriptException ex) { shellState.printException(ex); return 1; } finally { reader.close(); if (null != writer) { writer.close(); } } } else if (cl.hasOption(script.getOpt())) { String inlineScript = cl.getOptionValue(script.getOpt()); try { if (engine instanceof Compilable) { Compilable compiledEng = (Compilable) engine; CompiledScript script = compiledEng.compile(inlineScript); script.eval(ctx); if (invoke) { this.invokeFunctionOrMethod(shellState, engine, cl, argArray); } } else { engine.eval(inlineScript, ctx); if (invoke) { this.invokeFunctionOrMethod(shellState, engine, cl, argArray); } } } catch (ScriptException ex) { shellState.printException(ex); return 1; } finally { if (null != writer) { writer.close(); } } } if (null != writer) { writer.close(); } } else { printHelp(shellState); } return 0; }
From source file:org.apache.jmeter.util.JSR223TestElement.java
/** * This method will run inline script or file script with special behaviour for file script: * - If ScriptEngine implements Compilable script will be compiled and cached * - If not if will be run/*w w w.ja va 2 s .c o m*/ * @param scriptEngine ScriptEngine * @param bindings {@link Bindings} might be null * @return Object returned by script * @throws IOException when reading the script fails * @throws ScriptException when compiling or evaluation of the script fails */ protected Object processFileOrScript(ScriptEngine scriptEngine, Bindings bindings) throws IOException, ScriptException { if (bindings == null) { bindings = scriptEngine.createBindings(); } populateBindings(bindings); File scriptFile = new File(getFilename()); // Hack: bsh-2.0b5.jar BshScriptEngine implements Compilable but throws "java.lang.Error: unimplemented" boolean supportsCompilable = scriptEngine instanceof Compilable && !(scriptEngine.getClass().getName().equals("bsh.engine.BshScriptEngine")); // $NON-NLS-1$ if (!StringUtils.isEmpty(getFilename())) { if (scriptFile.exists() && scriptFile.canRead()) { BufferedReader fileReader = null; try { if (supportsCompilable) { String cacheKey = getScriptLanguage() + "#" + // $NON-NLS-1$ scriptFile.getAbsolutePath() + "#" + // $NON-NLS-1$ scriptFile.lastModified(); CompiledScript compiledScript = compiledScriptsCache.get(cacheKey); if (compiledScript == null) { synchronized (compiledScriptsCache) { compiledScript = compiledScriptsCache.get(cacheKey); if (compiledScript == null) { // TODO Charset ? fileReader = new BufferedReader(new FileReader(scriptFile), (int) scriptFile.length()); compiledScript = ((Compilable) scriptEngine).compile(fileReader); compiledScriptsCache.put(cacheKey, compiledScript); } } } return compiledScript.eval(bindings); } else { // TODO Charset ? fileReader = new BufferedReader(new FileReader(scriptFile), (int) scriptFile.length()); return scriptEngine.eval(fileReader, bindings); } } finally { IOUtils.closeQuietly(fileReader); } } else { throw new ScriptException("Script file '" + scriptFile.getAbsolutePath() + "' does not exist or is unreadable for element:" + getName()); } } else if (!StringUtils.isEmpty(getScript())) { if (supportsCompilable && !StringUtils.isEmpty(cacheKey)) { computeScriptMD5(); CompiledScript compiledScript = compiledScriptsCache.get(this.scriptMd5); if (compiledScript == null) { synchronized (compiledScriptsCache) { compiledScript = compiledScriptsCache.get(this.scriptMd5); if (compiledScript == null) { compiledScript = ((Compilable) scriptEngine).compile(getScript()); compiledScriptsCache.put(this.scriptMd5, compiledScript); } } } return compiledScript.eval(bindings); } else { return scriptEngine.eval(getScript(), bindings); } } else { throw new ScriptException("Both script file and script text are empty for element:" + getName()); } }
From source file:org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngineOverGraphTest.java
@Test @LoadGraphWith(LoadGraphWith.GraphData.MODERN) public void shouldBeThreadSafeOnCompiledScript() throws Exception { final GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine(); final CompiledScript script = engine .compile("t = g.V().has('name',name); if(t.hasNext()) { t } else { null }"); int runs = 500; final CountDownLatch latch = new CountDownLatch(runs); final List<String> names = Arrays.asList("marko", "peter", "josh", "vadas", "stephen", "pavel", "matthias"); final Random random = new Random(); for (int i = 0; i < runs; i++) { new Thread("test-thread-safety-on-compiled-script-" + i) { public void run() { String name = names.get(random.nextInt(names.size() - 1)); try { final Bindings bindings = engine.createBindings(); bindings.put("g", g); bindings.put("name", name); Object result = script.eval(bindings); if (name.equals("stephen") || name.equals("pavel") || name.equals("matthias")) assertNull(result); else assertNotNull(result); } catch (ScriptException e) { //System.out.println(e); assertFalse(true);//from w w w .ja va 2s . c o m } finally { if (graph.features().graph().supportsTransactions()) g.tx().rollback(); } latch.countDown(); } }.start(); } latch.await(); }
From source file:org.nuxeo.automation.scripting.test.TestCompileAndContext.java
@Test public void testNashornWithCompile() throws Exception { ScriptEngineManager engineManager = new ScriptEngineManager(); ScriptEngine engine = engineManager.getEngineByName(AutomationScriptingConstants.NASHORN_ENGINE); assertNotNull(engine);//from w w w .j a v a 2s . com Compilable compiler = (Compilable) engine; assertNotNull(compiler); InputStream stream = this.getClass().getResourceAsStream("/testScript" + ".js"); assertNotNull(stream); String js = IOUtils.toString(stream); CompiledScript compiled = compiler.compile(new StringReader(js)); engine.put("mapper", new Mapper()); compiled.eval(engine.getContext()); assertEquals("1" + System.lineSeparator() + "str" + System.lineSeparator() + "[1, 2, {a=1, b=2}]" + System.lineSeparator() + "{a=1, b=2}" + System.lineSeparator() + "This is a string" + System.lineSeparator() + "This is a string" + System.lineSeparator() + "2" + System.lineSeparator() + "[A, B, C]" + System.lineSeparator() + "{a=salut, b=from java}" + System.lineSeparator() + "done" + System.lineSeparator(), outContent.toString()); }
From source file:org.nuxeo.ecm.core.redis.embedded.RedisEmbeddedLuaEngine.java
public Object evalsha(String sha, List<String> keys, List<String> args) throws ScriptException { final CompiledScript script = binaries.get(sha); Bindings bindings = engine.createBindings(); bindings.put("KEYS", keys.toArray(new String[keys.size()])); bindings.put("ARGV", args.toArray(new String[args.size()])); Object result = script.eval(bindings); if (result instanceof LuaValue) { LuaValue value = (LuaValue) result; if (value.isboolean() && value.toboolean() == false) { return null; }/* w w w . j a va 2s . c o m*/ return value.tojstring(); } return result; }
From source file:org.nuxeo.ecm.webengine.scripting.Scripting.java
protected Object _runScript(ScriptFile script, Map<String, Object> args) throws Exception { SimpleBindings bindings = new SimpleBindings(); if (args != null) { bindings.putAll(args);//from w ww .ja v a 2 s .c o m } String ext = script.getExtension(); // check for a script engine ScriptEngine engine = getEngineManager().getEngineByExtension(ext); if (engine != null) { ScriptContext ctx = new SimpleScriptContext(); ctx.setBindings(bindings, ScriptContext.ENGINE_SCOPE); CompiledScript comp = getCompiledScript(engine, script.getFile()); // use cache for compiled scripts if (comp != null) { return comp.eval(ctx); } // compilation not supported - eval it on the fly try { Reader reader = new FileReader(script.getFile()); try { // TODO use __result__ to pass return value for engine that doesn't returns like jython Object result = engine.eval(reader, ctx); if (result == null) { result = bindings.get("__result__"); } return result; } finally { reader.close(); } } catch (IOException e) { throw new ScriptException(e); } } return null; }
From source file:org.openhab.binding.ebus.internal.parser.EBusTelegramParser.java
/** * Evaluates the compiled script of a entry. * @param entry The configuration entry to evaluate * @param scopeValues All known values for script scope * @return The computed value/* w w w.j a v a 2s .c o m*/ * @throws ScriptException */ private Object evaluateScript(Entry<String, Map<String, Object>> entry, Map<String, Object> scopeValues) throws ScriptException { Object value = null; // executes compiled script if (entry.getValue().containsKey("cscript")) { CompiledScript cscript = (CompiledScript) entry.getValue().get("cscript"); // Add global variables thisValue and keyName to JavaScript context Bindings bindings = cscript.getEngine().createBindings(); bindings.putAll(scopeValues); value = cscript.eval(bindings); } // try to convert the returned value to BigDecimal value = ObjectUtils.defaultIfNull(NumberUtils.toBigDecimal(value), value); // round to two digits, maybe not optimal for any result if (value instanceof BigDecimal) { ((BigDecimal) value).setScale(2, BigDecimal.ROUND_HALF_UP); } return value; }
From source file:org.openhab.binding.ebus.parser.EBusTelegramParser.java
/** * @param entry/*from www . j a va 2 s .c o m*/ * @param bindings2 * @return * @throws ScriptException */ private Object evaluateScript(Entry<String, Map<String, Object>> entry, Map<String, Object> bindings2) throws ScriptException { Object value = null; if (entry.getValue().containsKey("cscript")) { CompiledScript cscript = (CompiledScript) entry.getValue().get("cscript"); // Add global variables thisValue and keyName to JavaScript context Bindings bindings = cscript.getEngine().createBindings(); bindings.putAll(bindings2); value = cscript.eval(bindings); } value = ObjectUtils.defaultIfNull(NumberUtils.toBigDecimal(value), value); // round to two digits, maybe not optimal for any result if (value instanceof BigDecimal) { ((BigDecimal) value).setScale(2, BigDecimal.ROUND_HALF_UP); } return value; }
From source file:org.trafodion.rest.script.ScriptManager.java
public void runScript(ScriptContext ctx) { String scriptName;//from ww w . j a v a2 s .com if (ctx.getScriptName().length() == 0) scriptName = DEFAULT_SCRIPT_NAME; else if (!ctx.getScriptName().endsWith(".py")) scriptName = ctx.getScriptName() + PYTHON_SUFFIX; else scriptName = ctx.getScriptName(); try { ScriptEngine engine = manager.getEngineByName("python"); Bindings bindings = engine.createBindings(); bindings.put("scriptcontext", ctx); if (engine instanceof Compilable) { CompiledScript script = m.get(scriptName); if (script == null) { LOG.info("Compiling script " + scriptName); Compilable compilingEngine = (Compilable) engine; try { script = compilingEngine.compile(new FileReader(restHome + "/bin/scripts/" + scriptName)); } catch (Exception e) { LOG.warn(e.getMessage()); } m.put(scriptName, script); } script.eval(bindings); } else { try { engine.eval(new FileReader(restHome + "/bin/scripts/" + scriptName), bindings); } catch (Exception e) { LOG.warn(e.getMessage()); } } } catch (javax.script.ScriptException se) { LOG.warn(se.getMessage()); } }
From source file:ru.iris.events.EventsService.java
public EventsService() { Status status = new Status("Events"); if (status.checkExist()) { status.running();//from w ww.j av a 2s . c om } else { status.addIntoDB("Events", "Service that listen for events and exec scripts as needed"); } try { events = Ebean.find(Event.class).findList(); // take pause to save/remove new entity try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } // load all scripts, compile and put into map compiledScriptMap = loadAndCompile(events); // Pass jsonmessaging instance to js engine Bindings bindings = new SimpleBindings(); bindings.put("jsonMessaging", jsonMessaging); bindings.put("LOGGER", scriptLogger); // subscribe to events from db for (Event event : events) { jsonMessaging.subscribe(event.getSubject()); LOGGER.debug("Subscribe to subject: " + event.getSubject()); } // command launch jsonMessaging.subscribe("event.command"); // scripts jsonMessaging.subscribe("event.script.get"); jsonMessaging.subscribe("event.script.save"); jsonMessaging.subscribe("event.script.delete"); jsonMessaging.subscribe("event.script.list"); jsonMessaging.subscribe("event.reload"); jsonMessaging.setNotification(new JsonNotification() { @Override public void onNotification(JsonEnvelope envelope) { LOGGER.debug("Got envelope with subject: " + envelope.getSubject()); try { // Get script content if (envelope.getObject() instanceof EventGetScriptAdvertisement) { LOGGER.debug("Return JS script to: " + envelope.getReceiverInstance()); EventGetScriptAdvertisement advertisement = envelope.getObject(); File jsFile; if (advertisement.isCommand()) jsFile = new File("./scripts/command/" + advertisement.getName()); else jsFile = new File("./scripts/" + advertisement.getName()); jsonMessaging.response(envelope, new EventResponseGetScriptAdvertisement(FileUtils.readFileToString(jsFile))); } // Save new/existing script else if (envelope.getObject() instanceof EventResponseSaveScriptAdvertisement) { EventResponseSaveScriptAdvertisement advertisement = envelope.getObject(); LOGGER.debug("Request to save changes: " + advertisement.getName()); File jsFile; if (advertisement.isCommand()) jsFile = new File("./scripts/command/" + advertisement.getName()); else jsFile = new File("./scripts/" + advertisement.getName()); FileUtils.writeStringToFile(jsFile, advertisement.getBody()); LOGGER.info("Restart event service (reason: script change)"); reloadService(); } // Remove script else if (envelope.getObject() instanceof EventRemoveScriptAdvertisement) { EventRemoveScriptAdvertisement advertisement = envelope.getObject(); LOGGER.debug("Request to remove script: " + advertisement.getName()); File jsFile; if (advertisement.isCommand()) jsFile = new File("./scripts/command/" + advertisement.getName()); else jsFile = new File("./scripts/" + advertisement.getName()); FileUtils.forceDelete(jsFile); LOGGER.info("Restart event service (reason: script removed)"); reloadService(); } // List available scripts else if (envelope.getObject() instanceof EventListScriptsAdvertisement) { EventListScriptsAdvertisement advertisement = envelope.getObject(); File jsFile; if (advertisement.isCommand()) jsFile = new File("./scripts/command/"); else jsFile = new File("./scripts/"); EventResponseListScriptsAdvertisement response = new EventResponseListScriptsAdvertisement(); response.setScripts( (List<File>) FileUtils.listFiles(jsFile, new String[] { "js" }, false)); jsonMessaging.response(envelope, response); } // Check command and launch script else if (envelope.getObject() instanceof CommandAdvertisement) { CommandAdvertisement advertisement = envelope.getObject(); bindings.put("advertisement", envelope.getObject()); if (compiledCommandScriptMap.get(advertisement.getScript()) == null) { LOGGER.debug("Compile command script: " + advertisement.getScript()); File jsFile = new File("./scripts/command/" + advertisement.getScript()); CompiledScript compile = engine.compile(FileUtils.readFileToString(jsFile)); compiledCommandScriptMap.put(advertisement.getScript(), compile); LOGGER.debug("Launch compiled command script: " + advertisement.getScript()); compile.eval(bindings); } else { LOGGER.info("Launch compiled command script: " + advertisement.getScript()); compiledCommandScriptMap.get(advertisement.getScript()).eval(bindings); } } else if (envelope.getObject() instanceof EventChangesAdvertisement) { reloadService(); } else { for (Event event : events) { if (envelope.getSubject().equals(event.getSubject()) || wildCardMatch(event.getSubject(), envelope.getSubject())) { LOGGER.debug("Run compiled script: " + event.getScript()); try { bindings.put("advertisement", envelope.getObject()); CompiledScript script = compiledScriptMap.get(event.getScript()); if (script != null) script.eval(bindings); else LOGGER.error("Error! Script " + event.getScript() + " is NULL!"); } catch (ScriptException e) { LOGGER.error("Error in script scripts/command/" + event.getScript() + ": " + e.toString()); e.printStackTrace(); } } } } } catch (ScriptException | IOException e) { LOGGER.error("Error in script: " + e.toString()); e.printStackTrace(); } } }); jsonMessaging.start(); } catch (final RuntimeException t) { LOGGER.error("Error in Events!"); status.crashed(); t.printStackTrace(); } }