Example usage for javax.script ScriptEngineManager ScriptEngineManager

List of usage examples for javax.script ScriptEngineManager ScriptEngineManager

Introduction

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

Prototype

public ScriptEngineManager() 

Source Link

Document

The effect of calling this constructor is the same as calling ScriptEngineManager(Thread.currentThread().getContextClassLoader()).

Usage

From source file:com.qframework.core.ServerkoParse.java

ServerkoParse(GameonApp theApp) {

    mApp = theApp;/* w w w  .  j  a v a  2 s. c  o  m*/
    mMgr = new ScriptEngineManager();
    mScriptView = mMgr.getEngineByName("JavaScript");
    String scr = new String(
            "console ={msgs: new Array(), log: function(msg)   { console.msgs.push(msg); },info: function(msg) { console.msgs.push(msg); },warn : function(msg) { console.msgs.push(msg); },error: function(msg) { console.msgs.push(msg); },shift: function() { return console.msgs.shift(); }};");
    try {
        mScriptView.eval(scr);
    } catch (ScriptException e) {
        e.printStackTrace();
    }
}

From source file:org.apache.ranger.plugin.conditionevaluator.RangerScriptConditionEvaluator.java

@Override
public void init() {

    if (LOG.isDebugEnabled()) {
        LOG.debug("==> RangerScriptConditionEvaluator.init(" + condition + ")");
    }/*from  w w w . j  a v a 2s.com*/

    super.init();

    String engineName = "JavaScript";

    Map<String, String> evalOptions = conditionDef.getEvaluatorOptions();

    if (MapUtils.isNotEmpty(evalOptions)) {
        engineName = evalOptions.get("engineName");
    }

    if (StringUtils.isBlank(engineName)) {
        engineName = "JavaScript";
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("RangerScriptConditionEvaluator.init() - engineName=" + engineName);
    }

    try {
        ScriptEngineManager manager = new ScriptEngineManager();
        scriptEngine = manager.getEngineByName(engineName);
    } catch (Exception exp) {
        LOG.error("RangerScriptConditionEvaluator.init() failed with exception=" + exp);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("<== RangerScriptConditionEvaluator.init(" + condition + ")");
    }
}

From source file:org.wso2telco.dep.nashornmediator.NashornMediator.java

public NashornMediator() {
    try {//from  ww  w  .j a  va2  s  .c o  m
        scriptEngine = new ScriptEngineManager().getEngineByName("nashorn");
        emptyJsonObject = scriptEngine.eval("({})");
        jsonParser = new JsonParser();
    } catch (ScriptException e) {
        throw new SynapseException("Error occurred while initialising mediator", e);
    }
}

From source file:com.hypersocket.upgrade.UpgradeServiceImpl.java

public UpgradeServiceImpl() {
    manager = new ScriptEngineManager();
}

From source file:org.quackbot.hooks.loaders.JSHookLoader.java

@Override
public QListener load(String fileLocation) throws Exception {
    if (fileLocation.endsWith("JS_Template.js") || fileLocation.endsWith("QuackUtils.js"))
        //Ignore this
        return null;

    String[] pathParts = StringUtils.split(fileLocation, System.getProperty("file.separator"));
    String name = StringUtils.split(pathParts[pathParts.length - 1], ".")[0];
    log.info("New JavaScript Plugin: " + name);

    //Add utilities and wrappings
    ScriptEngine jsEngine = new ScriptEngineManager().getEngineByName("JavaScript");
    jsEngine.put("log", LoggerFactory.getLogger("JSPlugins." + name));
    LinkedHashMap<String, String> sourceMap = new LinkedHashMap();
    evalResource(jsEngine, sourceMap, "JSPluginBase/QuackUtils.js");
    evalResource(jsEngine, sourceMap, "JSPluginBase/JSCommand.js");
    evalResource(jsEngine, sourceMap, fileLocation);

    //Should we just ignore this?
    if (castToBoolean(jsEngine.get("ignore"))) {
        log.debug("Ignore variable set, skipping");
        return null;
    }/*from w ww  .  j  a va  2  s  . co  m*/

    //Return the appropiate hook
    if (jsEngine.get("onCommand") != null)
        //Has Command functions, return command
        return new JSCommandWrapper(jsEngine, sourceMap, fileLocation, name);

    //Assume hook
    return new JSHookWrapper(jsEngine, sourceMap, fileLocation, name);
}

From source file:net.landora.video.filerenaming.RenameScriptManager.java

RenamingScript createRenamingScript(String folderScript, String fileScript, boolean reportExceptions) {
    try {/* w w w . j  a v  a  2 s  . c o m*/
        StringBuilder str = new StringBuilder();

        str.append(getClassScript("RenameScript.py"));
        str.append("\n");
        str.append(createScript("findFolderName", folderScript));
        str.append("\n");
        str.append(createScript("findFilename", fileScript));

        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("jython");

        engine.eval(str.toString());

        Invocable inv = (Invocable) engine;
        return inv.getInterface(RenamingScript.class);
    } catch (Exception ex) {
        if (reportExceptions) {
            LoggerFactory.getLogger(getClass()).error("Error getting rename script.", ex);
        }
        return null;
    }
}

