JSONRPCBridge Class Reference

Inherits java::io::Serializable.

Inherited by JSONBridge.

Collaboration diagram for JSONRPCBridge:

Collaboration graph
[legend]

List of all members.

Classes

class  MethodCandidate
class  ObjectInstance

Public Member Functions

JSONRPCResult call (Object context[], JSONObject jsonReq)
JSONRPCBridgeState getBridgeState ()
CallbackController getCallbackController ()
HashMap getReferenceMap ()
boolean isCallableReference (Class clazz)
boolean isReference (Class clazz)
Class lookupClass (String name)
Object lookupObject (Object key)
void registerCallableReference (Class clazz) throws Exception
void registerCallback (InvocationCallback callback, Class contextInterface)
void registerClass (String name, Class clazz) throws Exception
void registerObject (Object key, Object o, Class interfaceClass)
void registerObject (Object key, Object o)
void registerReference (Class clazz) throws Exception
void registerSerializer (Serializer serializer) throws Exception
void setBridgeState (JSONRPCBridgeState state)
void setCallbackController (CallbackController cbc)
void setExceptionTransformer (ExceptionTransformer exceptionTransformer)
void unregisterCallback (InvocationCallback callback, Class contextInterface)
void unregisterClass (String name)
void unregisterObject (Object key)

Static Public Member Functions

static JSONRPCBridge getGlobalBridge ()
static JSONSerializer getSerializer ()
static void registerLocalArgResolver (Class argClazz, Class contextInterface, LocalArgResolver argResolver)
static void setSerializer (JSONSerializer ser)
static void unregisterLocalArgResolver (Class argClazz, Class contextInterface, LocalArgResolver argResolver)

Static Package Functions

 [static initializer]

Private Member Functions

void allInstanceMethods (HashSet m)
void allStaticMethods (HashSet m)
void applyFixup (JSONArray arguments, JSONArray fixup, JSONArray original) throws JSONException
MethodCandidate betterSignature (MethodCandidate methodCandidate, MethodCandidate methodCandidate1)
Object next (Object prev, String ref) throws JSONException
Object next (Object prev, int idx) throws JSONException
ClassData resolveClass (String className)
Method resolveMethod (HashMap methodMap, String methodName, JSONArray arguments)
ObjectInstance resolveObject (Object key)
Object traverse (JSONArray origin, JSONArray refs, boolean fixup) throws JSONException
MethodCandidate tryUnmarshallArgs (Method method, JSONArray arguments) throws UnmarshallException
Object[] unmarshallArgs (Object context[], Method method, JSONArray arguments) throws UnmarshallException

Static Private Member Functions

static String argSignature (Method method)
static String argSignature (JSONArray arguments)
static void uniqueMethods (HashSet m, String prefix, HashMap methodMap)

Private Attributes

CallbackController cbc = null
ExceptionTransformer exceptionTransformer = IDENTITY_EXCEPTION_TRANSFORMER
JSONRPCBridgeState state = new JSONRPCBridgeState(this)

Static Private Attributes

static final JSONRPCBridge globalBridge = new JSONRPCBridge()
static final ExceptionTransformer IDENTITY_EXCEPTION_TRANSFORMER
static final Logger log
static JSONSerializer ser = new JSONSerializer()
static final long serialVersionUID = 2


Detailed Description

This class implements a bridge that unmarshalls JSON objects in JSON-RPC request format, invokes a method on the exported object, and then marshalls the resulting Java objects to JSON objects in JSON-RPC result format.

There is a global bridge singleton object that allows exporting classes and objects to all HTTP clients. In addition to this, an instance of the JSONRPCBridge can optionally be placed in a users' HttpSession object registered under the attribute "JSONRPCBridge" to allow exporting of classes and objects to specific users. A session specific bridge will delegate requests for objects it does not know about to the global singleton JSONRPCBridge instance.

Using session specific bridge instances can improve the security of applications by allowing exporting of certain objects only to specific HttpSessions as well as providing a convenient mechanism for JavaScript clients to access stateful data associated with the current user.

You can create a HttpSession specific bridge in JSP with the usebean tag: <jsp:useBean id="JSONRPCBridge" scope="session" class="org.jabsorb.JSONRPCBridge" />

Then export an object for your JSON-RPC client to call methods on: JSONRPCBridge.registerObject("test", testObject);

This will make available all public methods of the object as test.<methodnames> to JSON-RPC clients. This approach should generally be performed after an authentication check to only export objects to clients that are authorised to use them.

Alternatively, the global bridge singleton object allows exporting of classes and objects to all HTTP clients. It can be fetched with JSONRPCBridge.getGlobalBridge().

To export all public instance methods of an object to all clients: JSONRPCBridge.getGlobalBridge().registerObject("myObject", myObject);

