コード例 #1
0
    public void action() {

      ACLMessage message = null;
      while (message == null) {
        message = receive();
        block();
      }

      etat_banque = Integer.parseInt(message.getContent());
      die_mess = message.getContent();
      if (die_mess.equals("meurt")) {
        doDelete();
      } else {
        System.out.println(getLocalName() + " a reçu " + etat_banque);

        int chiffre = 0;
        for (int i = 1; i < 4; i++) {
          if (((etat_banque - i) % 4) == 0) {
            chiffre = i;
            System.out.println("sapaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaasssee");
          } else {
            chiffre = 1;
          }
        }
        System.out.println("chiffre :" + chiffre);
        if (etat_banque + chiffre <= 21) envoyerMessage("Juge", Integer.toString(chiffre));
        else {
          doDelete();
        }
      }
    }
コード例 #2
0
  public static ElementModel getModel(ACLMessage message) {

    JsonParser js = new JsonParser();
    int color = ((JsonObject) js.parse(message.getContent())).get("color").getAsInt();
    String title = ((JsonObject) js.parse(message.getContent())).get("title").getAsString();

    AID agent = message.getSender();
    int type_model = ((JsonObject) js.parse(message.getContent())).get("type").getAsInt();

    ElementModel model = null;
    String content = null;

    JsonElement content_json = ((JsonObject) js.parse(message.getContent())).get("content");
    if (content_json != null) {
      content = content_json.getAsString();
    }

    if (type_model == Constants.TYPE_ELEMENT_PICTURE) {
      byte[] image = null;
      if (content != null) {
        image = Base64.decode(content, Base64.NO_OPTIONS);
      }
      model = new PictureElementModel(color, title, agent, image);

    } else if (type_model == Constants.TYPE_ELEMENT_FILE) {
      // TODO
      model = new TextElementModel(color, title, agent, content);
    } else if (type_model == Constants.TYPE_ELEMENT_LINK) {
      model = new LinkElementModel(color, title, agent, content);
    } else if (type_model == Constants.TYPE_ELEMENT_TEXT) {
      model = new TextElementModel(color, title, agent, content);
    }

    return (ElementModel) model;
  }
コード例 #3
0
  /**
   * An agent on the FrontEnd has sent a message. Note that the NotFoundException here is referred
   * to the sender and indicates an inconsistency between the FrontEnd and the BackEnd
   */
  public void messageOut(ACLMessage msg, String sender) throws NotFoundException, IMTPException {
    // Check whether the sender exists
    AID id = new AID(sender, AID.ISLOCALNAME);

    synchronized (frontEndSynchLock) {
      AgentImage image = getAgentImage(id);
      if (image == null) {
        if (synchronizing) {
          // The image is not yet there since the front-end is synchronizing.
          // Buffer the message. It will be delivered as soon as the
          // FrontEnd synchronization process completes
          postponeAfterFrontEndSynch(msg, sender);
          return;
        } else {
          throw new NotFoundException("No image for agent " + sender + " on the BackEndContainer");
        }
      }
    }

    int size;
    if (msg.hasByteSequenceContent()) {
      size = msg.getByteSequenceContent().length;
    } else {
      size = msg.getContent() != null ? msg.getContent().length() : 0;
    }
    myLogger.log(
        Logger.INFO,
        getID()
            + " - Delivering OUT message "
            + ACLMessage.getPerformative(msg.getPerformative())
            + ", size="
            + size);
    handleSend(msg, id, false);
  }
  @Override
  public void action() {
    ACLMessage messageServeur =
        myAgent.receive(
            MessageTemplate.and(
                MessageTemplate.MatchPerformative(ACLMessage.PROPAGATE),
                MessageTemplate.MatchSender(getServerAID())));
    if (messageServeur != null) {
      System.out.println(myAgent.getLocalName() + " reçu -> " + messageServeur.getContent());
      // On déséréalise le message
      ObjectMapper omap = new ObjectMapper();
      try {
        ServerLiaisonMessage msg =
            omap.readValue(messageServeur.getContent(), ServerLiaisonMessage.class);

      } catch (IOException e1) {
        e1.printStackTrace();
      }
      // Ecriture de message
      ACLMessage message =
          createMessageToDevices(messageServeur.getContent(), messageServeur.getConversationId());
      myAgent.send(message);
      System.out.println(myAgent.getLocalName() + " envoyé -> " + message.getContent());
    }
  }
