Search in sources :

Example 86 with ScriptContext

use of javax.script.ScriptContext in project sling by apache.

the class ScriptEngineHelper method eval.

public Object eval(String javascriptCode, Map<String, Object> data, final StringWriter sw) throws ScriptException {
    final PrintWriter pw = new PrintWriter(sw, true);
    ScriptContext ctx = new SimpleScriptContext();
    final Bindings b = new SimpleBindings();
    b.put("out", pw);
    if (data != null) {
        for (Map.Entry<String, Object> e : data.entrySet()) {
            b.put(e.getKey(), e.getValue());
        }
    }
    ctx.setBindings(b, ScriptContext.ENGINE_SCOPE);
    ctx.setWriter(sw);
    ctx.setErrorWriter(new OutputStreamWriter(System.err));
    Object result = getEngine().eval(javascriptCode, ctx);
    if (result instanceof Wrapper) {
        result = ((Wrapper) result).unwrap();
    }
    if (result instanceof ScriptableObject) {
        Context.enter();
        try {
            result = ((ScriptableObject) result).getDefaultValue(null);
        } finally {
            Context.exit();
        }
    }
    return result;
}
Also used : Wrapper(org.mozilla.javascript.Wrapper) ScriptableObject(org.mozilla.javascript.ScriptableObject) SimpleScriptContext(javax.script.SimpleScriptContext) SimpleBindings(javax.script.SimpleBindings) SimpleScriptContext(javax.script.SimpleScriptContext) ScriptContext(javax.script.ScriptContext) ScriptableObject(org.mozilla.javascript.ScriptableObject) OutputStreamWriter(java.io.OutputStreamWriter) Bindings(javax.script.Bindings) SimpleBindings(javax.script.SimpleBindings) HashMap(java.util.HashMap) Map(java.util.Map) PrintWriter(java.io.PrintWriter)

Example 87 with ScriptContext

use of javax.script.ScriptContext in project camel by apache.

the class ScriptBuilder method tryCreateScriptEngine.

/**
     * Attemps to create the script engine for the given langauge using the classloader
     *
     * @return the engine, or <tt>null</tt> if not able to create
     */
private static ScriptEngine tryCreateScriptEngine(String language, ClassLoader classLoader) {
    ScriptEngineManager manager = new ScriptEngineManager(classLoader);
    ScriptEngine engine = null;
    // some script names has alias
    String[] names = getScriptNames(language);
    for (String name : names) {
        try {
            engine = manager.getEngineByName(name);
            if (engine != null) {
                break;
            }
        } catch (NoClassDefFoundError ex) {
            LOG.warn("Cannot load ScriptEngine for " + name + ". Please ensure correct JARs is provided on classpath (stacktrace in DEBUG logging).");
            // include stacktrace in debug logging
            LOG.debug("Cannot load ScriptEngine for " + name + ". Please ensure correct JARs is provided on classpath.", ex);
        }
    }
    if (engine == null) {
        engine = checkForOSGiEngine(language);
    }
    if (engine != null && isPython(language)) {
        ScriptContext context = engine.getContext();
        context.setAttribute("com.sun.script.jython.comp.mode", "eval", ScriptContext.ENGINE_SCOPE);
    }
    return engine;
}
Also used : ScriptEngineManager(javax.script.ScriptEngineManager) ScriptContext(javax.script.ScriptContext) ScriptEngine(javax.script.ScriptEngine)

Example 88 with ScriptContext

use of javax.script.ScriptContext in project camel by apache.

the class ScriptBuilder method populateBindings.

protected ScriptContext populateBindings(ScriptEngine engine, Exchange exchange, Map<String, Object> attributes) {
    ScriptContext context = engine.getContext();
    int scope = ScriptContext.ENGINE_SCOPE;
    context.setAttribute("context", exchange.getContext(), scope);
    context.setAttribute("camelContext", exchange.getContext(), scope);
    context.setAttribute("exchange", exchange, scope);
    Message in = exchange.getIn();
    context.setAttribute("request", in, scope);
    context.setAttribute("headers", in.getHeaders(), scope);
    context.setAttribute("body", in.getBody(), scope);
    if (exchange.hasOut()) {
        Message out = exchange.getOut();
        context.setAttribute("out", out, scope);
        context.setAttribute("response", out, scope);
    }
    // to make using properties component easier
    context.setAttribute("properties", new ScriptPropertiesFunction(exchange.getContext()), scope);
    // any additional attributes
    if (attributes != null) {
        for (Map.Entry<String, Object> entry : attributes.entrySet()) {
            context.setAttribute(entry.getKey(), entry.getValue(), scope);
        }
    }
    return context;
}
Also used : Message(org.apache.camel.Message) ScriptContext(javax.script.ScriptContext) HashMap(java.util.HashMap) Map(java.util.Map)

