Java Code Examples for jdk.nashorn.api.scripting.NashornScriptEngineFactory#getScriptEngine()

The following examples show how to use jdk.nashorn.api.scripting.NashornScriptEngineFactory#getScriptEngine() . 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: ClassFilterTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public void runExternalJsTest() {
    final String[] paths = new String[]{
            "test/script/basic/compile-octane.js",
            "test/script/basic/jquery.js",
            "test/script/basic/prototype.js",
            "test/script/basic/runsunspider.js",
            "test/script/basic/underscore.js",
            "test/script/basic/yui.js",
            "test/script/basic/run-octane.js"
    };
    final NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
    for (final String path : paths) {
        final ScriptEngine engine = factory.getScriptEngine(new String[]{"-scripting"}, getClass().getClassLoader(), getClassFilter());
        try {
            engine.eval(new URLReader(new File(path).toURI().toURL()));
        } catch (final Exception e) {
            fail("Script " + path + " fails with exception :" + e.getMessage());
        }
    }
}
 
Example 2
Source File: CodeStoreAndPathTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void pathHandlingTest() {
    System.setProperty("nashorn.persistent.code.cache", codeCache);
    final NashornScriptEngineFactory fac = new NashornScriptEngineFactory();

    fac.getScriptEngine(ENGINE_OPTIONS_NOOPT);

    final Path expectedCodeCachePath = FileSystems.getDefault().getPath(oldUserDir + File.separator + codeCache);
    final Path actualCodeCachePath = FileSystems.getDefault().getPath(System.getProperty(
                        "nashorn.persistent.code.cache")).toAbsolutePath();
    // Check that nashorn code cache is created in current working directory
    assertEquals(actualCodeCachePath, expectedCodeCachePath);
    // Check that code cache dir exists and it's not empty
    final File file = new File(actualCodeCachePath.toUri());
    assertFalse(!file.isDirectory(), "No code cache directory was created!");
    assertFalse(file.list().length == 0, "Code cache directory is empty!");
}
 
Example 3
Source File: TrustedScriptEngineTest.java    From TencentKona-8 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 4
Source File: ClassFilterTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public void runExternalJsTest() {
    final String[] paths = new String[]{
            "test/script/basic/compile-octane.js",
            "test/script/basic/jquery.js",
            "test/script/basic/prototype.js",
            "test/script/basic/runsunspider.js",
            "test/script/basic/underscore.js",
            "test/script/basic/yui.js",
            "test/script/basic/run-octane.js"
    };
    final NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
    for (final String path : paths) {
        final ScriptEngine engine = factory.getScriptEngine(new String[]{"-scripting"}, getClass().getClassLoader(), getClassFilter());
        try {
            engine.eval(new URLReader(new File(path).toURI().toURL()));
        } catch (final Exception e) {
            fail("Script " + path + " fails with exception :" + e.getMessage());
        }
    }
}
 
Example 5
Source File: TrustedScriptEngineTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@Test
/**
 * Test that we can use same script name in repeated evals with --loader-per-compile=false
 * We used to get "class redefinition error" as name was derived from script name.
 */
public void noLoaderPerCompilerWithSameNameTest() {
    final ScriptEngineManager sm = new ScriptEngineManager();
    for (final ScriptEngineFactory fac : sm.getEngineFactories()) {
        if (fac instanceof NashornScriptEngineFactory) {
            final NashornScriptEngineFactory nfac = (NashornScriptEngineFactory)fac;
            final String[] options = new String[] { "--loader-per-compile=false" };
            final ScriptEngine e = nfac.getScriptEngine(options);
            e.put(ScriptEngine.FILENAME, "test.js");
            try {
                e.eval("2 + 3");
                e.eval("4 + 4");
            } catch (final ScriptException se) {
                se.printStackTrace();
                fail(se.getMessage());
            }
            return;
        }
    }
    fail("Cannot find nashorn factory!");
}
 
