Example usage for javax.script ScriptContext GLOBAL_SCOPE

List of usage examples for javax.script ScriptContext GLOBAL_SCOPE

Introduction

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

Prototype

int GLOBAL_SCOPE

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

Click Source Link

Document

GlobalScope attributes are visible to all engines created by same ScriptEngineFactory.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    ScriptContext ctx = new SimpleScriptContext();
    Bindings globalBindings = new SimpleBindings();
    ctx.setBindings(globalBindings, ScriptContext.GLOBAL_SCOPE);
    ctx.setAttribute("year", 2015, ScriptContext.GLOBAL_SCOPE);
    ctx.setAttribute("name", "Java", ScriptContext.GLOBAL_SCOPE);
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    ScriptEngineManager manager = new ScriptEngineManager();
    manager.put("global", "global bindings");

    dumpBindings(manager.getBindings());
    ScriptEngine engine = manager.getEngineByExtension("js");
    engine.put("engine", "engine bindings");

    dumpBindings(engine.getBindings(ScriptContext.GLOBAL_SCOPE));

    dumpBindings(engine.getBindings(ScriptContext.ENGINE_SCOPE));

    Bindings bindings = engine.createBindings();
    bindings.put("engine", "overridden engine bindings");
    bindings.put("bindings", bindings);
    engine.eval("app.dumpBindings (bindings);", bindings);

    ScriptEngine engine2 = manager.getEngineByExtension("js");
    engine2.put("engine2", "engine2 bindings");

    dumpBindings(engine2.getBindings(ScriptContext.GLOBAL_SCOPE));
    dumpBindings(engine2.getBindings(ScriptContext.ENGINE_SCOPE));
    dumpBindings(engine.getBindings(ScriptContext.ENGINE_SCOPE));
}

From source file:GetToKnowBindingsAndScopes.java

public static void main(String[] args) {
    ScriptEngineManager manager = new ScriptEngineManager();
    manager.put("global", "global bindings");

    dumpBindings(manager.getBindings());
    ScriptEngine engine = manager.getEngineByExtension("js");
    engine.put("engine", "engine bindings");

    dumpBindings(engine.getBindings(ScriptContext.GLOBAL_SCOPE));

    dumpBindings(engine.getBindings(ScriptContext.ENGINE_SCOPE));

    try {/* ww  w .  j a va 2s  . c om*/
        Bindings bindings = engine.createBindings();
        bindings.put("engine", "overridden engine bindings");
        bindings.put("app", new GetToKnowBindingsAndScopes());
        bindings.put("bindings", bindings);
        engine.eval("app.dumpBindings (bindings);", bindings);
    } catch (ScriptException se) {
        System.err.println(se.getMessage());
    }

    ScriptEngine engine2 = manager.getEngineByExtension("js");
    engine2.put("engine2", "engine2 bindings");

    dumpBindings(engine2.getBindings(ScriptContext.GLOBAL_SCOPE));
    dumpBindings(engine2.getBindings(ScriptContext.ENGINE_SCOPE));
    dumpBindings(engine.getBindings(ScriptContext.ENGINE_SCOPE));
}

From source file:Main.java

public static void main(String[] args) throws ScriptException {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");

    ScriptContext defaultCtx = engine.getContext();
    // Work with defaultCtx here

    // Create a new context
    ScriptContext ctx = new SimpleScriptContext();

    // Configure ctx here

    // Set ctx as the new default context for the engine
    engine.setContext(ctx);//from   ww w.java2  s.com

    ctx.setBindings(manager.getBindings(), ScriptContext.GLOBAL_SCOPE);

    engine.setContext(ctx);
}

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 w w w  . ja  va  2  s.  c  o  m
    if (scriptContext.getBindings(ScriptContext.ENGINE_SCOPE) != null) {
        variables.putAll(scriptContext.getBindings(ScriptContext.ENGINE_SCOPE));
    }
    return variables;
}

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

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

    SquirrelInterpretedScript sis = new SquirrelInterpretedScript();

    /*//from   ww  w. j a va 2  s  .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:at.alladin.rmbt.qos.testscript.TestScriptInterpreter.java

/**
 * /*from ww  w .j a v a 2  s  .c  o m*/
 * @param command
 * @return
 */
