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:org.wso2.carbon.identity.application.authentication.framework.config.model.graph.JsGraphBuilderFactory.java

public static void restoreCurrentContext(AuthenticationContext context, ScriptEngine engine)
        throws FrameworkException {

    Map<String, Object> map = (Map<String, Object>) context.getProperty(JS_BINDING_CURRENT_CONTEXT);
    Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
    if (map != null) {
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            Object deserializedValue = FrameworkUtils.fromJsSerializable(entry.getValue(), engine);
            if (deserializedValue instanceof AbstractJSObjectWrapper) {
                ((AbstractJSObjectWrapper) deserializedValue).initializeContext(context);
            }//from  www. j ava2  s . co  m
            bindings.put(entry.getKey(), deserializedValue);
        }
    }
}

From source file:utybo.branchingstorytree.swing.impl.XSFClient.java

@Override
public Object invokeScript(String resourceName, String function, XSFBridge bst, BranchingStory story, int line)
        throws BSTException {
    ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName("JavaScript");
    SimpleBindings binds = new SimpleBindings();
    binds.putAll(story.getRegistry().getAllInt());
    binds.putAll(story.getRegistry().getAllString());
    binds.put("bst", bst);
    scriptEngine.setBindings(binds, ScriptContext.ENGINE_SCOPE);
    try {//  w ww .  j a  v  a2 s  .  com
        scriptEngine.eval(scripts.get(resourceName));
        return scriptEngine.eval(function + "()");
    } catch (ScriptException e) {
        throw new BSTException(line, "Script exception : " + e.getMessage(), story);
    }
}

From source file:org.wso2.carbon.uuf.renderablecreator.hbs.internal.serialize.JsonSerializerTest.java

private static Bindings executeJavaScript(String jsScript) throws ScriptException {
    NashornScriptEngineFactory scriptEngineFactory = new NashornScriptEngineFactory();
    ScriptEngine engine = scriptEngineFactory.getScriptEngine("-strict", "--optimistic-types");
    engine.eval(jsScript);//  ww w. j  a va2 s.co  m
    return engine.getBindings(ScriptContext.ENGINE_SCOPE);
}

From source file:org.red5.server.script.rhino.RhinoScriptUtils.java

/**
 * Create a new Rhino-scripted object from the given script source.
 * /*from  w w w. j a  va  2 s  .  c om*/
 * @param scriptSource
 *            the script source text
 * @param interfaces
 *            the interfaces that the scripted Java object is supposed to
 *            implement
 * @param extendedClass
 * @return the scripted Java object
 * @throws ScriptCompilationException
 *             in case of Rhino parsing failure
 * @throws java.io.IOException
 */
@SuppressWarnings("rawtypes")
public static Object createRhinoObject(String scriptSource, Class[] interfaces, Class extendedClass)
        throws ScriptCompilationException, IOException, Exception {
    if (log.isDebugEnabled()) {
        log.debug("Script Engine Manager: " + mgr.getClass().getName());
    }
    ScriptEngine engine = mgr.getEngineByExtension("js");
    if (null == engine) {
        log.warn("Javascript is not supported in this build");
    }
    // set engine scope namespace
    Bindings nameSpace = engine.getBindings(ScriptContext.ENGINE_SCOPE);
    // add the logger to the script
    nameSpace.put("log", log);
    // compile the wrapper script
    CompiledScript wrapper = ((Compilable) engine).compile(jsWrapper);
    nameSpace.put("Wrapper", wrapper);

    // get the function name ie. class name / ctor
    String funcName = RhinoScriptUtils.getFunctionName(scriptSource);
    if (log.isDebugEnabled()) {
        log.debug("New script: " + funcName);
    }
    // set the 'filename'
    nameSpace.put(ScriptEngine.FILENAME, funcName);

    if (null != interfaces) {
        nameSpace.put("interfaces", interfaces);
    }

    if (null != extendedClass) {
        if (log.isDebugEnabled()) {
            log.debug("Extended: " + extendedClass.getName());
        }
        nameSpace.put("supa", extendedClass.newInstance());
    }
    //
    // compile the script
    CompiledScript script = ((Compilable) engine).compile(scriptSource);
    // eval the script with the associated namespace
    Object o = null;
    try {
        o = script.eval();
    } catch (Exception e) {
        log.error("Problem evaluating script", e);
    }
    if (log.isDebugEnabled()) {
        log.debug("Result of script call: " + o);
    }
    // script didnt return anything we can use so try the wrapper
    if (null == o) {
        wrapper.eval();
    } else {
        wrapper.eval();
        o = ((Invocable) engine).invokeFunction("Wrapper", new Object[] { engine.get(funcName) });
        if (log.isDebugEnabled()) {
            log.debug("Result of invokeFunction: " + o);
        }
    }
    return Proxy.newProxyInstance(ClassUtils.getDefaultClassLoader(), interfaces,
            new RhinoObjectInvocationHandler(engine, o));
}