Example 6
Source File: TrustedScriptEngineTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void factoryOptionsTest() {
    final ScriptEngineManager sm = new ScriptEngineManager();
    for (final ScriptEngineFactory fac : sm.getEngineFactories()) {
        if (fac instanceof NashornScriptEngineFactory) {
            final NashornScriptEngineFactory nfac = (NashornScriptEngineFactory)fac;
            // specify --no-syntax-extensions flag
            final String[] options = new String[] { "--no-syntax-extensions" };
            final ScriptEngine e = nfac.getScriptEngine(options);
            try {
                // try nashorn specific extension
                e.eval("var f = funtion(x) 2*x;");
                fail("should have thrown exception!");
            } catch (final Exception ex) {
                //empty
            }
            return;
        }
    }

    fail("Cannot find nashorn factory!");
}
 
Example 7
Source File: ScriptEngineSecurityTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void nashornConfigSecurityTest() {
    if (System.getSecurityManager() == null) {
        // pass vacuously
        return;
    }

    final NashornScriptEngineFactory fac = new NashornScriptEngineFactory();
    try {
        fac.getScriptEngine(new ClassFilter() {
           @Override
           public boolean exposeToScripts(final String name) {
               return true;
           }
        });
        fail("SecurityException should have been thrown");
    } catch (final SecurityException e) {
        //empty
    }
}
 
Example 8
Source File: CodeStoreAndPathTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void changeUserDirTest() throws ScriptException, IOException {
    System.setProperty("nashorn.persistent.code.cache", codeCache);
    final NashornScriptEngineFactory fac = new NashornScriptEngineFactory();
    final ScriptEngine e = fac.getScriptEngine(ENGINE_OPTIONS_NOOPT);
    final Path codeCachePath = getCodeCachePath(false);
    final String newUserDir = "build/newUserDir";
    // Now changing current working directory
    System.setProperty("user.dir", System.getProperty("user.dir") + File.separator + newUserDir);
    try {
        // Check that a new compiled script is stored in existing code cache
        e.eval(code1);
        final DirectoryStream<Path> stream = Files.newDirectoryStream(codeCachePath);
        checkCompiledScripts(stream, 1);
        // Setting to default current working dir
    } finally {
        System.setProperty("user.dir", oldUserDir);
    }
}
 
Example 9
Source File: TrustedScriptEngineTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@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"));
}
 
Example 10
Source File: TrustedScriptEngineTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void factoryClassLoaderTest() {
    final ScriptEngineManager sm = new ScriptEngineManager();
    for (final ScriptEngineFactory fac : sm.getEngineFactories()) {
        if (fac instanceof NashornScriptEngineFactory) {
            final NashornScriptEngineFactory nfac = (NashornScriptEngineFactory)fac;
            final MyClassLoader loader = new MyClassLoader();
            // set the classloader as app class loader
            final ScriptEngine e = nfac.getScriptEngine(loader);
            try {
                e.eval("Packages.foo");
                // check that the class loader was attempted
                assertTrue(loader.reached(), "did not reach class loader!");
            } catch (final ScriptException se) {
                se.printStackTrace();
                fail(se.getMessage());
            }
            return;
        }
    }

    fail("Cannot find nashorn factory!");
}
 
Example 11
Source File: LexicalBindingTest.java    From TencentKona-8 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 12
Source File: TrustedScriptEngineTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void factoryOptionsTest() {
    final ScriptEngineManager sm = new ScriptEngineManager();
    for (final ScriptEngineFactory fac : sm.getEngineFactories()) {
        if (fac instanceof NashornScriptEngineFactory) {
            final NashornScriptEngineFactory nfac = (NashornScriptEngineFactory)fac;
            // specify --no-syntax-extensions flag
            final String[] options = new String[] { "--no-syntax-extensions" };
            final ScriptEngine e = nfac.getScriptEngine(options);
            try {
                // try nashorn specific extension
                e.eval("var f = funtion(x) 2*x;");
                fail("should have thrown exception!");
            } catch (final Exception ex) {
                //empty
            }
            return;
        }
    }

    fail("Cannot find nashorn factory!");
}
 
