com.ls.lars.communication
Class CommunicationTemplate

java.lang.Object
  |
  +--java.lang.Thread
        |
        +--com.ls.lars.communication.CommunicationTemplate
All Implemented Interfaces:
ICommunication, IToLars, Runnable, Serializable
Direct Known Subclasses:
AgentTemplate, ClientCommunication

public abstract class CommunicationTemplate
extends Thread
implements Serializable, IToLars

provides the basic communication and logging functionalities needed by lars agents

Version:
$Revision: 1.41 $
Author:
Last modified by $Author: MHeitz $
See Also:
"all other agents", Serialized Form

Field Summary
protected  String agentName
          Name of this agent, initialized in the constructor.
protected  String homePlatform
          lars platform where this agent was born
protected  IPKIHandler iPKIHandler
          the Interface to integrate PKI-Handling
protected  ILogger logger
          log file of this agent
static boolean STATUS_CONNECTED
          connectionStatus = STATUS_CONNECTED: connection to lars platform is ok
static boolean STATUS_NOT_CONNECTED
          connectionStatus = STATUS_NOT_CONNECTED: connection to lars platform is not available
 
Fields inherited from class java.lang.Thread
MAX_PRIORITY, MIN_PRIORITY, NORM_PRIORITY
 
Fields inherited from interface com.ls.lars.communication.ICommunication
AUTHENTICATION_PASSWORD, AUTHENTICATION_USER, COMPRESSION_AUTO_COMPRESSION, COMPRESSION_AUTO_COMPRESSION_START_SIZE, COMPRESSION_LEVEL, COMPRESSION_TYPE, COMPRESSION_ZIP_ENTRY_NAME, CONNECTION_TYPE, HOST_ID, HOST_IP, HOST_PORT, HTTP, J_SECURE_SOCKET, J_SOCKET, JMS, JMS_INITIAL_CONTEXT_FACTORY, JMS_JMSMESSENGER_APPLICATION_LOCATION, JMS_PROVIDER_URL, JMS_RECEIVING_QUEUE_NAME, JMS_SECURITY_CREDENTIALS, JMS_SECURITY_PRINCIPAL, JMS_SENDING_QUEUE_NAME, MAXIMUM_MESSAGE_LENGTH, PROTOCOL, RMI, SOCKET, TIMEOUT, USE_OUTBOX
 
Constructor Summary
CommunicationTemplate(String agentName, Map connectionParameters)
          Constructor, that is used, if the agent wants to use and set up a it's own remote messenger (for example a SocketMessenger for socket communication).
CommunicationTemplate(String agentName, String homePlatform)
          Constructor, that creates a local messenger and does the basic initialization of a new agent.
 
Method Summary
 void addConnectionParameter(String key, Object connectionParameter)
          Sets a connection parameter e.g. compression settings, secure settings, ...
protected  void checkSendSystemReply(Message message, String serviceOfReply, int failureCode, String reasonDescription)
          Called to check, whether the system needs to generate and send a reply to the given message for the specified failure code.
 void connect()
          Initiates to connect to the lars system and then calls Messenger#waitForConnection().
protected  String createReplyId()
          returns a unique number / key to be used as reply ID of a message
 void disconnect()
          Disconnects from the lars system (if already connected).
protected  void disconnectForMigration()
          used for disconnecting an agent form a platform when he's mirating
abstract  void executeLifeCycle()
          Implements the "until the thread" loop (which probably in a while loop receives messages from the inbox by calling receiveBlockedMessage() and interprets them).
protected  void finalize()
          Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.
 void forwardMessage(Message message, List forwardReceivers)
          Forwards a message by creating a shallow copy and then exchanging the receiver in the copy.
 void forwardMessage(Message message, String forwardReceiver)
          Forwards a message by creating a shallow copy and then exchanging the receiver in the copy.
 String getAgentName()
          returns the name of the agent
 Map getConnectionParameters()
          Gets the connection parameters e.g. compression settings, secure settings, ...
 int getInboxSize()
          returns the size of the inbox
 String getLarsHost()
          Returns the host name of the lars system.
 long getNumberOfProcessedMessages()
          returns the number of processed messages since the start of the agent
 long getNumberOfProcessedMessagesPerMinute()
          returns the number of processed messages per hour
 long getStartTime()
          returns the start time this agent in milliseconds since 01-jan-1970
 boolean isConnected()
          Checkes if the object(messanger) is connected to the lars system or not.
protected  void logInbox()
          writes the content of the inbox of the agent to its log file
 Message receiveBlockedMessage()
          waits until a message arrives in the agent's inbox and returns it It may happen that an existing connection becomes invalid physically (e.g. due to a platform crash) - althought this party gets not informed about that.
 Message receiveBlockedMessage(long timeout)
          Waits until a message arrives in the agent's inbox and returns it If there is currently no message available, the method will wait for timeout milliseconds to receive one - after that time span it returns null.
