javax.script.ScriptEngine Java Examples

The following examples show how to use javax.script.ScriptEngine. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ScriptAddedFunctions.java    From hop with Apache License 2.0 6 votes vote down vote up
public static String resolveIP( ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
                                Object FunctionContext ) {
  String sRC = "";
  if ( ArgList.length == 2 ) {
    try {
      InetAddress addr = InetAddress.getByName( (String) ArgList[ 0 ] );
      if ( ( (String) ArgList[ 1 ] ).equals( "IP" ) ) {
        sRC = addr.getHostName();
      } else {
        sRC = addr.getHostAddress();
      }
      if ( sRC.equals( ArgList[ 0 ] ) ) {
        sRC = "-";
      }
    } catch ( Exception e ) {
      sRC = "-";
    }
  } else {
    throw new RuntimeException( "The function call resolveIP requires 2 arguments." );
  }

  return sRC;
}
 
Example #2
Source File: ScriptEngineTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void currentGlobalMissingTest() throws Exception {
    final ScriptEngineManager manager = new ScriptEngineManager();
    final ScriptEngine e = manager.getEngineByName("nashorn");

    final Context ctx = new Context();
    e.put("ctx", ctx);
    e.eval("var obj = { foo: function(str) { return str.toUpperCase() } }");
    e.eval("ctx.set(obj)");
    final Invocable inv = (Invocable)e;
    assertEquals("HELLO", inv.invokeMethod(ctx.get(), "foo", "hello"));
    // try object literal
    e.eval("ctx.set({ bar: function(str) { return str.toLowerCase() } })");
    assertEquals("hello", inv.invokeMethod(ctx.get(), "bar", "HELLO"));
    // try array literal
    e.eval("var arr = [ 'hello', 'world' ]");
    e.eval("ctx.set(arr)");
    assertEquals("helloworld", inv.invokeMethod(ctx.get(), "join", ""));
}
 
Example #3
Source File: InvocableTest.java    From jdk8u_nashorn with GNU General Public License v2.0 6 votes vote down vote up
@Test
/**
 * Check that we can get interface out of a script object even after
 * switching to use different ScriptContext.
 */
public void getInterfaceDifferentContext() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    try {
        final Object obj = e.eval("({ run: function() { } })");

        // change script context
        final ScriptContext ctxt = new SimpleScriptContext();
        ctxt.setBindings(e.createBindings(), ScriptContext.ENGINE_SCOPE);
        e.setContext(ctxt);

        final Runnable r = ((Invocable) e).getInterface(obj, Runnable.class);
        r.run();
    } catch (final Exception exp) {
        exp.printStackTrace();
        fail(exp.getMessage());
    }
}
 
Example #4
Source File: ScriptEngineTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@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(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());
}
 
Example #5
Source File: PluggableJSObjectTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@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());
    }
}
 
Example #6
Source File: ScriptEngineSecurityTest.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void fakeProxySubclassAccessCheckTest2() throws ScriptException {
    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 });

    String getClass = "Java.type(name + '$FakeProxy').makeProxyClass(cl, intfs);";

    // Should not be able to call static methods of Proxy via fake subclass
    try {
        Class c = (Class)e.eval(getClass);
        fail("should have thrown SecurityException");
    } catch (final Exception exp) {
        if (! (exp instanceof SecurityException)) {
            fail("SecurityException expected, got " + exp);
        }
    }
}
 
Example #7
Source File: ScriptObjectMirrorTest.java    From jdk8u_nashorn with GNU General Public License v2.0 6 votes vote down vote up
@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));
    }
}
 
Example #8
Source File: InvokeScriptMethod.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
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. This code defines a script object 'obj'
    // with one method called 'hello'.
    final String script = "var obj = new Object(); obj.hello = function(name) { print('Hello, ' + name); }";
    // evaluate script
    engine.eval(script);

    // javax.script.Invocable is an optional interface.
    // Check whether your script engine implements or not!
    // Note that the JavaScript engine implements Invocable interface.
    final Invocable inv = (Invocable) engine;

    // get script object on which we want to call the method
    final Object obj = engine.get("obj");

    // invoke the method named "hello" on the script object "obj"
    inv.invokeMethod(obj, "hello", "Script Method !!" );
}
 
