org.iperg.part.core
Class IpSystem

java.lang.Object
  extended by org.iperg.part.core.IpSystem

public final class IpSystem
extends java.lang.Object

The IpSystem class provides the main PART API for setting up connections to remote processes, and for listening and accepting incoming connections.

 // Set up a connection to a remote process
 IpIdentifier procId = IpSystem.connect(url1, timeout, false);
 // Also listen for incoming connections 
 IpSystem.listen(url2);

The IpSystem class also allows the appplication to catch events generated by the platform or sent by remote processes. For the application to receive such events, it must register an event handler:

 IpSystem.addEventHandler(handler);
If no handler has been added, the application will receive no events. If several handlers have been added, they will be called one after the other whenever events are generated.

Version:
1.0.0 Initial version
Author:
Olov Stahl - olovs@sics.se

Field Summary
static boolean s_debug
           
static java.lang.String TICK_EVENT
           
 
Constructor Summary
IpSystem()
           
 
Method Summary
static void addDebugHandler(IpDebugHandler newHandler)
          Add a debug handler.
static void addEventHandler(IpEventHandler handler)
          Add an event handler that will be notified about all events that are passed to the local process.
static void addTickEventHandler(IpEventHandler handler)
          Add an event handler that will be notified about tick events that are generated by the local process.
static void broadcast(IpNetworkEvent event)
          Broadcast an event to every process that can be reached from the local process.
static IpIdentifier connect(IpUrl url, int timeout, boolean persistent)
          Set up a connection to a remote process using an address represented by a url.
static boolean connectionInitiatedByLocalProcess(IpIdentifier procId)
          Check if a connection between the local and a remote process was initiated by the local process, i.e., if the local process called connect and the remote process listen.
static void debug(java.lang.Object obj, java.lang.String method, int level, java.lang.String message)
          Internal method that handles log messages.
static void disconnect(IpIdentifier procId)
          Close connection that exists between the local and a remote process.
static int getConnectionStatus(IpIdentifier procId)
          Get the status of a direct connection between the local and a remote process.
static IpUrl getConnectionUrl(IpUrl listenUrl)
          Given an url used in a call to listen, get an url that can be used by a remote process when calling connect to connect to the local process.
static int getConnectRetryInterval()
          Get interval (in seconds) that determines how often re-connects will be retried for unconnected persistent connections.
static int getDebugLevel()
          Get the debug level.
static IpProcess getLocalProcess()
          Get a process object that represents the local process.
static IpIdentifier getLocalProcessId()
          Get the identifier representing the local process.
static int getSubscriptionCancelTime()
          Get time after which a subscription is cancelled and removed by the master if not renewed.
static int getSubscriptionRenewInterval()
          Get the interval (in seconds) at which object property subscriptions made by the local process are renewed.
static void initialize(IpIdentifier id)
          Initialize local process object and set its identifier.
static boolean isConnectionPersistent(IpIdentifier procId)
          Check if a connection between the local and a remote process is peristent, i.e., if it will be re-connected automatically by PART if broken.
static void listen(IpUrl url)
          Start listening for connection attempts on a local address represented by a url.
static void notifyExitApp()
          Should be called to let the platform know that the application has been told to exit.
static void notifyPauseApp()
          Should be called to let the platform know that the application has been told to pause.
static void notifyResumeApp()
          Should be called to let the platform know that the application has been told to resume after a pause.
static void printTrafficStats(int interval)
          Generate network traffic statistics information at a regular interval.
static IpIdentifier[] searchObjectIds(IpIdentifier procId, IpObjectPattern pattern, int maxMatches, int timeout)
          Search for objects matching a given pattern in a remote process.
static IpObject[] searchObjects(IpIdentifier procId, IpObjectPattern pattern, int maxMatches, int timeout)
          Search for objects matching a given pattern in a remote process.
