Example usage for javax.script ScriptContext setAttribute

List of usage examples for javax.script ScriptContext setAttribute

Introduction

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

Prototype

public void setAttribute(String name, Object value, int scope);

Source Link

Document

Sets the value of an attribute in a given scope.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    ScriptContext ctx = new SimpleScriptContext();
    ctx.setAttribute("year", 2015, ScriptContext.ENGINE_SCOPE);
    ctx.setAttribute("month", 9, ScriptContext.ENGINE_SCOPE);
    ctx.setAttribute("day", 21, ScriptContext.ENGINE_SCOPE);

}

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) {
    ScriptContext ctx = new SimpleScriptContext();
    List<Integer> scopes = ctx.getScopes();
    System.out.println("Supported Scopes: " + scopes);

    ctx.setAttribute("year", 2015, ENGINE_SCOPE);

    Bindings globalBindings = new SimpleBindings();
    ctx.setBindings(globalBindings, GLOBAL_SCOPE);

    ctx.setAttribute("year", 2014, GLOBAL_SCOPE);
    ctx.setAttribute("name", "Jack", GLOBAL_SCOPE);

    String nameValue = (String) ctx.getAttribute("name");
    System.out.println("nameValue = " + nameValue);

    int engineScopeYear = (Integer) ctx.getAttribute("year", ENGINE_SCOPE);
    int globalScopeYear = (Integer) ctx.getAttribute("year", GLOBAL_SCOPE);

    System.out.println("engineScopeYear = " + engineScopeYear);
    System.out.println("globalScopeYear = " + globalScopeYear);
}

From source file:Main.java

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

    manager.put("n1", 1);
    String script = "var sum = n1 + n2;print(msg + " + "' n1=' + n1 + ', n2=' + n2 + " + "', sum=' + sum);";

    engine.put("n2", 2);
    engine.put("msg", "a string");
    engine.eval(script);/*from  w  w  w .  j a v  a2 s. com*/

    Bindings bindings = engine.createBindings();
    bindings.put("n2", 3);
    bindings.put("msg", "another string");
    engine.eval(script, bindings);

    ScriptContext ctx = new SimpleScriptContext();
    Bindings ctxGlobalBindings = engine.createBindings();
    ctx.setBindings(ctxGlobalBindings, GLOBAL_SCOPE);
    ctx.setAttribute("n1", 4, GLOBAL_SCOPE);
    ctx.setAttribute("n2", 5, ENGINE_SCOPE);
    ctx.setAttribute("msg", "ScriptContext:", ENGINE_SCOPE);
    engine.eval(script, ctx);

    engine.eval(script);
}

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

From source file:io.cloudslang.lang.runtime.bindings.ScriptEvaluator.java

public Serializable evalExpr(String expr, Map<String, ? extends Serializable> context) {
    ScriptContext scriptContext = new SimpleScriptContext();
    for (Map.Entry<String, ? extends Serializable> entry : context.entrySet()) {
        scriptContext.setAttribute(entry.getKey(), entry.getValue(), ScriptContext.ENGINE_SCOPE);
    }/*from   w  w  w. ja v  a2s  .co m*/
    if (scriptContext.getAttribute(TRUE) == null)
        scriptContext.setAttribute(TRUE, Boolean.TRUE, ScriptContext.ENGINE_SCOPE);
    if (scriptContext.getAttribute(FALSE) == null)
        scriptContext.setAttribute(FALSE, Boolean.FALSE, ScriptContext.ENGINE_SCOPE);
    try {
        return (Serializable) engine.eval(expr, scriptContext);
    } catch (ScriptException e) {
        ScriptException scriptException = new ScriptException(e);
        throw new RuntimeException("Error in running script expression or variable reference, for expression: '"
                + expr + "',\n\tScript exception is: " + scriptException.getMessage(), scriptException);
    }
}

From source file:org.openscore.lang.runtime.bindings.ScriptEvaluator.java

public Serializable evalExpr(String expr, Map<String, ? extends Serializable> context) {
    ScriptContext scriptContext = new SimpleScriptContext();
    for (Map.Entry<String, ? extends Serializable> entry : context.entrySet()) {
        scriptContext.setAttribute(entry.getKey(), entry.getValue(), ScriptContext.ENGINE_SCOPE);
    }//from  w  w  w .  j  a  va2s  .co m
    if (scriptContext.getAttribute(TRUE) == null)
        scriptContext.setAttribute(TRUE, Boolean.TRUE, ScriptContext.ENGINE_SCOPE);
    if (scriptContext.getAttribute(FALSE) == null)
        scriptContext.setAttribute(FALSE, Boolean.FALSE, ScriptContext.ENGINE_SCOPE);
    try {
        return (Serializable) engine.eval(expr, scriptContext);
    } catch (ScriptException e) {
        ScriptException scriptException = new ScriptException(e);
        throw new RuntimeException("Error in running script expression or variable reference, for expression: '"
                + expr + "', Script exception is: \n" + scriptException.getMessage(), scriptException);
    }
}