From source file:io.lavagna.service.ApiHooksService.java

private static void executeScript(String name, CompiledScript script, Map<String, Object> scope) {
    try {//from ww w  .ja  va 2 s  .c  o  m
        ScriptContext newContext = new SimpleScriptContext();
        Bindings engineScope = newContext.getBindings(ScriptContext.ENGINE_SCOPE);
        engineScope.putAll(scope);
        engineScope.put("log", LOG);
        engineScope.put("GSON", Json.GSON);
        engineScope.put("restTemplate", new RestTemplate());
        script.eval(newContext);
    } catch (ScriptException ex) {
        LOG.warn("Error while executing script " + name, ex);
    }
}

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

public static void persistCurrentContext(AuthenticationContext context, ScriptEngine engine) {

    Bindings engineBindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
    Map<String, Object> persistableMap = new HashMap<>();
    engineBindings.forEach((key, value) -> persistableMap.put(key, FrameworkUtils.toJsSerializable(value)));
    context.setProperty(JS_BINDING_CURRENT_CONTEXT, persistableMap);
}

From source file:org.netbeans.jcode.parser.ejs.EJSParser.java

public EJSParser() {

    try {//from ww w.  j  a  v a  2 s.co m
        engine = new ScriptEngineManager().getEngineByName("nashorn");
        engine.eval("var window = this;" + "var console = {\n" + "  debug: print,\n" + "  warn: print,\n"
                + "  log: print\n" + "};" + "function contains(obj, a) {\n"
                + "    for (var i = 0; i < a.length; i++) {\n" + "        if (a[i] === obj) {\n"
                + "            return true;\n" + "        }\n" + "    }\n" + "    return false;\n" + "}");

        Compilable compilingEngine = (Compilable) engine;
        cscript = compilingEngine
                .compile(new BufferedReader(new InputStreamReader(EJSParser.class.getClassLoader()
                        .getResourceAsStream("org/netbeans/jcode/parser/ejs/resources/ejs.js"), "UTF-8")));
        bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
        cscript.eval(bindings);
    } catch (ScriptException | UnsupportedEncodingException ex) {
        Exceptions.printStackTrace(ex);
    }
}

From source file:cloudlens.engine.CL.java

public CL(OutputStream out, OutputStream err, boolean stream, boolean withHistory) {
    this.stream = stream;
    this.withHistory = withHistory;
    this.executed = false;
    this.out = out;
    outWriter = new PrintWriter(out);
    this.err = err;
    errWriter = new PrintWriter(err);
    engine = new JSEngine();
    engine.getContext().setWriter(outWriter);
    engine.getContext().setErrorWriter(errWriter);
    engine.getContext().getBindings(ScriptContext.ENGINE_SCOPE).put("CLx", this);
    engine.eval(/*from  w ww.j  av a  2s.c o  m*/
            "(function() { var f = __noSuchProperty__; __noSuchProperty__ = function(name) { try { return f(name); } catch(err) { return undefined; } } })()");
    engine.eval("var CL = {result:null," + "log: (function() { var v = CLx; return function() v.log() }) (),"
            + "loadjs:(function() { var v = CLx; return function(url) v.loadjs(url) })(),"
            + "export:(function() { var v = CLx; return function(file) v.export(file) })(),"
            + "findRegex:(function() { var v = CLx; return function(regex, input) v.findRegex(regex, input) })(),"
            + "run:(function(){var v = CLx; return function(lens, stream, jsArgs){return v.run(lens, stream, jsArgs)} })(),"
            + " }");
    engine.eval("CL.log.toString = function() 'function log() { [native code] }'");
    engine.eval("CL.loadjs.toString = function() 'function loadjs() { [native code] }'");
    engine.eval("CL.export.toString = function() 'function export() { [native code] }'");
    engine.eval("CL.findRegex.toString = function() 'function findRegex() { [native code] }'");
    engine.eval("CL.run.toString = function() 'function run() { [native code] }'");
    engine.eval("Object.defineProperty(Function('return this')(), 'CL', {configurable:false, writable:false})");
    this.cl = engine.eval("CL");
    this.heapIt = new ArrayList<>();
    heapIt.add(0, new CLIterator(engine, engine.newArray(), withHistory));
}

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 {// ww  w. j  a  v a  2  s.com
        // 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:tk.tomby.tedit.services.ScriptingManager.java

/**
 * DOCUMENT ME!/* www  .  ja v a2  s .c om*/
 *
 * @param lang DOCUMENT ME!
 * @param script DOCUMENT ME!
 * @param buffer DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 */
public static Object eval(String lang, String script, IBuffer buffer) {
    Object result = null;

    try {
        ScriptEngine engine = manager.getEngineByName(lang);

        if (buffer != null) {
            Bindings bindings = engine.createBindings();
            bindings.put("buffer", new BufferDecorator(buffer));
            engine.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
        }

        result = engine.eval(script);
    } catch (ScriptException e) {
        log.error("error in script excution", e);
    }

    return result;
}