static void searchObjectsAsync(IpIdentifier procId, IpObjectPattern pattern, int maxMatches, java.lang.String tag)
          Search for objects matching a given pattern in a remote process, or in all processes that can be reached from the local process.
static void setConnectRetryInterval(int interval)
          Set the connect retry interval.
static void setDebugLevel(int level)
          Set the debug level.
static void setSubscriptionCancelTime(int time)
          Set time after which a subscription is cancelled and removed by the master if not renewed.
static void setSubscriptionRenewInterval(int interval)
          Set the subscription renew interval.
static void stopListen(IpUrl url)
          Stop listening for connection attempts on a local address represented by a url.
static void verifyRoute(IpIdentifier procId, int silenceThreshold)
          Tell PART to try to verify the connection route to a remote process.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

s_debug

public static final boolean s_debug
See Also:
Constant Field Values

TICK_EVENT

public static final java.lang.String TICK_EVENT
See Also:
Constant Field Values
Constructor Detail

IpSystem

public IpSystem()
Method Detail

initialize

public static void initialize(IpIdentifier id)
Initialize local process object and set its identifier. Should only be used if the application needs to control the identifier assigned to the local process object.

Parameters:
id - The identifier to be set as the identifier of the local process object. Should be unique if value is not null. If value is null, process object will be given an arbitrary unique identifier.

getLocalProcessId

public static IpIdentifier getLocalProcessId()
Get the identifier representing the local process.

Returns:
The local process identifier

getLocalProcess

public static IpProcess getLocalProcess()
Get a process object that represents the local process. The identifier of the local process object is the same as the identifier of the local process (which can be retreived via the getLocalProcessId method).

Returns:
The local process object

addEventHandler

public static void addEventHandler(IpEventHandler handler)
Add an event handler that will be notified about all events that are passed to the local process. Should be used by the application to receive local events triggered by the platform, or network events sent by remote processes. If several handlers have been added, they will be called one after the other whenever events are generated. If the handler has already been added, it won't be added twice.

Parameters:
handler - The event handler to add

addTickEventHandler

public static void addTickEventHandler(IpEventHandler handler)
Add an event handler that will be notified about tick events that are generated by the local process. Tick events are events of type IpEvent with type IpSystem.TICK_EVENT. Such events are generated by PART at a regular interval. The handlers can't make any assumptions on how often tick events are generated other than it will happen at least a couple of times each second.

Parameters:
handler - The event handler the will received tick events

notifyExitApp

public static void notifyExitApp()
Should be called to let the platform know that the application has been told to exit.


notifyPauseApp

public static void notifyPauseApp()
Should be called to let the platform know that the application has been told to pause.


notifyResumeApp

public static void notifyResumeApp()
Should be called to let the platform know that the application has been told to resume after a pause.


debug

public static void debug(java.lang.Object obj,
                         java.lang.String method,
                         int level,
                         java.lang.String message)
Internal method that handles log messages. If a log handler has been set via the addDebugHandler method, it is invoked to handle the log message. Otherwise we handle the message ourselves.


addDebugHandler

public static void addDebugHandler(IpDebugHandler newHandler)
Add a debug handler. The handler's handleDebug method will be invoked whenever a debug message is generated via the debug method.

Parameters:
newHandler - The reference to a class that implements the IpDebugHandler interface.

setDebugLevel

public static void setDebugLevel(int level)
Set the debug level.

Parameters:
level - The new debug level.

getDebugLevel

public static int getDebugLevel()
Get the debug level.

Returns:
The current debug level.

connect

public static IpIdentifier connect(IpUrl url,
                                   int timeout,
                                   boolean persistent)
                            throws IpInvalidUrlException,
                                   java.io.IOException,
                                   IpTimeoutException,
                                   IpAlreadyConnectedException
Set up a connection to a remote process using an address represented by a url. The exact url syntax is protocol specific, but a url will typically look something like protocol://device:protocol_specific, e.g., udp://localhost:1000.

