Example usage for javax.script Invocable invokeFunction

List of usage examples for javax.script Invocable invokeFunction

Introduction

In this page you can find the example usage for javax.script Invocable invokeFunction.

Prototype

public Object invokeFunction(String name, Object... args) throws ScriptException, NoSuchMethodException;

Source Link

Document

Used to call top-level procedures and functions defined in scripts.

Usage

From source file:org.eclairjs.nashorn.sql.JSUDF19.java

@SuppressWarnings({ "null", "unchecked" })
@Override//  w  w  w . j a  v a2 s .c  o m
public Object call(Object o, Object o2, Object o3, Object o4, Object o5, Object o6, Object o7, Object o8,
        Object o9, Object o10, Object o11, Object o12, Object o13, Object o14, Object o15, Object o16,
        Object o17, Object o18, Object o19) throws Exception {
    ScriptEngine e = NashornEngineSingleton.getEngine();
    if (this.fn == null) {
        this.fn = e.eval(func);
    }
    Invocable invocable = (Invocable) e;

    Object params[] = { this.fn, o, o2, o3, o4, o5, o6, o7, o8, o9, o10, o11, o12, o13, o14, o15, o16, o17, o18,
            o19 };

    if (this.args != null && this.args.length > 0) {
        params = ArrayUtils.addAll(params, this.args);
    }

    Object ret = invocable.invokeFunction("Utils_invoke", params);
    ret = this.castValueToReturnType(ret);
    return ret;
}

From source file:org.eclairjs.nashorn.sql.JSUDF20.java

@SuppressWarnings({ "null", "unchecked" })
@Override//from w w w .ja  va  2  s  .  c  om
public Object call(Object o, Object o2, Object o3, Object o4, Object o5, Object o6, Object o7, Object o8,
        Object o9, Object o10, Object o11, Object o12, Object o13, Object o14, Object o15, Object o16,
        Object o17, Object o18, Object o19, Object o20) throws Exception {
    ScriptEngine e = NashornEngineSingleton.getEngine();
    if (this.fn == null) {
        this.fn = e.eval(func);
    }
    Invocable invocable = (Invocable) e;

    Object params[] = { this.fn, o, o2, o3, o4, o5, o6, o7, o8, o9, o10, o11, o12, o13, o14, o15, o16, o17, o18,
            o19, o20 };

    if (this.args != null && this.args.length > 0) {
        params = ArrayUtils.addAll(params, this.args);
    }

    Object ret = invocable.invokeFunction("Utils_invoke", params);
    ret = this.castValueToReturnType(ret);
    return ret;
}

From source file:org.apache.accumulo.core.util.shell.commands.ScriptCommand.java

private void invokeFunctionOrMethod(Shell shellState, ScriptEngine engine, CommandLine cl, Object[] args) {
    try {//w w  w  .  j  av a  2s.  c  o m
        Invocable inv = (Invocable) engine;
        if (cl.hasOption(function.getOpt())) {
            inv.invokeFunction(cl.getOptionValue(function.getOpt()), args);
        } else if (cl.hasOption(object.getOpt())) {
            String objectMethod = cl.getOptionValue(object.getOpt());
            String[] parts = objectMethod.split(":");
            if (!(parts.length == 2)) {
                shellState.printException(new Exception("Object and Method must be supplied"));
                return;
            }
            String objectName = parts[0];
            String methodName = parts[1];
            Object obj = engine.get(objectName);
            inv.invokeMethod(obj, methodName, args);

        }
    } catch (Exception e) {
        shellState.printException(e);
    }
}

From source file:org.eclairjs.nashorn.sql.JSUDF21.java

@SuppressWarnings({ "null", "unchecked" })
@Override/*w  ww.j  ava 2s.com*/
public Object call(Object o, Object o2, Object o3, Object o4, Object o5, Object o6, Object o7, Object o8,
        Object o9, Object o10, Object o11, Object o12, Object o13, Object o14, Object o15, Object o16,
        Object o17, Object o18, Object o19, Object o20, Object o21) throws Exception {
    ScriptEngine e = NashornEngineSingleton.getEngine();
    if (this.fn == null) {
        this.fn = e.eval(func);
    }
    Invocable invocable = (Invocable) e;

    Object params[] = { this.fn, o, o2, o3, o4, o5, o6, o7, o8, o9, o10, o11, o12, o13, o14, o15, o16, o17, o18,
            o19, o20, o21 };

    if (this.args != null && this.args.length > 0) {
        params = ArrayUtils.addAll(params, this.args);
    }

    Object ret = invocable.invokeFunction("Utils_invoke", params);
    ret = this.castValueToReturnType(ret);
    return ret;
}

