Example usage for javax.script CompiledScript eval

List of usage examples for javax.script CompiledScript eval

Introduction

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

Prototype

public Object eval(Bindings bindings) throws ScriptException 

Source Link

Document

Executes the program stored in the CompiledScript object using the supplied Bindings of attributes as the ENGINE_SCOPE of the associated ScriptEngine during script execution.

Usage

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

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

    Object result = null;/*  w  w w . j a  v a  2s  . co  m*/

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

@Override
public Object execute(Script<CompiledScript> script) throws ScriptException {
    try {/*from ww w.  ja  va  2 s .  c  om*/
        ScriptEngine scriptEngine = getEngine();
        CompiledScript compiledScript = getCachedScript(script);
        ScriptContext scriptContext = new SimpleScriptContext();
        executePreExecuteScripts(scriptContext);
        Object object = compiledScript.eval(scriptContext);
        if (object == null)
            return scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE);
        return object;
    } catch (javax.script.ScriptException e) {
        throw new ScriptException(e);
    }
}

From source file:Engine.Lua.PlayerLua.java

public PlayerLua(String luaFile) {
    ScriptEngineManager sem = new ScriptEngineManager();
    ScriptEngine scriptEngine = sem.getEngineByName("luaj");
    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    InputStream is = classloader.getResourceAsStream("Scripts/" + luaFile);
    InputStreamReader isr = new InputStreamReader(is);
    CompiledScript script;
    try {//from ww  w  .  j a  v  a  2 s. co m
        script = ((Compilable) scriptEngine).compile(isr);
        isr.close();
        is.close();
        sb = new SimpleBindings();
        script.eval(sb); // Put the Lua functions into the sb environment
    } catch (ScriptException ex) {
        Logger.getLogger(PlayerLua.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(PlayerLua.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:Engine.Lua.PlayerLua.java

public void tester(String luaFile) {
    Dog dog = new Dog("Rex");
    Cat cat = new Cat("Felix");
    ScriptEngineManager sem = new ScriptEngineManager();
    ScriptEngine scriptEngine = sem.getEngineByName("luaj");
    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    InputStream is = classloader.getResourceAsStream("Scripts/" + luaFile);
    InputStreamReader isr = new InputStreamReader(is);
    CompiledScript script;
    try {/* www.jav a2 s . c o  m*/
        script = ((Compilable) scriptEngine).compile(isr);
        isr.close();
        is.close();
        Bindings sb = new SimpleBindings();
        script.eval(sb); // Put the Lua functions into the sb environment
        LuaValue luaDog = CoerceJavaToLua.coerce(dog); // Java to Lua
        //CoerceLuaToJava()
        LuaFunction onTalk = (LuaFunction) sb.get("onTalk"); // Get Lua function
        LuaValue b = onTalk.call(luaDog); // Call the function
        System.out.println("onTalk answered: " + b);
        LuaFunction onWalk = (LuaFunction) sb.get("onWalk");
        LuaValue[] dogs = { luaDog };
        Varargs dist = onWalk.invoke(LuaValue.varargsOf(dogs)); // Alternative

        System.out.println("onWalk returned: " + dist);

        Dog retunredDog = (Dog) CoerceLuaToJava.coerce(luaDog, Dog.class);
        System.out.println("AAAAAAAAAa:" + retunredDog.name);
    } catch (ScriptException ex) {
        Logger.getLogger(PlayerLua.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(PlayerLua.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:be.solidx.hot.JSR223ScriptExecutor.java

@Override
public Object execute(Script<CompiledScript> script, Writer writer) throws ScriptException {
    try {/*from www  .j a v a 2s.c  o  m*/
        ScriptEngine scriptEngine = getEngine();
        CompiledScript compiledScript = getCachedScript(script);
        SimpleScriptContext simpleScriptContext = new SimpleScriptContext();
        executePreExecuteScripts(simpleScriptContext);
        simpleScriptContext.setWriter(writer);
        Object object = compiledScript.eval(simpleScriptContext);
        writer.flush();
        if (object == null)
            return scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE);
        return object;
    } catch (Exception e) {
        throw new ScriptException(e);
    }
}

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

public Object eval(ScriptEngine engine, String script, ScriptContext context) throws ScriptException {
    if (engine instanceof Compilable && ATTEMPT_COMPILATION) {
        Compilable eng = (Compilable) engine;
        CompiledScript cs = eng.compile(script);
        return context != null ? cs.eval(context) : cs.eval();
    }/*from  ww w.  j  a v  a  2 s .  co m*/

    return context != null ? engine.eval(script, context) : engine.eval(script);
}

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());
    }/*from  www.j  a v a 2s . c  om*/

    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);
        }

    }
}

From source file:com.l2jfree.gameserver.scripting.L2ScriptEngineManager.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());
    }//from  w ww  .  j av a 2  s .  c o 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);
        }

    }
}

From source file:io.github.jeddict.jcode.parser.ejs.EJSParser.java

private ScriptEngine createEngine() {
    CompiledScript cscript;
    Bindings bindings;/*from  ww  w .  j a va2 s.  c  om*/
    ScriptEngine scriptEngine = new NashornScriptEngineFactory().getScriptEngine("--language=es6");//engine = new ScriptEngineManager().getEngineByName("nashorn");
    try {
        try {
            if (base == null) {
                base = IOUtils.toString(EJSParser.class.getClassLoader()
                        .getResourceAsStream("io/github/jeddict/jcode/parser/ejs/resources/base.js"), "UTF-8");
            }
            if (ejs == null) {
                ejs = IOUtils.toString(EJSParser.class.getClassLoader()
                        .getResourceAsStream("io/github/jeddict/jcode/parser/ejs/resources/ejs.js"), "UTF-8");
            }
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }

        scriptEngine.eval(base);
        Compilable compilingEngine = (Compilable) scriptEngine;
        cscript = compilingEngine.compile(ejs);
        bindings = scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE);
        cscript.eval(bindings);
        scriptEngine.eval(scripts.toString());

        for (Map<String, Object> context : contexts) {
            context.keySet().stream().forEach((key) -> {
                try {
                    bindings.put(key, context.get(key));
                    if (context.get(key) instanceof Collection) {
                        scriptEngine.eval(String.format("%s = Java.from(%s);", key, key));
                    }
                } catch (ScriptException ex) {
                    Exceptions.printStackTrace(ex);
                }
            });
        }

    } catch (ScriptException ex) {
        Exceptions.printStackTrace(ex);
    }
    return scriptEngine;
}

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 w ww .jav  a2 s  .c o  m*/
        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;
}