Example usage for javax.script ScriptContext setBindings

List of usage examples for javax.script ScriptContext setBindings

Introduction

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

Prototype

public void setBindings(Bindings bindings, int scope);

Source Link

Document

Associates a Bindings instance with a particular scope in this ScriptContext.

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 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);/*w ww . j a  v a 2s  .co m*/

    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:Main.java

public static void main(String[] args) throws Exception {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");
    engine.eval("var msg = 'Hello globals'");
    engine.eval("print(this.msg);");
    ScriptContext ctx = new SimpleScriptContext();
    ScriptContext defaultCtx = engine.getContext();
    Bindings engineBindings = defaultCtx.getBindings(ENGINE_SCOPE);
    ctx.setBindings(engineBindings, ENGINE_SCOPE);
    engine.eval("print(this.msg);", ctx);
}

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 w ww  .  jav  a 2  s. co  m

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

    engine.setContext(ctx);
}

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:be.solidx.hot.JSR223ScriptExecutor.java

@Override
public Object execute(Script<CompiledScript> script, Map<String, Object> contextVars) throws ScriptException {
    try {//ww w.  ja  v  a 2s  .  c om
        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.nuxeo.connect.connector.http.proxy.NashornProxyPacResolver.java

@Override
public String[] findPacProxies(String url) {
    ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
    ScriptContext context = new SimpleScriptContext();
    engine.setContext(context); // set as default context, for invokeFunctino
    SimpleBindings bindings = new SimpleBindings();
    context.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
    try {//from www  . j a  va 2s .  c  o m
        // Register internet functions as Java upcalls
        engine.eval("var NashornProxyPacResolver = Java.type('" + getClass().getName() + "');"
                + "var dnsResolve = NashornProxyPacResolver.dnsResolve;"
                + "var myIpAddress = NashornProxyPacResolver.myIpAddress");
        // Register others pac methods
        engine.eval(getFileReader(PAC_FUNCTIONS_FILE));
        // Register remote pac function
        engine.eval(getRemotePacBodyReader());
        // Call and return pac resolution function
        String proxies = (String) ((Invocable) engine).invokeFunction(EXEC_PAC_FUNC, url, getHost(url));
        return proxies.split(";");
    } catch (IOException | ScriptException | NoSuchMethodException e) {
        log.warn(e, e);
    }
    return null;
}

From source file:org.jahia.modules.irclogs.filters.IRCLogPageTitleFilter.java

@Override
public String execute(String previousOut, RenderContext renderContext, Resource resource, RenderChain chain)
        throws Exception {
    String out = previousOut;/*from   w w  w.  j  a  va  2  s .  c  om*/
    String script = getResolvedTemplate();
    if (script != null) {
        Source source = new Source(previousOut);
        OutputDocument outputDocument = new OutputDocument(source);
        List<Element> headElementList = source.getAllElements(HTMLElementName.TITLE);
        for (Element element : headElementList) {
            final EndTag bodyEndTag = element.getEndTag();
            final StartTag bodyStartTag = element.getStartTag();
            String extension = StringUtils.substringAfterLast(template, ".");
            ScriptEngine scriptEngine = scriptEngineUtils.scriptEngine(extension);
            ScriptContext scriptContext = new irclogsScriptContext();
            final Bindings bindings = scriptEngine.createBindings();
            bindings.put("resource", resource);
            scriptContext.setBindings(bindings, ScriptContext.GLOBAL_SCOPE);

            // The following binding is necessary for Javascript, which doesn't offer a console by default.
            bindings.put("out", new PrintWriter(scriptContext.getWriter()));

            // Parameters needed for title replacing
            bindings.put("orgTitle",
                    outputDocument.toString().substring(bodyStartTag.getEnd(), bodyEndTag.getBegin()));
            bindings.put("dateFormatter", dateFormatter);
            bindings.put("title", getTitle());
            bindings.put("renderContext", renderContext);

            scriptEngine.eval(script, scriptContext);
            StringWriter writer = (StringWriter) scriptContext.getWriter();
            final String irclogsScript = writer.toString();
            if (StringUtils.isNotBlank(irclogsScript)) {
                outputDocument.replace(bodyStartTag.getEnd(), bodyEndTag.getBegin() + 1,
                        AggregateCacheFilter.removeEsiTags(irclogsScript) + "<");
            }
            break; // avoid to loop if for any reasons multiple body in the page
        }
        out = outputDocument.toString().trim();
    }

    return out;
}

From source file:org.jahia.modules.portal.filter.PortalLibFilter.java

@Override
public String execute(String previousOut, RenderContext renderContext, Resource resource, RenderChain chain)
        throws Exception {
    String out = previousOut;/*from  w  w  w.  jav a 2 s  . co m*/

    // add portal API lib
    String path = "/modules/" + renderContext.getMainResource().getNode().getPrimaryNodeType()
            .getTemplatePackage().getBundle().getSymbolicName() + "/javascript/" + JS_API_FILE;
    path = StringUtils.isNotEmpty(renderContext.getRequest().getContextPath())
            ? renderContext.getRequest().getContextPath() + path
            : path;
    String encodedPath = URLEncoder.encode(path, "UTF-8");
    out += ("<jahia:resource type='javascript' path='" + encodedPath + "' insert='true' resource='"
            + JS_API_FILE + "'/>");

    // add portal instance
    String script = getResolvedTemplate();
    if (script != null) {
        String extension = StringUtils.substringAfterLast(template, ".");
        ScriptEngine scriptEngine = scriptEngineUtils.scriptEngine(extension);
        ScriptContext scriptContext = new PortalScriptContext();
        final Bindings bindings = scriptEngine.createBindings();

        // bindings
        bindings.put("portalContext", serializePortal(renderContext));
        scriptContext.setBindings(bindings, ScriptContext.GLOBAL_SCOPE);
        // The following binding is necessary for Javascript, which doesn't offer a console by default.
        bindings.put("out", new PrintWriter(scriptContext.getWriter()));
        scriptEngine.eval(script, scriptContext);
        StringWriter writer = (StringWriter) scriptContext.getWriter();
        final String portalScript = writer.toString();
        if (StringUtils.isNotBlank(portalScript)) {
            out += ("<jahia:resource type='inlinejavascript' path='" + URLEncoder.encode(portalScript, "UTF-8")
                    + "' insert='false' resource='' title='' key=''/>");
        }
    }

    return out;
}