Example 89 with ScriptContext

use of javax.script.ScriptContext in project camel by apache.

the class ScriptBuilder method doEvaluateScript.

protected Object doEvaluateScript(Exchange exchange, ScriptEngine scriptEngine) throws ScriptException, IOException {
    ScriptContext context = populateBindings(scriptEngine, exchange, attributes);
    addScriptEngineArguments(scriptEngine, exchange);
    Object result = runScript(scriptEngine, exchange, context);
    LOG.debug("The script evaluation result is: {}", result);
    return result;
}
Also used : ScriptContext(javax.script.ScriptContext)

Example 90 with ScriptContext

use of javax.script.ScriptContext in project javautils by jiadongpo.

the class ExecJs method execJs.

/**
 * 后置处理,执行js脚本
 * js 就是要执行的js脚本,map 是参数,就允许js脚本中用动态的参数 处理map中的值
 *
 * @param js
 * @throws Exception
 */
public void execJs(String js, Map<String, Object> map) throws Exception {
    if (log.isDebugEnabled()) {
        log.debug("execJs js : " + js);
        Iterator<Entry<String, Object>> it = map.entrySet().iterator();
        while (it.hasNext()) {
            Entry<String, Object> entry = (Entry<String, Object>) it.next();
            log.info("EXECJS MAP : " + entry.getKey() + "---" + entry.getValue());
        }
    // end while
    }
    // end if
    if ("".equals(js) || js == null) {
        log.info("EXECJS ERROR : JAVASCRIPT CONTENT IS NULL");
    } else if (map == null || map.size() <= 0) {
        log.info("EXECJS ERROR : MAP CONTENT IS NULL");
    } else {
        // 获取脚本引擎
        ScriptEngineManager mgr = new ScriptEngineManager();
        ScriptEngine engine = mgr.getEngineByName("javascript");
        // 绑定数据
        ScriptContext newContext = new SimpleScriptContext();
        Bindings bind = newContext.getBindings(ScriptContext.ENGINE_SCOPE);
        bind.putAll(map);
        try {
            engine.setBindings(bind, ScriptContext.ENGINE_SCOPE);
            engine.eval(js);
        } catch (Exception e) {
            log.info("EXECJS EXCEPTION : EXECUTE JAVASCRIPT EXCEPTION", e);
            throw (e);
        }
    // end try
    }
// end if
}
Also used : Entry(java.util.Map.Entry) SimpleScriptContext(javax.script.SimpleScriptContext) ScriptEngineManager(javax.script.ScriptEngineManager) SimpleScriptContext(javax.script.SimpleScriptContext) ScriptContext(javax.script.ScriptContext) Bindings(javax.script.Bindings) ScriptEngine(javax.script.ScriptEngine)

Aggregations

ScriptContext (javax.script.ScriptContext)126 SimpleScriptContext (javax.script.SimpleScriptContext)83 Bindings (javax.script.Bindings)33 Test (org.junit.Test)30 SimpleBindings (javax.script.SimpleBindings)28 Test (org.junit.jupiter.api.Test)19 ScriptEngine (javax.script.ScriptEngine)18 ScriptException (javax.script.ScriptException)18 HashMap (java.util.HashMap)13 CompiledScript (javax.script.CompiledScript)11 IOException (java.io.IOException)9 Map (java.util.Map)8 ScriptEngineManager (javax.script.ScriptEngineManager)8 XWikiDocument (com.xpn.xwiki.doc.XWikiDocument)7 Test (org.testng.annotations.Test)7 StringWriter (java.io.StringWriter)6 NashornScriptEngine (jdk.nashorn.api.scripting.NashornScriptEngine)6 XWikiException (com.xpn.xwiki.XWikiException)5 Reader (java.io.Reader)5 StringReader (java.io.StringReader)5