Example usage for javax.script ScriptEngine eval

List of usage examples for javax.script ScriptEngine eval

Introduction

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

Prototype

public Object eval(Reader reader) throws ScriptException;

Source Link

Document

Same as eval(String) except that the source of the script is provided as a Reader

Usage

From source file:Main.java

public static void main(String[] args) {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("js");
    engine.put("a", 1);
    engine.put("b", 5);

    Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
    Object a = bindings.get("a");
    Object b = bindings.get("b");
    System.out.println("a = " + a);
    System.out.println("b = " + b);

    Object result;/*from  w w  w  . ja va2  s . c  om*/
    try {
        result = engine.eval("c = aaaa + bbbb;");
        System.out.println("a + b = " + result);
    } catch (ScriptException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:Main.java

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

    File outputFile = new File("jsoutput.txt");
    System.out.println("Script output will be written to " + outputFile.getAbsolutePath());

    FileWriter writer = new FileWriter(outputFile);
    ScriptContext defaultCtx = engine.getContext();
    defaultCtx.setWriter(writer);/* w  w  w . j  a  va2s  .  c  om*/
    String script = "print('Hello custom output writer')";
    engine.eval(script);
    writer.close();

}

From source file:MonthlyPayment.java

public static void main(String[] args) throws Exception {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByExtension("js");
    String calcMonthlyPaymentScript = "intrate = intrate/1200.0;"
            + "payment = principal*intrate*(Math.pow (1+intrate, months)/"
            + "                            (Math.pow (1+intrate,months)-1));";

    engine.put("principal", 20000.0);
    System.out.println("Principal = " + engine.get("principal"));
    engine.put("intrate", 6.0);
    System.out.println("Interest Rate = " + engine.get("intrate") + "%");
    engine.put("months", 360);
    System.out.println("Months = " + engine.get("months"));
    engine.eval(calcMonthlyPaymentScript);
    System.out.printf("Monthly Payment = %.2f\n", engine.get("payment"));
}

From source file:Main.java

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

    String[] ops = { "+", "-", "*", "/" };

    JPanel gui = new JPanel(new BorderLayout(2, 2));
    JPanel labels = new JPanel(new GridLayout(0, 1));
    gui.add(labels, BorderLayout.WEST);
    labels.add(new JLabel("a"));
    labels.add(new JLabel("operand"));
    labels.add(new JLabel("b"));
    labels.add(new JLabel("="));

    JPanel controls = new JPanel(new GridLayout(0, 1));
    gui.add(controls, BorderLayout.CENTER);
    JTextField a = new JTextField(10);
    controls.add(a);/*from www .  j  a  v  a 2s.c o m*/
    JComboBox operand = new JComboBox(ops);
    controls.add(operand);
    JTextField b = new JTextField(10);
    controls.add(b);
    JTextField output = new JTextField(10);
    controls.add(output);

    ActionListener al = new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            String expression = a.getText() + operand.getSelectedItem() + b.getText();
            try {
                Object result = engine.eval(expression);
                if (result == null) {
                    output.setText("Output was 'null'");
                } else {
                    output.setText(result.toString());
                }
            } catch (ScriptException se) {
                output.setText(se.getMessage());
            }
        }
    };

    operand.addActionListener(al);
    a.addActionListener(al);
    b.addActionListener(al);

    JOptionPane.showMessageDialog(null, gui);
}

From source file:velo.scripting.ScriptingManager.java

