Beispiel #1
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;
 }
    private ACLMessage handleProfilerRequest(ACLMessage request) {
      AID profiler = request.getSender();
      ArrayList<Integer> requestedIDs;
      try {
        requestedIDs = (ArrayList<Integer>) request.getContentObject();
        // System.out.println(getName() + ": Received request from Profiler. He requested " +
        // requestedIDs.size() + " IDs.");
      } catch (UnreadableException e) {
        System.err.println(
            myAgent.getAID().getName()
                + ": Couldn't get IDs to look up. Will respond with an empty list...");
        requestedIDs = new ArrayList<>();
      }
      String conversationID = request.getConversationId();
      ArrayList<Artifact> relatedArtifacts = new ArrayList<>();

      for (Integer id : requestedIDs)
        for (Artifact a : artifacts) if (a.getId() == id) relatedArtifacts.add(a);

      ACLMessage response = new ACLMessage(ACLMessage.INFORM);
      response.addReceiver(profiler);
      response.setConversationId(conversationID);
      response.setOntology("tour-info");
      try {
        response.setContentObject(relatedArtifacts);
      } catch (IOException e) {
        System.err.println(
            myAgent.getAID().getName()
                + ": Couldn't serialize the Artifact list... Will cause problems with other agents.");
      }
      return response;
      // System.out.println(myAgent.getAID().getName() + ":Response message sent to Profiler with "
      // + relatedArtifacts.size() + " artifacts.");
    }
    public void action() {
      attempts++;

      logger.info(getLocalName() + ":" + "Attempting to cancel " + subjectName + ":" + sectionName);
      DFAgentDescription template = new DFAgentDescription();
      ServiceDescription sd = new ServiceDescription();
      sd.setType(subjectName);
      template.addServices(sd);
      try {
        DFAgentDescription[] result = DFService.search(myAgent, template);
        if (result.length != 0) {
          logger.info(getLocalName() + ": " + result[0].getName().getLocalName() + " agent found.");
          enlistorAgent = result[0].getName();
          msg = new ACLMessage(ACLMessage.REQUEST);
          msg.setContentObject(new EnlistorMessage(ACTION_CANCEL_SLOT, sectAss));
          msg.addReceiver(enlistorAgent);
          send(msg);
          reply = blockingReceive(MessageTemplate.MatchPerformative(ACLMessage.INFORM));
          if (reply != null && reply.getContent().equals(MSG_CONFIRM)) {
            schedule.removeSectionAssignment(subjectName);
          }
        }
      } catch (Exception fe) {
        fe.printStackTrace();
      }
    }
Beispiel #4
0
  public void requestSwapAppointments() {
    String conversationId = "request-swap";

    if (patientAgent.highPriorityAppointmentOwner != null) {

      System.out.println(
          patientAgent.getName()
              + " proposing to swap slot "
              + (patientAgent.allocatedAppointment + 1)
              + " with "
              + (patientAgent.swapSlot + 1));
      ACLMessage request = new ACLMessage(ACLMessage.PROPOSE);
      request.addReceiver(patientAgent.highPriorityAppointmentOwner);
      try {
        request.setContentObject(
            new SwapInfo(patientAgent.allocatedAppointment, patientAgent.swapSlot));
      } catch (IOException e) {
        e.printStackTrace();
      }
      request.setSender(patientAgent.getAID());
      request.setConversationId(conversationId);
      request.setReplyWith(conversationId + " " + System.currentTimeMillis());
      patientAgent.send(request);
      reqTemplate =
          MessageTemplate.and(
              MessageTemplate.MatchConversationId(conversationId),
              MessageTemplate.MatchInReplyTo(request.getReplyWith()));
      state = 1;
    }
  }
