Package madkit.kernel

Class AbstractAgent

java.lang.Object
madkit.kernel.AbstractAgent
All Implemented Interfaces:
Comparable<AbstractAgent>
Direct Known Subclasses:
AbstractModel, Agent, ConsoleAgent, Watcher

public class AbstractAgent extends Object implements Comparable<AbstractAgent>
The super class of all MaDKit agents, v 5. It provides support for
  • Agent's Life cycle, logging, and naming.
  • Agent launching and killing.
  • Artificial society creation and management.
  • Messaging.
  • Minimal graphical interface management.

The agent's behavior is intentionally not defined. It is up to the agent developer to choose an agent model or to develop his specific agent library on top of the facilities provided by the MaDKit API. However, all the launched agents share the same organizational view, and the basic messaging code, so integration of different agents is quite easy, even when they are coming from different developers or have heterogeneous models.

Agent-related methods (most of this API) is only effective after the agent has been launched and thus registered in the current Madkit session. Especially, that means that most of the API has no effect in the constructor method of an Agent and will only produce a warning if used.

MaDKit v.5 new features

  • One of the big change that comes with version 5 is how agents are identified and localized within the artificial society. An agent is no longer binded to a single agent address but has as many agent addresses as holden positions in the artificial society. see AgentAddress for more information.

  • With respect to the previous change, a withRole version of all the messaging methods has been added. See sendMessageWithRole(AgentAddress, Message, String) for an example of such a method.

  • A replying mechanism has been introduced through SendReply methods. It enables the agent with the possibility of replying directly to a given message. Also, it is now possible to get the reply to a message, or to wait for a reply ( for Agent subclasses only as they are threaded) See sendReply(Message, Message) for more details.

  • Agents now have a formal state during a MaDKit session. See the getState() method for detailed information.

  • One of the most convenient improvement of v.5 is the logging mechanism which is provided. See the getLogger() method for more details.
