Example usage for javax.script ScriptEngine getContext

List of usage examples for javax.script ScriptEngine getContext

Introduction

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

Prototype

public ScriptContext getContext();

Source Link

Document

Returns the default ScriptContext of the ScriptEngine whose Bindings, Reader and Writers are used for script executions when no ScriptContext is specified.

Usage

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   w  w  w . ja va 2s. co m
    engine.eval("var arg = " + jsonArguments);
    engine.eval(scriptFileReader);
    return NO_ERRORS;
}

From source file:com.mnxfst.stream.pipeline.element.script.ScriptEvaluatorPipelineElementTest.java

/**
 * This is not a test case but more a kind of a sandbox for fiddling around with the script engine
 *///w w w  .  j  a v  a2  s.  com
@Test
public void testEvaluateScriptWithReturn() throws Exception {

    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("JavaScript");
    StringWriter writer = new StringWriter();
    PrintWriter pw = new PrintWriter(writer, true);
    engine.getContext().setWriter(pw);

    engine.eval(new FileReader("/home/mnxfst/git/stream-analyzer/src/main/resources/spahql.js"));

    String script = "var result0 = '1';var result1 = '2';";
    engine.eval(script);
    StringBuffer sb = writer.getBuffer();
    System.out.println("StringBuffer contains: " + sb + " - " + engine.get("test"));
    System.out.println(engine.get("content"));

    for (int i = 0; i < Integer.MAX_VALUE; i++) {
        String content = (String) engine.get("result" + i);
        if (StringUtils.isBlank(content))
            break;
        System.out.println(content);
    }

    ObjectMapper mapper = new ObjectMapper();
    StreamEventMessage message = new StreamEventMessage();
    message.setIdentifier("test-id");
    message.setOrigin("test-origin");
    message.setTimestamp("2014-03-05");
    message.setEvent("10");
    //      message.addCustomAttribute("test-key-1", "3");
    //      message.addCustomAttribute("test-key-2", "value-1");
    //      message.addCustomAttribute("test-key-3", "19");
    //      message.addCustomAttribute("errors", (String)engine.get("test"));

    String json = mapper.writeValueAsString(message);
    System.out.println(json);
    StreamEventMessage msg = mapper.readValue(json, StreamEventMessage.class);
    System.out.println(message.getCustomAttributes().get("json"));

}

From source file:org.jahia.modules.docrules.EmailDocumentRule.java

private String evaluate(String subject, JCRNodeWrapper document) {
    if (subject.contains("${")) {
        try {//from   w ww.  j  a  v a 2 s  .  c  o  m
            ScriptEngine byName = ScriptEngineUtils.getInstance().getEngineByName("velocity");
            ScriptContext scriptContext = byName.getContext();
            final Bindings bindings = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE);
            bindings.put("document", document);
            scriptContext.setWriter(new StringWriter());
            scriptContext.setErrorWriter(new StringWriter());
            byName.eval(subject, bindings);
            return scriptContext.getWriter().toString().trim();
        } catch (ScriptException e) {
            logger.error("Error while evaluating value [" + subject + "]", e);
        }
    }

    return null;
}

From source file:sample.fa.ScriptRunnerApplication.java

private void executeScript(ActionEvent ae) {
    ScriptEngine se = (ScriptEngine) languagesModel.getSelectedItem();
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); Writer w = new OutputStreamWriter(baos);) {
        se.getContext().setWriter(w);

        Optional<Object> result = Optional.ofNullable(se.eval(scriptContents.getText()));

        scriptResults.setText(baos.toString() + "\n>>>>>>\n" + result.orElse("-null-").toString());
    } catch (Exception e) {
        e.printStackTrace(System.out);
        scriptResults.setText(e.getClass().getName() + " - " + e.getMessage());
    }//from ww w  . j  av a  2  s . c o m
}

From source file:org.jahia.modules.macros.filter.MacrosFilter.java