Example #9
Source File: JavaScriptExecutor.java    From mdw with Apache License 2.0 6 votes vote down vote up
public Object evaluate(String expression, Map<String, Object> bindings)
throws ExecutionException {
    try {
        ScriptEngineManager factory = new ScriptEngineManager();
        ScriptEngine engine = factory.getEngineByName("JavaScript");
        if (engine == null)
            engine = factory.getEngineByName("Rhino JavaScript");  // ServiceMix
        for (String bindName : bindings.keySet()) {
            engine.put(bindName, bindings.get(bindName));
        }

       return engine.eval(expression);
    }
    catch (ScriptException ex) {
        throw new ExecutionException("Error executing JavaScript: " + ex.getMessage(), ex);
    }
}
 
Example #10
Source File: InvokeScriptMethod.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
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. This code defines a script object 'obj'
    // with one method called 'hello'.
    final String script = "var obj = new Object(); obj.hello = function(name) { print('Hello, ' + name); }";
    // evaluate script
    engine.eval(script);

    // javax.script.Invocable is an optional interface.
    // Check whether your script engine implements or not!
    // Note that the JavaScript engine implements Invocable interface.
    final Invocable inv = (Invocable) engine;

    // get script object on which we want to call the method
    final Object obj = engine.get("obj");

    // invoke the method named "hello" on the script object "obj"
    inv.invokeMethod(obj, "hello", "Script Method !!" );
}
 
Example #11
Source File: ScriptEngineSecurityTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@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);
        }
    }
}
 
Example #12
Source File: GroovyScriptEngineFactory.java    From hasor with Apache License 2.0 6 votes vote down vote up
public Object getParameter(String key) {
    if (ScriptEngine.NAME.equals(key)) {
        return SHORT_NAME;
    } else if (ScriptEngine.ENGINE.equals(key)) {
        return getEngineName();
    } else if (ScriptEngine.ENGINE_VERSION.equals(key)) {
        return VERSION;
    } else if (ScriptEngine.LANGUAGE.equals(key)) {
        return LANGUAGE_NAME;
    } else if (ScriptEngine.LANGUAGE_VERSION.equals(key)) {
        return GroovySystem.getVersion();
    } else if ("THREADING".equals(key)) {
        return "MULTITHREADED";
    } else {
        throw new IllegalArgumentException("Invalid key");
    }
}
 
Example #13
Source File: ScriptAddedFunctions.java    From hop with Apache License 2.0 6 votes vote down vote up
public static Object getNextWorkingDay( ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
                                        Object FunctionContext ) {
  // (Date dIn){
  if ( ArgList.length == 1 ) {
    try {
      if ( isNull( ArgList[ 0 ] ) ) {
        return null;
      } else if ( isUndefined( ArgList[ 0 ] ) ) {
        return undefinedValue;
      }
      java.util.Date dIn = (java.util.Date) ArgList[ 0 ];
      Calendar startDate = Calendar.getInstance();
      startDate.setTime( dIn );
      startDate.add( Calendar.DATE, 1 );
      while ( startDate.get( Calendar.DAY_OF_WEEK ) == Calendar.SATURDAY
        || startDate.get( Calendar.DAY_OF_WEEK ) == Calendar.SUNDAY ) {
        startDate.add( Calendar.DATE, 1 );
      }
      return startDate.getTime();
    } catch ( Exception e ) {
      throw new RuntimeException( e.toString() );
    }
  } else {
    throw new RuntimeException( "The function call getNextWorkingDay requires 1 argument." );
  }
}
 
Example #14
Source File: JSONCompatibleTest.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #15
Source File: ScriptAddedFunctions.java    From hop with Apache License 2.0 6 votes vote down vote up
public static String rtrim( ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
                            Object FunctionContext ) {
  try {
    if ( ArgList.length == 1 ) {
      if ( isNull( ArgList[ 0 ] ) ) {
        return null;
      } else if ( isUndefined( ArgList[ 0 ] ) ) {
        return (String) undefinedValue;
      }
      String strValueToTrim = (String) ArgList[ 0 ];
      return strValueToTrim.replaceAll( "\\s+$", "" );
    } else {
      throw new RuntimeException( "The function call rtrim requires 1 argument." );
    }
  } catch ( Exception e ) {
    throw new RuntimeException( "The function call rtrim is not valid : " + e.getMessage() );
  }
}
 