コード例 #5
0
  /**
   * Dispatch a message to an agent in the FrontEnd. If this method is called by a thread that is
   * serving a message sent by an agent in the FrontEnd too, nothing is done as the dispatch has
   * already taken place in the FrontEnd (see messageOut()).
   */
  public boolean postMessageToLocalAgent(ACLMessage msg, AID receiverID) {

    // Try first in the LADT
    boolean found = super.postMessageToLocalAgent(msg, receiverID);
    if (found) {
      return found;
    } else {
      // The receiver must be in the FrontEnd
      AgentImage image = (AgentImage) agentImages.get(receiverID);
      if (image != null) {
        if (agentImages.containsKey(msg.getSender()) && isExplicitReceiver(msg, receiverID)) {
          // The message was sent by an agent living in the FrontEnd. The
          // receiverID (living in the FrontEnd too) has already received
          // the message.
          // The second part of the condition ensures that, if the
          // message was not directly sent to the receiver (e.g. it was sent to a topic
          // or an alias), message delivery occurs normally.
          // FIXME: This does not take into account that an agent not living
          // in the FrontEnd may send a message on behalf of an agent living
          // in the FrontEnd.
          return true;
        }

        try {
          // Forward the message to the FrontEnd
          int size;
          if (msg.hasByteSequenceContent()) {
            size = msg.getByteSequenceContent().length;
          } else {
            size = msg.getContent() != null ? msg.getContent().length() : 0;
          }
          myLogger.log(
              Logger.INFO,
              getID()
                  + " - Delivering IN message "
                  + ACLMessage.getPerformative(msg.getPerformative())
                  + ", size="
                  + size);
          myFrontEnd.messageIn(msg, receiverID.getLocalName());
          handlePosted(receiverID, msg);
          return true;
        } catch (NotFoundException nfe) {
          System.out.println("WARNING: Missing agent in FrontEnd");
          return false;
        } catch (IMTPException imtpe) {
          System.out.println("WARNING: Can't deliver message to FrontEnd");
          return false;
        }
      } else {
        // Agent not found
        System.out.println("WARNING: Agent " + receiverID + " not found on BackEnd container");
        return false;
      }
    }
  }
コード例 #6
0
  public void handleError(ACLMessage msg) {

    log.debug("WSIGBehaviour.handleError");

    status = FAILURE_STATUS;
    error = msg.getContent();
  }
コード例 #7
0
  public static Integer getAgentType(ACLMessage message) {

    JsonParser js = new JsonParser();
    int type =
        ((JsonObject) js.parse(message.getContent())).get(Constants.JSON_AGENT_TYPE).getAsInt();
    return type;
  }
コード例 #8
0
            @Override
            public boolean match(ACLMessage msg) {
              switch (msg.getPerformative()) {
                case ACLMessage.INFORM:
                case ACLMessage.REQUEST:
                case ACLMessage.QUERY_IF:
                  break;
                default:
                  return false;
              }

              JsonParser js = new JsonParser();

              JsonElement json = null;
              try {
                json = js.parse(msg.getContent());
              } catch (JsonSyntaxException e) {
                return false;
              }
              int action = ((JsonObject) json).get(Constants.JSON_ACTION).getAsInt();

              switch (action) {
                case Constants.MESSAGE_ACTION_CREATE_ELEMENT:
                  return true;
                default:
                  return false;
              }
            }
コード例 #9
0
  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();
    }
  }
コード例 #10
0
    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();
      }
    }
コード例 #11
0
 protected ACLMessage prepareResponse(ACLMessage request)
     throws NotUnderstoodException, RefuseException {
   System.out.println(
       controller.getLocalName()
           + ": REQUEST received from "
           + request.getSender().getName()
           + ". Action is "
           + request.getContent());
   if (request.getContent().equalsIgnoreCase("APScontroller-params-request")) {
     // do not send agree message, reply with inform
     return null;
   } else {
     // We refuse to perform the action
     System.out.println("Agent " + controller.getLocalName() + ": Refuse");
     throw new RefuseException("check-failed");
   }
 }
