示例#1
0
    /**
     * Start agent.
     *
     * @param nickName the nick name
     * @param agentClassName the agent class name
     * @param args the args
     * @return true, if successful
     */
    private boolean startAgent(String nickName, String agentClassName, Object[] args) {

      AID agentID = new AID();
      agentID.setLocalName(nickName);

      try {
        Agent agent = (Agent) ObjectManager.load(agentClassName, ObjectManager.AGENT_TYPE);
        if (agent == null) {
          agent = (Agent) Class.forName(agentClassName).newInstance();
        }
        agent.setArguments(args);
        myContainer.initAgent(agentID, agent, null, null);
        myContainer.powerUpLocalAgent(agentID);

      } catch (IMTPException
          | NameClashException
          | NotFoundException
          | JADESecurityException
          | ClassNotFoundException
          | InstantiationException
          | IllegalAccessException e) {
        logger.fatal(e);
      }
      return true;
    }
    private void handleInformKilled(VerticalCommand cmd)
        throws IMTPException, NotFoundException, ServiceException {
      Object[] params = cmd.getParams();
      AID target = (AID) params[0];

      // log("Source Sink consuming command INFORM_KILLED. Name is "+target.getName(), 3);
      if (myLogger.isLoggable(Logger.CONFIG))
        myLogger.log(
            Logger.CONFIG,
            "Source Sink consuming command INFORM_KILLED. Name is " + target.getName());

      // Remove CodeLocator entry.
      // #J2ME_EXCLUDE_BEGIN
      codeLocator.removeAgent(target);
      // #J2ME_EXCLUDE_END

      // Remove the dead agent from the LADT of the container
      removeLocalAgent(target);

      // Notify the main container through its slice
      AgentManagementSlice mainSlice = (AgentManagementSlice) getSlice(MAIN_SLICE);

      try {
        mainSlice.deadAgent(target, cmd);
      } catch (IMTPException imtpe) {
        // Try to get a newer slice and repeat...
        mainSlice = (AgentManagementSlice) getFreshSlice(MAIN_SLICE);
        mainSlice.deadAgent(target, cmd);
      }
    }
示例#3
0
 public String receivedFrom() {
   if (theMessage.getSender() != null) {
     AID sender = theMessage.getSender();
     return sender.getName();
   }
   return "<unknown>";
 }
    private void handleRequestKill(VerticalCommand cmd)
        throws IMTPException, JADESecurityException, NotFoundException, ServiceException {

      Object[] params = cmd.getParams();
      AID agentID = (AID) params[0];

      // log("Source Sink consuming command REQUEST_KILL. Name is "+agentID.getName(), 3);
      if (myLogger.isLoggable(Logger.CONFIG))
        myLogger.log(
            Logger.CONFIG,
            "Source Sink consuming command REQUEST_KILL. Name is " + agentID.getName());

      MainContainer impl = myContainer.getMain();
      if (impl != null) {
        ContainerID cid = impl.getContainerID(agentID);
        // Note that since getContainerID() succeeded, targetSlice can't be null
        AgentManagementSlice targetSlice = (AgentManagementSlice) getSlice(cid.getName());
        try {
          targetSlice.killAgent(agentID, cmd);
        } catch (IMTPException imtpe) {
          // Try to get a newer slice and repeat...
          targetSlice = (AgentManagementSlice) getFreshSlice(cid.getName());
          targetSlice.killAgent(agentID, cmd);
        }
      } else {
        // Do nothing for now, but could also route the command to the main slice, thus enabling
        // e.g. AMS replication
      }
    }
示例#5
0
    /* (non-Javadoc)
     * @see jade.core.Filter#accept(jade.core.VerticalCommand)
     */
    @Override
    public final boolean accept(VerticalCommand cmd) {
      if (cmd == null) {
        return true;
      }

      String cmdName = cmd.getName();
      if (cmdName.equals(MessagingSlice.SET_PLATFORM_ADDRESSES) && myContainerMTPurl == null) {
        // --- Handle that the MTP-Address was created ------
        Object[] params = cmd.getParams();
        AID aid = (AID) params[0];
        String[] aidArr = aid.getAddressesArray();
        if (aidArr.length != 0) {
          myContainerMTPurl = aidArr[0];
          setLocalCRCReply(false);
        }
        // Veto the original SEND_MESSAGE command, if needed
        // return false;
      } else if (cmdName.equals(AgentManagementSlice.KILL_CONTAINER)) {
        Object[] params = cmd.getParams();
        ContainerID id = (ContainerID) params[0];
        String containerName = id.getName();
        loadInfo.containerLoads.remove(containerName);
        loadInfo.containerLocations.remove(containerName);

      } else if (cmdName.equals(AgentMobilityHelper.INFORM_MOVED)) {
        Object[] params = cmd.getParams();
        @SuppressWarnings("unused")
        AID aid = (AID) params[0];
      }
      // Never veto other commands
      return true;
    }
示例#6
0
 /**
  * Gets the SendTo attribute of the MessageNode object
  *
  * @return The SendTo value
  */
 public String getSendTo() {
   if (theMessage.getAllReceiver().hasNext()) {
     AID sender = (AID) theMessage.getAllReceiver().next();
     return sender.getName();
   }
   return "<unknown>";
 }
  private void initAgent(AID target, Agent instance, VerticalCommand vCmd)
      throws IMTPException, JADESecurityException, NameClashException, NotFoundException,
          ServiceException {
    // #J2ME_EXCLUDE_BEGIN
    // If the agent was loaded from a separate space, register it to the codeLocator
    if (isLoadedFromSeparateSpace(instance)) {
      try {
        codeLocator.registerAgent(target, instance.getClass().getClassLoader());
      } catch (Exception e) {
        // Should never happen
        e.printStackTrace();
      }
    }
    // #J2ME_EXCLUDE_END

    // Connect the new instance to the local container
    Agent old = myContainer.addLocalAgent(target, instance);
    if (instance == old) {
      // This is a re-addition of an existing agent to a recovered main container
      // (FaultRecoveryService)
      old = null;
    }

    try {
      // Notify the main container through its slice
      AgentManagementSlice mainSlice = (AgentManagementSlice) getSlice(MAIN_SLICE);

      // We propagate the class-name to the main, but we don't want to keep it in the actual agent
      // AID.
      AID cloned = (AID) target.clone();
      cloned.addUserDefinedSlot(AID.AGENT_CLASSNAME, instance.getClass().getName());
      try {
        mainSlice.bornAgent(cloned, myContainer.getID(), vCmd);
      } catch (IMTPException imtpe) {
        // Try to get a newer slice and repeat...
        mainSlice = (AgentManagementSlice) getFreshSlice(MAIN_SLICE);
        mainSlice.bornAgent(cloned, myContainer.getID(), vCmd);
      }
      customize(instance);
    } catch (NameClashException nce) {
      removeLocalAgent(target);
      if (old != null) {
        myContainer.addLocalAgent(target, old);
      }
      throw nce;
    } catch (IMTPException imtpe) {
      removeLocalAgent(target);
      throw imtpe;
    } catch (NotFoundException nfe) {
      removeLocalAgent(target);
      throw nfe;
    } catch (JADESecurityException ae) {
      removeLocalAgent(target);
      throw ae;
    }
  }
示例#8
0
 //////////////////////////
 // Private utility methods
 //////////////////////////
 private String[] getParticipantNames() {
   String[] pp = new String[participants.size()];
   Iterator it = participants.iterator();
   int i = 0;
   while (it.hasNext()) {
     AID id = (AID) it.next();
     pp[i++] = id.getLocalName();
   }
   return pp;
 }
    private void handleRequestKill(VerticalCommand cmd)
        throws IMTPException, JADESecurityException, NotFoundException, ServiceException {

      Object[] params = cmd.getParams();
      AID agentID = (AID) params[0];

      // log("Target sink consuming command REQUEST_KILL: Name is "+agentID.getName(), 2);
      if (myLogger.isLoggable(Logger.FINE))
        myLogger.log(
            Logger.FINE,
            "Target sink consuming command REQUEST_KILL: Name is " + agentID.getName());

      killAgent(agentID);
    }
    private void handleInformKilled(VerticalCommand cmd)
        throws NotFoundException, ServiceException {

      Object[] params = cmd.getParams();
      AID agentID = (AID) params[0];

      // log("Target sink consuming command INFORM_KILLED: Name is "+agentID.getName(), 2);
      if (myLogger.isLoggable(Logger.FINE))
        myLogger.log(
            Logger.FINE,
            "Target sink consuming command INFORM_KILLED: Name is " + agentID.getName());

      deadAgent(agentID);
    }
    private void handleInformCreated(VerticalCommand cmd)
        throws NotFoundException, NameClashException, ServiceException {
      Object[] params = cmd.getParams();

      AID agentID = (AID) params[0];
      ContainerID cid = (ContainerID) params[1];

      if (myLogger.isLoggable(Logger.FINE)) {
        myLogger.log(
            Logger.FINE,
            "Target sink consuming command INFORM_CREATED: Name is " + agentID.getName());
      }

      bornAgent(agentID, cid, cmd.getPrincipal(), cmd.getCredentials());
    }
