Java Code Examples for javax.script.ScriptEngineManager#getEngineByName()

The following examples show how to use javax.script.ScriptEngineManager#getEngineByName() . 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: ScriptEngineSecurityTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void securityPackagesTest() {
    if (System.getSecurityManager() == null) {
        // pass vacuously
        return;
    }

    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    try {
        e.eval("var v = Packages.sun.misc.Unsafe;");
        fail("should have thrown SecurityException");
    } catch (final Exception exp) {
        if (exp instanceof SecurityException) {
            log("got " + exp + " as expected");
        } else {
            fail(exp.getMessage());
        }
    }
}
 
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 argumentsTest() {
    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("arguments[0]");
        final Object arg1 = e.eval("arguments[1]");
        assertEquals(args[0], arg0);
        assertEquals(args[1], arg1);
    } catch (final Exception exp) {
        exp.printStackTrace();
        fail(exp.getMessage());
    }
}
 
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: StringUtil.java    From cerberus-source with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Java function that encodes as string as the JavaScript function:
 * encodeURIComponent() Some characters (", &, #, +) need to be
 *
 * @param stringToEncode string to be encoded
 * @return string encoded
 */
public static String encodeAsJavaScriptURIComponent(String stringToEncode) {
    try {
        ScriptEngineManager factory = new ScriptEngineManager();
        ScriptEngine engine = factory.getEngineByName("JavaScript");
        //characters we special meaning need to be encoded before applying
        //the javascript function
        stringToEncode = stringToEncode.replace("\"", "%22");
        stringToEncode = stringToEncode.replace("&", "%26");
        stringToEncode = stringToEncode.replace("#", "%23");
        stringToEncode = stringToEncode.replace("+", "%2B");
        stringToEncode = engine.eval("encodeURIComponent(\"" + stringToEncode + "\")").toString();
        //the previous special characteres were encoded and additional %25 were added, therefore 
        //we need to restore them and replace the each adicional %25 with the decoded character %
        stringToEncode = stringToEncode.replace("%2522", "%22");
        stringToEncode = stringToEncode.replace("%2526", "%26");
        stringToEncode = stringToEncode.replace("%2523", "%23");
        stringToEncode = stringToEncode.replace("%252B", "%2B");
    } catch (ScriptException ex) {
        LOG.warn(ex);
    }
    return stringToEncode;
}
 
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: MultiScopes.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");

    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"
}
 
Example 7
Source File: ScriptEngineTest.java    From TencentKona-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 8
Source File: InvocableTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@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);
        }
    }
}
 
Example 9
Source File: ScriptEngineSecurityTest.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void securityPackagesTest() {
    if (System.getSecurityManager() == null) {
        // pass vacuously
        return;
    }

    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    try {
        e.eval("var v = Packages.sun.misc.Unsafe;");
        fail("should have thrown SecurityException");
    } catch (final Exception exp) {
        if (exp instanceof SecurityException) {
            log("got " + exp + " as expected");
        } else {
            fail(exp.getMessage());
        }
    }
}
 
Example 10
Source File: ScriptEngineTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void accessGlobalTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        e.eval("var x = 'hello'");
        assertEquals(e.get("x"), "hello");
    } catch (final ScriptException exp) {
        exp.printStackTrace();
        fail(exp.getMessage());
    }
}
 
Example 11
Source File: ScriptVars.java    From hottub with GNU General Public License v2.0 5 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");

    final File f = new File("test.txt");
    // expose File object as variable to script
    engine.put("file", f);

    // evaluate a script string. The script accesses "file"
    // variable and calls method on it
    engine.eval("print(file.getAbsolutePath())");
}
 
Example 12
Source File: EvalFile.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
    // create a script engine manager
    final ScriptEngineManager factory = new ScriptEngineManager();
    // create JavaScript engine
    final ScriptEngine engine = factory.getEngineByName("nashorn");
    // evaluate JavaScript code from given file - specified by first argument
    engine.eval(new java.io.FileReader(args[0]));
}
 
Example 13
Source File: StringUtil.java    From qaf with MIT License 5 votes vote down vote up
/**
 * 
 * @param expression
 * @param context
 * @return
 * @throws ScriptException
 */
@SuppressWarnings("unchecked")
public static <T> T eval(String expression, Map<? extends String, ? extends Object> context)
		throws ScriptException {
	ScriptEngineManager engineManager = new ScriptEngineManager();
	ScriptEngine jsEngine = engineManager.getEngineByName("JavaScript");
	jsEngine.getBindings(ScriptContext.ENGINE_SCOPE).putAll(context);
	return (T) jsEngine.eval(expression);
}
 
Example 14
Source File: InvocableTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void invokeMethodTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        e.eval("var Example = function() { this.hello = function() { return 'Hello World!'; };}; myExample = new Example();");
        final Object obj = e.get("myExample");
        final Object res = ((Invocable) e).invokeMethod(obj, "hello");
        assertEquals(res, "Hello World!");
    } catch (final Exception exp) {
        exp.printStackTrace();
        fail(exp.getMessage());
    }
}
 
