Example usage for javax.script ScriptContext ENGINE_SCOPE

List of usage examples for javax.script ScriptContext ENGINE_SCOPE

Introduction

In this page you can find the example usage for javax.script ScriptContext ENGINE_SCOPE.

Prototype

int ENGINE_SCOPE

To view the source code for javax.script ScriptContext ENGINE_SCOPE.

Click Source Link

Document

EngineScope attributes are visible during the lifetime of a single ScriptEngine and a set of attributes is maintained for each engine.

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  ww .j a  v  a  2 s.c  o  m*/
    engine.eval("var arg = " + jsonArguments);
    engine.eval(scriptFileReader);
    return NO_ERRORS;
}

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  ww  w.  j  a  v  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:be.solidx.hot.JSR223ScriptExecutor.java

@Override
public Object execute(Script<CompiledScript> script) throws ScriptException {
    try {/*from w ww  . j  a v a 2  s .c  o  m*/
        ScriptEngine scriptEngine = getEngine();
        CompiledScript compiledScript = getCachedScript(script);
        ScriptContext scriptContext = new SimpleScriptContext();
        executePreExecuteScripts(scriptContext);
        Object object = compiledScript.eval(scriptContext);
        if (object == null)
            return scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE);
        return object;
    } catch (javax.script.ScriptException e) {
        throw new ScriptException(e);
    }
}

From source file:com.googlecode.starflow.core.script.spel.SpelScriptEngine.java

private Map<String, Object> getVariables(ScriptContext scriptContext) {
    Map<String, Object> variables = new HashMap<String, Object>();
    if (scriptContext.getBindings(ScriptContext.GLOBAL_SCOPE) != null) {
        variables.putAll(scriptContext.getBindings(ScriptContext.GLOBAL_SCOPE));
    }//from www  .  j ava2s  .co m
    if (scriptContext.getBindings(ScriptContext.ENGINE_SCOPE) != null) {
        variables.putAll(scriptContext.getBindings(ScriptContext.ENGINE_SCOPE));
    }
    return variables;
}

From source file:org.rhq.enterprise.server.plugins.alertScriptlang.ScriptLangSender.java

@Override
public SenderResult send(Alert alert) {

    String scriptName = alertParameters.getSimpleValue("name", null);
    if (scriptName == null) {
        return new SenderResult(ResultState.FAILURE, "No script given");
    }/* w  w  w . j  av a 2  s  . co m*/
    String language = alertParameters.getSimpleValue("language", "jruby");

    ScriptEngine engine = pluginComponent.getEngineByLanguage(language);
    //        ScriptEngineManager manager = new ScriptEngineManager(serverPluginEnvironment.getPluginClassLoader());
    //        engine = manager.getEngineByName(language);

    if (engine == null) {
        return new SenderResult(ResultState.FAILURE,
                "Script engine with name [" + language + "] does not exist");
    }

    File file = new File(pluginComponent.baseDir + scriptName);
    if (!file.exists() || !file.canRead()) {
        return new SenderResult(ResultState.FAILURE, "Script [" + scriptName
                + "] does not exist or is not readable at [" + file.getAbsolutePath() + "]");
    }

    Object result;
    try {
        BufferedReader br = new BufferedReader(new FileReader(file));

        Map<String, String> preferencesMap = new HashMap<String, String>();
        for (String key : preferences.getSimpleProperties().keySet())
            preferencesMap.put(key, preferences.getSimple(key).getStringValue());

        Map<String, String> parameterMap = new HashMap<String, String>();
        for (String key : alertParameters.getSimpleProperties().keySet())
            parameterMap.put(key, alertParameters.getSimple(key).getStringValue());

        ScriptContext sc = engine.getContext();
        sc.setAttribute("alertPreferences", preferencesMap, ScriptContext.ENGINE_SCOPE);
        sc.setAttribute("alertParameters", parameterMap, ScriptContext.ENGINE_SCOPE);
        engine.eval(br);

        AlertManagerLocal alertManager = LookupUtil.getAlertManager();

        Object[] args = new Object[3];
        args[0] = alert;
        args[1] = alertManager.prettyPrintAlertURL(alert);
        args[2] = alertManager.prettyPrintAlertConditions(alert, false);
        result = ((Invocable) engine).invokeFunction("sendAlert", args);

        if (result == null) {
            return new SenderResult(ResultState.FAILURE,
                    "Script ]" + scriptName + "] returned null, so success is unknown");
        }
        if (result instanceof SenderResult)
            return (SenderResult) result;

        return new SenderResult(ResultState.SUCCESS, "Sending via script resulted in " + result.toString());
    } catch (Exception e) {
        e.printStackTrace();
        return new SenderResult(ResultState.FAILURE,
                "Sending via [" + scriptName + "] failed: " + e.getMessage());
    }
}

From source file:org.apache.sling.scripting.sightly.js.impl.JsEnvironment.java