コード例 #12
0
  public static Map<AID, String> getTitle(ACLMessage message) {
    Map<AID, String> e = new HashMap<AID, String>();
    JsonParser js = new JsonParser();
    String title = ((JsonObject) js.parse(message.getContent())).get("title").getAsString();

    AID agent = message.getSender();
    e.put(agent, title);
    return e;
  }
コード例 #13
0
ファイル: ResponderBehaviour.java プロジェクト: sojoe02/Agent
  public void action() {
    ACLMessage aclMessage = myAgent.receive(mt);

    if (aclMessage != null) {
      System.out.println(
          myAgent.getLocalName() + ": I receive message.\n" + aclMessage.getContent());
    } else {
      this.block();
    }
  }
コード例 #14
0
  /** returns the results of an action requested. */
  public List getResult() throws FIPAException, NotYetReady {
    if (notYetReady) throw new NotYetReady();
    if (lastMsg.getPerformative() != ACLMessage.INFORM) throw new FIPAException(lastMsg);

    Result r = AppletRequestProto.extractContent(lastMsg.getContent(), (SLCodec) c, o);
    Iterator i = r.getItems().iterator(); // this is the set of DFAgentDescription
    List l = new ArrayList();
    while (i.hasNext()) l.add(i.next());
    return l;
  }
コード例 #15
0
    public void action() {
      final ACLMessage msg = myAgent.receive(mt);
      if (msg != null) {
        log.info("Receive ChessBoard update request: " + msg.getContent());
        String[] parsedMsg = msg.getContent().split(",");
        boolean update = Boolean.valueOf(parsedMsg[0]);
        int row = Integer.valueOf(parsedMsg[1]);
        int col = Integer.valueOf(parsedMsg[2]);
        gui.update(row, col, update);

        if (update) {
          final String nextQueenToStart = "Queen" + (col + 1);
          addBehaviour(
              new WakerBehaviour(myAgent, SLEEP_TIME) {
                protected void onWake() {
                  proposeMove(nextQueenToStart);
                }
              });
        }
      }
    }
コード例 #16
0
 public void action() {
   ACLMessage msg = myAgent.receive(template);
   if (msg != null) {
     if (msg.getPerformative() == ACLMessage.INFORM) {
       myGui.notifySpoken(msg.getSender().getLocalName(), msg.getContent());
     } else {
       handleUnexpected(msg);
     }
   } else {
     block();
   }
 }
