Reflection - can't call java method from JSON-RPC request

926 views Asked by At

I want to call a method based on JSON-RPC request from a servlet I have code like this:

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("application/json");
    ServletInputStream in = request.getInputStream();
    PrintWriter out = response.getWriter();
    String json_request = this.readStream(in);
    Object id = null;
    try {
        JSONRPC2Request reqIn = JSONRPC2Request.parse(json_request);
        id = reqIn.getID();
        Object params = reqIn.getPositionalParams().toArray();
        String method_name = reqIn.getMethod();

        Service service = new Service();
        Method[] methods = service.getClass().getMethods();
        Method method = null;
        // getMethod need class as second argument
        for (int i=0; i<methods.length; ++i) {
            if (methods[i].getName().equals(method_name)) {
                method = methods[i];
                break;
            }
        }
        if (method != null) {
            Object result = method.invoke(service, params);
            JSONRPC2Response respOut = new JSONRPC2Response(result, id);
            out.println(respOut);
        } else {
            out.println(JSONRPC2Error.METHOD_NOT_FOUND);
        }
    } catch (IllegalArgumentException e) {
        out.println(new JSONRPC2Response(JSONRPC2Error.INVALID_PARAMS, id));
    } catch (IllegalAccessException e) {
        out.println(new JSONRPC2Response(JSONRPC2Error.INTERNAL_ERROR, id));
    } catch (InvocationTargetException e) {
        out.println(new JSONRPC2Response(JSONRPC2Error.INTERNAL_ERROR, id));
    } catch (JSONRPC2ParseException e) {
        out.println("{\"error\": \"Parse Error: " + e.getMessage() + "\"}");
    }
}

I try to call method login from service class:

public class Service {
    public String login(String username, String password) {
        return "token";
    }
}

I call it from javascript using jQuery:

var request = JSON.stringify({
    method: "login",
    params: ["foo", "Bar"],
    id: 1,
    jsonrpc: "2.0"
});
$.post('/app/rpc', request, function(res) { console.log(res); });

But I keep getting runtime IllegalArgumentException. What's wrong with my code? I also try to cast params to object with the same result.

0

There are 0 answers