Agent System POND 1.2 (28.2.2002)

PkgAgentSystem
Class AgentBase

java.lang.Object
  |
  +--java.lang.Thread
        |
        +--FIM.Util.Threads.CancellableThread
              |
              +--PkgAgentSystem.AgentBase
All Implemented Interfaces:
Runnable, Serializable
Direct Known Subclasses:
GUIAgentBase

public abstract class AgentBase
extends CancellableThread
implements Serializable

Base class for all agents. Contains the following parts:

Version:
1.0, 1.7.2000
Author:
Michael Sonntag
See Also:
AgentSystem, Message, NamedKeyPair, NamedKeyAndCertificate, Serialized Form

Field Summary
protected  Hashtable conversationArchive
          Previous conversations that were archived.
(package private)  Object initializeParam
          The parameter to pass to initialize
(package private) static int STARTUP_ACTION_AFTER_DEPERSIST
          When starting, call onAfterDePersist
(package private) static int STARTUP_ACTION_AFTER_MOVING
          When starting, call onAfterMoving
(package private) static int STARTUP_ACTION_INITIALIZE
          When starting, call initialize
(package private) static int STARTUP_ACTION_NONE
          When starting do nothing, just enter main method/message-loop
(package private)  int startupAction
          What the agent should do when starting (initialize, onAfterMoving, onAfterDepersist; or nothing)
 
Fields inherited from class java.lang.Thread
inheritableThreadLocals, MAX_PRIORITY, MIN_PRIORITY, NORM_PRIORITY, threadLocals
 
Constructor Summary
protected AgentBase()
          Constructor for class AgentBase.
 
Method Summary
 void addMessage(MessageType msg)
          Add a message to the queue.
protected  void addOwnExperience(Statement stat, boolean broadcast)
          Adds a statement to our own experiences.
protected  void addPermissionListener(PermissionChangeListener listener)
          Add a listener for permission changes.
protected  void agentMain()
          Main loop of the agent.
protected  void broadcastMessage(BroadcastMessage msg)
          Sends a message to all other local agents.
protected  boolean createConversationAllowed(long convTypeID)
          Checks, whether it is currently allowed to create this type of conversation.
 URL currentLocation()
          Returns the current location of the agent in form of an URL.
(package private)  void endConversation(Conversation conv, boolean shouldArchive)
          Ends a conversation.
(package private)  void endConversations()
          Terminates all ongoing conversations and removes all messages pending handling.
(package private)  void firePermissionChange(PermissionEvent permEvent)
          Call this to send a PermissionEvent to all registered listeners.
 String getAgentName()
          The public, non-unique plaintext name of the agent.
 AgentSystem getAgentSystem()
          Returns the agent system where the agent currently is located.
protected  Conversation getArchivedConversation(long convID)
          Retrieve a certain conversation from the archive.
protected  long[] getArchivedConversationIDs()
          Retrieve the IDs of all archived conversations.
 Experiences getExperiences()
          Returns the experiences object of this agent.
 AgentIdentity getIdentity()
          The identity of the agent (contains the public key).
protected  NamedKeyAndCertificate getKeyAndCertificate(String name)
          Retrieve a private key and the matching certificate from the certificate-store by its name
protected  Enumeration getKeyAndCertificates()
          Returns an enumeration of all the names, under which private keys and matching certificates are stored in the certificate-store.
protected  NamedKeyPair getKeyPair(String name)
          Retrieve a keypair from the key-store by its name
protected  Enumeration getKeyPairs()
          Returns an enumeration of all the names, under which keys are stored in the key-store.
protected  Vector getLog()
          Returns a copy of the log
protected  MessageType getNextMessage()
          Retrieve the next message in the queue.
protected  Conversation getOngoingConversation(long convID)
          Retrieve a certain currently ongoing conversation.
