本文整理汇总了Java中javax.script.ScriptEngine类的典型用法代码示例。如果您正苦于以下问题:Java ScriptEngine类的具体用法?Java ScriptEngine怎么用?Java ScriptEngine使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ScriptEngine类属于javax.script包,在下文中一共展示了ScriptEngine类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: executeJs
import javax.script.ScriptEngine; //导入依赖的package包/类
public Object executeJs(String js,@Nullable String funcName,Object... args){
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("javascript");
try {
Object res=engine.eval(js);
if(StringUtils.isNotBlank(funcName)){
if (engine instanceof Invocable) {
Invocable invoke = (Invocable) engine;
res = invoke.invokeFunction(funcName, args);
}
}
return res;
} catch (Exception e) {
log.error("",e);
}
return null;
}
示例2: main
import javax.script.ScriptEngine; //导入依赖的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);
}
示例3: main
import javax.script.ScriptEngine; //导入依赖的package包/类
public static void main(String[] args) {
ScriptEngineManager engineManager = new ScriptEngineManager();
ScriptEngine engine = engineManager.getEngineByName("javascript");
try {
// UserVO user = new UserVO();
// user.setId(1000);
// user.setUsername("xingtianyu");
// Map<String,Object> usermap = new HashMap<>();
// usermap.put("id",user.getId());
// usermap.put("username",user.getUsername());
JSContext context = new JSContext();
engine.put(JSContext.CONTEXT,context.getCtx());
engine.eval(new FileReader("/home/code4j/IDEAWorkspace/myutils/myutils-slardar/src/main/resources/mapper/usermapper.js"));
Invocable func = (Invocable)engine;
// Map<String,Object> resultMap = (Map<String, Object>) func.invokeFunction("findUserByCondition",usermap);
// Map<String,Object> paramMap = (Map<String, Object>) resultMap.get("param");
// System.out.println(resultMap.get("sql"));
// System.out.println(paramMap.get("1"));
} catch (Exception e) {
e.printStackTrace();
}
}
示例4: invokeFunctionWithCustomScriptContextTest
import javax.script.ScriptEngine; //导入依赖的package包/类
@Test
public void invokeFunctionWithCustomScriptContextTest() throws Exception {
final ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
// create an engine and a ScriptContext, but don't set it as default
final ScriptContext scriptContext = new SimpleScriptContext();
// Set some value in the context
scriptContext.setAttribute("myString", "foo", ScriptContext.ENGINE_SCOPE);
// Evaluate script with custom context and get back a function
final String script = "function (c) { return myString.indexOf(c); }";
final CompiledScript compiledScript = ((Compilable)engine).compile(script);
final Object func = compiledScript.eval(scriptContext);
// Invoked function should be able to see context it was evaluated with
final Object result = ((Invocable) engine).invokeMethod(func, "call", func, "o", null);
assertTrue(((Number)result).intValue() == 1);
}
示例5: testJS
import javax.script.ScriptEngine; //导入依赖的package包/类
@Test
public void testJS() {
// https://stackoverflow.com/questions/22492641/java8-js-nashorn-convert-array-to-java-array
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("javascript");
try {
engine.put("line", "刘长炯 微信号weblogic (10.3.2) [46a5432f8fdea99a6186a927e8da5db7a51854ac]");
// engine.put("regex", )
String regex = "/(.*?) \\((.*?)\\) \\[(.*?)\\]/";
String[] value = (String[])engine.eval("Java.to(line.match(" + regex + "),\"java.lang.String[]\" );");
System.out.println(value.length);
System.out.println(value[1]);
String[] result = {"刘长炯 微信号weblogic (10.3.2) [46a5432f8fdea99a6186a927e8da5db7a51854ac]",
"刘长炯 微信号weblogic", "10.3.2", "46a5432f8fdea99a6186a927e8da5db7a51854ac"};
Assert.assertArrayEquals("result shold match", result, value);
// Collection<Object> val = value.values();
// if(value.isArray()) {
// System.out.println(value.getMember("1"));
// }
} catch (ScriptException e) {
e.printStackTrace();
}
}
示例6: invokeMethodMixEnginesTest
import javax.script.ScriptEngine; //导入依赖的package包/类
@Test
/**
* Check that calling method on mirror created by another engine results in
* IllegalArgumentException.
*/
public void invokeMethodMixEnginesTest() {
final ScriptEngineManager m = new ScriptEngineManager();
final ScriptEngine engine1 = m.getEngineByName("nashorn");
final ScriptEngine engine2 = m.getEngineByName("nashorn");
try {
final Object obj = engine1.eval("({ run: function() {} })");
// pass object from engine1 to engine2 as 'thiz' for invokeMethod
((Invocable) engine2).invokeMethod(obj, "run");
fail("should have thrown IllegalArgumentException");
} catch (final Exception exp) {
if (!(exp instanceof IllegalArgumentException)) {
exp.printStackTrace();
fail(exp.getMessage());
}
}
}
示例7: ScriptRouter
import javax.script.ScriptEngine; //导入依赖的package包/类
public ScriptRouter(URL url) {
this.url = url;
String type = url.getParameter(Constants.TYPE_KEY);
this.priority = url.getParameter(Constants.PRIORITY_KEY, 0);
String rule = url.getParameterAndDecoded(Constants.RULE_KEY);
if (type == null || type.length() == 0){
type = Constants.DEFAULT_SCRIPT_TYPE_KEY;
}
if (rule == null || rule.length() == 0){
throw new IllegalStateException(new IllegalStateException("route rule can not be empty. rule:" + rule));
}
ScriptEngine engine = engines.get(type);
if (engine == null){
engine = new ScriptEngineManager().getEngineByName(type);
if (engine == null) {
throw new IllegalStateException(new IllegalStateException("Unsupported route rule type: " + type + ", rule: " + rule));
}
engines.put(type, engine);
}
this.engine = engine;
this.rule = rule;
}
示例8: getParameter
import javax.script.ScriptEngine; //导入依赖的package包/类
@Override
public Object getParameter(String key) {
switch(key) {
case ScriptEngine.ENGINE:
return getEngineName();
case ScriptEngine.ENGINE_VERSION:
return getEngineVersion();
case ScriptEngine.LANGUAGE:
return getLanguageName();
case ScriptEngine.LANGUAGE_VERSION:
return getLanguageVersion();
case ScriptEngine.NAME:
return getNames().get(0);
default:
return null;
}
}
示例9: load
import javax.script.ScriptEngine; //导入依赖的package包/类
protected static ScriptId load(Plugin plugin, String id, String script, String ext) throws ScriptException {
ScriptManager manager = scripts();
final String engineName = manager.getExtensionsToEngineName().get(ext);
if (engineName == null)
throw new IllegalArgumentException("Cannot find engine for \"" + ext + "\"");
ScriptEngine engine;
{//Load the engine
final Thread currentThread = Thread.currentThread();
final ClassLoader oldLoader = currentThread.getContextClassLoader();
try {
currentThread.setContextClassLoader(manager.getClassLoader());
engine = manager.getEngineManager().getEngineByName(engineName);
} finally {
currentThread.setContextClassLoader(oldLoader);
}
}
if (engine == null)
throw new IllegalStateException("Cannot find engine \"" + engineName + "\"");
return new ScriptId(plugin, id, Script.of(engine, script));
}
示例10: argumentsWithTest
import javax.script.ScriptEngine; //导入依赖的package包/类
@Test
public void argumentsWithTest() {
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("var imports = new JavaImporter(java.io); " +
" with(imports) { arguments[0] }");
final Object arg1 = e.eval("var imports = new JavaImporter(java.util, java.io); " +
" with(imports) { arguments[1] }");
assertEquals(args[0], arg0);
assertEquals(args[1], arg1);
} catch (final Exception exp) {
exp.printStackTrace();
fail(exp.getMessage());
}
}
示例11: invokeMethodMissingTest
import javax.script.ScriptEngine; //导入依赖的package包/类
@Test
/**
* Check that invokeMethod throws NoSuchMethodException on missing method.
*/
public void invokeMethodMissingTest() {
final ScriptEngineManager m = new ScriptEngineManager();
final ScriptEngine e = m.getEngineByName("nashorn");
try {
final Object obj = e.eval("({})");
((Invocable) e).invokeMethod(obj, "nonExistentMethod");
fail("should have thrown NoSuchMethodException");
} catch (final Exception exp) {
if (!(exp instanceof NoSuchMethodException)) {
exp.printStackTrace();
fail(exp.getMessage());
}
}
}
示例12: argumentsTest
import javax.script.ScriptEngine; //导入依赖的package包/类
@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());
}
}
示例13: isJsFunctionAvailable
import javax.script.ScriptEngine; //导入依赖的package包/类
private boolean isJsFunctionAvailable(ScriptEngine eng, String functionName, boolean doDeepTest) {
// We want to test if the function is there, but without actually
// invoking it.
Object obj = eng.get(functionName);
if (!doDeepTest && obj != null) {
// Shallow test. We've established that there's
// "something" in the ENGINE_SCOPE with a name like
// functionName, and we *hope* it is a function, but we really don't
// know, therefore we call it a shallow test.
return true;
}
// For Nashorn post JDK8u40 we can do even deeper validation
// using the ScriptObjectMirror class. This will not work for Rhino.
if (doDeepTest && obj != null) {
if (obj instanceof ScriptObjectMirror) {
ScriptObjectMirror som = (ScriptObjectMirror) obj;
if (som.isFunction()) {
return true;
}
}
}
return false;
}
示例14: mapScriptObjectMirrorCallsiteTest
import javax.script.ScriptEngine; //导入依赖的package包/类
@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));
}
示例15: globalPerEngineTest
import javax.script.ScriptEngine; //导入依赖的package包/类
@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"));
}