List of usage examples for javax.script ScriptEngineManager getEngineByName
public ScriptEngine getEngineByName(String shortName)
ScriptEngine
for a given name. From source file:GetEngineByName.java
public static void main(String[] args) { ScriptEngineManager manager = new ScriptEngineManager(); /* Retrieve a ScriptEngine registered with the rhino name */ ScriptEngine jsEngine = manager.getEngineByName("rhino"); if (!(jsEngine == null)) { System.out.println(jsEngine); } else {/*from ww w . j a v a2 s . co m*/ System.out.println("\nNo supported script engine foundregistered as Rhino."); } }
From source file:ObtainScriptEngine.java
public static void main(String[] args) { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine1 = manager.getEngineByExtension("js"); System.out.println(engine1);/*from w w w . j a v a 2 s.c o m*/ ScriptEngine engine2 = manager.getEngineByMimeType("application/javascript"); System.out.println(engine2); ScriptEngine engine3 = manager.getEngineByName("rhino"); System.out.println(engine3); }
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 . j a v a 2 s.com*/ 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 void main(String[] args) throws Exception { ScriptEngineManager mgr = new ScriptEngineManager(); List<ScriptEngineFactory> engines = mgr.getEngineFactories(); for (ScriptEngineFactory engine : engines) { System.out.println(engine.getEngineName()); for (String n : engine.getNames()) { System.out.println("Short name : " + n); }//from w ww . j ava 2 s . c o m } ScriptEngine engine = mgr.getEngineByName("JavaScript"); String myJSCode = "function myFunction(){return (4+2);}myFunction();"; System.out.println(engine.eval(myJSCode)); }
From source file:com.kactech.otj.examples.App_otj.java
@SuppressWarnings("unchecked") public static void main(String[] args) throws Exception { String command = null;/*from w ww .j a v a 2 s .c om*/ 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:Main.java
public static void execute(ScriptEngineManager manager, String engineName, String script) { ScriptEngine engine = manager.getEngineByName(engineName); if (engine == null) { System.out.println(engineName + " is not available."); return;/* ww w .j a va 2s .c om*/ } try { engine.eval(script); } catch (ScriptException e) { e.printStackTrace(); } }
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; }
From source file:Main.java
public static Object getValue(String filepath, String key) { try {/*w ww .ja v a 2s.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 {//from w ww. j a va 2 s. co m 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 ww w . j av a 2 s . c om }