Beispiel #5
0
  private void proposeMove(String queenName) {
    DFAgentDescription template = new DFAgentDescription();
    ServiceDescription sd = new ServiceDescription();
    sd.setType("Publish-queen");
    template.addServices(sd);

    try {
      DFAgentDescription[] result = DFService.search(this, template);
      if (result != null && result.length > 0) {
        ACLMessage msg = new ACLMessage(ACLMessage.PROPOSE);
        for (int i = 0; i < result.length; ++i) {
          if (result[i].getName().getLocalName().equals(queenName)) {
            msg.addReceiver(result[i].getName());
          }
        }

        msg.setContent(ChessCommand.MOVE);
        send(msg);

      } else {
        log.severe("Queen is not registred or not available");
      }

    } catch (FIPAException e) {
      log.severe(e.getMessage());
    }
  }
  @Override
  public void action() {
    ACLMessage message = new ACLMessage(ACLMessage.REQUEST);
    System.out.println(" ----- SendFileToServerBehaviour started ----- ");

    try {
      jO = new JSONObject();
      jO.put("action", "ADD");
      jO.put("login", LoginActivity.USER_LOGIN);
      jO.put("project_name", ProjectsFragment.PROJECT_NAME);
      jO.put("project_id", ProjectsFragment.PROJECT_NAME);
      jO.put("session_id", SessionsFragment.SESSION_NAME);
      jO.put("file_name", AddFileActivity.FILE_NAME);
      jO.put("file", AddFileActivity.FILE_TO_STRING);

      message.setContent(jO.toString());
      System.out.println(" jO messageToserver= " + jO);

    } catch (JSONException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    message.addReceiver(clientAgent.searchServer());
    myAgent.send(message);
  }
  @Override
  public void action() {
    block(15000);
    if (Biblioteca.podeTrocarDia()) {

      Biblioteca.quantidadeClientesAtendidos = 0;
      Biblioteca.quantidadeClientesInicioDia = Biblioteca.clienteIndex;

      DFAgentDescription template = new DFAgentDescription();
      ServiceDescription sd = new ServiceDescription();
      sd.setType(Cliente.TIPO_SERVICO_ACORDAR);
      sd.setName(Cliente.NOME_SERVICO_ACORDAR);
      template.addServices(sd);
      Ambiente.HOJE.add(Calendar.DATE, 1);
      System.out.println("Passou o dia, data atual: " + Ambiente.HOJE.getTime());

      Biblioteca.data.setText(new SimpleDateFormat("dd/MM/yyyy").format(Ambiente.HOJE.getTime()));
      try {

        DFAgentDescription[] result = DFService.search(myAgent, template);

        if (result != null && result.length > 0) {
          ACLMessage message = new ACLMessage(ACLMessage.REQUEST);
          message.setProtocol(FIPANames.InteractionProtocol.FIPA_REQUEST);
          message.setConversationId(ID_MENSAGEM_ACORDAR_CLIENTE);
          for (int i = 0; i < result.length; i++) {
            message.addReceiver(result[i].getName());
          }
          myAgent.addBehaviour(new IniciarAcordarCliente(myAgent, message));
        }
      } catch (FIPAException ex) {
        Logger.getLogger(Cliente.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
  }
    @Override
    protected void onTick() { // every 1000 ms
      if (awaitingRelease == false) {
        if (moveMentQueue.size() == 0) // agent has no pending movement
        {
          if (travelPoints.size() != 0) // if there are actually points
          // to visit
          {
            movementVerified = false;
            calculateNextHop();
            try {
              Thread.sleep(2);
            } catch (InterruptedException e) {
              e.printStackTrace(); // wait a small while to receive
              // a reply to the hop claim
            }
          }
        }

        if (moveMentQueue.size() > 0 && movementVerified) {
          String conversationString = "";
          String statusID = "V"; // holding item
          if (holdingItem.x == 0) // not holding item
          {
            statusID = "R";
          }
          if (claimDropdownID == true) {
            statusID = "D";
            claimDropdownID = false;
          }
          if (nextDestination.get(0) == ITEMDROPDOWN
              && moveMentQueue.get(0).x == holdingItem.x
              && moveMentQueue.get(0).y == holdingItem.y) {
            claimDropdownID = true;
          }
          conversationString += (statusID + ",");
          conversationString += (location.x + ",");
          conversationString += (location.y + ",");
          conversationString += (moveMentQueue.get(0).x + ",");
          conversationString += moveMentQueue.get(0).y;
          location = moveMentQueue.get(0);
          moveMentQueue.remove(0);
          if (location.x == travelPoints.get(0).x && location.y == travelPoints.get(0).y) {
            checkArrival();
          }
          ACLMessage mapUpd = new ACLMessage(ACLMessage.INFORM);
          mapUpd.addReceiver(guiAgents[0]); // The gui agent needs to
          // know that the robot
          // actually did a move

          mapUpd.setContent(conversationString); // x,y is for the
          // GUI agent, it
          // has to
          // visualize
          // movement
          mapUpd.setConversationId("map-update");
          myAgent.send(mapUpd);
        }
      }
    }
    protected void setup() {
      Object[] args = getArguments();
      if (args != null && args.length == 1) {
        myReceiver = new AID((String) args[0], AID.ISLOCALNAME);
      } else {
        System.out.println("Missing receiver name !!!!!");
        doDelete();
        return;
      }
      msg.addReceiver(myReceiver);
      msg.setByteSequenceContent(content);
      myTemplate = MessageTemplate.MatchSender(myReceiver);

      System.out.println(
          "RTT-Sender " + getName() + " ready: my receiver is " + myReceiver.getName());
      notifyReady();

      if (timeInterval > 0) {
        addBehaviour(
            new TickerBehaviour(this, timeInterval) {
              public void onTick() {
                job();
              }
            });
      } else {
        addBehaviour(
            new CyclicBehaviour(this) {
              public void run() {
                job();
              }
            });
      }
    }
  private void downloadDocument() {

    final DownloadRequest request = new DownloadRequest(doc);
    ACLMessage message = new ACLMessage(ACLMessage.REQUEST);
    message.addReceiver(this.dest);
    message.setContent(request.toJSON());
    this.myAgent.send(message);

    final ACLMessage answer = this.myAgent.blockingReceive();

    final ObjectMapper mapper = new ObjectMapper();
    mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

    BinaryContent res = null;
    try {
      //			System.out.println("Sessions reçues :"+answer.getContent());
      res = mapper.readValue(answer.getContent(), BinaryContent.class);
    } catch (IOException e) {
      e.printStackTrace();
    }

    final String path =
        RequestConstants.clientAgentDirectory + this.doc.getName() + this.doc.getType();
    FileOutputStream fos;
    try {
      fos = new FileOutputStream(path);
      fos.write(res.getContent());
      fos.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
 @Override
 public void action() {
   // DEBUG
   System.out.println("Seller: sending to give !");
   Seller mySeller = (Seller) super.myAgent;
   ACLMessage mess = new ACLMessage(FishMarketProtocol.Performatives.TO_GIVE);
   // Receiver
   mess.addReceiver(mySeller.getMarketAgent());
   // Set topic
   mess.addReceiver(MarketFSMBehaviourAuctionProgress.MESSAGE_TOPIC);
   // Set conversation id
   mess.setConversationId(this.myFSM.getConversationId());
   // send
   mySeller.send(mess);
   // DEBUG (break point)
   System.out.println();
 }
Beispiel #12
0
  /**
   * This method configures and send a ACLMessage to start a new remote-Container.
   *
   * @param remConf the RemoteContainerConfig
   * @param preventUsageOfAlreadyUsedComputers the boolean prevent usage of already used computers
   * @return the name of the container
   */
  private String sendMsgRemoteContainerRequest(RemoteContainerConfig inConf) {

    // --- Get the local Address of JADE ------------------------
    String myPlatformAddress = myContainer.getPlatformID();

    // --- If the remote-configuration is null configure it now -
    RemoteContainerConfig remConf = this.getRemoteContainerConfigAuto();
    if (inConf != null) {
      if (inConf.getJadeContainerName() != null) {
        String name = inConf.getJadeContainerName();
        int suf = getSuffixNo(inConf.getJadeContainerName());
        name = name + suf;
        remConf.setJadeContainerName(name);
      }
      if (inConf.getJadeHost() != null) {
        remConf.setJadeHost(inConf.getJadeHost());
      }
      if (inConf.getJadePort() != null) {
        remConf.setJadePort(inConf.getJadePort());
      }
      if (inConf.getJadeServices() != null) {
        remConf.setJadeServices(inConf.getJadeServices());
      }
    }

    // --- Define the AgentAction -------------------------------
    ClientRemoteContainerRequest req = new ClientRemoteContainerRequest();
    req.setRemoteConfig(remConf);

    Action act = new Action();
    act.setActor(myContainer.getAMS());
    act.setAction(req);

    // --- Define receiver of the Message -----------------------
    AID agentGUIAgent = new AID("server.client" + "@" + myPlatformAddress, AID.ISGUID);

    // --- Build Message ----------------------------------------
    ACLMessage msg = new ACLMessage(ACLMessage.INFORM);
    msg.setSender(myContainer.getAMS());
    msg.addReceiver(agentGUIAgent);
    msg.setLanguage(new SLCodec().getName());
    msg.setOntology(DistributionOntology.getInstance().getName());
    try {
      msg.setContentObject(act);
    } catch (IOException errCont) {
      logger.error(errCont);
    }

    // --- Send message -----------------------------------------
    myContainer.postMessageToLocalAgent(msg, agentGUIAgent);

    // --- Remind, that we're waiting for this container --------
    loadInfo.setNewContainer2Wait4(remConf.getJadeContainerName());

    // --- Return -----------------------------------------------
    return remConf.getJadeContainerName();
  }
 @Override
 public void action() {
   // DEBUG
   System.out.println("Seller: wait more bid timeout !");
   Seller mySeller = (Seller) super.myAgent;
   // Select transition
   float nextPrice = mySeller.getCurrentPrice() + mySeller.getPriceStep();
   float maxPrice = mySeller.getMaxPrice();
   float nextPriceStep = mySeller.getPriceStep() / 2f;
   float minPriceStep = mySeller.getMinPriceStep();
   boolean repBidOk = false;
   this.transition = SellerFSMBehaviourAuctionProgress.TRANSITION_TO_ANNOUNCE;
   if (nextPrice < maxPrice) {
     mySeller.increasePrice();
     // DEBUG
     System.out.println(
         "Seller: transition is set to announce, with price increased by priceStep !");
   } else if (nextPriceStep >= minPriceStep) {
     mySeller.decreasePriceStep();
     mySeller.increasePrice();
     // DEBUG
     System.out.println(
         "Seller: transition is set to announce, with price increased by priceStep/2 !");
   } else {
     repBidOk = true;
     // DEBUG
     System.out.println("Seller: setting transition to attribute !");
     this.transition = SellerFSMBehaviourAuctionProgress.TRANSITION_TO_ATTRIBUTE;
   }
   // DEBUG
   System.out.println("Seller: sending rep_bid(" + repBidOk + ") !");
   // send rep_bid
   ACLMessage reply = new ACLMessage(FishMarketProtocol.Performatives.REP_BID);
   // Receiver
   reply.addReceiver(mySeller.getMarketAgent());
   // Set topic
   reply.addReceiver(MarketFSMBehaviourAuctionProgress.MESSAGE_TOPIC);
   // Set conversation id
   reply.setConversationId(this.myFSM.getConversationId());
   // Add selected bidder AID
   reply.setContent(String.valueOf(repBidOk));
   // Send
   mySeller.send(reply);
 }
 private ACLMessage createMessageToDevices(String content, String conversationId) {
   ACLMessage message = new ACLMessage(ACLMessage.INFORM);
   for (AID destinataire : addDevicesRecivers()) {
     message.addReceiver(destinataire);
   }
   // Ajout du contenu du message.
   message.setConversationId(conversationId);
   message.setContent(content);
   return message;
 }
 @Override
 public void action() {
   ACLMessage msg = new ACLMessage(ACLMessage.INFORM);
   msg.setLanguage("myLanguage");
   msg.setContent("olá");
   msg.addReceiver(new AID("rma#localhost:1099/JADE", false));
   send(msg);
   System.out.println("Agente: " + getAID().getName() + " - Mensagem enviada");
   doDelete();
 }
Beispiel #16
0
 void enviarMensaje(String mensaje) {
   ACLMessage msg = new ACLMessage(ACLMessage.INFORM);
   for (int i = 0; i < m_AidListaMensajeros.size(); i++) {
     msg.addReceiver(m_AidListaMensajeros.elementAt(i));
   }
   msg.setProtocol(FIPANames.InteractionProtocol.FIPA_REQUEST);
   msg.setConversationId("MS");
   msg.setContent(mensaje);
   send(msg);
   System.out.println(getLocalName() + ": Ha enviado un mensaje: " + mensaje);
 }
  @Override
  public void action() {
    ACLMessage message = new ACLMessage(ACLMessage.REQUEST);
    message.setContent(writeMessage());
    message.setConversationId(conversationId);
    message.addReceiver(getSynchroAgent());
    // Envoi de message vers Sync
    myAgent.send(message);

    // Création du behaviour qui va attendre la réponse de la synchronisation
    myAgent.addBehaviour(new ServerWaitingSynchronistBehaviour(conversationId, user));
  }
 protected void nuevoMensaje(String destinatario, String contenido) {
   // Realizamos las acciones necesarias cada cierto tiempo
   // Construye mensaje de tipo INFORM
   ACLMessage msg = new ACLMessage(ACLMessage.INFORM);
   // agrega contenido
   // String contenido = generaCoordenadas();
   msg.setContent(contenido);
   // agrega la direccion del destinatario
   msg.addReceiver(new AID(destinatario, AID.ISLOCALNAME));
   // envia mensaje
   myAgent.send(msg);
 }
Beispiel #19
0
 private void informHospital(AID swapPatientAgentAID, int currentSlot, int swapSlot)
     throws IOException {
   String conversationId = "inform-swap-to-hospital";
   ACLMessage request = new ACLMessage(ACLMessage.INFORM);
   request.addReceiver(patientAgent.allocationAgent);
   request.setSender(patientAgent.getAID());
   request.setContentObject(new SwapInfoForHospital(currentSlot, swapSlot, swapPatientAgentAID));
   request.setConversationId(conversationId);
   request.setReplyWith(conversationId + " " + System.currentTimeMillis());
   System.out.println(patientAgent.getAID().getName() + " sending confirmation to hospital");
   patientAgent.send(request);
 }
Beispiel #20
0
    public void action() { // request the map from the GuiAgent
      updateGuiAgents();
      // System.out.println("I did a one shot map request");//debugging
      // purpose
      ACLMessage mapReq = new ACLMessage(ACLMessage.QUERY_IF);

      mapReq.addReceiver(guiAgents[0]);
      mapReq.setContent("Give me map");
      mapReq.setConversationId("map-request");
      myAgent.send(mapReq);

      ACLMessage mapUpd = new ACLMessage(ACLMessage.INFORM);
      mapUpd.addReceiver(guiAgents[0]); // The gui agent needs to know
      // where the agent is
      // initialized
      mapUpd.setContent("R,26,1" + "," + location.x + "," + location.y); // put the agent on
      // the map
      mapUpd.setConversationId("map-update");
      myAgent.send(mapUpd);
      done();
    }
 @Override
 public void action() {
   // DEBUG
   System.out.println("Seller: sending auction over !");
   Seller mySeller = (Seller) super.myAgent;
   ACLMessage mess = new ACLMessage(FishMarketProtocol.Performatives.AUCTION_OVER);
   // Receiver
   mess.addReceiver(mySeller.getMarketAgent());
   // Set topic
   mess.addReceiver(MarketFSMBehaviourAuctionProgress.MESSAGE_TOPIC);
   // Set conversation id
   mess.setConversationId(this.myFSM.getConversationId());
   // Send
   mySeller.send(mess);
   mySeller.notifyAuctionOver();
   // Remove running auction
   mySeller.removeBehaviour(this.myFSM);
   // Add create auction
   mySeller.reset();
   mySeller.addBehaviour(new SellerFSMBehaviourAuctionCreation(mySeller));
 }
 public void onStart() {
   // Subscribe as a chat participant to the ChatManager agent
   ACLMessage subscription = new ACLMessage(ACLMessage.SUBSCRIBE);
   subscription.setLanguage(codec.getName());
   subscription.setOntology(onto.getName());
   String convId = "C-" + myAgent.getLocalName();
   subscription.setConversationId(convId);
   subscription.addReceiver(new AID(CHAT_MANAGER_NAME, AID.ISLOCALNAME));
   myAgent.send(subscription);
   // Initialize the template used to receive notifications
   // from the ChatManagerAgent
   template = MessageTemplate.MatchConversationId(convId);
 }
 @Override
 public void action() {
   // DEBUG
   System.out.println("Seller: sending to cancel !");
   Seller mySeller = (Seller) super.myAgent;
   // Notify auction cancelled
   ACLMessage cancelMess = new ACLMessage(FishMarketProtocol.Performatives.TO_CANCEL);
   // Receiver
   cancelMess.addReceiver(mySeller.getMarketAgent());
   // Set topic
   cancelMess.addReceiver(MarketFSMBehaviourAuctionProgress.MESSAGE_TOPIC);
   // Set conversation id
   cancelMess.setConversationId(this.myFSM.getConversationId());
   // send
   mySeller.send(cancelMess);
   mySeller.notifyAuctionCancelled();
   // Remove running auction
   mySeller.removeBehaviour(this.myFSM);
   // Add create auction
   mySeller.reset();
   mySeller.addBehaviour(new SellerFSMBehaviourAuctionCreation(mySeller));
 }
  private void enviaSolicitacaoProduto(AID name, SolicitacaoPedido solicitacaoPedido)
      throws IOException {
    ACLMessage message = new ACLMessage();
    message.setPerformative(ACLMessage.AGREE);
    message.setOntology(TipoMensagem.SOLICITAR_PEDIDO_FORNECEDOR);
    message.addReceiver(name);

    List<ProdutoEmEstoque> produtos = new ArrayList<ProdutoEmEstoque>();
    produtos.add((new ProdutoEmEstoque(solicitacaoPedido.produto, solicitacaoPedido.quantidade)));
    Pedido pedido = new Pedido(this.getAID(), produtos);
    message.setContentObject(pedido);
    this.send(message);
    solicitacoes.add(solicitacaoPedido);
  }
Beispiel #25
0
  // generates and sends messages
  @Override
  void generate() {
    if (rand.nextDouble() < sprob) {
      try {
        int i = rand.nextInt(myUser.getReceivers().size());
        ACLMessage msgL3 = new ACLMessage(ACLMessage.INFORM);
        msgL3.setContentObject(new Integer(1));
        msgL3.addReceiver(myUser.getReceivers().get(i));
        msgL3.setSender(myUser.getAID());

        ACLMessage msgL2 = new ACLMessage(ACLMessage.INFORM);
        msgL2.setContentObject(msgL3);
        msgL2.setConversationId(Constants.NULL_CID);
        msgL2.addReceiver(myUser.getGateway());
        msgL2.setProtocol(Constants.INFORM_MESSAGE);

        log.log(
            Logger.INFO,
            myUser.getLocalName()
                + "# sended message to "
                + myUser.getReceivers().get(i).getLocalName());
        myUser.send(msgL2);
      } catch (IOException e) {
        log.log(Logger.SEVERE, "problems with output stream exception: ", e);
      } catch (IllegalArgumentException e) {
        log.log(
            Logger.WARNING,
            "User "
                + myUser.getLocalName()
                + " must have at least one destination user to generate traffic",
            e);
        block();
      } catch (Exception e) {
        log.log(Logger.SEVERE, "Exception", e);
      }
    }
  }
    @Override
    public void action() {
      //			System.out.println(getName() + ": state=Handle_CFP");
      informed = false;
      MessageTemplate template_cfp = MessageTemplate.MatchPerformative(ACLMessage.CFP);
      MessageTemplate template_nobids = MessageTemplate.MatchContent("no-bids");
      ACLMessage cfp = receive(template_cfp);
      ACLMessage nobids = receive(template_nobids);
      if (cfp != null && cfp.getConversationId().equals(convID)) { // CFP received
        try {
          receivedItem = (Artifact) cfp.getContentObject();
          // System.out.println(getName() + ": Received CFP - " + receivedItem.getName());
          ACLMessage proposal = new ACLMessage(ACLMessage.PROPOSE);
          proposal.addReceiver(marketAgent);
          proposal.setConversationId(convID);

          if (acceptOffer(receivedItem)) proposal.setContent("yes");
          else proposal.setContent("no");
          send(proposal);
          // System.out.println(getName() + ": Proposal sent to Auctioneer. Proposal= " +
          // proposal.getContent());
        } catch (UnreadableException e) {
          ACLMessage notUnderstood = new ACLMessage(ACLMessage.NOT_UNDERSTOOD);
          notUnderstood.addReceiver(marketAgent);
          notUnderstood.setConversationId(convID);
          send(notUnderstood);
        }

        informed = true;
        status = CFP_RECEIVED;
      } else if (nobids != null && nobids.getConversationId().equals(convID)) {
        // System.out.println(getName() + ": No-bids received...");
        informed = true;
        status = NO_BIDS;
      } else block();
    }
  public void action() {
    buySideOrders.addAll(MarketAgent.buySideQueue);
    Collections.sort(buySideOrders);
    sellSideOrders.addAll(MarketAgent.sellSideQueue);
    Collections.sort(sellSideOrders);

    System.out.println(myAgent.getLocalName() + " LocalBuyOrders: " + buySideOrders.size());
    System.out.println(myAgent.getLocalName() + " LocalSellOrders: " + sellSideOrders.size());

    ACLMessage tradingRequestMsg = new ACLMessage(ACLMessage.REQUEST);
    tradingRequestMsg.setConversationId("TradingRequest");
    tradingRequestMsg.setContent("ReadyToStart");
    tradingRequestMsg.addReceiver(MarketAgent.marketAID);
    myAgent.send(tradingRequestMsg);
  }
 @Override
 public void action() {
   Seller mySeller = (Seller) super.myAgent;
   mySeller.notifyAuctionStarted();
   this.myFSM.resetBidCount();
   this.myFSM.resetWaitCycleCount();
   // DEBUG
   System.out.println("Seller: sending to_announce(" + mySeller.getCurrentPrice() + ") !");
   ACLMessage mess = new ACLMessage(FishMarketProtocol.Performatives.TO_ANNOUNCE);
   // Receiver
   mess.addReceiver(mySeller.getMarketAgent());
   // Set topic
   mess.addReceiver(MarketFSMBehaviourAuctionProgress.MESSAGE_TOPIC);
   // Set conversation id
   mess.setConversationId(this.myFSM.getConversationId());
   // Add price
   mess.setContent(String.valueOf(mySeller.getCurrentPrice()));
   // Send
   mySeller.send(mess);
   // Update GUI
   mySeller.notifyNewAnnounce();
   // DEBUG
   System.out.println("Seller: notifying GUI !");
 }
Beispiel #29
0
    public void action() { // request the map from the GuiAgent
      // updateGuiAgents();
      // System.out.println("I did a one shot map request");//debugging
      // purpose
      ACLMessage mapReq = new ACLMessage(ACLMessage.QUERY_IF);

      mapReq.addReceiver(guiAgents[0]);
      if (wantsCleanMap) {
        mapReq.setContent("Give me map, clean");
      } else {
        mapReq.setContent("Give me map");
      }
      mapReq.setConversationId("map-request");
      myAgent.send(mapReq);

      done();
    }
Beispiel #30
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();
    }
  }