protected  long[] getOngoingConversationIDs()
          Retrieve the IDs of all currently ongoing conversations.
 boolean hasPermission(Permission perm)
          Allows the agent to inquiry whether he currently actually has a permission (NOT "could get it", ...).
protected  void initialize(Object param)
          Initialization of the agent.
 void logMessage(String msg)
          Adds the message to the internal log.
protected  void move(URL destination)
          Helper function to initiate moving this agent to another system.
 Conversation newConversation(long convTypeID, AgentIdentity counterpart)
          Method for creatign a new conversation.
protected  void onAfterDePersist()
          Called after restoring the agent from a secondary storage and before starting it again.
protected  void onAfterMoving()
          Called after receiving the agent from another host and before starting it again.
protected  void onBeforeMoving()
          Called before moving (When trying to transfer the agent to another host and stop it afterwards).
protected  void onBeforePersist()
          Called before persisting (When trying to safe the agent to a secondary storage and stop it afterwards).
protected  void persist()
          Helper function to initiate persisting this agent by itself.
protected  void registerConversation(Conversation conv)
          Registers a conversation.
protected  void registerReplaceConversation(Conversation conv)
          Registers a conversation.
protected  void removeKeyAndCertificate(String name)
          Remove a private key and the matching certificate from the certificate-store
protected  void removeKeyPair(String name)
          Remove a keypair from the key-store
protected  void removePermissionListener(PermissionChangeListener listener)
          Remove a listener for permission changes.
 byte[] replyToChallenge(byte[] challenge)
          This method can be used to verify, whether the agent knows a certain private key.
 byte[] replyToChallenge(String keyname, byte[] challenge)
          This method can be used to verify, whether the agent knows a certain private key.
 void run()
          The main method which is run when the agent is started.
protected  void sendMessage(Message msg)
          Sends a message to another agent.
(package private)  void setAgentIdentity(AgentIdentity identity, PrivateKey agentPrivateKey)
          Method for setting the identity and the private key of the agent.
(package private)  void setAgentSystem(AgentSystem sys)
          Method for setting the agent system the agent is in.
protected  void setKeyAndCertificate(NamedKeyPair nkp)
          Store a private key and the matching certificate in the certificate-store under the provided name.
protected  void setKeyPair(NamedKeyPair nkp)
          Store a keypair in the key-store under the provided name.
 boolean startConversation(Conversation conv)
          Starts a conversation.
protected  void stopAgent()
          Helper function to stop this agent.
protected  boolean typeIsRegistered(long conversationTypeID)
          Checks, wheter a conversation is registered under this id or not.
 boolean verifySignedMessage(SignedMessage msg)
          To verify a signed message.
protected  void writeExperiencesTo(PrintWriter out)
          Dump the experiences to a stream.
protected  void writeLogTo(PrintWriter out)
          Writes the log to a PrintWriter stream.
 
Methods inherited from class FIM.Util.Threads.CancellableThread
cancel, isCancelled, terminate
 
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, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

conversationArchive

protected Hashtable conversationArchive
Previous conversations that were archived. See Conversation.setShouldArchive.

STARTUP_ACTION_NONE

static final int STARTUP_ACTION_NONE
When starting do nothing, just enter main method/message-loop

STARTUP_ACTION_INITIALIZE

static final int STARTUP_ACTION_INITIALIZE
When starting, call initialize

STARTUP_ACTION_AFTER_MOVING

static final int STARTUP_ACTION_AFTER_MOVING
When starting, call onAfterMoving

STARTUP_ACTION_AFTER_DEPERSIST

static final int STARTUP_ACTION_AFTER_DEPERSIST
When starting, call onAfterDePersist

initializeParam

transient Object initializeParam
The parameter to pass to initialize

startupAction

transient int startupAction
What the agent should do when starting (initialize, onAfterMoving, onAfterDepersist; or nothing)
Constructor Detail

AgentBase

