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:org.siphon.common.js.JsEngineUtil.java

public static Object eval(ScriptEngine jsEngine, String srcFile, String code) throws ScriptException {

    jsEngine.put(ScriptEngine.FILENAME, srcFile);
    return jsEngine.eval(code);
}

From source file:org.jumpmind.metl.core.runtime.component.ModelAttributeScriptHelper.java

public static Object eval(Message message, ComponentContext context, ModelAttribute attribute, Object value,
        ModelEntity entity, EntityData data, String expression) {
    ScriptEngine engine = scriptEngine.get();
    if (engine == null) {
        ScriptEngineManager factory = new ScriptEngineManager();
        engine = factory.getEngineByName("groovy");
        scriptEngine.set(engine);/*from  ww w  .  j a  va  2s. c o m*/
    }
    engine.put("value", value);
    engine.put("data", data);
    engine.put("entity", entity);
    engine.put("attribute", attribute);
    engine.put("message", message);
    engine.put("context", context);

    try {
        String importString = "import org.jumpmind.metl.core.runtime.component.ModelAttributeScriptHelper;\n";
        String code = String.format(
                "return new ModelAttributeScriptHelper(message, context, attribute, entity, data, value) { public Object eval() { return %s } }.eval()",
                expression);
        return engine.eval(importString + code);
    } catch (ScriptException e) {
        throw new RuntimeException("Unable to evaluate groovy script.  Attribute ==> " + attribute.getName()
                + ".  Value ==> " + value.toString() + "." + e.getCause().getMessage(), e);
    }
}

From source file:temp.groovy.java

