javax.script.Invocable#invokeFunction ( )源码实例Demo

下面列出了javax.script.Invocable#invokeFunction ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: scipio-erp   文件: ScriptUtil.java
/**
 * 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;
}
 
源代码2 项目: TencentKona-8   文件: InvokeScriptFunction.java
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!!" );
}
 
源代码3 项目: openhab-core   文件: ScriptEngineManagerImpl.java
@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());
        }
    }
}
 
源代码4 项目: saluki   文件: ScriptRouter.java
@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;
  }
}
 
源代码5 项目: aurous-app   文件: YouTubeService.java
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";
}
 
源代码6 项目: validatar   文件: JSON.java
/**
 * 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;
}
 
源代码7 项目: mapleLemon   文件: ReactorScriptManager.java
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);
    }
}
 
源代码8 项目: TencentKona-8   文件: ScriptObjectMirrorTest.java
@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));
}
 
源代码9 项目: jdk8u60   文件: JSJavaScriptEngine.java
/**
 * 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);
  }
}
 
源代码10 项目: openjdk-jdk8u-backup   文件: JSJavaScriptEngine.java
/**
 * 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);
  }
}
 
源代码11 项目: mapleLemon   文件: NPCScriptManager.java
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;
}
 
源代码14 项目: java8-tutorial   文件: Nashorn1.java
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());
}
 
源代码15 项目: java8-tutorial   文件: Nashorn7.java
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);
}
 
源代码16 项目: proxyee-down   文件: ExtensionUtil.java
/**
 * 运行一个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];
}
 
源代码17 项目: mapleLemon   文件: QuestScriptManager.java
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);
    }
}
 
源代码18 项目: javacore   文件: Nashorn7.java
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);
}
 
源代码19 项目: mamute   文件: MarkDown.java
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);
	}
}
 
源代码20 项目: owltools   文件: JsCommandRunner.java
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);
	}
}