protected AgentBase()
Constructor for class AgentBase. The conversations registered are: The creation of the agent is logged in its private log.
See Also:
TerminateAgentConversation, ExperienceExchangeConversation
Method Detail

registerConversation

protected void registerConversation(Conversation conv)
Registers a conversation. This object will be cloned when a conversation of this type is required. The conversationTypeID has to be unique.
Parameters:
conv - the prototype of the conversation to register
Throws:
IllegalArgumentException - if a conversation with this typeID is already registered (or none provided)
See Also:
Conversation

registerReplaceConversation

protected void registerReplaceConversation(Conversation conv)
Registers a conversation. This object will be cloned when a conversation of this type is required. The conversationTypeID need not be unique; will overwrite a conversation with this typeID if it exists. If a null value is provided, the conversation will be removed (unregistering).
Parameters:
conv - the prototype of the conversation to register
See Also:
Conversation

typeIsRegistered

protected boolean typeIsRegistered(long conversationTypeID)
Checks, wheter a conversation is registered under this id or not. Only usable for verification of existence; does not verify the class associated with this type.
Parameters:
conversationTypeID - the id to check
Returns:
true if a conversation is registered under this id
See Also:
Conversation

initialize

protected void initialize(Object param)
                   throws InitializationException
Initialization of the agent. Will be called only once in the lifetime of the object. Will NOT be called after moving to another host!
Parameters:
param - Generic parameter for the Agent (can be anything the agent knows how to interpret)
Throws:
InitializationException - if an exception occurs during initialization
See Also:
InitializationException

setAgentSystem

final void setAgentSystem(AgentSystem sys)
Method for setting the agent system the agent is in. Used only by the AgentSystem. Package access as only the system itself needs to use it (and may use it for security reasons). Setting the system is logged with current location in the private log.
Parameters:
sys - the AgentSystem
Throws:
SecurityException - if the agent system has already been set

setAgentIdentity

final void setAgentIdentity(AgentIdentity identity,
                            PrivateKey agentPrivateKey)
Method for setting the identity and the private key of the agent. Used only by the AgentSystem. If a public key is included in the identity, a provided private key will be stored under the name "Agents own keys" in the key table. It is not checked, if the public and the private key match. Package access as only the system itself needs to use it (and may use it for security reasons). Setting the identity is logged in the private log.
Parameters:
identity - the identity of the agent
agentPrivateKey - the private key of the agent (ignored if no public key in the identity)
Throws:
SecurityException - if the agents identity has already been set

getKeyPair

protected NamedKeyPair getKeyPair(String name)
Retrieve a keypair from the key-store by its name
Parameters:
name - the name of the keypair
Returns:
the named keypair or null if not found
See Also:
NamedKeyPair

removeKeyPair

protected void removeKeyPair(String name)
Remove a keypair from the key-store
Parameters:
name - the name of the keypair to remove
See Also:
NamedKeyPair

setKeyPair

protected void setKeyPair(NamedKeyPair nkp)
Store a keypair in the key-store under the provided name. Existing keypairs with the same name will be replaced with the new one.
Parameters:
nkp - the named keypair to store
See Also:
NamedKeyPair

getKeyPairs

protected Enumeration getKeyPairs()
Returns an enumeration of all the names, under which keys are stored in the key-store.
Returns:
Enumeration of all names of stored keys
See Also:
NamedKeyPair

getKeyAndCertificate

protected NamedKeyAndCertificate getKeyAndCertificate(String name)
Retrieve a private key and the matching certificate from the certificate-store by its name
Parameters:
name - the name of the certificate
Returns:
the named key and certificate or null if not found
See Also:
NamedKeyAndCertificate

removeKeyAndCertificate

protected void removeKeyAndCertificate(String name)
Remove a private key and the matching certificate from the certificate-store
Parameters:
name - the name of the private key and certificate to remove
See Also:
NamedKeyAndCertificate

setKeyAndCertificate

protected void setKeyAndCertificate(NamedKeyPair nkp)
Store a private key and the matching certificate in the certificate-store under the provided name. Existing private key and certificates with the provided name will be replaced with the new one.
Parameters:
nkp - the named private key and certificate to store
See Also:
NamedKeyAndCertificate

getKeyAndCertificates

protected Enumeration getKeyAndCertificates()
Returns an enumeration of all the names, under which private keys and matching certificates are stored in the certificate-store.
Returns:
Enumeration of all names of stored private keys and certificates
See Also:
NamedKeyAndCertificate

replyToChallenge

public final byte[] replyToChallenge(byte[] challenge)
This method can be used to verify, whether the agent knows a certain private key. To prove it, he has to sign a challenge provided. Encryption cannot be used, as some keys might not be usable for this (e. g. DSA-keys).
To avoid signing some data another agent provided, which might be anything, the challenge is limited to 16 bytes. Additionally, in front and at the end four bytes are appended before signing. This should destroy any meaningful data and prohibit misusing this function. The bytes added are 'P', 'O', 'N', and 'D'.
Any exception will lead to a failure, resulting in a return value of null.
Parameters:
challenge - the challenge, which may consist of up to 16 bytes
Returns:
the signature on the challenge provided

replyToChallenge

public final byte[] replyToChallenge(String keyname,
                                     byte[] challenge)
This method can be used to verify, whether the agent knows a certain private key. To prove it, he has to sign a challenge provided. Encryption cannot be used, as some keys might not be usable for this (e. g. DSA-keys). The keypair to be used is defined through the parameter (This must be the name under which it is store in the key-store).
To avoid signing some data another agent provided, which might be anything, the challenge is limited to 16 bytes. Additionally, in front and at the end four bytes are appended before signing. This should destroy any meaningful data and prohibit misusing this function. The bytes added are 'P', 'O', 'N', and 'D'. Any exception will lead to a failure, resulting in a return value of null.
Parameters:
keyname - the name of the keypair to use for signing (if null, the agents own keys are used; same as providing "Agents own keys")
challenge - the challenge, which may consist of up to 16 bytes
Returns:
the signature on the challenge provided

getAgentName

public String getAgentName()
The public, non-unique plaintext name of the agent.
Returns:
name of the agent or null if no identity set

getIdentity

public AgentIdentity getIdentity()
The identity of the agent (contains the public key).
Returns:
identity of the agent or null if not set

onBeforePersist

protected void onBeforePersist()
                        throws PersistingDeniedException
Called before persisting (When trying to safe the agent to a secondary storage and stop it afterwards). May throw a PersistingDeniedException to avoid or delay this. Take care: The agent system may not allow deferring or disabling persisting, so the agent may be killed in this case!
See Also:
AgentSystem.persist(AgentBase), PersistingDeniedException

onAfterDePersist

protected void onAfterDePersist()
Called after restoring the agent from a secondary storage and before starting it again. You MAY NOT call move, persist, .... from within this!
See Also:
AgentSystem.dePersist(AgentData)

onBeforeMoving

protected void onBeforeMoving()
                       throws MovingDeniedException
Called before moving (When trying to transfer the agent to another host and stop it afterwards). May throw a MovingDeniedException to avoid or delay this. Take care: The agent system may not allow deferring or disabling moving, so the agent may be killed in this case!
See Also:
AgentSystem.move(AgentBase,URL), MovingDeniedException

onAfterMoving

protected void onAfterMoving()
Called after receiving the agent from another host and before starting it again. You MAY NOT call move, persist, .... from within this! This might lead to a deadlock! You CAN send messages from within here.

getAgentSystem

public final AgentSystem getAgentSystem()
Returns the agent system where the agent currently is located.
Returns:
the agent system the agent is currently in
Throws:
SecurityException - if the agent system is not set (This should not happen)

currentLocation

