Search in sources :

Example 1 with ClassFilter

use of jdk.nashorn.api.scripting.ClassFilter 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)

Aggregations

Bindings (javax.script.Bindings)1 Invocable (javax.script.Invocable)1 ScriptEngine (javax.script.ScriptEngine)1 ScriptException (javax.script.ScriptException)1 ClassFilter (jdk.nashorn.api.scripting.ClassFilter)1 NashornScriptEngineFactory (jdk.nashorn.api.scripting.NashornScriptEngineFactory)1 ExpressionContext (org.apache.commons.jxpath.ExpressionContext)1 JXPathException (org.apache.commons.jxpath.JXPathException)1 JXPathInvalidAccessException (org.apache.commons.jxpath.JXPathInvalidAccessException)1