コード例 #17
0
ファイル: ConnRecvMsg.java プロジェクト: volterr/NAM
 @Override
 public void action() {
   while ((msg = myAgent.receive(mt)) != null) {
     switch (msg.getPerformative()) {
       case ACLMessage.REQUEST:
         if (msg.getProtocol().equals(Constants.REQUEST_ROUTE)) {
           AIDPair destSrcPair;
           try {
             destSrcPair = (AIDPair) msg.getContentObject();
             log.log(
                 Logger.INFO,
                 myAgent.getLocalName()
                     + "# received request for path("
                     + destSrcPair.getFirst().getLocalName()
                     + ", "
                     + destSrcPair.getSecond().getLocalName()
                     + ") from "
                     + msg.getSender().getLocalName());
             myAgent.addBehaviour(
                 new ConnSendRoute(
                     msg.getSender(), destSrcPair.getFirst(), destSrcPair.getSecond()));
           } catch (UnreadableException e) {
             log.log(Logger.SEVERE, "Read msg content Exception: ", e);
           }
         }
         break;
       case ACLMessage.INFORM:
         log.log(
             Logger.INFO,
             myAgent.getLocalName()
                 + "#"
                 + msg.getSender().getLocalName()
                 + " notified about failure");
         if (msg.getProtocol().equals(Constants.INFORM_COFFEE)) {
           AID aid = msg.getSender();
           if (msg.getContent().equals("down")) myConnector.nodeStatusChange(aid, false);
           else myConnector.nodeStatusChange(aid, true);
         }
         break;
       case ACLMessage.CONFIRM:
         log.log(
             Logger.INFO,
             myAgent.getLocalName() + "#" + msg.getSender().getLocalName() + " finished modeling");
         if (msg.getProtocol().equals(Constants.CONFIRM_FINISHMODELING)) {
           handleModMsg(msg);
         }
         break;
     }
   }
   // Блокируем поведение, пока в очереди сообщений агента
   // не появится хотя бы одно сообщение
   block();
 }
  @Override
  public void action() {

    MessageTemplate messageTemplate = MessageTemplate.MatchConversationId(CONVID_ACL_MESSAGE);
    ACLMessage messageRecu = myAgent.receive(messageTemplate);

    if (messageRecu != null) {
      // Si le problème n'est pas chargé, refuser
      if (((AgentGestionPopulation) myAgent).getMonProbleme() == null) {
        ACLMessage refuse = new ACLMessage(ACLMessage.REFUSE);
        gererMessage(refuse, messageRecu, "problem is not loaded");
      }
      // Si l'acte est de type REQUEST, analyser le message
      if (messageRecu.getPerformative() == ACLMessage.REQUEST) {
        // Si le language est correct, traiter la demande de génération
        if (messageRecu.getLanguage() != null
            && messageRecu.getLanguage().equals(LANGUAGE_ACL_MESSAGE)) {
          String content = messageRecu.getContent();
          // Si le contenu est conforme (nb d'individus), les générer
          if (content != null) {
            try {
              int nbIndividu = Integer.parseInt(content); // throw NumberFormatException

              ACLMessage agreeMessage = new ACLMessage(ACLMessage.AGREE);
              gererMessage(agreeMessage, messageRecu, "");

              ProblemeCARP p = ((AgentGestionPopulation) myAgent).getMonProbleme();
              ((AgentGestionPopulation) myAgent)
                  .getPopulationGlobale()
                  .genererIndividus(nbIndividu, p);

              ACLMessage informMessage = new ACLMessage(ACLMessage.INFORM);
              gererMessage(informMessage, messageRecu, "done");
            } catch (NumberFormatException nfException) {
              ACLMessage refuse = new ACLMessage(ACLMessage.REFUSE);
              gererMessage(refuse, messageRecu, "invalid arguments");
            }

          } else {
            ACLMessage refuse = new ACLMessage(ACLMessage.REFUSE);
            gererMessage(refuse, messageRecu, "invalid arguments");
          }
        } else {
          ACLMessage refuse = new ACLMessage(ACLMessage.REFUSE);
          gererMessage(refuse, messageRecu, "invalid ACL language");
        }
      } else {
        ACLMessage notUnderstoodMessage = new ACLMessage(ACLMessage.NOT_UNDERSTOOD);
        gererMessage(notUnderstoodMessage, messageRecu, "AGPop only serves request");
      }
    } else block();
  }
コード例 #19
0
 public void action() {
   MessageTemplate mt =
       MessageTemplate.and(
           MessageTemplate.MatchPerformative(ACLMessage.INFORM),
           MessageTemplate.MatchConversationId("map-request"));
   ACLMessage msg = myAgent.receive(mt);
   if (msg != null) { // this agent received a map after his map request
     String response = msg.getContent();
     wantsCleanMap = false;
     createUIGraph(response);
   } else {
     block();
   }
 }
コード例 #20
0
    public void action() { // listen to incomming CFP from storageAgents

      MessageTemplate mt = MessageTemplate.MatchPerformative(ACLMessage.CFP);
      ACLMessage msg = myAgent.receive(mt);

      /*System.out.println("REQUEST RECEIVED");
      System.out.println(msg);*/
      if (msg != null) { // only respond to CFP messages
        // CFP Message received. Process it
        // System.out.println("Got request");
        String requestedLocation = msg.getContent();
        ACLMessage reply = msg.createReply(); // add the sender as
        // recipient
        Integer x =
            Integer.parseInt(
                requestedLocation.substring(
                    0, requestedLocation.lastIndexOf(','))); // parse the x of
        // product
        Integer y =
            Integer.parseInt(
                requestedLocation.substring(
                    requestedLocation.lastIndexOf(',') + 1,
                    requestedLocation.length())); // parse the y of product
        Integer price = calculatePathCost(new Point(x, y));
        if (holdingItem.x == x && holdingItem.y == y) { // robot is
          // carrying the
          // requested
          // item
          price = 1;
        }
        if (price != null) {
          reply.setPerformative(ACLMessage.PROPOSE);
          reply.setContent(String.valueOf(price.intValue()));
          // System.out.println(getAID().getName() + ": My cost is " +
          // price + ". To get to location: " +x + ","+y);//debugging
          // purpose
        } else {
          reply.setPerformative(ACLMessage.REFUSE);
          reply.setContent("Pathplanning error");
        }
        myAgent.send(reply);
      } else {
        block();
      }
    }