Version:
5.8
Author:
Fabien Michel, Olivier Gutknecht
  • Constructor Details

    • AbstractAgent

      public AbstractAgent()
  • Method Details

    • getSimulationTime

      public Scheduler.SimulationTime getSimulationTime()
      Returns the Scheduler.SimulationTime of the current simulation. This is automatically initialized when the agent is associated with an activator for the first time. So it stays null if the agent is not related to a simulation
      Returns:
      the simulationTime of the simulation in which the agent participates
    • getNextEventDate

      public LocalDateTime getNextEventDate()
      Method which is used by discrete-event simulation activators for doing fine-grained simulations. By default, this method returns an event which is one second ahead of the current date of the simulation. So, this method can be overridden to fulfil the simulation requirement
      Returns:
      the date of the next event for this agent.
      See Also:
    • createGUIOnStartUp

      public void createGUIOnStartUp()
      Activates the MaDKit GUI initialization when launching the agent whatever the launching parameters. By default agents are launched without a GUI but some of them always need one: This ensures that the agent will have one. This method should be used only in the constructor of the agent, otherwise it will be useless as it specifies a boot property of the agent.
    • hasGUI

      public boolean hasGUI()
      Tells if this agent has a GUI automatically built by the kernel
      Returns:
      true if this agent has a GUI built by the kernel
    • hashCode

      public final int hashCode()
      The ID of an agent. All the agents have different hashCode value in one kernel. Thus it can be used to identify one agent. In a networked environment, this value should be used in combination with the kernelAddress of the agent for unique identification. This also holds when multiple MaDKit kernels are launched within the same JVM.
      Overrides:
      hashCode in class Object
      Returns:
      the agent's unique ID in the MaDKit kernel
    • getNetworkID

      public final String getNetworkID()
      Return a string representing a unique identifier for the agent over the network.
      Returns:
      the agent's network identifier
    • getSimpleNetworkID

      public final String getSimpleNetworkID()
      Return a string representing a shorter version of the unique identifier of the agent over the network. As a simplified version, this string may not be unique.
      Returns:
      a simplified version of the agent's network identifier
      See Also:
    • isAlive

      public boolean isAlive()
      Returns true if the agent has been launched and is not ended nor killed.
    • activate

      protected void activate()
      This method corresponds to the first behavior which is called by the MaDKit kernel when an agent is launched. Usually a good place to take a position in the organization of the artificial society.

      Here is a typical example:

       @Override
       protected void activate()
       {
              AbstractAgent.ReturnCode returnCode = requestRole("a community", "a group", "my role");
              if (returnCode == AbstractAgent.ReturnCode.SUCCESS){
                      if(logger != null)
                              logger.info("I am now playing my role in the artificial society");
              }
              else{
                      if(logger != null)
                              logger.warning("something wrong, return code is "+returnCode);
              }
       }
       
    • end

      protected void end()
      This method corresponds to the last behavior which is called by the MaDKit kernel. This call occurs when a threaded agent normally exits its live method or when the agent is killed. Usually a good place to release taken resources or log what has to be logged. It has to be noted that the kernel automatically takes care of removing the agent from the organizations it is in. However, this cleaning is not logged by the agent. Therefore it could be of interest for the agent to do that itself.

      Here is a typical example:

       @Override
       protected void end()
       {
              AbstractAgent.ReturnCode returnCode = leaveRole("a community", "a group", "my role");
              if (returnCode == AbstractAgent.ReturnCode.SUCCESS){
                      if(logger != null)
                              logger.info("I am leaving the artificial society");
              }
              else{
                      if(logger != null)
                              logger.warning("something wrong when ending, return code is "+returnCode);
              }
              if(logger != null)
                      logger.info("I am done");
              }
       }
       
    • launchAgent

      public AbstractAgent.ReturnCode launchAgent(AbstractAgent agent)
      Launches a new agent in the MaDKit platform. This has the same effect as launchAgent(agent,Integer.MAX_VALUE,false)
      Parameters:
      agent - the agent to launch.
      Returns:
      Since:
      MaDKit 5.0
      See Also:
    • launchAgent

      public AbstractAgent.ReturnCode launchAgent(AbstractAgent agent, int timeOutSeconds)
      Launches a new agent in the MaDKit platform. This has the same effect as launchAgent(agent,timeOutSeconds,false)
      Parameters:
      agent - the agent to launch.
      timeOutSeconds - time to wait the end of the agent's activation until returning a TIMEOUT.
      Returns:
    • launchAgent

      public AbstractAgent.ReturnCode launchAgent(AbstractAgent agent, boolean createFrame)
      Launches a new agent in the MaDKit platform. This has the same effect as launchAgent(agent,Integer.MAX_VALUE,withGUIManagedByTheBooter)
      Parameters:
      agent - the agent to launch.
      createFrame - if true, the kernel will launch a JFrame for this agent.
      Returns:
      Since:
      MaDKit 5.0
      See Also:
    • launchAgent

      public AbstractAgent.ReturnCode launchAgent(AbstractAgent agent, int timeOutSeconds, boolean createFrame)
      Launches a new agent and returns when the agent has completed its activate() method or when timeOutSeconds seconds elapsed. That is, the launched agent has not finished its activate() before the time out time elapsed. Additionally, if createFrame is true, it tells to MaDKit that an agent GUI should be managed by the Kernel. In such a case, the kernel takes the responsibility to assign a JFrame to the agent and to manage its life cycle (e.g. if the agent ends or is killed then the JFrame is closed) Using this feature there are two possibilities:
      • 1. the agent overrides the method setupFrame(AgentFrame) and so setup the default JFrame as will
      • 2. the agent does not override it so that MaDKit will setup the JFrame with the default Graphical component delivered by the MaDKit platform: OutputPanel
      Parameters:
      agent - the agent to launch.
      timeOutSeconds - time to wait for the end of the agent's activation until returning a TIMEOUT.
      createFrame - if true, the kernel will launch a JFrame for this agent.
      Returns:
      Since:
      MaDKit 5.0
    • launchAgent

      public AbstractAgent launchAgent(String agentClass)
      Launches a new agent using its full class name.
      This has the same effect as launchAgent(agentClass, Integer.MAX_VALUE, false).
      Parameters:
      agentClass - the full class name of the agent to launch
      Returns:
      the instance of the launched agent or null if the operation times out or failed.
    • launchAgent

      public AbstractAgent launchAgent(String agentClass, int timeOutSeconds)
      Launches a new agent using its full class name.
      This has the same effect as launchAgent(agentClass, timeOutSeconds, false).
      Parameters:
      timeOutSeconds - time to wait the end of the agent's activation until returning null
      agentClass - the full class name of the agent to launch
      Returns:
      the instance of the launched agent or null if the operation times out or failed.
    • launchAgent

      public AbstractAgent launchAgent(String agentClass, boolean createFrame)
      Launches a new agent using its full class name.
      This has the same effect as launchAgent(agentClass, Integer.MAX_VALUE, defaultGUI).
      Parameters:
      createFrame - if true a default GUI will be associated with the launched agent
      agentClass - the full class name of the agent to launch
      Returns:
      the instance of the launched agent or null if the operation times out or failed.
    • launchAgent

      public AbstractAgent launchAgent(String agentClass, int timeOutSeconds, boolean createFrame)
      Launches a new agent using its full class name and returns when the launched agent has completed its activate() method or when the time out is elapsed. This has the same effect as launchAgent(AbstractAgent, int, boolean) but allows to launch agent using a class name found reflexively. The targeted agent class should have a default constructor for this to work. Additionally, this method will launch the last compiled byte code of the corresponding class if it has been reloaded using MadkitClassLoader.reloadClass(String). Finally, if the launch timely succeeded, this method returns the instance of the created agent.
      Parameters:
      timeOutSeconds - time to wait the end of the agent's activation until returning null
      createFrame - if true a default GUI will be associated with the launched agent
      agentClass - the full class name of the agent to launch
      Returns:
      the instance of the launched agent or null if the operation times out or failed.
    • launchAgentBucket

      public List<AbstractAgent> launchAgentBucket(String agentClass, int bucketSize, int cpuCoreNb, String... roles)
      Optimizes mass agent launching. Launches bucketSize instances of agentClassName (an agent class) and put them in the artificial society at the locations defined by cgrLocations. Each string of the cgrLocations array defines a complete CGR location. So for example, cgrLocations could be defined and used with code such as :

       launchAgentBucketWithRoles("madkit.bees.Bee", 1000000, "community,group,role", "anotherC,anotherG,anotherR")
       
      In this example all the agents created by this process will have these two roles in the artificial society, even if they do not request them in their activate() method.

      Additionally, in order to avoid to change the code of the agent considering how they will be launched (using the bucket mode or not). One should use the following alternative of the usual request methods : bucketModeCreateGroup(String, String, boolean, Gatekeeper), bucketModeRequestRole(String, String, String, Object): If used in activate(), these requests will be ignored when the bucket mode is used or normally proceeded otherwise.

      If some of the corresponding groups do not exist before this call, the caller agent will automatically become the manager of these groups.

      Parameters:
      agentClass - the name of the class from which the agents should be built.
      bucketSize - the desired number of instances.
      cpuCoreNb - the number of parallel tasks to use. Beware that if cpuCoreNb is greater than 1, the agents' constructors and activate() methods will be called simultaneously so that one has to be careful if shared resources are accessed by the agents
      roles - default locations in the artificial society for the launched agents. Each string of the cgrLocations array defines a complete CGR location by separating C, G and R with commas as follows: "community,group,role". It can be null.
      Returns:
      a list containing all the agents which have been launched, or null if the operation has failed
      Since:
      MaDKit 5.0.0.6
    • launchAgentBucket

      public List<AbstractAgent> launchAgentBucket(String agentClass, int bucketSize, String... roles)
      This has the same effect as launchAgentBucket(agentClass, bucketSize, 1, roles).
      Parameters:
      agentClass - the name of the class from which the agents should be built.
      bucketSize - the desired number of instances.
      roles - default locations in the artificial society for the launched agents. Each string of the cgrLocations array defines a complete CGR location by separating C, G and R with commas as follows: "community,group,role"
      Returns:
      a list containing all the agents which have been launched, or null if the operation has failed
      Since:
      MaDKit 5.0.2
    • launchAgentBucket

      public void launchAgentBucket(List<? extends AbstractAgent> bucket, String... roles)
      This call is equivalent to This has the same effect as launchAgentBucket(bucket, 1, roles), That is only one core will be used for the launch.
      Parameters:
      bucket - the list of agents to launch
      roles - default locations in the artificial society for the launched agents. Each string of the cgrLocations array defines a complete CGR location by separating C, G and R with commas as follows: "community,group,role". It can be null
    • launchAgentBucket

      public void launchAgentBucket(List<? extends AbstractAgent> bucket, int nbOfParallelTasks, String... roles)
      Similar to launchAgentBucket(String, int, String...) except that the list of agents to launch is given. Especially, this could be used when the agents have no default constructor.
      Parameters:
      bucket - the list of agents to launch
      nbOfParallelTasks - the number of parallel tasks to use for launching the agents. Beware that if nbOfParallelTasks is greater than 1, the agents' activate() methods will be called simultaneously so that one has to be careful if shared resources are accessed
      roles - default locations in the artificial society for the launched agents. Each string of the cgrLocations array defines a complete CGR location by separating C, G and R with commas as follows: "community,group,role". It can be null
    • killAgent

      public AbstractAgent.ReturnCode killAgent(AbstractAgent target)
      Kills the targeted agent. This has the same effect as killAgent(target,Integer.MAX_VALUE) so that the targeted agent has a lot of time to complete its end() method.
      Returns:
      Since:
      MaDKit 5.0
      See Also:
    • killAgent

      public AbstractAgent.ReturnCode killAgent(AbstractAgent target, int timeOutSeconds)
      Kills the targeted agent. The kill process stops the agent's life cycle but allows it to process its end() method until the time out elapsed.

      If the target is in the activate or live method (Agent subclasses), it will be brutally stop and then proceed its end method.

      The method returns only when the targeted agent actually ends its life. So if the target contains a infinite loop, the caller can be blocked. Using a timeout thus ensures that the caller will be blocked only a certain amount of time. Using 0 as timeout will stop the target as soon as possible, eventually brutally stop its life cycle. In such a case, if its end method has not been started, it will never run.

      Returns:
      Since:
      MaDKit 5.0
    • getName

      public String getName()
      The agent's name.
      Returns:
      the name to display in logger info, GUI title and so on. Default is "class name + internal ID"
    • setName

      public void setName(String name)
      Changes the agent's name
      Parameters:
      name - the name to display in logger info, GUI title and so on, default is "class name + internal ID"
    • setLogLevel

      @Deprecated public void setLogLevel(Level newLevel)
      Deprecated.
      as of MaDKit 5.2, AgentLogger.setLevel(Level) should now be used through getLogger()
      Sets the agent's log level. This should be used instead of directly AgentLogger.setLevel(Level) because this also works when logger is null and allows to set it to null to save cpu time.
      Parameters:
      newLevel - The log level under which log messages are displayed. If Level.OFF is used then logger is set to null
      See Also:
      • logger
    • getLogger

      public AgentLogger getLogger()
      Returns the agent's logger. It is lazily created so that if getLogger() is not used, there is no memory foot print at all, which could be crucial when working with thousands of abstract agents in simulation mode.
      Returns:
      the agent's logger.
      Since:
      MaDKit 5.0.0.6
      See Also:
    • compareTo

      public int compareTo(AbstractAgent other)
      Compares this agent with the specified agent for order with respect to instantiation time.
      Specified by:
      compareTo in interface Comparable<AbstractAgent>
      Parameters:
      other - the agent to be compared.
      Returns:
      a negative integer, a positive integer or zero as this agent has been instantiated before, after or is the same agent than the specified agent.
    • createGroup

      public AbstractAgent.ReturnCode createGroup(String community, String group)
      Creates a new Group within a community. This has the same effect as createGroup(community, group, false, null)
      Parameters:
      community - the community within which the group will be created. If this community does not exist it will be created.
      group - the name of the new group
      Returns:
      Since:
      MaDKit 5.0
      See Also:
    • createGroup

      public AbstractAgent.ReturnCode createGroup(String community, String group, boolean isDistributed)
      Creates a new Group within a community. This has the same effect as createGroup(community, group, isDistributed, null)
      Parameters:
      community - the community within which the group will be created. If this community does not exist it will be created.
      group - the name of the new group.
      isDistributed - if true the new group will be distributed when multiple MaDKit kernels are connected.
      Returns:
      Since:
      MaDKit 5.0
      See Also:
    • createGroup

      public AbstractAgent.ReturnCode createGroup(String community, String group, boolean isDistributed, Gatekeeper keyMaster)
      Creates a new Group within a community.

      If this operation succeed, the agent will automatically handle the role defined by DefaultMaDKitRoles.GROUP_MANAGER_ROLE, which value is "manager", in this created group. Especially, if the agent leaves the role of "manager", it will also automatically leave the group and thus all the roles it has in this group.

      Agents that want to enter the group may send messages to the "manager" using the role defined by DefaultMaDKitRoles.GROUP_CANDIDATE_ROLE, which value is "candidate".

      Parameters:
      community - the community within which the group will be created. If this community does not exist it will be created.
      group - the name of the new group.
      isDistributed - if true the new group will be distributed when multiple MaDKit kernels are connected.
      keyMaster - any object that implements the Gatekeeper interface. If not null, this object will be used to check if an agent can be admitted in the group. When this object is null, there is no group access control.
      Returns:
      Since:
      MaDKit 5.0
      See Also:
    • bucketModeCreateGroup

      public AbstractAgent.ReturnCode bucketModeCreateGroup(String community, String group, boolean isDistributed, Gatekeeper keyMaster)
      Creates a new Group within a community even if the agent has been launched using using one of the launchAgentBucket methods. This method is only useful when called within the activate() method.

      For instance, this is useful if you launch one million of agents and when only some of them have to create a specific group, not defined in the parameters of launchAgentBucket(List, int, String...)

      Parameters:
      community - the community within which the group will be created. If this community does not exist it will be created.
      group - the name of the new group.
      isDistributed - if true the new group will be distributed when multiple MaDKit kernels are connected.
      keyMaster - any object that implements the Gatekeeper interface. If not null, this object will be used to check if an agent can be admitted in the group. When this object is null, there is no group access control.
      Returns:
      Since:
      MaDKit 5.0.2
      See Also:
    • createGroupIfAbsent

      public boolean createGroupIfAbsent(String community, String group)
      Creates a new Group within a community but does not produce any warning if the group already exists. This has the same effect as createGroupIfAbsent(community, group, false, null)
      Parameters:
      community - the community within which the group will be created. If this community does not exist it will be created.
      group - the name of the new group.
      Returns:
      true if the group has been created, false if such a group already exists.
      Since:
      MaDKit 5.0
      See Also:
    • createGroupIfAbsent

      public boolean createGroupIfAbsent(String community, String group, boolean isDistributed)
      Creates a new Group within a community but does not produce any warning if the group already exists. This has the same effect as createGroupIfAbsent(community, group, isDistributed, null)
      Parameters:
      community - the community within which the group will be created. If this community does not exist it will be created.
      group - the name of the new group
      isDistributed - if true the new group will be distributed when multiple MaDKit kernels are connected.
      Returns:
      true if the group has been created, false if such a group already exists.
      Since:
      MaDKit 5.0
      See Also:
    • createGroupIfAbsent

      public boolean createGroupIfAbsent(String community, String group, boolean isDistributed, Gatekeeper keyMaster)
      Creates a new Group within a community but does not produce any warning if the group already exists. If this operation succeed, the agent will automatically handle the role of group manager in the created group.
      Parameters:
      community - the community within which the group will be created. If this community does not exist it will be created.
      group - the name of the new group
      isDistributed - if true the new group will be distributed when multiple MaDKit kernels are connected.
      keyMaster - any object that implements the Gatekeeper interface. If not null, this object will be used to check if an agent can be admitted in the group. When this object is null, there is no group access control.
      Returns:
      true if the group has been created, false if such a group already exists.
      Since:
      MaDKit 5.0
      See Also:
    • leaveGroup

      public AbstractAgent.ReturnCode leaveGroup(String community, String group)
      Makes this agent leaves the group of a particular community.
      Parameters:
      community - the community name
      group - the group name
      Returns:
      Since:
      MaDKit 5.0
      See Also:
    • requestRole

      public AbstractAgent.ReturnCode requestRole(String community, String group, String role)
      Requests a role within a group of a particular community. This has the same effect as requestRole(community, group, role, null, false). So the passKey is null and the group must not be secured for this to succeed.
      Parameters:
      community - the group's community.
      group - the targeted group.
      role - the desired role.
      Since:
      MaDKit 5.0
      See Also:
    • requestRole

      public AbstractAgent.ReturnCode requestRole(String community, String group, String role, Object passKey)
      Requests a role within a group of a particular community using a passKey.
      Parameters:
      community - the group's community.
      group - the targeted group.
      role - the desired role.
      passKey - the passKey to enter a secured group. It is generally delivered by the group's group manager. It could be null, which is sufficient to enter an unsecured group. Especially, requestRole(String, String, String) uses a null passKey.
      Returns:
      Since:
      MaDKit 5.0
      See Also:
    • bucketModeRequestRole

      public AbstractAgent.ReturnCode bucketModeRequestRole(String community, String group, String role, Object passKey)
      Requests a role even if the agent has been launched using one of the launchAgentBucket methods with no null roles. For instance, this is useful if you launch one million of agents and when only some of them have to take a specific role which cannot be defined in the parameters of launchAgentBucket(List, int, String...) because they are priorly unknown and built at runtime.
      Parameters:
      community - the group's community.
      group - the targeted group.
      role - the desired role.
      passKey - the passKey to enter a secured group. It is generally delivered by the group's group manager. It could be null, which is sufficient to enter an unsecured group. Especially, requestRole(String, String, String) uses a null passKey.
      Returns:
      Since:
      MaDKit 5.0
      See Also:
    • leaveRole

      public AbstractAgent.ReturnCode leaveRole(String community, String group, String role)
      Abandons an handled role within a group of a particular community.
      Parameters:
      community - the community name
      group - the group name
      role - the role name
      Returns:
      Since:
      MaDKit 5.0
      See Also:
    • getAgentAddressIn

      public AgentAddress getAgentAddressIn(String community, String group, String role)
      Agent's address at this CGR location.
      Parameters:
      community -
      group -
      role -
      Returns:
      the agent's address in this location or null if this agent does not handle this role.
      Since:
      MaDKit 5.0.0.15
    • getAgentWithRole

      public AgentAddress getAgentWithRole(String community, String group, String role)
      Returns an AgentAddress corresponding to an agent having this position in the organization. The caller is excluded from the search.
      Parameters:
      community - the community name
      group - the group name
      role - the role name
      Returns:
      an AgentAddress corresponding to an agent handling this role or null if such an agent does not exist.
    • getDistantAgentWithRole

      public AgentAddress getDistantAgentWithRole(String community, String group, String role, KernelAddress from)
      AgentAddress corresponding to an agent having this position in the organization on a particular kernel. The caller is excluded from the search.
      Parameters:
      community - the community name
      group - the group name
      role - the role name
      from - the kernel address on which the agent is running
      Returns:
      an AgentAddress corresponding to an agent handling this role on the targeted kernel or null if such an agent does not exist.
    • getAgentsWithRole

      public List<AgentAddress> getAgentsWithRole(String community, String group, String role)
      A list containing other agents playing this role in the organization. The caller is excluded from this list.
      Parameters:
      community - the community name
      group - the group name
      role - the role name
      Returns:
      a List containing agents that handle this role or null if no agent has been found.
    • getAgentsWithRole

      public List<AgentAddress> getAgentsWithRole(String community, String group, String role, boolean callerIncluded)
      A list containing all the agents playing this role in the organization.
      Parameters:
      community - the community name
      group - the group name
      role - the role name
      callerIncluded - if false, the caller is removed from the list if it is in.
      Returns:
      a List containing agents that handle this role or null if no agent has been found.
    • nextMessage

      public Message nextMessage()
      Retrieves and removes the oldest received message contained in the mailbox.
      Returns:
      The next message or null if the message box is empty.
    • nextMessage

      public Message nextMessage(MessageFilter filter)
      Retrieves and removes the first oldest message of the mailbox that matches the filter.
      Returns:
      The next acceptable message or null if such message has not been found.
    • nextMessages

      public List<Message> nextMessages(MessageFilter filter)
      Retrieves and removes all the messages of the mailbox that match the filter, in the order they were received.
      Parameters:
      filter - if null all the messages are returned and removed from the mailbox.
      Returns:
      the ordered list of matching messages, or an empty list if none has been found.
    • getLastReceivedMessage

      public Message getLastReceivedMessage()
      Gets the last received message.
      Returns:
      the last received message or null if the mailbox is empty.
    • getLastReceivedMessage

      public Message getLastReceivedMessage(MessageFilter filter)
      Gets the last received message according to a filter.
      Parameters:
      filter - the message filter to use
      Returns:
      the last received message that matches the filter or null if such message has not been found.
    • purgeMailbox

      public Message purgeMailbox()
      Purges the mailbox and returns the most recent received message at that time.
      Returns:
      the most recent received message or null if the mailbox is already empty.
    • isMessageBoxEmpty

      public boolean isMessageBoxEmpty()
      Tells if there is a message in the mailbox
      Returns:
      true if there is no message in the mailbox.
    • sendMessage

      public AbstractAgent.ReturnCode sendMessage(AgentAddress receiver, Message messageToSend)
      Sends a message to an agent using an agent address. This has the same effect as sendMessageWithRole(receiver, messageToSend, null).
      Parameters:
      receiver -
      messageToSend -
      Returns:
      See Also:
    • sendMessageWithRole

      public AbstractAgent.ReturnCode sendMessageWithRole(AgentAddress receiver, Message message, String senderRole)
      Sends a message, using an agent address, specifying explicitly the role used to send it.
      Parameters:
      receiver - the targeted agent
      message - the message to send
      Returns:
      See Also:
    • sendMessage

      public AbstractAgent.ReturnCode sendMessage(String community, String group, String role, Message message)
      Sends a message to an agent having this position in the organization, specifying explicitly the role used to send it. This has the same effect as sendMessageWithRole(community, group, role, messageToSend,null). If several agents match, the target is chosen randomly. The sender is excluded from this search.
      Parameters:
      community - the community name
      group - the group name
      role - the role name
      message - the message to send
      Returns:
      See Also:
    • sendMessageWithRole

      public AbstractAgent.ReturnCode sendMessageWithRole(String community, String group, String role, Message message, String senderRole)
      Sends a message to an agent having this position in the organization. This has the same effect as sendMessageWithRole(community, group, role, messageToSend,null) . If several agents match, the target is chosen randomly. The sender is excluded from this search.
      Parameters:
      community - the community name
      group - the group name
      role - the role name
      message - the message to send
      senderRole - the agent's role with which the message has to be sent
      Returns:
      See Also:
    • broadcastMessage

      public AbstractAgent.ReturnCode broadcastMessage(String community, String group, String role, Message message)
      Broadcasts a message to every agent having a role in a group in a community, but not to the sender.
      Parameters:
      community - the community name
      group - the group name
      role - the role name
      message -
      Returns:
      See Also:
    • broadcastMessageWithRole

      public AbstractAgent.ReturnCode broadcastMessageWithRole(String community, String group, String role, Message messageToSend, String senderRole)
      Broadcasts a message to every agent having a role in a group in a community using a specific role for the sender. The sender is excluded from the search.
      Parameters:
      community - the community name
      group - the group name
      role - the role name
      messageToSend -
      senderRole - the agent's role with which the message should be sent
      Returns:
      See Also:
    • sendReplyWithRole

      public AbstractAgent.ReturnCode sendReplyWithRole(Message messageToReplyTo, Message reply, String senderRole)
      Sends a message by replying to a previously received message. The sender is excluded from this search.
      Parameters:
      messageToReplyTo - the previously received message.
      reply - the reply itself.
      senderRole - the agent's role with which the message should be sent
      Returns:
      See Also:
    • sendReply

      public AbstractAgent.ReturnCode sendReply(Message messageToReplyTo, Message reply)
      Sends a message by replying to a previously received message. This has the same effect as sendReplyWithRole(messageToReplyTo, reply, null).
      Parameters:
      messageToReplyTo - the previously received message.
      reply - the reply itself.
      Returns:
      See Also:
    • getReplyTo

      public Message getReplyTo(Message originalMessage)
      Gets the next message which is a reply to the originalMessage.
      Parameters:
      originalMessage - the message to which a reply is searched.
      Returns:
      a reply to the originalMessage or null if no reply to this message has been received.
    • receiveMessage

      public void receiveMessage(Message m)
      This method offers a convenient way for regular object to send messages to Agents, especially threaded agents. For instance when a GUI wants to discuss with its linked agent: This allows to enqueue work to do in their life cycle
      Parameters:
      m -
    • getMadkitProperty

      public final String getMadkitProperty(String key)
      Gets the MaDKit session property indicated by the specified key. This call is equivalent to getMadkitConfig().getProperty(key)
      Parameters:
      key - the name of the MaDKit property
      Returns:
      the string value of the MaDKit property, or null if there is no property with that key.
      See Also:
    • getMadkitProperty

      public <E extends Enum<E>> String getMadkitProperty(E option)
      Shortcut for getMadkitProperty(option.name()). Runtime options could be represented using enumeration constants, as it is the case for MaDKit's, so this is a convenient method for retrieving the value of an option.
      Parameters:
      option - the constant representing a MaDKit option
      Returns:
      the corresponding value as a String, or null if there is no property having the corresponding name.
      Since:
      MaDKit 5.0.3
      See Also:
    • setMadkitProperty

      public void setMadkitProperty(String key, String value)
      Set the MaDKit session property indicated by the specified key.
      Parameters:
      key - the name of the MaDKit property
      See Also:
    • setMadkitProperty

      public <E extends Enum<E>> void setMadkitProperty(E option, String value)
      Set the MaDKit session property indicated by the specified constant representing a MaDKit option.
      Parameters:
      option - the constant representing a MaDKit option
      See Also:
    • isMadkitPropertyTrue

      public <E extends Enum<E>> boolean isMadkitPropertyTrue(E option)
      Shortcut for Boolean.parseBoolean(getMadkitProperty(option))
      Parameters:
      option - the constant representing a runtime option
      Returns:
      true if the option has been set to true
      Since:
      MadKit 5.0.3
    • setupFrame

      public void setupFrame(AgentFrame frame)
      Called when the default GUI mechanism is used upon agent creation. This provides an empty frame which will be used as GUI for the agent. The life cycle of the frame is automatically managed: The frame is disposed when the agent is terminated. Some menus are available by default. Default code is only one line: frame.setContentPane(new OutputPanel(this));. Default settings for the frame are:
      Parameters:
      frame - the default frame which has been created by MaDKit for this agent.
      Since:
      MaDKit 5.1.1
      See Also:
    • getOrganizationSnapShot

      public OrganizationSnapshot getOrganizationSnapShot(boolean global)
      Returns a snapshot view of all the current organization for debugging purpose. Community -> Group -> Role -> AgentAddress
      Parameters:
      global - if true this takes into account agents coming from other connected kernels
      Returns:
      a data containing all the organization structure
    • getExistingCommunities

      public SortedSet<String> getExistingCommunities()
      Returns the names of the communities that exist.
      Returns:
      an alphanumerically ordered set containing the names of the communities which exist.
      Since:
      MaDKit 5.0.0.20
    • getExistingGroups

      public SortedSet<String> getExistingGroups(String community)
      Returns the names of the groups that exist in this community.
      Parameters:
      community - the community's name
      Returns:
      an alphanumerically ordered set containing the names of the groups which exist in this community, or null if this community does not exist.
      Since:
      MaDKit 5.0.0.20
    • getMyGroups

      public SortedSet<String> getMyGroups(String community)
      Gets the names of the groups the agent is in according to a community
      Parameters:
      community -
      Returns:
      a set containing the names of the groups the agent is in, or null if this community does not exist. This set could be empty.
    • getMyRoles

      public SortedSet<String> getMyRoles(String community, String group)
      Gets the names of the roles that the agent has in a specific group
      Parameters:
      community -
      group -
      Returns:
      a sorted set containing the names of the roles the agent has in a group, or null if the community or the group does not exist. This set could be empty.
    • getExistingRoles

      public SortedSet<String> getExistingRoles(String community, String group)
      Returns the names of the roles that exist in this group.
      Parameters:
      community - the community's name
      group - the group's name
      Returns:
      an alphanumerically ordered set containing the names of the roles which exist in this group, or null if it does not exist.
      Since:
      MaDKit 5.0.0.20
    • checkAgentAddress

      public boolean checkAgentAddress(AgentAddress agentAddress)
      Checks if this agent address is still valid. I.e. the corresponding agent is still playing this role.
      Returns:
      true if the address still exists in the organization.
      Since:
      MaDKit 5.0.4
    • isCommunity

      public boolean isCommunity(String community)
      Tells if a community exists in the artificial society.
      Parameters:
      community - the name of the community
      Returns:
      true If a community with this name exists, false otherwise.
    • isGroup

      public boolean isGroup(String community, String group)
      Tells if a group exists in the artificial society.
      Parameters:
      community - the name of the community the group is in
      group - the name of the group
      Returns:
      true If a group with this name exists in this community, false otherwise.
    • hasRole

      public boolean hasRole(String community, String group, String role)
      Tells if the agent is currently playing a specific role.
      Parameters:
      community -
      group -
      role -
      Returns:
      true if the agent is playing this role
      Since:
      MaDKit 5.0.3
    • isRole

      public boolean isRole(String community, String group, String role)
      Tells if a role exists in the artificial society.
      Parameters:
      community - the name of the community the group is in
      group - the name of the group
      role - the name of the role
      Returns:
      true If a role with this name exists in this <community;group> couple, false otherwise.
    • toString

      public String toString()
      Overrides:
      toString in class Object
      Returns:
      a String giving the name and the current state of the agent
    • getMadkitConfig

      public MadkitProperties getMadkitConfig()
      Returns the Properties object of this MaDKit session. That is by default the parameter which has been used to launch the kernel the agent is running on. If the agent has not been launched yet, the Properties returned is the default MaDKit configuration. It can be programmatically modified to launch a new session with different parameters. It can also be used as a black board shared by all the agents of a kernel by adding new user defined properties at run time or via the command line. The default set of MaDKit properties includes values for the following keys: </tr
      Key Description of Associated Value
      madkit.version MaDKit kernel version
      build.id MaDKit kernel build ID
      madkit.repository.url the agent repository for this version, usually http://www.madkit.net/madkit/repository/MaDKit-version
      desktop true or false: Launch the desktop during boot phase
      launchAgents The agents launched during the boot phase
      createLogFiles true or false: Create log files automatically for the new agents
      logDirectory The directory used for the log files (./logs by default)
      agentLogLevel the default log level for the new agents
      warningLogLevel the default warning log level for the new agents
      network true or false: Launch the network during boot phase

      Returns:
      the Properties object defining the values of each MaDKit options in the current session.
      Since:
      MaDKit 5.0.0.10
      See Also:
    • getKernelAddress

      public KernelAddress getKernelAddress()
      The kernel's address on which this agent is running.
      Returns:
      the kernel address representing the MaDKit kernel on which the agent is running
    • getServerInfo

      public String getServerInfo()
      Returns the server's info, IP and port, if the kernel is online.
      Returns:
      server's info: e.g. /192.168.1.14:4444
    • destroyCommunity

      public void destroyCommunity(String community)
      Wipes out an entire community at once. Mostly useful when doing simulated systems. This greatly optimizes the time required to make all the agents leave a community.
      Parameters:
      community - the community to destroy
      Since:
      MaDKit 5.0.0.9
    • destroyGroup

      public void destroyGroup(String community, String group)
      Wipes out an entire group at once. Mostly useful when doing simulated systems. This greatly optimizes the time required to make all the agents leave a group.
      Parameters:
      community - the community
      group - the group to destroy
      Since:
      MaDKit 5.0.0.10
    • destroyRole

      public void destroyRole(String community, String group, String role)
      Wipes out an entire role at once. Mostly useful when doing simulated systems. This greatly optimizes the time required to make all the agents leave a role.
      Parameters:
      community - the community
      group - the group
      role - the group to destroy
      Since:
      MaDKit 5.0.0.10
    • launchXmlAgents

      launch all the agents defined in an xml configuration file
      Parameters:
      xmlFile - the XML file to parse
      Returns:
      AbstractAgent.ReturnCode.SEVERE if the launch failed
      Throws:
      ParserConfigurationException
      IOException
      SAXException
    • launchNode

      public AbstractAgent.ReturnCode launchNode(Node agentXmlNode)
      Launch agents by parsing an XML node. The method immediately returns without waiting the end of the agents' activation,
      Parameters:
      agentXmlNode - the XML node
      Returns:
      AbstractAgent.ReturnCode.SEVERE if the launch failed
      See Also:
    • getState

      public AbstractAgent.State getState()
      Returns the current state of the agent in the MaDKit platform. This method provides a way of knowing what is the current state of the agent regarding its life cycle. This could be convenient when you design a method that could work differently depending on the actual state of the agent.
      Returns:
      the current state of the agent:
    • reload

      public void reload()
      Kills the caller and launches a new instance of this agent using the latest byte code available for the corresponding class.
    • proceedEnumMessage

      public <E extends Enum<E>> void proceedEnumMessage(EnumMessage<E> message)
      Proceeds an EnumMessage so that if it is correctly built, the agent will trigger its corresponding behavior using the parameters of the message.
      Parameters:
      message - the message to proceed
      Since:
      MaDKit 5.0.0.14
      See Also:
    • isKernelOnline

      public boolean isKernelOnline()
      Tells if the kernel on which this agent is running is online.
      Returns:
      true if the kernel is online.
    • executeThisAgent

      protected static Madkit executeThisAgent(int nbOfInstances, boolean createFrame, String... args)
      This offers a convenient way to create main a main method that launches the agent class under development. The agent is launched in a new instance MaDKit. This call only works in the main method of the agent's class. MaDKit. Here is an example of use that will work in any subclass of AbstractAgent:
       
       public static void main(String[] args) {
              executeThisAgent(args);
       }
       
       
      Still, the agent must have a default constructor for that to work.
      Parameters:
      nbOfInstances - specify how many of this kind should be launched
      createFrame -
      args - MaDKit options. For example, this will launch the agent in desktop mode :
                            
       public static void main(String[] args) {
              executeThisAgent(BooleanOption.desktop.toString());
       }
       
      Returns:
      the kernel instance that actually launches this agent, so that it is possible to do other actions after the launch using Madkit.doAction(madkit.action.KernelAction, Object...)
      Since:
      MaDKit 5.0.0.14
      See Also:
    • executeThisAgent

      protected static Madkit executeThisAgent(String... args)
      This offers a convenient way to create a main method that launches the agent class under development. This call only works in the main method of the agent's class. This call is equivalent to executeThisAgent(1, true, args)
      Parameters:
      args - MaDKit options
      Returns:
      the kernel instance that actually launches this agent, so that it is possible to do other actions after the launch using Madkit.doAction(madkit.action.KernelAction, Object...)
      Since:
      MaDKit 5.0.0.14
      See Also:
    • executeThisAgent

      protected static Madkit executeThisAgent()
      This offers a convenient way to create a main method that launches the agent class under development. This call only works in the main method of the agent's class. This call is equivalent to executeThisAgent(null, 1, true)
      Returns:
      the kernel instance that actually launches this agent, so that it is possible to do other actions after the launch using Madkit.doAction(madkit.action.KernelAction, Object...)
      Since:
      MaDKit 5.0.0.15
      See Also: