List of usage examples for javax.script ScriptEngine put
public void put(String key, Object value);
From source file:Main.java
public static void main(String[] args) throws ScriptException { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); manager.put("n1", 1); String script = "var sum = n1 + n2;print(msg + " + "' n1=' + n1 + ', n2=' + n2 + " + "', sum=' + sum);"; engine.put("n2", 2); engine.put("msg", "a string"); engine.eval(script);/*w w w .j av a 2s . c o m*/ Bindings bindings = engine.createBindings(); bindings.put("n2", 3); bindings.put("msg", "another string"); engine.eval(script, bindings); ScriptContext ctx = new SimpleScriptContext(); Bindings ctxGlobalBindings = engine.createBindings(); ctx.setBindings(ctxGlobalBindings, GLOBAL_SCOPE); ctx.setAttribute("n1", 4, GLOBAL_SCOPE); ctx.setAttribute("n2", 5, ENGINE_SCOPE); ctx.setAttribute("msg", "ScriptContext:", ENGINE_SCOPE); engine.eval(script, ctx); engine.eval(script); }
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 {/*from ww w .j av a 2 s . com*/ //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: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: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 w w w .j a va 2s . c om 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:fr.assoba.open.sel.generator.LanguageExecutor.java
public static void execute(List<Namespace> namespaceList, IO io, String... languages) throws IOException, ScriptException { ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine jsEngine = factory.getEngineByName("JavaScript"); jsEngine.put("IO", io); jsEngine.eval(io.readFile("underscore.js")); jsEngine.eval(io.readFile("handlebars-v1.3.0.js")); ObjectMapper mapper = new ObjectMapper(); jsEngine.eval("namespaces=" + mapper.writeValueAsString(namespaceList)); for (String lang : languages) { if (generatorMap.containsKey(lang)) { generatorMap.get(lang).generate(namespaceList, io); } else {//from www . j a v a 2s . co m jsEngine.eval(io.readFile(lang + ".js")); } } }
From source file:org.mycontroller.standalone.scripts.McScriptEngineUtils.java
public static void updateMcApi(ScriptEngine engine) { engine.put(MC_API, new McScriptApi()); }
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 w w . j a va2s . c om 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:com.netsteadfast.greenstep.util.ScriptExpressionUtils.java
private static void executeRenjin(String scriptExpression, Map<String, Object> results, Map<String, Object> parameters) throws Exception { ScriptEngine engine = buildRenjinScriptEngine(); if (parameters != null) { for (Map.Entry<String, Object> entry : parameters.entrySet()) { engine.put(entry.getKey(), entry.getValue()); }//from w ww . j a v a 2 s . co m } engine.eval(scriptExpression); if (results != null) { for (Map.Entry<String, Object> entry : results.entrySet()) { Object res = engine.get(entry.getKey()); if (res instanceof AbstractAtomicVector) { if (((AbstractAtomicVector) res).length() > 0) { entry.setValue(((AbstractAtomicVector) res).getElementAsObject(0)); } } else { entry.setValue(res); } } } }
From source file:org.siphon.common.js.JsEngineUtil.java
/** * /*w w w. j a v a 2 s .co m*/ * @param jsEngine * @param libs [path, path, ...] */ public static void initEngine(ScriptEngine jsEngine, Object[] libs) { try { jsEngine.put("engine", jsEngine); NashornScriptEngine nashornScriptEngine = (NashornScriptEngine) jsEngine; JsTypeUtil jsTypeUtil = new JsTypeUtil(jsEngine); ScriptObjectMirror importedFiles = jsTypeUtil.newObject(); jsEngine.put("IMPORTED_FILES", importedFiles); ScriptObjectMirror stk = jsTypeUtil.newArray(); jsEngine.put("IMPORTS_PATH_STACK", stk); ScriptObjectMirror defaults = (libs.length > 0 && libs[0] != null && libs[0] instanceof String && ((String) libs[0]).length() > 0) ? jsTypeUtil.newArray(libs) : jsTypeUtil.newArray(); jsEngine.put("DEFAULT_IMPORTS_PATHS", defaults); jsEngine.put(ScriptEngine.FILENAME, "common/engine.js"); jsEngine.eval(importsFn); } catch (ScriptException e) { e.printStackTrace(); } }
From source file:org.siphon.common.js.JsEngineUtil.java
public static Object eval(ScriptEngine jsEngine, String srcFile) throws ScriptException, IOException { jsEngine.put(ScriptEngine.FILENAME, srcFile); return jsEngine.eval(FileUtils.readFileToString(new File(srcFile))); }