當前位置: 首頁>>代碼示例>>Java>>正文


Java NashornScriptEngineFactory類代碼示例

本文整理匯總了Java中jdk.nashorn.api.scripting.NashornScriptEngineFactory的典型用法代碼示例。如果您正苦於以下問題:Java NashornScriptEngineFactory類的具體用法?Java NashornScriptEngineFactory怎麽用?Java NashornScriptEngineFactory使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


NashornScriptEngineFactory類屬於jdk.nashorn.api.scripting包,在下文中一共展示了NashornScriptEngineFactory類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: main

import jdk.nashorn.api.scripting.NashornScriptEngineFactory; //導入依賴的package包/類
public static void main(String[] args) throws Exception{
    
    NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
    ScriptEngine engine = factory.getScriptEngine("--language=es6");
    
    //Javascript function
    engine.eval("function sum(a, b) { return a + b; }");
    System.out.println(engine.eval("sum(1, 2);"));

    //Template strings
    engine.eval("let name = 'Sanaulla'");
    System.out.println(engine.eval("print(`Hello Mr. ${name}`)"));

    //Set
    engine.eval("var s = new Set(); s.add(1).add(2).add(3).add(4).add(5).add(6);");
    System.out.println("Set elements");
    engine.eval("for (let e of s) { print(e); }");
    
    //Reading Javascript source
    engine.eval(new FileReader("src/embedded.nashorn/com/packt/embeddable.js"));
    int difference = (int)engine.eval("difference(1, 2);");
    System.out.println("Difference between 1, 2 is: " + difference);
}
 
開發者ID:PacktPublishing,項目名稱:Java-9-Cookbook,代碼行數:24,代碼來源:EmbeddedNashornDemo.java

示例2: createScriptEngine

import jdk.nashorn.api.scripting.NashornScriptEngineFactory; //導入依賴的package包/類
@Override
protected ScriptEngine createScriptEngine() {
    String scripEngineName = SCRIPT_ENGINE_NAME;
    // ScriptEngine result = new ScriptEngineManager().getEngineByName(scripEngineName);
    NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
    ScriptEngine result = factory.getScriptEngine("-scripting");

    Validate.isInstanceOf(Compilable.class, result, "ScriptingEngine %s doesn't implement Compilable", scripEngineName);
    Validate.isInstanceOf(Invocable.class, result, "ScriptingEngine %s doesn't implement Invocable", scripEngineName);

    PROCESSOR_CLASSES.forEach((interfaceClass, scriptClass) -> addImport(result, scriptClass, interfaceClass.getSimpleName()));
    addImport(result, NashornPlugin.class, Plugin.class.getSimpleName());

    getStandardImportClasses().forEach(cls -> addImport(result, cls));

    result.put(KnowledgeBaseConstants.VAR_ENGINE_OPERATIONS, getEngineOperations());

    eval(result, "load(\"classpath:" + INITIAL_SCRIPT + "\");");

    return result;
}
 
開發者ID:softelnet,項目名稱:sponge,代碼行數:22,代碼來源:NashornKnowledgeBaseInterpreter.java

示例3: nashornConfigSecurityTest

import jdk.nashorn.api.scripting.NashornScriptEngineFactory; //導入依賴的package包/類
@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
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:21,代碼來源:ScriptEngineSecurityTest.java

示例4: nashornConfigSecurityTest2

