Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  //  The contents of this file are subject to the Mozilla Public License
  //  Version 1.1 (the "License"); you may not use this file except in
  //  compliance with the License. You may obtain a copy of the License
  //  at http://www.mozilla.org/MPL/
  //
  //  Software distributed under the License is distributed on an "AS IS"
  //  basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
  //  the License for the specific language governing rights and
  //  limitations under the License.
 //
 //  The Original Code is RabbitMQ.
 //
 //  The Initial Developer of the Original Code is VMware, Inc.
 //  Copyright (c) 2007-2011 VMware, Inc.  All rights reserved.
 //
 
 package com.rabbitmq.tools.jsonrpc;
 
 import java.util.Map;
 
JSON-RPC is a lightweight RPC mechanism using JSON as a data language for request and reply messages. It is rapidly becoming a standard in web development, where it is used to make RPC requests over HTTP. RabbitMQ provides an AMQP transport binding for JSON-RPC in the form of the JsonRpcClient class. JSON-RPC services are self-describing - each service is able to list its supported procedures, and each procedure describes its parameters and types. An instance of JsonRpcClient retrieves its service description using the standard system.describe procedure when it is constructed, and uses the information to coerce parameter types appropriately. A JSON service description is parsed into instances of ServiceDescription. Client code can access the service description by reading the serviceDescription field of JsonRpcClient instances.

 
 public class JsonRpcClient extends RpcClient implements InvocationHandler {
    
Holds the JSON-RPC service description for this client.
 
     private ServiceDescription serviceDescription;

    
Construct a new JsonRpcClient, passing the parameters through to RpcClient's constructor. The service description record is retrieved from the server during construction.

Throws:
java.util.concurrent.TimeoutException if a response is not received within the timeout specified, if any
 
     public JsonRpcClient(Channel channelString exchangeString routingKeyint timeout)
         throws IOExceptionJsonRpcExceptionTimeoutException
     {
 	super(channelexchangeroutingKeytimeout);
     }
 
     public JsonRpcClient(Channel channelString exchangeString routingKey)
     {
         this(channelexchangeroutingKey.);
     }

    
Private API - parses a JSON-RPC reply object, checking it for exceptions.

Returns:
the result contained within the reply, if no exception is found Throws JsonRpcException if the reply object contained an exception
 
     public static Object checkReply(Map<StringObjectreply)
         throws JsonRpcException
     {
 	if (reply.containsKey("error")) {
             @SuppressWarnings("unchecked")
             Map<StringObjectmap = (Map<StringObject>) reply.get("error");
             // actually a Map<String, Object>
             throw new JsonRpcException(map);
         }
 
         Object result = reply.get("result");
         //System.out.println(new JSONWriter().write(result));
         return result;
    }

    
Public API - builds, encodes and sends a JSON-RPC request, and waits for the response.

Returns:
the result contained within the reply, if no exception is found
Throws:
JsonRpcException if the reply object contained an exception
java.util.concurrent.TimeoutException if a response is not received within the timeout specified, if any
    public Object call(String methodObject[] paramsthrows IOExceptionJsonRpcExceptionTimeoutException
    {
        HashMap<StringObjectrequest = new HashMap<StringObject>();
        request.put("id"null);
        request.put("method"method);
        request.put("version".);
        request.put("params", (params == null) ? new Object[0] : params);
        String requestStr = new JSONWriter().write(request);
        try {
            String replyStr = this.stringCall(requestStr);
            @SuppressWarnings("unchecked")
            Map<StringObjectmap = (Map<StringObject>) (new JSONReader().read(replyStr));
            return checkReply(map);
        } catch(ShutdownSignalException ex) {
            throw new IOException(ex.getMessage()); // wrap, re-throw
        }
    }

    
Public API - implements InvocationHandler.invoke. This is useful for constructing dynamic proxies for JSON-RPC interfaces.
    public Object invoke(Object proxyMethod methodObject[] args)
        throws Throwable
    {
        return call(method.getName(), args);
    }

    
Public API - gets a dynamic proxy for a particular interface class.
    public Object createProxy(Class<?> klass)
        throws IllegalArgumentException
    {
        return Proxy.newProxyInstance(klass.getClassLoader(),
                                      new Class[] { klass },
                                      this);
    }

    
Private API - used by call(java.lang.String[]) to ad-hoc convert strings into the required data types for a call.
    public static Object coerce(String valString type)
    {
	if ("bit".equals(type)) {
	    return Boolean.getBoolean(val) ? . : .;
else if ("num".equals(type)) {
	    try {
		return new Integer(val);
	    } catch (NumberFormatException nfe) {
		return new Double(val);
	    }
else if ("str".equals(type)) {
	    return val;
else if ("arr".equals(type) || "obj".equals(type) || "any".equals(type)) {
	    return new JSONReader().read(val);
else if ("nil".equals(type)) {
	    return null;
else {
	    throw new IllegalArgumentException("Bad type: " + type);
	}
    }

    
Public API - as call(java.lang.String,java.lang.Object[]), but takes the method name from the first entry in args, and the parameters from subsequent entries. All parameter values are passed through coerce() to attempt to make them the types the server is expecting.

Returns:
the result contained within the reply, if no exception is found
Throws:
JsonRpcException if the reply object contained an exception
java.lang.NumberFormatException if a coercion failed
java.util.concurrent.TimeoutException if a response is not received within the timeout specified, if any
See also:
coerce(java.lang.String,java.lang.String)
    public Object call(String[] args)
    {
	if (args.length == 0) {
	    throw new IllegalArgumentException("First string argument must be method name");
	}
	String method = args[0];
        int arity = args.length - 1;
	ParameterDescription[] params = proc.getParams();
	Object[] actuals = new Object[arity];
	for (int count = 0; count < params.lengthcount++) {
	    actuals[count] = coerce(args[count + 1], params[count].);
	}
	return call(methodactuals);
    }

    
Public API - gets the service description record that this service loaded from the server itself at construction time.
    }

    
Private API - invokes the "system.describe" method on the server, and parses and stores the resulting service description in this object. TODO: Avoid calling this from the constructor.

Throws:
java.util.concurrent.TimeoutException if a response is not received within the timeout specified, if any
    {
        @SuppressWarnings("unchecked")
        Map<StringObjectrawServiceDescription = (Map<StringObject>) call("system.describe"null);
         = new ServiceDescription(rawServiceDescription);
    }
New to GrepCode? Check out our FAQ X