Example usage for javax.script Compilable compile

List of usage examples for javax.script Compilable compile

Introduction

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

Prototype

public CompiledScript compile(Reader script) throws ScriptException;

Source Link

Document

Compiles the script (source read from Reader) for later execution.

Usage

From source file:CompilableDemo.java

public static void main(String[] args) throws Exception {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("js");

    Compilable jsCompile = (Compilable) engine;
    CompiledScript script = jsCompile.compile("function hi () {print ('www.java2s.com !'); }; hi ();");

    for (int i = 0; i < 5; i++) {
        script.eval();//from   www.j  a v a  2s .c  o m
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");

    if (!(engine instanceof Compilable)) {
        System.out.println("Script compilation not supported.");
        return;//ww  w.j  ava  2  s  . c  om
    }
    Compilable comp = (Compilable) engine;

    CompiledScript cScript = comp.compile("print(n1 + n2)");

    Bindings scriptParams = engine.createBindings();
    scriptParams.put("n1", 2);
    scriptParams.put("n2", 3);
    cScript.eval(scriptParams);

    scriptParams.put("n1", 9);
    scriptParams.put("n2", 7);
    cScript.eval(scriptParams);
}

From source file:CompileTest.java

public static void main(String args[]) {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("javascript");
    engine.put("counter", 0);
    if (engine instanceof Compilable) {
        Compilable compEngine = (Compilable) engine;
        try {//ww w .  j  a v a  2s . c  o  m
            CompiledScript script = compEngine
                    .compile("function count(){counter=counter+1;return counter;}; count();");
            System.out.println(script.eval());
            System.out.println(script.eval());
            System.out.println(script.eval());
        } catch (ScriptException e) {
            System.err.println(e);
        }
    } else {
        System.err.println("Engine can't compile code");
    }
}

From source file:TestCompilationSpeed.java

public static void main(String[] args) throws Exception {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");

    String fact = "function fact (n){if (n == 0)return 1; else return n*fact (n-1);};";

    long time = System.currentTimeMillis();
    for (int i = 0; i < MAX_ITERATIONS; i++)
        engine.eval(fact);/* ww  w. j  ava 2  s.c  o m*/
    System.out.println(System.currentTimeMillis() - time);

    Compilable compilable = null;
    if (engine instanceof Compilable) {
        compilable = (Compilable) engine;
        CompiledScript script = compilable.compile(fact);

        time = System.currentTimeMillis();
        for (int i = 0; i < MAX_ITERATIONS; i++)
            script.eval();
        System.out.println(System.currentTimeMillis() - time);
    }
}

From source file:com.kactech.otj.examples.App_otj.java

@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
    String command = null;//from   ww  w  .  j a v  a  2 s .  co m
    String hisacct = null;
    String hisacctName = null;
    String hisacctAsset = null;
    String asset = null;
    String assetName = null;
    List<String> argList = null;
    boolean newAccount = false;
    File dir = null;
    ConnectionInfo connection = null;
    List<ScriptFilter> filters = null;

    CommandLineParser parser = new GnuParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println("Command-line parsing error: " + e.getMessage());
        help();
        System.exit(-1);
    }
    if (cmd.hasOption('h')) {
        help();
        System.exit(0);
    }
    @SuppressWarnings("unchecked")
    List<String> list = cmd.getArgList();
    if (list.size() > 1) {
        System.err.println("only one command is supported, you've typed " + list);
        help();
        System.exit(-1);
    }
    if (list.size() > 0)
        command = list.get(0).trim();

    List<SampleAccount> accounts = ExamplesUtils.getSampleAccounts();

    if (cmd.hasOption('s')) {
        String v = cmd.getOptionValue('s').trim();
        connection = ExamplesUtils.findServer(v);
        if (connection == null) {
            System.err.println("unknown server: " + v);
            System.exit(-1);
        }
    } else {
        connection = ExamplesUtils.findServer(DEF_SERVER_NAME);
        if (connection == null) {
            System.err.println("default server not found server: " + DEF_SERVER_NAME);
            System.exit(-1);
        }
    }

    if (cmd.hasOption('t')) {
        String v = cmd.getOptionValue('t');
        for (SampleAccount ac : accounts)
            if (ac.accountName.startsWith(v)) {
                hisacct = ac.accountID;
                hisacctName = ac.accountName;
                hisacctAsset = ac.assetID;
                break;
            }
        if (hisacct == null)
            if (mayBeValid(v))
                hisacct = v;
            else {
                System.err.println("invalid hisacct: " + v);
                System.exit(-1);
            }
    }
    if (cmd.hasOption('p')) {
        String v = cmd.getOptionValue('p');
        for (SampleAccount ac : accounts)
            if (ac.assetName.startsWith(v)) {
                asset = ac.assetID;
                assetName = ac.assetName;
                break;
            }
        if (asset == null)
            if (mayBeValid(v))
                asset = v;
            else {
                System.err.println("invalid asset: " + v);
                System.exit(-1);
            }
    }

    if (cmd.hasOption('a')) {
        String v = cmd.getOptionValue('a');
        argList = new ArrayList<String>();
        boolean q = false;
        StringBuilder b = new StringBuilder();
        for (int i = 0; i < v.length(); i++) {
            char c = v.charAt(i);
            if (c == '"') {
                if (q) {
                    argList.add(b.toString());
                    b = null;
                    q = false;
                    continue;
                }
                if (b != null)
                    argList.add(b.toString());
                b = new StringBuilder();
                q = true;
                continue;
            }
            if (c == ' ' || c == '\t') {
                if (q) {
                    b.append(c);
                    continue;
                }
                if (b != null)
                    argList.add(b.toString());
                b = null;
                continue;
            }
            if (b == null)
                b = new StringBuilder();
            b.append(c);
        }
        if (b != null)
            argList.add(b.toString());
        if (q) {
            System.err.println("unclosed quote in args: " + v);
            System.exit(-1);
        }
    }

    dir = new File(cmd.hasOption('d') ? cmd.getOptionValue('d') : DEF_CLIENT_DIR);

    if (cmd.hasOption('x'))
        del(dir);

    newAccount = cmd.hasOption('n');

    if (cmd.hasOption('f')) {
        filters = new ArrayList<ScriptFilter>();
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("JavaScript");
        Compilable compilingEngine = (Compilable) engine;
        for (String fn : cmd.getOptionValue('f').split(",")) {
            fn = fn.trim();
            if (fn.isEmpty())
                continue;
            fn += ".js";
            Reader r = null;
            try {
                r = new InputStreamReader(new FileInputStream(new File("filters", fn)), Utils.UTF8);
            } catch (Exception e) {
                try {
                    r = new InputStreamReader(
                            App_otj.class.getResourceAsStream("/com/kactech/otj/examples/filters/" + fn));
                } catch (Exception e2) {
                }
            }
            if (r == null) {
                System.err.println("filter not found: " + fn);
                System.exit(-1);
            } else
                try {
                    CompiledScript compiled = compilingEngine.compile(r);
                    ScriptFilter sf = new ScriptFilter(compiled);
                    filters.add(sf);
                } catch (Exception ex) {
                    System.err.println("error while loading " + fn + ": " + ex);
                    System.exit(-1);
                }
        }
    }

    System.out.println("server: " + connection.getEndpoint() + " " + connection.getID());
    System.out.println("command: '" + command + "'");
    System.out.println("args: " + argList);
    System.out.println("hisacct: " + hisacct);
    System.out.println("hisacctName: " + hisacctName);
    System.out.println("hisacctAsset: " + hisacctAsset);
    System.out.println("asset: " + asset);
    System.out.println("assetName: " + assetName);

    if (asset != null && hisacctAsset != null && !asset.equals(hisacctAsset)) {
        System.err.println("asset differs from hisacctAsset");
        System.exit(-1);
    }

    EClient client = new EClient(dir, connection);
    client.setAssetType(asset != null ? asset : hisacctAsset);
    client.setCreateNewAccount(newAccount);
    if (filters != null)
        client.setFilters(filters);

    try {
        Utils.init();
        Client.DEBUG_JSON = true;
        client.init();

        if ("balance".equals(command))
            System.out.println("Balance: " + client.getAccount().getBalance().getAmount());
        else if ("acceptall".equals(command))
            client.processInbox();
        else if ("transfer".equals(command)) {
            if (hisacct == null)
                System.err.println("please specify --hisacct");
            else {
                int idx = argList != null ? argList.indexOf("amount") : -1;
                if (idx < 0)
                    System.err.println("please specify amount");
                else if (idx == argList.size())
                    System.err.println("amount argument needs value");
                else {
                    Long amount = -1l;
                    try {
                        amount = new Long(argList.get(idx + 1));
                    } catch (Exception e) {

                    }
                    if (amount <= 0)
                        System.err.println("invalid amount");
                    else {
                        client.notarizeTransaction(hisacct, amount);
                    }
                }
            }
        } else if ("reload".equals(command))
            client.reloadState();
        else if ("procnym".equals(command))
            client.processNymbox();
    } finally {
        client.saveState();
        client.close();
    }
}

