A Glimpse into SMILE Programming

businessunknownInternet and Web Development

Nov 12, 2013 (4 years ago)

218 views







A Glimpse into SMILE Programming

Version

1.0
,
December

2007


S. Salsano
(1)
,
G. Bartolomeo
(1
)
,
R
.
Glaschick

(2
)

(1)
University of Rome “Tor Vergata”

{
stefano.salsano
, giovanni.bartolomeo}
@uniroma2.it

(1)
Siemens C
-
Lab

rainer.glaschick@c
-
lab.de



Available
at:
http://netgroup.uniroma2.it/twiki/bin/view.cgi/SMS/TechnicalReports


DISCLAIMER

This
work has
been performed in the context of the EU funded IST Simple Mobile Service
project
(http:www.ist
-
sms.org), but

it does not necessarily represent the official p
osition of
the project itself and of its partners. Authors are solely

responsible

for
the views, results and
conclusions contained in this
work.


COPYRIGHT

"Copyright and all rights therein are retained by authors. This work may not be modified or
reposted

without the explicit permission of the copyright holder"



Context definition and handling in the

S
imple Mobile Services architecture



Page
2

of
22

Table of Content
s


1

INTRODUCTION

................................
................................
................................
................................
........

3

2

A DEEPER LOOK INTO A
SYNCHRONOUS MESS
AGING AND SYNCHRONOU
S CALLS

.........

7

3

A SAMPLE APPLICATION

................................
................................
................................
.....................

12

3.1

H
ELLO
S
ERVER

................................
................................
................................
................................
..........

12

3.2

H
ELLO
C
LIENT

................................
................................
................................
................................
...........

15

4

APPENDIX A


SMILE ON MOBILE PHON
ES

................................
................................
...................

18

5

REFERENCES

................................
................................
................................
................................
...........

21













Context definition and handling in the

S
imple Mobile Services architecture



Page
3

of
22

1

Introduction

SMILE is a very lightweight execution and communication framework, based on an
application
-
level peer
-
to
-
peer communication paradigm which facilitates the development of
distributed application. This kind of frameworks are in general called

“middleware”; what
however differentiates SMILE from other middleware platforms is that, rather than being a
“specific” middleware (e.g. rather than exploiting a given communication protocol, discovery
mechanism or data
-
serializer), it defines an abstract

layer, providing the developer with a total
insulation of their applications with the underlying concrete middleware platform. SMILE is
based on the notion of abstract platform [ref] and defines its own abstraction primitives for the
following issues:



Com
munication between peers



Peer identification



Discovery mechanism



Peer Lifecycle management

In the following we take a look at each of the aforementioned points.

1.1

Communication Primitives

Each SMILE peer is an entity which may communicate with other peers in

two ways: by
sending asynchronous independent messages or by using a synchronous remote procedure
call. This has been taken from an understanding of the original purpose of the Web Service
Definition Language (WSDL) which defined an abstraction language
to describe the interfaces
provided by Web Services and bring their development closer to SOA principles.
Unfortunately, the original goals were lost and nowadays WSDL and Web services are seen as
a synonym of SOAP. Whereas it is evident that SOAP is the m
ost widely accepted standard
for Web Services (even to overload the acronym SOA’s meaning as “SOAP Oriented
Architecture), the original purpose of WSDL was to be an abstract language, whose
applications could be implemented using a number of different bind
ings. SMILE did borrow
and emphasize this concept and even the terminology. As we’ll say, a “binding” represent a
link between an abstract definition of the application and a concrete technology to rely on
which implement the abstract primitives provided b
y SMILE itself.

Without going into a more detailed argumentation about the use of SOAP versus new trends
in the Internet for a lighter infrastructure (see for example JSON as an alternative of XML,
Web2.0 application using asynchronous Java scripts in the
client against BPEL logic

Context definition and handling in the

S
imple Mobile Services architecture



Page
4

of
22

execution on servers and so on), we describes the basics four interaction patterns provided by
the original WSDL definitions
1
.

A WSDL service is composed of a number of related “sub
-
services”, called porttype. Each
porttype group

a number of logically related operations. There are four kinds of operations,
classified according to the originator and the executor of the operation; the WSDL
terminology refers these latter as client and server, as follow:



A OneWay operation consists i
n a message originated by the client toward a server. The
message is sent asynchronously, no “session” is created between the client and the server.



A RequestResponse operation consists in a request message from the client to the server,
followed by a repl
y message (“response”). There is a logical correlation between the
request and the response, meaning that the execution environment should provide the
response in an unambiguous way as reply to a given request. Alternatively, a “fault
message” may come to
the client if something has gone wrong at the server side. Typically
this is implemented in a synchronous call, i.e. after sending the request, the client stays
blocked till the response comes.

The second pair of operations are complementary to the first o
ne; the originating is the server
as follow:



A Notification operation is made of a message sent asynchronously by the server to a
client, no “session” is created between the client and the server.



A SolicitResponse operation consists in a solicitation mess
age sent from the server to the
client, followed by a reply message (“response”) in the opposite direction. Solicitations
may originate fault as well and the execution environment should take care of correlation
between solicitation, response or fault mess
ages.

As we’ll see, SMILE reflects this classification providing primitives to send asynchronous
message as well as to perform synchronous calls.

1.2

SMILE Peers, SMILE Processes and Identifiers