public static void main(String[] args) throws FactoryException {
    //ScriptingManager sm = new ScriptingManager();
    //ScriptEngine se = sm.getScriptEngine("groovy");
    ScriptEngine se = ScriptingManager.getScriptEngine("groovy");

    OperationContext oc = new OperationContext();
    se.put("name", "moshe");
    se.put("cntx", oc);
    //String a = "<?xml version=\"1.0\"?><j:jelly trim=\"false\" xmlns:j=\"jelly:core\" xmlns:x=\"jelly:xml\" xmlns:html=\"jelly:html\"><html><head><title>${name}'s Page</title></head></html></j:jelly>";
    //String a = "def a = new Date(); println(a.getClass().getName()); def myArr = new Date[1]; myArr[0] = a; println(myArr.getClass().getName()); cntx.addVar('myArr',myArr);";
    String a = "def a = new Date(); a.getClass().getName(); def myArr = new Date[1]; myArr[0] = a; myArr.getClass().getName(); cntx.addVar('myArr',myArr);";

    //Sadly it seems that invoking via se.eval and script.eval almost return the same times, thought it should be much more effecient :/
    try {//w  w w .j av  a  2s .c o m
        //groovy
        //se.eval("println(name);");
        StopWatch sw = new StopWatch();
        sw.start();

        for (int i = 0; i < 100000; i++) {
            se.eval(a);
        }
        sw.stop();
        System.out.println("time in seconds: '" + sw.getTime() / 1000 + "'");
        sw.reset();

        sw.start();
        CompiledScript script = ((Compilable) se).compile(a);
        for (int i = 0; i < 100000; i++) {
            script.eval();
        }
        sw.stop();
        System.out.println("time in seconds: '" + sw.getTime() / 1000 + "'");

        OperationContext getOc = (OperationContext) se.get("cntx");
        Date[] arrOfDate = (Date[]) getOc.get("myArr");
        //System.out.println(arrOfDate);

    } catch (ScriptException e) {
        System.out.println("ERROR: " + e);
    }
}

From source file:com.ikanow.aleph2.analytics.spark.assets.SparkJsInterpreterTopology.java