@Test
public void foo() {
    JexlEngine eng = new JexlEngine();
    eng.setLenient(false);//from  w ww  .  ja v  a  2 s. com
    eng.setSilent(false);
    Expression expr = eng.createExpression("a == '9' and a =~ ['7','9']");
    System.out.println(expr.dump());
    JexlContext ctx = new MapContext();
    ctx.set("a", "9");
    Boolean result = (Boolean) expr.evaluate(ctx);
    try {
        ScriptEngineManager factory = new ScriptEngineManager();
        ScriptEngine engine = factory.getEngineByName("jython");

        engine.put("first", 9);
        result = (Boolean) engine.eval("first not in [7,9]");
        result = (Boolean) engine.eval("first in ['7','9']");
        assertEquals(true, result);
        //This next example illustrates calling an invokable function:

        String fact = "def factorial(n) { n == 1 ? 1 : n * factorial(n - 1) }";
        engine.eval(fact);
        Invocable inv = (Invocable) engine;
        Object[] params = { 5 };
        Object oresult = inv.invokeFunction("factorial", params);
        assertEquals(120, oresult);
    } catch (ScriptException | NoSuchMethodException ex) {
        Logger.getLogger(groovy.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:reconf.server.services.JavaScriptEngine.java

public Object eval(String js, Map<String, Object> params, String resultVariableName) {
    try {/*from  ww  w.jav  a 2  s . c  o m*/
        ScriptEngineManager factory = new ScriptEngineManager();
        ScriptEngine engine = factory.getEngineByName("JavaScript");
        for (Entry<String, Object> each : params.entrySet()) {
            engine.put(each.getKey(), each.getValue());
        }
        engine.eval(js);
        return engine.get(resultVariableName);

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.callimachusproject.fluid.consumers.HttpJavaScriptResponseWriter.java

public HttpJavaScriptResponseWriter() throws ScriptException {
    String systemId = getSystemId("SCRIPT");
    ScriptEngineManager man = new ScriptEngineManager();
    ScriptEngine engine = man.getEngineByName("rhino");
    engine.put(ScriptEngine.FILENAME, systemId);
    engine.eval(SCRIPT);/*from   w  ww .  j a v a  2s  . c  o  m*/
    this.engine = (Invocable) engine;
    this.delegate = new HttpMessageWriter();
}

From source file:org.eclipse.smarthome.transform.javascript.internal.JavaScriptTransformationService.java

/**
 * Transforms the input <code>source</code> by Java Script. It expects the
 * transformation rule to be read from a file which is stored under the
 * 'configurations/transform' folder. To organize the various
 * transformations one should use subfolders.
 * /* w w  w .  jav  a 2  s .c  o  m*/
 * @param filename
 *            the name of the file which contains the Java script
 *            transformation rule. Transformation service inject input
 *            (source) to 'input' variable.
 * @param source
 *            the input to transform
 */
@Override
public String transform(String filename, String source) throws TransformationException {
    Logger logger = LoggerFactory.getLogger(JavaScriptTransformationService.class);
    if (filename == null || source == null) {
        throw new TransformationException("the given parameters 'filename' and 'source' must not be null");
    }

    logger.debug("about to transform '{}' by the Java Script '{}'", source, filename);

    Reader reader;

    try {
        String path = ConfigConstants.getConfigFolder() + File.separator
                + TransformationService.TRANSFORM_FOLDER_NAME + File.separator + filename;
        reader = new InputStreamReader(new FileInputStream(path));
    } catch (FileNotFoundException e) {
        throw new TransformationException("An error occurred while loading script.", e);
    }

    ScriptEngineManager manager = new ScriptEngineManager();

    ScriptEngine engine = manager.getEngineByName("javascript");
    engine.put("input", source);

    Object result = null;

    long startTime = System.currentTimeMillis();

    try {
        result = engine.eval(reader);
    } catch (ScriptException e) {
        throw new TransformationException("An error occurred while executing script.", e);
    } finally {
        IOUtils.closeQuietly(reader);
    }

    logger.trace("JavaScript execution elapsed {} ms", System.currentTimeMillis() - startTime);

    return String.valueOf(result);
}

From source file:org.eclipse.smarthome.core.transform.internal.service.JavaScriptTransformationService.java

/**
 * Transforms the input <code>source</code> by Java Script. It expects the
 * transformation rule to be read from a file which is stored under the
 * 'configurations/transform' folder. To organize the various
 * transformations one should use subfolders.
 * // w ww .  j a v a 2s.co  m
 * @param filename
 *            the name of the file which contains the Java script
 *            transformation rule. Transformation service inject input
 *            (source) to 'input' variable.
 * @param source
 *            the input to transform
 */
public String transform(String filename, String source) throws TransformationException {

    if (filename == null || source == null) {
        throw new TransformationException("the given parameters 'filename' and 'source' must not be null");
    }

    logger.debug("about to transform '{}' by the Java Script '{}'", source, filename);

    Reader reader;

    try {
        String path = ConfigDispatcher.getConfigFolder() + File.separator
                + TransformationActivator.TRANSFORM_FOLDER_NAME + File.separator + filename;
        reader = new InputStreamReader(new FileInputStream(path));
    } catch (FileNotFoundException e) {
        throw new TransformationException("An error occured while loading script.", e);
    }

    ScriptEngineManager manager = new ScriptEngineManager();

    ScriptEngine engine = manager.getEngineByName("javascript");
    engine.put("input", source);

    Object result = null;

    long startTime = System.currentTimeMillis();

    try {
        result = engine.eval(reader);
    } catch (ScriptException e) {
        throw new TransformationException("An error occured while executing script.", e);
    } finally {
        IOUtils.closeQuietly(reader);
    }

    logger.trace("JavaScript execution elapsed {} ms", System.currentTimeMillis() - startTime);

    return String.valueOf(result);
}

From source file:edu.anu.spice.SpiceScorer.java

public void scoreBatch(SpiceArguments args) throws IOException, ScriptException {
    Stopwatch timer = Stopwatch.createStarted();
    SpiceParser parser = new SpiceParser(args.cache, args.numThreads, args.synsets);

    // Build filters for tuple categories
    Map<String, TupleFilter> filters = new HashMap<String, TupleFilter>();
    if (args.tupleSubsets) {
        filters.put("Object", TupleFilter.objectFilter);
        filters.put("Attribute", TupleFilter.attributeFilter);
        filters.put("Relation", TupleFilter.relationFilter);
        filters.put("Cardinality", TupleFilter.cardinalityFilter);
        filters.put("Color", TupleFilter.colorFilter);
        filters.put("Size", TupleFilter.sizeFilter);
    }//from w ww  .  j  ava2  s  . co  m

    // Parse test and refs from input file
    ArrayList<Object> image_ids = new ArrayList<Object>();
    ArrayList<String> testCaptions = new ArrayList<String>();
    ArrayList<String> refCaptions = new ArrayList<String>();
    ArrayList<Integer> refChunks = new ArrayList<Integer>();
    JSONParser json = new JSONParser();
    JSONArray input;
    try {
        input = (JSONArray) json.parse(new FileReader(args.inputPath));
        for (Object o : input) {
            JSONObject item = (JSONObject) o;
            image_ids.add(item.get("image_id"));
            testCaptions.add((String) item.get("test"));
            JSONArray refs = (JSONArray) item.get("refs");
            refChunks.add(refs.size());
            for (Object ref : refs) {
                refCaptions.add((String) ref);
            }
        }
    } catch (ParseException e) {
        System.err.println("Could not read input: " + args.inputPath);
        System.err.println(e.toString());
        e.printStackTrace();
    }

    System.err.println("Parsing reference captions");
    List<SceneGraph> refSgs = parser.parseCaptions(refCaptions, refChunks);
    System.err.println("Parsing test captions");
    List<SceneGraph> testSgs = parser.parseCaptions(testCaptions);

    this.stats = new SpiceStats(filters, args.detailed);
    for (int i = 0; i < testSgs.size(); ++i) {
        this.stats.score(image_ids.get(i), testSgs.get(i), refSgs.get(i), args.synsets);
    }
    if (!args.silent) {
        System.out.println(this.stats.toString());
    }

    if (args.outputPath != null) {
        BufferedWriter outputWriter = new BufferedWriter(new FileWriter(args.outputPath));

        // Pretty print output using javascript
        String jsonStringNoWhitespace = this.stats.toJSONString();
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine scriptEngine = manager.getEngineByName("JavaScript");
        scriptEngine.put("jsonString", jsonStringNoWhitespace);
        scriptEngine.eval("result = JSON.stringify(JSON.parse(jsonString), null, 2)");
        String prettyPrintedJson = (String) scriptEngine.get("result");

        outputWriter.write(prettyPrintedJson);
        outputWriter.close();
    }
    System.out.println("SPICE evaluation took: " + timer.stop());
}

From source file:org.sonar.fortify.crawler.Main.java

private void executeJSCode(String pageSrc) throws ScriptException {
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("JavaScript");
    engine.put("d", this);
    engine.eval(pageSrc);//from  ww w .j a va  2  s.c  o m
}

From source file:org.ngrinder.operation.cotroller.ScriptConsoleController.java

/**
 * Run the given script. The run result is stored in "result" of the given model.
 *
 * @param script script//from   w  w w. j  a  va2s .c o m
 * @param model  model
 * @return operation/script_console
 */
@RequestMapping("")
public String run(@RequestParam(value = "script", defaultValue = "") String script, Model model) {
    if (StringUtils.isNotBlank(script)) {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("Groovy");
        engine.put("applicationContext", this.applicationContext);
        engine.put("agentManager", this.agentManager);
        engine.put("agentManagerService", this.agentManagerService);
        engine.put("regionService", this.regionService);
        engine.put("consoleManager", this.consoleManager);
        engine.put("userService", this.userService);
        engine.put("perfTestService", this.perfTestService);
        engine.put("tagService", this.tagService);
        engine.put("fileEntryService", this.fileEntryService);
        engine.put("config", getConfig());
        engine.put("pluginManager", this.pluginManager);
        engine.put("cacheManager", this.cacheManager);
        engine.put("user", getCurrentUser());
        final StringWriter out = new StringWriter();
        PrintWriter writer = new PrintWriter(out);
        engine.getContext().setWriter(writer);
        engine.getContext().setErrorWriter(writer);
        try {
            Object result = engine.eval(script);
            result = out.toString() + "\n" + ObjectUtils.defaultIfNull(result, "");
            model.addAttribute("result", result);
        } catch (ScriptException e) {
            model.addAttribute("result", out.toString() + "\n" + e.getMessage());
        }
    }
    model.addAttribute("script", script);
    return "operation/script_console";
}