Monday, October 20, 2008

GWT-RPC serialization with restlets

One of the major feature of GWT is the ability to serialize objects from/to client to/from server. It simplifies the communication between server and clients, but also improve data security by making the code readable with difficulty.
In the frame of restlets, or even more generally RESTFul applications, we focus more on scalability of the application and portability of the data which are exchanged. Nevertheless we may choose an architecture where communication betwwen server and clients could mimic the GWT-RPC one, ie by transmitting serialized objects through the network.
This possible by using some classes provided by the GWT framework. For instance :

* on the client side : SerializationStreamFactory, SerailizationStreamReader
* on the server side : RPC.encodeResponseForSuccess

Example :
1) on the client side

// Create the serialization stream factory
SerializationStreamFactory serializationFactory =
GWT.create(MyClass.class);

// Create a stream reader : the argument is the serialized string from the server
SerializationStreamReader streamReader =
serializationFactory.createStreamReader(aStringReturnedFromRestletCommunication);

// Deserialize the instance
MyClass aClass= (MyClass)(streamReader.readObject());



2) on the server side

String encoded =null;
try {
String encoded = RPC.encodeResponseForSuccess(MyClass.getMethod("aMethodName"),myClass);
} catch (SecurityException e) {
e.printStackTrace();
} catch (SerializationException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return encoded;

No comments: