public void timeOut(final long delay, final EventInstanceManager eim) { if (disposed || eim == null) { return; } eventTimer = EventTimer.getInstance().schedule(new Runnable() { @Override public void run() { if (disposed || eim == null || em == null) { return; } try { em.getIv().invokeFunction("scheduledTimeout", eim); } catch (NoSuchMethodException | ScriptException ex) { System.out.println("Event name" + em.getName() + ", Instance name : " + name + ", method Name : scheduledTimeout:\n" + ex); } } }, delay); }
/** * Make sure lexically defined variables are accessible in other scripts. */ @Test public void lexicalScopeTest() throws ScriptException { final NashornScriptEngineFactory factory = new NashornScriptEngineFactory(); final ScriptEngine e = factory.getScriptEngine(LANGUAGE_ES6); e.eval("let x; const y = 'world';"); assertEquals(e.eval("x = 'hello'"), "hello"); assertEquals(e.eval("typeof x"), "string"); assertEquals(e.eval("typeof y"), "string"); assertEquals(e.eval("x"), "hello"); assertEquals(e.eval("y"), "world"); assertEquals(e.eval("typeof this.x"), "undefined"); assertEquals(e.eval("typeof this.y"), "undefined"); assertEquals(e.eval("this.x"), null); assertEquals(e.eval("this.y"), null); }
/** * Ensure that the old behaviour (every object is a Map) is unchanged. */ @Test public void testNonWrapping() throws ScriptException { final ScriptEngine engine = new NashornScriptEngineFactory().getScriptEngine(); final Object val = engine.eval("({x: [1, {y: [2, {z: [3]}]}, [4, 5]]})"); final Map<String, Object> root = asMap(val); final Map<String, Object> x = asMap(root.get("x")); assertEquals(x.get("0"), 1); final Map<String, Object> x1 = asMap(x.get("1")); final Map<String, Object> y = asMap(x1.get("y")); assertEquals(y.get("0"), 2); final Map<String, Object> y1 = asMap(y.get("1")); final Map<String, Object> z = asMap(y1.get("z")); assertEquals(z.get("0"), 3); final Map<String, Object> x2 = asMap(x.get("2")); assertEquals(x2.get("0"), 4); assertEquals(x2.get("1"), 5); }
@Test public void classFilterTest2() throws ScriptException { final NashornScriptEngineFactory fac = new NashornScriptEngineFactory(); final ScriptEngine e = fac.getScriptEngine(new String[0], Thread.currentThread().getContextClassLoader(), new ClassFilter() { @Override public boolean exposeToScripts(final String fullName) { // don't allow anything that is not "java." return fullName.startsWith("java."); } }); assertEquals(e.eval("typeof javax.script.ScriptEngine"), "object"); assertEquals(e.eval("typeof java.util.Vector"), "function"); try { e.eval("Java.type('javax.script.ScriptContext')"); fail("should not reach here"); } catch (final ScriptException | RuntimeException se) { if (! (se.getCause() instanceof ClassNotFoundException)) { fail("ClassNotFoundException expected"); } } }
@Test public void globalPerEngineTest() throws ScriptException { final NashornScriptEngineFactory fac = new NashornScriptEngineFactory(); final String[] options = new String[] { "--global-per-engine" }; final ScriptEngine e = fac.getScriptEngine(options); e.eval("function foo() {}"); final ScriptContext newCtx = new SimpleScriptContext(); newCtx.setBindings(e.createBindings(), ScriptContext.ENGINE_SCOPE); // all global definitions shared and so 'foo' should be // visible in new Bindings as well. assertTrue(e.eval("typeof foo", newCtx).equals("function")); e.eval("function bar() {}", newCtx); // bar should be visible in default context assertTrue(e.eval("typeof bar").equals("function")); }
public final void action(final MapleClient c, final byte mode, final byte type, final int selection) { if (mode != -1) { final NPCConversationManager cm = cms.get(c); if (cm == null || cm.getLastMsg() > -1) { return; } final Lock lock = c.getNPCLock(); lock.lock(); try { if (cm.pendingDisposal) { dispose(c); } else { c.setClickedNPC(); cm.getIv().invokeFunction("action", mode, type, selection); } } catch (final ScriptException | NoSuchMethodException e) { System.err.println("Error executing NPC script. NPC ID : " + cm.getNpc() + ":" + e); dispose(c); e.printStackTrace(); } finally { lock.unlock(); } } }
@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]"); }
/** * Setup javascript shortcuts such as 'server'. */ private void initJS() { // Allow JS to load java classes. Thread currentThread = Thread.currentThread(); ClassLoader previousClassLoader = currentThread.getContextClassLoader(); currentThread.setContextClassLoader(Core.getInstance().getClass().getClassLoader()); try { this.engine = new ScriptEngineManager().getEngineByName("JavaScript"); engine.put("engine", engine); // Allow JS to do consistent eval. engine.eval(new InputStreamReader(Core.getInstance().getResource("boot.js"))); // Run JS startup. MechanicManager.getMechanics().forEach(this::bindObject); // Create shortcuts for all mechanics. bindClass(Utils.class); bindClass(KCPlayer.class); bindClass(ReflectionUtil.class); } catch (ScriptException ex) { ex.printStackTrace(); Core.warn("Failed to initialize JS shortcuts."); } finally { // Set back the previous class loader. currentThread.setContextClassLoader(previousClassLoader); } }
@Override public int[] getIntegerVector(final String variable) { if (isNull(variable)) { return null; } else { try { final Vector sexp = (Vector) engine.unwrap().eval(variable); final int[] array = new int[sexp.length()]; for (int i = 0; i < array.length; i++) { array[i] = sexp.getElementAsInt(i); } return array; } catch (final ScriptException e) { throw new RuntimeException(e); } } }
@Override public boolean[][] getBooleanMatrix(final String variable) { if (isNull(variable)) { return null; } else { try { final Matrix sexp = new Matrix((Vector) engine.unwrap().eval(variable)); final boolean[][] matrix = new boolean[sexp.getNumRows()][]; for (int row = 0; row < matrix.length; row++) { final boolean[] vector = new boolean[sexp.getNumCols()]; for (int col = 0; col < vector.length; col++) { vector[col] = sexp.getElementAsInt(row, col) > 0; } matrix[row] = vector; } return matrix; } catch (final ScriptException e) { throw new RuntimeException(e); } } }
protected void setJsSentence(INlpSentence s) throws CoreCriticalException { try { jsEngine.eval("var sentence = [];"); if ((Boolean) jsEngine.eval(String.format("sentence.positionInSentence == %d", s.getSentenceIndexInCorpus()))) return; jsEngine.eval(String.format("sentence.positionInSentence = %d", s.getSentenceIndexInCorpus())); for (int i = 0; i< s.getTokenCount(); i++) { Token token = s.getToken(i); jsEngine.eval(String.format("sentence[%d] = %s;", token.getTokenIndexInSentence(), tokenToJson(token))); } jsEngine.eval("sentence.spanAnnotations = []"); for (SpanAnnotation annotation : s.getSpanAnnotations()) { jsEngine.eval(String.format("sentence.spanAnnotations.push(%s);", annotationToJson(annotation))); for (int i = annotation.getStartTokenIndex(); i <= annotation.getEndTokenIndex(); i++) { jsEngine.eval(String.format("sentence[%s].parentAnnotations.push(sentence.spanAnnotations[sentence.spanAnnotations.length - 1]);", i)); } } } catch (ScriptException e) { throw new CoreCriticalException(e); } }
private Object evalReader(Reader in, String filename) { try { engine.put(ScriptEngine.FILENAME, filename); return engine.eval(in); } catch (ScriptException sexp) { System.err.println(sexp); printError(sexp.toString(), sexp); } finally { try { in.close(); } catch (IOException ioe) { printError(ioe.toString(), ioe); } } return null; }
public final void schedule(final String methodName, final long delay) { if (disposed) { return; } EventTimer.getInstance().schedule(new Runnable() { @Override public void run() { if (disposed || EventInstanceManager.this == null || em == null) { return; } try { em.getIv().invokeFunction(methodName, EventInstanceManager.this); } catch (NullPointerException npe) { } catch (NoSuchMethodException | ScriptException ex) { System.out.println("Event name" + em.getName() + ", Instance name : " + name + ", method Name : " + methodName + ":\n" + ex); } } }, delay); }
@Test public void scriptObjectAutoConversionTest() throws ScriptException { final ScriptEngineManager m = new ScriptEngineManager(); final ScriptEngine e = m.getEngineByName("nashorn"); e.eval("obj = { foo: 'hello' }"); e.put("Window", e.eval("Packages.jdk.nashorn.api.scripting.test.Window")); assertEquals(e.eval("Window.funcJSObject(obj)"), "hello"); assertEquals(e.eval("Window.funcScriptObjectMirror(obj)"), "hello"); assertEquals(e.eval("Window.funcMap(obj)"), "hello"); assertEquals(e.eval("Window.funcJSObject(obj)"), "hello"); }
@Test public void accessStaticFieldString() throws ScriptException { e.eval("var ps_string = SharedObject.publicStaticString;"); assertEquals(SharedObject.publicStaticString, e.get("ps_string")); assertEquals("string", e.eval("typeof ps_string;")); e.eval("SharedObject.publicStaticString = 'changedString';"); assertEquals("changedString", SharedObject.publicStaticString); }
private static Invocable createEngine() throws ScriptException, IOException { ScriptEngine engine = CoreUtil.getJsEngine(); //engine.put(ScriptEngine.FILENAME, FIELD_CALCULATION_JS_FILE_NAME); //ScriptContext context = engine.getContext(); //context.setAttribute("window", file.getParent(), ScriptContext.ENGINE_SCOPE);//$NON-NLS-1$ //context.setAttribute("items", this.items.toArray(), ScriptContext.ENGINE_SCOPE); //$NON-NLS-1$ //context.setAttribute("baseDir", file.getParent(), ScriptContext.ENGINE_SCOPE);//$NON-NLS-1$ // context.setBindings(new Bindings(ScriptEngine.FILENAME, FIELD_CALCULATION_JS_FILE_NAME),ScriptContext.ENGINE_SCOPE)); // try { // engine.eval(new FileReader(ENV_JS_FILE_NAME)); // engine.eval(new FileReader(SPRINTF_JS_FILE_NAME)); // engine.eval(new FileReader(DATE_JS_FILE_NAME)); // engine.eval(new FileReader(TIME_JS_FILE_NAME)); // engine.eval(new FileReader(STRIP_COMMENTS_JS_FILE_NAME)); // engine.eval(new FileReader(JQUERY_BASE64_JS_FILE_NAME)); // engine.eval(new FileReader(REST_API_SHIM_JS_FILE_NAME)); // engine.eval(new FileReader(LOCATION_DISTANCE_SHIM_JS_FILE_NAME)); // engine.eval(new FileReader(FIELD_CALCULATION_JS_FILE_NAME)); engine.eval(getJsFile(ENV_JS_FILE_NAME)); engine.eval(getJsFile(SPRINTF_JS_FILE_NAME)); engine.eval(getJsFile(JSON2_JS_FILE_NAME)); engine.eval(getJsFile(DATE_JS_FILE_NAME)); engine.eval(getJsFile(TIME_JS_FILE_NAME)); engine.eval(getJsFile(STRIP_COMMENTS_JS_FILE_NAME)); engine.eval(getJsFile(JQUERY_BASE64_JS_FILE_NAME)); engine.eval(getJsFile(REST_API_JS_FILE_NAME)); engine.eval(getJsFile(LOCATION_DISTANCE_JS_FILE_NAME)); engine.eval(getJsFile(FIELD_CALCULATION_JS_FILE_NAME)); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } return (Invocable) engine; }
@Test public void accessFieldByteBoxing() throws ScriptException { e.eval("var p_byte = o.publicByteBox;"); assertEqualsDouble(o.publicByteBox, "p_byte"); e.eval("o.publicByteBox = 16;"); assertEquals(Byte.valueOf((byte)16), o.publicByteBox); }
private void performCloudFlareAuthorization() throws IOException { try { httpClientContext = httpFactory.createClientContext(); CloudFlareAuthorizer cloudFlareAuthorizer = new CloudFlareAuthorizer(httpClient,httpClientContext); cloudFlareAuthorizer.getAuthorizationResult("https://bittrex.com"); } catch (ScriptException e) { log.error("Failed to perform CloudFlare authorization",e); } }
@Test public void accessMethodFloat() throws ScriptException { assertEquals(0.0f, e.eval("o.floatMethod(0.0);")); assertEquals(4.2f, e.eval("o.floatMethod(2.1);")); assertEquals(0.0f, e.eval("o.floatMethod('0.0');")); assertEquals(4.2f, e.eval("o.floatMethod('2.1');")); }
/** * Wrap an embedded array as a list. */ @Test public void testWrapObjectWithArray() throws ScriptException { final ScriptEngine engine = new NashornScriptEngineFactory().getScriptEngine(); final Object val = engine.eval("Java.asJSONCompatible({x: [1, 2, 3]})"); assertEquals(asList(asMap(val).get("x")), Arrays.asList(1, 2, 3)); }
public void act(MapleClient c, MapleReactor reactor) { try { ReactorActionManager rm = new ReactorActionManager(c, reactor); Invocable iv = getInvocable("reactor/" + reactor.getId() + ".js", c); // System.out.println(reactor.getId()); if (iv == null) { return; } engine.put("rm", rm); iv.invokeFunction("act"); } catch (final ScriptException | NoSuchMethodException | NullPointerException e) { FilePrinter.printError(FilePrinter.REACTOR + reactor.getId() + ".txt", e); } }
/** * Test multi-threaded access to global getters and setters for shared script classes with multiple globals. */ @Test public static void getterSetterTest() throws ScriptException, InterruptedException { final ScriptEngineManager m = new ScriptEngineManager(); final ScriptEngine e = m.getEngineByName("nashorn"); final Bindings b = e.createBindings(); final ScriptContext origContext = e.getContext(); final ScriptContext newCtxt = new SimpleScriptContext(); newCtxt.setBindings(b, ScriptContext.ENGINE_SCOPE); final String sharedScript = "accessor1"; e.eval(new URLReader(ScopeTest.class.getResource("resources/gettersetter.js")), origContext); assertEquals(e.eval("accessor1 = 1;"), 1); assertEquals(e.eval(sharedScript), 1); e.eval(new URLReader(ScopeTest.class.getResource("resources/gettersetter.js")), newCtxt); assertEquals(e.eval("accessor1 = 2;", newCtxt), 2); assertEquals(e.eval(sharedScript, newCtxt), 2); final Thread t1 = new Thread(new ScriptRunner(e, origContext, sharedScript, 1, 1000)); final Thread t2 = new Thread(new ScriptRunner(e, newCtxt, sharedScript, 2, 1000)); t1.start(); t2.start(); t1.join(); t2.join(); assertEquals(e.eval(sharedScript), 1); assertEquals(e.eval(sharedScript, newCtxt), 2); assertEquals(e.eval("v"), 1); assertEquals(e.eval("v", newCtxt), 2); }
public void method() throws ScriptException { // a context with a new global bindings, same engine bindings final ScriptContext sc = new SimpleScriptContext(); final Bindings global = new SimpleBindings(); sc.setBindings(global, ScriptContext.GLOBAL_SCOPE); sc.setBindings(engineBindings, ScriptContext.ENGINE_SCOPE); global.put("text", "methodText"); final String value = engine.eval("text", sc).toString(); Assert.assertEquals(value, "methodText"); }
@Test public void accessStaticFinalFieldChar() throws ScriptException { e.eval("var psf_char = SharedObject.publicStaticFinalChar;"); assertEquals(SharedObject.publicStaticFinalChar, e.get("psf_char")); e.eval("SharedObject.publicStaticFinalChar = 'Z';"); assertEquals('K', SharedObject.publicStaticFinalChar); }
public void startInstance(MapleCharacter character, String leader) { try { EventInstanceManager eim = (EventInstanceManager) (iv.invokeFunction("setup", (Object) null)); eim.registerPlayer(character); eim.setProperty("leader", leader); eim.setProperty("guildid", String.valueOf(character.getGuildId())); setProperty("guildid", String.valueOf(character.getGuildId())); } catch (NoSuchMethodException | ScriptException ex) { System.out.println("Event name : " + name + ", method Name : setup-Guild:\n" + ex); } }
@Test(expected=NullPointerException.class) public void throwExceptionNoCause() throws Throwable { try { scriptEngine.eval("throw new NullPointerException();"); } catch(ScriptException e) { throw e.getCause(); } }
@Test public void accessMethodLong() throws ScriptException { assertEquals((long)0, e.eval("o.longMethod(0);")); assertEquals((long)400, e.eval("o.longMethod(200);")); assertEquals((long) 0, e.eval("o.longMethod('0');")); assertEquals((long) 400, e.eval("o.longMethod('200');")); }
JsonParser() { try { nashornParser = (JSObject) new ScriptEngineManager().getEngineByName("nashorn").eval("JSON.parse"); } catch (ScriptException e) { throw new IllegalStateException("Can not get 'JSON.parse' from 'nashorn' script engine.", e); } }
public void formatFunction() { Double lower; Double upper; while(function.indexOf(']')>0) { lower = Double.parseDouble(function.substring((function.indexOf('[')+1),function.indexOf(':'))); upper = Double.parseDouble(function.substring((function.indexOf(':')+1),function.indexOf(']'))); function = function.substring(0, function.indexOf('v'))+variableMaker(lower,upper)+function.substring(function.indexOf(']')+1); } try { findAnswer(); } catch (ScriptException e) { e.printStackTrace(); } }
@Test public void createAndUseManyEngine() throws ScriptException { final ScriptEngineManager m = new ScriptEngineManager(); final ScriptEngine e1 = m.getEngineByName("nashorn"); e1.eval("var x = 33; print(x);"); final ScriptEngine e2 = m.getEngineByName("nashorn"); e2.eval("try { print(x) } catch(e) { print(e); }"); }
public DebugRestHandler() { engine = new ScriptEngineManager().getEngineByName("nashorn"); try { engine.eval("var imports = new JavaImporter(java.io, java.lang, java.util);"); } catch (ScriptException ex) { log.error("Failed setting up Nashorn", ex); } }
/** * Builds the script invocable */ private void buildInvocable() { ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("JavaScript"); try { if (hasScript()) { engine.eval(script.getValue()); inv = (Invocable) engine; } } catch (ScriptException e) { ExceptionHandler.get().handle(e); } }
@Test public void accessVolatileField() throws ScriptException { e.eval("var pv_boolean = o.volatileBoolean;"); assertEquals(o.volatileBoolean, e.get("pv_boolean")); assertEquals("boolean", e.eval("typeof pv_boolean;")); e.eval("o.volatileBoolean = false;"); assertEquals(false, o.volatileBoolean); }
/** * Get the line number for a {@code ScriptObject} representing an error * * @param errObj the error object * @return the line number, or undefined if wrapped exception is not a ParserException */ public static Object getLineNumber(final ScriptObject errObj) { final Object e = getException(errObj); if (e instanceof NashornException) { return ((NashornException)e).getLineNumber(); } else if (e instanceof ScriptException) { return ((ScriptException)e).getLineNumber(); } return UNDEFINED; }
@Test public void accessFinalFieldString() throws ScriptException { e.eval("var pf_string = o.publicFinalString;"); assertEquals(o.publicFinalString, e.get("pf_string")); assertEquals("string", e.eval("typeof pf_string;")); e.eval("o.publicFinalString = 'changedString';"); assertEquals("PublicFinalString", o.publicFinalString); }
@Test public void testConsStringFromMirror() throws ScriptException { final Bindings b = e.getBindings(ScriptContext.ENGINE_SCOPE); //final Map<Object, Object> m = new HashMap<>(); e.eval("var x = 'f'; x += 'oo'; var obj = {x: x};"); assertEquals("foo", ((JSObject)b.get("obj")).getMember("x")); }
@Test public void accessFinalFieldByte() throws ScriptException { e.eval("var pf_byte = o.publicFinalByte;"); assertEquals((double)o.publicFinalByte, ((Number)e.get("pf_byte")).doubleValue()); e.eval("o.publicFinalByte = 16;"); assertEquals(-7, o.publicFinalByte); }
@SuppressWarnings("unchecked") public <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException { try { List<Invoker<T>> invokersCopy = new ArrayList<Invoker<T>>(invokers); Compilable compilable = (Compilable) engine; Bindings bindings = engine.createBindings(); bindings.put("invokers", invokersCopy); bindings.put("invocation", invocation); bindings.put("context", RpcContext.getContext()); CompiledScript function = compilable.compile(rule); Object obj = function.eval(bindings); if (obj instanceof Invoker[]) { invokersCopy = Arrays.asList((Invoker<T>[]) obj); } else if (obj instanceof Object[]) { invokersCopy = new ArrayList<Invoker<T>>(); for (Object inv : (Object[]) obj) { invokersCopy.add((Invoker<T>)inv); } } else { invokersCopy = (List<Invoker<T>>) obj; } return invokersCopy; } catch (ScriptException e) { //fail then ignore rule .invokers. logger.error("route error , rule has been ignored. rule: " + rule + ", method:" + invocation.getMethodName() + ", url: " + RpcContext.getContext().getUrl(), e); return invokers; } }
/** * Evaluates the stream of the script. * * @param is * @return true if eval succeeded * @throws ScriptedAgentException */ final protected boolean evalStream(Reader reader) throws ScriptedAgentException { try { engine.eval(reader); return true; } catch (ScriptException e) { getLog().severe("Script error -> " + e.getMessage()); throw new ScriptedAgentException("Script error -> " + e.getMessage(), e); } }
@Test public void invalidScriptTest() { RunScript runScript = new RunScript("++++"); TUExecutionResult executionResult = runScript.execution(transformedAppFolder, transformationContext); Assert.assertEquals(executionResult.getType(), TUExecutionResult.Type.ERROR); Assert.assertNull(executionResult.getValue()); Assert.assertEquals(runScript.getDescription(), "Executes script '++++' and saves its evaluation result"); Assert.assertEquals(runScript.getScript(), "++++"); Assert.assertEquals(runScript.getObjects().size(), 0); Assert.assertEquals(runScript.getAttributes().size(), 0); Assert.assertEquals(runScript.getLanguage(), "js"); Assert.assertNotNull(executionResult.getException()); Assert.assertEquals(executionResult.getException().getClass(), ScriptException.class); Assert.assertEquals(executionResult.getException().getMessage(), "<eval>:1:2 Expected l-value but found ++\n++++\n ^ in <eval> at line number 1 at column number 2"); }