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

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

源代码1 项目: TencentKona-8   文件: InvokeScriptMethod.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. This code defines a script object 'obj'
    // with one method called 'hello'.
    final String script = "var obj = new Object(); obj.hello = function(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;

    // get script object on which we want to call the method
    final Object obj = engine.get("obj");

    // invoke the method named "hello" on the script object "obj"
    inv.invokeMethod(obj, "hello", "Script Method !!" );
}
 
源代码2 项目: jdk8u60   文件: InvokeScriptMethod.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. This code defines a script object 'obj'
    // with one method called 'hello'.
    final String script = "var obj = new Object(); obj.hello = function(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;

    // get script object on which we want to call the method
    final Object obj = engine.get("obj");

    // invoke the method named "hello" on the script object "obj"
    inv.invokeMethod(obj, "hello", "Script Method !!" );
}
 
源代码3 项目: openjdk-jdk8u   文件: InvokeScriptMethod.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. This code defines a script object 'obj'
    // with one method called 'hello'.
    final String script = "var obj = new Object(); obj.hello = function(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;

    // get script object on which we want to call the method
    final Object obj = engine.get("obj");

    // invoke the method named "hello" on the script object "obj"
    inv.invokeMethod(obj, "hello", "Script Method !!" );
}
 
源代码4 项目: lams   文件: ScriptTemplateView.java
@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
		HttpServletResponse response) throws Exception {

	try {
		ScriptEngine engine = getEngine();
		Invocable invocable = (Invocable) engine;
		String url = getUrl();
		String template = getTemplate(url);

		Object html;
		if (this.renderObject != null) {
			Object thiz = engine.eval(this.renderObject);
			html = invocable.invokeMethod(thiz, this.renderFunction, template, model, url);
		}
		else {
			html = invocable.invokeFunction(this.renderFunction, template, model, url);
		}

		response.getWriter().write(String.valueOf(html));
	}
	catch (ScriptException ex) {
		throw new ServletException("Failed to render script template", new StandardScriptEvalException(ex));
	}
}
 
源代码5 项目: openjdk-jdk8u-backup   文件: InvokeScriptMethod.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. This code defines a script object 'obj'
    // with one method called 'hello'.
    final String script = "var obj = new Object(); obj.hello = function(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;

    // get script object on which we want to call the method
    final Object obj = engine.get("obj");

    // invoke the method named "hello" on the script object "obj"
    inv.invokeMethod(obj, "hello", "Script Method !!" );
}
 
源代码6 项目: openjdk-jdk9   文件: Test8.java
public static void main(String[] args) throws Exception {
    System.out.println("\nTest8\n");
    ScriptEngineManager m = new ScriptEngineManager();
    ScriptEngine e  = Helper.getJsEngine(m);
    if (e == null) {
        System.out.println("Warning: No js engine found; test vacuously passes.");
        return;
    }
    e.eval(new FileReader(
        new File(System.getProperty("test.src", "."), "Test8.js")));
    Invocable inv = (Invocable)e;
    inv.invokeFunction("main", "Mustang");
    // use method of a specific script object
    Object scriptObj = e.get("scriptObj");
    inv.invokeMethod(scriptObj, "main", "Mustang");
}
 
源代码7 项目: hottub   文件: InvokeScriptMethod.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. This code defines a script object 'obj'
    // with one method called 'hello'.
    final String script = "var obj = new Object(); obj.hello = function(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;

    // get script object on which we want to call the method
    final Object obj = engine.get("obj");

    // invoke the method named "hello" on the script object "obj"
    inv.invokeMethod(obj, "hello", "Script Method !!" );
}
 
@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
		HttpServletResponse response) throws Exception {

	try {
		ScriptEngine engine = getEngine();
		Invocable invocable = (Invocable) engine;
		String url = getUrl();
		String template = getTemplate(url);

		Object html;
		if (this.renderObject != null) {
			Object thiz = engine.eval(this.renderObject);
			html = invocable.invokeMethod(thiz, this.renderFunction, template, model, url);
		}
		else {
			html = invocable.invokeFunction(this.renderFunction, template, model, url);
		}

		response.getWriter().write(String.valueOf(html));
	}
	catch (ScriptException ex) {
		throw new ServletException("Failed to render script template", new StandardScriptEvalException(ex));
	}
}
 
源代码9 项目: jdk8u_nashorn   文件: InvokeScriptMethod.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. This code defines a script object 'obj'
    // with one method called 'hello'.
    final String script = "var obj = new Object(); obj.hello = function(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;

    // get script object on which we want to call the method
    final Object obj = engine.get("obj");

    // invoke the method named "hello" on the script object "obj"
    inv.invokeMethod(obj, "hello", "Script Method !!" );
}
 
