Class Agent

java.lang.Object
madkit.kernel.Agent
Direct Known Subclasses:
SimuAgent

public abstract class Agent extends Object
The super class of all MaDKit agents. 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.

An Agent will be given its own thread if it overrides the onLive() method

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 just fail if used.

Agents are identified and localized within the artificial society. An agent is no longer

A replying mechanism can be used to answer messages using SendReply methods. It enables the agent with the possibility of replying directly to a given message. Also, it is possible to get the reply to a message, or to wait for a reply. See reply(Message, Message) for more details.

One of the most convenient part of the API is the logging mechanism which is provided. See the getLogger() method for more details.

Since:
MaDKit 6.0
  • Constructor Details

    • Agent

      protected Agent()
      Constructs a new Agent instance.

      The agent's hashCode is set when the agent is created. This hashCode is unique for each agent instance and is used to uniquely identify the agent within the artificial society.

      It is important to note that the agent is not yet alive at this point.

  • Method Details

    • onActivation

      protected void onActivation()
      First method called when the agent is launched. This method should be overridden to define custom activation behavior.
    • onLive

      protected void onLive()
      Defines the main behavior of the agent. This method should be overridden to define custom behavior while the agent is alive. It is automatically called when the onActivation method finishes. If implemented, the agent will be given its own thread, thus making the agent completely autonomous. The agent will be alive until this method returns or it is killed.
    • onEnd

      protected void onEnd()
      This method is called when the agent finishes its life cycle. Either because the agent was killed or because the onLive method returned. This method can be overridden to define custom cleanup behavior.
    • isAlive

      public final boolean isAlive()
      Checks if the agent is alive. An agent is considered alive if it has been launched and has not yet been killed.
      Returns:
      true if the agent is alive, false otherwise.
    • exitOnKill

      protected void exitOnKill() throws AgentInterruptedException
      Checks if the current agent's thread has been interrupted, for instance, due to a kill attempt. If it has, an AgentInterruptedException is thrown.
      Throws:
      AgentInterruptedException - if the thread has been interrupted.
    • launchAgent

      public Agent.ReturnCode launchAgent(Agent a)
      Launches a new agent and waits until the launched agent has completed its onActivation() method. This has the same effect as launchAgent(Agent, int) but with a default timeout of Integer.MAX_VALUE.
      Parameters:
      a - the agent to launch.
      Returns:
      the result of the launch operation.
    • launchAgent

      public Agent.ReturnCode launchAgent(Agent a, int timeOutSeconds)
      Launches a new agent and waits until the launched agent has completed its onActivation() method or until the timeout is elapsed.

      The launch is logged at the Level.FINER level.

      Parameters:
      a - the agent to launch.
      timeOutSeconds - the maximum time to wait for the agent to launch.
      Returns:
      the result of the launch operation.
    • prng

      public RandomGenerator prng()
      Returns the random generator used by the MaDKit kernel for this session.
      Returns:
      the random generator.
    • launchAgent

      public <T extends Agent> T launchAgent(String agentClass, int timeOutSeconds)
      Launches a new agent using its full class name and returns when the launched agent has completed its onActivation() method or when the timeout is elapsed. This has the same effect as launchAgent(Agent, int) but allows launching an 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 bytecode of the corresponding class if it has been reloaded using MadkitClassLoader.reloadClass(String). Finally, if the launch succeeds within the timeout, this method returns the instance of the created agent.
      Type Parameters:
      T - the type of the agent to launch.
      Parameters:
      agentClass - the full class name of the agent to launch.
      timeOutSeconds - time to wait for the end of the agent's activation until returning null.
      Returns:
      the instance of the launched agent or null if the operation times out or fails.
    • killAgent

      protected Agent.ReturnCode killAgent(Agent a)
      Kills the specified agent, waiting forever for this agent to end.
      Parameters:
      a - the agent to be killed.
      Returns:
      the result of the kill operation.
    • killAgent

      protected Agent.ReturnCode killAgent(Agent agent, int timeOutSeconds)
      Kills the specified agent with a specified timeout.
      Parameters:
      agent - the agent to be killed.
      timeOutSeconds - the maximum time to wait for the agent to be killed.
      Returns:
      the result of the kill operation.
    • activate

      @Deprecated(since="6", forRemoval=true) protected void activate()
      Deprecated, for removal: This API element is subject to removal in a future version.
      Use onActivation() instead.
    • live

      @Deprecated(since="6", forRemoval=true) protected void live()
      Deprecated, for removal: This API element is subject to removal in a future version.
      Use onLive() instead.
    • end

      @Deprecated(since="6", forRemoval=true) protected void end()
      Deprecated, for removal: This API element is subject to removal in a future version.
      Use onEnd() instead.
    • getLogger

      public AgentLogger getLogger()
      Returns the agent's logger. It should not be used before onActivation() to get the proper logging level, that is the one set using "agentLogLevel".
      Returns:
      the agent's logger.
      Since:
      MaDKit 5.0.0.6
      See Also:
    • pause

      protected void pause(int milliSeconds)
      Stops the agent's process for a specified duration.
      Parameters:
      milliSeconds - the number of milliseconds for which the agent should pause.
    • getName

      public String getName()
      Gets the agent's name. The default name is "class name + internal ID". This name is used in logger info, GUI title, and so on. This method can be overridden to obtain a customized name.
      Returns:
      the agent's name.
    • hashCode

      public final int hashCode()
      Gets the agent's hash code. This hash code is unique for each agent instance. It is equal to the agent's internal ID, which is incremented for each agent created.
      Overrides:
      hashCode in class Object
      Returns:
      the agent's hash code.
    • equals

      public final boolean equals(Object obj)
      An Agent is unique and therefore equals to only itself.
      Overrides:
      equals in class Object
    • getKernelConfig

      public KernelConfig getKernelConfig()
      Gets the kernel configuration associated with the agent.
      Returns:
      the kernel configuration.
    • createGroup

      public Agent.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 Agent.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:
    • getOrganization

      public Organization getOrganization()
      Gets the organization. This method should not be used before the agent has been launched. The organization is the agent's view of the artificial society.
      Returns:
      the organization to which the agent is attached.
    • createGroup

      public Agent.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 SystemRoles.GROUP_MANAGER, 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 SystemRoles.GROUP_CANDIDATE, 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:
    • requestRole

      public Agent.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.
      Returns:
      the result of the request operation.
      Since:
      MaDKit 5.0
      See Also:
    • requestRole

      public Agent.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:
    • leaveGroup

      public Agent.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:
    • leaveRole

      public Agent.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:
    • getAgentWithRole

      public AgentAddress getAgentWithRole(String community, String group, String role)
      Returns an AgentAddress of a random agent having this position in the organization. The caller is excluded from the search. The PRNG used is the one associated with the caller.
      Parameters:
      community - the community name
      group - the group name
      role - the role name
      Returns:
      an AgentAddress corresponding to a random agent having this role, or null if such an agent does not exist.
    • getNetworkID

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

      public String toString()
      To string.
      Overrides:
      toString in class Object
      Returns:
      the string
    • 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.
    • sendWithRole

      public Agent.ReturnCode sendWithRole(Message message, AgentAddress receiver, String senderRole)
      Sends a message, using an agent address, specifying explicitly the role used to send it.
      Parameters:
      message - the message to send
      receiver - the targeted agent
      senderRole - the agent's role with which the message has to be sent
      Returns:
      See Also:
    • send

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

      public Agent.ReturnCode send(Message message, String community, String group, String role)
      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:
      message - the message to send
      community - the community name
      group - the group name
      role - the role name
      Returns:
      See Also:
    • sendWithRole

      public Agent.ReturnCode sendWithRole(Message message, String community, String group, String role, 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:
      message - the message to send
      community - the community name
      group - the group name
      role - the role name
      senderRole - the agent's role with which the message has to be sent
      Returns:
      See Also:
    • sendWithRoleWaitReply

      protected <T extends Message> T sendWithRoleWaitReply(Message messageToSend, String community, String group, String role, String senderRole, Integer timeOutMilliSeconds)
      Sends a message to an agent having this position in the organization and waits for an answer to it. The targeted agent is selected randomly among matched agents. The sender is excluded from this search.
      Type Parameters:
      T - the type of the message to get
      Parameters:
      messageToSend - the message to send.
      community - the community name
      group - the group name
      role - the role name
      senderRole - the role with which the sending is done.
      timeOutMilliSeconds - the maximum time to wait. If null the agent will wait indefinitely.
      Returns:
      the reply received as soon as available, or null if the time out has elapsed or if there was an error when sending the message.
      Since:
      MaDKit 5
    • sendWithRoleWaitReply

      protected <T extends Message> T sendWithRoleWaitReply(Message messageToSend, AgentAddress receiver, String senderRole, Integer timeOutMilliSeconds)
      Sends a message and waits for an answer to it. Additionally, the sending is done using a specific role for the sender.
      Type Parameters:
      T - the type of the message to get
      Parameters:
      messageToSend - the message to send.
      receiver - the targeted agent by the send.
      senderRole - the role with which the sending is done.
      timeOutMilliSeconds - the maximum time to wait. If null the agent will wait indefinitely.
      Returns:
      the reply received as soon as available, or null if the time out has elapsed or if there was an error when sending the message,
      Since:
      MaDKit 5
    • sendWaitReply

      protected <T extends Message> T sendWaitReply(Message messageToSend, AgentAddress receiver, Integer timeOutMilliSeconds)
    • sendWaitReply

      protected <T extends Message> T sendWaitReply(Message messageToSend, String community, String group, String role, Integer timeOutMilliSeconds)
      Sends a message to an agent having this position in the organization and waits for an answer to it. The targeted agent is selected randomly among matched agents. The sender is excluded from this search.
      Type Parameters:
      T - the type of the message to get agent will wait indefinitely.
      Parameters:
      messageToSend - the message to send.
      community - the community name
      group - the group name
      role - the role name
      timeOutMilliSeconds - the maximum time to wait. If null the
      Returns:
      the reply received as soon as available, or null if the time out has elapsed or if there was an error when sending the message.
      Since:
      MaDKit 5
    • broadcast

      public Agent.ReturnCode broadcast(Message message, List<AgentAddress> receivers)
      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:
      message - message to send
      receivers - list of agent addresses to send the message to
      Returns:
      See Also:
    • broadcastWithRole

      public Agent.ReturnCode broadcastWithRole(Message message, List<AgentAddress> receivers, String role)
      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:
      message - message to send
      receivers - list of agent addresses to send the message to
      role - the agent's role with which the message should be sent
      Returns:
      See Also:
    • broadcastWithRoleWaitForReplies

      protected <T extends Message> List<T> broadcastWithRoleWaitForReplies(Message message, List<AgentAddress> receivers, String senderRole, Integer timeOutMilliSeconds)
      Broadcasts a message and wait for answers considering a timeout duration.
      Type Parameters:
      T - the type of the message to get
      Parameters:
      message - the message to broadcast
      receivers - the list of agent addresses to send the message to
      senderRole - the agent's role with which the message should be
      timeOutMilliSeconds - the maximum time to wait.
      Returns:
      a list of messages which are answers to the message which has been broadcasted.
    • getAgentsWithRole

      public List<AgentAddress> getAgentsWithRole(String community, String group, String role)
      Returns a list of agent addresses corresponding to agents having this role in the organization. The caller is excluded from this search.
      Parameters:
      community - the community name
      group - the group name
      role - the role name
      Returns:
      a list of agent addresses corresponding to agents handling this role
    • checkAgentAddress

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

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

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

      public <T extends Message> T getReplyTo(Message originalMessage)
      Gets the next message which is a reply to the originalMessage.
      Type Parameters:
      T - the type of the message to get
      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.
    • waitNextMessage

      protected <T extends Message> T waitNextMessage()
      This method is the blocking version of nextMessage(). If there is no message in the mailbox, it suspends the agent life until a message is received
      Type Parameters:
      T - the type of the message to get
      Returns:
      the first received message
      See Also:
    • waitNextMessage

      protected <T extends Message> T waitNextMessage(long timeOutMilliseconds)
      This method gets the next message of the mailbox or waits for a new incoming message considering a certain delay.
      Type Parameters:
      T - the type of the message to get
      Parameters:
      timeOutMilliseconds - the maximum time to wait, in milliseconds.
      Returns:
      the first message in the mailbox, or null if no message has been received before the time out delay is elapsed
    • waitAnswer

      protected <T extends Message> T waitAnswer(Message query)
      Retrieves and removes the next message that is a reply to the query message, waiting for ever if necessary until a matching reply becomes available.
      Type Parameters:
      T - the type of the message to get
      Parameters:
      query - the message for which a reply is waited for
      Returns:
      the first reply to the query message
      Since:
      MadKit 5.0.4
    • waitAnswer

      protected <T extends Message> T waitAnswer(Message query, Integer timeOutMilliSeconds)
      Retrieves and removes the next message that is a reply to the query message, waiting for ever if necessary until a matching reply becomes available.
      Type Parameters:
      T - the type of the message to get
      Parameters:
      query - the message for which a reply is waited for
      timeOutMilliSeconds - the maximum time to wait, in milliseconds.
      Returns:
      the first reply to the query message
      Since:
      MadKit 5.0.4
    • receiveMessage

      public void receiveMessage(Message message)
      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:
      message - the message to send
    • getMailbox

      protected Mailbox getMailbox()
      Returns the agent's mailbox
      Returns:
      the mailbox
    • setupDefaultGUI

      public void setupDefaultGUI()
      Creates a default frame for the agent. It is made of a FXAgentStage containing a FXOutputPane
    • 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
    • nextMessage

      public <M extends Message> M nextMessage()
      Retrieves the next message from the mailbox.

      It returns the next message of type M from the mailbox. The type parameter M must extend the Message class, allowing for flexibility in the types of messages that can be processed.

      Type Parameters:
      M - the type of the message to get
      Returns:
      the next message of type M from the mailbox.
    • executeThisAgent

      protected static Madkit executeThisAgent(int nbOfInstances, 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 Agent: To launch 10 instances of an agent, you can use:
                           
                           public static void main(String[] args) {
                           executeThisAgent(10, args);
                           }
       
       
      Still, the agent must have a default constructor for that to work.
      Parameters:
      nbOfInstances - specify how many of this kind should be launched
      args - MaDKit options.
      Returns:
      the kernel instance that actually launches this agent, so that it is possible to do other actions after the launch
      Since:
      MaDKit 5.0.0.14
    • 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.launchAgent(Agent)
      Since:
      MaDKit 5.0.0.14
      See Also:
    • handleRequestActionMessage

      public void handleRequestActionMessage(RequestActionMessage message)
      Handles a RequestActionMessage so that the agent will trigger the corresponding method using the parameters of the message. Such messages are usually sent by GUI buttons or other user interfaces to trigger actions in the agent.
      Parameters:
      message - the message to handle