public URL currentLocation()
Returns the current location of the agent in form of an URL. The url could be used to transfer an agent to this agent system (Protocol: AMP; Host: Current hostname; Port: Address of this agent system). Convenience method instead of getAgentSystem.getLocation().
Returns:
the URL for the current agent system.

persist

protected void persist()
Helper function to initiate persisting this agent by itself. Remember not to throw PersistingDeniedException in onBeforePersisting! Will fail silently if the agent could not be serialized. If successful, the method will NOT be returned from if called by the agent.
See Also:
PersistingDeniedException

move

protected void move(URL destination)
             throws ReceiveAgentDeniedException,
                    CannotSendException
Helper function to initiate moving this agent to another system. Remember not to throw MovingDeniedException in onBeforeMoving! If successful, the method will NOT be returned from if called by the agent.
Parameters:
destination - URL for the destination. May be another host or another port to move to another agent system.
Throws:
ReceiveAgentDeniedException - if the remote host denied the agent access
CannotSendException - if there was an error during transfering the agent
See Also:
MovingDeniedException

stopAgent

protected void stopAgent()
Helper function to stop this agent. If successful, the method will NOT be returned from if called by the agent.

logMessage

public void logMessage(String msg)
Adds the message to the internal log. The current date and time are automatically added at the beginning.
Parameters:
msg - the message to add to the log

writeLogTo

protected void writeLogTo(PrintWriter out)
Writes the log to a PrintWriter stream.
Parameters:
out - the stream to write the log to

getLog

protected Vector getLog()
Returns a copy of the log
Returns:
a copy of the log (each line is a entry in the Vector)

run

public final void run()
The main method which is run when the agent is started. Final so it cannot be changed. By default, messaging is used. If other work should be done, overwrite agentMain.
Overrides:
run in class CancellableThread
Throws:
IllegalStateException - if the agent system or the agents identity is not set
ThreadDeath - if terminated from within its own thread
Error - if the agents main thread terminated because of an exception or error
See Also:
agentMain()

agentMain

protected void agentMain()
Main loop of the agent. If no messaging is desired, this method can be overwritten. Please note, that the agent will be terminated (and consequently destroyed) after leaving this method.

getNextMessage

protected MessageType getNextMessage()
                              throws InterruptedException
Retrieve the next message in the queue. This method will block until either a message is available (which will be returned), or it is interrupted (in which case it will rethrow this exception).
Returns:
the next message in the queue
Throws:
InterruptedException - if the agent was waiting for a message but was interrupted

addMessage

public final void addMessage(MessageType msg)
Add a message to the queue. It will always be appended at the end. If debugging, a line will be printed if more than 10 messages are in the queue.

newConversation

public Conversation newConversation(long convTypeID,
                                    AgentIdentity counterpart)
Method for creatign a new conversation. It is only created, not started. The conversation may not yet receive messages.
createConversationAllowed is NOT checked here: The user should know when he wants to start which conversation!
Parameters:
convTypeID - type of the conversation to create
counterpart - the identity of the other agent. null if there is no single other agent (e. g. for sending broadcasts)
Returns:
the newly created conversation or null is the conversation type ID is wrong (i. e. unknown conversation type)
See Also:
startConversation(Conversation)

createConversationAllowed

protected boolean createConversationAllowed(long convTypeID)
Checks, whether it is currently allowed to create this type of conversation. This implementation always returns true.
Parameters:
convTypeID - the type id od the conversation, which shall be created
Returns:
true if it is currently allowed to create this type of conversation
See Also:
Conversation

startConversation

public boolean startConversation(Conversation conv)
Starts a conversation. The method handleMessage will be called with a null parameter. After this method has completed, the conversation can receive messages.
Parameters:
conv - the conversation to start
Returns:
true if successfully started (return value from conv.handleMessage(null))
See Also:
Conversation

endConversation

void endConversation(Conversation conv,
                     boolean shouldArchive)