import jdk.nashorn.api.scripting.NashornScriptEngineFactory; //導入依賴的package包/類
@Test
public void nashornConfigSecurityTest2() {
    if (System.getSecurityManager() == null) {
        // pass vacuously
        return;
    }

    final NashornScriptEngineFactory fac = new NashornScriptEngineFactory();
    try {
        fac.getScriptEngine(new String[0], null, new ClassFilter() {
           @Override
           public boolean exposeToScripts(final String name) {
               return true;
           }
        });
        fail("SecurityException should have been thrown");
    } catch (final SecurityException e) {
        //empty
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:21,代碼來源:ScriptEngineSecurityTest.java

示例5: megamorphicPropertyReadTest

import jdk.nashorn.api.scripting.NashornScriptEngineFactory; //導入依賴的package包/類
@Test
public void megamorphicPropertyReadTest() throws ScriptException {
    final NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
    final ScriptEngine engine = factory.getScriptEngine();
    final Bindings scope = engine.getBindings(ScriptContext.ENGINE_SCOPE);
    boolean ret;

    // Why 16 is the upper limit of this loop? The default nashorn dynalink megamorphic threshold is 16.
    // See jdk.nashorn.internal.runtime.linker.Bootstrap.NASHORN_DEFAULT_UNSTABLE_RELINK_THRESHOLD
    // We do, 'eval' of the same in this loop twice. So, 16*2 = 32 times that callsite in the script
    // is exercised - much beyond the default megamorphic threshold.

    for (int i = 0; i < 16; i++) {
        scope.remove(VAR_NAME);
        ret = lookupVar(engine, VAR_NAME);
        assertFalse(ret, "Expected false in iteration " + i);
        scope.put(VAR_NAME, "foo");
        ret = lookupVar(engine, VAR_NAME);
        assertTrue(ret, "Expected true in iteration " + i);
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:22,代碼來源:ScopeTest.java

示例6: testNonWrapping

import jdk.nashorn.api.scripting.NashornScriptEngineFactory; //導入依賴的package包/類
/**
 * 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);
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:21,代碼來源:JSONCompatibleTest.java

示例7: megamorphicSingleGlobalLetTest

import jdk.nashorn.api.scripting.NashornScriptEngineFactory; //導入依賴的package包/類
/**
 * 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);
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:24,代碼來源:LexicalBindingTest.java

示例8: megamorphicInheritedGlobalLetTest

import jdk.nashorn.api.scripting.NashornScriptEngineFactory; //導入依賴的package包/類
/**
 * 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);
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:24,代碼來源:LexicalBindingTest.java

示例9: lexicalScopeTest

import jdk.nashorn.api.scripting.NashornScriptEngineFactory; //導入依賴的package包/類
/**
 * 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);
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:21,代碼來源:LexicalBindingTest.java

示例10: pathHandlingTest

import jdk.nashorn.api.scripting.NashornScriptEngineFactory; //導入依賴的package包/類
@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());
    assertTrue(file.exists(), "No code cache directory was created!");
    assertTrue(file.isDirectory(), "Code cache location is not a directory!");
    assertFalse(file.list().length == 0, "Code cache directory is empty!");
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:19,代碼來源:CodeStoreAndPathTest.java

示例11: changeUserDirTest

import jdk.nashorn.api.scripting.NashornScriptEngineFactory; //導入依賴的package包/類
@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);
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:20,代碼來源:CodeStoreAndPathTest.java

示例12: runExternalJsTest

import jdk.nashorn.api.scripting.NashornScriptEngineFactory; //導入依賴的package包/類
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());
        }
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:21,代碼來源:ClassFilterTest.java

示例13: factoryClassLoaderTest

import jdk.nashorn.api.scripting.NashornScriptEngineFactory; //導入依賴的package包/類
@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!");
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:24,代碼來源:TrustedScriptEngineTest.java

示例14: factoryOptionsTest

import jdk.nashorn.api.scripting.NashornScriptEngineFactory; //導入依賴的package包/類
@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!");
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:23,代碼來源:TrustedScriptEngineTest.java

示例15: noLoaderPerCompilerTest

import jdk.nashorn.api.scripting.NashornScriptEngineFactory; //導入依賴的package包/類
@Test
/**
 * Test repeated evals with --loader-per-compile=false
 * We used to get "class redefinition error".
 */
public void noLoaderPerCompilerTest() {
    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);
            try {
                e.eval("2 + 3");
                e.eval("4 + 4");
            } catch (final ScriptException se) {
                se.printStackTrace();
                fail(se.getMessage());
            }
            return;
        }
    }
    fail("Cannot find nashorn factory!");
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:25,代碼來源:TrustedScriptEngineTest.java


注:本文中的jdk.nashorn.api.scripting.NashornScriptEngineFactory類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。