public static void main(String[] args)
        throws InstantiationException, IllegalAccessException, ClassNotFoundException {

    final SetOnce<IBucketLogger> bucket_logger = new SetOnce<>();
    final SetOnce<String> job_name = new SetOnce<>(); // (the string we'll use in logging activities)
    try {/*from ww w  .  jav  a2 s  .  c o  m*/
        final Tuple2<IAnalyticsContext, Optional<ProcessingTestSpecBean>> aleph2_tuple = SparkTechnologyUtils
                .initializeAleph2(args);
        final IAnalyticsContext context = aleph2_tuple._1();
        final Optional<ProcessingTestSpecBean> test_spec = aleph2_tuple._2();

        bucket_logger.set(context.getLogger(context.getBucket()));
        job_name.set(context.getJob().map(j -> j.name()).orElse("no_name"));

        // Optional: make really really sure it exists after the specified timeout
        SparkTechnologyUtils.registerTestTimeout(test_spec, () -> {
            System.exit(0);
        });

        final SparkTopologyConfigBean config = BeanTemplateUtils
                .from(context.getJob().map(job -> job.config()).orElse(Collections.emptyMap()),
                        SparkTopologyConfigBean.class)
                .get();

        final String js_script = Optional.ofNullable(config.script()).orElse("");

        //INFO:
        System.out.println("Starting " + job_name.get());

        SparkConf spark_context = new SparkConf().setAppName(job_name.get());

        test_spec.ifPresent(spec -> System.out
                .println("OPTIONS: test_spec = " + BeanTemplateUtils.toJson(spec).toString()));

        try (final JavaSparkContext jsc = new JavaSparkContext(spark_context)) {

            final Multimap<String, JavaPairRDD<Object, Tuple2<Long, IBatchRecord>>> inputs = SparkTechnologyUtils
                    .buildBatchSparkInputs(context, test_spec, jsc, Collections.emptySet());
            final JavaPairRDD<Object, Tuple2<Long, IBatchRecord>> all_inputs = inputs.values().stream()
                    .reduce((acc1, acc2) -> acc1.union(acc2)).orElse(null);

            // Load globals:
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("JavaScript");
            engine.put("_a2_global_context", context);
            engine.put("_a2_global_bucket", context.getBucket().get());
            engine.put("_a2_global_job", context.getJob().get());
            engine.put("_a2_global_config",
                    BeanTemplateUtils.configureMapper(Optional.empty()).convertValue(config, JsonNode.class));
            engine.put("_a2_global_mapper", BeanTemplateUtils.configureMapper(Optional.empty()));
            //TODO (until bucket logger is serializable, don't allow anywhere)
            //engine.put("_a2_bucket_logger", bucket_logger.optional().orElse(null));
            engine.put("_a2_enrichment_name", job_name.get());
            engine.put("_a2_spark_inputs", inputs);
            engine.put("_a2_spark_inputs_all", all_inputs);
            engine.put("_a2_spark_context", jsc);

            Stream.concat(config.uploaded_lang_files().stream(),
                    Stream.of("aleph2_sparkjs_globals_before.js", ""))
                    .flatMap(Lambdas.flatWrap_i(import_path -> {
                        try {
                            if (import_path.equals("")) { // also import the user script just before here
                                return js_script;
                            } else
                                return IOUtils.toString(SparkJsInterpreterTopology.class.getClassLoader()
                                        .getResourceAsStream(import_path), "UTF-8");
                        } catch (Throwable e) {
                            bucket_logger.optional()
                                    .ifPresent(l -> l.log(Level.ERROR,
                                            ErrorUtils.lazyBuildMessage(false,
                                                    () -> SparkJsInterpreterTopology.class.getSimpleName(),
                                                    () -> job_name.get() + ".main", () -> null,
                                                    () -> ErrorUtils.get(
                                                            "Error initializing stage {0} (script {1}): {2}",
                                                            job_name.get(), import_path, e.getMessage()),
                                                    () -> ImmutableMap.<String, Object>of("full_error",
                                                            ErrorUtils.getLongForm("{0}", e)))));

                            System.out.println(ErrorUtils.getLongForm("onStageInitialize: {0}", e));
                            throw e; // ignored
                        }
                    })).forEach(Lambdas.wrap_consumer_i(script -> {
                        try {
                            engine.eval(script);
                        } catch (Throwable e) {
                            bucket_logger.optional()
                                    .ifPresent(l -> l.log(Level.ERROR,
                                            ErrorUtils.lazyBuildMessage(false,
                                                    () -> SparkJsInterpreterTopology.class.getSimpleName(),
                                                    () -> job_name.get() + ".main", () -> null,
                                                    () -> ErrorUtils.get(
                                                            "Error initializing stage {0} (main script): {1}",
                                                            job_name.get(), e.getMessage()),
                                                    () -> ImmutableMap.<String, Object>of("full_error",
                                                            ErrorUtils.getLongForm("{0}", e)))));

                            System.out.println(ErrorUtils.getLongForm("onStageInitialize: {0}", e));
                            throw e; // ignored
                        }
                    }));
            ;

            jsc.stop();

            //INFO:
            System.out.println("Finished " + job_name.get());
        }
    } catch (Throwable t) {
        System.out.println(ErrorUtils.getLongForm("ERROR: {0}", t));

        bucket_logger.optional().ifPresent(l -> l.log(Level.ERROR, ErrorUtils.lazyBuildMessage(false,
                () -> SparkJsInterpreterTopology.class.getSimpleName()
                        + job_name.optional().map(j -> "." + j).orElse(""),
                () -> job_name.optional().orElse("global") + ".main", () -> null,
                () -> ErrorUtils.get("Error on batch in job {0}: {1}",
                        job_name.optional().orElse("global") + ".main", t.getMessage()),
                () -> ImmutableMap.<String, Object>of("full_error", ErrorUtils.getLongForm("{0}", t)))));
    }
}

From source file:Main.java

public static Object getValue(String filepath, String key) {
    try {/*from   ww w  .  j a  v a2 s  . c  o m*/
        ScriptEngineManager sem = new ScriptEngineManager();
        ScriptEngine jsEngine = sem.getEngineByName("js");
        jsEngine.eval(new FileReader(filepath));
        return jsEngine.get(key);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

From source file:Main.java

public static Object invokeFunction(String filepath, String funcname, Object... params) {
    try {/*www. j a  v a 2  s .  c  om*/
        ScriptEngineManager sem = new ScriptEngineManager();
        ScriptEngine jsEngine = sem.getEngineByName("js");
        jsEngine.eval(new FileReader(filepath));
        Invocable invocable = (Invocable) jsEngine;
        return invocable.invokeFunction(funcname, params);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

From source file:JavaScriptUtils.java

public static void eval(JavaScript script) throws ScriptException {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("js");
    engine.eval(script.value());
}

From source file:Main.java

public static String evalScript(String engineName, String script) throws Exception {
    //System.out.println("evaluating "+script);
    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine engine = mgr.getEngineByName("JavaScript");
    String result = "" + engine.eval(script);
    return result;
}