Example usage for javax.script ScriptEngine getBindings

List of usage examples for javax.script ScriptEngine getBindings

Introduction

In this page you can find the example usage for javax.script ScriptEngine getBindings.

Prototype

public Bindings getBindings(int scope);

Source Link

Document

Returns a scope of named values.

Usage

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  v a 2  s . c o m*/
 * @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:org.wso2.carbon.business.rules.core.util.TemplateManagerHelper.java

/**
 * Runs the script that is given as a string, and gives all the variables specified in the script
 *
 * @param script/*w w w .  ja va  2  s . co m*/
 * @return Map of Strings
 * @throws TemplateManagerHelperException
 */
public static Map<String, String> getScriptGeneratedVariables(String script)
        throws RuleTemplateScriptException {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");

    ScriptContext scriptContext = new SimpleScriptContext();
    scriptContext.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE);

    try {
        // Run script
        engine.eval(script);
        Map<String, Object> returnedScriptContextBindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);

        // Variable names and their values as strings, from the script context binding
        Map<String, String> scriptVariables = new HashMap<>();
        for (Map.Entry scriptVariable : returnedScriptContextBindings.entrySet()) {
            if (scriptVariable.getValue() == null) {
                scriptVariables.put(scriptVariable.getKey().toString(), null);
            } else {
                scriptVariables.put(scriptVariable.getKey().toString(), scriptVariable.getValue().toString());
            }
        }
        return scriptVariables;
    } catch (ScriptException e) {
        throw new RuleTemplateScriptException(e.getCause().getMessage(), e);
    }
}

From source file:org.paxml.test.SelfTest.java

public void testSyntax() throws Exception {
    ScriptEngine runtime = new ScriptEngineManager().getEngineByName("javascript");
    Bindings bindings = runtime.getBindings(ScriptContext.ENGINE_SCOPE);
    bindings.put("util", "xx");
    runtime.setBindings(new SimpleBindings() {

    }, ScriptContext.ENGINE_SCOPE);

}

From source file:com.intuit.karate.Script.java

public static ScriptValue evalInNashorn(String exp, ScriptContext context, ScriptValue selfValue,
        ScriptValue parentValue) {//from  www .  j ava  2s. c  o  m
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine nashorn = manager.getEngineByName("nashorn");
    Bindings bindings = nashorn.getBindings(javax.script.ScriptContext.ENGINE_SCOPE);
    if (context != null) {
        Map<String, Object> map = context.getVariableBindings();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            bindings.put(entry.getKey(), entry.getValue());
        }
        bindings.put(ScriptContext.KARATE_NAME, new ScriptBridge(context));
    }
    if (selfValue != null) {
        bindings.put(VAR_SELF, selfValue.getValue());
    }
    if (parentValue != null) {
        bindings.put(VAR_DOLLAR, parentValue.getAfterConvertingFromJsonOrXmlIfNeeded());
    }
    try {
        Object o = nashorn.eval(exp);
        ScriptValue result = new ScriptValue(o);
        logger.trace("nashorn returned: {}", result);
        return result;
    } catch (Exception e) {
        throw new RuntimeException("script failed: " + exp, e);
    }
}

From source file:io.lightlink.translator.JSBeautifyPostProcessor.java

@Override
public String process(String script) throws IOException {
    String beautifier = IOUtils.toString(Thread.currentThread().getContextClassLoader()
            .getResourceAsStream("io/lightlink/translator/beautify.js"));

    ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
    try {/*from  ww  w .j  a  va2s  .c  o m*/
        engine.eval(beautifier);
        engine.getBindings(ScriptContext.ENGINE_SCOPE).put("$originalScript", script);
        return engine.eval("js_beautify($originalScript, {})") + "";
    } catch (ScriptException e) {
        LOG.error(e.toString(), e);
        return script;
    }

}

From source file:cc.arduino.net.CustomProxySelector.java

private Proxy pacProxy(String pac, URI uri) throws IOException, ScriptException, NoSuchMethodException {
    setAuthenticator(preferences.get(Constants.PREF_PROXY_AUTO_USERNAME),
            preferences.get(Constants.PREF_PROXY_AUTO_PASSWORD));

    URLConnection urlConnection = new URL(pac).openConnection();
    urlConnection.connect();/*  w  w  w .j  a  va  2s  .c  o m*/
    if (urlConnection instanceof HttpURLConnection) {
        int responseCode = ((HttpURLConnection) urlConnection).getResponseCode();
        if (responseCode != 200) {
            throw new IOException("Unable to fetch PAC file at " + pac + ". Response code is " + responseCode);
        }
    }
    String pacScript = new String(IOUtils.toByteArray(urlConnection.getInputStream()),
            Charset.forName("ASCII"));

    ScriptEngine nashorn = new ScriptEngineManager().getEngineByName("nashorn");
    nashorn.getBindings(ScriptContext.ENGINE_SCOPE).put("pac", new PACSupportMethods());
    Stream.of("isPlainHostName(host)", "dnsDomainIs(host, domain)", "localHostOrDomainIs(host, hostdom)",
            "isResolvable(host)", "isInNet(host, pattern, mask)", "dnsResolve(host)", "myIpAddress()",
            "dnsDomainLevels(host)", "shExpMatch(str, shexp)").forEach((fn) -> {
                try {
                    nashorn.eval("function " + fn + " { return pac." + fn + "; }");
                } catch (ScriptException e) {
                    throw new RuntimeException(e);
                }
            });
    nashorn.eval(pacScript);
    String proxyConfigs = callFindProxyForURL(uri, nashorn);
    return makeProxyFrom(proxyConfigs);
}

