下面列出了javax.script.Invocable#invokeFunction ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Executes a compiled script and returns the result.
*
* @param script Compiled script.
* @param functionName Optional function or method to invoke.
* @param scriptContext Script execution context.
* @return The script result.
* @throws IllegalArgumentException
*/
public static Object executeScript(CompiledScript script, String functionName, ScriptContext scriptContext, Object[] args) throws ScriptException, NoSuchMethodException {
Assert.notNull("script", script, "scriptContext", scriptContext);
Object result = script.eval(scriptContext);
if (UtilValidate.isNotEmpty(functionName)) {
if (Debug.verboseOn()) {
Debug.logVerbose("Invoking function/method " + functionName, module);
}
ScriptEngine engine = script.getEngine();
try {
Invocable invocableEngine = (Invocable) engine;
result = invocableEngine.invokeFunction(functionName, args == null ? EMPTY_ARGS : args);
} catch (ClassCastException e) {
throw new ScriptException("Script engine " + engine.getClass().getName() + " does not support function/method invocations");
}
}
return result;
}
public static void main(final String[] args) throws Exception {
final ScriptEngineManager manager = new ScriptEngineManager();
final ScriptEngine engine = manager.getEngineByName("nashorn");
// JavaScript code in a String
final String script = "function hello(name) { print('Hello, ' + name); }";
// evaluate script
engine.eval(script);
// javax.script.Invocable is an optional interface.
// Check whether your script engine implements or not!
// Note that the JavaScript engine implements Invocable interface.
final Invocable inv = (Invocable) engine;
// invoke the global function named "hello"
inv.invokeFunction("hello", "Scripting!!" );
}
@Override
public void loadScript(String engineIdentifier, InputStreamReader scriptData) {
ScriptEngineContainer container = loadedScriptEngineInstances.get(engineIdentifier);
if (container == null) {
logger.error("Could not load script, as no ScriptEngine has been created");
} else {
ScriptEngine engine = container.getScriptEngine();
try {
engine.eval(scriptData);
if (engine instanceof Invocable) {
Invocable inv = (Invocable) engine;
try {
inv.invokeFunction("scriptLoaded", engineIdentifier);
} catch (NoSuchMethodException e) {
logger.trace("scriptLoaded() is not defined in the script: {}", engineIdentifier);
}
} else {
logger.trace("ScriptEngine does not support Invocable interface");
}
} catch (Exception ex) {
logger.error("Error during evaluation of script '{}': {}", engineIdentifier, ex.getMessage());
}
}
}
@Override
public boolean match(List<GrpcURL> providerUrls) {
String rule = super.getRule();
try {
engine.eval(super.getRule());
Invocable invocable = (Invocable) engine;
GrpcURL refUrl = super.getRefUrl();
Object obj = invocable.invokeFunction("route", refUrl, providerUrls);
if (obj instanceof Boolean) {
return (Boolean) obj;
} else {
return true;
}
} catch (ScriptException | NoSuchMethodException e) {
log.error("route error , rule has been ignored. rule: " + rule + ", url: " + providerUrls, e);
return true;
}
}
private static String signDecipher(final String signature,
final String playercode) {
try {
final ScriptEngine engine = new ScriptEngineManager()
.getEngineByName("nashorn");
engine.eval(new FileReader("data/scripts/decrypt.js"));
final Invocable invocable = (Invocable) engine;
final Object result = invocable.invokeFunction("getWorkingVideo",
signature, playercode);
return (String) result;
} catch (ScriptException | FileNotFoundException
| NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "error";
}
/**
* Uses the user provided query to process and return a JSON columnar format of the data.
*
* @param data The data from the REST call.
* @param function The function name to invoke.
* @param query The Query object being run.
* @return The String JSON response of the call, null if exception (query is failed).
*/
String convertToColumnarJSON(String data, String function, Query query) {
try {
log.info("Evaluating query using Javascript function: {}\n{}", function, query.value);
evaluator.eval(query.value);
Invocable invocable = (Invocable) evaluator;
String columnarJSON = (String) invocable.invokeFunction(function, data);
log.info("Processed response using query into JSON: {}", columnarJSON);
return columnarJSON;
} catch (ScriptException se) {
log.error("Exception while processing input Javascript", se);
query.setFailure(se.toString());
query.addMessage(se.toString());
} catch (NoSuchMethodException nsme) {
log.error("Method {} not found in {}\n{}", function, query.value, nsme);
query.setFailure(nsme.toString());
}
return null;
}
public void act(MapleClient c, MapleReactor reactor) {
try {
Invocable iv = getInvocable("reactors/" + reactor.getReactorId() + ".js", c);
if (iv == null) {
if (c.getPlayer().isShowPacket()) {
c.getPlayer().dropMessage(5, "未找到 反应堆 文件中的 " + reactor.getReactorId() + ".js 文件.");
}
FileoutputUtil.log(FileoutputUtil.Reactor_ScriptEx_Log, "未找到 反应堆 文件中的 " + reactor.getReactorId() + ".js 文件.");
return;
}
ScriptEngine scriptengine = (ScriptEngine) iv;
ReactorActionManager rm = new ReactorActionManager(c, reactor);
scriptengine.put("rm", rm);
iv.invokeFunction("act", new Object[0]);
} catch (ScriptException | NoSuchMethodException e) {
System.err.println("执行反应堆文件出错 反应堆ID: " + reactor.getReactorId() + ", 反应堆名称: " + reactor.getName() + " 错误信息: " + e);
FileoutputUtil.log(FileoutputUtil.Reactor_ScriptEx_Log, "执行反应堆文件出错 反应堆ID: " + reactor.getReactorId() + ", 反应堆名称: " + reactor.getName() + " 错误信息: " + e);
}
}
@Test
public void checkMirrorToObject() throws Exception {
final ScriptEngineManager engineManager = new ScriptEngineManager();
final ScriptEngine engine = engineManager.getEngineByName("nashorn");
final Invocable invocable = (Invocable)engine;
engine.eval("function test1(arg) { return { arg: arg }; }");
engine.eval("function test2(arg) { return arg; }");
engine.eval("function compare(arg1, arg2) { return arg1 == arg2; }");
final Map<String, Object> map = new HashMap<>();
map.put("option", true);
final MirrorCheckExample example = invocable.getInterface(MirrorCheckExample.class);
final Object value1 = invocable.invokeFunction("test1", map);
final Object value2 = example.test1(map);
final Object value3 = invocable.invokeFunction("test2", value2);
final Object value4 = example.test2(value2);
// check that Object type argument receives a ScriptObjectMirror
// when ScriptObject is passed
assertEquals(ScriptObjectMirror.class, value1.getClass());
assertEquals(ScriptObjectMirror.class, value2.getClass());
assertEquals(ScriptObjectMirror.class, value3.getClass());
assertEquals(ScriptObjectMirror.class, value4.getClass());
assertTrue((boolean)invocable.invokeFunction("compare", value1, value1));
assertTrue(example.compare(value1, value1));
assertTrue((boolean)invocable.invokeFunction("compare", value3, value4));
assertTrue(example.compare(value3, value4));
}
/**
* Call the script function of given name passing the
* given arguments.
*/
public Object call(String name, Object[] args) {
Invocable invocable = (Invocable)engine;
try {
return invocable.invokeFunction(name, args);
} catch (RuntimeException re) {
throw re;
} catch (Exception exp) {
throw new RuntimeException(exp);
}
}
/**
* Call the script function of given name passing the
* given arguments.
*/
public Object call(String name, Object[] args) {
Invocable invocable = (Invocable)engine;
try {
return invocable.invokeFunction(name, args);
} catch (RuntimeException re) {
throw re;
} catch (Exception exp) {
throw new RuntimeException(exp);
}
}
public void start(MapleClient c, int npcId, String npcMode) {
try {
if (c.getPlayer().isAdmin()) {
c.getPlayer().dropMessage(5, "对话NPC:" + npcId + " 模式:" + npcMode);
}
if (this.cms.containsKey(c)) {
dispose(c);
return;
}
Invocable iv;
if (npcMode == null) {
iv = getInvocable("npc/" + npcId + ".js", c, true);
} else {
iv = getInvocable("特殊/" + npcMode + ".js", c, true);
}
ScriptEngine scriptengine = (ScriptEngine) iv;
NPCConversationManager cm = new NPCConversationManager(c, npcId, npcMode, ScriptType.NPC, iv);
if ((iv == null) || (getInstance() == null)) {
if (iv == null) {
c.getPlayer().dropMessage(5,"找不到NPC脚本(ID:" + npcId + "), 特殊模式(" + npcMode + "),所在地图(ID:" + c.getPlayer().getMapId() + ")");
}
dispose(c);
return;
}
this.cms.put(c, cm);
scriptengine.put("cm", cm);
c.getPlayer().setConversation(1);
c.setClickedNPC();
try {
iv.invokeFunction("start", new Object[0]);
} catch (NoSuchMethodException nsme) {
iv.invokeFunction("action", new Object[]{(byte) 1, (byte) 0, (int) (byte) 0});
}
} catch (NoSuchMethodException | ScriptException e) {
System.err.println("NPC脚本出错(ID : " + npcId + ")模式:" + npcMode + "错误内容: " + e);
FileoutputUtil.log(FileoutputUtil.ScriptEx_Log, "NPC脚本出错(ID : " + npcId + ")模式" + npcMode + ".\r\n错误信息:" + e);
dispose(c);
notice(c, npcId, npcMode);
}
}
private Object execute(MapAttribute wellKnowsAttributes) throws MetaException {
try {
SimpleBindings bindings = new SimpleBindings();
bindings.put("attributes", wellKnowsAttributes);
Invocable invocable = (Invocable)engines.getCachedEngine(javascriptPath);
return invocable.invokeFunction("create", wellKnowsAttributes);
} catch (ScriptException|NoSuchMethodException|IOException|URISyntaxException ex) {
throw new MetaException("Error executing script.", ex);
}
}
private Object evalScript(String script, Order order, Reader scriptReader)
throws ScriptException, NoSuchMethodException {
final Object result;
final ScriptEngine engine = manager.getEngineByName("JavaScript");
try {
engine.eval(scriptReader);
Invocable inv = (Invocable) engine;
result = inv.invokeFunction("isInconsistent", order);
} catch (ScriptException | NoSuchMethodException se) {
log.error("The script {} thruw up", script);
log.error("Script executing exception", se);
throw se;
}
return result;
}
public static void main(String[] args) throws Exception {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
engine.eval(new FileReader("res/nashorn1.js"));
Invocable invocable = (Invocable) engine;
Object result = invocable.invokeFunction("fun1", "Peter Parker");
System.out.println(result);
System.out.println(result.getClass());
invocable.invokeFunction("fun2", new Date());
invocable.invokeFunction("fun2", LocalDateTime.now());
invocable.invokeFunction("fun2", new Person());
}
public static void main(String[] args) throws ScriptException, NoSuchMethodException {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
engine.eval("function foo(predicate, obj) { return !!(eval(predicate)); };");
Invocable invocable = (Invocable) engine;
Person person = new Person();
person.setName("Hans");
String predicate = "obj.getLengthOfName() >= 4";
Object result = invocable.invokeFunction("foo", predicate, person);
System.out.println(result);
}
/**
* 运行一个js方法
*/
public static Object invoke(ExtensionInfo extensionInfo, Event event, Object param, boolean async) throws NoSuchMethodException, ScriptException, FileNotFoundException, InterruptedException {
//初始化js引擎
ScriptEngine engine = ExtensionUtil.buildExtensionRuntimeEngine(extensionInfo);
Invocable invocable = (Invocable) engine;
//执行resolve方法
Object result = invocable.invokeFunction(StringUtils.isEmpty(event.getMethod()) ? event.getOn() : event.getMethod(), param);
//结果为null或者异步调用直接返回
if (result == null || async) {
return result;
}
final Object[] ret = {null};
//判断是不是返回Promise对象
ScriptContext ctx = new SimpleScriptContext();
ctx.setAttribute("result", result, ScriptContext.ENGINE_SCOPE);
boolean isPromise = (boolean) engine.eval("!!result&&typeof result=='object'&&typeof result.then=='function'", ctx);
if (isPromise) {
//如果是返回的Promise则等待执行完成
CountDownLatch countDownLatch = new CountDownLatch(1);
invocable.invokeMethod(result, "then", (Function) o -> {
try {
ret[0] = o;
} catch (Exception e) {
LOGGER.error("An exception occurred while resolve()", e);
} finally {
countDownLatch.countDown();
}
return null;
});
invocable.invokeMethod(result, "catch", (Function) o -> {
countDownLatch.countDown();
return null;
});
//等待解析完成
countDownLatch.await();
} else {
ret[0] = result;
}
return ret[0];
}
public void startQuest(MapleClient c, int npcId, int questId) {
try {
if (this.qms.containsKey(c)) {
FileoutputUtil.log("脚本任务挂了!!!!");
dispose(c);
return;
}
Invocable iv = getInvocable("quests/" + questId + ".js", c, true);
FileoutputUtil.log("读取脚本任务完成!!!");
if (iv == null) {
//c.getPlayer().forceCompleteQuest(questId);
if (c.getPlayer().isShowPacket()) {
c.getPlayer().dropMessage(5, "开始任务脚本不存在 NPC:" + npcId + " Quest:" + questId);
}
dispose(c);
FileoutputUtil.log(FileoutputUtil.Quest_ScriptEx_Log, "开始任务脚本不存在 NPC:" + npcId + " Quest:" + questId);
return;
}
if (c.getPlayer().isShowPacket()) {
c.getPlayer().dropMessage(5, "开始脚本任务 NPC:" + npcId + " Quest:" + questId);
}
ScriptEngine scriptengine = (ScriptEngine) iv;
QuestActionManager qm = new QuestActionManager(c, npcId, questId, true, ScriptType.QUEST_START, iv);
this.qms.put(c, qm);
scriptengine.put("qm", qm);
c.getPlayer().setConversation(1);
c.setClickedNPC();
iv.invokeFunction("start", new Object[]{(byte) 1, (byte) 0, (int) (byte) 0});
} catch (ScriptException | NoSuchMethodException e) {
System.err.println("执行任务脚本失败 任务ID: (" + questId + ")..NPCID: " + npcId + ":" + e);
FileoutputUtil.log(FileoutputUtil.Quest_ScriptEx_Log, "执行任务脚本失败 任务ID: (" + questId + ")..NPCID: " + npcId + ". \r\n错误信息: " + e);
dispose(c);
notice(c, questId);
}
}
public static void main(String[] args) throws ScriptException, NoSuchMethodException {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
engine.eval("function foo(predicate, obj) { return !!(eval(predicate)); };");
Invocable invocable = (Invocable) engine;
Person person = new Person();
person.setName("Hans");
String predicate = "obj.getLengthOfName() >= 4";
Object result = invocable.invokeFunction("foo", predicate, person);
System.out.println(result);
}
public synchronized static String parse(String content) {
if(content == null || content.isEmpty()) return null;
try {
Invocable invocable = (Invocable) js;
Object result = invocable.invokeFunction("marked", content);
return result.toString();
} catch (ScriptException | NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
private void run(ScriptEngine engine, String script, String methodName)
throws ScriptException, NoSuchMethodException
{
// either create the functions to be called or runs the script
engine.eval(script);
if (methodName != null) {
// optional
Invocable invocableEngine = (Invocable) engine;
// call a parameterless function
invocableEngine.invokeFunction(methodName);
}
}