示例#12
0
 /**
  * create a new ACLMessage that is a reply to this message. In particular, it sets the following
  * parameters of the new message: receiver, language, ontology, protocol, conversation-id,
  * in-reply-to, reply-with. The programmer needs to set the communicative-act and the content. Of
  * course, if he wishes to do that, he can reset any of the fields.
  *
  * @return the ACLMessage to send as a reply
  */
 public ACLMessage createReply() {
   ACLMessage m = new ACLMessage(getPerformative());
   Iterator it = getAllReplyTo();
   while (it.hasNext()) m.addReceiver((AID) it.next());
   if ((reply_to == null) || reply_to.isEmpty()) m.addReceiver(getSender());
   m.setLanguage(getLanguage());
   m.setOntology(getOntology());
   m.setProtocol(getProtocol());
   m.setInReplyTo(getReplyWith());
   if (source != null) m.setReplyWith(source.getName() + java.lang.System.currentTimeMillis());
   else m.setReplyWith("X" + java.lang.System.currentTimeMillis());
   m.setConversationId(getConversationId());
   // Copy only well defined user-def-params
   String trace = getUserDefinedParameter(TRACE);
   if (trace != null) {
     m.addUserDefinedParameter(TRACE, trace);
   }
   // #CUSTOM_EXCLUDE_BEGIN
   // Set the Aclrepresentation of the reply message to the aclrepresentation of the sent message
   if (messageEnvelope != null) {
     m.setDefaultEnvelope();
     String aclCodec = messageEnvelope.getAclRepresentation();
     if (aclCodec != null) m.getEnvelope().setAclRepresentation(aclCodec);
   } else m.setEnvelope(null);
   // #CUSTOM_EXCLUDE_END
   return m;
 }
示例#13
0
  /**
   * Request for medicine.
   *
   * <p>This method sends a <b> FIPA REQUEST </b> message to all agents who offers the <tt>
   * m_sMedicService </tt> service.
   *
   * <p>The content of message is: <tt> ( x , y , z ) ( health ) </tt>.
   *
   * <p>Variable <tt> m_iMedicsCount </tt> is updated.
   *
   * <p><em> It's very useful to overload this method. </em>
   */
  protected void CallForMedic() {

    try {

      DFAgentDescription dfd = new DFAgentDescription();
      ServiceDescription sd = new ServiceDescription();
      sd.setType(m_sMedicService);
      dfd.addServices(sd);
      DFAgentDescription[] result = DFService.search(this, dfd);

      if (result.length > 0) {

        m_iMedicsCount = result.length;

        // Fill the REQUEST message
        ACLMessage msg = new ACLMessage(ACLMessage.REQUEST);

        for (int i = 0; i < result.length; i++) {

          DFAgentDescription dfdMedic = result[i];
          AID Medic = dfdMedic.getName();
          if (!Medic.equals(getName())) msg.addReceiver(dfdMedic.getName());
          else m_iMedicsCount--;
        }
        msg.setProtocol(FIPANames.InteractionProtocol.FIPA_REQUEST);
        msg.setConversationId("CFM");
        msg.setContent(
            " ( "
                + m_Movement.getPosition().x
                + " , "
                + m_Movement.getPosition().y
                + " , "
                + m_Movement.getPosition().z
                + " ) ( "
                + GetHealth()
                + " ) ");
        send(msg);
        System.out.println(getLocalName() + ": Need a Medic! (v21)");

      } else {
        m_iMedicsCount = 0;
      }
    } catch (FIPAException fe) {
      fe.printStackTrace();
    }
  }