If the connection can't be established within the time specified by the timeout parameter, an IpTimeoutException is thrown.

If the connect method returns without an exception, the connection was successful and an object representing the connection is returned. An IpProcessEvent of type IpProcessEvent.CONNECTION_ESTABLISHED is also generated.

If the persistent parameter is true and the initial connect fails, PART will try to redo the connect until a connection is successfully established to the remote process. The rate at which re-connects will be attempted is determined by the connection retry interval, which can be set via setConnectRetryInterval. Each time a re-connect fails, an IpProcessEvent of type IpProcessEvent.CONNECT_FAIL will be posted. If the connection is flagged as being persistent, PART will also try to re-establish the connection if it becomes broken for some reason. If the connection is successfully established, an IpProcessEvent of type IpProcessEvent.CONNECTION_ESTABLISHED is generated.

Parameters:
url - The url that describes the address to which the connection will be established
timeout - Timeout in milliseconds, 0 means no timeout
persistent - If true, connection will be persistent, otherwise not
Returns:
The identifier of the remote process to which a connection was established
Throws:
IpInvalidUrlException - if the url is invalid, e.g., doesn't specify a valid network address
java.io.IOException - if an io exception occurs while setting up the connection to the remote process
IpTimeoutException - if the connection can't be established within the time specified by the timeout parameter
IpAlreadyConnectedException

listen

public static void listen(IpUrl url)
                   throws IpInvalidUrlException,
                          java.io.IOException
Start listening for connection attempts on a local address represented by a url. The exact url syntax is protocol specific, but a url will typically look something like protocol://device:protocol_specific, e.g., udp://localhost:1000. If host is part of url, it has to identify the local host. If a remote host is given, an InvalidAddressException is generated.

If a remote process connects to the local addresses, an IpProcessEvent of type CONNECTION_ESTABLISHED will be dispatched and delivered to application's event handler.

Parameters:
url - A url identifying a local address
Throws:
IpInvalidUrlException - if the url parameter is invalid, e.g., doesn't identify a local address
java.io.IOException - if a protocol specific error occured

stopListen

public static void stopListen(IpUrl url)
                       throws java.io.IOException
Stop listening for connection attempts on a local address represented by a url. The same url should have previously been used in a call to listen.

Parameters:
url - A url identifying a local address
Throws:
java.io.IOException - if a protocol specific error occured

getConnectionUrl

public static IpUrl getConnectionUrl(IpUrl listenUrl)
Given an url used in a call to listen, get an url that can be used by a remote process when calling connect to connect to the local process.

Parameters:
listenUrl - The url that was used in the call to listen.
Returns:
A url that can be used in a call to connect, or null if the given listen url is not "active".

disconnect

public static void disconnect(IpIdentifier procId)
                       throws IpException
Close connection that exists between the local and a remote process.

Parameters:
procId - The identifier of the remote process
Throws:
IpException

isConnectionPersistent

public static boolean isConnectionPersistent(IpIdentifier procId)
                                      throws IpException
Check if a connection between the local and a remote process is peristent, i.e., if it will be re-connected automatically by PART if broken.

Parameters:
procId - The identifier of the remote process
Returns:
true if connection is persistent, false otherwise.
Throws:
IpException - if no direct connection exists between the local and the remote process

connectionInitiatedByLocalProcess

public static boolean connectionInitiatedByLocalProcess(IpIdentifier procId)
                                                 throws IpException
Check if a connection between the local and a remote process was initiated by the local process, i.e., if the local process called connect and the remote process listen.

Parameters:
procId - The identifier of the remote process
Returns:
true if local process called connect, false otherwise.
Throws:
IpException - if no direct connection exists between the local and the remote process

searchObjects

public static IpObject[] searchObjects(IpIdentifier procId,
                                       IpObjectPattern pattern,
                                       int maxMatches,
                                       int timeout)
                                throws IpTimeoutException,
                                       java.io.IOException
