Search in sources :

Example 26 with Invocable

use of javax.script.Invocable in project jgnash by ccavanaugh.

the class ImportFilter method getDescription.

public String getDescription() {
    try {
        final Invocable invocable = (Invocable) scriptEngine;
        final Object result = invocable.invokeFunction("getDescription", Locale.getDefault());
        return result.toString();
    } catch (final ScriptException | NoSuchMethodException e) {
        logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
    }
    return "";
}
Also used : Invocable(javax.script.Invocable) ScriptException(javax.script.ScriptException)

Example 27 with Invocable

use of javax.script.Invocable in project groovy by apache.

the class JSR223SpecTest method testInvocableFunction.

@Test
public void testInvocableFunction() throws ScriptException, NoSuchMethodException {
    // tag::jsr223_invocable[]
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("groovy");
    String fact = "def factorial(n) { n == 1 ? 1 : n * factorial(n - 1) }";
    engine.eval(fact);
    Invocable inv = (Invocable) engine;
    Object[] params = { 5 };
    Object result = inv.invokeFunction("factorial", params);
    assertEquals(Integer.valueOf(120), result);
// end::jsr223_invocable[]
}
Also used : Invocable(javax.script.Invocable) ScriptEngineManager(javax.script.ScriptEngineManager) ScriptEngine(javax.script.ScriptEngine) Test(org.junit.Test)

Example 28 with Invocable

use of javax.script.Invocable in project hutool by looly.

the class ScriptUtil method evalInvocable.

/**
 * 执行Javascript脚本,返回Invocable,此方法分为两种情况:
 *
 * <ol>
 *     <li>执行的脚本返回值是可执行的脚本方法</li>
 *     <li>脚本为函数库,则ScriptEngine本身为可执行方法</li>
 * </ol>
 *
 * @param script 脚本内容
 * @return 执行结果
 * @throws ScriptRuntimeException 脚本异常
 * @since 5.3.6
 */
public static Invocable evalInvocable(String script) throws ScriptRuntimeException {
    final ScriptEngine jsEngine = getJsEngine();
    final Object eval;
    try {
        eval = jsEngine.eval(script);
    } catch (ScriptException e) {
        throw new ScriptRuntimeException(e);
    }
    if (eval instanceof Invocable) {
        return (Invocable) eval;
    } else if (jsEngine instanceof Invocable) {
        return (Invocable) jsEngine;
    }
    throw new ScriptRuntimeException("Script is not invocable !");
}
Also used : ScriptException(javax.script.ScriptException) Invocable(javax.script.Invocable) ScriptEngine(javax.script.ScriptEngine)

Example 29 with Invocable

use of javax.script.Invocable in project hutool by looly.

the class NashornDeepTest method main.

public static void main(String[] args) throws ScriptException, NoSuchMethodException {
    ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");
    engine.eval(ResourceUtil.readUtf8Str("filter1.js"));
    final Object filter1 = ((Invocable) engine).invokeFunction("filter1", 1, 2);
    Assert.assertFalse((Boolean) filter1);
}
Also used : Invocable(javax.script.Invocable) ScriptEngineManager(javax.script.ScriptEngineManager) ScriptEngine(javax.script.ScriptEngine)

Example 30 with Invocable

use of javax.script.Invocable in project proxyee-down by monkeyWie.

the class ExtensionUtil method invoke.

/**
 * 运行一个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];
}
Also used : ExtensionInfo(org.pdown.gui.extension.ExtensionInfo) LoggerFactory(org.slf4j.LoggerFactory) TaskForm(org.pdown.rest.form.TaskForm) SimpleScriptContext(javax.script.SimpleScriptContext) Function(java.util.function.Function) StandardCopyOption(java.nio.file.StandardCopyOption) FileUtil(org.pdown.core.util.FileUtil) Meta(org.pdown.gui.extension.Meta) Event(org.pdown.gui.extension.HookScript.Event) Path(java.nio.file.Path) ScriptException(javax.script.ScriptException) ExtensionContent(org.pdown.gui.extension.ExtensionContent) OutputStream(java.io.OutputStream) NativeController(org.pdown.gui.http.controller.NativeController) Logger(org.slf4j.Logger) Files(java.nio.file.Files) DownApplication(org.pdown.gui.DownApplication) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) FileOutputStream(java.io.FileOutputStream) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) HookScript(org.pdown.gui.extension.HookScript) FileInputStream(java.io.FileInputStream) InputStreamReader(java.io.InputStreamReader) Collectors(java.util.stream.Collectors) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) ScriptContext(javax.script.ScriptContext) ConfigUtil(org.pdown.gui.util.ConfigUtil) CountDownLatch(java.util.concurrent.CountDownLatch) HttpHandlerUtil(org.pdown.gui.http.util.HttpHandlerUtil) Invocable(javax.script.Invocable) AppUtil(org.pdown.gui.util.AppUtil) Paths(java.nio.file.Paths) ScriptEngine(javax.script.ScriptEngine) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) JavascriptEngine(org.pdown.gui.extension.jsruntime.JavascriptEngine) PDownConfigContent(org.pdown.gui.content.PDownConfigContent) InputStream(java.io.InputStream) StringUtils(org.springframework.util.StringUtils) Invocable(javax.script.Invocable) SimpleScriptContext(javax.script.SimpleScriptContext) SimpleScriptContext(javax.script.SimpleScriptContext) ScriptContext(javax.script.ScriptContext) CountDownLatch(java.util.concurrent.CountDownLatch) ScriptEngine(javax.script.ScriptEngine) ScriptException(javax.script.ScriptException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException)

Aggregations

Invocable (javax.script.Invocable)68 ScriptException (javax.script.ScriptException)41 ScriptEngine (javax.script.ScriptEngine)30 ScriptEngineManager (javax.script.ScriptEngineManager)22 IOException (java.io.IOException)19 File (java.io.File)10 InputStreamReader (java.io.InputStreamReader)10 UndeclaredThrowableException (java.lang.reflect.UndeclaredThrowableException)10 FileReader (java.io.FileReader)9 Reader (java.io.Reader)9 Compilable (javax.script.Compilable)5 CompiledScript (javax.script.CompiledScript)5 BufferedReader (java.io.BufferedReader)4 HashSet (java.util.HashSet)4 Map (java.util.Map)4 Bindings (javax.script.Bindings)4 ScriptContext (javax.script.ScriptContext)4 Writer (java.io.Writer)3 SimpleScriptContext (javax.script.SimpleScriptContext)3 ValidationResult (org.apache.nifi.components.ValidationResult)3