示例#14
0
 void buscarMensajeros() {
   try {
     DFAgentDescription dfd = new DFAgentDescription();
     ServiceDescription sd = new ServiceDescription();
     sd.setType("Mensajero_Axis");
     dfd.addServices(sd);
     DFAgentDescription[] result = DFService.search(this, dfd);
     if (result.length > 0) {
       for (int i = 0; i < result.length; i++) {
         DFAgentDescription dfdMensajero = result[i];
         AID mensajero = dfdMensajero.getName();
         if (!mensajero.equals(getName())) m_AidListaMensajeros.add(mensajero);
       }
     }
   } catch (FIPAException fe) {
     fe.printStackTrace();
   }
 }
  /**
   * Get a controller (i.e. a proxy) to a local agent given its local-name or GUID.
   *
   * @param name The local name or the GUID of the desired agent.
   * @param isGuid A flag indicating whether <code>name</code> represents the local-name (<code>
   *     AID.ISLOCALNAME</code>) or the GUID (<code>AID.ISGUID</code>) of the desired agent.
   * @throws ControllerException If any problems occur obtaining this proxy or if no such agent
   *     exists in the local container.
   */
  public AgentController getAgent(String name, boolean isGuid) throws ControllerException {
    if (myImpl == null || myProxy == null) {
      throw new StaleProxyException();
    }

    if (!isGuid) {
      name = AID.createGUID(name, myImpl.getPlatformID());
    }
    AID agentID = new AID(name, AID.ISGUID);

    // Check that the agent exists
    jade.core.Agent instance = myImpl.acquireLocalAgent(agentID);
    if (instance == null) {
      throw new ControllerException("Agent " + agentID.getName() + " not found.");
    }
    myImpl.releaseLocalAgent(agentID);
    return new AgentControllerImpl(agentID, myProxy, myImpl);
  }
    private void handleInformCreated(VerticalCommand cmd)
        throws IMTPException, NotFoundException, NameClashException, JADESecurityException,
            ServiceException {
      Object[] params = cmd.getParams();
      AID target = (AID) params[0];
      Agent instance = (Agent) params[1];
      JADEPrincipal owner = (JADEPrincipal) params[2];

      if (myLogger.isLoggable(Logger.CONFIG)) {
        String ownerInfo = owner != null ? ", Owner = " + owner : "";
        myLogger.log(
            Logger.CONFIG,
            "Source Sink consuming command INFORM_CREATED. Name is "
                + target.getName()
                + ownerInfo);
      }

      initAgent(target, instance, cmd);
    }
  /**
   * Utility method that updates the contact list extracting contact info and location from DF
   * descriptions.
   *
   * @param onlineContactsDescs array of {@link DFAgentDescription} objects that define services as
   *     results of a DF query
   */
  private void updateContactList(DFAgentDescription[] onlineContactsDescs) {

    for (int i = 0; i < onlineContactsDescs.length; i++) {
      Iterator serviceDescIt = onlineContactsDescs[i].getAllServices();

      if (serviceDescIt.hasNext()) {
        ServiceDescription desc = (ServiceDescription) serviceDescIt.next();

        Iterator propertyIt = desc.getAllProperties();
        Location loc = Helper.extractLocation(propertyIt);

        AID cId = onlineContactsDescs[i].getName();
        if (!cId.equals(myAgent.getAID())) {
          // Create an online contact (or update it)
          String phoneNumber = cId.getLocalName();
          ContactManager.getInstance().addOrUpdateOnlineContact(phoneNumber, loc);
        }
      }
    }
  }
