本文整理匯總了Java中jdk.nashorn.api.scripting.NashornScriptEngineFactory.getScriptEngine方法的典型用法代碼示例。如果您正苦於以下問題:Java NashornScriptEngineFactory.getScriptEngine方法的具體用法?Java NashornScriptEngineFactory.getScriptEngine怎麽用?Java NashornScriptEngineFactory.getScriptEngine使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類jdk.nashorn.api.scripting.NashornScriptEngineFactory
的用法示例。
在下文中一共展示了NashornScriptEngineFactory.getScriptEngine方法的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);
}
示例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;
}
示例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
}
}
示例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
}
}
示例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);
}
}
示例6: 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);
}
示例7: 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!");
}
示例8: 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());
}
}
}
示例9: 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!");
}
示例10: 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!");
}
示例11: 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!");
}
示例12: noLoaderPerCompilerWithSameNameTest
import jdk.nashorn.api.scripting.NashornScriptEngineFactory; //導入方法依賴的package包/類
@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!");
}
示例13: evalFileNameWithSpecialCharsTest
import jdk.nashorn.api.scripting.NashornScriptEngineFactory; //導入方法依賴的package包/類
@Test
public void evalFileNameWithSpecialCharsTest() throws ScriptException {
final NashornScriptEngineFactory fac = new NashornScriptEngineFactory();
final ScriptEngine engine = fac.getScriptEngine(new String[] { "--verify-code=true" });
final ScriptContext ctxt = new SimpleScriptContext();
// use file name with "dangerous" chars.
ctxt.setAttribute(ScriptEngine.FILENAME, "<myscript>", ScriptContext.ENGINE_SCOPE);
engine.eval("var a = 3;");
ctxt.setAttribute(ScriptEngine.FILENAME, "[myscript]", ScriptContext.ENGINE_SCOPE);
engine.eval("var h = 'hello';");
ctxt.setAttribute(ScriptEngine.FILENAME, ";/\\$.", ScriptContext.ENGINE_SCOPE);
engine.eval("var foo = 'world';");
// name used by jjs shell tool for the interactive mode
ctxt.setAttribute(ScriptEngine.FILENAME, "<shell>", ScriptContext.ENGINE_SCOPE);
engine.eval("var foo = 'world';");
}
示例14: classFilterTest2
import jdk.nashorn.api.scripting.NashornScriptEngineFactory; //導入方法依賴的package包/類
@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");
}
}
}
示例15: 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());
assertFalse(!file.isDirectory(), "No code cache directory was created!");
assertFalse(file.list().length == 0, "Code cache directory is empty!");
}