javax.script.ScriptException Java Examples

The following examples show how to use javax.script.ScriptException. 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: NumberBoxingTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void accessFieldFloatBoxing() throws ScriptException {
    e.eval("var p_float = o.publicFloatBox;");
    assertEqualsDouble(o.publicFloatBox, "p_float");
    o.publicFloatBox = 0.0f / 0.0f;
    assertEquals(true, e.eval("isNaN(o.publicFloatBox)"));
    o.publicFloatBox = 1.0f / 0.0f;
    assertEquals(true, e.eval("Number.POSITIVE_INFINITY === o.publicFloatBox"));
    o.publicFloatBox = -1.0f / 0.0f;
    assertEquals(true, e.eval("Number.NEGATIVE_INFINITY === o.publicFloatBox"));
    e.eval("o.publicFloatBox = 20;");
    assertEquals(20, o.publicFloatBox, 1e-10);
    e.eval("o.publicFloatBox = 0.0/0.0;");
    assertTrue(Float.isNaN(o.publicFloatBox));
    e.eval("o.publicFloatBox = 1.0/0.0;");
    assertEquals(Float.floatToIntBits(Float.POSITIVE_INFINITY), Float.floatToIntBits(o.publicFloatBox));
    e.eval("o.publicFloatBox = -1.0/0.0;");
    assertEquals(Float.NEGATIVE_INFINITY, o.publicFloatBox, 1e-10);
}
 
Example #2
Source File: TrustedScriptEngineTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void classFilterTest() throws ScriptException {
    final NashornScriptEngineFactory fac = new NashornScriptEngineFactory();
    final ScriptEngine e = fac.getScriptEngine(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 #3
Source File: LexicalBindingTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Test access to global lexically declared variables for shared script classes with single global.
 */
@Test
public static void megamorphicSingleGlobalLetTest() throws ScriptException, InterruptedException {
    final NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
    final ScriptEngine e = factory.getScriptEngine(LANGUAGE_ES6);
    final String sharedGetterScript = "foo";
    final String sharedSetterScript = "foo = 1";

    for (int i = 0; i < MEGAMORPHIC_LOOP_COUNT; i++) {
        assertEquals(e.eval(sharedSetterScript), 1);
        assertEquals(e.eval(sharedGetterScript), 1);
        assertEquals(e.eval("delete foo; a" + i + " = 1; foo = " + i + ";"), i);
        assertEquals(e.eval(sharedGetterScript), i);
    }

    assertEquals(e.eval("let foo = 'foo';"), null);
    assertEquals(e.eval(sharedGetterScript), "foo");
    assertEquals(e.eval(sharedSetterScript), 1);
    assertEquals(e.eval(sharedGetterScript), 1);
    assertEquals(e.eval("this.foo"), MEGAMORPHIC_LOOP_COUNT - 1);
}
 
Example #4
Source File: LexicalBindingTest.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Test access to global lexically declared variables for shared script classes with single global.
 */
@Test
public static void megamorphicInheritedGlobalLetTest() throws ScriptException, InterruptedException {
    final NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
    final ScriptEngine e = factory.getScriptEngine(LANGUAGE_ES6);
    final String sharedGetterScript = "foo";
    final String sharedSetterScript = "foo = 1";

    for (int i = 0; i < MEGAMORPHIC_LOOP_COUNT; i++) {
        assertEquals(e.eval(sharedSetterScript), 1);
        assertEquals(e.eval(sharedGetterScript), 1);
        assertEquals(e.eval("delete foo; a" + i + " = 1; Object.prototype.foo = " + i + ";"), i);
        assertEquals(e.eval(sharedGetterScript), i);
    }

    assertEquals(e.eval("let foo = 'foo';"), null);
    assertEquals(e.eval(sharedGetterScript), "foo");
    assertEquals(e.eval(sharedSetterScript), 1);
    assertEquals(e.eval(sharedGetterScript), 1);
    assertEquals(e.eval("this.foo"), MEGAMORPHIC_LOOP_COUNT - 1);
}
 
Example #5
Source File: GremlinGroovyScriptEngineTimedInterruptTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldContinueToEvalScriptsEvenWithTimedInterrupt() throws Exception {
    final ScriptEngine engine = new GremlinGroovyScriptEngine(
            new TimedInterruptGroovyCustomizer(1000));

    for (int ix = 0; ix < 5; ix++) {
        try {
            // this script takes 1000 ms longer than the interruptionTimeout
            engine.eval("s = System.currentTimeMillis();\nwhile((System.currentTimeMillis() - s) < 2000) {}");
            fail("This should have timed out");
        } catch (ScriptException se) {
            assertEquals(org.apache.tinkerpop.gremlin.groovy.jsr223.TimedInterruptTimeoutException.class, se.getCause().getCause().getClass());
        }

        // this script takes 500 ms less than the interruptionTimeout
        assertEquals("test", engine.eval("s = System.currentTimeMillis();\nwhile((System.currentTimeMillis() - s) < 500) {};'test'"));
    }

    assertEquals(2, engine.eval("1+1"));
}
 
Example #6
Source File: PromptHandler.java    From sqlline with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private AttributedString getPromptFromScript(SqlLine sqlLine,
    String promptScript) {
  try {
    final ScriptEngine engine = SCRIPT_ENGINE_SUPPLIER.get();
    final Bindings bindings = new SimpleBindings();
    final ConnectionMetadata meta = sqlLine.getConnectionMetadata();
    bindings.put("connectionIndex", meta.getIndex());
    bindings.put("databaseProductName", meta.getDatabaseProductName());
    bindings.put("userName", meta.getUserName());
    bindings.put("url", meta.getUrl());
    bindings.put("currentSchema", meta.getCurrentSchema());
    final Object o = engine.eval(promptScript, bindings);
    return new AttributedString(String.valueOf(o));
  } catch (ScriptException e) {
    e.printStackTrace();
    return new AttributedString(">");
  }
}
 
Example #7
Source File: ScriptObjectMirrorTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@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));
}
 