Search for objects matching a given pattern in a remote process. The search will be performed in the process identified by the process identifier parameter. All matching objects will brought back to the local process and returned to the caller.

The call blocks until the matching objects (if any) have been retrieved. If no result has been received within the time specified by the timeout parameter, an IpTimeoutException is thrown.

Parameters:
procId - The identifier of the remote process where the search will take place. May not be null.
pattern - A pattern that will be sent to the remote process and matched against all objects
maxMatches - The maximum number of objects that should be returned. A value of 0 means that all matching objects should be retrieved.
timeout - A time in milliseconds. If value if zero, the retrieval attempt will never timeout.
Returns:
An array of IpObject instances brought back from the remote process as a result of them matching the given pattern. If no matching object was found, null is returned.
Throws:
IpTimeoutException - if timeout occurs before the match result is returned
java.io.IOException - if an io exception occurs while sending the pattern to the remote process or while receiving match results

searchObjectIds

public static IpIdentifier[] searchObjectIds(IpIdentifier procId,
                                             IpObjectPattern pattern,
                                             int maxMatches,
                                             int timeout)
                                      throws IpTimeoutException,
                                             java.io.IOException
Search for objects matching a given pattern in a remote process. The search will be performed in the process identified by the process identifier parameter. The identifiers of matching objects will brought back to the local process and returned to the caller.

The call blocks until the matching object identifiers (if any) have been retrieved. If no result has been received within the time specified by the timeout parameter, an IpTimeoutException is thrown.

Parameters:
procId - The identifier of the remote process where the search will take place. May not be null.
pattern - A pattern that will be sent to the remote process and matched against all objects
maxMatches - The maximum number of object identifiers that should be returned. A value of 0 means that the identifiers of all matching objects should be retrieved.
timeout - A time in milliseconds. If value if zero, the retrieval attempt will never timeout.
Returns:
An array of IpIdentifier instances brought back from the remote process as a result of the corresponding objects matching the given pattern. If no matching object was found, null is returned.
Throws:
IpTimeoutException - if timeout occurs before the match result is returned
java.io.IOException - if an io exception occurs while sending the pattern to the remote process or while receiving match results

searchObjectsAsync

public static void searchObjectsAsync(IpIdentifier procId,
                                      IpObjectPattern pattern,
                                      int maxMatches,
                                      java.lang.String tag)
                               throws java.io.IOException
Search for objects matching a given pattern in a remote process, or in all processes that can be reached from the local process.

The search is implemented by sending an object pattern to remote PART processes, which matches it against all PART objects that they hold. Matching objects are then send back to the calling process. Note that the search is not continuous, receiving processes will perform the match only once. If the given process identifier is null, the search will be broadcasted to all processes. If the identifier is not null, the pattern will be sent to that process only.

The call returns immediately. When a result is returned from the remote process, it will be delivered via a IpObjectSearchResultEvent.

Parameters:
procId - The identifier of the remote process where the search will take place
pattern - The pattern that will be matched against objects in the remote processes
maxMatches - The maximum number of matching objects that should be returned by each process. A value of 0 means that all matching objects should be returned.
tag - A tag that can be used to identify the search, may be null
Throws:
java.io.IOException - if an io exception occurs when initiating the object search

broadcast

public static void broadcast(IpNetworkEvent event)
                      throws java.io.IOException
Broadcast an event to every process that can be reached from the local process. Broadcasting is implemented by sending the event to our neighbours, who send it to their neighbours (except the one from where they gotr the event), and so on.

Parameters:
event - The event to broadcast
Throws:
java.io.IOException - if an io exception occurs when sending the event to the network

getConnectionStatus

public static int getConnectionStatus(IpIdentifier procId)
Get the status of a direct connection between the local and a remote process.

A return value of IpConnection.UNCONNECTED means that the local and remote processes are not directly connected.

A return value of IpConnection.CONNECTING means that a connection between the local and remote process is being set up, but is not yet completeted.