protected  boolean reconnectAfterMigration()
          Reconnects an agent on a (guest) platform.
 void run()
          Executes when this thread gets started.
 void sendMessage(Message message)
          sends a message
Note: the sender of the message is set to the current agent's name
 Message sendSynchronousRequest(Message message)
          sends a message expecting a request for synchronous messaging by calling sendSynchronousRequest(Message, long)
 Message sendSynchronousRequest(Message message, long timeout)
          sends a message expecting a request for synchronous messaging
Note: the sender of the message is set to the current agent's name Note for developers: You should use this method if - and only if - you're absolutely sure that the call does not make your agent blocking for a longer period.
 void setConnectionParameters(Map connectionParameters)
          Sets the connection parameters e.g. compression settings, secure settings, ...
protected  void setLog()
          sets the ILogger of the messenger
protected  void setMeantimeBetweenConnectionCheck(long meantime)
          sets the meantime between checking the connection
 boolean terminateAction()
          Executes actions that have to be performed before the agent terminates.
 void waitForConnection()
          Blocks the calling thread, if the current connection status is STATUS_NOT_CONNECTED.
 void waitForConnection(long timeout)
          Blocks the calling thread, if - timeout time in milliseconds is not reached and - current connection status is STATUS_NOT_CONNECTED. if the timeout is zero, then the thread blocks as long as the connection status is not changed in a connection setup inside of a Messenger (then called by another thread).
 
Methods inherited from class java.lang.Thread
activeCount, checkAccess, countStackFrames, currentThread, destroy, dumpStack, enumerate, getContextClassLoader, getName, getPriority, getThreadGroup, interrupt, interrupted, isAlive, isDaemon, isInterrupted, join, join, join, resume, setContextClassLoader, setDaemon, setName, setPriority, sleep, sleep, start, stop, stop, suspend, toString, yield
 
Methods inherited from class java.lang.Object
clone, equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
 
Methods inherited from interface com.ls.lars.communication.IToLars
start
 

Field Detail

STATUS_NOT_CONNECTED

public static final boolean STATUS_NOT_CONNECTED
connectionStatus = STATUS_NOT_CONNECTED: connection to lars platform is not available

STATUS_CONNECTED

public static final boolean STATUS_CONNECTED
connectionStatus = STATUS_CONNECTED: connection to lars platform is ok

agentName

protected final String agentName
Name of this agent, initialized in the constructor.
Note: This name cannot be modified!

homePlatform

protected String homePlatform
lars platform where this agent was born

iPKIHandler

protected IPKIHandler iPKIHandler
the Interface to integrate PKI-Handling

logger

protected transient ILogger logger
log file of this agent
Constructor Detail

CommunicationTemplate

public CommunicationTemplate(String agentName,
                             String homePlatform)
                      throws NullPointerException
Constructor, that creates a local messenger and does the basic initialization of a new agent.
Parameters:
agentName - name of the agent (example: xyz )
homePlatform - name of the platform, where the agent was created (example: 195.52.158.233/lars)
Throws:
NullPointerException - If the given agentName is null or empty or If the given homePlatform is null or empty
See Also:
LocalMessenger

CommunicationTemplate

public CommunicationTemplate(String agentName,
                             Map connectionParameters)
                      throws ConnectionException,
                             NullPointerException
Constructor, that is used, if the agent wants to use and set up a it's own remote messenger (for example a SocketMessenger for socket communication). This constructor takes a java.util.Map object, containing the connection parameters being used for setting up it's own messenger. The keys for this map are defined in the ICommunication interface.
Parameters:
agentName - name of the agent (example: "xyz@195.52.158.233/lars")
connectionParameters - being used for establishing the connection
Throws:
ConnectionException - if a connection cannot be established
NullPointerException - If the given agentName is null or empty or if the given map is null or if the given map does not contain mappings for ICommunication.HOST_IP and ICommunication.HOST_ID
See Also:
ClientMessengerFactory, ICommunication
Method Detail

setLog

protected void setLog()
sets the ILogger of the messenger

setMeantimeBetweenConnectionCheck

protected void setMeantimeBetweenConnectionCheck(long meantime)
sets the meantime between checking the connection
Parameters:
meantime - the time between connection checks

getInboxSize

public final int getInboxSize()
returns the size of the inbox
Returns:
number of messages in the inbox

getNumberOfProcessedMessages

public final long getNumberOfProcessedMessages()
returns the number of processed messages since the start of the agent
Returns:
number of processed messages

getNumberOfProcessedMessagesPerMinute

