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(); } } }
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(); } }
protected void handleMessage(ACLMessage msg) { try { receivedContentElement = myAgent.getContentManager().extractContent(msg); Object keyCel = extractKeyContentElement(receivedContentElement); if (myLogger.isLoggable(Logger.FINE)) { myLogger.log( Logger.FINE, "Agent " + myAgent.getName() + " - Serving " + keyCel.getClass().getName() + " " + ACLMessage.getPerformative(msg.getPerformative())); } Method m = findServerMethod(keyCel, msg.getPerformative()); if (m != null) { try { m.invoke(serverDelegate, new Object[] {keyCel, msg}); } catch (InvocationTargetException ite) { handleServingFailure(ite.getCause(), keyCel, msg); } catch (Exception e) { // Since we only use public methods with proper arguments this can only happen if the // serverDelegate class is not accessible handleServingFailure(e, keyCel, msg); } } else { handleUnsupported(keyCel, msg); } } catch (ContentException ce) { handleNotUnderstood(ce, msg); } }
@Override protected ACLMessage handleAcceptProposal(ACLMessage cfp, ACLMessage propose, ACLMessage accept) { // TODO Handle the accept Cfp content = null; try { content = (Cfp) accept.getContentObject(); } catch (UnreadableException e) { // TODO Auto-generated catch block e.printStackTrace(); } // System.out.println(myAgent.getLocalName() + ": proposta aceite:" + // propose.getConversationId() + " content = " + content.getOrigin().getLocalName() + " " + // content.getDestination().getLocalName() + " " + content.getAgv().getLocalName()); ACLMessage reply = accept.createReply(); reply.setPerformative(ACLMessage.INFORM); if (myAgent.getClass() == AGV.class) { AGV a = (AGV) myAgent; AgvTransport t = new AgvTransport((AGV) myAgent, content); a.setTransportBehaviour(t); a.addBehaviour(new AgvTransport(a, content)); } return reply; }
@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; } }
protected void handleFailure(ACLMessage failure) { if (failure.getSender().equals(myAgent.getDefaultDF())) { System.out.println("Failure delivering message"); } else { System.out.println("AutoAgent recieved FAILURE from " + failure.getSender().getName()); } }
@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); } } }
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(); } }); } }
protected ACLMessage prepareResponse(ACLMessage msg) throws NotUnderstoodException, RefuseException { boolean agreed = false; ContentElement content; Concept action = null; System.out.println("Message Received"); try { content = myAgent.getContentManager().extractContent(msg); action = ((Action) content).getAction(); if (action instanceof AssignPowerRequest) { System.out.println("Received AssignPowerRequest"); agreed = true; } else if (action instanceof BeginPowerTransitionRequest) { System.out.println("Received BeginPowerTransitionRequest"); agreed = true; } else { System.out.println("Received AnotherAction, but will not perform it"); agreed = false; } } catch (Exception e) { e.printStackTrace(); } if (agreed) { ACLMessage agree = msg.createReply(); agree.setPerformative(ACLMessage.AGREE); System.out.println("Sent AGREE"); return agree; } else { throw new RefuseException("unknown operation"); } }
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(); } }
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 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); } } }
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; }
@Override public void action() { // System.out.println(getName() + ": state=HandleResponse"); receivedResponse = false; MessageTemplate template_accepted = MessageTemplate.MatchPerformative(ACLMessage.ACCEPT_PROPOSAL); MessageTemplate template_rejected = MessageTemplate.MatchPerformative(ACLMessage.REJECT_PROPOSAL); ACLMessage acceptMessage = receive(template_accepted); ACLMessage rejectMessage = receive(template_rejected); if (acceptMessage != null && acceptMessage.getConversationId().equals(convID)) { // System.out.println(getName() + ": My proposal was accepted! Content: " + // acceptMessage.getContent()); accepted = PROPOSAL_ACCEPTED; receivedResponse = true; artifacts.add(receivedItem); money -= receivedItem.getPrice(); // subtract item's cost from bank balance System.out.print(getName() + ": ARTIFACT STOCK: "); for (int i = 0; i < artifacts.size(); i++) System.out.print( "\"" + artifacts.get(i).getName() + "\"" + ((i != artifacts.size() - 1) ? ", " : "")); System.out.print("\n\n"); } else if (rejectMessage != null && rejectMessage.getConversationId().equals(convID)) { // System.out.println(getName() + ": My proposal was rejected... Content: " + // rejectMessage.getContent()); accepted = PROPOSAL_REJECTED; receivedResponse = true; } else block(); }
@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); }
private void handleAuctionStart(ACLMessage msg) { try { if (msg.getContentObject() != null && msg.getContentObject() instanceof Auction) { final Auction auction = (Auction) msg.getContentObject(); knownAuctions.add(auction); myAgent.addBehaviour( new OneShotBehaviour() { @Override public void action() { participatingAuctions.add(auction); Random random = new Random(); double maxFactor = ((double) (random.nextInt(60) + 30)) / 100; int maxPrice = (int) ((float) auction.getCurrentPrice() * maxFactor); int strategy = 0; int prefPrice = (int) ((float) 0.7 * maxPrice); BidSettings bs = new BidSettings(maxPrice, prefPrice, strategy); auctionSettings.put(auction.getArtifact().getId(), bs); } }); } else { block(); } } catch (UnreadableException ex) { block(); } }
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; }
public void action() { SSResponder parent = (SSResponder) getParent(); ACLMessage received = (ACLMessage) getDataStore().get(parent.RECEIVED_KEY); if (received != null && parent.checkInSequence(received)) { ret = received.getPerformative(); } else { ret = OUT_OF_SEQUENCE_EXIT_CODE; } }
/** 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; }
@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(); }
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; }
protected ACLMessage prepareResultNotification(ACLMessage request, ACLMessage response) { if (request.getOntology().equals("request-ids")) return handleTourGuideRequest(request); else if (request.getOntology().equals("get-item-information")) return handleProfilerRequest(request); else { ACLMessage informDone = request.createReply(); informDone.setPerformative(ACLMessage.NOT_UNDERSTOOD); return informDone; } }
@Override public boolean match(ACLMessage msg) { String ontology = msg.getOntology(); return ontology.equalsIgnoreCase(Ontologies.AUCTION_START) || ontology.equalsIgnoreCase(Ontologies.CALL_FOR_PROPOSALS) || ontology.equalsIgnoreCase(Ontologies.AUCTION_NO_BIDS) || ontology.equalsIgnoreCase(Ontologies.AUCTION_WON) || msg.getPerformative() == ACLMessage.ACCEPT_PROPOSAL || msg.getPerformative() == ACLMessage.REJECT_PROPOSAL; }
@Override public int onEnd() { // send to the seller. request was firstly sent by him ACLMessage reply = request.createReply(); reply.setContent("the winner is:"); reply.setPerformative(ACLMessage.INFORM); // depending if it is failure or ... myAgent.send(reply); return 0; }
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(); } }
private void handleReject(ACLMessage msg) { try { if (msg.getContentObject() != null && msg.getContentObject() instanceof Auction) { final Auction auction = (Auction) msg.getContentObject(); } else { block(); } } catch (UnreadableException ex) { block(); } }
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); }
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); }
@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)); }
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(); } }