From source file:org.eclairjs.nashorn.sql.JSUDF22.java

@SuppressWarnings({ "null", "unchecked" })
@Override/*from  w  w  w.ja  va  2 s  . co  m*/
public Object call(Object o, Object o2, Object o3, Object o4, Object o5, Object o6, Object o7, Object o8,
        Object o9, Object o10, Object o11, Object o12, Object o13, Object o14, Object o15, Object o16,
        Object o17, Object o18, Object o19, Object o20, Object o21, Object o22) throws Exception {
    ScriptEngine e = NashornEngineSingleton.getEngine();
    if (this.fn == null) {
        this.fn = e.eval(func);
    }
    Invocable invocable = (Invocable) e;

    Object params[] = { this.fn, o, o2, o3, o4, o5, o6, o7, o8, o9, o10, o11, o12, o13, o14, o15, o16, o17, o18,
            o19, o20, o21, o22 };

    if (this.args != null && this.args.length > 0) {
        params = ArrayUtils.addAll(params, this.args);
    }

    Object ret = invocable.invokeFunction("Utils_invoke", params);
    ret = this.castValueToReturnType(ret);
    return ret;
}

From source file:com.yahoo.validatar.execution.rest.JSON.java

/**
 * Uses the user provided query to process and return a JSON columnar format of the data.
 *
 * @param data The data from the REST call.
 * @param function The function name to invoke.
 * @param query The Query object being run.
 * @return The String JSON response of the call, null if exception (query is failed).
 *//*from  ww  w  . ja  v a  2  s .c  o  m*/
String convertToColumnarJSON(String data, String function, Query query) {
    try {
        log.info("Evaluating query using Javascript function: {}\n{}", function, query.value);
        evaluator.eval(query.value);
        Invocable invocable = (Invocable) evaluator;
        String columnarJSON = (String) invocable.invokeFunction(function, data);
        log.info("Processed response using query into JSON: {}", columnarJSON);
        return columnarJSON;
    } catch (ScriptException se) {
        log.error("Exception while processing input Javascript", se);
        query.setFailure(se.toString());
        query.addMessage(se.toString());
    } catch (NoSuchMethodException nsme) {
        log.error("Method {} not found in {}\n{}", function, query.value, nsme);
        query.setFailure(nsme.toString());
    }
    return null;
}

From source file:com.cubeia.ProtocolGeneratorMojo.java

private void generateCode(String lang, File protocolFile, File outputBaseDirectory, String packageName,
        boolean generateVisitors, String version, boolean failOnBadPacketOrder, String javascript_package_name)
        throws MojoExecutionException, MojoFailureException {

    if (append_language_to_output_base_dir) {
        outputBaseDirectory = appendLangToBaseDir(lang, outputBaseDirectory);
        getLog().info("Appended language '" + lang + "' to base dir, new base dir: " + outputBaseDirectory);
    }/*from  ww w. jav  a2s  .c  o  m*/

    ScriptEngineManager factory = new ScriptEngineManager();

    // Create a JRuby engine.
    ScriptEngine engine = factory.getEngineByName("jruby");

    // Evaluate JRuby code from string.
    InputStream scriptIn = getClass().getResourceAsStream(GENERATOR_WRAPPER_SCRIPT);
    if (scriptIn == null) {
        new MojoExecutionException(
                "unable to find code generator script resource: " + GENERATOR_WRAPPER_SCRIPT);
    }

    Object[] args = new Object[] { protocolFile.getPath(), lang, outputBaseDirectory.getPath(), packageName,
            generateVisitors ? "true" : null, version, failOnBadPacketOrder ? "true" : null,
            javascript_package_name };

    InputStreamReader scriptReader = new InputStreamReader(scriptIn);

    try {
        engine.eval(scriptReader);
        Invocable invocableEngine = (Invocable) engine;
        invocableEngine.invokeFunction("generate_code", args);
    } catch (ScriptException e) {
        throw new MojoFailureException("code generation error: " + e.toString());
    } catch (NoSuchMethodException e) {
        throw new MojoExecutionException("error calling code generator script: " + e.getMessage());
    }
}

From source file:services.plugins.system.notification1.EventNotificationPluginRunner.java

/**
 * Initialize a new script engine based on the plugin configuration
 * @throws PluginException //  www  .  ja  va  2  s  .  co m
 */