Building application on an abstraction layer like SMILE, each app
lication is abstract as
well.In order to make it work, it needs a “binding” to a concrete middleware platform. Each
SMILE peer therefore must be bound to at least one running process. A process is an
implementation of SMILE abstract primitives in a middlew
are specific platform (henceafter
referred as “binding”). The same SMILE peer can be bound at more than one process. We use
the term multibinding to refer to a SMILE peer which keeps than one binding. It worth to be
noted that these processes may belongs t
o the same or to different bindings as well, enabling
cross messaging among different middleware platforms.




1

We base this description
on WSDL 1.1 specifications.
TDB
-
describe why


Context definition and handling in the

S
imple Mobile Services architecture



Page
5

of
22

Each process has its own address, which is an instance of a class inheriting from ProcessID
(e.g. RMIProcessID, SIPProcessID). A multibound peer kee
ps one address for each bound
process.

Like a single bound peer, a multibound peer uses the Yellow Page service search operation to
retrieve the contact point of other processes exposing a given service. However, in a
multibinding environment the search op
eration extends its scope to every binding and
therefore returns an array of ProcessID, each element of this array is an instance of a class
inheriting from ProcessID.

The same way, a multibound peer uses the publish operation to register its services and
the
publish operation extends its scope to every binding. The same published service will be made
available through a number of different contact points, one per binding.

E.g. Let’s suppose the “MeteoService” peer is a twice
-
bound peer, using the SIP bind
ing and
the RMI binding. Once the MeteoService publishes its service, the service is registered twice,
i.e. in both the SIP infrastructure and the RMI infrastructure, obviously with different
addresses, like the following ones

sip
://metoservice
-
1@sipbind
ing.it

and
RMI://myhost:1029/meteo
-
service
-
1

Let’s now suppose a twice
-
bound client (with SIP and RMI bindings) looks for the
MeteoService using the SMILE search primitive: the client will find two contact points: one
provided by SIP and one more by RMI. F
urthermore, this means that the MeteoService could
be found and contacted by SMILE single
-
bound peer using either the SIP binding or the RMI
binding.

Unfortunately, this introduce a degree of ambiguity, because there is no way to know whether
two identifi
ers related to two different bindings refers to the same peer or not. This could be a
problem for some use cases. Assume, for example, that one peer has to multicast a message to
a number of others, whose ProcessIDs have been obtained through the search()

operation.
Let’s assume that one of target peer is bound to two processes as aforementioned. The search
operation will return more than one ProcessID for the same process. When doing multicast,
the same peer will receive the message twice, one for bindin
g; In some circumstances this
could be not acceptable, even if it could be solved at application level, a general mechanism
allowing to understand whether two process identifiers belongs to the same peer is needed.

A proposed solution is the following:



Eac
h SMILE peer will be provided by an Unique Identifier UUID generated according
to well known rules in peer to peer environment [ref] which allows to assign unique
identifiers in a distributed way (locally on the peer), avoiding conflicts.

The UUID could be

integrated as a reference
-
subfield inside each ProcessID, so that the
association between the two IDs will be permanent.

1.3

Discovery Mechanisms


Context definition and handling in the

S
imple Mobile Services architecture



Page
6

of
22

A peer may discover other peers using registration and lookup facilitations offered by the
SMILE API. This way, i
t is possible to write complex applications. A 3
rd

party application is
an application developed by 3
rd

party developers using SMILE APIs and may involve one or
more SMILE process.

Currently a basic discovery mechanism is implemented in SMILE. The discove
ry facilitations
are related to the functional features provided by each peer. We call this discovery facilitation
“Yellow Pages” services. Following SMILE characteristics, the “Yellow Pages” is not a
concrete entity, i.e. there is not necessary a single n
ode implementing a repository of peer
provided functionalities; instead it is an abstract model and the underlying implementation is
not defined: it may be a single node, a distributed community of repositories, an advertisement
based mechanism like in JXT
A or any other discovery mechanism. In any case, services
provided by peers are described in the following format:



A service type, corresponding to the wsdl definition of “porttype”