From source file:org.apache.accumulo.shell.commands.ScriptCommand.java

@Override
public int execute(String fullCommand, CommandLine cl, Shell shellState) throws Exception {

    boolean invoke = false;
    ScriptEngineManager mgr = new ScriptEngineManager();

    if (cl.hasOption(list.getOpt())) {
        listJSREngineInfo(mgr, shellState);
    } else if (cl.hasOption(file.getOpt()) || cl.hasOption(script.getOpt())) {
        String engineName = DEFAULT_ENGINE;
        if (cl.hasOption(engine.getOpt())) {
            engineName = cl.getOptionValue(engine.getOpt());
        }/*from   ww w .  j  a  v  a 2  s  . com*/
        ScriptEngine engine = mgr.getEngineByName(engineName);
        if (null == engine) {
            shellState.printException(new Exception(engineName + " not found"));
            return 1;
        }

        if (cl.hasOption(object.getOpt()) || cl.hasOption(function.getOpt())) {
            if (!(engine instanceof Invocable)) {
                shellState.printException(
                        new Exception(engineName + " does not support invoking functions or methods"));
                return 1;
            }
            invoke = true;
        }

        ScriptContext ctx = new SimpleScriptContext();

        // Put the following objects into the context so that they
        // are available to the scripts
        // TODO: What else should go in here?
        Bindings b = engine.getBindings(ScriptContext.ENGINE_SCOPE);
        b.put("connection", shellState.getConnector());

        List<Object> argValues = new ArrayList<Object>();
        if (cl.hasOption(args.getOpt())) {
            String[] argList = cl.getOptionValue(args.getOpt()).split(",");
            for (String arg : argList) {
                String[] parts = arg.split("=");
                if (parts.length == 0) {
                    continue;
                } else if (parts.length == 1) {
                    b.put(parts[0], null);
                    argValues.add(null);
                } else if (parts.length == 2) {
                    b.put(parts[0], parts[1]);
                    argValues.add(parts[1]);
                }
            }
        }
        ctx.setBindings(b, ScriptContext.ENGINE_SCOPE);
        Object[] argArray = argValues.toArray(new Object[argValues.size()]);

        Writer writer = null;
        if (cl.hasOption(out.getOpt())) {
            File f = new File(cl.getOptionValue(out.getOpt()));
            writer = new FileWriter(f);
            ctx.setWriter(writer);
        }

        if (cl.hasOption(file.getOpt())) {
            File f = new File(cl.getOptionValue(file.getOpt()));
            if (!f.exists()) {
                if (null != writer) {
                    writer.close();
                }
                shellState.printException(new Exception(f.getAbsolutePath() + " not found"));
                return 1;
            }
            Reader reader = new FileReader(f);
            try {
                engine.eval(reader, ctx);
                if (invoke) {
                    this.invokeFunctionOrMethod(shellState, engine, cl, argArray);
                }
            } catch (ScriptException ex) {
                shellState.printException(ex);
                return 1;
            } finally {
                reader.close();
                if (null != writer) {
                    writer.close();
                }
            }
        } else if (cl.hasOption(script.getOpt())) {
            String inlineScript = cl.getOptionValue(script.getOpt());
            try {
                if (engine instanceof Compilable) {
                    Compilable compiledEng = (Compilable) engine;
                    CompiledScript script = compiledEng.compile(inlineScript);
                    script.eval(ctx);
                    if (invoke) {
                        this.invokeFunctionOrMethod(shellState, engine, cl, argArray);
                    }
                } else {
                    engine.eval(inlineScript, ctx);
                    if (invoke) {
                        this.invokeFunctionOrMethod(shellState, engine, cl, argArray);
                    }
                }
            } catch (ScriptException ex) {
                shellState.printException(ex);
                return 1;
            } finally {
                if (null != writer) {
                    writer.close();
                }
            }
        }
        if (null != writer) {
            writer.close();
        }

    } else {
        printHelp(shellState);
    }
    return 0;
}

From source file:net.unit8.longadeseo.plugin.impl.JRubyExcelPlugin.java

public void init() {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("jruby");
    Reader scriptReader = null;// w ww . ja  v  a2s .  c  o m
    try {
        if (scriptText == null || scriptText.length() == 0) {
            scriptReader = new InputStreamReader(getClass().getClassLoader().getResourceAsStream(scriptFile));
            script = ((Compilable) engine).compile(scriptReader);
        } else {
            script = ((Compilable) engine).compile(scriptText);
        }
    } catch (ScriptException e) {
        throw new PluginExecutionException(e);
    } finally {
        IOUtils.closeQuietly(scriptReader);
    }
}

From source file:org.apache.accumulo.core.util.shell.commands.ScriptCommand.java