From source file:com.espertech.esper.epl.script.jsr223.JSR223Helper.java

public static CompiledScript verifyCompileScript(ExpressionScriptProvided script, String dialect)
        throws ExprValidationException {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName(dialect);
    if (engine == null) {
        throw new ExprValidationException("Failed to obtain script engine for dialect '" + dialect
                + "' for script '" + script.getName() + "'");
    }/*from  w  ww.jav  a  2  s  .c  o  m*/
    engine.put(ScriptEngine.FILENAME, script.getName());

    Compilable compilingEngine = (Compilable) engine;
    try {
        return compilingEngine.compile(script.getExpression());
    } catch (ScriptException ex) {
        String message = "Exception compiling script '" + script.getName() + "' of dialect '" + dialect + "': "
                + getScriptCompileMsg(ex);
        log.info(message, ex);
        throw new ExprValidationException(message, ex);
    }
}

From source file:de.ingrid.iplug.ckan.utils.ScriptEngine.java

/**
 * Get the compiled version of the given script
 * @param script The script file//from  w  w  w.j  a  va 2  s . c om
 * @return CompiledScript
 * @throws ScriptException
 * @throws IOException 
 */
protected static CompiledScript getCompiledScript(Resource script) throws ScriptException, IOException {
    String filename = script.getFilename();
    if (!compiledScripts.containsKey(filename)) {
        javax.script.ScriptEngine engine = getEngine(script);
        if (engine instanceof Compilable) {
            Compilable compilable = (Compilable) engine;
            CompiledScript compiledScript = compilable.compile(new InputStreamReader(script.getInputStream()));
            compiledScripts.put(filename, compiledScript);
        }
    }
    return compiledScripts.get(filename);
}

From source file:org.zaproxy.VerifyScripts.java

private static Consumer<Reader> parser(Compilable engine) {
    return r -> {
        try {//from w  ww. j a  v  a 2 s.com
            engine.compile(r);
        } catch (ScriptException e) {
            throw new RuntimeException(e);
        }
    };
}

From source file:org.nuxeo.ecm.webengine.scripting.Scripting.java

public static CompiledScript compileScript(ScriptEngine engine, File file) throws ScriptException {
    if (engine instanceof Compilable) {
        Compilable comp = (Compilable) engine;
        try {//ww  w .  ja v  a2  s. c  om
            Reader reader = new FileReader(file);
            try {
                return comp.compile(reader);
            } finally {
                reader.close();
            }
        } catch (IOException e) {
            throw new ScriptException(e);
        }
    } else {
        return null;
    }
}

From source file:net.orzo.scripting.SourceCode.java

/**
 * @throws ScriptException/*from ww w .  j a v a 2  s  . co  m*/
 */
public CompiledScript compile(Compilable compilable) throws ScriptException {
    return compilable.compile(getContents());
}