Example #16
Source File: PluggableJSObjectTest.java    From jdk8u_nashorn with GNU General Public License v2.0 6 votes vote down vote up
@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());
    }
}
 
Example #17
Source File: ScriptEngineTest.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
@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());
    }
}
 
Example #18
Source File: ScriptAddedFunctions.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
public static Object isNum( ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
  Object FunctionContext ) {

  if ( ArgList.length == 1 ) {
    try {
      if ( isNull( ArgList[0] ) ) {
        return null;
      } else if ( isUndefined( ArgList[0] ) ) {
        return undefinedValue;
      }
      double sArg1 = (Double) ArgList[0];
      if ( Double.isNaN( sArg1 ) ) {
        return Boolean.FALSE;
      } else {
        return Boolean.TRUE;
      }
    } catch ( Exception e ) {
      return Boolean.FALSE;
    }
  } else {
    throw new RuntimeException( "The function call isNum requires 1 argument." );
  }
}
 
Example #19
Source File: ScriptTemplateView.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
protected ScriptEngine getEngine() {
	if (Boolean.FALSE.equals(this.sharedEngine)) {
		Map<Object, ScriptEngine> engines = enginesHolder.get();
		if (engines == null) {
			engines = new HashMap<Object, ScriptEngine>(4);
			enginesHolder.set(engines);
		}
		Object engineKey = (!ObjectUtils.isEmpty(this.scripts) ?
				new EngineKey(this.engineName, this.scripts) : this.engineName);
		ScriptEngine engine = engines.get(engineKey);
		if (engine == null) {
			engine = createEngineFromName();
			engines.put(engineKey, engine);
		}
		return engine;
	}
	else {
		// Simply return the configured ScriptEngine...
		return this.engine;
	}
}
 
Example #20
Source File: InvocableTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@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());
        }
    }
}
 
Example #21
Source File: RunnableImpl.java    From jdk8u_nashorn with GNU General Public License v2.0 6 votes vote down vote up
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 = "function run() { print('run called'); }";

    // evaluate script
    engine.eval(script);

    final Invocable inv = (Invocable) engine;

    // get Runnable interface object from engine. This interface methods
    // are implemented by script functions with the matching name.
    final Runnable r = inv.getInterface(Runnable.class);

    // start a new thread that runs the script implemented
    // runnable interface
    final Thread th = new Thread(r);
    th.start();
    th.join();
}
 
Example #22
Source File: ScopeTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void invokeFunctionWithCustomScriptContextTest() throws Exception {
    final ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");

    // create an engine and a ScriptContext, but don't set it as default
    final ScriptContext scriptContext = new SimpleScriptContext();

    // Set some value in the context
    scriptContext.setAttribute("myString", "foo", ScriptContext.ENGINE_SCOPE);

    // Evaluate script with custom context and get back a function
    final String script = "function (c) { return myString.indexOf(c); }";
    final CompiledScript compiledScript = ((Compilable)engine).compile(script);
    final Object func = compiledScript.eval(scriptContext);

    // Invoked function should be able to see context it was evaluated with
    final Object result = ((Invocable) engine).invokeMethod(func, "call", func, "o", null);
    assertTrue(((Number)result).intValue() == 1);
}
 
Example #23
Source File: TrustedScriptEngineTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@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");
        }
    }
}
 
Example #24
Source File: Context.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Initialize given global scope object.
 *
 * @param global the global
 * @param engine the associated ScriptEngine instance, can be null
 * @return the initialized global scope object.
 */
