public Object executeJs(String js,@Nullable String funcName,Object... args){ ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("javascript"); try { Object res=engine.eval(js); if(StringUtils.isNotBlank(funcName)){ if (engine instanceof Invocable) { Invocable invoke = (Invocable) engine; res = invoke.invokeFunction(funcName, args); } } return res; } catch (Exception e) { log.error("",e); } return null; }
public ScriptRouter(URL url) { this.url = url; String type = url.getParameter(Constants.TYPE_KEY); this.priority = url.getParameter(Constants.PRIORITY_KEY, 0); String rule = url.getParameterAndDecoded(Constants.RULE_KEY); if (type == null || type.length() == 0){ type = Constants.DEFAULT_SCRIPT_TYPE_KEY; } if (rule == null || rule.length() == 0){ throw new IllegalStateException(new IllegalStateException("route rule can not be empty. rule:" + rule)); } ScriptEngine engine = engines.get(type); if (engine == null){ engine = new ScriptEngineManager().getEngineByName(type); if (engine == null) { throw new IllegalStateException(new IllegalStateException("Unsupported route rule type: " + type + ", rule: " + rule)); } engines.put(type, engine); } this.engine = engine; this.rule = rule; }
public static void main(String[] args) throws Exception { System.out.println("\nTest4\n"); ScriptEngineManager m = new ScriptEngineManager(); ScriptEngine e = Helper.getJsEngine(m); if (e == null) { System.out.println("Warning: No js engine found; test vacuously passes."); return; } e.eval(new FileReader( new File(System.getProperty("test.src", "."), "Test4.js"))); Invocable inv = (Invocable)e; Runnable run1 = (Runnable)inv.getInterface(Runnable.class); run1.run(); // use methods of a specific script object Object intfObj = e.get("intfObj"); Runnable run2 = (Runnable)inv.getInterface(intfObj, Runnable.class); run2.run(); }
@Test /** * Check that calling method on mirror created by another engine results in * IllegalArgumentException. */ public void invokeMethodMixEnginesTest() { final ScriptEngineManager m = new ScriptEngineManager(); final ScriptEngine engine1 = m.getEngineByName("nashorn"); final ScriptEngine engine2 = m.getEngineByName("nashorn"); try { final Object obj = engine1.eval("({ run: function() {} })"); // pass object from engine1 to engine2 as 'thiz' for invokeMethod ((Invocable) engine2).invokeMethod(obj, "run"); fail("should have thrown IllegalArgumentException"); } catch (final Exception exp) { if (!(exp instanceof IllegalArgumentException)) { exp.printStackTrace(); fail(exp.getMessage()); } } }
@Test // array-like indexed access for a JSObject public void indexedAccessTest() { final ScriptEngineManager m = new ScriptEngineManager(); final ScriptEngine e = m.getEngineByName("nashorn"); try { final BufferObject buf = new BufferObject(2); e.put("buf", buf); // array-like access on BufferObject objects assertEquals(e.eval("buf.length"), buf.getBuffer().capacity()); e.eval("buf[0] = 23"); assertEquals(buf.getBuffer().get(0), 23); assertEquals(e.eval("buf[0]"), 23); assertEquals(e.eval("buf[1]"), 0); buf.getBuffer().put(1, 42); assertEquals(e.eval("buf[1]"), 42); assertEquals(e.eval("Array.isArray(buf)"), Boolean.TRUE); } catch (final Exception exp) { exp.printStackTrace(); fail(exp.getMessage()); } }
public CustomFrameTitleBuilder() { PropertiesComponent prop = PropertiesComponent.getInstance(); projectPattern = prop.getValue(Settings.TEMPLATE_PATTERN_PROJECT, DEFAULT_TEMPLATE_PATTERN_PROJECT); filePattern = prop.getValue(Settings.TEMPLATE_PATTERN_FILE, DEFAULT_TEMPLATE_PATTERN_FILE); engine = new ScriptEngineManager().getEngineByName("nashorn"); try { // evaluate JavaScript Underscore library engine.eval(new InputStreamReader(getClass().getResourceAsStream("/underscore-min.js"))); // create new JavaScript methods references for templates engine.eval("var projectTemplate;"); engine.eval("var fileTemplate;"); prepareTemplateSettings(); } catch (Exception e) { // we took precaution below } TitleComponent.addSettingChangeListener(this); }
public static void main(final String[] args) throws Exception { final ScriptEngineManager manager = new ScriptEngineManager(); final ScriptEngine engine = manager.getEngineByName("nashorn"); // JavaScript code in a String final String script = "var obj = new Object(); obj.run = function() { print('run method called'); }"; // evaluate script engine.eval(script); // get script object on which we want to implement the interface with final Object obj = engine.get("obj"); final Invocable inv = (Invocable) engine; // get Runnable interface object from engine. This interface methods // are implemented by script methods of object 'obj' final Runnable r = inv.getInterface(obj, Runnable.class); // start a new thread that runs the script implemented // runnable interface final Thread th = new Thread(r); th.start(); th.join(); }
@Test public void functionalInterfaceObjectTest() throws Exception { final ScriptEngineManager manager = new ScriptEngineManager(); final ScriptEngine e = manager.getEngineByName("nashorn"); final AtomicBoolean invoked = new AtomicBoolean(false); e.put("c", new Consumer<Object>() { @Override public void accept(final Object t) { assertTrue(t instanceof ScriptObjectMirror); assertEquals(((ScriptObjectMirror)t).get("a"), "xyz"); invoked.set(true); } }); e.eval("var x = 'xy'; x += 'z';c({a:x})"); assertTrue(invoked.get()); }
@Test // a factory JSObject public void factoryJSObjectTest() { final ScriptEngineManager m = new ScriptEngineManager(); final ScriptEngine e = m.getEngineByName("nashorn"); try { e.put("Factory", new Factory()); // check new on Factory assertEquals(e.eval("typeof Factory"), "function"); assertEquals(e.eval("typeof new Factory()"), "object"); assertEquals(e.eval("(new Factory()) instanceof java.util.Map"), Boolean.TRUE); } catch (final Exception exp) { exp.printStackTrace(); fail(exp.getMessage()); } }
@Test // check that print prints all arguments (more than one) public void printManyTest() { final ScriptEngineManager m = new ScriptEngineManager(); final ScriptEngine e = m.getEngineByName("nashorn"); final StringWriter sw = new StringWriter(); e.getContext().setWriter(sw); try { e.eval("print(34, true, 'hello')"); } catch (final Throwable t) { t.printStackTrace(); fail(t.getMessage()); } assertEquals(sw.toString(), println("34 true hello")); }
@Test /** * Check that calling method on non-script object 'thiz' results in * IllegalArgumentException. */ public void invokeMethodNonScriptObjectThizTest() { final ScriptEngineManager m = new ScriptEngineManager(); final ScriptEngine e = m.getEngineByName("nashorn"); try { ((Invocable) e).invokeMethod(new Object(), "toString"); fail("should have thrown IllegalArgumentException"); } catch (final Exception exp) { if (!(exp instanceof IllegalArgumentException)) { exp.printStackTrace(); fail(exp.getMessage()); } } }
@Test /** * Check that calling getInterface on mirror created by another engine * results in IllegalArgumentException. */ public void getInterfaceMixEnginesTest() { final ScriptEngineManager m = new ScriptEngineManager(); final ScriptEngine engine1 = m.getEngineByName("nashorn"); final ScriptEngine engine2 = m.getEngineByName("nashorn"); try { final Object obj = engine1.eval("({ run: function() {} })"); // pass object from engine1 to engine2 as 'thiz' for getInterface ((Invocable) engine2).getInterface(obj, Runnable.class); fail("should have thrown IllegalArgumentException"); } catch (final Exception exp) { if (!(exp instanceof IllegalArgumentException)) { exp.printStackTrace(); fail(exp.getMessage()); } } }
@Test public void indexPropertiesExternalBufferTest() throws ScriptException { final ScriptEngineManager m = new ScriptEngineManager(); final ScriptEngine e = m.getEngineByName("nashorn"); final ScriptObjectMirror obj = (ScriptObjectMirror)e.eval("var obj = {}; obj"); final ByteBuffer buf = ByteBuffer.allocate(5); int i; for (i = 0; i < 5; i++) { buf.put(i, (byte)(i+10)); } obj.setIndexedPropertiesToExternalArrayData(buf); for (i = 0; i < 5; i++) { assertEquals((byte)(i+10), ((Number)e.eval("obj[" + i + "]")).byteValue()); } e.eval("for (i = 0; i < 5; i++) obj[i] = 0"); for (i = 0; i < 5; i++) { assertEquals((byte)0, ((Number)e.eval("obj[" + i + "]")).byteValue()); assertEquals((byte)0, buf.get(i)); } }
@Test /** * Check that we can call invokeMethod on an object that we got by * evaluating script with different Context set. */ public void invokeMethodDifferentContextTest() { final ScriptEngineManager m = new ScriptEngineManager(); final ScriptEngine e = m.getEngineByName("nashorn"); try { // define an object with method on it final Object obj = e.eval("({ hello: function() { return 'Hello World!'; } })"); final ScriptContext ctxt = new SimpleScriptContext(); ctxt.setBindings(e.createBindings(), ScriptContext.ENGINE_SCOPE); e.setContext(ctxt); // invoke 'func' on obj - but with current script context changed final Object res = ((Invocable) e).invokeMethod(obj, "hello"); assertEquals(res, "Hello World!"); } catch (final Exception exp) { exp.printStackTrace(); fail(exp.getMessage()); } }
private static Map<String, Object> getAttributesFromInlineGroovyScript(final Map<String, Object> attributes, final Matcher matcherInline) throws ScriptException { final String script = matcherInline.group(1).trim(); final ScriptEngine engine = new ScriptEngineManager().getEngineByName("groovy"); if (engine == null) { LOGGER.warn("Script engine is not available for Groovy"); return new HashMap<>(); } final Object[] args = {attributes, LOGGER}; LOGGER.debug("Executing script, with parameters [{}]", args); final Bindings binding = new SimpleBindings(); binding.put("attributes", attributes); binding.put("logger", LOGGER); return (Map<String, Object>) engine.eval(script, binding); }
/** * Exec a string match function with JavaScript regex expression and return the match result. * @param str * @param regex * @return null if no match, otherwise a String[] result value */ public static String[] jsMatchExpr(String str, String regex) { // https://stackoverflow.com/questions/22492641/java8-js-nashorn-convert-array-to-java-array if(engine == null) { ScriptEngineManager manager = new ScriptEngineManager(); engine = manager.getEngineByName("javascript"); } try { engine.put("str", str); String[] value = (String[])engine.eval("Java.to(str.match(" + regex + "),\"java.lang.String[]\" );"); return value; } catch (ScriptException e) { e.printStackTrace(); } return null; }
@Test public void testJS() { // https://stackoverflow.com/questions/22492641/java8-js-nashorn-convert-array-to-java-array ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("javascript"); try { engine.put("line", "刘长炯 微信号weblogic (10.3.2) [46a5432f8fdea99a6186a927e8da5db7a51854ac]"); // engine.put("regex", ) String regex = "/(.*?) \\((.*?)\\) \\[(.*?)\\]/"; String[] value = (String[])engine.eval("Java.to(line.match(" + regex + "),\"java.lang.String[]\" );"); System.out.println(value.length); System.out.println(value[1]); String[] result = {"刘长炯 微信号weblogic (10.3.2) [46a5432f8fdea99a6186a927e8da5db7a51854ac]", "刘长炯 微信号weblogic", "10.3.2", "46a5432f8fdea99a6186a927e8da5db7a51854ac"}; Assert.assertArrayEquals("result shold match", result, value); // Collection<Object> val = value.values(); // if(value.isArray()) { // System.out.println(value.getMember("1")); // } } catch (ScriptException e) { e.printStackTrace(); } }
@Test /** * Tests whether invocation of a JavaScript method through a variable arity * Java method will pass the vararg array. Both non-vararg and vararg * JavaScript methods are tested. * * @throws ScriptException */ public void variableArityInterfaceTest() throws ScriptException { final ScriptEngineManager m = new ScriptEngineManager(); final ScriptEngine e = m.getEngineByName("nashorn"); e.eval( "function test1(i, strings) {" + " return 'i == ' + i + ', strings instanceof java.lang.String[] == ' + (strings instanceof Java.type('java.lang.String[]')) + ', strings == ' + java.util.Arrays.toString(strings)" + "}" + "function test2() {" + " return 'arguments[0] == ' + arguments[0] + ', arguments[1] instanceof java.lang.String[] == ' + (arguments[1] instanceof Java.type('java.lang.String[]')) + ', arguments[1] == ' + java.util.Arrays.toString(arguments[1])" + "}"); final VariableArityTestInterface itf = ((Invocable) e).getInterface(VariableArityTestInterface.class); Assert.assertEquals(itf.test1(42, "a", "b"), "i == 42, strings instanceof java.lang.String[] == true, strings == [a, b]"); Assert.assertEquals(itf.test2(44, "c", "d", "e"), "arguments[0] == 44, arguments[1] instanceof java.lang.String[] == true, arguments[1] == [c, d, e]"); }
public JtSqlEngine(){ ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); jsEngine = scriptEngineManager.getEngineByName("nashorn"); jtapi = new JTAPI(); jsEngine.put("JTAPI",jtapi); try { jsEngine.eval("var jtapi_global={};"); jsEngine.eval("function require(url){var lib=md5(url);if(!jtapi_global[lib]){var code=http({url:url});jtapi_global[lib]=eval(code)};return jtapi_global[lib]};"); jsEngine.eval("function guid(){return JTAPI.guid()};"); jsEngine.eval("function md5(txt){return JTAPI.md5(txt)};"); jsEngine.eval("function sha1(txt){return JTAPI.sha1(txt)};"); jsEngine.eval("function set(key,obj){JTAPI.set(key,JSON.stringify(obj))};"); jsEngine.eval("function get(key){var txt=JTAPI.get(key);if(txt){return JSON.parse(txt)}else{return null}};"); jsEngine.eval("function log(txt){JTAPI.log(txt)};"); jsEngine.eval("function http(obj){return JTAPI.http(JSON.stringify(obj))};"); //obj:{url:'xxx', form:{}, header:{}} jsEngine.eval("function sql(txt){var _d=JTAPI.sql(txt);if(_d&&typeof(_d)=='object'&&_d.getRow){var item=_d.getRow(0);var keys=item.keys();if(_d.getRowCount()==1){var obj={};for(var i in keys){var k1=keys.get(i);obj[k1]=item.get(k1)};return obj}else{var ary=[];if(item.count()==1){var list=_d.toArray(0);for(var i in list){ary.push(list[i])}}else{var rows=_d.getRows();for(var j in rows){var m1=rows.get(j);var obj={};for(var i in keys){var k1=keys.get(i);obj[k1]=m1.get(k1)};ary.push(obj)}};return ary}}else{return _d}};"); }catch (Exception ex){ ex.printStackTrace(); } }
private List<Path> findMainLibraryPaths() throws ScriptException, FileNotFoundException { LOGGER.info("Looking for main library paths"); Path includesCachePath = Paths.get(preprocessDirPath.toAbsolutePath().toString(), "includes.cache"); ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByExtension("js"); ScriptObjectMirror mirror = (ScriptObjectMirror) scriptEngine.eval(new FileReader(includesCachePath.toString())); List<Path> libraryPaths = new ArrayList<>(); mirror.entrySet().forEach(e -> { if (e.getValue() instanceof ScriptObjectMirror) { ScriptObjectMirror m = (ScriptObjectMirror) e.getValue(); Object sourceFile = m.get("Sourcefile"); if (sourceFile != null && !sourceFile.toString().trim().isEmpty()) { String entry = m.get("Includepath").toString(); if ( !entry.trim().isEmpty() ) { LOGGER.log( Level.INFO, "Found library path: {0}", entry ); libraryPaths.add( Paths.get(entry) ); } } } }); return libraryPaths; }
/** * Create a new script engine manager * <p> * <em>Note:</em> The context class loader will be set during the creation * of the script engine. However the constructor * {@link ScriptEngineManager#ScriptEngineManager(ClassLoader)} with the * parameter <code>null</code> will still be used in order to look up the * default script languages of the JRE. * </p> * * @param contextClassLoader * the context class loader to use * @return a new instanceof a {@link ScriptEngineManager} */ public static ScriptEngineManager createManager ( final ClassLoader contextClassLoader ) { try { return executeWithClassLoader ( contextClassLoader, new Callable<ScriptEngineManager> () { @Override public ScriptEngineManager call () { return new ScriptEngineManager ( null ); } } ); } catch ( final Exception e ) { // should never happen throw new RuntimeException ( e ); } }
public static void main(String[] args) throws Exception { System.out.println("\nTest8\n"); ScriptEngineManager m = new ScriptEngineManager(); ScriptEngine e = Helper.getJsEngine(m); if (e == null) { System.out.println("Warning: No js engine found; test vacuously passes."); return; } e.eval(new FileReader( new File(System.getProperty("test.src", "."), "Test8.js"))); Invocable inv = (Invocable)e; inv.invokeFunction("main", "Mustang"); // use method of a specific script object Object scriptObj = e.get("scriptObj"); inv.invokeMethod(scriptObj, "main", "Mustang"); }
@Test public void fakeProxySubclassAccessCheckTest() { if (System.getSecurityManager() == null) { // pass vacuously return; } final ScriptEngineManager m = new ScriptEngineManager(); final ScriptEngine e = m.getEngineByName("nashorn"); e.put("name", ScriptEngineSecurityTest.class.getName()); e.put("cl", ScriptEngineSecurityTest.class.getClassLoader()); e.put("intfs", new Class[] { Runnable.class }); final String getClass = "Java.type(name + '$FakeProxy').getProxyClass(cl, intfs);"; // Should not be able to call static methods of Proxy via fake subclass try { e.eval(getClass); fail("should have thrown SecurityException"); } catch (final Exception exp) { if (! (exp instanceof SecurityException)) { fail("SecurityException expected, got " + exp); } } }
public ScriptVisibilityProviderImpl ( final ScriptEngineManager scriptEngineManager, final ScriptContext scriptContext, String engineName, final String scriptCode ) { fireChange ( false ); if ( engineName == null || engineName.isEmpty () ) { engineName = "JavaScript"; } try { final ScriptExecutor executor = new ScriptExecutor ( scriptEngineManager, engineName, scriptCode, Activator.class.getClassLoader () ); fireChange ( makeResult ( executor.execute ( scriptContext ) ) ); } catch ( final Exception e ) { logger.warn ( "Failed to eval visibility", e ); } }
private void loadScriptModule ( final ScriptEngineManager engineManager, final ScriptContext scriptContext, final ScriptModule module ) throws Exception { String engineName = module.getScriptLanguage (); if ( engineName == null || engineName.isEmpty () ) { engineName = "JavaScript"; //$NON-NLS-1$ } if ( module.getCode () != null && !module.getCode ().isEmpty () ) { new ScriptExecutor ( engineManager, engineName, module.getCode (), Activator.class.getClassLoader () ).execute ( scriptContext ); } if ( module.getCodeUri () != null && !module.getCodeUri ().isEmpty () ) { new ScriptExecutor ( engineManager, engineName, new URL ( module.getCodeUri () ), Activator.class.getClassLoader () ).execute ( scriptContext ); } }
@Test public void argumentsWithTest() { final ScriptEngineManager m = new ScriptEngineManager(); final ScriptEngine e = m.getEngineByName("nashorn"); final String[] args = new String[] { "hello", "world" }; try { e.put("arguments", args); final Object arg0 = e.eval("var imports = new JavaImporter(java.io); " + " with(imports) { arguments[0] }"); final Object arg1 = e.eval("var imports = new JavaImporter(java.util, java.io); " + " with(imports) { arguments[1] }"); assertEquals(args[0], arg0); assertEquals(args[1], arg1); } catch (final Exception exp) { exp.printStackTrace(); fail(exp.getMessage()); } }
@Override protected boolean processInterceptItem ( final Item item, final ItemInterceptor interceptorElement, final MasterContext masterContext, final Properties properties ) { final ModbusExporterInterceptor interceptor = (ModbusExporterInterceptor)interceptorElement; final Script script = interceptor.getScript (); final ScriptEngineManager manager = new ScriptEngineManager (); try { final ScriptExecutor executor = new ScriptExecutor ( manager, script.getLanguage (), script.getSource (), null ); final ScriptContext context = new SimpleScriptContext (); final ModbusProcessor modbus = new ModbusProcessor ( this, interceptor, masterContext, item ); context.setAttribute ( "MODBUS", modbus, ScriptContext.ENGINE_SCOPE ); context.setAttribute ( "item", item, ScriptContext.ENGINE_SCOPE ); context.setAttribute ( "properties", properties, ScriptContext.ENGINE_SCOPE ); executor.execute ( context ); } catch ( final Exception e ) { throw new RuntimeException ( "Failed to process script", e ); } return true; }
@Test /** * Try passing non-interface Class object for interface implementation. */ public void getNonInterfaceGetInterfaceTest() { final ScriptEngineManager manager = new ScriptEngineManager(); final ScriptEngine engine = manager.getEngineByName("nashorn"); try { log(Objects.toString(((Invocable) engine).getInterface(Object.class))); fail("Should have thrown IllegalArgumentException"); } catch (final Exception exp) { if (!(exp instanceof IllegalArgumentException)) { fail("IllegalArgumentException expected, got " + exp); } } }
public static void main(final String[] args) throws Exception { final ScriptEngineManager manager = new ScriptEngineManager(); final ScriptEngine engine = manager.getEngineByName("nashorn"); engine.put("x", "hello"); // print global variable "x" engine.eval("print(x);"); // the above line prints "hello" // Now, pass a different script context final ScriptContext newContext = new SimpleScriptContext(); newContext.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE); final Bindings engineScope = newContext.getBindings(ScriptContext.ENGINE_SCOPE); // add new variable "x" to the new engineScope engineScope.put("x", "world"); // execute the same script - but this time pass a different script context engine.eval("print(x);", newContext); // the above line prints "world" }
@Test /** * Check that getInterface on null 'thiz' results in * IllegalArgumentException. */ public void getInterfaceNullThizTest() { final ScriptEngineManager m = new ScriptEngineManager(); final ScriptEngine e = m.getEngineByName("nashorn"); try { ((Invocable) e).getInterface(null, Runnable.class); fail("should have thrown IllegalArgumentException"); } catch (final Exception exp) { if (!(exp instanceof IllegalArgumentException)) { exp.printStackTrace(); fail(exp.getMessage()); } } }
public static void testScriptEngine() throws Exception { ScriptEngineManager sem = new ScriptEngineManager(); ScriptEngine js = sem.getEngineByName("JavaScript"); js.eval("blubb = 1\n" + "muh = blubb + 2\n" + "// just a comment...\n" + "crap = \"asd\""); System.out.println(js.get("muh").getClass()); System.out.println("Testing ScriptEngine Performance..."); long start = System.currentTimeMillis(); Config c = Config.getInstance(new FileInputStream("res/customConfig.js")); double[] d = new double[]{1.0, 7.5, 1.3+2.5+6.3+3.1, 6.0};; for (int i = 0; i < 100000; i++) { //c.pReassignVnf(i); //d = new double[]{d[0] + 1.0, d[1] - 0.5, d[0] + d[1], d[3] * 1.1}; c.objectiveVector(new double[Solution.Vals.values().length]); } System.out.println(Arrays.toString(d)); long dur = System.currentTimeMillis() - start; System.out.println("Duration: " + dur + "ms"); System.out.println(c.topologyFile.toAbsolutePath().toString()); }
@Test public void mapScriptObjectMirrorCallsiteTest() throws ScriptException { final ScriptEngineManager m = new ScriptEngineManager(); final ScriptEngine engine = m.getEngineByName("nashorn"); final String TEST_SCRIPT = "typeof obj.foo"; final Bindings global = engine.getContext().getBindings(ScriptContext.ENGINE_SCOPE); engine.eval("var obj = java.util.Collections.emptyMap()"); // this will drive callsite "obj.foo" of TEST_SCRIPT // to use "obj instanceof Map" as it's guard engine.eval(TEST_SCRIPT, global); // redefine 'obj' to be a script object engine.eval("obj = {}"); final Bindings newGlobal = engine.createBindings(); // transfer 'obj' from default global to new global // new global will get a ScriptObjectMirror wrapping 'obj' newGlobal.put("obj", global.get("obj")); // Every ScriptObjectMirror is a Map! If callsite "obj.foo" // does not see the new 'obj' is a ScriptObjectMirror, it'll // continue to use Map's get("obj.foo") instead of ScriptObjectMirror's // getMember("obj.foo") - thereby getting null instead of undefined assertEquals("undefined", engine.eval(TEST_SCRIPT, newGlobal)); }
@Test public void factoryOptionsTest() { final ScriptEngineManager sm = new ScriptEngineManager(); for (final ScriptEngineFactory fac : sm.getEngineFactories()) { if (fac instanceof NashornScriptEngineFactory) { final NashornScriptEngineFactory nfac = (NashornScriptEngineFactory)fac; // specify --no-syntax-extensions flag final String[] options = new String[] { "--no-syntax-extensions" }; final ScriptEngine e = nfac.getScriptEngine(options); try { // try nashorn specific extension e.eval("var f = funtion(x) 2*x;"); fail("should have thrown exception!"); } catch (final Exception ex) { //empty } return; } } fail("Cannot find nashorn factory!"); }
@Test public void windowItemTest() { final ScriptEngineManager m = new ScriptEngineManager(); final ScriptEngine e = m.getEngineByName("nashorn"); final Window window = new Window(); try { e.put("window", window); final String item1 = (String)e.eval("window.item(65535)"); assertEquals(item1, "ffff"); final String item2 = (String)e.eval("window.item(255)"); assertEquals(item2, "ff"); } catch (final Exception exp) { exp.printStackTrace(); fail(exp.getMessage()); } }
public static void main(String args[]) throws Exception { ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn"); String name = "Mahesh"; System.out.println(nashorn.getClass()); Integer result = null; try { nashorn.eval("print('" + name + "')"); result = (Integer) nashorn.eval("10 + 2"); } catch (ScriptException e) { System.out.println("Error executing script: " + e.getMessage()); } jdk.nashorn.api.scripting.NashornScriptEngine x = (jdk.nashorn.api.scripting.NashornScriptEngine) nashorn; CompiledScript v = x.compile("1+2"); System.out.println(v.eval()); }
@Test public void shouldHaveACoolAPI() throws Exception { // Create the engine. ScriptEngine engine = new ScriptEngineManager().getEngineByName("v8"); Assert.assertNotNull(engine); // Perform basic evaluation. Assert.assertEquals(34, engine.eval("30 + 4")); // Perform advanced evaluation. Assert.assertEquals("l33t", engine.eval("\"l\" + (33).toString() + \"t\"")); // Perform scope put-get. engine.put("myVar", 42); Assert.assertEquals(42, engine.get("myVar")); }
public static void main(String[] args) { ScriptEngineManager engineManager = new ScriptEngineManager(); ScriptEngine engine = engineManager.getEngineByName("javascript"); try { // UserVO user = new UserVO(); // user.setId(1000); // user.setUsername("xingtianyu"); // Map<String,Object> usermap = new HashMap<>(); // usermap.put("id",user.getId()); // usermap.put("username",user.getUsername()); JSContext context = new JSContext(); engine.put(JSContext.CONTEXT,context.getCtx()); engine.eval(new FileReader("/home/code4j/IDEAWorkspace/myutils/myutils-slardar/src/main/resources/mapper/usermapper.js")); Invocable func = (Invocable)engine; // Map<String,Object> resultMap = (Map<String, Object>) func.invokeFunction("findUserByCondition",usermap); // Map<String,Object> paramMap = (Map<String, Object>) resultMap.get("param"); // System.out.println(resultMap.get("sql")); // System.out.println(paramMap.get("1")); } catch (Exception e) { e.printStackTrace(); } }
@Test /** * Test that we can use same script name in repeated evals with --loader-per-compile=false * We used to get "class redefinition error" as name was derived from script name. */ public void noLoaderPerCompilerWithSameNameTest() { final ScriptEngineManager sm = new ScriptEngineManager(); for (final ScriptEngineFactory fac : sm.getEngineFactories()) { if (fac instanceof NashornScriptEngineFactory) { final NashornScriptEngineFactory nfac = (NashornScriptEngineFactory)fac; final String[] options = new String[] { "--loader-per-compile=false" }; final ScriptEngine e = nfac.getScriptEngine(options); e.put(ScriptEngine.FILENAME, "test.js"); try { e.eval("2 + 3"); e.eval("4 + 4"); } catch (final ScriptException se) { se.printStackTrace(); fail(se.getMessage()); } return; } } fail("Cannot find nashorn factory!"); }
public ScriptRouter(URL url) { this.url = url; String type = url.getParameter(Constants.TYPE_KEY); this.priority = url.getParameter(Constants.PRIORITY_KEY, 0); String rule = url.getParameterAndDecoded(Constants.RULE_KEY); if (type == null || type.length() == 0) { type = Constants.DEFAULT_SCRIPT_TYPE_KEY; } if (rule == null || rule.length() == 0) { throw new IllegalStateException(new IllegalStateException("route rule can not be empty. rule:" + rule)); } ScriptEngine engine = engines.get(type); if (engine == null) { engine = new ScriptEngineManager().getEngineByName(type); if (engine == null) { throw new IllegalStateException(new IllegalStateException("Unsupported route rule type: " + type + ", rule: " + rule)); } engines.put(type, engine); } this.engine = engine; this.rule = rule; }