Java Code Examples for javax.script.Invocable#invokeMethod()

The following examples show how to use javax.script.Invocable#invokeMethod() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: InvokeScriptMethod.java    From TencentKona-8 with GNU General Public License v2.0 7 votes vote down vote up
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 !!" );
}
 
Example 2
Source File: InvokeScriptMethod.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
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 !!" );
}
 
Example 3
Source File: BaseScriptedLookupService.java    From nifi with Apache License 2.0 6 votes vote down vote up
@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);
        }
    }
}
 
Example 4
Source File: ScriptedActionHandler.java    From nifi with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example 5
Source File: InvokeScriptedProcessor.java    From nifi with Apache License 2.0 6 votes vote down vote up
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);
            }
        }
    }
}
 
Example 6
Source File: InvokeScriptMethod.java    From jdk8u_nashorn with GNU General Public License v2.0 6 votes vote down vote up
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 !!" );
}
 
Example 7
Source File: ScriptTemplateView.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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));
	}
}
 
Example 8
Source File: Test8.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
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");
}
 
Example 9
Source File: InvokeScriptMethod.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
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 !!" );
}
 
Example 10
Source File: ScriptTemplateView.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@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));
	}
}
 
Example 11
Source File: InvokeScriptMethod.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
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 !!" );
}
 
Example 12
Source File: InvokeScriptMethod.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
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 !!" );
}
 
Example 13
Source File: BaseScriptedLookupService.java    From nifi with Apache License 2.0 5 votes vote down vote up
@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);
        }
    }
}
 
Example 14
Source File: ExtensionUtil.java    From proxyee-down with Apache License 2.0 5 votes vote down vote up
/**
 * 运行一个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];
}
 
Example 15
Source File: EJSParser.java    From jeddict with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 16
Source File: BattleLogScriptController.java    From logbook-kai with MIT License 5 votes vote down vote up
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;
}
 
Example 17
Source File: JavascriptEngine.java    From proxyee-down with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 18
Source File: ScriptedRulesEngine.java    From nifi with Apache License 2.0 5 votes vote down vote up
@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);
        }
    }
}
 
Example 19
Source File: ScriptedActionHandler.java    From nifi with Apache License 2.0 5 votes vote down vote up
@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);
        }
    }
}
 
Example 20
Source File: ScriptingTutorial.java    From netbeans with Apache License 2.0 4 votes vote down vote up
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());
}