A return value of IpConnection.CONNECTED means that the local and remote process are connected and the connection seems to be working ok.

A return value of IpConnection.CLOSED_LOCALLY means that the connection was closed by the local process.

A return value of IpConnection.CLOSED_REMOTELY means that the connection was closed by the remote process.

A return value of IpConnection.BROKEN means that the connection is not working properly for some reason.

Parameters:
procId - The identifier of the remote process
Returns:
The connection status

verifyRoute

public static void verifyRoute(IpIdentifier procId,
                               int silenceThreshold)
Tell PART to try to verify the connection route to a remote process. This is done by monitoring the incoming traffic from the process, and by sending ping events if no traffic has been received for a given amount of time (silence threshold).

If the silence threshold has been reached, i.e., if no network data has been received from the remote process within the number of seconds given by the threshold parameter, the local process will send a ping event to the remote process. At the same time, a IpProcessEvent.PROCESS_SILENT event will be posted locally. This behaviour will repeated whenever the silence threshold is reached.

If a IpProcessEvent.PROCESS_SILENT has been posted to indicate that no data has been received from the remeote process in a while, a IpProcessEvent.PROCESS_ALIVE will be posted if network data is indeed received originating from the process. Note that process alive events are only posted as a result of receiving incoming data from a process, if a process silence event was previously posted.

The route verfification may be turned off by supplying a value of 0 for the silence threshold.

Parameters:
procId - The identifier of the remote process
silenceThreshold - Silence threshold in seconds, must be >= 0

getConnectRetryInterval

public static int getConnectRetryInterval()
Get interval (in seconds) that determines how often re-connects will be retried for unconnected persistent connections.

For instance, assume that a connection to a remote process is made via connect and that the persistent parameter is true:

 IpIdentifer procId = connect(url, timeout, true);

If the connect fails for some reason, PART will redo the connect in the number of seconds determined by the connect retry interval. This will go on until the connect is either successful (in which case a IpProcessEvent event of type IpProcessEvent.CONNECTION_ESTABLSIHED will be posted) or until the connect is cancelled via a call to disconnect. Whenever a connect is retried and fails, a IpProcessEvent event of type IpProcessEvent.CONNECT_FAILED is posted.

Returns:
The connecti retry interval

setConnectRetryInterval

public static void setConnectRetryInterval(int interval)
Set the connect retry interval. For a description of the connect retry mechanism, see getConnectRetryInterval.

Parameters:
interval - Interval in seconds, must be > 0

getSubscriptionRenewInterval

public static int getSubscriptionRenewInterval()
Get the interval (in seconds) at which object property subscriptions made by the local process are renewed. A renew for a particular object involves sending an event to the master process (the process holding the master copy of the object), requesting all property subscriptions for that object to be renewed. If the renewal is accepted, the holder will send back a subscription confirm event, confirming the property subscriptions. Whenever such an event is received by the local process, a IpSubscriptionEvent of type IpSubscriptionEvent.SUBSCRIPTION_CONFIRM is posted.


setSubscriptionRenewInterval

public static void setSubscriptionRenewInterval(int interval)
Set the subscription renew interval. For a description of the subscription renew mechanism, see getSubscriptionRenewInterval.

Note that since subscription renewals will generate network traffic, a low renewal interval may flood a low bandwidth connection (e.g., GPRS).

Parameters:
interval - The renew interval in seconds, must be > 0

getSubscriptionCancelTime

public static int getSubscriptionCancelTime()
Get time after which a subscription is cancelled and removed by the master if not renewed.

Returns:
Subscription cancel time in seconds

setSubscriptionCancelTime

public static void setSubscriptionCancelTime(int time)
Set time after which a subscription is cancelled and removed by the master if not renewed.

Parameters:
time - Cancel time in seconds

printTrafficStats

public static void printTrafficStats(int interval)
Generate network traffic statistics information at a regular interval.