Ends a conversation. The conversation can no longer receive messages. If the conversation shall be archived, it is placed into the conversationsArchive under the key "Long(conversation ID)". Package access. May only be called from within the conversation.
Parameters:
conv - the conversation to stop
shouldArchive - true if the conversation shall be moved to the conversationsArchive
See Also:
Conversation

sendMessage

protected void sendMessage(Message msg)
                    throws MessageException
Sends a message to another agent. May not be a broadcast (use broadcastMessage for this).
Parameters:
msg - the message to send
Throws:
MessageException - if an error occured during sending the message

broadcastMessage

protected void broadcastMessage(BroadcastMessage msg)
                         throws MessageException
Sends a message to all other local agents. Must be a broadcast (use sendMessage for other).
Parameters:
msg - the message to send
Throws:
MessageException - if an error occured during sending the message

endConversations

void endConversations()
Terminates all ongoing conversations and removes all messages pending handling.

addOwnExperience

protected void addOwnExperience(Statement stat,
                                boolean broadcast)
Adds a statement to our own experiences. Can be broadcast to all other agents or remain private according to the second parameter.
Parameters:
stat - the statement to add
broadcast - if true, the statement will be broadcast to all other agents
See Also:
ExperienceExchangeConversation

getExperiences

public Experiences getExperiences()
Returns the experiences object of this agent. Public needed, as ExperienceExchangeConversation is in another package
Returns:
the experiences object of this agent

writeExperiencesTo

protected void writeExperiencesTo(PrintWriter out)
Dump the experiences to a stream. Useful for testing
Parameters:
out - the PrintWriter stream to write the experience data to

addPermissionListener

protected final void addPermissionListener(PermissionChangeListener listener)
Add a listener for permission changes. If already in the list, the request is ignored.
Parameters:
listener - the listener to add

removePermissionListener

protected final void removePermissionListener(PermissionChangeListener listener)
Remove a listener for permission changes. Does nothing if this listener is currently not registered.
Parameters:
listener - the listener to remove

firePermissionChange

final void firePermissionChange(PermissionEvent permEvent)
Call this to send a PermissionEvent to all registered listeners. Package access as only internally used.
Parameters:
permEvent - the event to distribute

verifySignedMessage

public boolean verifySignedMessage(SignedMessage msg)
To verify a signed message. In this standard implementation it must be signed with our own private key. Verification will fail if the signature does not match or any error occurs. Override to use other keys.
Parameters:
msg - the signed message
Returns:
true if the signature was successfully verified

getArchivedConversation

protected Conversation getArchivedConversation(long convID)
Retrieve a certain conversation from the archive.
Parameters:
convID - the ID of the conversation to retrieve
Returns:
the retrieved conversation or null if this is an invalid ID or the conversation was not archived (or did not exist)

getArchivedConversationIDs

protected long[] getArchivedConversationIDs()
Retrieve the IDs of all archived conversations.
Returns:
an array of all the IDs of the archived conversations

getOngoingConversation

protected Conversation getOngoingConversation(long convID)
Retrieve a certain currently ongoing conversation.
Parameters:
convID - the ID of the conversation to retrieve
Returns:
the retrieved conversation or null if this is an invalid ID or the conversation does not currently exists

getOngoingConversationIDs

protected long[] getOngoingConversationIDs()
Retrieve the IDs of all currently ongoing conversations.
Returns:
an array of all the IDs of the ongoing conversations

hasPermission

public boolean hasPermission(Permission perm)
Allows the agent to inquiry whether he currently actually has a permission (NOT "could get it", ...). Just a convenience function.
Parameters:
perm - the permission the agent wants to know about (if null, return true)
Returns:
true if the agent currently has this permission

Agent System POND 1.2 (28.2.2002)

Submit a bug

Copyright 2001,2002 Michael Sonntag & Institute for Information Processing and Microprocessor Technology (FIM), Johannes-Kepler-University Linz, Altenbergerstr. 69, A-4040 Linz, Austria.