示例#18
0
  // #MIDP_EXCLUDE_BEGIN
  public synchronized Object clone() {

    ACLMessage result;

    try {
      result = (ACLMessage) super.clone();
      result.persistentID = null;
      if (source != null) {
        result.source = (AID) source.clone();
      }

      // Deep clone receivers
      if (dests != null) {
        result.dests = new ArrayList(dests.size());
        Iterator it = dests.iterator();
        while (it.hasNext()) {
          AID id = (AID) it.next();
          result.dests.add(id.clone());
        }
      }

      // Deep clone reply_to
      if (reply_to != null) {
        result.reply_to = new ArrayList(reply_to.size());
        Iterator it = reply_to.iterator();
        while (it.hasNext()) {
          AID id = (AID) it.next();
          result.reply_to.add(id.clone());
        }
      }

      // Deep clone user-def-properties if present
      if (userDefProps != null) result.userDefProps = (Properties) userDefProps.clone();
      // Deep clone envelope if present
      if (messageEnvelope != null) result.messageEnvelope = (Envelope) messageEnvelope.clone();
    } catch (CloneNotSupportedException cnse) {
      throw new InternalError(); // This should never happen
    }

    return result;
  }
    private void handleRequestCreate(VerticalCommand cmd)
        throws IMTPException, JADESecurityException, NotFoundException, NameClashException,
            ServiceException {

      Object[] params = cmd.getParams();
      String name = (String) params[0];
      String className = (String) params[1];
      Object[] args = (Object[]) params[2];
      ContainerID cid = (ContainerID) params[3];
      JADEPrincipal owner = (JADEPrincipal) params[4];
      Credentials initialCredentials = (Credentials) params[5];

      if (myLogger.isLoggable(Logger.CONFIG))
        myLogger.log(
            Logger.CONFIG, "Source Sink consuming command REQUEST_CREATE. Name is " + name);
      MainContainer impl = myContainer.getMain();
      if (impl != null) {

        AID agentID = new AID(AID.createGUID(name, myContainer.getPlatformID()), AID.ISGUID);
        AgentManagementSlice targetSlice = (AgentManagementSlice) getSlice(cid.getName());
        if (targetSlice != null) {
          try {
            targetSlice.createAgent(
                agentID,
                className,
                args,
                owner,
                initialCredentials,
                AgentManagementSlice.CREATE_AND_START,
                cmd);
          } catch (IMTPException imtpe) {
            // Try to get a newer slice and repeat...
            targetSlice = (AgentManagementSlice) getFreshSlice(cid.getName());
            targetSlice.createAgent(
                agentID,
                className,
                args,
                owner,
                initialCredentials,
                AgentManagementSlice.CREATE_AND_START,
                cmd);
          }
        } else {
          throw new NotFoundException("Container " + cid.getName() + " not found");
        }
      } else {
        // Do nothing for now, but could also route the command to the main slice, thus enabling
        // e.g. AMS replication
      }
    }
    private void handleRequestCreate(VerticalCommand cmd)
        throws IMTPException, JADESecurityException, NotFoundException, NameClashException,
            ServiceException {

      Object[] params = cmd.getParams();
      AID agentID = (AID) params[0];
      String className = (String) params[1];
      Object[] arguments = (Object[]) params[2];
      JADEPrincipal owner = (JADEPrincipal) params[3];
      Credentials initialCredentials = (Credentials) params[4];
      boolean startIt = ((Boolean) params[5]).booleanValue();

      // log("Target sink consuming command REQUEST_CREATE: Name is "+agentID.getName(), 2);
      if (myLogger.isLoggable(Logger.FINE)) {
        String ownerInfo = owner != null ? ", Owner = " + owner : "";
        myLogger.log(
            Logger.FINE,
            "Target sink consuming command REQUEST_CREATE: Name is "
                + agentID.getName()
                + ownerInfo);
      }

      createAgent(agentID, className, arguments, owner, initialCredentials, startIt);
    }
  /**
   * Creates a new JADE agent, running within this container,
   *
   * @param nickname A platform-unique nickname for the newly created agent. The agent will be given
   *     a FIPA compliant agent identifier using the nickname and the ID of the platform it is
   *     running on.
   * @param className The fully qualified name of the class that implements the agent.
   * @param args An object array, containing initialization parameters to pass to the new agent.
   * @return A proxy object, allowing to call state-transition forcing methods on the real agent
   *     instance.
   */
  public AgentController createNewAgent(String nickname, String className, Object[] args)
      throws StaleProxyException {
    if (myImpl == null || myProxy == null) {
      throw new StaleProxyException();
    }

    AID agentID = new AID(AID.createGUID(nickname, myImpl.getPlatformID()), AID.ISGUID);

    try {
      myProxy.createAgent(agentID, className, args);
      return new AgentControllerImpl(agentID, myProxy, myImpl);
    } catch (Throwable t) {
      t.printStackTrace();
      throw new StaleProxyException(t);
    }
  }
  /**
   * Add an Agent to this container. Typically Agent would be some class extending Agent which was
   * instantiated and configured.
   *
   * @param nickname A platform-unique nickname for the newly created agent. The agent will be given
   *     a FIPA compliant agent identifier using the nickname and the ID of the platform it is
   *     running on.
   * @param anAgent The agent to be added to this agent container.
   * @return An AgentController, allowing to call state-transition forcing methods on the real agent
   *     instance.
   */
  public AgentController acceptNewAgent(String nickname, jade.core.Agent anAgent)
      throws StaleProxyException {
    if (myImpl == null || myProxy == null) {
      throw new StaleProxyException();
    }

    AID agentID = new AID(AID.createGUID(nickname, myImpl.getPlatformID()), AID.ISGUID);
    // FIXME: This call skips the security checks on the local container
    try {
      jade.core.NodeDescriptor nd = myImpl.getNodeDescriptor();
      // The owner of the new agent is the owner of the local container.
      // The new agent has NO initial credentials
      myImpl.initAgent(agentID, anAgent, nd.getOwnerPrincipal(), null);
    } catch (Exception e) {
      throw new StaleProxyException(e);
    }
    return new AgentControllerImpl(agentID, myProxy, myImpl);
  }
 private ACLMessage createMessage() {
   ACLMessage message;
   if (id == -1) message = new ACLMessage(ACLMessage.FAILURE);
   else {
     message = new ACLMessage(ACLMessage.INFORM);
     BDDAnswerMessage answer = new BDDAnswerMessage();
     answer.setDemande(demande);
     answer.setUser(user);
     answer.setId(id);
     ObjectMapper omap = new ObjectMapper();
     String messageCorps;
     try {
       messageCorps = omap.writeValueAsString(answer);
       message.setContent(messageCorps);
       message.addReceiver(receiver);
       System.out.println(receiver.getName());
       message.setConversationId(conversationId);
     } catch (JsonProcessingException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
     }
   }
   return message;
 }
    public VerticalCommand serve(HorizontalCommand cmd) {
      VerticalCommand result = null;
      try {
        String cmdName = cmd.getName();
        Object[] params = cmd.getParams();

        if (cmdName.equals(AgentManagementSlice.H_CREATEAGENT)) {
          GenericCommand gCmd =
              new GenericCommand(
                  AgentManagementSlice.REQUEST_CREATE, AgentManagementSlice.NAME, null);
          AID agentID = (AID) params[0];
          String className = (String) params[1];
          Object[] arguments = (Object[]) params[2];
          JADEPrincipal owner = (JADEPrincipal) params[3];
          Credentials initialCredentials = (Credentials) params[4];
          Boolean startIt = (Boolean) params[5];
          gCmd.addParam(agentID);
          gCmd.addParam(className);
          gCmd.addParam(arguments);
          gCmd.addParam(owner);
          gCmd.addParam(initialCredentials);
          gCmd.addParam(startIt);

          result = gCmd;
        } else if (cmdName.equals(AgentManagementSlice.H_KILLAGENT)) {
          GenericCommand gCmd =
              new GenericCommand(
                  AgentManagementSlice.REQUEST_KILL, AgentManagementSlice.NAME, null);
          AID agentID = (AID) params[0];
          gCmd.addParam(agentID);

          result = gCmd;
        } else if (cmdName.equals(AgentManagementSlice.H_CHANGEAGENTSTATE)) {
          GenericCommand gCmd =
              new GenericCommand(
                  AgentManagementSlice.REQUEST_STATE_CHANGE, AgentManagementSlice.NAME, null);
          AID agentID = (AID) params[0];
          Integer newState = (Integer) params[1];
          gCmd.addParam(agentID);
          gCmd.addParam(newState);

          result = gCmd;
        } else if (cmdName.equals(AgentManagementSlice.H_BORNAGENT)) {
          GenericCommand gCmd =
              new GenericCommand(
                  AgentManagementSlice.INFORM_CREATED, AgentManagementSlice.NAME, null);
          AID agentID = (AID) params[0];
          ContainerID cid = (ContainerID) params[1];
          gCmd.addParam(agentID);
          gCmd.addParam(cid);

          JADEPrincipal owner = cmd.getPrincipal();
          if (myLogger.isLoggable(Logger.FINE)) {
            String ownerInfo = owner != null ? ", Owner = " + owner : "";
            myLogger.log(
                Logger.CONFIG,
                "Local slice processing H-command BORN_AGENT. Name is "
                    + agentID.getName()
                    + ownerInfo);
          }

          result = gCmd;
        } else if (cmdName.equals(AgentManagementSlice.H_DEADAGENT)) {
          GenericCommand gCmd =
              new GenericCommand(
                  AgentManagementSlice.INFORM_KILLED, AgentManagementSlice.NAME, null);
          AID agentID = (AID) params[0];
          gCmd.addParam(agentID);

          result = gCmd;
        } else if (cmdName.equals(AgentManagementSlice.H_SUSPENDEDAGENT)) {
          GenericCommand gCmd =
              new GenericCommand(
                  AgentManagementSlice.INFORM_STATE_CHANGED, AgentManagementSlice.NAME, null);
          AID agentID = (AID) params[0];
          gCmd.addParam(agentID);
          gCmd.addParam(jade.domain.FIPAAgentManagement.AMSAgentDescription.SUSPENDED);
          gCmd.addParam("*");

          result = gCmd;
        } else if (cmdName.equals(AgentManagementSlice.H_RESUMEDAGENT)) {
          GenericCommand gCmd =
              new GenericCommand(
                  AgentManagementSlice.INFORM_STATE_CHANGED, AgentManagementSlice.NAME, null);
          AID agentID = (AID) params[0];
          gCmd.addParam(agentID);
          gCmd.addParam(jade.domain.FIPAAgentManagement.AMSAgentDescription.ACTIVE);
          gCmd.addParam(jade.domain.FIPAAgentManagement.AMSAgentDescription.SUSPENDED);

          result = gCmd;
        } else if (cmdName.equals(AgentManagementSlice.H_EXITCONTAINER)) {
          GenericCommand gCmd =
              new GenericCommand(
                  AgentManagementSlice.KILL_CONTAINER, AgentManagementSlice.NAME, null);

          result = gCmd;
        }

      } catch (Throwable t) {
        cmd.setReturnValue(t);
      }
      return result;
    }
    /**
     * Overrides SubscriptionInitiator.handleInform(), defining what to do each time the DF is
     * modified by a contact Basically it adds/removes/updates contacts from ContactList according
     * to what has happened to DF. It also fires events on the GUI any time a view refresh is
     * needed.
     *
     * @param inform the message from DF containing a list of changes
     */
    protected void handleInform(ACLMessage inform) {

      myLogger.log(
          Logger.FINE,
          "Thread " + Thread.currentThread().getId() + ": Notification received from DF");
      ContactManager.getInstance().resetModifications();

      try {

        DFAgentDescription[] results = DFService.decodeNotification(inform.getContent());

        if (results.length > 0) {

          for (int i = 0; i < results.length; ++i) {
            DFAgentDescription dfd = results[i];
            AID contactAID = dfd.getName();
            // Do something only if the notification deals with an agent different from the current
            // one
            if (!contactAID.equals(myAgent.getAID())) {

              myLogger.log(
                  Logger.INFO,
                  "Thread "
                      + Thread.currentThread().getId()
                      + ":df says that agent "
                      + myAgent.getAID().getLocalName()
                      + " updates or registers");
              Iterator serviceIter = dfd.getAllServices();

              // Registered or updated
              if (serviceIter.hasNext()) {
                ServiceDescription serviceDesc = (ServiceDescription) serviceIter.next();
                Iterator propertyIt = serviceDesc.getAllProperties();
                Location loc = Helper.extractLocation(propertyIt);
                String phoneNum = contactAID.getLocalName();
                ContactManager.getInstance().addOrUpdateOnlineContact(phoneNum, loc);
              } else {
                myLogger.log(
                    Logger.INFO,
                    "Thread "
                        + Thread.currentThread().getId()
                        + ":df says that agent "
                        + myAgent.getAID().getLocalName()
                        + " deregisters");
                String phoneNumber = contactAID.getLocalName();
                Contact c = ContactManager.getInstance().getContact(phoneNumber);
                ContactManager.getInstance().setContactOffline(phoneNumber);
                MsnEvent event =
                    MsnEventMgr.getInstance().createEvent(MsnEvent.CONTACT_DISCONNECT_EVENT);
                event.addParam(MsnEvent.CONTACT_DISCONNECT_PARAM_CONTACTNAME, c.getName());
                MsnEventMgr.getInstance().fireEvent(event);
              }

              MsnEvent event = MsnEventMgr.getInstance().createEvent(MsnEvent.VIEW_REFRESH_EVENT);
              ContactListChanges changes = ContactManager.getInstance().getModifications();
              Map<String, Contact> cMap = ContactManager.getInstance().getAllContacts();
              Map<String, ContactLocation> cLocMap =
                  ContactManager.getInstance().getAllContactLocations();

              myLogger.log(
                  Logger.FINE,
                  "Thread "
                      + Thread.currentThread().getId()
                      + ":Adding to VIEW_REFRESH_EVENT this list of changes: "
                      + changes.toString());
              event.addParam(MsnEvent.VIEW_REFRESH_PARAM_LISTOFCHANGES, changes);
              event.addParam(MsnEvent.VIEW_REFRESH_CONTACTSMAP, cMap);
              event.addParam(MsnEvent.VIEW_REFRESH_PARAM_LOCATIONMAP, cLocMap);
              MsnEventMgr.getInstance().fireEvent(event);
            }
          }
        }

      } catch (Exception e) {
        myLogger.log(Logger.WARNING, "See printstack for Exception.", e);
        e.printStackTrace();
      }
    }
  private WSIGService createWSIGService(AID aid, ServiceDescription sd) throws Exception {

    // Get service prefix & name
    String servicePrefix = getServicePrefix(sd);
    String serviceName = servicePrefix + sd.getName();

    // Verify if is a wsig service
    if (!isWSIGService(sd)) {
      log.info("Service " + serviceName + " discarded (no wsig service)");
      return null;
    }

    // Verify if the service is already registered
    if (wsigStore.isServicePresent(serviceName)) {
      log.info("Service " + serviceName + " of agent " + aid.getName() + " is already registered");
      return null;
    }

    // Get ontology
    // FIX-ME elaborate only first ontology
    String ontoName = null;
    Iterator ontoIt = sd.getAllOntologies();
    if (ontoIt.hasNext()) {
      ontoName = (String) ontoIt.next();
    }
    if (ontoName == null) {
      log.info(
          "Service "
              + serviceName
              + " of agent "
              + aid.getName()
              + " have not ontology registered");
      return null;
    }

    // Create ontology instance
    String ontoClassname = WSIGConfiguration.getInstance().getOntoClassname(ontoName);
    if (ontoClassname == null) {
      log.warn("Ontology " + ontoName + " not present in WSIG configuration file");
      return null;
    }

    Ontology serviceOnto;
    try {
      Class ontoClass = Class.forName(ontoClassname);
      Method getInstanceMethod = ontoClass.getMethod("getInstance");
      serviceOnto = (Ontology) getInstanceMethod.invoke(null);
    } catch (Exception e) {
      log.warn("Ontology class " + ontoClassname + " not present in WSIG classpath", e);
      return null;
    }

    // Register new onto in anget
    getContentManager().registerOntology(serviceOnto);

    // Get mapper class
    Class mapperClass = getMapperClass(sd);

    // Create new WSIGService
    WSIGService wsigService = new WSIGService();
    wsigService.setServiceName(serviceName);
    wsigService.setServicePrefix(servicePrefix);
    wsigService.setAid(aid);
    wsigService.setWsdl(
        new URL(WSIGConfiguration.getInstance().getWsdlUri() + "/" + serviceName + ".wsdl"));
    wsigService.setOnto(serviceOnto);
    wsigService.setMapperClass(mapperClass);

    // Create wsdl
    SDToWSDL.createWSDLFromSD(this, sd, wsigService);

    return wsigService;
  }
