Example usage for javax.script ScriptEngine put

List of usage examples for javax.script ScriptEngine put

Introduction

In this page you can find the example usage for javax.script ScriptEngine put.

Prototype

public void put(String key, Object value);

Source Link

Document

Sets a key/value pair in the state of the ScriptEngine that may either create a Java Language Binding to be used in the execution of scripts or be used in some other way, depending on whether the key is reserved.

Usage

From source file:nz.net.orcon.kanban.automation.plugin.ScriptPlugin.java

@Override
public Map<String, Object> process(Action action, Map<String, Object> context) throws Exception {

    ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");

    for (Entry<String, Object> entry : context.entrySet()) {
        if (StringUtils.isNotBlank(entry.getKey())) {
            engine.put(entry.getKey(), entry.getValue());
        }//from   www.  j av a  2 s .c o  m
    }

    if (action.getProperties() != null) {
        for (Entry<String, String> entry : action.getProperties().entrySet()) {
            if (StringUtils.isNotBlank(entry.getKey())) {
                engine.put(entry.getKey(), entry.getValue());
            }
        }
    }

    engine.put("lists", listController);
    engine.put("log", log);

    String script = null;
    if (StringUtils.isNotBlank(action.getResource())) {
        script = resourceController.getResource((String) context.get("boardid"), action.getResource());
    } else {
        script = action.getMethod();
    }

    engine.eval(script);
    Bindings resultBindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
    for (Entry<String, Object> entry : resultBindings.entrySet()) {
        if (entry.getKey().equals("context") || entry.getKey().equals("print")
                || entry.getKey().equals("println")) {
            continue;
        }
        context.put(entry.getKey(), entry.getValue());
    }
    return context;
}

From source file:org.quackbot.hooks.loaders.JSHookLoader.java

@Override
public QListener load(String fileLocation) throws Exception {
    if (fileLocation.endsWith("JS_Template.js") || fileLocation.endsWith("QuackUtils.js"))
        //Ignore this
        return null;

    String[] pathParts = StringUtils.split(fileLocation, System.getProperty("file.separator"));
    String name = StringUtils.split(pathParts[pathParts.length - 1], ".")[0];
    log.info("New JavaScript Plugin: " + name);

    //Add utilities and wrappings
    ScriptEngine jsEngine = new ScriptEngineManager().getEngineByName("JavaScript");
    jsEngine.put("log", LoggerFactory.getLogger("JSPlugins." + name));
    LinkedHashMap<String, String> sourceMap = new LinkedHashMap();
    evalResource(jsEngine, sourceMap, "JSPluginBase/QuackUtils.js");
    evalResource(jsEngine, sourceMap, "JSPluginBase/JSCommand.js");
    evalResource(jsEngine, sourceMap, fileLocation);

    //Should we just ignore this?
    if (castToBoolean(jsEngine.get("ignore"))) {
        log.debug("Ignore variable set, skipping");
        return null;
    }/* w ww .  ja va 2s  .  c  o m*/

    //Return the appropiate hook
    if (jsEngine.get("onCommand") != null)
        //Has Command functions, return command
        return new JSCommandWrapper(jsEngine, sourceMap, fileLocation, name);

    //Assume hook
    return new JSHookWrapper(jsEngine, sourceMap, fileLocation, name);
}

From source file:net.mindengine.galen.suite.actions.GalenPageActionRunJavascript.java

@Override
public List<ValidationError> execute(Browser browser, GalenPageTest pageTest,
        ValidationListener validationListener) throws Exception {

    File file = GalenUtils.findFile(javascriptPath);
    Reader scriptFileReader = new FileReader(file);
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("JavaScript");
    ScriptContext context = engine.getContext();
    context.setAttribute("name", "JavaScript", ScriptContext.ENGINE_SCOPE);

    engine.put("global", new ScriptExecutor(engine, file.getParent()));
    engine.put("browser", browser);

    provideWrappedWebDriver(engine, browser);

    importAllMajorClasses(engine);//from   ww  w  .  j av  a2 s .c  om
    engine.eval("var arg = " + jsonArguments);
    engine.eval(scriptFileReader);
    return NO_ERRORS;
}

From source file:org.nyu.edu.dlts.CodeViewerDialog.java

/**
 * Method to evaluate the syntax of the script.
 * Basically try running and see if any syntax errors occur
 *//*from  w w w.  ja  v  a  2  s  . c o m*/
private void evaluateButtonActionPerformed() {
    try {
        if (textArea.getSyntaxEditingStyle().equals(RSyntaxTextArea.SYNTAX_STYLE_JAVA)) {
            Interpreter bsi = new Interpreter();
            bsi.set("record", new String("Test"));
            bsi.set("recordType", "test");
            bsi.eval(getCurrentScript());
        } else if (textArea.getSyntaxEditingStyle().equals(RSyntaxTextArea.SYNTAX_STYLE_RUBY)) {
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine jri = manager.getEngineByName("jruby");
            jri.put("recordType", "test");
            jri.eval(getCurrentScript());
        } else if (textArea.getSyntaxEditingStyle().equals(RSyntaxTextArea.SYNTAX_STYLE_PYTHON)) {
            PythonInterpreter pyi = new PythonInterpreter();
            pyi.set("record", new String("Test"));
            pyi.set("recordType", "test");
            pyi.exec(getCurrentScript());
        } else {
            // must be java script
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine jsi = manager.getEngineByName("javascript");
            jsi.put("record", new String("Test"));
            jsi.put("recordType", "test");
            jsi.eval(getCurrentScript());
        }

        messageTextArea.setText("No Syntax Errors Found ...");
    } catch (Exception e) {
        messageTextArea.setText("Error Occurred:\n" + dbCopyFrame.getStackTrace(e));
    }
}

