OpenBaseMovil
Welcome at » Tutorials

We will now address how to create a servlet to handle RemoteCalls from our device.

The first piece of code is a very generic servlet that takes the binary data, handles it to another class, and sends back the result. That second class is the one that will do the parsing. This way is easier to perform unit testing, for example.

Here is the code for the servlet:

/*
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
 
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
 
    You should have received a copy of the GNU General Public License
    along with this program.  If not, see .
*/
 
public class RPCServlet
    extends HttpServlet
{
    private String infoPage;
 
    public void init( final ServletConfig config )
    {
        infoPage = config.getInitParameter( "informationPage" );
    }
 
    protected void doGet(
            final HttpServletRequest    request,
            final HttpServletResponse response
    )
            throws ServletException,
                   IOException
    {
        request.getRequestDispatcher( infoPage ).forward( request, response );
    }
 
    protected void doPost(
            final HttpServletRequest     request,
            final HttpServletResponse   response
    )
            throws ServletException,
                   IOException
    {
        processRequest( request, response );
    }
 
    private void processRequest(
            final HttpServletRequest request,
            final HttpServletResponse   response
    )
            throws ServletException
    {
        try
        {
            // Read all the data into a byte array
            final BufferedInputStream bis = new BufferedInputStream(
                    request.getInputStream()
            );
            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int c = bis.read();
            while( c != -1 )
            {
                baos.write( c );
                c = bis.read();
            }
            final byte[] data = baos.toByteArray();
 
            // Handle the data to the RPCBroker class
            final byte[] result = RPCBroker.handle( data );
 
            // Return the result to the device
            response.setContentType( "application/octet-stream" );
            response.setContentLength( result.length );
            response.getOutputStream().write( result );
        }
        catch( Exception e )
        {
            throw new ServletException( e );
        }
    }
}
 

Now the RPCBroker has to parse the data and make the actual call. We will not be doing here the call, you can do what suits you better: from a simple if-else structure to calling objects using reflection. If you use reflection, please be careful that you allow calls to the objects you want to be called and not a generic approach, since that could lead to big security problems.

 
/*
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
 
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
 
    You should have received a copy of the GNU General Public License
    along with this program.  If not, see .
*/
public class RPCBroker
{
    private static Log log = LogFactory.getLog( RPCBroker.class );
 
    public static final int RC_SUCCESS              = 0;
    public static final int RC_INVALID_OBJECT       = 1;
    public static final int RC_INVALID_METHOD       = 2;
    public static final int RC_NOT_ALLOWED          = 3;
    public static final int RC_INVALID_ARGUMENTS    = 4;
    public static final int RC_INVOKATION_EXCEPTION = 5;
    public static final int RC_INVALID_CRC          = 6;
 
    public static byte[] handle( final byte[] data )
        throws IOException,
               SerializationException
    {
        if( data == null )
        {
            return sendError( RC_INVALID_CRC, "Null data" );
        }
        try
        {
            final ByteArrayInputStream bais = new ByteArrayInputStream( data );
            final ChecksumedInputStream cis = new ChecksumedInputStream( bais );
            final SerializerInputStream in = new SerializerInputStream( cis );
            final byte      version     = in.readByte();
            final byte      encryption  = in.readByte();
            final String    deviceGuid  = in.readString();
            final long      deviceId    = in.readLong();
            final String    objectName  = in.readString();
            final String    methodName  = in.readString();
            final Object[]  parameters;
            try
            {
                parameters = (Object[]) in.readNullableObject();
            }
            catch( SerializationException e )
            {
                throw new IOException( e.getMessage() );
            }
            final long crc = cis.getCRC();
            final String    endOfData   = in.readString();
            if( endOfData.equals( "END_OF_DATA" ) )
            {
                final long originalCRC = in.readLong();
                if( originalCRC != crc )
                {
                    return sendError( RC_INVALID_CRC, "Invalid CRC" );
                }
                else
                {
                    return invoke(
                            version,
                            deviceGuid,
                            deviceId,
                            objectName,
                            methodName,
                            parameters
                    );
                }
            }
            else
            {
                return sendError( RC_INVALID_ARGUMENTS, "Wrong signature" );
            }
        }
        catch( SerializationException e )
        {
            return sendError( RC_INVALID_CRC, e.getMessage() );
        }
    }
 
    private static byte[] invoke(
            final byte      version,
            final String    deviceGuid,
            final long      deviceId,
            final String    objectName,
            final String    methodName,
            final Object[]  parameters
    )
            throws IOException,
                   SerializationException
    {
        // Here is where you actually look up the object
        // make the call and return the value
 
        Object retval;
        /*
        1. Lookup object
 
        if object is not found: return sendError( RC_INVALID_OBJECT, "error message" );
 
        2. Check security, if applicable
 
        if not allowed to call: return sendError( RC_NOT_ALLOWED, "error message" );
 
        3. Make the call
 
        store the return value in the retval variable.
        if an error raises: return sendError( RC_INVOKATION_EXCEPTION, "error message" );
        */
 
        // You should perform the appropriate try-catch
        // The following code should be placed into a try block,
        // when the call has been successful
       final ByteArrayOutputStream baos = new ByteArrayOutputStream();
       final SerializerOutputStream out = new SerializerOutputStream( baos );
       out.writeInt( RC_SUCCESS );
       out.writeString( "OK" );
       out.writeNullableObject( retval );
       out.flush();
       return baos.toByteArray();
    }
 
    private static byte[] sendError( final int code, final String message )
            throws IOException,
                   SerializationException
    {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final SerializerOutputStream out = new SerializerOutputStream( baos );
        out.writeInt( code );
        out.writeString( message != null ? message : "" );
        out.flush();
        return baos.toByteArray();
    }
}
 

With this second article you should have almost everything you need to perform remote calls.

Please, leave your comments and suggestions.

BlogLines del.icio.us Digg Facebook Google Google Reader Yahoo! MyWeb Newsgator Newsvine reddit SlashDot StumbleUpon Technorati

The Networking library in OpenBaseMovil (openbasemovil-net) provides some very useful networking methods that you can use in your applications.

One of the most useful ones is the RemoteCall class. As you can guess it is a remote call procedure, and it is a binary one. If your target platform supports the remote call or webservice optional APIs, you can use them, but we wanted to provide an approach that could be used on any device (many of the current devices in the market do not support those optional APIs). We also decided to use a binary protocol since it is more compact and more efficient for binary data, instead of XML.

We also wanted to control how the network was reached and do it in a very simple way.

The library contains three main blocks: Net, Binding and RemoteCall.

Net has all the needed constants, and also some networking wide configuration settings. It also has a checkNetwork method that will allow you to check if you have signal and if your remote server is up and running.

The synchronization engine uses the deviceGuid and deviceId settings to perform simple authentication. Those settings are sent from the server to the device when the user successfully authenticates in our system using the company name, user name and password.
You can use them for your own purposes, or you can ignore them, they are not really needed. If not set, they will be sent as an empty string and 0 respectively to the server in the remote call protocol.

The checkNetwork method provides also a small example of RemoteCall usage, as it calls a remote Object called “LoginHandler” to a method called “ping”. That checks if our server is up and running. If it can not make the call, it checks if it can read the home page of yahoo (you could put any other well known service). That is used to check if the previous error was due to the server being down or to the lack of network connectivity (we assume yahoo is up :) ).

final RemoteCall rc = new RemoteCall(
    "LoginHandler", // remote object name
    "ping",         // remote object method name
    0               // number of parameters
);
rc.invoke();

The RemoteCall class allows you to set a default url to call, so you can later just call the no argument version of invoke, but you can also provide an url for each call using the other version of invoke.
In the previous example, the Net class assumes that you have previously set the defaultURL property in the RemoteCall class. That should be done at application startup.

The RemoteCall class sends a binary stream to a remote url, using a the POST method through the Binding class. RemoteCall will try to invoke the remote method up to MAX_RETRIES (currently 5) times if there’s a network error (not if the server returns an error), providing you with a level of network security (mobile networks can be very error prone).

The protocol is very simple, and it uses the openbasemovil-core serialization tools to send and receive the data, so complex objects can be sent and received (anything that can be serialized through the SerializerOutputStream).
It is already present as a comment in the code, but I will put it here:

