Inspirel banner

Programming Distributed Systems with YAMI4

6.3.3 Java

The following example is an extract from the calculator server that accepts the message from the client and computes the sum and difference of two numbers provided in the message payload. The message handler needs to be registered in the server-side agent so that incoming messages can be properly routed to it.

class Calculator implements IncomingMessageCallback {
    @Override
    public void call(IncomingMessage im) throws Exception {

        Parameters params = im.getParameters();

        int a = params.getInteger("a");
        int b = params.getInteger("b");

        Parameters replyParams = new Parameters();

        replyParams.setInteger("sum", a + b);
        replyParams.setInteger("difference", a - b);

        im.reply(replyParams);
    }
}

In the above example the call() function is a callback implementation that is invoked by the agent whenever there is an incoming message addressed to the logical object for which the handler was registered. The callback has to be part of a user-provided class that implements the IncomingMessageCallback interface.

The im parameter of the call() function refers to internal agent's structures and allows to initiate further communication that is needed to send the reply or rejection to the originating client program. Several operations can be executed on this message object and in this example the parameters object that was received as part of this message's payload is inspected with the getParameters() function. Later, the reply is prepared based on the incoming parameters - in this example the server reads two values and computes their sum and difference and inserts both result values into a single parameters object that becomes the reply payload. After the reply() function is called on the incoming message object, the processing is completed and the agent can proceed with transmission of the reply to the client.

The above pattern is the most fundamental idiom for server-side processing of incoming messages and can be characterized by the fact that the complete message processing is contained in the scope of the callback invocation.

It is also possible to move the state of incoming message outside of the callback by simply copying the incoming message reference to another variable. This allows the server to process the incoming message asynchronously and outside of the handler callback.