@Override
public String execute(String previousOut, RenderContext renderContext, Resource resource, RenderChain chain)
        throws Exception {
    if (StringUtils.isEmpty(previousOut)) {
        return previousOut;
    }/*  w w w .  j  av a2 s. c om*/
    long timer = System.currentTimeMillis();
    boolean evaluated = false;

    Matcher matcher = macrosPattern.matcher(previousOut);
    while (matcher.find()) {
        evaluated = true;
        String macroName = matcher.group(1);
        String[] macro = getMacro(macroName);
        if (macro != null) {
            try {
                // execute macro
                ScriptEngine scriptEngine = scriptEngineUtils.scriptEngine(macro[1]);
                ScriptContext scriptContext = scriptEngine.getContext();
                scriptContext.setWriter(new StringWriter());
                scriptContext.setErrorWriter(new StringWriter());
                scriptEngine.eval(macro[0], getBindings(renderContext, resource, scriptContext, matcher));
                String scriptResult = scriptContext.getWriter().toString().trim();
                previousOut = matcher.replaceFirst(scriptResult);
            } catch (ScriptException e) {
                logger.warn("Error during execution of macro " + macroName + " with message " + e.getMessage(),
                        e);
                previousOut = matcher.replaceFirst(macroName);
            }
            matcher = macrosPattern.matcher(previousOut);
        } else if (replaceByErrorMessageOnMissingMacros) {
            previousOut = matcher.replaceFirst("macro " + macroName + " not found");
            logger.warn("Unknown macro '{}'", macroName);
            matcher = macrosPattern.matcher(previousOut);
        }
    }

    if (evaluated && logger.isDebugEnabled()) {
        logger.debug("Evaluation of macros took {} ms", (System.currentTimeMillis() - timer));
    }
    return previousOut;
}

From source file:com.aionemu.commons.scripting.AionScriptEngineManager.java

public ScriptContext getScriptContext(ScriptEngine engine) {
    return engine.getContext();
}

From source file:com.github.safrain.remotegsh.server.RgshFilter.java

/**
 * Create a script engine with stdout and stderr replaced by {@link ServletResponse#getWriter()}.
 * Script extensions in {@link #scriptExtensions} will be evaluated after the engine creation.
 *///from  w w w .jav  a 2  s.c o m
private ScriptEngine prepareEngine(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    ScriptEngine engine = createGroovyEngine();
    PrintWriter writer = response.getWriter();
    engine.getContext().setWriter(writer);
    engine.getContext().setErrorWriter(writer);
    engine.put("_request", request);
    engine.put("_response", response);
    engine.put("_charset", charset);

    try {
        for (Entry<String, CompiledScript> entry : scriptExtensions.entrySet()) {
            try {
                entry.getValue().eval(engine.getContext());
            } catch (ScriptException e) {
                //Ignore script extension evaluation errors
                log.log(Level.WARNING, String.format("Error evaluating script extension '%s'", entry.getKey()),
                        e);
            }
        }
    } catch (Exception e) {
        log.log(Level.SEVERE, "Error while creating engine.", e);
        throw new RuntimeException(e);
    }
    return engine;
}

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

/**
 * /*from ww  w  .j ava2 s .co  m*/
 * @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:org.ms123.common.utils.UtilsServiceImpl.java

public Object executeScript(String scriptName, String namespace, String user, Map params) throws Exception {
    System.out.println("UtilsServiceImpl.executeScript:" + params);
    String storeId = (String) params.get("storeId");
    StoreDesc sdesc = StoreDesc.get(storeId);
    namespace = sdesc.getNamespace();/*from  w  w w . j av a  2s .  c o  m*/
    System.out.println("UtilsServiceImpl.namespace:" + sdesc + "/" + namespace);
    ScriptEngine se = m_scriptEngineService.getEngineByName("groovy");
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    se.getContext().setWriter(pw);
    Bindings b = se.createBindings();
    b.putAll(params);
    b.put("jdo", m_dataLayer);
    b.put("ws", lookupServiceByName("org.ms123.common.workflow.api.WorkflowService"));
    b.put("ss", lookupServiceByName("org.ms123.common.setting.api.SettingService"));
    b.put("et", lookupServiceByName("org.ms123.common.entity.api.EntityService"));
    b.put("storeDesc", sdesc);
    b.put("home", System.getProperty("simpl4.dir"));
    b.put("log", m_logger);
    b.put("user", user);
    b.put("namespace", namespace);
    se.setBindings(b, ScriptContext.ENGINE_SCOPE);
    b.put("se", se);
    Object r = "";
    FileReader fr = getScriptFile(namespace, scriptName);
    r = se.eval(fr);
    System.out.println("r:" + r);
    pw.close();
    m_logger.info("executeScript:" + sw);
    System.out.println("executeScript:" + sw);
    return null;
}

From source file:org.apache.camel.builder.script.ScriptBuilder.java

protected void populateBindings(ScriptEngine engine, Exchange exchange) {
    ScriptContext context = engine.getContext();
    int scope = ScriptContext.ENGINE_SCOPE;
    context.setAttribute("context", exchange.getContext(), scope);
    context.setAttribute("exchange", exchange, scope);
    context.setAttribute("request", exchange.getIn(), scope);
    if (exchange.hasOut()) {
        context.setAttribute("response", exchange.getOut(), scope);
    }/*  w  w w. ja  v a  2 s.c  o  m*/
}