Example #8
Source File: NumberAccessTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void accessFieldChar() throws ScriptException {
    e.eval("var p_char = o.publicChar;");
    assertEquals(o.publicChar, e.get("p_char"));
    e.eval("o.publicChar = 'S';");
    assertEquals('S', o.publicChar);
    e.eval("o.publicChar = 10;");
    assertEquals(10, o.publicChar);
    e.eval("try {"
            + "    o.publicChar = 'Big string';" +
            "} catch(e) {" +
            "    var isThrown = true;" +
            "}");
    assertEquals("Exception thrown", true, e.get("isThrown"));
    assertEquals(10, o.publicChar);
}
 
Example #9
Source File: Titan1Graph.java    From incubator-atlas with Apache License 2.0 6 votes vote down vote up
private Object executeGremlinScript(String gremlinQuery) throws AtlasBaseException {
    GremlinGroovyScriptEngine scriptEngine = getGremlinScriptEngine();

    try {
        Bindings bindings = scriptEngine.createBindings();

        bindings.put("graph", getGraph());
        bindings.put("g", getGraph().traversal());

        Object result = scriptEngine.eval(gremlinQuery, bindings);

        return result;
    } catch (ScriptException e) {
        throw new AtlasBaseException(AtlasErrorCode.GREMLIN_SCRIPT_EXECUTION_FAILED, gremlinQuery);
    } finally {
        releaseGremlinScriptEngine(scriptEngine);
    }
}
 
Example #10
Source File: GroovyScriptEngineImpl.java    From groovy with Apache License 2.0 6 votes vote down vote up
public Object eval(String script, ScriptContext ctx)
        throws ScriptException {
    try {
        String val = (String) ctx.getAttribute("#jsr223.groovy.engine.keep.globals", ScriptContext.ENGINE_SCOPE);
        ReferenceBundle bundle = ReferenceBundle.getHardBundle();
        if (val != null && val.length() > 0) {
            if (val.equalsIgnoreCase("soft")) {
                bundle = ReferenceBundle.getSoftBundle();
            } else if (val.equalsIgnoreCase("weak")) {
                bundle = ReferenceBundle.getWeakBundle();
            } else if (val.equalsIgnoreCase("phantom")) {
                bundle = ReferenceBundle.getPhantomBundle();
            }
        }
        globalClosures.setBundle(bundle);
    } catch (ClassCastException cce) { /*ignore.*/ }

    try {
        Class<?> clazz = getScriptClass(script, ctx);
        if (clazz == null) throw new ScriptException("Script class is null");
        return eval(clazz, ctx);
    } catch (Exception e) {
        if (debug) e.printStackTrace();
        throw new ScriptException(e);
    }
}
 
