public abstract class AbstractProcess extends Thread implements ProcessInterface, PolicyAgentInterface, CasaObservable, Comparable<AbstractProcess>, TraceInterface
This class contains the basic methods for any process. It's primary responsibility is sending and receiving
messages. Messages (MLMessage
) are sent directly using either local calls (if the other agent happens
to be in the same process) or TCP/IP. Messages (and other Event
s) are received by removing them an
EventQueue
, which is populated by the AbstractProcess's sister thread, a SocketServer
.
One of ABstractProcess's most important functions is to monitor the event queue in an event loop, removing items (such
as messages) for processing (via processEvent(Event)
or, if there is nothing in the event queue,
calling processCommitments()
. (If there's nothing left to do, it just sleeps.)
The class makes use of several important methods as part of the event loop (which listens for incoming messages and other events):
message loop status | method called | function |
---|---|---|
not started | initializeConstructor(ParamsMap, AgentUI, int) |
pre-loop init, called once only, during the constructor, and in the thread of the caller, not the agent's thread. |
initializeThread(ParamsMap, AgentUI) |
pre-loop init, called once only, before theevent loop starts, and in the agent's main thread, not the caller's thread.
This is called before the agent is registered (see TransientAgent.initializeAfterRegistered(boolean) for the method called after the agent is registered with the LAC . |
|
running | eventBufferLoopBody() |
implements the body of the loop, called repeatedly. The default version will call doIdle() if there's no messages available |
pendingFinishRun() |
called when an exit() has been called, called only once | |
finished | finishRun() |
called after the message loop has exited, called only once |
When overriding these methods, be sure to call the super version to avoid crippling the functionality of the process.
In addition, there are several important virtual methods having to do with
message handling. All of these methods should return a Status
with a value of:
method | comment |
---|---|
handleEvent(Event) |
Normal handling of incoming messages. See TransientAgent.handleEvent(Event) . |
#resolveConnectException(MLMessage) |
This method is called when a send has failed due to a
ConnectionException, which might have been caused by an unresolved URL.
The subclass can resolve the URL (as
TransientAgent#resolveConnectException(MLMessage) does) and
return 0 to cause the send to be retried (once). AbstractProcess's
default is to do nothing and return -1. |
unhandledMessage(MLMessage) |
This method is called as a last-ditch effort to handle the message, after all other normal processing has not handled it (as opposed to failing). AbstractProcess's default is to reply with a not-understood message. This method has a void return |
When overriding these methods, be sure to call the super version so that superclasses may handle any relevant messages that your class does not.
Other important messages are:
sendMessage(MLMessage)
sendMessage(String, String, URLDescriptor, String...)
sendRequestAndWait(MLMessage, long, MessageEventDescriptor...)
sendRequestAndWait(String, String, URLDescriptor, String[])
Copyright: Copyright 2003-2014, Knowledge Science Group, University of Calgary. Permission to use, copy, modify, distribute and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. The Knowledge Science Group makes no representations about the suitability of this software for any purpose. It is provided "as is" without express or implied warranty.
TransientAgent
,
ProcessInterface
Modifier and Type | Class and Description |
---|---|
class |
AbstractProcess.Subthread |
Thread.State, Thread.UncaughtExceptionHandler
Modifier and Type | Field and Description |
---|---|
private static CasaLispOperator |
AGENT__SHOW_EVENT_QUEUE
Lisp operator: (SHOW-EVENTQUEUE)
Show the agent's events on the event queue. |
(package private) EventQueue |
eventQueue
The agent's event queue.
|
private boolean |
exit
Set by
exit() to signal the agent to exit. |
private boolean |
exited
Set when the agent is fully existed and not longer accepting any messages
|
(package private) int |
exitWaitCounter |
private static CasaLispOperator |
GET_HOST_NAMES
Lisp operator: (GET-HOST-NAMES)
Show the host names for this computer. |
private static CasaLispOperator |
GET_INETADDRESSES
Lisp operator: (GET-INETADDRESSES)
Show the host names for this computer. |
(package private) long |
heartbeat
The interval (in milliseconds) that the agent should sleep if it has nothing else to do.
|
protected boolean |
huntForPort
True if this agent is to keep looking for a port if it fails to open
the port suggested in the constructor.
|
private boolean |
initializationComplete |
protected ParamsMap |
initParams |
private AgentUI |
initUI |
private static int |
maxPort
The normal maximum range of agent lister port numbers
|
private static int |
minPort
The normal minimum range of agent lister port numbers
|
private CasaObservableObject |
observerDelegate
This class should actually multiply inherit from Thread and CasaObservable,
but this is Java, so it can't: Instead we're forced to hold this reference
to an ObservableState object.
|
protected Ontology |
ontology
The performative type hierarchy for this agent
|
protected static Ontology |
ontologyShared |
ProcessOptions |
options
The user-setable and potential persistent options for this object type.
|
private boolean |
pause
Set to true to pause the agent at the next message send or recieve
|
private static int |
portCounter
Agents use this static as a place to start when searching for ports.
|
private boolean |
portOpen
True whenever the message listener port is open
|
private int |
reqID
A number to be used to generate unique reply-with fields in
messages.
|
protected SecurityFilterInterface |
securityFilter
The security filter used to encode/decode outgoing/incoming messages
|
private SocketServerInterface |
socketServer
The Listener thread that will queue incoming messages to the event queue
(see
eventQueue ). |
private Thread |
starter
used only to signal the starting thread that this agent is up and running
|
private long |
subthreadID |
protected Trace |
trace
the Trace object that handles debugging traces and messages
|
static int |
TRACE_MONITOR
Constant as a bit mask to signal tracing to a monitor window
|
static int |
TRACE_OFF
Constant as a bit mask to signal tracing is off
|
static int |
TRACE_ON
Constant as a bit mask to signal tracing is on
|
static int |
TRACE_TO_FILE
Constant as a bit mask to signal tracing to a log file
|
static int |
TRACE_UNDEFINED
Constant as a bit mask to signal the trace mode is undefined
|
(package private) ConcurrentSkipListSet<Transformation> |
transformations |
protected static int |
uniqueThreadName |
private URLDescriptor |
url
The URL of this object
|
boolean |
waitingForAgentToStart
Used only by
#makeAgentInThisProc(ParamsMap, AgentUI) and run() to synchronize the start of the socket server. |
(package private) boolean |
waitingForEvent
used by
eventBufferLoopBody() and EventQueue.notifyNewItem(Event) to notify of events being placed in the queue |
(package private) boolean |
waitingForSocketServerToStart
Used only by
startSocketServer() and SocketServerTCPIP.run() to synchronize the start of the socket server. |
MAX_PRIORITY, MIN_PRIORITY, NORM_PRIORITY
Constructor and Description |
---|
AbstractProcess(ParamsMap params,
AgentUI ui,
int port)
Constructor.
|
Modifier and Type | Method and Description |
---|---|
abstract void |
addConversation(String convID,
Conversation conv) |
void |
addObserver(Observer observer)
Part of the Observable interface from the observer pattern (Gamma et al.).
|
void |
addObserver(Observer o,
String... notifyTypes) |
void |
addObserver(URLDescriptor observer)
Extension to the Observable interface from the observer pattern (Gamma et al.).
|
void |
addObserver(URLDescriptor observer,
String... notifyTypes) |
int |
addTraceTags(String tags)
Adds a comma-delimited list of trace tags to a string.
|
void |
addTransformation(Transformation trans) |
boolean |
authorizeMessage(MLMessage msg)
Determines whether the given message should be handled by receiveMessage,
or if it should be thrown out.
|
void |
bump()
wakes up the agent if it is sleeping waiting for an event to happen
|
void |
clearAllTraceTags()
Turns off ALL the trace tags.
|
void |
closePort()
Method to close the module's open port and return it to the system.
|
int |
compareTo(AbstractProcess o) |
int |
countObservers() |
void |
defer(Runnable x)
Can be used to defer a section of code on to the agent's event queue so that the code
will execute in the agent's main thread.
|
void |
defer(Runnable x,
long milliseconds)
Can be used to defer a section of code on to the agent's event queue so that the code
will execute in the agent's main thread.
|
void |
deleteObserver(Observer observer)
Part of the Observable interface from the observer pattern (Gamma et al.).
|
void |
deleteObserver(URLDescriptor observer)
Extension to the Observable interface from the observer pattern (Gamma et al.).
|
void |
deleteObservers() |
void |
dequeueEvent(Event event)
Remove the event from the agent's event queue
iff the event is already in the queue
|
boolean |
equals(Object other) |
private void |
eventBufferLoop()
The basic loop where this process checks for incoming messages on it's
socket port.
|
protected void |
eventBufferLoopBody()
This method is called by
eventBufferLoop() and may be overridden
by a subclass as the actual code to dequeue messages off the queue. |
protected void |
eventBufferLoopPeriodic()
Deprecated.
|
protected Event |
eventQueuePeek() |
boolean |
existed() |
void |
exit()
Tells the process to exit.
|
protected void |
finalize() |
protected void |
finishRun()
Subclasses may override this method to cleanup after the
message loop exits and the agent is about to terminate.
|
void |
fixupMessage(MLMessage message)
corrects message fields like message timeout if bad
|
static AbstractProcess |
getAgent() |
String |
getAgentName()
Returns the name of the current process
|
protected abstract SocialCommitment |
getChosenCommitment() |
abstract LinkedList<Conversation> |
getConversation(String convID) |
protected String |
getEventQueue() |
ParamsMap |
getInitParams() |
MLMessage |
getNewMessage(String performative,
String act,
URLDescriptor reciever)
Creates a basic message with the given performative, act, and reciever.
|
MLMessage |
getNewMessage(String performative,
String act,
URLDescriptor reciever,
String... list)
Creates a basic message with the given performative, act, and reciever.
|
ProcessOptions |
getOptions()
Returns a reference to this object's
ProcessOptions object. |
int |
getPort()
Returns the port that this agent is listening on.
|
SocketServerInterface |
getSocketServer() |
abstract String |
getStrategy()
Returns the strategy that this agent uses to interpret messages.
|
Trace |
getTrace()
get the associated
Trace object. |
String |
getTraceTags() |
Transformation |
getTransformationFor(Describable d) |
String |
getUniqueRequestID()
Returns a unique string that can be conveniently used in the reply-with and
in-reply-to fields of a message.
|
URLDescriptor |
getURL()
Returns a copy of the URL of the current process
|
boolean |
getUseAckProtocol()
Retrieves whether this agent will use the the Ack (acknowledge) protocol.
|
boolean |
getUsePriority()
Get the state of using message queue priorities.
|
protected abstract void |
handleEvent(Event event)
This method is called from
processEvent(Event) . |
protected abstract boolean |
hasActiveCommitments() |
boolean |
hasChanged() |
abstract boolean |
hasConversation(String convID)
Abstract classes for managing agent conversations.
|
boolean |
hasOpenPort()
Tests if this process has any open ports.
|
void |
in(String methodName)
Debugging method: should be the first line of every method in this class and
in every subclass.
|
protected void |
initializeConstructor(ParamsMap params,
AgentUI ui,
int port)
Initializes all local variables and starts up the listener thread (to listen
for and queue up any incoming messages).
|
protected void |
initializeThread(ParamsMap params,
AgentUI ui)
Subclasses may override this method to initialize before the message loop is called,
after the constructor is finished but before control is returned to the thread
that called the constructor.
|
protected URLDescriptor |
initializeURL(int port,
String name)
Initialize the URL for this object.
|
boolean |
isA(Act child,
Act ancestor)
Determines if child is a subtype of (or the same type as the act
named by the String ancestor.
|
boolean |
isA(Act child,
String ancestor)
Determines if child is a subtype of (or the same type as the act
named by the String ancestor.
|
boolean |
isA(String child,
Act ancestor)
Determines if child is a subtype of (or the same type as the act
named by the String ancestor.
|
boolean |
isA(String child,
String ancestor)
Determines if child is a subtype of (or the same
type as) ancestor.
|
boolean |
isAAct(Act child,
Act ancestor)
Determines if child is a subtype of (or the same type as the act
named by the String ancestor.
|
boolean |
isAAct(String child,
String ancestor) |
boolean |
isAgentThread() |
boolean |
isAPerformative(MLMessage m,
String ancestor)
Determines if performative field of message m is a subtype of (or the same
type as the performative named by the String performative.
|
boolean |
isAPerformative(String child,
String ancestor)
Determines if child is a subtype of (or the same
type as the performative named by the String ancestor.
|
protected boolean |
isEventQueueReady()
Determines if the event queue has an event ready to process.
|
boolean |
isExiting()
determines if this process is in the process of exiting.
|
boolean |
isInitialized() |
boolean |
isLoggingTag(String tag)
Returns true if the process is logging tag, tag is "error," or tag is null
|
boolean |
isObserveMessages() |
boolean |
isPaused()
Determines if the agent is currently in the pause state.
|
boolean |
isStoppable()
determines if this process can be stopped.
|
boolean |
isThisMyAddress(URLDescriptor theURL) |
boolean |
isTracing()
Is tracing on?
|
static void |
loadClass(String className) |
protected ProcessOptions |
makeOptions()
Factory method to make a new options object.
|
Thread |
makeSubthread(Runnable runnable)
Creates a new thread in the same
ThreadGroup as this agent, with the agent
specified. |
Thread |
makeSubthread(Runnable runnable,
String name)
Creates a new thread in the same
ThreadGroup as this agent, with the agent
specified. |
protected int |
makeTraceParam()
Used to make a trace parameter integer that matches the current options.
|
void |
notifyObservers() |
void |
notifyObservers(String eventType,
Object argument) |
void |
notifyObserversWithNoArg(String notifyType)
Notify with no arguments
|
void |
notifyObserversWithTop(Object arg)
TOP is the notification type
|
protected void |
notifySendingMessage(MLMessage message)
This method is to be overridden by any subclasses that wish to be informed
whenever a message is actually sent out.
|
void |
out(String methodName)
Debugging method: should be the last line of every method (and every exiting
branch) in this class and
in every subclass.
|
private void |
pauseCheck()
Checks for the pause state and wait()'s until interuped if paused.
|
protected void |
pendingFinishRun()
Subclasses may override this method to cleanup after an
exit() has been
called, but before the
message loop exits and the agent is about to terminate. |
String |
println(String traceTag,
String txt)
Debugging or error method: Uses the
Trace object to log the
string if appropriate (ie: the traceTAg matches a tag that's turned on
in the Trace object. |
String |
println(String traceTag,
String txt,
int flags)
Equivalent to
println(tag, string, null, flag) |
String |
println(String traceTag,
String txt,
Status tempStatus)
Deprecated.
|
String |
println(String traceTag,
String txt,
Throwable ex)
Same as
println(String, String) but appends ex.toString() and prints
a stack trace after. |
String |
println(String traceTag,
String txt,
Throwable ex,
int flags)
This is the println method that defines all the other println methods.
|
protected abstract SocialCommitment |
processCommitment(SocialCommitment sc) |
protected SocialCommitment |
processCommitments()
Subclasses will normally override this.
|
private void |
processEvent(Event event)
This method is a pre-processing step before the event from the event queue is passed
passed on to
handleEvent(Event) for actual processing event. |
void |
queueEvent(Event event)
Queues an event to the agent's event queue
|
void |
queueEventIf(Event event)
Put the Event on the agent's event queue
iff the event is not already on the queue.
|
void |
realizeAgentBehaviourFromOptions()
Refresh agent behaviour from the options object.
|
abstract Conversation |
removeConversation(Conversation conv) |
int |
removeTraceTags(String tags)
Removes the tags in the comma-delimited streams specified in tags.
|
protected void |
resetRuntimeOptionsFromCommandLine() |
protected void |
resetSecurityPackage(String pack) |
protected void |
resetTraceOptions()
Synchronize the trace options with what's actually happening: if
options
says we're monitoring, start the monitor; if they say to log to a file, make
sure the file is open for logging. |
protected Status |
resolveConnectException(MLMessage msg,
Runnable1<String,Status> cmd)
This method may be overridden by a subclass to handle a ConnectionException
during a call to sendMessage(MLMessage).
|
Describable |
revTransform(Describable d) |
String |
revTransform(String d) |
void |
run()
This method starts the message handling loop
by calling
eventBufferLoop() , which actually does the loop. |
(package private) Status |
sendMessage_primitive(MLMessage message,
boolean... shouldResolve)
Sends the message to the the message.receiver or, if
message.receiver is missing or empty, to message.to.
|
Status |
sendMessage(MLMessage message)
Sends the message to the the message.receiver or, if
message.receiver is missing or empty, to message.to.
|
Status |
sendMessage(String performative,
String act,
URLDescriptor reciever,
String... list)
Utility method to construct and send a message asynchronously using
sendMessage(MLMessage) . |
protected StatusObject<MLMessage> |
sendMessageAndWait(MLMessage message,
long timeout,
MessageEventDescriptor... messageDescriptors)
Sends a message, message, waiting up to timeout milliseconds
for the request transaction to complete, and returns as StatusObject which contains
the final message, if it completed.
|
protected StatusObject<MLMessage> |
sendQueryAndWait(MLMessage message,
long timeout,
MessageEventDescriptor... messageDescriptors)
Sends a QUERY (QUERY-REF or QUERY-IF) message, message, waiting up to timeout milliseconds
for the query transaction to complete, and returns as StatusObject which contains
the final message, if it completed.
|
protected StatusObject<MLMessage> |
sendRequestAndWait(MLMessage message,
long timeout,
MessageEventDescriptor... messageDescriptors)
Sends a REQUEST message, message, waiting up to timeout milliseconds
for the request transaction to complete, and returns as StatusObject which contains
the final message, if it completed.
|
MLMessage |
sendRequestAndWait(String performative,
String act,
URLDescriptor reciever,
String... list)
Utility method to construct and send a syncronous message using
sendRequestAndWait(MLMessage, long, MessageEventDescriptor...) . |
void |
setAllTraceTags()
Turns all ALL the trace tags.
|
void |
setObserveMessages(boolean newVal)
Set whether the agent will ignore or process messages that are not
addressed to it (broadcaste messages never ignored).
|
void |
setOptions(ProcessOptions options)
Sets this object's ProcessOptions object.
|
void |
setPause(boolean val)
Set or clear the agent pausing immediately after processing the next message send
or recieve.
|
int |
setTraceTags(String tags)
Works the same as addTraceTags, but removes all previous tags beforehand.
|
void |
setTracing(boolean doTrace)
Turn tracing on / off.
|
void |
setURL(URLDescriptor url)
Sets the URL of for current process
|
boolean |
setUseAckProtocol(boolean b)
Sets whether this agent will use the the Ack (acknowledge) protocol.
|
void |
setUsePriority(boolean newVal)
Set the use of message priorities.
|
private boolean |
someTriggered(MessageObserverEvent[] events) |
protected void |
startSocketServer()
Start the SocketServer and initialize the eventQueue
|
void |
startTraceMonitor()
Display the trace monitor window.
|
void |
step()
If the agent is is the pause state, activates (resumes) the agent until processing the
next sent or recieved message.
|
Describable |
transform(Describable d) |
String |
transform(String d) |
protected void |
unhandledMessage(MLMessage message)
Subclasses may override this method to override default processing of
unhandled messages.
|
void |
update(Observable o,
Object arg) |
void |
updateOptions()
Save the options to a persistent database.
|
activeCount, checkAccess, clone, countStackFrames, currentThread, destroy, dumpStack, enumerate, getAllStackTraces, getContextClassLoader, getDefaultUncaughtExceptionHandler, getId, getName, getPriority, getStackTrace, getState, getThreadGroup, getUncaughtExceptionHandler, holdsLock, interrupt, interrupted, isAlive, isDaemon, isInterrupted, join, join, join, resume, setContextClassLoader, setDaemon, setDefaultUncaughtExceptionHandler, setName, setPriority, setUncaughtExceptionHandler, sleep, sleep, start, stop, stop, suspend, toString, yield
getClass, hashCode, notify, notifyAll, wait, wait, wait
getName
abclEval, abclEval, abclEval, chooseSC, dispatchMsgHandlerMethod, evesdrop, executeCommand, getKnowledgeBase, getName, getOntology, getSCStore, getSubscribeEvents
private CasaObservableObject observerDelegate
private URLDescriptor url
private SocketServerInterface socketServer
eventQueue
).EventQueue eventQueue
private int reqID
getUniqueRequestID()
.private boolean exit
exit()
to signal the agent to exit.private boolean exited
protected boolean huntForPort
private static final int minPort
private static final int maxPort
private static int portCounter
private boolean portOpen
protected final Trace trace
public static final int TRACE_UNDEFINED
public static final int TRACE_OFF
public static final int TRACE_ON
public static final int TRACE_MONITOR
public static final int TRACE_TO_FILE
public ProcessOptions options
protected Ontology ontology
protected static Ontology ontologyShared
protected SecurityFilterInterface securityFilter
private final Thread starter
ConcurrentSkipListSet<Transformation> transformations
private boolean initializationComplete
protected ParamsMap initParams
private AgentUI initUI
volatile boolean waitingForSocketServerToStart
startSocketServer()
and SocketServerTCPIP.run()
to synchronize the start of the socket server.public volatile boolean waitingForAgentToStart
#makeAgentInThisProc(ParamsMap, AgentUI)
and run()
to synchronize the start of the socket server.volatile boolean waitingForEvent
eventBufferLoopBody()
and EventQueue.notifyNewItem(Event)
to notify of events being placed in the queueint exitWaitCounter
long heartbeat
protected static int uniqueThreadName
private boolean pause
private long subthreadID
private static final CasaLispOperator AGENT__SHOW_EVENT_QUEUE
private static final CasaLispOperator GET_HOST_NAMES
private static final CasaLispOperator GET_INETADDRESSES
public AbstractProcess(ParamsMap params, AgentUI ui, int port) throws IPSocketException
initialize()
method.params
- The parameters for creating this agentui
- The UI to use to report any problemsport
- The port number this process will use for communication with other objects. A -ve value indicates the agent should search starting with this port; +ve means it should fail if it can't open this port; 0 means it should choose it's own port.IPSocketException
- when trying to bind to an IPSocket (port)
that is either in use or invalid. See the port param above.public static final void loadClass(String className)
public SocketServerInterface getSocketServer()
public boolean existed()
protected final int makeTraceParam()
public void addTransformation(Transformation trans)
addTransformation
in interface PolicyAgentInterface
public Transformation getTransformationFor(Describable d)
getTransformationFor
in interface PolicyAgentInterface
public Describable transform(Describable d)
transform
in interface PolicyAgentInterface
public Describable revTransform(Describable d)
revTransform
in interface PolicyAgentInterface
public String transform(String d)
transform
in interface PolicyAgentInterface
public String revTransform(String d)
revTransform
in interface PolicyAgentInterface
public final boolean isInitialized()
initializeThread(ParamsMap, AgentUI)
and in running its main thread.public ParamsMap getInitParams()
protected void initializeConstructor(ParamsMap params, AgentUI ui, int port) throws Exception
params
- The parameters for initializing this agentui
- port
- int this process will use for communication with other objects. A -ve value indicates the agent should search starting with this port; +ve means it should fail if it can't open this port; 0 means it should choose it's own port.IPSocketException
Exception
public boolean isAgentThread()
protected void resetRuntimeOptionsFromCommandLine()
protected void resetTraceOptions()
options
says we're monitoring, start the monitor; if they say to log to a file, make
sure the file is open for logging.protected ProcessOptions makeOptions()
public abstract boolean hasConversation(String convID)
public abstract LinkedList<Conversation> getConversation(String convID)
public abstract Conversation removeConversation(Conversation conv)
public abstract void addConversation(String convID, Conversation conv)
public boolean isAPerformative(MLMessage m, String ancestor)
isAPerformative
in interface PolicyAgentInterface
m
- the message under questionancestor
- the String name of the performative that's expected to be a super typepublic boolean isAPerformative(String child, String ancestor)
isAPerformative
in interface PolicyAgentInterface
isAPerformative
in interface ProcessInterface
child
- the name of the proposed child typeancestor
- the name of the proposed ancestor of the childpublic boolean isA(String child, String ancestor)
isA
in interface PolicyAgentInterface
isA
in interface ProcessInterface
child
- the name of the proposed child type; null is taken as "top"ancestor
- the name of the proposed ancestor of the child; null is taken as "top"public boolean isA(Act child, Act ancestor)
isA
in interface PolicyAgentInterface
child
- the name of the proposed child typeancestor
- the name of the proposed ancestor of the childpublic boolean isA(String child, Act ancestor)
isA
in interface PolicyAgentInterface
child
- the name of the proposed child typeancestor
- the name of the proposed ancestor of the childpublic boolean isA(Act child, String ancestor)
isA
in interface PolicyAgentInterface
child
- the name of the proposed child typeancestor
- the name of the proposed ancestor of the childpublic boolean isAAct(Act child, Act ancestor)
isAAct
in interface PolicyAgentInterface
child
- the name of the proposed child typeancestor
- the name of the proposed ancestor of the childprotected URLDescriptor initializeURL(int port, String name)
port
- The port that this object will open on (if -ve it's changed to its absolute value)name
- The name of the agent. Can be either with a path or not (in
which case, the class name us used to infer a path)public void in(String methodName)
trace
.in() to log the invocation
of the method.methodName
- The string name of the method in the form "[className].[methodName]"public void out(String methodName)
trace
.out() to log the exiting
of the method.methodName
- The string name of the method in the form "[className].[methodName]"public URLDescriptor getURL()
getURL
in interface PolicyAgentInterface
getURL
in interface ProcessInterface
public String getAgentName()
getAgentName
in interface ProcessInterface
public abstract String getStrategy()
getStrategy
in interface ProcessInterface
public void setURL(URLDescriptor url)
url
- a reference to URLDescriptor that will become this agent's URLpublic boolean getUseAckProtocol()
getUseAckProtocol
in interface PolicyAgentInterface
getUseAckProtocol
in interface ProcessInterface
public boolean setUseAckProtocol(boolean b)
setUseAckProtocol
in interface ProcessInterface
b
- true to set the protocol, false to not use the protocol.public ProcessOptions getOptions()
ProcessOptions
object.getOptions
in interface PolicyAgentInterface
getOptions
in interface ProcessInterface
ProcessOptions
object.public void setOptions(ProcessOptions options)
setOptions
in interface ProcessInterface
options
- a reference to a ProcessOptions object will become this agent's
options objectpublic void updateOptions()
updateOptions
in interface ProcessInterface
public void realizeAgentBehaviourFromOptions()
realizeAgentBehaviourFromOptions
in interface ProcessInterface
public boolean authorizeMessage(MLMessage msg)
msg
- contains the message to authorizetrue
if the message is authorized to be processed;
false
otherwisepublic void fixupMessage(MLMessage message) throws URLDescriptorException
message
- the message to correctURLDescriptorException
- thrown if the receiver URL in the message is badpublic Status sendMessage(MLMessage message)
getUseAckProtocol()
returns true).
options
.minTimeout
if it is missing or
or malformed or less than current time plus options.minTimeout (the exception
is it is a subscribe message and message.timeout==0,
which means "no timeout on the standing request").
#resolveConnectException(MLMessage)
. Normally, this will be because
of an unresolved recipient URL. If resolveConnectException() is able to
resolve the URL and returns 0, the send will be tried one more time.sendMessage
in interface MessageSender
sendMessage
in interface PolicyAgentInterface
sendMessage
in interface ProcessInterface
message
- MLMessage of the message being sent, which
contains the info about the recipient in the receiver or
to fields.IPMessage
final Status sendMessage_primitive(MLMessage message, boolean... shouldResolve) throws URLDescriptorException, IOException
#resolveConnectException(MLMessage)
. Normally, this will be because
of an unresolved recipient URL. If resolveConnectException() is able to
resolve the URL and returns 0, the send will be tried one more time.message
- MLMessage of the message being sent, which
contains the info about the recipient in the receiver or
to fields.shouldResolve
- Uses only by recursive calls: Do not use.URLDescriptorException
IOException
public Status sendMessage(String performative, String act, URLDescriptor reciever, String... list)
sendMessage(MLMessage)
.performative
- the performative field of the messageact
- the act fieldreciever
- the URL of the message recieverlist
- an array of key/value pairs (keys are even, values are odd).
Key may not be null, but values may be.sendMessage(MLMessage)
public MLMessage sendRequestAndWait(String performative, String act, URLDescriptor reciever, String... list)
sendRequestAndWait(MLMessage, long, MessageEventDescriptor...)
.performative
- the performative field of the messageact
- the act fieldreciever
- the reciever fieldlist
- an array of key/value pairs (keys are even, values are
odd). Key may not be null, but values may be.RuntimeException
- if the list parameter is malformedprotected void notifySendingMessage(MLMessage message)
message
- Exception
protected Status resolveConnectException(MLMessage msg, Runnable1<String,Status> cmd)
msg
- the MLMessage the generated a ConnectionException on send.protected StatusObject<MLMessage> sendRequestAndWait(MLMessage message, long timeout, MessageEventDescriptor... messageDescriptors) throws UnsupportedOperationException
If the messageDescriptor's are left out, this method will generate descriptors for PROPOSE/DISCHARGE|PERFORM|x, FAILURE/DISCHARGE|PERFORM|x, REFUSE/REQUEST|x, and NOT_UNDERSOOD/REQUEST|x.
message
- The message to send, which should be a properly-addressed REQUEST message.timeout
- the time in milliseconds to wait if no event occursmessageDescriptors
- describing all the possible events to watch for the message, defaults to typical request protocol.UnsupportedOperationException
- if the message is somehow mangledprotected StatusObject<MLMessage> sendQueryAndWait(MLMessage message, long timeout, MessageEventDescriptor... messageDescriptors) throws UnsupportedOperationException
If the messageDescriptor's are left out, this method will generate descriptors for QUERY-IF-REPLYs or QUERY-REF-REPLYs respectively (depending on the message performative).
message
- The message to send, which should be a properly-addressed REQUEST message.timeout
- the time in milliseconds to wait if no event occursmessageDescriptors
- describing all the possible events to watch for the message, defaults to typical query protocol.UnsupportedOperationException
- if the message is somehow mangledprotected StatusObject<MLMessage> sendMessageAndWait(MLMessage message, long timeout, MessageEventDescriptor... messageDescriptors) throws UnsupportedOperationException
message
- The message to send, which should be a properly-addressed REQUEST message.timeout
- the time in milliseconds to wait if no event occursmessageDescriptors
- describing all the possible events to watch for the message.UnsupportedOperationException
- if the message is somehow mangled or you don't supply the messageDescriptorsprivate boolean someTriggered(MessageObserverEvent[] events)
protected abstract void handleEvent(Event event)
processEvent(Event)
. It should be overridden in
subclasses to add actual behaviour. The overriding method should normally
call and return super.handleMessage() if it doesn't handle the message.
An overriding method should return:
event
- The recieved messageprotected void startSocketServer() throws IPSocketException
IPSocketException
public void queueEvent(Event event)
queueEvent
in interface PolicyAgentInterface
event
- the event to queuepublic void queueEventIf(Event event)
queueEventIf
in interface PolicyAgentInterface
event
- The event to queue.public void dequeueEvent(Event event)
dequeueEvent
in interface PolicyAgentInterface
event
- The event to dequeue.public final void run()
eventBufferLoop()
, which actually does the loop.
If messageBufferLoop() returns, run() signals socketServer
to exit and sends a inform/exit message to self so that socketServer
will wake up to exit.public boolean isStoppable()
eventQueue
is empty and there are no (non-standing-request) requests
with replies pending.isStoppable
in interface ProcessInterface
public void exit()
isStoppable()
is true before
it can actually exit (terminate eventBufferLoop()
). In the event this
method is called more than once, it will only call pendingFinishRun()
the first time.exit
in interface ProcessInterface
public boolean isExiting()
isExiting
in interface ProcessInterface
protected void initializeThread(ParamsMap params, AgentUI ui)
quals
- protected void pendingFinishRun()
exit()
has been
called, but before the
message loop exits and the agent is about to terminate. Called once, just
before the message loop terminates.
This implementation does a notifyObservers(state.STATE_EXITING)
.protected void finishRun()
notifyObservers(state.STATE_EXITED)
.protected void finalize() throws Throwable
private final void eventBufferLoop()
eventBufferLoopBody()
until after exit()
has been called and isStoppable()
becomes true.public void defer(Runnable x, long milliseconds)
x
- some Runnable to executemilliseconds
- the number of milliseconds (minimum) to wait before executing.public void defer(Runnable x)
defer
in interface PolicyAgentInterface
x
- some Runnable to executeprotected SocialCommitment processCommitments()
protected boolean isEventQueueReady()
protected Event eventQueuePeek()
protected void eventBufferLoopBody()
eventBufferLoop()
and may be overridden
by a subclass as the actual code to dequeue messages off the queue. However,
the subclass method is best off by calling
super.eventBufferLoopBody()
as part of it's implementation.processCommitments()
) and exit.
processCommitments()
) and exit.
exit
state, then wait 500ms}).
public boolean isThisMyAddress(URLDescriptor theURL)
private void processEvent(Event event)
handleEvent(Event)
for actual processing event. In particular,
message events require special processing:
isObserveMessages()
is not true and the
message is not addressed to this agent.
authorizeMessage(MLMessage)
notifyObservers()
is called with parameters ML.EVENT_MESSAGE_RECEIVED
and the message itself
handleEvent(Event)
and if that returnsevent
- the event on the queue being processedprivate void pauseCheck()
public boolean isPaused()
setPause(boolean)
public void setPause(boolean val)
val
- public void step()
@Deprecated protected void eventBufferLoopPeriodic()
eventBufferLoopBody()
. Subclasses may
override to add fucntionality. This method does nothing.protected void unhandledMessage(MLMessage message)
message
- the unhandled message.public String getUniqueRequestID()
getUniqueRequestID
in interface PolicyAgentInterface
getUniqueRequestID
in interface ProcessInterface
public int getPort()
getPort
in interface ProcessInterface
public void closePort()
closePort
in interface ProcessInterface
public boolean hasOpenPort()
hasOpenPort
in interface ProcessInterface
true
if and only if the process has an open port;
false
otherwise.public void addObserver(Observer observer)
addObserver
in interface ProcessInterface
observer
- the Observer object to add.public void addObserver(URLDescriptor observer)
addObserver
in interface ProcessInterface
observer
- the Observer object to add.public void deleteObserver(Observer observer)
deleteObserver
in interface CasaObservable
deleteObserver
in interface ProcessInterface
observer
- the Observer object to delete from the list of observerspublic void deleteObserver(URLDescriptor observer)
deleteObserver
in interface CasaObservable
deleteObserver
in interface ProcessInterface
observer
- the URL of the observer to delete from the list of observerspublic void notifyObservers(String eventType, Object argument)
notifyObservers
in interface CasaObservable
notifyObservers
in interface PolicyAgentInterface
public MLMessage getNewMessage(String performative, String act, URLDescriptor reciever)
getNewMessage
in interface ProcessInterface
performative
- The performative of the new message.act
- The act of the new message.reciever
- The reciever of the new message.public MLMessage getNewMessage(String performative, String act, URLDescriptor reciever, String... list)
performative
- The performative of the new message.act
- The act of the new message.reciever
- The reciever of the new message.list
- an array of strings: odd indicis are taken as keys and even as valuespublic void setTracing(boolean doTrace)
setTracing
in interface ProcessInterface
doTrace
- true to turn tracing on, false to turn tracing offpublic boolean isTracing()
isTracing
in interface ProcessInterface
public Trace getTrace()
Trace
object. If isTracing() == true, then this is guaranteed
non-null, otherwise, this may return null.getTrace
in interface ProcessInterface
public boolean isLoggingTag(String tag)
isLoggingTag
in interface AgentPrintInterface
isLoggingTag
in interface PolicyAgentInterface
isLoggingTag
in interface ProcessInterface
isLoggingTag
in interface TraceInterface
tag
- The tag in question of being traced or not.public void setUsePriority(boolean newVal)
newVal
- true to use message queue priorities; false to use FIFO.public boolean getUsePriority()
public void setObserveMessages(boolean newVal)
newVal
- true to have the agent process messages not addressed to it.public boolean isObserveMessages()
public void startTraceMonitor()
startTraceMonitor
in interface ProcessInterface
protected void resetSecurityPackage(String pack)
protected String getEventQueue()
public int countObservers()
countObservers
in interface CasaObservable
public void deleteObservers()
deleteObservers
in interface CasaObservable
public boolean hasChanged()
hasChanged
in interface CasaObservable
public void notifyObservers()
notifyObservers
in interface CasaObservable
public void notifyObserversWithTop(Object arg)
CasaObservable
notifyObserversWithTop
in interface CasaObservable
arg
- the argument to usepublic void addObserver(Observer o, String... notifyTypes)
addObserver
in interface CasaObservable
public void addObserver(URLDescriptor observer, String... notifyTypes)
addObserver
in interface CasaObservable
public void notifyObserversWithNoArg(String notifyType)
CasaObservable
notifyObserversWithNoArg
in interface CasaObservable
notifyType
- the notification type to usepublic void bump()
bump
in interface PolicyAgentInterface
public void update(Observable o, Object arg)
public Thread makeSubthread(Runnable runnable, String name)
ThreadGroup
as this agent, with the agent
specified. Don't forget to call start() on the thread.runnable
- The runnable to execute.name
- The name of he new Thread.public Thread makeSubthread(Runnable runnable)
ThreadGroup
as this agent, with the agent
specified. Don't forget to call start() on the thread.runnable
- The runnable to execute.public static AbstractProcess getAgent()
public int compareTo(AbstractProcess o)
compareTo
in interface Comparable<AbstractProcess>
protected abstract SocialCommitment getChosenCommitment()
protected abstract boolean hasActiveCommitments()
protected abstract SocialCommitment processCommitment(SocialCommitment sc)
public int setTraceTags(String tags)
TraceInterface
setTraceTags
in interface TraceInterface
tags
- A command-delimited list of tags. White space is ignored.public int removeTraceTags(String tags)
TraceInterface
removeTraceTags
in interface TraceInterface
tags
- The tags to be removed.TraceInterface.setTraceTags(String)
public String getTraceTags()
getTraceTags
in interface TraceInterface
public int addTraceTags(String tags)
TraceInterface
addTraceTags
in interface TraceInterface
tags
- a comma-delimited list of trace tagspublic String println(String traceTag, String txt, Throwable ex, int flags)
TraceInterface
#OPT_INCLUDE_CODE_LINE_NUMBER
is in flags then so short string of ">"'s.
In any of these cases, the ">"'s is followed by the guess of the calling source file and line number.
#OPT_SUPRESS_STACK_TRACE
is not set, or #OPT_FORCE_STACK_TRACE
is set.
[* timestamp : agentName : tag : thread-name *]
println
in interface TraceInterface
traceTag
- This tag MUST be present in set of traceTags for anything to be printed/logged.txt
- The message to be printed/logged.ex
- If this is non-null, the stack trace will be appended to the messageflags
- The options flags; use bitwise disjunct ("|") to combine options - #OPT_SUPPRESS_AGENT_LOG
, #OPT_COPY_TO_SYSERR
, #OPT_COPY_TO_SYSOUT
, #OPT_FORCE_STACK_TRACE
, #OPT_INCLUDE_CODE_LINE_NUMBER
, #OPT_SUPPRESS_HEADER_ON_SYSOUT
, #OPT_SUPRESS_STACK_TRACE
.public String println(String traceTag, String txt)
Trace
object to log the
string if appropriate (ie: the traceTAg matches a tag that's turned on
in the Trace object.println
in interface AgentPrintInterface
println
in interface PolicyAgentInterface
println
in interface ProcessInterface
println
in interface TraceInterface
traceTag
- The txt String will be logged if the traceTag matches a tag that's turned on in the Trace object.txt
- The String to be loggedTraceInterface.println(String, String, Throwable, int)
public String println(String traceTag, String txt, Throwable ex)
println(String, String)
but appends ex.toString() and prints
a stack trace after.println
in interface AgentPrintInterface
println
in interface PolicyAgentInterface
println
in interface ProcessInterface
println
in interface TraceInterface
traceTag
- The txt String will be logged if the traceTag matches a tag that's turned on in the Trace object.txt
- The String to be loggedex
- An Exception objectTraceInterface.println(String, String, Throwable, int)
@Deprecated public String println(String traceTag, String txt, Status tempStatus)
println(String, String)
but appends tempStatus.getExplanation().println
in interface AgentPrintInterface
println
in interface PolicyAgentInterface
println
in interface ProcessInterface
traceTag
- The txt String will be logged if the traceTag matches a tag that's turned on in the Trace object.txt
- The String to be loggedtempStatus
- A Status objectpublic String println(String traceTag, String txt, int flags)
TraceInterface
println(tag, string, null, flag)
println
in interface TraceInterface
flags
- The options flags; use bitwise disjunct ("|") to combine options - #OPT_SUPPRESS_AGENT_LOG
, #OPT_COPY_TO_SYSERR
, #OPT_COPY_TO_SYSOUT
, #OPT_FORCE_STACK_TRACE
, #OPT_INCLUDE_CODE_LINE_NUMBER
, #OPT_SUPPRESS_HEADER_ON_SYSOUT
, #OPT_SUPRESS_STACK_TRACE
.TraceInterface.println(String, String, Throwable, int)
public void setAllTraceTags()
TraceInterface
setAllTraceTags
in interface TraceInterface
public void clearAllTraceTags()
TraceInterface
clearAllTraceTags
in interface TraceInterface