To export all public static methods of a class to all clients: JSONRPCBridge.getGlobalBridge().registerClass("MyClass", com.example.MyClass.class);


Member Function Documentation

[static initializer] (  )  [static, package]

void allInstanceMethods ( HashSet  m  )  [private]

Add all instance methods that can be invoked on this bridge to a HashSet.

Parameters:
m HashSet to add all static methods to.

void allStaticMethods ( HashSet  m  )  [private]

Add all static methods that can be invoked on this bridge to the given HashSet.

Parameters:
m HashSet to add all static methods to.

void applyFixup ( JSONArray  arguments,
JSONArray  fixup,
JSONArray  original 
) throws JSONException [private]

Apply one fixup assigment to the incoming json arguments.

WARNING: the resultant "fixed up" arguments may contain circular references after this operation. That is the whole point of course-- but the JSONArray and JSONObject's themselves aren't aware of circular references when certain methods are called (e.g. toString) so be careful when handling these circular referenced json objects.

Parameters:
arguments the json arguments for the incoming json call.
fixup the fixup entry.
original the original value to assign to the fixup.
Exceptions:
org.json.JSONException if invalid or unexpected fixup data is encountered.

static String argSignature ( Method  method  )  [static, private]

Display a method call argument signature for a method as a String for debugging/logging purposes. The string contains the comma separated list of argument types that the given method takes.

Parameters:
method Method instance to display the argument signature for.
Returns:
the argument signature for the method, as a String.

static String argSignature ( JSONArray  arguments  )  [static, private]

Creates a signature for an array of arguments

Parameters:
arguments The argumnts
Returns:
A comma seperated string listing the arguments

MethodCandidate betterSignature ( MethodCandidate  methodCandidate,
MethodCandidate  methodCandidate1 
) [private]

Returns the more fit of the two method candidates

Parameters:
methodCandidate One of the methodCandidates to compare
methodCandidate1 The other of the methodCandidates to compare
Returns:
The better of the two candidates

JSONRPCResult call ( Object  context[],
JSONObject  jsonReq 
)

Call a method using a JSON-RPC request object.

Parameters:
context The transport context (the HttpServletRequest object in the case of the HTTP transport).
jsonReq The JSON-RPC request structured as a JSON object tree.
Returns:
a JSONRPCResult object with the result of the invocation or an error.

JSONRPCBridgeState getBridgeState (  ) 

Get the JSONRPCBridgeState object associated with this bridge.

Returns:
the JSONRPCBridgeState object associated with this bridge.

CallbackController getCallbackController (  ) 

Get the CallbackController object associated with this bridge.

Returns:
the CallbackController object associated with this bridge.

static JSONRPCBridge getGlobalBridge (  )  [static]

This method retrieves the global bridge singleton.

It should be used with care as objects should generally be registered within session specific bridges for security reasons.

Returns:
returns the global bridge object.

HashMap getReferenceMap (  ) 

Gets the map of referenced objects used by this bridge.

The reference map contains objects of classes that have been registered as a Reference or CallableReference.

Returns:
a HashMap with the references currently in use on this bridge instance.

static JSONSerializer getSerializer (  )  [static]

Get the global JSONSerializer object.

Returns:
the global JSONSerializer object.

boolean isCallableReference ( Class  clazz  ) 

Check whether a class is registered as a callable reference type.

Parameters:
clazz The class object to check is a callable reference.
Returns:
true if it is, false otherwise

boolean isReference ( Class  clazz  ) 

Check whether a class is registered as a reference type.

Parameters:
clazz The class object to check is a reference.
Returns:
true if it is, false otherwise.

Class lookupClass ( String  name  ) 

Lookup a class that is registered with this bridge.

Parameters:
name The registered name of the class to lookup.
Returns:
the class for the name

Object lookupObject ( Object  key  ) 

Lookup an object that is registered with this bridge.

Parameters:
key The registered name of the object to lookup.
Returns:
The object desired if it exists, else null.

Object next ( Object  prev,
String  ref 
) throws JSONException [private]

Given a previous json object, find the next object under the given ref.

Parameters:
prev object to find subobject of.
ref reference of sub object to find.
Returns:
the next object in a fixup reference chain (prev[ref])
Exceptions:
JSONException if something goes wrong.

Object next ( Object  prev,
int  idx 
) throws JSONException [private]

Given a previous json object, find the next object under the given index.

Parameters:
prev object to find subobject of.
idx index of sub object to find.
Returns:
the next object in a fixup reference chain (prev[idx])
Exceptions:
JSONException if something goes wrong.

void registerCallableReference ( Class  clazz  )  throws Exception

Registers a class to be returned as a callable reference.

The JSONBridge will return a callable reference to the JSON-RPC client for registered classes instead of passing them by value. The JSONBridge will take a references to these objects and the JSON-RPC client will create an invocation proxy for objects of this class for which methods will be called on the instance on the server.