private synchronized void initScriptEngine() throws PluginException {
    if (log.isDebugEnabled()) {
        log.debug("Activating the script engine...");
    }
    this.supportedDataTypes = new ArrayList<DataType>();
    this.scriptEngine = getScriptService().getEngine(getPluginContext().getPluginConfigurationName());
    this.scriptEngine.getContext().setAttribute("scriptUtils",
            new HookScriptUtils(getCustomAttributeManagerService(), getPluginContext(), getWsClient()),
            ScriptContext.ENGINE_SCOPE);
    Pair<Boolean, byte[]> hookScriptConfiguration = getPluginContext().getConfiguration(getPluginContext()
            .getPluginDescriptor().getConfigurationBlockDescriptors().get(HOOKSCRIPT_CONFIGURATION_NAME), true);
    if (!hookScriptConfiguration.getLeft()) {
        try {
            //Evaluate the script
            this.scriptEngine.eval(new String(hookScriptConfiguration.getRight()));
        } catch (ScriptException e) {
            if (log.isDebugEnabled()) {
                log.debug("Invalid hook script", e);
            }
            throw new PluginException("Invalid hook script", e);
        }

        //Get the registered data types
        Invocable invocable = (Invocable) this.scriptEngine;
        try {
            List<String> supportedDataTypeNames = new ArrayList<String>();
            invocable.invokeFunction("register", supportedDataTypeNames);
            for (String supportedDataTypeName : supportedDataTypeNames) {
                DataType dataType = DataType.getDataType(supportedDataTypeName);
                if (dataType == null) {
                    throw new PluginException(
                            "Invalid data type " + supportedDataTypeName + " in the \"register\" method");
                }
                this.supportedDataTypes.add(dataType);
            }
        } catch (NoSuchMethodException e) {
            throw new PluginException("No method \"register\" in this hook script", e);
        } catch (ScriptException e) {
            throw new PluginException("No method \"register\" in this hook script or invalid method", e);
        }
    } else {
        throw new PluginException(
                "WARNING: the current script might not be compatible with the version of the plugin"
                        + ", please edit it and save it before attempting a new start");
    }
    if (log.isDebugEnabled()) {
        log.debug("...script engine activated");
    }
}

From source file:com.github.safrain.remotegsh.server.RgshFilter.java

private void performShellExecute(HttpServletRequest request, HttpServletResponse response) throws IOException {
    ShellSession session = getSession(request.getParameter("sid"));
    if (session == null) {
        response.setStatus(410);// Http status GONE
        return;/*w  w  w. ja  v  a  2 s . com*/
    }
    ScriptEngine engine = session.getEngine();

    String action = request.getParameter("action");
    if (action == null) {
        StringWriter responseWriter = new StringWriter();
        engine.getContext().setWriter(responseWriter);
        engine.getContext().setErrorWriter(response.getWriter());
        String script = toString(request.getInputStream(), charset);
        JSONObject json = new JSONObject();
        try {
            try {
                Object result = engine.eval(script);
                json.put("result", String.valueOf(result));
                response.setStatus(200);
                json.put("response", responseWriter.getBuffer().toString());
            } catch (ScriptException e) {
                log.log(Level.SEVERE, "Error while running shell command:" + script, e);
                response.setStatus(500);
                e.getCause().printStackTrace(response.getWriter());
                return;
            }
        } catch (JSONException e) {
            log.log(Level.SEVERE, "Error while running shell command:" + script, e);
            response.setStatus(500);
            e.printStackTrace(response.getWriter());
            return;
        }
        response.getWriter().write(json.toString());
    } else {
        Invocable invocable = (Invocable) engine;
        try {
            invocable.invokeFunction("shellAction", action);
        } catch (ScriptException e) {
            response.setStatus(500);
            e.printStackTrace(response.getWriter());
        } catch (NoSuchMethodException e) {
            response.setStatus(500);
            response.getWriter().println("Action not supported");
        } catch (Exception e) {
            response.setStatus(500);
            e.printStackTrace(response.getWriter());
        }
    }

}

From source file:org.eclairjs.nashorn.JSComparator.java

@SuppressWarnings({ "null", "unchecked" })
@Override//from   w  w w  . j  av a2 s .  c  o  m
public int compare(Object o, Object o2) {
    int ret = -1;

    try {

        ScriptEngine e = NashornEngineSingleton.getEngine();
        // if (this.fn == null) {
        /*
        if we try to save teh evaluated function for future use we get serialization exception,
        why Comparators are different than java.api.functions ?
         */
        Object fn = e.eval(func);
        //}
        Invocable invocable = (Invocable) e;

        Object params[] = { fn, o, o2 };

        if (this.args != null && this.args.length > 0) {
            params = ArrayUtils.addAll(params, this.args);
        }
        //Tuple2<String, String> s = new Tuple2("foo", "bar");
        //scala.collection.Iterator<Object> i = s.productIterator();

        ret = Integer.valueOf(invocable.invokeFunction("Utils_invoke", params).toString());

        return ret;
    } catch (Exception exc) {
        exc.printStackTrace();
    }

    return ret;
}