public final long getNumberOfProcessedMessagesPerMinute()
returns the number of processed messages per hour
Returns:
number of processed messages per hour

getAgentName

public final String getAgentName()
returns the name of the agent
Specified by:
getAgentName in interface ICommunication
Returns:
name of this agent

getLarsHost

public final String getLarsHost()
Returns the host name of the lars system. This variable is set after the connection.
Specified by:
getLarsHost in interface IToLars
Returns:
hostName The host name of the lars system

getStartTime

public final long getStartTime()
returns the start time this agent in milliseconds since 01-jan-1970
Returns:
this agent's start time

logInbox

protected final void logInbox()
writes the content of the inbox of the agent to its log file

isConnected

public final boolean isConnected()
Checkes if the object(messanger) is connected to the lars system or not. For checking the connection this method utilizes the getConnectionStatus() method of the messenger.
Specified by:
isConnected in interface IToLars
Returns:
true, if connected; false else

sendMessage

public final void sendMessage(Message message)
sends a message
Note: the sender of the message is set to the current agent's name
Specified by:
sendMessage in interface ICommunication
Parameters:
message - message to be sent

sendSynchronousRequest

public final Message sendSynchronousRequest(Message message)
                                     throws TimeoutException,
                                            ProgrammingException
sends a message expecting a request for synchronous messaging by calling sendSynchronousRequest(Message, long)

Specified by:
sendSynchronousRequest in interface ICommunication
Parameters:
message - to be sent
Returns:
Message the message desired and given by the replyId
Throws:
TimeoutException - If no message with the specified reply ID could be read from the inbox within the default timeout time
ProgrammingException - If no 'replyWith' field was specified for the synchronous request

sendSynchronousRequest

public final Message sendSynchronousRequest(Message message,
                                            long timeout)
                                     throws TimeoutException,
                                            ProgrammingException
sends a message expecting a request for synchronous messaging
Note: the sender of the message is set to the current agent's name

Note for developers: You should use this method if - and only if - you're absolutely sure that the call does not make your agent blocking for a longer period. Especially when your agent holds a very important position on the , platform this blocking could result in an very bad runtime behavior of the whole system.

Example:
Think of an agent, who is to process multiple incoming requests from a number of connected servlets.
When you are sending the messages synchronously using this method, all other requests are blocked until the agent receives the response for the outgoing message, or receives a TimeoutException.

The more sophisticated way would be to send all your messages only in an asynchronous way using the standard sendMessage(Message) method. In this case your agent is not blocked and thus free to perform any other operations, instead of wasting time while waiting for an awaited response message.

Specified by:
sendSynchronousRequest in interface ICommunication
Parameters:
message - message to be sent
timeout - time in milliseconds how long to wait for an answer, before throwing a TimeoutException
Returns:
answer to the sent message
Throws:
TimeoutException - If no message with the specified reply ID could be read from the inbox within the specified timeout time
ProgrammingException - If no 'replyWith' field was specified for the synchronous request

forwardMessage

public final void forwardMessage(Message message,
                                 String forwardReceiver)
Forwards a message by creating a shallow copy and then exchanging the receiver in the copy.
Note: If the given message is not an instance of SingleMessage, it is converted into a SingleMessage. Then the original message type cannot be determined at the forwardReceiver any more.
Note: For performance reasons the message's content is only a shallow copy - if you need to change parts of the message (e.g. the content), make a copy by yourself before calling forwardMessage.
Specified by:
forwardMessage in interface ICommunication
Parameters:
message - message to be forwarded
forwardReceiver - new receiver of the message (the one, to whom the message will be forwarded)

forwardMessage

public final void forwardMessage(Message message,
                                 List forwardReceivers)
Forwards a message by creating a shallow copy and then exchanging the receiver in the copy.
Note: If the given message is not an instance of MulticastMessage, it is converted into a MulticastMessage. Then the original message type cannot be determined at the forwardReceivers any more.
Note: For performance reasons the message's content is only a shallow copy - if you need to change parts of the message (e.g. the content), make a copy by yourself before calling forwardMessage.
Specified by:
forwardMessage in interface ICommunication
Parameters:
message - message to be forwarded
forwardReceivers - list of new receivers of the message (the ones, to whom the message will be forwarded)

receiveBlockedMessage

public final Message receiveBlockedMessage()
waits until a message arrives in the agent's inbox and returns it It may happen that an existing connection becomes invalid physically (e.g. due to a platform crash) - althought this party gets not informed about that. Therefore we check the underlying messenger's connection status explicitely before calling its Messenger#getBlockedInboxMessage()
Returns:
message received from the inbox

receiveBlockedMessage

public final Message receiveBlockedMessage(long timeout)
                                    throws TimeoutException