コード例 #21
0
    public void action() {

      MessageTemplate mt =
          MessageTemplate.and(
              MessageTemplate.MatchPerformative(ACLMessage.INFORM),
              MessageTemplate.MatchConversationId("arrival-inform"));
      ACLMessage msg = myAgent.receive(mt);
      if (msg != null) { // this agent received a YES or NO after his
        // movement request
        String response = msg.getContent();
        if (response.contains("go")) {
          awaitingRelease = false;
        }
      } else {
        awaitingRelease = false;
        block();
      }
    }
コード例 #22
0
  private void selectSession() {
    this.dest = ((ClientAgent) this.myAgent).findDocumentAgent()[0].getName();
    final SelectRequest request = new SelectRequest(objectTypes.session, new Predicate[0]);
    final 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);

    ModelObject[] res = null;
    try {
      //			System.out.println("Sessions reçues :"+answer.getContent());
      res = mapper.readValue(answer.getContent(), ModelObject[].class);
    } catch (IOException e) {
      e.printStackTrace();
    }
    this.session = (Session) res[res.length - 1];
  }
コード例 #23
0
  private void selectDocument() {
    Predicate p[] = {new MobilizedIn(session)};
    final SelectRequest request = new SelectRequest(objectTypes.document, p);
    final 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);

    ModelObject[] res = null;
    try {
      //			System.out.println("Documents reçus :"+answer.getContent());
      res = mapper.readValue(answer.getContent(), ModelObject[].class);
    } catch (IOException e) {
      e.printStackTrace();
    }
    this.doc = (Document) res[0];
  }