public int execute(String fullCommand, CommandLine cl, Shell shellState) throws Exception {

    boolean invoke = false;
    ScriptEngineManager mgr = new ScriptEngineManager();

    if (cl.hasOption(list.getOpt())) {
        listJSREngineInfo(mgr, shellState);
    } else if (cl.hasOption(file.getOpt()) || cl.hasOption(script.getOpt())) {
        String engineName = DEFAULT_ENGINE;
        if (cl.hasOption(engine.getOpt())) {
            engineName = cl.getOptionValue(engine.getOpt());
        }/*from ww w .j  a  v  a2  s.com*/
        ScriptEngine engine = mgr.getEngineByName(engineName);
        if (null == engine) {
            shellState.printException(new Exception(engineName + " not found"));
            return 1;
        }

        if (cl.hasOption(object.getOpt()) || cl.hasOption(function.getOpt())) {
            if (!(engine instanceof Invocable)) {
                shellState.printException(
                        new Exception(engineName + " does not support invoking functions or methods"));
                return 1;
            }
            invoke = true;
        }

        ScriptContext ctx = new SimpleScriptContext();

        // Put the following objects into the context so that they
        // are available to the scripts
        // TODO: What else should go in here?
        Bindings b = engine.getBindings(ScriptContext.ENGINE_SCOPE);
        b.put("connection", shellState.getConnector());

        List<Object> argValues = new ArrayList<Object>();
        if (cl.hasOption(args.getOpt())) {
            String[] argList = cl.getOptionValue(args.getOpt()).split(",");
            for (String arg : argList) {
                String[] parts = arg.split("=");
                if (parts.length == 0) {
                    continue;
                } else if (parts.length == 1) {
                    b.put(parts[0], null);
                    argValues.add(null);
                } else if (parts.length == 2) {
                    b.put(parts[0], parts[1]);
                    argValues.add(parts[1]);
                }
            }
        }
        ctx.setBindings(b, ScriptContext.ENGINE_SCOPE);
        Object[] argArray = argValues.toArray(new Object[argValues.size()]);

        Writer writer = null;
        if (cl.hasOption(out.getOpt())) {
            File f = new File(cl.getOptionValue(out.getOpt()));
            writer = new FileWriter(f);
            ctx.setWriter(writer);
        }

        if (cl.hasOption(file.getOpt())) {
            File f = new File(cl.getOptionValue(file.getOpt()));
            if (!f.exists()) {
                if (null != writer) {
                    writer.close();
                }
                shellState.printException(new Exception(f.getAbsolutePath() + " not found"));
                return 1;
            }
            Reader reader = new FileReader(f);
            try {
                engine.eval(reader, ctx);
                if (invoke) {
                    this.invokeFunctionOrMethod(shellState, engine, cl, argArray);
                }
            } catch (ScriptException ex) {
                shellState.printException(ex);
                return 1;
            } finally {
                reader.close();
                if (null != writer) {
                    writer.close();
                }
            }
        } else if (cl.hasOption(script.getOpt())) {
            String inlineScript = cl.getOptionValue(script.getOpt());
            try {
                if (engine instanceof Compilable) {
                    Compilable compiledEng = (Compilable) engine;
                    CompiledScript script = compiledEng.compile(inlineScript);
                    script.eval(ctx);
                    if (invoke) {
                        this.invokeFunctionOrMethod(shellState, engine, cl, argArray);
                    }
                } else {
                    engine.eval(inlineScript, ctx);
                    if (invoke) {
                        this.invokeFunctionOrMethod(shellState, engine, cl, argArray);
                    }
                }
            } catch (ScriptException ex) {
                shellState.printException(ex);
                return 1;
            } finally {
                if (null != writer) {
                    writer.close();
                }
            }
        }
        if (null != writer) {
            writer.close();
        }

    } else {
        printHelp(shellState);
    }
    return 0;
}

From source file:org.wso2.carbon.mediator.datamapper.engine.core.executors.ScriptExecutor.java

/**
 * Create a script executor of the provided script executor type
 *
 * @param scriptExecutorType//  w  ww  . j ava2 s  .c  om
 */
public ScriptExecutor(ScriptExecutorType scriptExecutorType) {
    switch (scriptExecutorType) {
    case NASHORN:
        scriptEngine = new ScriptEngineManager().getEngineByName(DataMapperEngineConstants.NASHORN_ENGINE_NAME);
        log.debug("Setting Nashorn as Script Engine");
        break;
    case RHINO:
        scriptEngine = new ScriptEngineManager().getEngineByName(DataMapperEngineConstants.DEFAULT_ENGINE_NAME);
        log.debug("Setting Rhino as Script Engine");
        break;
    default:
        scriptEngine = new ScriptEngineManager().getEngineByName(DataMapperEngineConstants.DEFAULT_ENGINE_NAME);
        log.debug("Setting default Rhino as Script Engine");
        break;
    }
}