public static <T> Object interprete(String command, Hstore hstore, AbstractResult<T> object,
        boolean useRecursion, ResultOptions resultOptions) {

    if (jsEngine == null) {
        ScriptEngineManager sem = new ScriptEngineManager();
        jsEngine = sem.getEngineByName("JavaScript");
        System.out.println("JS Engine: " + jsEngine.getClass().getCanonicalName());
        Bindings b = jsEngine.createBindings();
        b.put("nn", new SystemApi());
        jsEngine.setBindings(b, ScriptContext.GLOBAL_SCOPE);
    }

    command = command.replace("\\%", "{PERCENT}");

    Pattern p;
    if (!useRecursion) {
        p = PATTERN_COMMAND;
    } else {
        p = PATTERN_RECURSIVE_COMMAND;

        Matcher m = p.matcher(command);
        while (m.find()) {
            String replace = m.group(0);
            //System.out.println("found: " + replace);
            String toReplace = String.valueOf(interprete(replace, hstore, object, false, resultOptions));
            //System.out.println("replacing: " + m.group(0) + " -> " + toReplace);
            command = command.replace(m.group(0), toReplace);
        }

        command = command.replace("{PERCENT}", "%");
        return command;
    }

    Matcher m = p.matcher(command);
    command = command.replace("{PERCENT}", "%");

    String scriptCommand;
    String[] args;

    if (m.find()) {
        if (m.groupCount() != 2) {
            return command;
        }
        scriptCommand = m.group(1);

        if (!COMMAND_EVAL.equals(scriptCommand)) {
            args = m.group(2).trim().split("\\s");
        } else {
            args = new String[] { m.group(2).trim() };
        }
    } else {
        return command;
    }

    try {
        if (COMMAND_RANDOM.equals(scriptCommand)) {
            return random(args);
        } else if (COMMAND_PARAM.equals(scriptCommand)) {
            return parse(args, hstore, object, resultOptions);
        } else if (COMMAND_EVAL.equals(scriptCommand)) {
            return eval(args, hstore, object);
        } else if (COMMAND_RANDOM_URL.equals(scriptCommand)) {
            return randomUrl(args);
        } else {
            return command;
        }
    } catch (ScriptException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:me.tfeng.toolbox.dust.NashornEngine.java

private Object evaluate(String script, Map<String, Object> data) throws ScriptException {
    Bindings bindings = new SimpleBindings(data);
    scriptEngine.getContext().setBindings(bindings, ScriptContext.GLOBAL_SCOPE);
    return scriptEngine.eval(script);
}

From source file:org.wso2.carbon.identity.application.authentication.framework.config.model.graph.JsGraphBuilderFactory.java

public ScriptEngine createEngine(AuthenticationContext authenticationContext) {

    ScriptEngine engine = factory.getScriptEngine("--no-java");

    Bindings bindings = engine.createBindings();
    engine.setBindings(bindings, ScriptContext.GLOBAL_SCOPE);
    engine.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE);
    SelectAcrFromFunction selectAcrFromFunction = new SelectAcrFromFunction();
    //        todo move to functions registry
    bindings.put(FrameworkConstants.JSAttributes.JS_FUNC_SELECT_ACR_FROM,
            (SelectOneFunction) selectAcrFromFunction::evaluate);

    JsLogger jsLogger = new JsLogger();
    bindings.put(FrameworkConstants.JSAttributes.JS_LOG, jsLogger);
    return engine;
}

From source file:org.jahia.services.render.scripting.JSR223Script.java

/**
 * Execute the script and return the result as a string
 *
 * @param resource resource to display/* w  ww  .ja v a 2 s . c o  m*/
 * @param context
 * @return the rendered resource
 * @throws org.jahia.services.render.RenderException
 */
public String execute(Resource resource, RenderContext context) throws RenderException {
    ScriptEngine scriptEngine = null;

    ClassLoader tccl = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(view.getModule().getChainedClassLoader());

    try {
        scriptEngine = ScriptEngineUtils.getInstance().scriptEngine(view.getFileExtension());

        if (scriptEngine != null) {
            ScriptContext scriptContext = new SimpleScriptContext();
            final Bindings bindings = new SimpleBindings();
            Enumeration<?> attrNamesEnum = context.getRequest().getAttributeNames();
            while (attrNamesEnum.hasMoreElements()) {
                String currentAttributeName = (String) attrNamesEnum.nextElement();
                if (!"".equals(currentAttributeName)) {
                    bindings.put(currentAttributeName, context.getRequest().getAttribute(currentAttributeName));
                }
            }
            bindings.put("params", context.getRequest().getParameterMap());
            Reader scriptContent = null;
            try {
                InputStream scriptInputStream = getViewInputStream();
                if (scriptInputStream != null) {
                    scriptContent = new InputStreamReader(scriptInputStream);
                    scriptContext.setWriter(new StringWriter());
                    scriptContext.setErrorWriter(new StringWriter());
                    // The following binding is necessary for Javascript, which doesn't offer a console by default.
                    bindings.put("out", new PrintWriter(scriptContext.getWriter()));
                    scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
                    scriptContext.setBindings(scriptEngine.getContext().getBindings(ScriptContext.GLOBAL_SCOPE),
                            ScriptContext.GLOBAL_SCOPE);

                    scriptEngine.eval(scriptContent, scriptContext);

                    StringWriter writer = (StringWriter) scriptContext.getWriter();
                    return writer.toString().trim();
                } else {
                    throw new RenderException(
                            "Error while retrieving input stream for the resource " + view.getPath());
                }
            } catch (ScriptException e) {
                throw new RenderException("Error while executing script " + view.getPath(), e);
            } catch (IOException e) {
                throw new RenderException(
                        "Error while retrieving input stream for the resource " + view.getPath(), e);
            } finally {
                if (scriptContent != null) {
                    IOUtils.closeQuietly(scriptContent);
                }
            }
        }

    } catch (ScriptException e) {
        logger.error(e.getMessage(), e);
    } finally {
        Thread.currentThread().setContextClassLoader(tccl);
    }

    return null;
}