Example 15
Source File: ScriptObjectMirrorTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void mirrorNewObjectGlobalFunctionTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final ScriptEngine e2 = m.getEngineByName("nashorn");

    e.eval("function func() {}");
    e2.put("foo", e.get("func"));
    final ScriptObjectMirror e2global = (ScriptObjectMirror)e2.eval("this");
    final Object newObj = ((ScriptObjectMirror)e2global.getMember("foo")).newObject();
    assertTrue(newObj instanceof ScriptObjectMirror);
}
 
Example 16
Source File: ScriptEngineTest.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void typeErrorForGlobalThisCallTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    try {
        e.eval("try { this.foo() } catch(e) { if (! (e instanceof TypeError)) throw 'no type error' }");
    } catch (final Exception exp) {
        exp.printStackTrace();
        fail(exp.getMessage());
    }
}
 
Example 17
Source File: GraalEnginesTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Test
public void accessPolyglotBindings() throws Exception {
    ScriptEngineManager man = Scripting.createManager();
    ScriptEngine js = man.getEngineByName("GraalVM:js");
    ScriptEngine python = man.getEngineByName("GraalVM:python");

    List<Integer> scopes = js.getContext().getScopes();
    assertEquals(1, scopes.size());
    assertEquals(ScriptContext.GLOBAL_SCOPE, scopes.get(0).intValue());

    Bindings bindings = js.getBindings(ScriptContext.GLOBAL_SCOPE);
    bindings.put("x", 42);

    js.eval("\n"
        + "var x = Polyglot.import('x');\n"
        + "Polyglot.export('y', x);\n"
        + ""
    );

    Object y = python.eval("\n"
        + "import polyglot;\n"
        + "polyglot.import_value('y')"
    );

    assertTrue("Expecting number, but was: " + y, y instanceof Number);
    assertEquals(42, ((Number)y).intValue());
}
 
Example 18
Source File: MainPanel.java    From java-swing-tips with MIT License 5 votes vote down vote up
private static ScriptEngine createEngine() {
  ScriptEngineManager manager = new ScriptEngineManager();
  ScriptEngine engine = manager.getEngineByName("JavaScript");
  URL url = MainPanel.class.getResource("prettify.js");
  try (Reader r = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8))) {
    engine.eval("var window={}, navigator=null;");
    engine.eval(r);
  } catch (IOException | ScriptException ex) {
    ex.printStackTrace();
    Toolkit.getDefaultToolkit().beep();
  }
  return engine;
}
 
Example 19
Source File: ScopeTest.java    From jdk8u_nashorn with GNU General Public License v2.0 5 votes vote down vote up
@Test
public static void contextOverwriteTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final Bindings b = new SimpleBindings();
    b.put("context", "hello");
    b.put("foo", 32);
    final ScriptContext newCtxt = new SimpleScriptContext();
    newCtxt.setBindings(b, ScriptContext.ENGINE_SCOPE);
    e.setContext(newCtxt);
    assertEquals(e.eval("context"), "hello");
    assertEquals(((Number)e.eval("foo")).intValue(), 32);
}
 
Example 20
Source File: ScriptEngineTest.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void factoryTests() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    assertNotNull(e);

    final ScriptEngineFactory fac = e.getFactory();

    assertEquals(fac.getLanguageName(), "ECMAScript");
    assertEquals(fac.getParameter(ScriptEngine.NAME), "javascript");
    assertEquals(fac.getLanguageVersion(), "ECMA - 262 Edition 5.1");
    assertEquals(fac.getEngineName(), "Oracle Nashorn");
    assertEquals(fac.getOutputStatement("context"), "print(context)");
    assertEquals(fac.getProgram("print('hello')", "print('world')"), "print('hello');print('world');");
    assertEquals(fac.getParameter(ScriptEngine.NAME), "javascript");

    boolean seenJS = false;
    for (final String ext : fac.getExtensions()) {
        if (ext.equals("js")) {
            seenJS = true;
        }
    }

    assertEquals(seenJS, true);
    final String str = fac.getMethodCallSyntax("obj", "foo", "x");
    assertEquals(str, "obj.foo(x)");

    boolean seenNashorn = false, seenJavaScript = false, seenECMAScript = false;
    for (final String name : fac.getNames()) {
        switch (name) {
            case "nashorn": seenNashorn = true; break;
            case "javascript": seenJavaScript = true; break;
            case "ECMAScript": seenECMAScript = true; break;
        default:
            break;
        }
    }

    assertTrue(seenNashorn);
    assertTrue(seenJavaScript);
    assertTrue(seenECMAScript);

    boolean seenAppJS = false, seenAppECMA = false, seenTextJS = false, seenTextECMA = false;
    for (final String mime : fac.getMimeTypes()) {
        switch (mime) {
            case "application/javascript": seenAppJS = true; break;
            case "application/ecmascript": seenAppECMA = true; break;
            case "text/javascript": seenTextJS = true; break;
            case "text/ecmascript": seenTextECMA = true; break;
        default:
            break;
        }
    }

    assertTrue(seenAppJS);
    assertTrue(seenAppECMA);
    assertTrue(seenTextJS);
    assertTrue(seenTextECMA);
}