Example #11
Source File: JavaScriptConfigEvaluator.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
public String evaluateJavaScript(Reader fileReader)
{
    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine engine = mgr.getEngineByName("JavaScript");
    try
    {
        engine.eval(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("json2.js")));
        engine.eval(new InputStreamReader(getClass().getClassLoader().getResourceAsStream("test-utils.js")));
        engine.eval(fileReader);
        engine.eval("jsonString = JSON.stringify(" + TEST_CONFIG_VARIABLE_NAME + ")");
    }
    catch (ScriptException e)
    {
        throw new DistributedTestException("Exception while evaluating test config", e);
    }
    String result = (String) engine.get("jsonString");

    return result;
}
 
Example #12
Source File: BSFRuleExpression.java    From rice with Educational Community License v2.0 6 votes vote down vote up
public RuleExpressionResult evaluate(Rule rule, RouteContext context) {
    org.kuali.rice.kew.api.rule.RuleContract ruleDefinition = rule.getDefinition();
    String name = "" + ruleDefinition.getName();
    String type = ruleDefinition.getRuleExpressionDef().getType();
    String lang = parseLang(type, "groovy");
    String expression = ruleDefinition.getRuleExpressionDef().getExpression();
    RuleExpressionResult result;
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName(lang);
    try {
        declareBeans(engine, rule, context);
        result = (RuleExpressionResult) engine.eval(expression);
    } catch (ScriptException e) {
        String details =  ( e.getLineNumber() >= 0 ?  " line: " + e.getLineNumber() + " column: " + e.getColumnNumber() : "" );
        LOG.debug("Error evaluating rule '" + name + "' " + type +  " expression" + details + ": '" + expression + "'" + details, e);
        throw new RiceIllegalStateException("Error evaluating rule '" + name + "' " + type + " expression" + details, e);
    }
    if (result == null) {
        return new RuleExpressionResult(rule, false);
    } else {
        return result;
    }
}
 
Example #13
Source File: ScriptEngineTest.java    From jdk8u_nashorn with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void checkProxyAccess() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final boolean[] reached = new boolean[1];
    final Runnable r = (Runnable)Proxy.newProxyInstance(
        ScriptEngineTest.class.getClassLoader(),
        new Class[] { Runnable.class },
        new InvocationHandler() {
            @Override
            public Object invoke(final Object p, final Method mtd, final Object[] a) {
                reached[0] = true;
                return null;
            }
        });

    e.put("r", r);
    e.eval("r.run()");

    assertTrue(reached[0]);
}
 
Example #14
Source File: Processor.java    From Java-9-Programming-By-Example with MIT License 5 votes vote down vote up
private void execute(final String scriptFileName, final String engineName)
		throws ScriptException, FileNotFoundException {
	final ScriptEngineManager factory = new ScriptEngineManager();
	final ScriptEngine engine;
	if (engineName != null && engineName.length() > 0) {
		engine = factory.getEngineByName(engineName);
	} else {
		engine = factory
				.getEngineByExtension(getExtensionFrom(scriptFileName));
	}
	Reader scriptFileReade = new FileReader(new File(scriptFileName));
	engine.eval(scriptFileReade);
}
 
Example #15
Source File: StringAccessTest.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void accessFinalFieldStringArray() throws ScriptException {
    e.eval("var pf_string_array = o.publicFinalStringArray;");
    assertEquals(o.publicFinalStringArray[0], e.eval("o.publicFinalStringArray[0]"));
    assertArrayEquals(o.publicFinalStringArray, (String[])e.get("pf_string_array"));
    e.eval("var tf_string_arr = new (Java.type(\"java.lang.String[]\"))(3);" +
            "tf_string_arr[0] = 'abc';" +
            "tf_string_arr[1] = '123';" +
            "tf_string_arr[2] = 'xyzzzz';" +
            "o.publicFinalStringArray = tf_string_arr;");
    assertArrayEquals(new String[] { "FinalArrayString[0]", "FinalArrayString[1]", "FinalArrayString[2]", "FinalArrayString[3]" }, o.publicFinalStringArray);
    e.eval("o.publicFinalStringArray[0] = 'nashorn';");
    assertEquals("nashorn", o.publicFinalStringArray[0]);
}
 