源代码10 项目: nifi   文件: InvokeScriptedProcessor.java
private void invokeScriptedProcessorMethod(String methodName, Object... params) {
    // Run the scripted processor's method here, if it exists
    if (scriptEngine instanceof Invocable) {
        final Invocable invocable = (Invocable) scriptEngine;
        final Object obj = scriptEngine.get("processor");
        if (obj != null) {

            ComponentLog logger = getLogger();
            try {
                invocable.invokeMethod(obj, methodName, params);
            } catch (final NoSuchMethodException nsme) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Configured script Processor does not contain the method " + methodName);
                }
            } catch (final Exception e) {
                // An error occurred during onScheduled, propagate it up
                logger.error("Error while executing the scripted processor's method " + methodName, e);
                if (e instanceof ProcessException) {
                    throw (ProcessException) e;
                }
                throw new ProcessException(e);
            }
        }
    }
}
 
源代码11 项目: nifi   文件: ScriptedActionHandler.java
public void execute(PropertyContext context, Action action, Map<String, Object> facts) {
    // Attempt to call a non-ActionHandler interface method (i.e. execute(context, action, facts) from PropertyContextActionHandler)
    final Invocable invocable = (Invocable) scriptEngine;

    try {
        // Get the actual object from the script engine, versus the proxy stored in ActionHandler. The object may have additional methods,
        // where ActionHandler is a proxied interface
        final Object obj = scriptEngine.get("actionHandler");
        if (obj != null) {
            try {
                invocable.invokeMethod(obj, "execute", context, action, facts);
            } catch (final NoSuchMethodException nsme) {
                if (getLogger().isDebugEnabled()) {
                    getLogger().debug("Configured script ActionHandler is not a PropertyContextActionHandler and has no execute(context, action, facts) method, falling back to"
                    + "execute(action, facts).");
                }
                execute(action, facts);
            }
        } else {
            throw new ScriptException("No ActionHandler was defined by the script.");
        }
    } catch (ScriptException se) {
        throw new ProcessException("Error executing onEnabled(context) method: " + se.getMessage(), se);
    }
}
 
源代码12 项目: nifi   文件: BaseScriptedLookupService.java
@OnDisabled
public void onDisabled(final ConfigurationContext context) {
    // Call an non-interface method onDisabled(context), to allow a scripted LookupService the chance to shut down as necessary
    final Invocable invocable = (Invocable) scriptEngine;
    if (configurationContext != null) {
        try {
            // Get the actual object from the script engine, versus the proxy stored in lookupService. The object may have additional methods,
            // where lookupService is a proxied interface
            final Object obj = scriptEngine.get("lookupService");
            if (obj != null) {
                try {
                    invocable.invokeMethod(obj, "onDisabled", context);
                } catch (final NoSuchMethodException nsme) {
                    if (getLogger().isDebugEnabled()) {
                        getLogger().debug("Configured script LookupService does not contain an onDisabled() method.");
                    }
                }
            } else {
                throw new ScriptException("No LookupService was defined by the script.");
            }
        } catch (ScriptException se) {
            throw new ProcessException("Error executing onDisabled(context) method", se);
        }
    }
}
 
源代码13 项目: proxyee-down   文件: JavascriptEngine.java
public static ScriptEngine buildEngine() throws ScriptException, NoSuchMethodException {
  NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
  ScriptEngine engine = factory.getScriptEngine(new SafeClassFilter());
  Window window = new Window();
  Object global = engine.eval("this");
  Object jsObject = engine.eval("Object");
  Invocable invocable = (Invocable) engine;
  invocable.invokeMethod(jsObject, "bindProperties", global, window);
  engine.eval("var window = this");
  return engine;
}
 
源代码14 项目: 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];
}
 
源代码15 项目: nifi   文件: BaseScriptedLookupService.java
@Override
@OnEnabled
public void onEnabled(final ConfigurationContext context) {
    synchronized (scriptingComponentHelper.isInitialized) {
        if (!scriptingComponentHelper.isInitialized.get()) {
            scriptingComponentHelper.createResources();
        }
    }
    super.onEnabled(context);

    // Call an non-interface method onEnabled(context), to allow a scripted LookupService the chance to set up as necessary
    final Invocable invocable = (Invocable) scriptEngine;
    if (configurationContext != null) {
        try {
            // Get the actual object from the script engine, versus the proxy stored in lookupService. The object may have additional methods,
            // where lookupService is a proxied interface
            final Object obj = scriptEngine.get("lookupService");
            if (obj != null) {
                try {
                    invocable.invokeMethod(obj, "onEnabled", context);
                } catch (final NoSuchMethodException nsme) {
                    if (getLogger().isDebugEnabled()) {
                        getLogger().debug("Configured script LookupService does not contain an onEnabled() method.");
                    }
                }
            } else {
                throw new ScriptException("No LookupService was defined by the script.");
            }
        } catch (ScriptException se) {
            throw new ProcessException("Error executing onEnabled(context) method", se);
        }
    }
}
 
源代码16 项目: jeddict   文件: EJSParser.java
public String parse(String template) throws ScriptException {
    // Hack until NETBEANS-2705 fixed
    System.getProperties().setProperty("polyglot.js.nashorn-compat", "true");
    String result = null;
    try {
        if (engine == null) {
            engine = createEngine();
        }
        Object ejs = engine.eval("ejs");
        Invocable invocable = (Invocable) engine;
        Map<String, Object> options = new HashMap<>();
        options.put("filename", "template");
        if (importTemplate != null) {
            options.put("ext", importTemplate);
        }
        if (delimiter != null) {
            options.put("delimiter", delimiter);
        }

        result = (String) invocable.invokeMethod(ejs, "render", template, null, options);
    } catch (NoSuchMethodException ex) {
        Exceptions.printStackTrace(ex);
    }
    // Hack until NETBEANS-2705 fixed
    System.getProperties().remove("polyglot.js.nashorn-compat");
    return result;
}
 