コード例 #24
0
  @Override
  public void action() {
    MessageTemplate template =
        MessageTemplate.and(
            MessageTemplate.MatchPerformative(ACLMessage.REQUEST),
            MessageTemplate.MatchConversationId("1"));
    ACLMessage message = myAgent.receive(template);

    if (message != null) {
      try {
        RequestCellsMessage requestMessage =
            mapper.readValue(message.getContent(), RequestCellsMessage.class);
        List<Cellule> cellules =
            EnvironnementAgent.sudoku.getCellulesForRank(requestMessage.getRank());
        CellsMessage cellsMessage = new CellsMessage(cellules, requestMessage.getRank());
        StringWriter stringWriter = new StringWriter();
        try {
          mapper.writeValue(stringWriter, cellsMessage);
        } catch (Exception e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        String messageString = stringWriter.toString();
        if (messageString != null) {
          ACLMessage response = new ACLMessage(ACLMessage.INFORM);
          response.setContent(messageString);
          response.setConversationId("1");
          response.addReceiver(new AID("AgentSimulation", AID.ISLOCALNAME));
          myAgent.send(response);
        }
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

    } else {
      block();
    }
  }
コード例 #25
0
 public void action() {
   DFAgentDescription template = new DFAgentDescription();
   ServiceDescription sd = new ServiceDescription();
   sd.setType(swapEntry.getSubject().getName());
   template.addServices(sd);
   try {
     DFAgentDescription[] result = DFService.search(myAgent, template);
     if (result.length != 0) {
       enlistorAgent = result[0].getName();
       msg = new ACLMessage(ACLMessage.REQUEST);
       msg.setContentObject(swapEntry);
       msg.addReceiver(enlistorAgent);
       send(msg);
       reply = blockingReceive(MessageTemplate.MatchPerformative(ACLMessage.INFORM));
       if (reply != null && reply.getContent().equals(MSG_CONFIRM)) {
         logger.info(getLocalName() + " swap request added.");
       }
     }
   } catch (Exception fe) {
     fe.printStackTrace();
   }
 }
コード例 #26
0
ファイル: DAOAgentPool.java プロジェクト: srvarey/postion
  public static Serializable callMethod(
      Class clazz, String methodName, List<Serializable> arguments) {
    GaiaDAOAgent daoagent = getAvailableDAOAgent();
    /** thread */
    DAOCallerAgent.DAOCallBehaviour request =
        new DAOCallerAgent.DAOCallBehaviour(
            daoagent.getAID(), clazz.getName(), methodName, arguments, false, false);

    daoCallerAgent.addBehaviour(new ThreadedBehaviourFactory().wrap(request));
    ACLMessage msg = daoCallerAgent.blockingReceive();

    try {
      if (msg.getConversationId().equals(DAO_QUERY_REPLY)) {
        return msg.getContentObject();
      }
    } catch (Exception e) {
      logger.error(StringUtils.formatErrorMessage(e));
      logger.error(msg.getConversationId());
      logger.error(msg.getContent());
    }
    return null;
  }
コード例 #27
0
  //  send CFPs to the bidders
  protected Vector<ACLMessage> prepareCfps(ACLMessage cfp) {
    // look for the bidders in the DF
    DFAgentDescription[] template = searchForBidders(cfp);
    // prepare request
    Vector<ACLMessage> result = new Vector<ACLMessage>(); // prep result vector

    Good theGood = neg.getGood();
    cfp.setContent("Offer is");
    try {
      cfp.setContentObject(theGood);
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    System.out.println("Offer:" + request.getContent() + "by" + request.getSender());

    for (int i = 0; i < template.length; i++) {
      cfp.addReceiver(template[i].getName());
    }
    result.add(cfp);
    return result;
  }
コード例 #28
0
  @Override
  public void action() {

    // message templte for dutch auction
    MessageTemplate mt =
        MessageTemplate.and(
            MessageTemplate.MatchPerformative(ACLMessage.INFORM),
            MessageTemplate.MatchProtocol(FIPANames.InteractionProtocol.FIPA_DUTCH_AUCTION));

    msg = myAgent.receive(mt);

    if (msg != null) {
      if (msg.getPerformative() == ACLMessage.INFORM) {
        if (msg.getOntology().equals("AUCTION")) {
          if (msg.getContent().startsWith("AUCTION")) {
            System.out.println(myAgent.getLocalName() + ": auction has started");
            // Auction with 100 as this agents highest buying price
            int price = 40000 + rand.nextInt(15000);
            myAgent.addBehaviour(new NewAuctionBehaviour(Integer.toString(price)));
          } else myAgent.putBack(msg);
        }
      }
    }
  }
コード例 #29
0
  @Override
  public void action() {
    ACLMessage message = myAgent.receive(template);
    if (message != null) {
      ACLMessage answer = null;

      JsonParser js = new JsonParser();
      int action =
          ((JsonObject) js.parse(message.getContent())).get(Constants.JSON_ACTION).getAsInt();

      // si MESSAGE_ACTION_GET_CONTENT renvoie le contenu en envoyant au client un message
      // MESSAGE_RECEIVE_ELEMENT_TITLE

      switch (action) {
        case Constants.MESSAGE_ACTION_CREATE_ELEMENT:
          AgentController newElement;
          try {
            AgentContainer controller = myAgent.getContainerController();
            Date dNow = new Date();
            SimpleDateFormat ft = new SimpleDateFormat("hh:mm:ss");

            newElement =
                controller.createNewAgent(
                    "Nouvel element : " + ft.format(dNow),
                    "com.workhub.jade.agent.ElementAgent",
                    new Object[] {MessageFactory.getAgentType(message), message.getSender()});
            newElement.start();
          } catch (StaleProxyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
      }
    } else {
      block();
    }
  }
コード例 #30
0
  @Override
  public void action() {
    // On attend un message précis INFORM d'un provider préçis
    ACLMessage msg = myAgent.receive(mt);
    // if (countAttente < 3) {
    if (msg != null) {
      // On vérifie l'existence ce provider dans le DF
      String content = msg.getContent();
      double price = 0;
      double betterPrice = 0;
      if (content != null) {
        try {
          price = Double.valueOf(content);
          betterPrice = myAgent.getBestPrice();
          // On regarde si le prix que nous a proposé ce founisseur est plus avantageux
          if (price < betterPrice) {
            myAgent.setBestProvider(msg.getSender());
            myAgent.setBestPrice(price);
          }
        } catch (NumberFormatException e) {
          System.err.println("Prix reçu au mauvais format!");
        } catch (Exception e) {
          System.err.println("Problème pour la transformation de string en double");
        }

        // Ce fournisseur nous a répondu, le Behaviour est donc fini
      }
      finished = true;
    } else {
      block(VendeurAgent.TEMPS_POUR_REPONDRE);
    }
    //        } else {
    //            finished = true;
    //        }
    //        countAttente++;
  }