Example 13
Source File: TrustedScriptEngineTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void nullClassFilterTest2() {
    final NashornScriptEngineFactory fac = new NashornScriptEngineFactory();
    try {
        fac.getScriptEngine(new String[0], null, null);
        fail("should have thrown NPE");
    } catch (final NullPointerException e) {
        //empty
    }
}
 
Example 14
Source File: TrustedScriptEngineTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void nullArgsTest2() {
    final NashornScriptEngineFactory fac = new NashornScriptEngineFactory();
    try {
        fac.getScriptEngine(null, null, new ClassFilter() {
            @Override
            public boolean exposeToScripts(final String name) {
                return true;
            }
        });
        fail("should have thrown NPE");
    } catch (final NullPointerException e) {
        //empty
    }
}
 
Example 15
Source File: TrustedScriptEngineTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void nashornSwallowsConstKeyword() throws Exception {
    final NashornScriptEngineFactory f = new NashornScriptEngineFactory();
    final String[] args = new String[] { "--const-as-var" };
    final ScriptEngine engine = f.getScriptEngine(args);

    final Object ret = engine.eval(""
        + "(function() {\n"
        + "  const x = 10;\n"
        + "  return x;\n"
        + "})();"
    );
    assertEquals(ret, 10, "Parsed and executed OK");
}
 
Example 16
Source File: CodeStoreAndPathTest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void codeCacheTest() throws ScriptException, IOException {
    System.setProperty("nashorn.persistent.code.cache", codeCache);
    final NashornScriptEngineFactory fac = new NashornScriptEngineFactory();
    final ScriptEngine e = fac.getScriptEngine(ENGINE_OPTIONS_NOOPT);
    final Path codeCachePath = getCodeCachePath(false);
    e.eval(code1);
    e.eval(code2);
    e.eval(code3);// less than minimum size for storing
    // adding code1 and code2.
    final DirectoryStream<Path> stream = Files.newDirectoryStream(codeCachePath);
    checkCompiledScripts(stream, 2);
}
 
Example 17
Source File: TrustedScriptEngineTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void nullArgsTest() {
    final NashornScriptEngineFactory fac = new NashornScriptEngineFactory();
    try {
        fac.getScriptEngine((String[])null);
        fail("should have thrown NPE");
    } catch (final NullPointerException e) {
        //empty
    }
}
 
Example 18
Source File: CodeStoreAndPathTest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void codeCacheTestOpt() throws ScriptException, IOException {
    System.setProperty("nashorn.persistent.code.cache", codeCache);
    final NashornScriptEngineFactory fac = new NashornScriptEngineFactory();
    final ScriptEngine e = fac.getScriptEngine(ENGINE_OPTIONS_OPT);
    final Path codeCachePath = getCodeCachePath(true);
    e.eval(code1);
    e.eval(code2);
    e.eval(code3);// less than minimum size for storing
    // adding code1 and code2.
    final DirectoryStream<Path> stream = Files.newDirectoryStream(codeCachePath);
    checkCompiledScripts(stream, 4);
}
 
Example 19
Source File: ClassFilterTest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void noJavaOptionTest() {
    final NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
    final ScriptEngine engine = factory.getScriptEngine(new String[]{"--no-java"}, getClass().getClassLoader(), getClassFilter());
    try {
        engine.eval("var str = Java.type('java.lang.String');");
        fail("TypeError should have been thrown");
    } catch (final ScriptException e) {
        //emtpy
    }
}
 
Example 20
Source File: TrustedScriptEngineTest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void nullClassFilterTest2() {
    final NashornScriptEngineFactory fac = new NashornScriptEngineFactory();
    try {
        fac.getScriptEngine(new String[0], null, null);
        fail("should have thrown NPE");
    } catch (final NullPointerException e) {
        //empty
    }
}