From source file:org.jasig.maven.plugin.sass.AbstractSassMojo.java

/**
 * Execute the SASS Compilation Ruby Script
 *//*from ww  w .j av  a  2s  .  com*/
protected void executeSassScript(String sassScript) throws MojoExecutionException, MojoFailureException {
    final Log log = this.getLog();
    System.setProperty("org.jruby.embed.localcontext.scope", "threadsafe");

    log.debug("Execute SASS Ruby Script:\n" + sassScript);

    final ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
    final ScriptEngine jruby = scriptEngineManager.getEngineByName("jruby");
    try {
        CompilerCallback compilerCallback = new CompilerCallback(log);
        jruby.getBindings(ScriptContext.ENGINE_SCOPE).put("compiler_callback", compilerCallback);
        jruby.eval(sassScript);
        if (failOnError && compilerCallback.hadError()) {
            throw new MojoFailureException("SASS compilation encountered errors (see above for details).");
        }
    } catch (final ScriptException e) {
        throw new MojoExecutionException("Failed to execute SASS ruby script:\n" + sassScript, e);
    }
}

From source file:org.jtotus.network.NordnetConnect.java

public String fetchEncryptedPassword(String encryptJS, String pass, String pubKey, String sessionId) {
    String password = null;// w  w  w  . j  a  va  2 s  . c o  m

    StartUpLoader loader = StartUpLoader.getInstance();

    //ScriptEngineManager mgr = loader.getLoadedScriptManager();
    //         Bindings bindings = mgr.getBindings();

    ScriptEngine engine = loader.getLoadedEngine();
    Bindings bindings = engine.getBindings(ScriptContext.GLOBAL_SCOPE);

    try {
        StringBuilder strBuild = new StringBuilder();
        strBuild.append(encryptJS);

        strBuild.append(" \n var keyObj = RSA.getPublicKey(\'" + pubKey + "\');\n"
                + "  var encryptedPass = RSA.encrypt(\'" + pass + "\', keyObj, \'" + sessionId + "\');\n");

        engine.eval(strBuild.toString(), bindings);

        password = (String) bindings.get("encryptedPass");

    } catch (ScriptException ex) {
        Logger.getLogger(NordnetConnector.class.getName()).log(Level.SEVERE, null, ex);
    }

    log.info("JavaScript engine loaded:" + engine.NAME);

    return password;
}

From source file:org.apache.nifi.reporting.script.ScriptedReportingTask.java

@Override
public void onTrigger(final ReportingContext context) {
    synchronized (scriptingComponentHelper.isInitialized) {
        if (!scriptingComponentHelper.isInitialized.get()) {
            scriptingComponentHelper.createResources();
        }//from ww  w  . j  a v a  2s  .c  om
    }
    ScriptEngine scriptEngine = scriptingComponentHelper.engineQ.poll();
    ComponentLog log = getLogger();
    if (scriptEngine == null) {
        // No engine available so nothing more to do here
        return;
    }

    try {

        try {
            Bindings bindings = scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE);
            if (bindings == null) {
                bindings = new SimpleBindings();
            }
            bindings.put("context", context);
            bindings.put("log", log);
            bindings.put("vmMetrics", vmMetrics);

            // Find the user-added properties and set them on the script
            for (Map.Entry<PropertyDescriptor, String> property : context.getProperties().entrySet()) {
                if (property.getKey().isDynamic()) {
                    // Add the dynamic property bound to its full PropertyValue to the script engine
                    if (property.getValue() != null) {
                        bindings.put(property.getKey().getName(), context.getProperty(property.getKey()));
                    }
                }
            }

            scriptEngine.setBindings(bindings, ScriptContext.ENGINE_SCOPE);

            // Execute any engine-specific configuration before the script is evaluated
            ScriptEngineConfigurator configurator = scriptingComponentHelper.scriptEngineConfiguratorMap
                    .get(scriptingComponentHelper.getScriptEngineName().toLowerCase());

            // Evaluate the script with the configurator (if it exists) or the engine
            if (configurator != null) {
                configurator.eval(scriptEngine, scriptToRun, scriptingComponentHelper.getModules());
            } else {
                scriptEngine.eval(scriptToRun);
            }
        } catch (ScriptException e) {
            throw new ProcessException(e);
        }
    } catch (final Throwable t) {
        // Mimic AbstractProcessor behavior here
        getLogger().error("{} failed to process due to {}; rolling back session", new Object[] { this, t });
        throw t;
    } finally {
        scriptingComponentHelper.engineQ.offer(scriptEngine);
    }

}

From source file:org.jaffa.rules.util.ScriptEnginePool.java

/**
 * Clears the script engine of all previous state except, if it is a BeanShell interpreter,
 * the engine is left/*from w  ww.j a va 2s .c  o m*/
 *
 * @param scriptEngine ScriptEngine to clear
 */
private void clearEngine(String language, ScriptEngine scriptEngine) {
    // Clear everything except the BeanShell engine ("bsh" in the binding)
    // This will clear all imported class, methods, and variables
    List<String> itemsToRemove = new ArrayList<String>();
    for (Map.Entry<String, Object> bindingEntry : scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE)
            .entrySet()) {
        if (language.equalsIgnoreCase(BEANSHELL)
                && bindingEntry.getKey().equalsIgnoreCase(BEANSHELL_ENGINE_NAME)) {
            continue;
        }
        itemsToRemove.add(bindingEntry.getKey());
    }
    for (String value : itemsToRemove) {
        scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE).remove(value);
    }

    // Clear entire global scope
    scriptEngine.getBindings(ScriptContext.GLOBAL_SCOPE).clear();
}