Search in sources :

Example 71 with Invocable

use of javax.script.Invocable in project wso2-synapse by wso2.

the class ScriptMediator method mediateWithExternalScript.

/**
 * Mediation implementation when the script to be executed should be loaded from the registry
 *
 * @param synCtx the message context
 * @return script result
 * @throws ScriptException       For any errors , when compile, run the script
 * @throws NoSuchMethodException If the function is not defined in the script
 */
private Object mediateWithExternalScript(MessageContext synCtx) throws ScriptException, NoSuchMethodException {
    ScriptEngineWrapper sew = null;
    Object obj;
    try {
        sew = prepareExternalScript(synCtx);
        XMLHelper helper;
        if (language.equalsIgnoreCase(JAVA_SCRIPT) || language.equals(NASHORN_JAVA_SCRIPT)) {
            helper = xmlHelper;
        } else {
            helper = XMLHelper.getArgHelper(sew.getEngine());
        }
        ScriptMessageContext scriptMC;
        scriptMC = getScriptMessageContext(synCtx, helper);
        processJSONPayload(synCtx, scriptMC);
        Invocable invocableScript = (Invocable) sew.getEngine();
        obj = invocableScript.invokeFunction(function, new Object[] { scriptMC });
    } finally {
        if (sew != null) {
            // return engine to front of queue or drop if queue is full (i.e. if getNewScriptEngine() spawns a new engine)
            pool.offer(sew);
        }
    }
    return obj;
}
Also used : Invocable(javax.script.Invocable) XMLHelper(org.apache.bsf.xml.XMLHelper)

Example 72 with Invocable

use of javax.script.Invocable in project thingsboard by thingsboard.

the class AbstractNashornJsInvokeService method doInvokeFunction.

@Override
protected ListenableFuture<Object> doInvokeFunction(UUID scriptId, String functionName, Object[] args) {
    jsPushedMsgs.incrementAndGet();
    ListenableFuture<Object> result = jsExecutor.executeAsync(() -> {
        try {
            if (useJsSandbox()) {
                return sandbox.getSandboxedInvocable().invokeFunction(functionName, args);
            } else {
                return ((Invocable) engine).invokeFunction(functionName, args);
            }
        } catch (Exception e) {
            onScriptExecutionError(scriptId, e, functionName);
            throw new ExecutionException(e);
        }
    });
    if (maxRequestsTimeout > 0) {
        result = Futures.withTimeout(result, maxRequestsTimeout, TimeUnit.MILLISECONDS, timeoutExecutorService);
    }
    Futures.addCallback(result, invokeCallback, MoreExecutors.directExecutor());
    return result;
}
Also used : Invocable(javax.script.Invocable) ExecutionException(java.util.concurrent.ExecutionException) ScriptException(javax.script.ScriptException) ExecutionException(java.util.concurrent.ExecutionException)

Example 73 with Invocable

use of javax.script.Invocable in project vorto by eclipse.

the class JavascriptEvalFunction method invoke.

@Override
@SuppressWarnings({ "rawtypes" })
public Object invoke(ExpressionContext context, Object[] parameters) {
    NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
    ScriptEngine engine = factory.getScriptEngine(new ClassFilter() {

        @Override
        public boolean exposeToScripts(String s) {
            return false;
        }
    });
    try {
        final Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
        bindings.remove("print");
        bindings.remove("load");
        bindings.remove("loadWithNewGlobal");
        bindings.remove("exit");
        bindings.remove("quit");
        engine.eval(functionBody);
    } catch (ScriptException e) {
        throw new JXPathException("Problem evaluating " + functionName, e);
    }
    Invocable inv = (Invocable) engine;
    Object[] args;
    int pi = 0;
    Class[] types = toTypes(parameters);
    if (types.length >= 1 && ExpressionContext.class.isAssignableFrom(types[0])) {
        pi = 1;
    }
    args = new Object[parameters.length + pi];
    if (pi == 1) {
        args[0] = context;
    }
    for (int i = 0; i < parameters.length; i++) {
        args[i + pi] = TypeUtils.convert(parameters[i], types[i + pi]);
    }
    try {
        return inv.invokeFunction(functionName, unwrap(args));
    } catch (NoSuchMethodException e) {
        throw new JXPathInvalidAccessException("Cannot find function with the list of parameters", e);
    } catch (ScriptException e) {
        throw new JXPathInvalidAccessException("Problem executing javascript", e);
    }
}
Also used : Bindings(javax.script.Bindings) JXPathInvalidAccessException(org.apache.commons.jxpath.JXPathInvalidAccessException) ScriptEngine(javax.script.ScriptEngine) NashornScriptEngineFactory(jdk.nashorn.api.scripting.NashornScriptEngineFactory) ScriptException(javax.script.ScriptException) Invocable(javax.script.Invocable) ExpressionContext(org.apache.commons.jxpath.ExpressionContext) ClassFilter(jdk.nashorn.api.scripting.ClassFilter) JXPathException(org.apache.commons.jxpath.JXPathException)

Example 74 with Invocable

use of javax.script.Invocable in project spf4j by zolyfarkas.

the class RetryPolicies method toInvocable.

/**
 * Scripted predicates are not there for application users to modify.
 * Scripted predicates should be written by Operation engineers.
 * The script engine choice needs to be carefully done as to not allow even ops to do bad stuff by mistake.
 * (calling system.exit, etc...)
 * The main reason for allowing scripted predicates is deployment speed.
 * (a config change will propagates to your fleet several order of magnitudes faster than binaries,
 * and will not require a process restart)
 * Now this speed means also any stupid stuff can propagate faster, so canarying a config change is also a must.
 * @param engine
 * @param script
 * @return
 * @throws ScriptException
 */
@SuppressFBWarnings("SCRIPT_ENGINE_INJECTION")
public static Invocable toInvocable(final ScriptEngine engine, final String script) throws ScriptException {
    final Invocable invocable;
    if (engine instanceof Compilable) {
        Compilable ceng = (Compilable) engine;
        final CompiledScript predicateScript = ceng.compile(script);
        if (predicateScript instanceof Invocable) {
            invocable = (Invocable) predicateScript;
        } else {
            Object result = predicateScript.eval();
            if (result instanceof Invocable) {
                invocable = (Invocable) result;
            } else {
                throw new ScriptException("Script must evaluate to a Invocable/function, not: " + result);
            }
        }
    } else {
        Object result = engine.eval(script);
        if (result instanceof Invocable) {
            invocable = (Invocable) result;
        } else {
            throw new ScriptException("Script must evaluate to a Invocable/function, not: " + result);
        }
    }
    return invocable;
}
Also used : CompiledScript(javax.script.CompiledScript) Invocable(javax.script.Invocable) ScriptException(javax.script.ScriptException) Compilable(javax.script.Compilable) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Aggregations

Invocable (javax.script.Invocable)74 ScriptException (javax.script.ScriptException)45 ScriptEngine (javax.script.ScriptEngine)34 ScriptEngineManager (javax.script.ScriptEngineManager)24 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)8 CompiledScript (javax.script.CompiledScript)8 Bindings (javax.script.Bindings)7 Map (java.util.Map)5 BufferedReader (java.io.BufferedReader)4 HashSet (java.util.HashSet)4 Test (org.junit.Test)4 Writer (java.io.Writer)3 HashMap (java.util.HashMap)3 ScriptContext (javax.script.ScriptContext)3