From source file:com.lucidtechnics.blackboard.util.Jsr223ScriptingUtil.java

public Object executeScript(String _scriptResource) {
    ScriptContext scriptContext = getScriptEngine().getContext();

    Object result = null;//ww w. j  ava  2  s  .  com

    try {
        for (String key : getBindingsMap().keySet()) {
            scriptContext.setAttribute(key, getBindingsMap().get(key), ScriptContext.ENGINE_SCOPE);
        }

        CompiledScript script = compileScript(_scriptResource);

        if (script != null) {
            result = script.eval(scriptContext);
        } else {
            result = getScriptEngine().eval(new InputStreamReader(findScript(_scriptResource)), scriptContext);
        }
    } catch (Throwable t) {
        throw new RuntimeException(
                "Unable to execute script: " + _scriptResource + " for this reason: " + t.toString(), t);
    }

    return result;
}

From source file:com.lucidtechnics.blackboard.util.Jsr223ScriptingUtil.java

public Object executeScript(String[] _scriptResources) {
    ScriptContext scriptContext = getScriptEngine().getContext();

    Object result = null;/* www.  ja v a  2  s  . com*/

    int i = 0;

    try {
        for (String key : getBindingsMap().keySet()) {
            scriptContext.setAttribute(key, getBindingsMap().get(key), ScriptContext.ENGINE_SCOPE);
        }

        for (i = 0; i < _scriptResources.length; i++) {
            CompiledScript script = compileScript(_scriptResources[i]);

            if (script != null) {
                result = script.eval(scriptContext);
            } else {
                result = getScriptEngine().eval(new InputStreamReader(findScript(_scriptResources[i])),
                        scriptContext);
            }
        }
    } catch (Throwable t) {
        throw new RuntimeException(
                "Unable to execute script: " + _scriptResources[i] + " for this reason: " + t.toString(), t);
    }

    return result;
}

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

public void executeScript(ScriptEngine engine, File file) throws FileNotFoundException, ScriptException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));

    if (VERBOSE_LOADING) {
        log.info("Loading Script: " + file.getAbsolutePath());
    }//w  ww .j  av  a 2 s.co m

    if (PURGE_ERROR_LOG) {
        String name = file.getAbsolutePath() + ".error.log";
        File errorLog = new File(name);
        if (errorLog.isFile()) {
            errorLog.delete();
        }
    }

    if (engine instanceof Compilable && ATTEMPT_COMPILATION) {
        ScriptContext context = new SimpleScriptContext();
        context.setAttribute("mainClass", getClassForFile(file).replace('/', '.').replace('\\', '.'),
                ScriptContext.ENGINE_SCOPE);
        context.setAttribute(ScriptEngine.FILENAME, file.getName(), ScriptContext.ENGINE_SCOPE);
        context.setAttribute("classpath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE);
        context.setAttribute("sourcepath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE);
        context.setAttribute("parentLoader", ClassLoader.getSystemClassLoader(), ScriptContext.ENGINE_SCOPE);

        setCurrentLoadingScript(file);
        ScriptContext ctx = engine.getContext();
        try {
            engine.setContext(context);
            if (USE_COMPILED_CACHE) {
                CompiledScript cs = _cache.loadCompiledScript(engine, file);
                cs.eval(context);
            } else {
                Compilable eng = (Compilable) engine;
                CompiledScript cs = eng.compile(reader);
                cs.eval(context);
            }
        } finally {
            engine.setContext(ctx);
            setCurrentLoadingScript(null);
            context.removeAttribute(ScriptEngine.FILENAME, ScriptContext.ENGINE_SCOPE);
            context.removeAttribute("mainClass", ScriptContext.ENGINE_SCOPE);
            context.removeAttribute("parentLoader", ScriptContext.ENGINE_SCOPE);
        }
    } else {
        ScriptContext context = new SimpleScriptContext();
        context.setAttribute("mainClass", getClassForFile(file).replace('/', '.').replace('\\', '.'),
                ScriptContext.ENGINE_SCOPE);
        context.setAttribute(ScriptEngine.FILENAME, file.getName(), ScriptContext.ENGINE_SCOPE);
        context.setAttribute("classpath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE);
        context.setAttribute("sourcepath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE);
        context.setAttribute("parentLoader", ClassLoader.getSystemClassLoader(), ScriptContext.ENGINE_SCOPE);
        setCurrentLoadingScript(file);
        try {
            engine.eval(reader, context);
        } finally {
            setCurrentLoadingScript(null);
            engine.getContext().removeAttribute(ScriptEngine.FILENAME, ScriptContext.ENGINE_SCOPE);
            engine.getContext().removeAttribute("mainClass", ScriptContext.ENGINE_SCOPE);
            engine.getContext().removeAttribute("parentLoader", ScriptContext.ENGINE_SCOPE);
        }

    }
}