源代码17 项目: logbook-kai   文件: BattleLogScriptController.java
public Object reduce(Object callback, Object initialValue) throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    Invocable invocable = (Invocable) this.engine;

    Object parser = this.engine.eval("JSON");

    Object result = initialValue;
    for (BattleLogDetail log : this.details) {
        BattleLog battleLog = BattleLogs.read(log.getDate());
        String json = mapper.writeValueAsString(battleLog);
        Object obj = invocable.invokeMethod(parser, "parse", json);
        result = ((JSObject) callback).call(null, result, obj);
    }
    return result;
}
 
源代码18 项目: nifi   文件: ScriptedRulesEngine.java
@Override
@OnEnabled
public void onEnabled(final ConfigurationContext context) {
    synchronized (scriptingComponentHelper.isInitialized) {
        if (!scriptingComponentHelper.isInitialized.get()) {
            scriptingComponentHelper.createResources();
        }
    }
    super.onEnabled(context);

    // Call an non-interface method onEnabled(context), to allow a scripted RulesEngineService the chance to set up as necessary
    final Invocable invocable = (Invocable) scriptEngine;
    if (configurationContext != null) {
        try {
            // Get the actual object from the script engine, versus the proxy stored in RulesEngineService. The object may have additional methods,
            // where RulesEngineService is a proxied interface
            final Object obj = scriptEngine.get("rulesEngine");
            if (obj != null) {
                try {
                    invocable.invokeMethod(obj, "onEnabled", context);
                } catch (final NoSuchMethodException nsme) {
                    if (getLogger().isDebugEnabled()) {
                        getLogger().debug("Configured script RulesEngineService does not contain an onEnabled() method.");
                    }
                }
            } else {
                throw new ScriptException("No RulesEngineService was defined by the script.");
            }
        } catch (ScriptException se) {
            throw new ProcessException("Error executing onEnabled(context) method: " + se.getMessage(), se);
        }
    }
}
 
源代码19 项目: nifi   文件: ScriptedActionHandler.java
@Override
@OnEnabled
public void onEnabled(final ConfigurationContext context) {
    synchronized (scriptingComponentHelper.isInitialized) {
        if (!scriptingComponentHelper.isInitialized.get()) {
            scriptingComponentHelper.createResources();
        }
    }
    super.onEnabled(context);

    // Call an non-interface method onEnabled(context), to allow a scripted ActionHandler the chance to set up as necessary
    final Invocable invocable = (Invocable) scriptEngine;
    if (configurationContext != null) {
        try {
            // Get the actual object from the script engine, versus the proxy stored in ActionHandler. The object may have additional methods,
            // where ActionHandler is a proxied interface
            final Object obj = scriptEngine.get("actionHandler");
            if (obj != null) {
                try {
                    invocable.invokeMethod(obj, "onEnabled", context);
                } catch (final NoSuchMethodException nsme) {
                    if (getLogger().isDebugEnabled()) {
                        getLogger().debug("Configured script ActionHandler does not contain an onEnabled() method.");
                    }
                }
            } else {
                throw new ScriptException("No ActionHandler was defined by the script.");
            }
        } catch (ScriptException se) {
            throw new ProcessException("Error executing onEnabled(context) method", se);
        }
    }
}
 
源代码20 项目: netbeans   文件: ScriptingTutorial.java
public void callJavaScriptClassFactoryFromJava() throws Exception {
    String src = "\n"
        + "(function() {\n"
        + "  class JSIncrementor {\n"
        + "     constructor(init) {\n"
        + "       this.value = init;\n"
        + "     }\n"
        + "     inc() {\n"
        + "       return ++this.value;\n"
        + "     }\n"
        + "     dec() {\n"
        + "       return --this.value;\n"
        + "     }\n"
        + "  }\n"
        + "  return function(init) {\n"
        + "    return new JSIncrementor(init);\n"
        + "  }\n"
        + "})\n";

    // Evaluate JavaScript function definition
    Object jsFunction = engine.eval(src);

    final Invocable inv = (Invocable) engine;

    // Execute the JavaScript function
    Object jsFactory = inv.invokeMethod(jsFunction, "call");

    // Execute the JavaScript factory to create Java objects
    Incrementor initFive = inv.getInterface(
        inv.invokeMethod(jsFactory, "call", null, 5),
        Incrementor.class
    );
    Incrementor initTen = inv.getInterface(
        inv.invokeMethod(jsFactory, "call", null, 10),
        Incrementor.class
    );

    initFive.inc();
    assertEquals("Now at seven", 7, initFive.inc());

    initTen.dec();
    assertEquals("Now at eight", 8, initTen.dec());
    initTen.dec();

    assertEquals("Values are the same", initFive.value(), initTen.value());
}