For each service types, optionally, it is possible to specify the related
implemented
operations (corresponding to wsdl “operation” element

Each peer is provided with the following set of discovery primitives to interact with the
Yellow Pages service:




publish() is used to publish the service description



delete() is used to remo
ve the aforementioned description from the Yellow Pages



search() is used to find peers providing a given service; it returns an array of identifiers
corresponding to the peers providing this service. This search is performed using simple
matching between a

template (DescriptorFilter) and the published services; in addition it is
possible to specify that only a given a subset of peers is returned, e.g. matching a given
name criterion in their identifier or simply returning only a certain specified number of
results.

Normally the publication is made once at the beginning of the peer lifecycle and is cancelled
once the peer ends. Nevertheless, sometimes it could be useful to interact with the Yellow
Pages also during service execution. Reasons to do this includ
e temporary service
unavailability or publication of new offered services. In any case, the programmer should take
care that no more valid service publications are removed from the Yellow Pages, in order to
prevent client requests to fail.

1.4

Peer Lifecycle

E
ach SMILE peer can be decomposed into two parts: a message answering part and a
sequential application part.

The message answering part is totally event driven. The messages are unsolicited, i.e. can
arrive at any time during the lifetime of the SMILE pro
cess, and independent, as they arrive in

Context definition and handling in the

S
imple Mobile Services architecture



Page
7

of
22

no specified order. Using asynchronous messages, it is not assured that messages arrive in the
same order as they’ve been sent. Furthermore, even message delivery is not guaranteed (every
binding has its own setting
s for timeout and retransmission of not delivered messages). In this
case, the third party application implemented over the SMILE layer shall take care of assuring
consistency. Using the remote procedure calls, instead, a confirmation of the reception of t
he
request is implicit in the receiving of the answer (or of a fault message); however, this way the
sending process is blocked till the response or a fault arrives.

The sequential application part is used to implement a sequential programming logic, that
allows SMILE peers to communicate with the user (e.g. managing a GUI), to send messages
to other SMILE processes, or use any other functions or services of the operating
environment. The sequential part is made up of three phases: setup phase, typically us
ed to
allocate resources, register services or lookup for remote services; business logic execution
phase, in which the process executes its own processing (especially background processing
fits into this phase, as clarified with an example in section
Error! Reference source not
found.
); takedown phase, useful to release and dispose the allocated resources and un
-
register
published services. The third party application developer controls the sequential part by
implementing the callbacks setup(
) dobusiness() and takedown(), coming from the
ProcessLifecycle interface, which every SMILE process has to implement
.

2

A Deeper Look into Asynchronous Messaging and
Synchronous Calls

Though SMILE was originally born as a simple, message passing library, th
ere are a number
of reasons which induced us to provide the developer with a ready to use support for
synchronous call
2
. In this paragraph, we elaborate a bit more on the difference between
synchronous calls and asynchronous message passing. With simple me
ssage passing, the
sender should not assume nothing except that the SMILE framework will do its best to deliver
the message to the intended recipient, provided the recipient is reachable at the time of
sending
3
. Note that the sender has no way to know whet
her the message has been actually



2

In this discussion between synchronous calls and asynchronous messages, we see analogies with transport
protocols.
While UDP is much more elegant and efficient than TCP, most applications use TCP, because the
glue
code needed to write reliable applications using UDP is re
-
invented each time, and nearly always the problems
and inefficiencies with TCP are less critical than those re
-
inventing a good UDP driver.

3

SMILE does its best in order to deliver asynchron
ous messages. All RPC oriented bindings guarantee reliable
delivery of messages. Other bindings, which are based on unreliable transport (e.g. JXTA pipes or SIP messages)
are enhanced with retransmission mechanisms which ensures that the message will be de
livered to the intended
recipient within a given amount of time. Please note however that these mechanisms don’t necessary assure that
the order in which asynchronous messages are sent is also the one followed to deliver them. Timeouts and
retransmissions
may alter the sequence and fail to deliver messages in the correct order. Furthermore, they don’t
even assure that the message is delivered, as after a timeout expires, no retransmission is performed.


Context definition and handling in the

S
imple Mobile Services architecture



Page
8

of
22

delivered or not, as the send() method returns immediately, without waiting for a confirmation
of the delivery. Therefore, if asynchronous message is used and a confirmation of the
reception is required, it is the 3
rd

part
y application that must take care of assuring this by
sending back a message containing the confirmation.

We come here at an important conclusion: there is a deep difference between asynchronous
messaging and synchronous calls. Whenever a confirmation of d
elivery is required,
asynchronous message is not the best solution, unless complemented by explicit
acknowledgement messages.

A similar issue also applies to the request
-
response pattern, being the sent back response
logically similar to a confirmation (an
d even sometimes used as a confirmation). In this case, a
synchronous call is better than exchanging two simple, asynchronous messages. In order to
understand why, let’s ask us w
hat happens e.g. if the response message does not arrive
(timeout) or more tha
n one response message arrives.
The latter may happen if, after a
timeout, the request is resent, and then both replies, i.e. the one that was assumed to be lost
and the second one, arrive shortly in a row. This also can happen if another (similar) request

is
sent, and the (unreliable) server answers again. Also, the response to the first request, that was
stuck in the network, may be delivered together with the response to the second request. Also,
a malicious intruder might generate extra response message
s (a technique known as
“injection”); provided that the client application doesn’t check the identity of the response
originator, a security risk arises here.

2.1

Solutions for Correlating Request and Response (or
ACK
) Messages

In the following we discuss a n
umber of mechanisms from the literature used to correlate a
request message to a response message are described.

2.1.1

Option "Nonce"

A linking nonce
4
, directly supported by SMILE, is one option . This is simply copied by the
server from the request, to the rep
ly. In this case, the thread that sends the request would send
this nonce to the
onReceived
callback (in a thread safe manner), and the latter rejects any other
incoming messages. A general implementation would use a queue, but many applications
could live

with a queue of length 1. This also eliminates several exception and error
conditions.






One should refer to the specific binding documentation
for more details about number of retransmissions,
timeouts and message order preservation. However, the general recommendation is to use asynchronous message
only when message loosing is not critical, e.g. in case of real
-
time or streaming applications.


4

A nonce (coined by Roger Needham) is an unpredictable token only used once (within a practiaclly infitinite
time interval). Often, (pseudo) random numbers are used as nonces.


Context definition and handling in the

S
imple Mobile Services architecture



Page
9

of
22

For practical reasons
5
, a random number can be used instead of a real nonce. The probablilty
that the same random number is generated within 24 hours of continuous oper
ation should be
less than once a decade, i.e. 1/3600.

2.1.2

Option "Checksum"

Instead of a true nonce, a proper checksum, calculated in the sender, might be an alternative.

However, this has the drawback that two request message may have the same
6

checksum, and
as a consequence, the same checksum will be copied in the responses. This is not a problem if
the server delivers always the same response if fed by the same request (stateless server), but
this is not true in the general case, i.e.for stateful servers.

It

would be best to have SMILE calculate the checksum, and no bother the application. If the
sender must alert the receiver for the message coming, the checksum is needed before send, as
to avoid race conditions. If SMILE is also filtering the incoming mess
ages, a checksum may
be used.

2.1.3

Option "Serial Number"

Because the "only used once" property of a nonce is required from a functional view, a serial
number could be used insted. An unpredictable number, however, reduces the chances for
intruders to send me
ssages that cannot be easily detected as wrong.

2.1.4

Option "Serial Number+Random Number"

Clearly the best would be a serial number, concatenated to a random number. Because each
message is instantiated just before sent, is has normally not a chance to maintai
n serial
numbers, which would add much complexity for small value. If, however, SMILE wraps this,
serial numbers should not be the problem.

2.1.5

Option "Request Copy Included"

In case of pure stateless server, the reply could contain all the request data inste
ad, so that the
sender can verify that the reply is indeed an answer to the outstanding request. In this case, no
request
-
response linking is necessary. However, the verification of the incoming message
requires significantly more effort, and could thus m
ake denial
-
of
-
service attacks more
dangerous.

Normal server authentication by signing the reply also needs either a copy of the request data
(if stateless) or a request serial number, so that a context is established. If challenge
-
response
authentication i
s used, the underlying security layer can assure that the response belongs to the



5

But keep in mind that WEP was buggy also because of insufficient randomness.

6

"Same" does not mean identical, but with a delta which is below the uncertaincy of the data, e.g. noise.


Context definition and handling in the

S
imple Mobile Services architecture



Page
10

of
22

reply. In this case, this Information can either be transferred to SMILE, or SMILE must ensure
it itself.

2.2

Providing SMILE with a Synchronous Call Support

In theory, the afore
mentioned mechanisms might be implemented by each third party
application which wants to provide correlation between its request and response messages.
But, as stated in [refWSDL], the request
-
response pattern is so common that we realized that
the request

response pattern had to be integrated into SMILE as a primitive service.

Before proceeding, we should however understand one important concept.
There are bindings
which are RPC oriented (CORBA, RMI, HTTP, Spring Remoting mechanisms) and bindings
which, ye
t providing communications between distributed nodes, don’t provide any RPC like
facilitation
7
.

Obvious claims are the following:



It is trivial to implement the request
-
response pattern on a RPC oriented environment



It is trivial to emulate SMILE asynchron
ous message exchange on a RPC oriented
environment (just implement the
send()

method as a remote call to the
onReceived()
callback



It is straightforward to implement SMILE asynchronous message exchange in not RPC
oriented environments



It is a bit more comp
lex to implement the request
-
response pattern in not RPC oriented
environments. Mechanisms such as those described in section
Error! Reference source
not found.

are to be used.

Focusing on the last point, we should note here that the request
-
response pattern

may be
implemented in not RPC oriented environment as following:



Each message has a serial number that is automatically generated whenever the object
message is instantiated. It may be changed before the message sent. Also, if SMILE does
the complete prot
ection for the request
-
response pattern, SMILE may modify the serial
number, e.g. inserting a serial, during
send

(see below).




7

This is the case of JADE which has a message oriented, but reliable interface
-

this is because message
exchange is emulated over RPC oriented proto
cols
-

and SIP which instead provides only asynchronous
messaging, augmented by a delivery
-
confirmation mechanism. In JXTA unicast and propagate pipes are, as the
specification says,
unreliable
, but the actual behavior depends on the concrete protocol they
’re implemented with;
mostly JXTA implementations are done using TCP, and therefore they are reliable.


Context definition and handling in the

S
imple Mobile Services architecture



Page
11

of
22



Each message has a
refSerial

field, to which, in case of reply message, the server copies
the serial number of the request it ans
wers. Unsolicited messages have
refSerial

equals to
zero.



The constructor for reply messages accepts the request message as parameter, and copy the
serial number into
refSerial

of the new message. If further security functions are desirable,
they can be in
serted without code changes of the applications, in particular if
cryptographic chain authentication is to be added.



A boolean query method
refersTo

tells if a reply refers to a request sent and ignores all
incoming messages that do not refer to the outsta
nding one.



Cryptographic authentication of servers could be transparently done this way, with the
refersTo

method returning false if the reply is not authentic.

To implement the request
-
response pattern as a service offered by SMILE, SMILE supports a
guar
ded wait for clients without disturbing the general message
-
passing only paradigm. In
particular, SMILE itself disposes of all messages out of order as described in the following
steps:



A method
expectMessage

allows to register the message number or reply
number to
expect. This should be called immediately before
send

(or as an option to
send
).



After sending the request, the sender does message cleanup and then call a SMILE
wait
method
, specifying a timeout. This block the sender for a while, and make the
call
synchronous. Timeout expiration will throw an exception and clears the
expectingMessage

state too.



Once the right message arrived, the
expectingMessage

state is cleared, and then a callback
is called to deliver the response message to the applicatio
n.



SMILE returns from the
wait

after the receive callback has returned. Thus, the
programmer needs not to care for thread safeness, because both threads are mutually
exclusive without further concern.

To summarize, the following operations are executed:



B
efore a request message is sent, all received response messages are discarded.



Sending a message may update the serial number and registers a single response for
reception (method
expectMessage
)



SMILE turn the application into a
wait

state.



The
wait

return
s normally if the callback for the receive message returns normally, i.e. a
matching response message is received.


Context definition and handling in the

S
imple Mobile Services architecture



Page
12

of
22



Otherwise, a timeout exception is raised.


3

A Sample Application

This section describes a sample application implemented using SMILE, consist
ing on one
client and two servers, friendly named “Donald” and “Frank”. The servers provide a simple
“time
-
service”, i.e. a service which, once subscribed, sends a time notification every five
seconds. In this example, the client performs a query to the Ye
llow Pages services in order to
obtain references to the registered servers, contacts one of them and subscribes to its time
-
service. As a result, the client gets back a number of notifications from the server.

This example illustrates:



how to startup a S
MILE process and assigning a binding



how to manage
the SMILE process lifecycle



how to publish service
s into the Yellow Page services



how to discover registered services, using filters on offered ser
vice type and provider
identity



the usage of synchronous c
al
l and asynchronous notification

3.1

HelloServer

Take a look at the HelloServer

implementation:

package it.uniroma2.smile.test;


import it.uniroma2.smile.core.*;


import java.util.Date;

import java.util.Vector;


public class HelloServer extends SMILEPeer {



public final static String SERVICE_TYPE="HelloService";


public final static String[]
OPERATIONS_TYPE={"HelloSubscribeOperation","HelloNotifyOperation"};


public final static String
A_REQ_MESSAGE_NAME=SayHelloSubscribeRequestMessage.class.getName(
);


public final static String
A_RESP_MESSAGE_NAME=SayHelloSubscribeResponseMessage.class.getName();


public final static String
A_NOTIF_MESSAGE_NAME=SayHelloNotificationMessage.class.getName();




private String myName;


private Descriptor d;


pr
ivate Vector subs;





Context definition and handling in the

S
imple Mobile Services architecture



Page
13

of
22


public HelloServer(String name) {



super();



myName=name;



subs=new Vector();


}




public Message onRequestReceived(ProcessID sender,Message request) {


log("received request from "+sender);



if (request.getName().equals(A_REQ_MESSAGE_NAME)) {




subs.add(sender);




log("subscription accepted");




return new SayHelloSubscribeResponseMessage();




} else {




log("message not understood");




return new

DefaultFaultMessage("Request not understood!");


}


}




public void setup() {


d= new Descriptor();


d.setType(SERVICE_TYPE);


d.setOperation(OPERATIONS_TYPE);


try {




publish(d);



}

catch (MalformedDescriptorException e) {




// TODO Auto
-
generated catch block




e.printStackTrace();



}



log("Published service "+SERVICE_TYPE);





}



public void takedown() {



delete(d);



log("Service "+SERVICE_T
YPE+" deleted from the YP");


}





public void doBusiness() {



//send notifications every five seconds for 8 times



for (int i=0;i<8;i++) {



try {





Thread.sleep(5000);




} catch (InterruptedException e) {





// TODO Auto
-
generated catch
block





e.printStackTrace();




}




SayHelloNotificationMessage notif=new
SayHelloNotificationMessage();




notif.setHello("hello from "+myName+" local time is "+new
Date());




ProcessID recipient;




for (int j=0;j<subs.size();j++) {





try {






re
cipient=(ProcessID)subs.elementAt(j);






log("sending (asynchronous) notification to
"+recipient);






this.send(notif, recipient);






log("notification sent");










} catch (InvalidReceiverAddressException e) {






// TODO Auto
-
generated catch b
lock






e.printStackTrace();





}




}



}








}



public void log(String s) {


Context definition and handling in the

S
imple Mobile Services architecture



Page
14

of
22




System.out.println("["+myName+"] "+s);


}

}


First, we extend the base class which all SMILE processes have to derive from,
SMILEPeer
:

Public class HelloSer
ver
extends

SMILEPeer

Then
, we implement the
setup()

callback, which is the right place to create a descriptor to
store information about the offered services, and to publish it on the Yellow Pages:

Public void setup() {


d=new Descriptor();


d
.setType(SERVICE_TYPE);


d.setOperation(OPERATIONS_TYPE);


try {



publish(d);


} catch (MalformedDescriptorException e) {



// TODO Auto
-
generated catch block



e.printStackTrace();


}


log("Published service "+SERVICE_TYPE);





}


Then, we implement the
takedown()
callback, because we have to remember to deregister the
offered service when the SMILE peer dies:

Public void takedown() {



delete(d);


log("Service "+SERVICE_TYPE+" deleted from the YP");

}

Now, we implement the
doBusiness()
callback. Since the HelloServer has to send
asynchronous notifications to all registered clients, we put here the business code which
implements this function:

public void doBusiness() {


for (int i=0;i<8;i++) {



try {




Thread.sleep(5000);



} catch (InterruptedException e) {




// TODO Auto
-
generated catch block




e.printStackTrace();



}





SayHelloNotificationMessage notif=new
SayHelloNotificationMessage();



notif.setHello("hello from "+myName+" local time is "+
new Date());





ProcessID recipient;



for (int j=0;j<subs.size();j++) {




try {





recipient=(ProcessID)subs.elementAt(j);





log("sending (asynchronous) notification to
"+recipient);





this.send(notif, recipient);





log("notification sent");








} catch (InvalidReceiverAddressException e) {





// TODO Auto
-
generated catch block





e.printStackTrace();




}



}


Context definition and handling in the

S
imple Mobile Services architecture



Page
15

of
22


}







}


Every five seconds, and for eight times, the HelloServer constructs a
SayHelloNotificationMessage

containing the curren
t date and time, and sends it to the
previously registered clients, through the
send()

method. This method offers an asynchronous
and unrelilable channel to interact with another SMILE process, and suits well for the purpose
of sending a notification to a
subscriber client; no errors or exception is raised if the receiving
process is dead, if it has a problem handling the message, or in any other case. As we’re going
to say, a reliable delivery can be obtained usingd the
sendRequest()

method instead of the
send()

method, obtaining this way a confirmation of reception.

Finally, we implement the
onRequestReceived()

callback; this is called whenever a message is
received through the
sendRequest()

method. The latter method offers a synchronous and
reliable chann
el to interact with another SMILE process; the receiver process, in fact, can
directly reply with a message (it can be a response, a simple acknowledgement, or an error),
and the sender is notified in case of error. Since the HelloServer has to accept subs
cription
requests from clients, and at the same time the clients have to rely on these requests to be
fulfilled, the HelloServer replies the
SayHelloSubscribeRequestMessage

with a
SayHelloSubscribeResponseMessage
:

public Message onRequestReceived(ProcessID

sender,Message request) {


log("received request from "+sender);


if (request.getName().equals(A_REQ_MESSAGE_NAME)) {




subs.add(sender);




log("subscription accepted");




return new SayHelloSubscribeResponseMessage()
;




} else {




log("message not understood");




return new DefaultFaultMessage("Request not understood!");


}

}


W
e check whether the message name matches “SayHelloSubscribeRequestMessage”; in this
case, we add the sender to

the list of subscribers, and return a
SayHelloSubscribeResponseMessage
; on the contrary, we return a
DefaultFaultMessage
.

Just for clearness, the same result could be reached using a couple of asynchronous
send()

methods to deliver the messages instead of

relying on the
sendRequest()

method, but this way
nothing is assured: nor the delivery of the request message to the server, nor the delivery of
the response, nor the correlation between request response (the developer should in this case
implement a corr
elation mechanism, e.g. a message identifier, in order to avoid that in case of
multiple request one response is taken as response of a wrong request
. A deeper analysis is
proposed in section
Error! Reference source not found.
).

3.2

HelloClient

Here is the HelloC
lient implementation:

package it.uniroma2.smile.test;



Context definition and handling in the

S
imple Mobile Services architecture



Page
16

of
22

import it.uniroma2.smile.core.*;


public class HelloClient extends SMILEPeer{




public final static String SERVICE_TYPE="HelloService";


public final static String[]
OPERATIONS_TYPE={"HelloSubsc
ribeOperation","HelloNotifyOperation"};


public final static String
A_REQ_MESSAGE_NAME=SayHelloSubscribeRequestMessage.class.getName();


public final static String
A_RESP_MESSAGE_NAME=SayHelloSubscribeResponseMessage.class.getName();


public final

static String
A_NOTIF_MESSAGE_NAME=SayHelloNotificationMessage.class.getName();




public HelloClient() {



super();


}




public void onReceived(ProcessID sender,Message message){


log("received notification from "+sender);



if (message.getName().equals(A_NOTIF_MESSAGE_NAME)) {




log("
\
""+((SayHelloNotificationMessage)message).getHello()+"
\
"");


} else {




log("message not understood, message name is "+message.getName());


}


}





public void setup() {




log("process started");




}




public void takedown() {



log("process finished");


}



public void doBusiness() {



DescriptorFilter d= new DescriptorFilter();



d.setType(SERVICE_TYPE);



//un
-
commentin
g the following line will cause that only processes
whose



//PIDs matches with "Donald" (e.g. "Donald_bnding_RMI") will be
returned as a result of the



//search() operation



d.setMatchingPID("Donald");



//



log("Searching for "+SERVICE_TYPE+" provi
ders...");



ProcessID[] pID=search(d);



log("[HelloClient] Found "+pID.length+" process(es)");



if (pID.length!=0) {




//choose one provider




ProcessID providerPID=pID[0];




log("[HelloClient] Sending subscribe request to
"+providerPID);







SayHelloSubscribeRequestMessage req= new
SayHelloSubscribeRequestMessage();




SayHelloSubscribeResponseMessage res;










try {





res=(SayHelloSubscribeResponseMessage)doRequest(req,providerPID);




} catch (InvalidReceiverAddressException e) {







e.printStackTrace();




} catch (ClassCastException e) {









log("Invalid subscription response. This process
will end.");




} catch (Fault e) {





log("Received a fault message from the provider");


Context definition and handling in the

S
imple Mobile Services architecture



Page
17

of
22




}




//wait 30 seconds for the notifications,

then shutdown




log("waiting 1 minute for notifications...");




try {





Thread.sleep(60000);




} catch (InterruptedException e) {





// TODO Auto
-
generated catch block





e.printStackTrace();




}






log("Shutting down now...");



} else {




log
("[HelloClient] No provider found. This process will
end.");



}


}




public void log(String s) {



System.out.println("[HelloClient] "+s);


}


}


The HelloClient code looks quite simple. The interesting points are two: one is the
doBusiness()
callback:

public void doBusiness() {


DescriptorFilter d= new DescriptorFilter();


d.setType(SERVICE_TYPE);




//un
-
commenting the following line will cause that only processes whose


//PIDs matches with "Donald" (e.g. "Donald_bnding_RMI") will be returned as
a re
sult of the search() operation


d.setMatchingPID("Donald");





log("Searching for "+SERVICE_TYPE+" providers...");


ProcessID[] pID=search(d);


log("[HelloClient] Found "+pID.length+" process(es)");


if (pID.length!=0) {



//choose one provider



P
rocessID providerPID=pID[0];



log("[HelloClient] Sending subscribe request to "+providerPID);






SayHelloSubscribeRequestMessage req= new
SayHelloSubscribeRequestMessage();



SayHelloSubscribeResponseMessage res;









try {



res=(SayHelloSubscribeRe
sponseMessage)doRequest(req,providerPID);



} catch (InvalidReceiverAddressException e) {






e.printStackTrace();



} catch (ClassCastException e) {








log("Invalid subscription response. This process will
end.");



} catch (Fault e) {




log("Receiv
ed a fault message from the provider");



}



//wait 30 seconds for the notifications, then shutdown



log("waiting 1 minute for notifications...");



try {




Thread.sleep(60000);



} catch (InterruptedException e) {




// TODO Auto
-
generated catch block




e.printStackTrace();



}





log("Shutting down now...");


} else {


Context definition and handling in the

S
imple Mobile Services architecture



Page
18

of
22



log("[HelloClient] No provider found. This process will end.");


}

}


In this method, the client creates a
DescriptorFilter

object which is used, when interacting
with the Yellow Pag
es, to look for a specific service provided by other SMILE peers. It sets
the service type to “
HelloService
” and the process identifier to “Donald”
,
so only the
processes with the following properties will be returned:



The process must be bound to SMILE pe
ers which have published the “HelloService”
service into the Yellow Pages;



The process identifier must contains the string “Donald” (e.g. “
Donald_binding_RMI”,
“Donald2_binding_RMI”, “myDonald_HTTP”


this one could be possibly an identifier
assigned to an

http binding, and so on)

The
search()

method returns an array of process identifiers which offer the required service
and have the specified name; we chose just the first one of these processes as service provider.

The client therefore subscribes itself t
o the “HelloService”, sending it a

SayHelloSubscribeRequestMessage
” within a
doRequest()

method. As described before, this
implements a synchronous and reliable interaction between SMILE peers, so the client
remains blocked until it receives back a
SayHel
loSubscribeResponseMessage or a Fault from
the server; this way, the client can be sure about the receipt of his subscription request.

NOTE: if a timeout expires, then an
InvalidReceiverAddressException

will be thrown. This
exception may occur for two rea
sons: either (a) because of an invalid process identifier
provided as recipient identifier or (b) because of timeout expiration. The same exception can
be thrown by the
send()

method, but only in case (a): because of an invalid process identifier
provided
as recipient identifier. In fact, the
send()

method provides only unreliable message
delivery and therefore no timeout mechanism is used.

The periodic notifications are sent by the server to the clients through the
send()

method,
because the server doesn’t

need to be sure about the delivery of its messages; so, the client can
handle these messages thanks to the
onReceived()

callback, and prints them on the screen:


public void onReceived(ProcessID sender,Message message){


log("received notification from "+
sender);


if (message.getName().equals(A_NOTIF_MESSAGE_NAME)) {




log("
\
""+((SayHelloNotificationMessage)message).getHello()+"
\
"");


} else {




log("message not understood, message name is "+message.getName());


}

}

4

App
endix A


SMILE on Mobile Phones

In this section we propose an overview of one of the implemented bindings, the JSON/SIP
binding, which
has been used

to port the SMILE framework on mobile
micro
devices

(e.g.

Context definition and handling in the

S
imple Mobile Services architecture



Page
19

of
22

cellphones) using Java J2ME MIDP. Despite in lit
erature there are lots of middleware Java
platforms which have been ported to mobile devices using J2ME MIDP, many of them just
offer a reduced set of the facilitation offered by the original framework (e.g. Jade/Leap,
JXME/JXTA). Instead, our explicit des
ign goal has been to preserve all of SMILE original
functionalities (including messaging and remote procedure calls), so that every 3
rd

party
application written for SMILE would have preserved its portability, running in mobile micro
devices as well (obvi
ously provided the device would offer the needed hardware requirements
in terms of CPU processing, memory, etc. and the application wouldn’t use Java API
unavailable in J2ME).

The first difficulty we faced out was the unavailability of automatic serializat
ion
mechanisms in J2ME. In fact, in order to exchange information between distributed processes,
a serialization mechanism must be employed. In J2SE, a similar mechanism is built in.
Through the use of reflection it is possible to introspect an object, bro
wse its fields and emit a
serialized representation; unfortunately this is not the case in J2ME, and typically the
application developer has to implement his own serialization mechanism for each application.
In our design goals, however, the serialization
mechanism had to be seamless and must be
performed by the framework itself. Section
Error! Reference source not found.

describes
our approach to solve this issue. Despite this approach is suitable for any serialization format,
in SMILE for mobile phones we’ve
chosen the
JavaScript Object Notation (JSON), a
lightweight data
-
interchange format which keeps the advantage of being human readable
though reasonably less verbose than XML, improving performances.

The second issue was due to the presence of NAT and firew
all which blocks peer to peer
communications among mobile devices. Typically this is solved using a persistent TCP
connection between the mobile device and a Proxy in the network; this solution however
requires that a network element (the proxy) keeps stat
e information (the session it is
allowing), resulting in scalability problems when the number of mobile devices contacting the
same proxy increases. In order to transport SMILE messages we used instead an
implementation of the SIP protocol whose overall ar
chitecture is shown in Fig. 2.



Figure
4
-
1

SIP Network Architecture For SMILE





Context definition and handling in the

S
imple Mobile Services architecture



Page
20

of
22

The SIP infrastructure is composed by these entities: the
SIP Registrar

and Proxy
,

which has
the aim
to maintain the mapping between
SIP
user agent identifiers and their IP addresses; the
SIP Session Border Controller

(SBC) representing

intermediary for terminal
mobile
clients
behind NATs;
Relay
, a support for mobile terminals suffer
ing

from limitation in

transmitted
maximum packet size
8
; and finally the
Mobile terminals
, components on which
mobile
applications are implemented.
This infrastructure allows the use of UDP packets to exchange
SIP messages between different mobile terminal, even residing in dif
ferent networks and
behind NATs and firewalls. However, i
n order to turn this
solution

into a complete
middleware solution
compliant with all the functionalities

offered

by SMILE
, we further
elaborate this infrastructure and
implemented
: (1) A

Yellow Page
s

server, whose functionality
is to allow
SMILE
processes to
(un)register their services and look for services offered by
other peers
.

(2) A sliding window mechanism which fragments SIP (UDP) messages
exceeding the MTU provided by the underlying network inf
rastructure, in order to overcome
the fragmentation provided by IP which may result in bad performances and is limited to a
maximum of 64Kbytes. (3) A mechanism to create simple sessions between two peers

in order

to allow synchronous remote procedure call
.





8

In our
tests
, the Nokia 6630 phone has
reported a similar behaviour.


Context definition and handling in the

S
imple Mobile Services architecture



Page
21

of
22

5

References

[1]

P. Grace, G. S. Blair, and S. Samuel, “ReMMoC: A Reflective Middleware to support
Mobile Client Interoperability”

in Proceedings of International Symposium on
Distributed Object and Application (DOA), Catania, Italy, November 2003

[2]

A. Uribarr
en, J. Parra, K. Makibar,I. Olalde, N. Herrasti, “Service Oriented Pervasive
Application Based On Interoperable Middleware”, Workshop on Requirements and
Solutions for Pervasive Software Infracstructure (RSPSI2006), in Pervasive 2006
Workshop Proceedings,
Dublin, Ireland, May 2006

[3]

W. K. Edwards, M. W. Newman, J. Sedivy, T. Smith, S. Izadi, “Challenge: Recombinant
Computing and the Speakeasy Approach”, Proceedings of Mobicom '02, September 2002

[4]

D. Greenwood, M. Calisti, "Engineering Web Service
-

Agent Inte
gration," in IEEE
Conference of Systems, Man and Cybernetics, The Hague, 2004

[5]

A. Harrison, I. J. Taylor “WSPeer
-

An Interface to Web Service Hosting and
Invocation”, Proceedings of the 19th IEEE International Parallel and Distributed
Processing Symposium

(IPDPS'05)
-

Workshop 4
-

Volume 05

[6]

V. de Castro, E. Marcos, B. Vela, “Representing WSDL with extended UML”, Revista
Columbiana de Computation, vol. 5, Lug 2004, ISSN 1657


2831

[7]

N. Milanovic, M. Malek, "Current Solutions for Web Service Composition" IEEE

Internet Computing, vol. 08, no. 6, pp. 51
-
59, Nov/Dec, 2004.

[8]

Q. Z. Sheng, B. Benatallah, “ContextUML: A UML
-
Based Modeling Language for
Model
-
Driven Development of Context
-
Aware Web Services”, The 4th International
Conference on Mobile Business (ICMB
'05), IEEE Computer Society. July 11
-
13 2005,
Sydney, Australia.

[9]

J. P. A. Almeida, R. Dijkman, M. van Sinderen and L. F. Pires, "On the Notion of
Abstract Platform in MDA Development", in Proceedings Eighth IEEE International
Conference on Enterprise Distr
ibuted Object Computing (EDOC 2004), California, USA,
http://doi.ieeecomputersociety.org/10.1109/EDOC.2004.10010

[10]

Web Services Description Language (WSDL) 1.1, W3C Note 15 March 200
1,
http://www.w3.org/TR/wsdl

[11]

Object Management Group, Model Driven Architecture, home page,
http://www.omg.org/mda/

[12]

The Thinlet project, home page,
http://thinlet.sourceforge.net/home.html

[13]

The XML User Interface Language (XUL),
http://www.mozilla.org/projects/xul/


Context definition and handling in the

S
imple Mobile Services architecture



Page
22

of
22

[14]

The Simple Mobile Services Project, home page.
http://www.ist
-
sms.org

[15]

The Simplicity Project, home page.
http://www.ist
-
simplicity.org

[16]

The SMILE project, home page,
http://netgroup.uniroma2.it/twiki/bin/view.cgi/Main/SmilePublic

[17]

MJSIP, homepage,
http://www.mjsip.org/

[18]

JSON, homepage,
http://www.json.org/

[19]

The OpenCom

framework, home page,
http://www.comp.lancs.ac.uk/computing/research/mpg/reflection/opencom.php

[20]

The JXTA project, home page,
https://jxta.dev.java.net/

[21]

The OSGi project, home page,
http://www.osgi.org/

[22]

CORBA in wikipedia,
http://en.wikipedia.org/wiki/CORBA

[23]

JADE, the Java Agent Developm
ent framework, home page,
http://jade.tilab.com/

[24]

Service Oriented Architecture definition in wikipedia,
http://en.wikipedia.org/wiki/Soa