public void runResource(Resource scriptResource, Bindings globalBindings, Bindings arguments,
        UnaryCallback callback) {//from   w  w w . j  av a  2 s. co m
    ScriptContext scriptContext = new SimpleScriptContext();
    CommonJsModule module = new CommonJsModule();
    Bindings scriptBindings = buildBindings(scriptResource, globalBindings, arguments, module);
    scriptContext.setBindings(scriptBindings, ScriptContext.ENGINE_SCOPE);
    scriptContext.setAttribute(ScriptEngine.FILENAME, scriptResource.getPath(), ScriptContext.ENGINE_SCOPE);
    runScript(scriptResource, scriptContext, callback, module);
}

From source file:be.solidx.hot.JSR223ScriptExecutor.java

@Override
public Object execute(Script<CompiledScript> script, Map<String, Object> contextVars) throws ScriptException {
    try {/*from  w  w w.j a va2s  . c  o  m*/
        ScriptEngine scriptEngine = getEngine();
        Bindings bindings = scriptEngine.createBindings();
        ScriptContext scriptContext = new SimpleScriptContext();
        scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
        bindings.putAll(contextVars);
        executePreExecuteScripts(scriptContext);
        CompiledScript compiledScript = getCachedScript(script);
        Object object = compiledScript.eval(scriptContext);
        if (object == null)
            return bindings;
        return object;
    } catch (javax.script.ScriptException e) {
        throw new ScriptException(e);
    }
}

From source file:org.fireflow.engine.modules.script.ScriptEngineHelper.java

private static Object evaluateJSR233Expression(RuntimeContext rtCtx, Expression fireflowExpression,
        Map<String, Object> contextObjects) {
    ScriptEngine scriptEngine = rtCtx.getScriptEngine(fireflowExpression.getLanguage());

    ScriptContext scriptContext = new SimpleScriptContext();
    Bindings engineScope = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE);
    engineScope.putAll(contextObjects);/*from   ww  w  .  j  av  a 2  s . c o m*/
    try {
        Object result = scriptEngine.eval(fireflowExpression.getBody(), scriptContext);
        return result;
    } catch (ScriptException e) {
        throw new RuntimeException("Can NOT evaluate the expression. ", e);
    }
}

From source file:org.icesquirrel.jsr223.IcesquirrelScriptEngine.java

@Override
public Object eval(Reader reader, ScriptContext context) throws ScriptException {

    SquirrelInterpretedScript sis = new SquirrelInterpretedScript();

    /*/*from  w ww  . j a v a 2s  . c  o  m*/
     * If the global bindings is already a SquirrelTable, use that directly.
     * A squirrel table is kind of compatible with a bindings object, except
     * the key may be an Object instead of a string.
     */
    Bindings bindings = context.getBindings(ScriptContext.GLOBAL_SCOPE);
    if (bindings instanceof BindingsAdapter) {
        sis.setRootTable(((BindingsAdapter) bindings).getTable());
    } else {
        // Otherwise copy global bindings into our root table
        for (Entry<String, Object> s : bindings.entrySet()) {
            bind(sis, s);
        }
    }

    // Now the engine scoped bindings. If these are already a squirrel
    // table, add them as
    // a delegate, otherwise copy
    Bindings engBindings = context.getBindings(ScriptContext.ENGINE_SCOPE);
    SquirrelTable addedDelegate = null;
    if (engBindings instanceof BindingsAdapter) {
        BindingsAdapter ba = (BindingsAdapter) engBindings;
        if (ba.getTable() != sis.getRootTable()) {
            SquirrelTable pt = sis.setRootTable(ba.getTable());
            if (pt != null && !ba.getTable().getDelegates().contains(pt)) {
                ba.getTable().addDelegate(pt);
                addedDelegate = pt;
            }
        }
    } else {
        for (Entry<String, Object> s : engBindings.entrySet()) {
            bind(sis, s);
        }
    }

    SquirrelRuntime runtime = SquirrelRuntime.getDefaultRuntime();
    SquirrelExecutionContext ctx = null;
    if (!SquirrelExecutionContext.is()) {
        ctx = new SquirrelExecutionContext();
        ctx.start(sis.getRootTable(), runtime, new SquirrelInterpretedProcessor());
    }

    try {
        try {
            // TODO encoding
            sis.execute(new ReaderInputStream(reader));
        } catch (SquirrelException se) {
            // TODO line number etc
            throw new ScriptException(se);
        } catch (Exception e) {
            // TODO line number etc
            throw new ScriptException(e);
        }
        Object result = sis.getResult();
        if (result instanceof SquirrelObjectWrapper) {
            return ((SquirrelObjectWrapper) result).getObject();
        }
        return result;
    } finally {
        if (addedDelegate != null) {
            sis.getRootTable().removeDelegate(addedDelegate);
        }
        if (ctx != null) {
            ctx.stop();
        }
    }
}

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());
        }//from  w w  w . j a v a2 s .  c  o  m
        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;
}