示例#27
0
文件: ASU.java 项目: agentlab/sg-sim
  public void setup() {
    System.out.println("ASU.setup()");

    getContentManager().registerLanguage(codec);
    getContentManager().registerOntology(ontology);

    ACLMessage aclmsg = new ACLMessage(ACLMessage.REQUEST);
    AssignPowerRequest apr = new AssignPowerRequest();
    apr.setAssignedPower(100000);

    aclmsg.setLanguage(codec.getName());
    aclmsg.setOntology(ontology.getName());
    aclmsg.setProtocol(FIPANames.InteractionProtocol.FIPA_REQUEST);
    aclmsg.setReplyByDate(new Date(System.currentTimeMillis() + 30000));

    AMSAgentDescription[] agents = null;
    try {
      SearchConstraints c = new SearchConstraints();
      c.setMaxResults(new Long(-1));

      agents = AMSService.search(this, new AMSAgentDescription(), c);
    } catch (Exception e) {
      System.out.println("Problem searching AMS: " + e);
      e.printStackTrace();
    }

    for (AMSAgentDescription agent : agents) {

      AID agentID = agent.getName();

      try {
        getContentManager().fillContent(aclmsg, new Action(agentID, apr));
      } catch (Exception e) {
        e.printStackTrace();
      }

      System.out.println(agentID.getLocalName());

      if (agentID.getLocalName().compareTo("TURBINE") != 0) continue;

      aclmsg.clearAllReceiver();
      aclmsg.addReceiver(agentID);

      System.out.println("Sending to " + agentID);

      addBehaviour(new ASURequestInitiatorBehaviour(this, aclmsg));

      try {
        Thread.yield();
        Thread.sleep(5000);
      } catch (Exception e) {
        System.out.println("INTERRUPT");
      }

      ACLMessage aclmsg2 = new ACLMessage(ACLMessage.REQUEST);
      BeginPowerTransitionRequest bptr = new BeginPowerTransitionRequest();
      bptr.setAssignedPowerValid(false);

      aclmsg2.setLanguage(codec.getName());
      aclmsg2.setOntology(ontology.getName());
      aclmsg2.setProtocol(FIPANames.InteractionProtocol.FIPA_REQUEST);
      aclmsg2.setReplyByDate(new Date(System.currentTimeMillis() + 30000));

      try {
        getContentManager().fillContent(aclmsg2, new Action(agentID, bptr));
      } catch (Exception e) {
        e.printStackTrace();
      }

      aclmsg2.clearAllReceiver();
      aclmsg2.addReceiver(agentID);

      System.out.println("Sending to " + agentID);

      addBehaviour(new ASURequestInitiatorBehaviour(this, aclmsg2));
    }
  }