Example #16
Source File: StringAccessTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@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);
}
 
Example #17
Source File: NumberAccessTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void accessStaticFinalFieldCharArray() throws ScriptException {
    e.eval("var psf_char_array = SharedObject.publicStaticFinalCharArray;");
    assertEquals(SharedObject.publicStaticFinalCharArray[0], e.eval("SharedObject.publicStaticFinalCharArray[0];"));
    assertArrayEquals(SharedObject.publicStaticFinalCharArray, (char[])e.get("psf_char_array"));
    e.eval("var tsf_char_arr = new (Java.type(\"char[]\"))(3);" +
            "tsf_char_arr[0] = 'Z';" +
            "tsf_char_arr[1] = 'o';" +
            "tsf_char_arr[2] = 'o';" +
            "SharedObject.publicStaticFinalCharArray = tsf_char_arr;");
    assertArrayEquals("StaticString".toCharArray(), SharedObject.publicStaticFinalCharArray);
    e.eval("SharedObject.publicStaticFinalCharArray[0] = 'Z';");
    assertEquals('Z', SharedObject.publicStaticFinalCharArray[0]);
}
 
Example #18
Source File: NumberBoxingTest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void accessStaticFieldIntBoxing() throws ScriptException {
    e.eval("var ps_int = SharedObject.publicStaticInt;");
    assertEquals(SharedObject.publicStaticInt, e.get("ps_int"));
    e.eval("SharedObject.publicStaticInt = 140;");
    assertEquals(140, SharedObject.publicStaticInt);
}
 
Example #19
Source File: ReactorScriptManager.java    From HeavenMS with GNU Affero General Public License v3.0 5 votes vote down vote up
public void act(MapleClient c, MapleReactor reactor) {
    try {
        NashornScriptEngine iv = getScriptEngine("reactor/" + reactor.getId() + ".js", c);
        if (iv == null) return;
        
        ReactorActionManager rm = new ReactorActionManager(c, reactor, iv);
        iv.put("rm", rm);
        iv.invokeFunction("act");
    } catch (final ScriptException | NoSuchMethodException | NullPointerException e) {
        FilePrinter.printError(FilePrinter.REACTOR + reactor.getId() + ".txt", e);
    }
}
 
Example #20
Source File: NumberAccessTest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void accessFinalFieldInt() throws ScriptException {
    e.eval("var pf_int = o.publicFinalInt;");
    assertEquals(o.publicFinalInt, e.get("pf_int"));

    e.eval("o.publicFinalInt = 10;");
    assertEquals(20712023, o.publicFinalInt);
}
 
Example #21
Source File: HealthTest.java    From apollo with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void initialize() throws ScriptException, IOException, SQLException, ApolloClientException {
    apolloTestClient = Common.signupAndLogin();
    standaloneApollo = StandaloneApollo.getOrCreateServer();
    standaloneApollo.startKubernetesHealth();
    ModelsGenerator.createAndSubmitEnvironment(apolloTestClient);
}
 
Example #22
Source File: FXShell.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Load and evaluate the specified JavaScript file.
 *
 * @param path Path to UTF-8 encoded JavaScript file.
 *
 * @return Last evaluation result (discarded.)
 */
@SuppressWarnings("resource")
private Object load(String path) {
    try {
        FileInputStream file = new FileInputStream(path);
        InputStreamReader input = new InputStreamReader(file, "UTF-8");
        return engine.eval(input);
    } catch (FileNotFoundException | UnsupportedEncodingException | ScriptException ex) {
        ex.printStackTrace();
    }

    return null;
}
 
Example #23
Source File: NumberAccessTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void accessStaticFieldShort() throws ScriptException {
    e.eval("var ps_short = SharedObject.publicStaticShort;");
    assertEquals((double)SharedObject.publicStaticShort, ((Number)e.get("ps_short")).doubleValue());
    e.eval("SharedObject.publicStaticShort = 180;");
    assertEquals(180, SharedObject.publicStaticShort);
}
 
Example #24
Source File: NumberBoxingTest.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@BeforeClass
public static void setUpClass() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    e = m.getEngineByName("nashorn");
    o = new SharedObject();
    e.put("o", o);
    e.eval("var SharedObject = Packages.jdk.nashorn.api.javaaccess.test.SharedObject;");
}
 
Example #25
Source File: NumberAccessTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void accessStaticFieldLong() throws ScriptException {
    e.eval("var ps_long = SharedObject.publicStaticLong;");
    assertEquals(SharedObject.publicStaticLong, e.get("ps_long"));
    e.eval("SharedObject.publicStaticLong = 120;");
    assertEquals(120, SharedObject.publicStaticLong);
}
 
Example #26
Source File: LexicalBindingTest.java    From jdk8u_nashorn with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Test multi-threaded access to global lexically declared variables for shared script classes with multiple globals.
 */
@Test
public static void multiThreadedLetTest() throws ScriptException, InterruptedException {
    final NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
    final ScriptEngine e = factory.getScriptEngine(LANGUAGE_ES6);
    final Bindings b = e.createBindings();
    final ScriptContext origContext = e.getContext();
    final ScriptContext newCtxt = new SimpleScriptContext();
    newCtxt.setBindings(b, ScriptContext.ENGINE_SCOPE);
    final String sharedScript = "foo";

    assertEquals(e.eval("let foo = 'original context';", origContext), null);
    assertEquals(e.eval("let foo = 'new context';", newCtxt), null);

    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();

    assertEquals(e.eval("foo = 'newer context';", newCtxt), "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();

    assertEquals(e.eval(sharedScript), "original context");
    assertEquals(e.eval(sharedScript, newCtxt), "newer context");
}
 
Example #27
Source File: JavaScriptResponseHandlerImpl.java    From smockin with Apache License 2.0 5 votes vote down vote up
public RestfulResponseDTO executeUserResponse(final Request req, final RestfulMock mock) {
    logger.debug("executeUserResponse called");

    Object engineResponse;

    try {

        engineResponse = executeJS(
                defaultRequestObject
                    + populateRequestObjectWithInbound(req, mock.getPath(), mock.getCreatedBy().getCtxPath())
                    + populateKVPs(req, mock)
                    + keyValuePairFindFunc
                    + defaultResponseObject
                    + userResponseFunctionInvoker
                    + mock.getJavaScriptHandler().getSyntax());

    } catch (ScriptException ex) {

        return new RestfulResponseDTO(500,
                "text/plain",
                "Looks like there is an issue with the Javascript driving this mock " + ex.getMessage());
    }

    if (!(engineResponse instanceof ScriptObjectMirror)) {
        return new RestfulResponseDTO(500,
                "text/plain",
                "Looks like there is an issue with the Javascript driving this mock!");
    }

    final ScriptObjectMirror response = (ScriptObjectMirror) engineResponse;

    return new RestfulResponseDTO(
            (int) response.get("status"),
            (String) response.get("contentType"),
            (String) response.get("body"),
            convertResponseHeaders(response));
}
 
Example #28
Source File: ScriptEngineTest.java    From jdk8u_nashorn with GNU General Public License v2.0 5 votes vote down vote up
@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");
}
 
Example #29
Source File: JSONCompatibleTest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Wrap a top-level array as a list.
 */
@Test
public void testWrapArray() throws ScriptException {
    final ScriptEngine engine = new NashornScriptEngineFactory().getScriptEngine();
    final Object val = engine.eval("Java.asJSONCompatible([1, 2, 3])");
    assertEquals(asList(val), Arrays.asList(1, 2, 3));
}
 
Example #30
Source File: InvocableCallable.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public Object call(Object[] args) throws ScriptException {
  try {
    if (target == null) {
      return invocable.invokeFunction(name, args);
    } else {
      return invocable.invokeMethod(target, name, args);
    }
  } catch (NoSuchMethodException nme) {
    throw new ScriptException(nme);
  }
}