From source file:org.archive.modules.ScriptedProcessor.java

@Override
protected void innerProcess(CrawlURI curi) {
    // depending on previous configuration, engine may 
    // be local to this thread or shared
    ScriptEngine engine = getEngine();
    synchronized (engine) {
        // synchronization is harmless for local thread engine,
        // necessary for shared engine
        engine.put("curi", curi);
        engine.put("appCtx", appCtx);
        try {//  www  .  j a v a 2 s.c o  m
            engine.eval("process(curi)");
        } catch (ScriptException e) {
            logger.log(Level.WARNING, e.getMessage(), e);
        } finally {
            engine.put("curi", null);
            engine.put("appCtx", null);
        }
    }
}

From source file:it.geosolutions.geobatch.action.scripting.ScriptingTest.java

@Test
public void testGroovyFileAndParam() throws ScriptException, IOException {

    String engineName = "groovy";

    ScriptEngineManager mgr = new ScriptEngineManager();
    // create a JavaScript engine
    ScriptEngine engine = mgr.getEngineByName(engineName);
    assertNotNull("Can't find engine '" + engineName + "'", engine);

    File script = new ClassPathResource("test-data/test.groovy").getFile();

    assertNotNull("Can't find test script", script);

    engine.put("gbtest", "testok");

    // evaluate code from File
    engine.eval(new FileReader(script));
}

From source file:org.archive.modules.deciderules.ScriptedDecideRule.java

@Override
public DecideResult innerDecide(CrawlURI uri) {
    // depending on previous configuration, engine may 
    // be local to this thread or shared
    ScriptEngine engine = getEngine();
    synchronized (engine) {
        // synchronization is harmless for local thread engine,
        // necessary for shared engine
        try {//from  w w w .j av a 2 s  .c o m
            engine.put("object", uri);
            engine.put("appCtx", appCtx);
            return (DecideResult) engine.eval("decisionFor(object)");
        } catch (ScriptException e) {
            logger.log(Level.WARNING, e.getMessage(), e);
            return DecideResult.NONE;
        } finally {
            engine.put("object", null);
            engine.put("appCtx", null);
        }
    }
}

From source file:com.intuit.tank.tools.script.ScriptRunner.java

/**
 * //  w w  w .  jav  a 2  s .  c  om
 * @param scriptName
 * @param script
 * @param engine
 * @param inputs
 * @param output
 * @return
 * @throws ScriptException
 */
public ScriptIOBean runScript(@Nullable String scriptName, @Nonnull String script, @Nonnull ScriptEngine engine,
        @Nonnull Map<String, Object> inputs, OutputLogger output) throws ScriptException {
    Reader reader = null;
    ScriptIOBean ioBean = null;
    try {
        reader = new StringReader(script);
        ioBean = new ScriptIOBean(inputs, output);
        engine.put("ioBean", ioBean);
        ioBean.println("Starting test...");
        engine.eval(reader, engine.getContext());
        ioBean.println("Finished test...");
    } catch (ScriptException e) {
        throw new ScriptException(e.getMessage(), scriptName, e.getLineNumber(), e.getColumnNumber());
    } finally {
        IOUtils.closeQuietly(reader);
    }
    return ioBean;
}

From source file:de.ingrid.mdek.mapping.ScriptImportDataMapper.java

private void doMap(Map<String, Object> parameters) throws Exception {
    try {/*from   ww  w  . j av  a2 s  .  c om*/
        ScriptEngine engine = this.getScriptEngine();

        // pass all parameters
        for (String param : parameters.keySet())
            engine.put(param, parameters.get(param));
        engine.put("log", log);

        // execute the mapping
        log.debug("Mapping with script: " + mapperScript);
        engine.eval(new InputStreamReader(mapperScript.getInputStream()));

    } catch (ScriptException e) {
        log.error("Error while evaluating the script!", e);
        throw e;
    } catch (IOException e) {
        log.error("Error while accessing the mapper script!", e);
        throw e;
    }

}

From source file:org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngineOverGraphTest.java

@Test
@FeatureRequirementSet(FeatureRequirementSet.Package.VERTICES_ONLY)
public void shouldProcessUTF8Query() throws Exception {
    final Vertex nonUtf8 = graph.addVertex("name", "marko", "age", 29);
    final Vertex utf8Name = graph.addVertex("name", "", "age", 32);

    final ScriptEngine engine = new GremlinGroovyScriptEngine();

    engine.put("g", g);
    Traversal eval = (Traversal) engine.eval("g.V().has('name', 'marko')");
    assertEquals(nonUtf8, eval.next());/*from   w w  w.ja va2 s . c o m*/
    eval = (Traversal) engine.eval("g.V().has('name','')");
    assertEquals(utf8Name, eval.next());
}