public Global initGlobal(final Global global, final ScriptEngine engine) {
    // Need only minimal global object, if we are just compiling.
    if (!env._compile_only) {
        final Global oldGlobal = Context.getGlobal();
        try {
            Context.setGlobal(global);
            // initialize global scope with builtin global objects
            global.initBuiltinObjects(engine);
        } finally {
            Context.setGlobal(oldGlobal);
        }
    }

    return global;
}
 
Example #25
Source File: ScriptEngineTest.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void argumentsWithTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    String[] args = new String[] { "hello", "world" };
    try {
        e.put("arguments", args);
        Object arg0 = e.eval("var imports = new JavaImporter(java.io); " +
                " with(imports) { arguments[0] }");
        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());
    }
}
 
Example #26
Source File: PluggableJSObjectTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Test
// iteration tests
public void iteratingJSObjectTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    try {
        final MapWrapperObject obj = new MapWrapperObject();
        obj.setMember("foo", "hello");
        obj.setMember("bar", "world");
        e.put("obj", obj);

        // check for..in
        Object val = e.eval("var str = ''; for (i in obj) str += i; str");
        assertEquals(val.toString(), "foobar");

        // check for..each..in
        val = e.eval("var str = ''; for each (i in obj) str += i; str");
        assertEquals(val.toString(), "helloworld");
    } catch (final Exception exp) {
        exp.printStackTrace();
        fail(exp.getMessage());
    }
}
 
Example #27
Source File: InvocableTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@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());
        }
    }
}
 
Example #28
Source File: ScriptUtil.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
/**
 * Executes a compiled script and returns the result.
 *
 * @param script Compiled script.
 * @param functionName Optional function or method to invoke.
 * @param scriptContext Script execution context.
 * @return The script result.
 * @throws IllegalArgumentException
 */
public static Object executeScript(CompiledScript script, String functionName, ScriptContext scriptContext, Object[] args) throws ScriptException, NoSuchMethodException {
    Assert.notNull("script", script, "scriptContext", scriptContext);
    Object result = script.eval(scriptContext);
    if (UtilValidate.isNotEmpty(functionName)) {
        if (Debug.verboseOn()) {
            Debug.logVerbose("Invoking function/method " + functionName, module);
        }
        ScriptEngine engine = script.getEngine();
        try {
            Invocable invocableEngine = (Invocable) engine;
            result = invocableEngine.invokeFunction(functionName, args == null ? EMPTY_ARGS : args);
        } catch (ClassCastException e) {
            throw new ScriptException("Script engine " + engine.getClass().getName() + " does not support function/method invocations");
        }
    }
    return result;
}
 
Example #29
Source File: InvocableTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
@Test
/**
 * Check that getInterface on non-script object 'thiz' results in
 * IllegalArgumentException.
 */
public void getInterfaceNonScriptObjectThizTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        ((Invocable) e).getInterface(new Object(), Runnable.class);
        fail("should have thrown IllegalArgumentException");
    } catch (final Exception exp) {
        if (!(exp instanceof IllegalArgumentException)) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }
}
 
Example #30
Source File: ScopeTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Test multi-threaded access to primitive prototype user accessor properties for shared script classes with multiple globals.
 */
@Test
public static void multiThreadedPrimitiveAccessorTest() 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);

    e.eval("Object.defineProperty(String.prototype, 'foo', { get: function() 'original context' })", origContext);
    e.eval("Object.defineProperty(String.prototype, 'foo', { get: function() 'new context' })", newCtxt);
    final String sharedScript = "''.foo";

    final Thread t1 = new Thread(new ScriptRunner(e, origContext, sharedScript, "original context", 1000));
    final Thread t2 = new Thread(new ScriptRunner(e, newCtxt, sharedScript, "new context", 1000));
    t1.start();
    t2.start();
    t1.join();
    t2.join();

    final Object obj3 = e.eval("delete String.prototype.foo; Object.prototype.foo = 'newer context';", newCtxt);
    assertEquals(obj3, "newer context");
    final Thread t3 = new Thread(new ScriptRunner(e, origContext, sharedScript, "original context", 1000));
    final Thread t4 = new Thread(new ScriptRunner(e, newCtxt, sharedScript, "newer context", 1000));

    t3.start();
    t4.start();
    t3.join();
    t4.join();
}