Waits until a message arrives in the agent's inbox and returns it If there is currently no message available, the method will wait for timeout milliseconds to receive one - after that time span it returns null. It may happen that an existing connection becomes invalid physically (e.g. due to a platform crash) - althought this party gets not informed about that. Therefore we check the underlying messenger's connection status explicitely before calling its Messenger#getBlockedInboxMessage()
Parameters:
timeout - timeout time in milliseconds after null will be returned.
Returns:
message received from the inbox
Throws:
TimeoutException - if no message could be received within the specified amount of time

checkSendSystemReply

protected final void checkSendSystemReply(Message message,
                                          String serviceOfReply,
                                          int failureCode,
                                          String reasonDescription)
Called to check, whether the system needs to generate and send a reply to the given message for the specified failure code. If QualityOfService.createReply(message, serviceOfReply, failureCode, reasonDescription, null) returns a reply message, this is sent.
Parameters:
message - message which's quality of service needs to be checked
serviceOfReply - service to use in the reply message
failureCode - code of the failure (see QualityOfService)
reasonDescription - contains the textual description of the reason for the failure

createReplyId

protected final String createReplyId()
returns a unique number / key to be used as reply ID of a message
Returns:
unique number / key

run

public final void run()
Executes when this thread gets started.
  1. calls messenger.waitForConnection()
  2. calls executeLifeCycle()
  3. calls disconnect()
Overrides:
run in class Thread

executeLifeCycle

public abstract void executeLifeCycle()
Implements the "until the thread" loop (which probably in a while loop receives messages from the inbox by calling receiveBlockedMessage() and interprets them).

Note: This method is called in run(), after the messenger was initialized.


connect

public void connect()
             throws ConnectionException
Initiates to connect to the lars system and then calls Messenger#waitForConnection(). This method uses the connection parameters, which have to be provided by setConnectionParameters(Map).
Specified by:
connect in interface IToLars
Throws:
ConnectionException - If the connection setup fails

disconnect

public void disconnect()
Disconnects from the lars system (if already connected).
Specified by:
disconnect in interface IToLars

terminateAction

public boolean terminateAction()
Executes actions that have to be performed before the agent terminates. This method performs the following tasks:
  1. steals this agent's messenger's monitor and sends it a notify
Note for developers: Only if your Agent needs to perform special clean up tasks before terminating (like terminating threads or sending unregister messages) you need to overwrite this method. Call super.terminateAction() at the method's end then to assure proper thread termination!
Returns:
true - CommunicationTemplate termination is always successful

setConnectionParameters

public void setConnectionParameters(Map connectionParameters)
Sets the connection parameters e.g. compression settings, secure settings, ... .
Specified by:
setConnectionParameters in interface IToLars
Parameters:
connectionParameters - contains any Map with any parameters

addConnectionParameter

public void addConnectionParameter(String key,
                                   Object connectionParameter)
Sets a connection parameter e.g. compression settings, secure settings, ... .
Parameters:
key - key of the parameter
connectionParameter - value of the parameter
See Also:
setConnectionParameters(java.util.Map)

getConnectionParameters

public Map getConnectionParameters()
Gets the connection parameters e.g. compression settings, secure settings, ... .
Specified by:
getConnectionParameters in interface IToLars
Returns:
connectionParameters contains any Map with any parameters

waitForConnection

public void waitForConnection()
                       throws ConnectionException
Blocks the calling thread, if the current connection status is STATUS_NOT_CONNECTED. The calling thread is blocked as long as the connection status is not changed in a connection setup inside of a Messenger (then called by another thread).
Specified by:
waitForConnection in interface IToLars
Throws:
ConnectionException - If the connection setup fails
See Also:
Messenger#waitForConnection

waitForConnection

public void waitForConnection(long timeout)
                       throws ConnectionException
Blocks the calling thread, if - timeout time in milliseconds is not reached and - current connection status is STATUS_NOT_CONNECTED. if the timeout is zero, then the thread blocks as long as the connection status is not changed in a connection setup inside of a Messenger (then called by another thread).
Specified by:
waitForConnection in interface IToLars
Parameters:
timeout - time in milliseconds; How long is the calling thread waits until an exception is thrown.
Throws:
ConnectionException - If the connection setup fails

disconnectForMigration

protected final void disconnectForMigration()
used for disconnecting an agent form a platform when he's mirating

reconnectAfterMigration

protected boolean reconnectAfterMigration()
Reconnects an agent on a (guest) platform. Therefore it sets and starts a new local messenger.
Returns:
always true

finalize

protected void finalize()
                 throws Throwable
Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. Any exception thrown by the finalize method causes the finalization of this object to be halted, but is otherwise ignored.
Overrides:
finalize in class Object
Throws:
Throwable - If an error occurs