Device request:
 
(data:
{byte       version}        // RPC version, currently 2
{byte       encryption}     // Encryption: 0 - none, 1 - Blowfish
{String     deviceGuid}     // Device Globally Unique Identifier
{long       deviceId}       // Device remote id
{String     object}         // Name of object to call
{String     method}         // Object method to call
{byte[]     parameters}     // Parameters serialized using
                            // SerializerOutputStream
                            // writeNullableObject method
)
{String     "END_OF_DATA"}      // Constant text to identify
                                // data boundary
{long       CRC}                // Adler32 CRC code of the data
 
Server response:
 
{int        responseCode}       // Result of the method call
{String     responseMessage}    // Result message
{byte[]     responseData}       // An object serialized using
                                // SerializerOutputStream
                                // writeNullableObject method
 
responseCode can be one of:
 
0 - RC_SUCCESS
Everything went fine
1 - RC_INVALID_OBJECT
The requested object is invalid
2 - RC_INVALID_METHOD
The object has no method with the requested name
3 - RC_NOT_ALLOWED
The caller is not allowed to execute the requested method
4 - RC_INVALID_ARGUMENTS
The arguments passed are invalid
5 - RC_INVOKATION_EXCEPTION
The method produced an exception when invoked
6 - RC_INVALID_CRC
The CRC of the data sent is invalid

So you can code a Servlet (or whatever) in your server, handle the post request, and parse the data sent using the openbasemovil-core SerializerInputStream class. Then is your turn to locate the object, the method, make sure you want the device make that call, make the call, and finally send the response back using the SerializerOutputStream class.
For the response, the responseCode and responseMessage are mandatory, and if the call is successful then the responseData is also mandatory.
responseData will be read by the device using SerializerInputStream.readNullableObject.

Your server side code should check that after the incomming data the END_OF_STREAM string si found and also the CRC code. And you should also perform the CRC checking using the openbasemovil-core Adler32 class, to make sure that everything arrived ok.

A bit more complex example of RemoteCall use, calling a remote object called “MyServer”, to a method called “sendImage” which receives three paremeters, a String, a byte array, and a Vector of String objects.

// Somewhere in your code at startup you will set the default URL
RemoteCall.setDefaultURL( "http://myserver/rpc" );
 
// Now we will make the call
/**
 * Send an image to the server.
 * @param name image file name
 * @param data image raw data
 * @param attributes image attributes, a collection of Strings
 */
public Long sendImage(
                 final String name,
                 final byte[] data,
                 final Vector attributes
)
    throws RemoteCallException
{
    final RemoteCall rc = new RemoteCall(
                                   "MyServer",
                                   "sendImage",
                                   3
    );
    rc.setParameter( 0, name );
    rc.setParameter( 1, data );
    rc.setParameter( 2, attributes );
    return (Long) rc.invoke();
}

The RemoteCall method uses the Binding class to actually call the remote server with a POST method.

The Binding class provides an easy and extensible way to abstract you from the real method used to make the call. It also controls all the open bindings, allowing you to close them all at once to make sure that there’re no connections open.

Binding is an abstract class that by default uses the provided sublcass HttpBinding. As you can imagine, the HttpBinding class uses the javax.microedition.connection to actually create an http or https connection.

With the Binding framework you could create other Binding subclasses and use other means for connecting to the network. For example, in future versions we will provide a BluetotthBinding and a Java SE Proxy. With them you will be able to connect your phone through bluetooth using the proxy running on a PC. And everything will work exactly the same.

To create a new Binding class and use it you simply need to subclass Binding, implement the needed methods, and then set it as the binding factory with:

// For CLDC 1.0
Binding.setFactory( new BluetoothBinding().getClass() );

or

// For CLDC 1.1
Binding.setFactory( BluetoothBinding.class );

This introduction to the networking part of OpenBaseMovil will be included in the next revisions of the documentation.
We look forward for your comments to enhance and clarify it before it is actually included.

BlogLines del.icio.us Digg Facebook Google Google Reader Yahoo! MyWeb Newsgator Newsvine reddit SlashDot StumbleUpon Technorati