Note: A limitation exists in the JSON-RPC client where only the top most object returned from a method can be made into a proxy.

A Callable Reference in JSON format looks like this: { "javaClass":"org.jabsorb.test.Bar",
"objectID":4827452,
"JSONRPCType":"CallableReference" }

Parameters:
clazz The class object that should be marshalled as a callable reference.
Exceptions:
Exception If the bridge is global, callable references cannot be added

void registerCallback ( InvocationCallback  callback,
Class  contextInterface 
)

Registers a callback to be called before and after method invocation

Parameters:
callback The object implementing the InvocationCallback Interface
contextInterface The type of transport Context interface the callback is interested in eg. HttpServletRequest.class for the servlet transport.

void registerClass ( String  name,
Class  clazz 
) throws Exception

Registers a class to export static methods.

The JSONBridge will export all static methods of the class. This is useful for exporting factory classes that may then return CallableReferences to the JSON-RPC client.

Calling registerClass for a clazz again under the same name will have no effect.

To export instance methods you need to use registerObject.

Parameters:
name The name to register the class with.
clazz The class to export static methods from.
Exceptions:
Exception If a class is already registed with this name

static void registerLocalArgResolver ( Class  argClazz,
Class  contextInterface,
LocalArgResolver  argResolver 
) [static]

Registers a Class to be removed from the exported method signatures and instead be resolved locally using context information from the transport.

Parameters:
argClazz The class to be resolved locally
argResolver The user defined class that resolves the and returns the method argument using transport context information
contextInterface The type of transport Context object the callback is interested in eg. HttpServletRequest.class for the servlet transport

void registerObject ( Object  key,
Object  o,
Class  interfaceClass 
)

Registers an object to export all instance methods defined by interfaceClass.

The JSONBridge will export all instance methods defined by interfaceClass of the particular object under the name passed in as a key.

This will make available these methods of the object as <key>.<methodnames> to JSON-RPC clients.

Parameters:
key The named prefix to export the object as
o The object instance to be called upon
interfaceClass The type that this object should be registered as.
This can be used to restrict the exported methods to the methods defined in a specific superclass or interface.

void registerObject ( Object  key,
Object  o 
)

Registers an object to export all instance methods and static methods.

The JSONBridge will export all instance methods and static methods of the particular object under the name passed in as a key.

This will make available all methods of the object as <key>.<methodnames> to JSON-RPC clients.

Calling registerObject for a name that already exists will replace the existing entry.

Parameters:
key The named prefix to export the object as
o The object instance to be called upon

void registerReference ( Class  clazz  )  throws Exception

Registers a class to be returned by reference and not by value as is done by default.

The JSONBridge will take a references to these objects and return an opaque object to the JSON-RPC client. When the opaque object is passed back through the bridge in subsequent calls, the original object is substitued in calls to Java methods. This should be used for any objects that contain security information or complex types that are not required in the Javascript client but need to be passed as a reference in methods of exported objects.

A Reference in JSON format looks like this:

{ "javaClass":"org.jabsorb.test.Foo",
"objectID":5535614,
"JSONRPCType":"Reference" }

Parameters:
clazz The class object that should be marshalled as a reference.
Exceptions:
Exception If the bridge is global, callable references cannot be added

void registerSerializer ( Serializer  serializer  )  throws Exception

Register a new serializer on this bridge.

Parameters:
serializer A class implementing the Serializer interface (usually derived from AbstractSerializer).
Exceptions:
Exception If a serialiser has already been registered that serialises the same class

ClassData resolveClass ( String  className  )  [private]

Resolves a string to a class

Parameters:
className The name of the class to resolve
Returns:
The data associated with the className

Method resolveMethod ( HashMap  methodMap,
String  methodName,
JSONArray  arguments 
) [private]

Resolve which method the caller is requesting

If a method with the requested number of arguments does not exist at all, null will be returned.

If the object or class (for static methods) being invoked contains more than one overloaded methods that match the method key signature, find the closest matching method to invoke according to the JSON arguments being passed in.

Parameters:
methodMap Map keyed by MethodKey objects and the values will be either a Method object, or an array of Method objects, if there is more than one possible method that can be invoked matching the MethodKey.
methodName method name being called.
arguments JSON arguments to the method, as a JSONArray.
Returns:
the Method that most closely matches the call signature, or null if there is not a match.

ObjectInstance resolveObject ( Object  key  )  [private]

Resolve the key to a specified instance object. If an instance object of the requested key is not found, and this is not the global bridge, then look in the global bridge too.

If the key is not found in this bridge or the global bridge, the requested key may be a class method (static method) or may not exist (not registered under the requested key.)

Parameters:
key registered object key being requested by caller.
Returns:
ObjectInstance that has been registered under this key, in this bridge or the global bridge.

void setBridgeState ( JSONRPCBridgeState  state  ) 

Set the JSONRPCBridgeState object for this bridge.

Parameters:
state the JSONRPCBridgeState object to be set for this bridge.

void setCallbackController ( CallbackController  cbc  ) 

Set the CallbackController object for this bridge.

Parameters:
cbc the CallbackController object to be set for this bridge.

void setExceptionTransformer ( ExceptionTransformer  exceptionTransformer  ) 

Sets the exception transformer for the bridge.

Parameters:
exceptionTransformer The new exception transformer to use.

static void setSerializer ( JSONSerializer  ser  )  [static]

Set the global JSONSerializer object.

Parameters:
ser the global JSONSerializer object.

Object traverse ( JSONArray  origin,
JSONArray  refs,
boolean  fixup 
) throws JSONException [private]

Traverse a list of references to find the target reference in an original or fixup list.

Parameters:
origin origin JSONArray (arguments) to begin traversing at.
refs JSONArray containing array integer references and or String object references.
fixup if true, stop one short of the traversal chain to return the parent of the fixup rather than the fixup itself (which will be non-existant)
Returns:
either a JSONObject or JSONArray for the Object found at the end of the traversal.
Exceptions:
JSONException if something unexpected is found in the data

MethodCandidate tryUnmarshallArgs ( Method  method,
JSONArray  arguments 
) throws UnmarshallException [private]

Tries to unmarshall the arguments to a method

Parameters:
method The method to unmarshall the arguments for.
arguments The arguments to unmarshall
Returns:
The MethodCandidate that should suit the arguements and method.
Exceptions:
UnmarshallException If one of the arguments cannot be unmarshalled

static void uniqueMethods ( HashSet  m,
String  prefix,
HashMap  methodMap 
) [static, private]

Create unique method names by appending the given prefix to the keys from the given HashMap and adding them all to the given HashSet.

Parameters:
m HashSet to add unique methods to.
prefix prefix to append to each method name found in the methodMap.
methodMap a HashMap containing MethodKey keys specifying methods.

Object [] unmarshallArgs ( Object  context[],
Method  method,
JSONArray  arguments 
) throws UnmarshallException [private]

Convert the arguments to a method call from json into java objects to be used for invoking the method, later.

Parameters:
context the context of the caller. This will be the servlet request and response objects in an http servlet call environment. These are used to insert local arguments (e.g. the request, response or session,etc.) when found in the java method call argument signature.
method the java method that will later be invoked with the given args.
arguments the arguments from the caller, in json format.
Returns:
the java arguments as unmarshalled from json.
Exceptions:
UnmarshallException if there is a problem unmarshalling the arguments.

void unregisterCallback ( InvocationCallback  callback,
Class  contextInterface 
)

Unregisters a callback

Parameters:
callback The previously registered InvocationCallback object
contextInterface The previously registered transport Context interface.

void unregisterClass ( String  name  ) 

Unregisters a class exported with registerClass.

The JSONBridge will unexport all static methods of the class.

Parameters:
name The registered name of the class to unexport static methods from.

static void unregisterLocalArgResolver ( Class  argClazz,
Class  contextInterface,
LocalArgResolver  argResolver 
) [static]

Unregisters a LocalArgResolver.

Parameters:
argClazz The previously registered local class
argResolver The previously registered LocalArgResolver object
contextInterface The previously registered transport Context interface.

void unregisterObject ( Object  key  ) 

Unregisters an object exported with registerObject.

The JSONBridge will unexport all instance methods and static methods of the particular object under the name passed in as a key.

Parameters:
key The named prefix of the object to unexport


Member Data Documentation

CallbackController cbc = null [private]

The callback controller

ExceptionTransformer exceptionTransformer = IDENTITY_EXCEPTION_TRANSFORMER [private]

The functor used to convert exceptions

final JSONRPCBridge globalBridge = new JSONRPCBridge() [static, private]

Global bridge (for exporting to all users)

final ExceptionTransformer IDENTITY_EXCEPTION_TRANSFORMER [static, private]

Initial value:

 new ExceptionTransformer()
  {
    
    private final static long serialVersionUID = 2;

    public Object transform(Throwable t)
    {
      return t;
    }
  }
A simple transformer that makes no change

final Logger log [static, private]

Initial value:

 LoggerFactory
      .getLogger(JSONRPCBridge.class)
The logger for this class

JSONSerializer ser = new JSONSerializer() [static, private]

Global JSONSerializer instance

final long serialVersionUID = 2 [static, private]

Unique serialisation id.

JSONRPCBridgeState state = new JSONRPCBridgeState(this) [private]

Bridge state


The documentation for this class was generated from the following file:

Generated on Sat May 26 06:43:38 2012 for Project Wonder by  doxygen 1.5.8