Пример #1
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());
    }
  }
Пример #2
0
  /**
   * Permet de trouver tous les agents en fonction d'un service
   *
   * @param service
   * @return tableau d'adresses d'agents
   */
  protected AID[] findAgentsFromService(String service) {
    DFAgentDescription dfd = new DFAgentDescription();
    ServiceDescription sd = new ServiceDescription();
    sd.setType(service);
    dfd.addServices(sd);

    SearchConstraints ALL = new SearchConstraints();
    ALL.setMaxResults(new Long(-1));

    AID[] agents = null;

    try {
      DFAgentDescription[] result = DFService.search(this, dfd, ALL);
      agents = new AID[result.length];

      for (int i = 0; i < result.length; i++) {
        agents[i] = result[i].getName();
      }

    } catch (FIPAException fe) {
      fe.printStackTrace();
    }

    return agents;
  }
Пример #3
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();
      }
    }
  @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);
      }
    }
  }
Пример #5
0
  /** entry point of agent */
  protected void setup() {
    claimDropdownID = false;
    holdingItem = new Point(0, 0);
    // nextDestination.add(IDLE);
    movementVerified = false;
    awaitingRelease = false;
    // uiMap = new Map();
    updateGuiAgents(); // Robot agent wont start without an active GuiAgent
    if (guiAgents.length == 0) {
      /*System.out.println("No gui agent found, robot agent is terminating");*/
      doDelete();
    }

    // RobotAgent wont start without coordination arguments (looks like: 1,1
    // ) on startup
    Object[] args = getArguments();
    if (args != null && args.length > 0) {
      location = new Point(Integer.parseInt((String) args[0]), Integer.parseInt((String) args[1]));
      /*System.out.println(getAID().getName() + " is positioned at "
      + location.x + "," + location.y);*/
    } else {
      // Make the agent terminate
      /*System.out.println("No position defined, closing down");*/
      doDelete();
    }

    //		System.out.println("Hallo! Robot-agent " + getAID().getName()
    //				+ " is ready.");

    // register at yellow pages serivce
    DFAgentDescription dfd = new DFAgentDescription();
    dfd.setName(getAID());
    ServiceDescription sd = new ServiceDescription();
    sd.setType("Warehouse-RobotAgent");
    sd.setName("Warehouse-RobotAutomation");
    dfd.addServices(sd);
    try {
      DFService.register(this, dfd);

    } catch (FIPAException e) {
      //			System.out.println("catch");
      e.printStackTrace();
    }

    addBehaviour(new OfferRequestsServer()); // bid on current requests
    addBehaviour(new AcceptRequestServer()); // accept an incomming request
    addBehaviour(new MapReceiver()); // awaits a map message from guiAgent
    addBehaviour(new MapRequest()); // one shot behaviour to load the map
    addBehaviour(new MovementBehaviour(this, 500)); // every second the
    // robot is allowed to
    // move a spot
    addBehaviour(new HopReply()); // Behaviour which awaits incomming
    // accept/decline after a hop claim
    // request
    addBehaviour(new ArrivalReply()); // Behaviour which awaits incomming go
    // after arriving at a storage agent

    this.calculateNextHopSetup();
  }
Пример #6
0
 /** Subscribing to the first finding service */
 protected void subscribe() {
   ServiceDescription sd = new ServiceDescription();
   sd.setType("Building");
   sd.setName("Building");
   DFAgentDescription template = new DFAgentDescription();
   template.addServices(sd);
   addBehaviour(new NRJStationRegisterBehaviour(template, this, 1000));
 }
 private AID getSynchroAgent() {
   DFAgentDescription template = new DFAgentDescription();
   ServiceDescription sd = new ServiceDescription();
   sd.setType("Synchro");
   template.addServices(sd);
   try {
     DFAgentDescription[] result = DFService.search(myAgent, template);
     return result[0].getName();
   } catch (FIPAException fe) {
     fe.printStackTrace();
   }
   return null;
 }
Пример #8
0
 private void register() {
   DFAgentDescription dfd = new DFAgentDescription();
   dfd.setName(getAID());
   ServiceDescription sd = new ServiceDescription();
   sd.setType("Publish-chessboard");
   sd.setName("Chessboard");
   dfd.addServices(sd);
   try {
     DFService.register(this, dfd);
   } catch (FIPAException e) {
     log.severe(e.getMessage());
   }
 }
  private void publishServices() {
    /** ************************************************************** */
    /** ************ Publish the two services to DF **************** */
    /** ************************************************************** */
    ServiceDescription artifactInformation = new ServiceDescription();
    artifactInformation.setType("artifact-lookup");
    artifactInformation.setName("get-artifact-info");
    artifactInformation.addOntologies("get-item-information");
    Property args =
        new Property("args", "Send a Profile and use the ontology: get-item-information");
    artifactInformation.addProperties(args);

    ServiceDescription artifactSearch = new ServiceDescription();
    artifactSearch.setType("artifact-search");
    artifactSearch.setName("search-for-artifacts");
    artifactSearch.addOntologies("request-ids");
    args =
        new Property("args", "Send an ArrayList<Integer> of IDs and use the ontology: request-ids");
    artifactSearch.addProperties(args);

    ServiceDescription buyingArtifacts = new ServiceDescription();
    buyingArtifacts.setName("buying-artifacts");
    buyingArtifacts.setType("buying-artifacts");

    DFAgentDescription dfd = new DFAgentDescription();
    dfd.setName(getAID());
    dfd.addServices(artifactInformation);
    dfd.addServices(artifactSearch);
    dfd.addServices(buyingArtifacts);
    try {
      DFService.register(this, dfd);
      // System.out.println(getName() + ": Successfully registered services.");
    } catch (FIPAException e) {
      e.printStackTrace();
    }
    /** ************************************************************* */
  }
 /** Registers a WSIG into a DF */
 private void registerIntoDF() {
   DFAgentDescription dfad = new DFAgentDescription();
   dfad.setName(this.getAID());
   dfad.addLanguages(FIPANames.ContentLanguage.FIPA_SL);
   dfad.addProtocols(FIPANames.InteractionProtocol.FIPA_REQUEST);
   ServiceDescription sd = new ServiceDescription();
   sd.setType(AGENT_TYPE);
   sd.setName(getLocalName());
   dfad.addServices(sd);
   try {
     DFService.register(this, dfad);
   } catch (Exception e) {
     log.error("Agent " + getLocalName() + " - Error during DF registration", e);
   }
 }
  /**
   * Overrides the Behaviour.action() method. This method is executed by the agent thread. It
   * basically defines two sub behaviours, which are in charge of periodically updating the DF and
   * receiving DF notifications.
   */
  public void action() {
    try {
      // first thing to do is to register on the df and save current location if any
      DFAgentDescription myDescription = new DFAgentDescription();
      // fill a msn service description
      ServiceDescription msnServiceDescription = new ServiceDescription();
      msnServiceDescription.setName(MsnAgent.msnDescName);
      msnServiceDescription.setType(MsnAgent.msnDescType);
      myDescription.addServices(msnServiceDescription);

      ContactManager.getInstance().resetModifications();

      DFAgentDescription[] onlineContacts = DFService.search(myAgent, myDescription);

      updateContactList(onlineContacts);

      MsnEvent event = MsnEventMgr.getInstance().createEvent(MsnEvent.VIEW_REFRESH_EVENT);

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

      myLogger.log(
          Logger.FINE,
          "Thread "
              + Thread.currentThread().getId()
              + "After reading local contacts and first df query: "
              + "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);

      DFUpdaterBehaviour updater =
          new DFUpdaterBehaviour(myAgent, msnUpdateTime, myContactLocation);
      MsnAgent agent = (MsnAgent) myAgent;
      DFSubscriptionBehaviour subBh =
          new DFSubscriptionBehaviour(myAgent, agent.getSubscriptionMessage());

      myAgent.addBehaviour(updater);
      myAgent.addBehaviour(subBh);
    } catch (Exception e) {
      // TODO Auto-generated catch block
      myLogger.log(Logger.SEVERE, "Severe error: ", e);
      e.printStackTrace();
    }
  }
 private List<AID> addDevicesRecivers() {
   DFAgentDescription template = new DFAgentDescription();
   ServiceDescription sd = new ServiceDescription();
   sd.setType("Device");
   template.addServices(sd);
   List<AID> aids = new ArrayList<>();
   try {
     DFAgentDescription[] result = DFService.search(myAgent, template);
     for (DFAgentDescription agentd : result) {
       aids.add(agentd.getName());
     }
   } catch (FIPAException fe) {
     fe.printStackTrace();
   }
   return aids;
 }
Пример #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
  /**
   * Enregistrement des services
   *
   * @param type le type de son agent (TypeAgent)
   */
  protected void registerService(String type) {
    DFAgentDescription dfd = new DFAgentDescription();
    dfd.setName(this.getAID());

    ServiceDescription sd = new ServiceDescription();
    sd.setType(type);
    sd.setName(type);

    dfd.addServices(sd);

    try {
      DFService.register(this, dfd);
    } catch (FIPAException e) {
      System.err.println(
          getLocalName() + " registration with DF unsucceeded. Reason: " + e.getMessage());
      doDelete();
    }
  }
Пример #15
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();
   }
 }
  /**
   * Help method to search in the DF
   *
   * @param request
   * @return
   */
  private DFAgentDescription[] searchForBidders(ACLMessage request) {
    DFAgentDescription template = new DFAgentDescription();
    ServiceDescription sd = new ServiceDescription();
    sd.setType("IR-enterprise-agent");
    sd.setName("Bidder");
    template.addServices(sd);
    DFAgentDescription[] results = null;

    try {
      results = DFService.search(myAgent, template);

    } catch (FIPAException fe) {
      fe.printStackTrace();
      System.err.println("AuctionInit.searchForBidders() : " + fe.getMessage());
    }

    return results;
  }
Пример #17
0
 /** refreshes the list of current active StorageAgents */
 public void updateStorageAgents() {
   DFAgentDescription template = new DFAgentDescription();
   ServiceDescription sd = new ServiceDescription();
   sd.setType("Warehouse-StorageAgent");
   template.addServices(sd);
   try {
     DFAgentDescription[] result = DFService.search(this, template);
     storageAgents = new AID[result.length];
     /*System.out.println("Search performed, result amount: "
     + result.length);*/
     for (int i = 0; i < result.length; ++i) {
       storageAgents[i] = result[i].getName();
       /*System.out.println(storageAgents[i].getName());*/
     }
   } catch (FIPAException e) {
     e.printStackTrace();
     /*System.out.println("in the catch");*/
   }
 }
  private void solicitarProduto(SolicitacaoPedido solicitacaoPedido)
      throws FIPAException, IOException {
    DFAgentDescription df = new DFAgentDescription();

    ServiceDescription sd = new ServiceDescription();
    sd.setType(Servicos.Fornecedor);

    df.addServices(sd);
    DFAgentDescription[] result = DFService.search(this, df);
    int i = RandomNumber.rand(0, result.length - 1);

    AID aid = null;
    try {
      aid = result[i].getName();
    } catch (Exception ex) {
      ex.printStackTrace();
    }

    this.enviaSolicitacaoProduto(aid, solicitacaoPedido);
  }
Пример #19
0
    public void action() {

      ServiceDescription sd = new ServiceDescription();
      sd.setType(TOUR_GUIDE_AGENT);
      sd.setName(getName());
      DFAgentDescription dfd = new DFAgentDescription();
      dfd.setName(getAID());
      dfd.addServices(sd);
      try {
        DFAgentDescription[] dfds = DFService.search(myAgent, dfd);
        if (dfds.length > 0) {
          DFService.deregister(myAgent, dfd);
        }
        DFService.register(myAgent, dfd);
        System.out.println(getLocalName() + " is ready.");
      } catch (Exception ex) {
        System.out.println("Failed registering with DF! Shutting down...");
        ex.printStackTrace();
        doDelete();
      }
    }
Пример #20
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();
   }
 }
Пример #21
0
  /** Initialization */
  protected void setup() {
    // INitialize the logger
    logger = jade.util.Logger.getMyLogger(this.getClass().getName());
    logger.setLevel(Logger.SEVERE);

    logger.info("Student agent started: " + getLocalName());
    // studentNumber = (String)(String)getArguments()[0];

    /** Register the agent to the directory facilitator */
    DFAgentDescription dfd = new DFAgentDescription();
    dfd.setName(getAID());
    ServiceDescription sd = new ServiceDescription();
    sd.setType(getLocalName());
    sd.setName("Student Agent");
    dfd.addServices(sd);
    try {
      DFService.register(this, dfd);
    } catch (FIPAException fe) {
      fe.printStackTrace();
    }

    // Add main student agent behaviour
    addBehaviour(new StudentAgentBehaviour());
  }
  @Override
  public void action() {
    // Receive information update from world
    HashMap<Integer, ConnectionInfo> queryResponses = new HashMap<Integer, ConnectionInfo>();
    boolean worldMsg = false;
    TrafficLightInfoPacket packet = null;
    while (!worldMsg) {
      ACLMessage msg = myAgent.blockingReceive();
      while (msg.getPerformative() != ACLMessage.INFORM_REF) msg = myAgent.blockingReceive();
      try {
        packet = (TrafficLightInfoPacket) msg.getContentObject();
        worldMsg = true;
      } catch (Exception e) {
        try {
          ConnectionInfo conn = (ConnectionInfo) msg.getContentObject();
          queryResponses.put(conn.getRoadId(), conn);
        } catch (Exception e1) {
          e.printStackTrace();
        }
      }
    }

    // Inform all dependent agents
    ArrayList<ConnectionInfo> info = packet.getInfo();
    for (ConnectionInfo conn : info) {
      // Send register inform to world agent
      ACLMessage msg2 = new ACLMessage(ACLMessage.INFORM_REF);
      try {
        msg2.setContentObject(conn);
        msg2.addReceiver(conn.getAgentAID());
        myAgent.send(msg2);
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    // Receive responses
    boolean receiving = false;
    for (ConnectionInfo conn2 : packet.getInfo()) {
      if (queryResponses.get(conn2.getNextRoadId()) == null) {
        receiving = true;
        break;
      }
    }
    while (receiving) {
      ACLMessage msg3 = myAgent.blockingReceive();
      if (msg3.getPerformative() == ACLMessage.INFORM_REF) {
        try {
          ConnectionInfo conn = (ConnectionInfo) msg3.getContentObject();
          queryResponses.put(conn.getRoadId(), conn);
          receiving = false;
          for (ConnectionInfo conn2 : packet.getInfo()) {
            if (queryResponses.get(conn2.getNextRoadId()) == null) {
              receiving = true;
              break;
            }
          }
        } catch (UnreadableException e) {
          e.printStackTrace();
        }
      }
    }

    int verticalSend = 0;
    int horizontalSend = 0;
    HashMap<Integer, ConnectionInfo> connections = new HashMap<Integer, ConnectionInfo>();
    for (ConnectionInfo conn : packet.getInfo()) {
      int localMin = Math.min(conn.getMaxCarSpeed(), conn.getCarCount());
      connections.put(conn.getNextRoadId(), conn);
      if (conn.getRoadOrientation() == Orientation.UP
          || conn.getRoadOrientation() == Orientation.DOWN) verticalSend += localMin;
      else horizontalSend += localMin;
    }
    for (Entry<Integer, ConnectionInfo> entry : queryResponses.entrySet()) {
      Orientation ori = connections.get(entry.getValue().getRoadId()).getRoadOrientation();
      if (ori == Orientation.UP || ori == Orientation.DOWN)
        verticalSend -= (entry.getValue().getRoadCapacity() - entry.getValue().getCarCount());
      else horizontalSend -= (entry.getValue().getRoadCapacity() - entry.getValue().getCarCount());
    }
    boolean openVertical;
    if (verticalSend < horizontalSend) openVertical = true;
    else openVertical = false;

    // Build response to world
    ++cycleCount;
    boolean stateChanged = true;
    WorldUpdatePacket reply = new WorldUpdatePacket();
    for (ConnectionInfo conn : packet.getInfo()) {
      UpdateInfo uInfo = new UpdateInfo();
      uInfo.setRoadId(conn.getRoadId());
      uInfo.setNextRoadId(conn.getNextRoadId());
      if (cycleCount >= MAX_CYCLES_WITHOUT_CHANGE) {
        uInfo.setCurrentState(!conn.isCurrentState());
      } else if (cycleCount <= MIN_CYCLES_WITHOUT_CHANGE) {
        uInfo.setCurrentState(conn.isCurrentState());
      } else {
        if (openVertical
            && (conn.getRoadOrientation() == Orientation.UP
                || conn.getRoadOrientation() == Orientation.DOWN)) uInfo.setCurrentState(true);
        else if (!openVertical
            && (conn.getRoadOrientation() == Orientation.LEFT
                || conn.getRoadOrientation() == Orientation.RIGHT)) uInfo.setCurrentState(true);
        else uInfo.setCurrentState(false);
      }
      if (uInfo.isCurrentState() == conn.isCurrentState()) stateChanged = false;
      reply.addUpdateInfo(uInfo);
    }
    if (stateChanged) cycleCount = 0;

    // Reply to world
    DFAgentDescription template = new DFAgentDescription();
    ServiceDescription sd1 = new ServiceDescription();
    sd1.setType(Vocabulary.WORLD_AGENT_TYPE);
    template.addServices(sd1);
    DFAgentDescription[] result = {};
    try {
      result = DFService.search(myAgent, template);
      while (result.length <= 0) {
        result = DFService.search(myAgent, template);
      }

      // Clear message queue before responding
      while (myAgent.receive() != null) {}

      // Send register inform to world agent
      ACLMessage replyMsg = new ACLMessage(ACLMessage.INFORM_REF);
      replyMsg.setContentObject(reply);
      replyMsg.addReceiver(result[0].getName());
      myAgent.send(replyMsg);
    } catch (FIPAException | IOException e) {
      e.printStackTrace();
    }
  }
  @Override
  protected void setup() {
    super.setup();

    // Set non-standard archive scheme called “wsjar"
    System.setProperty("org.eclipse.emf.common.util.URI.archiveSchemes", "wsjar wszip jar zip");

    log.info("Agent " + getLocalName() + " - starting...");

    // Get agent arguments
    Object[] args = getArguments();
    for (int i = 0; i < args.length; i++) {
      log.info("arg[" + i + "]" + args[i]);
    }

    // Verify if config file is passed as first agent parameter
    String confFile = null;
    if (args.length >= 1 && !("".equals(args[0]))) {
      confFile = (String) args[0];
    }

    // Init agent configuration
    WSIGConfiguration.init(confFile);

    // Verify if wsdlDirectory is passed as second agent parameter
    if (args.length >= 2 && !("".equals(args[1]))) {
      String wsdlDirectory = (String) args[1];
      WSIGConfiguration.getInstance().setWsdlDirectory(wsdlDirectory);
    }

    // Verify if wsigStore is passed as third agent parameter
    if (args.length >= 3 && (args[2] instanceof WSIGStore)) {
      wsigStore = (WSIGStore) args[2];
    }
    if (wsigStore == null) {
      wsigStore = new WSIGStore();
    }

    // Create UDDIManager
    if (WSIGConfiguration.getInstance().isUddiEnable()) {
      uddiManager = new UDDIManager();
    }

    // Register ontology & language
    getContentManager().registerOntology(FIPAManagementOntology.getInstance());
    getContentManager().registerOntology(JADEManagementOntology.getInstance());
    getContentManager().registerLanguage(new SLCodec());

    // Register into a DF
    registerIntoDF();

    // Subscribe to the DF
    DFAgentDescription template = new DFAgentDescription();
    ServiceDescription sd = new ServiceDescription();
    sd.addProperties(new Property(WSIG_FLAG, "true"));
    template.addServices(sd);
    ACLMessage subscriptionMsg =
        DFService.createSubscriptionMessage(this, getDefaultDF(), template, null);
    addBehaviour(
        new SubscriptionInitiator(this, subscriptionMsg) {

          @Override
          protected void handleInform(ACLMessage inform) {
            log.debug(
                "Agent "
                    + getLocalName()
                    + " - Notification received from DF ("
                    + inform.getContent()
                    + ")");
            try {
              DFAgentDescription[] dfds = DFService.decodeNotification(inform.getContent());
              for (DFAgentDescription dfd : dfds) {
                Iterator services = dfd.getAllServices();
                if (services.hasNext()) {
                  // Registration of an agent
                  registerAgent(dfd);
                } else {
                  // Deregistration of an agent
                  deregisterAgent(dfd);
                }
              }
            } catch (Exception e) {
              log.warn(
                  "Agent " + myAgent.getLocalName() + " - Error processing DF notification", e);
            }
          }
        });

    log.info("Agent " + getLocalName() + " - started!");
  }
Пример #24
0
    /** The interesting stuff */
    public void action() {

      // increment number of attempts
      attempts++;

      // Don't enlist if adding a subject will exceed the allowed units
      if (schedule.getUnitsObtained() + 3 > (schedule.getWriteIn().getUnitsAllowed())) {
        done = true;
      }

      if (attempts > THRESH || done) {
        return;
      }

      logger.info(getLocalName() + ":" + "Attempting to enlist in " + sub.getName());
      // Search for the enlistor of the subject
      DFAgentDescription template = new DFAgentDescription();
      ServiceDescription sd = new ServiceDescription();
      sd.setType(sub.getName());
      template.addServices(sd);
      try {
        DFAgentDescription[] result = DFService.search(myAgent, template);
        // Ok we got the enlistor
        if (result.length != 0) {
          logger.info(getLocalName() + ": " + sub.getName() + " agent found.");
          enlistorAgent = result[0].getName();

          // Request for sections with available slots at this moment
          msg = new ACLMessage(ACLMessage.REQUEST);
          msg.setContentObject(new EnlistorMessage(ACTION_GET_SECTIONS_WITH_SLOTS, null));
          msg.addReceiver(enlistorAgent);
          send(msg);

          reply = blockingReceive(MessageTemplate.MatchPerformative(ACLMessage.INFORM));
          Vector sections = (Vector) reply.getContentObject();
          // Oops, all sections for this subject are full
          if (sections.size() == 0) {
            logger.info(getLocalName() + ":" + "No slots available for " + sub.getName());
          } else { // ok we have some sections
            // Randomize the sections.
            Collections.shuffle(sections);

            NoConflictConstraint constraint =
                new NoConflictConstraint(schedule.getSectionAssignments());
            // Look for the first section assignment that does not
            // conflict with the current form 5
            for (Iterator ite = sections.iterator(); ite.hasNext(); ) {
              SectionAssignment sectAss = (SectionAssignment) ite.next();
              if (!constraint.isSatisfied(sectAss.getLecture())) {
                // System.out.println(getLocalName()+":"+"Conflict in lecture of
                // "+sectAss.getLecture().getSectionName());
                continue;
              } else if ((sectAss.getLab() != null)
                  && (!constraint.isSatisfied(sectAss.getLab()))) {
                // System.out.println(getLocalName()+":"+"Conflict in lab of
                // "+sectAss.getLab().getSectionName());
                continue;
              } else {
                // Ok no conflict in lab or lecture
                // send message to enlist to this section assingment
                // msg.
                msg = new ACLMessage(ACLMessage.REQUEST);
                msg.setContentObject(new EnlistorMessage(ACTION_ENLIST, sectAss));
                msg.addReceiver(enlistorAgent);
                send(msg);
                reply = blockingReceive(MessageTemplate.MatchPerformative(ACLMessage.INFORM));
                if (reply != null && reply.getContent().equals(MSG_CONFIRM)) {
                  logger.info(
                      getLocalName()
                          + ":"
                          + "enlist to "
                          + sectAss.getSection().getSubject().getName()
                          + " "
                          + sectAss.getSection().getSectionName());
                  schedule.addSectionAssignment(sectAss);

                  done = true;
                }
                break;
              }
            }
          }
        }
      } catch (Exception fe) {
        fe.printStackTrace();
      }
    }
Пример #25
0
    public void action() {
      // TODO: Implement deliberation of for the next action
      // action=deliberate(Desire, Beliefs);

      switch (action) {
        case ACTION_SEARCH_MAIN_SCHEDULER:
          logger.info(getLocalName() + " searching for main scheduler...");
          DFAgentDescription template = new DFAgentDescription();
          ServiceDescription sd = new ServiceDescription();
          sd.setType("scheduler");
          template.addServices(sd);
          try {
            DFAgentDescription[] result = DFService.search(myAgent, template);
            if (result.length != 0) {
              logger.info(getLocalName() + ":scheduler agent found.");
              schedulerAgent = result[0].getName();
            }
          } catch (FIPAException fe) {
            fe.printStackTrace();
          }
          action = ACTION_GET_FORM5;
          break;
        case ACTION_GET_FORM5:
          try {
            logger.info(getLocalName() + " requesting for Form 5..");
            msg = new ACLMessage(ACLMessage.REQUEST);
            msg.setContent(MSG_GET_FORM5);
            msg.addReceiver(schedulerAgent);
            send(msg);
            reply = blockingReceive(MessageTemplate.MatchPerformative(ACLMessage.INFORM));
            if (reply != null) {
              schedule = (IForm5) reply.getContentObject();
              logger.info(
                  getLocalName()
                      + " schedule received, units obtained: "
                      + schedule.getUnitsObtained()
                      + ", units allowed: "
                      + schedule.getWriteIn().getUnitsAllowed());

              for (Iterator ite = schedule.getWriteIn().getSubjects().iterator(); ite.hasNext(); ) {
                ISubject sub = (ISubject) ite.next();
                SectionAssignment sectAss =
                    (SectionAssignment) schedule.getSectionAssignment(sub.getName());
                if (sectAss != null) {
                  logger.info(sub.getName() + " " + sectAss.getSection().getSectionName());
                  toCancel = sectAss;
                } else {
                  logger.info(sub.getName() + " NOT ENLISTED");
                }
              }
            }
          } catch (Exception ioe) {
            ioe.printStackTrace();
          }

          // action=ACTION_POST_SWAP_REQUEST;
          action = ACTION_ENLIST;

          break;
        case ACTION_ENLIST:
          List unassigned = schedule.getUnassigned();
          passCount++;
          if (unassigned.size() == 0) {
            action = ACTION_HAPPY;
            break;
          } else if (passCount == 1) {
            Map assignments = schedule.getSectionAssignments();
            List subjects = new ArrayList(assignments.keySet());
            if (subjects.size() > 1) {
              Collections.shuffle(subjects);
              for (int i = 0; i < (subjects.size() - 1); i++) {
                String subject = (String) subjects.get(i);
                SectionAssignment sectAss = schedule.getSectionAssignment(subject);
                myAgent.addBehaviour(new CancelSlotBehaviour(sectAss));
              }
            }
            /*
             for(Iterator ite2=assignments.keySet().iterator();ite2.hasNext();){
            	String subject=(String)ite2.next();
            	SectionAssignment sectAss=schedule.getSectionAssignment(subject);
            	myAgent.addBehaviour(new CancelSlotBehaviour(sectAss));
            }
            */
            // for each unassigned subject, attempt to enlist
            for (Iterator ite = unassigned.iterator(); ite.hasNext(); ) {
              ISubject sub = (ISubject) ite.next();
              myAgent.addBehaviour(new EnlistBehaviour(sub));
            }
          } else {
            action = ACTION_HAPPY;
          }
          break;
        case ACTION_CANCEL_SLOT:
          myAgent.addBehaviour(new CancelSlotBehaviour(toCancel));
          action = ACTION_END;
          break;
        case ACTION_POST_SWAP_REQUEST:
          SwapEntry entry = new SwapEntry(getLocalName(), toCancel.getSection(), null);
          myAgent.addBehaviour(new PostSwapRequestBehaviour(entry));
          action = ACTION_END;
          break;
        case ACTION_HAPPY:
          // At this point student agent submits his schedule
          /*
          System.out.println("HAPPY");

          for (Iterator ite=schedule.getSectionAssignments().keySet().iterator();ite.hasNext();){
          	String key=(String)ite.next();
          	SectionAssignment sectAss = schedule.getSectionAssignment(key);
          	String sectName=sectAss.getSection().getSectionName();
          	System.out.println(getLocalName()+":"+key+" "+sectName);
          }
          */
          try {
            msg = new ACLMessage(ACLMessage.REQUEST);
            msg.setContentObject(schedule);
            msg.addReceiver(schedulerAgent);
            send(msg);
          } catch (Exception e) {
            e.printStackTrace();
          }
          action = ACTION_END;
          myAgent.doDelete();
          break;
      }
    }
Пример #26
0
  /**
   * Prints a hello message and creates a sequential behavior.
   *
   * <p>First sub-behavior is a finite state machine, which tries to get tour information. It
   * contacts tour guide agent to get the tour guide. In case of failure, machine ends. If a
   * response is received, it contacts curator agent to get tour details.
   *
   * <p>Second sub-behavior prints goodbye message.
   */
  protected void setup() {
    /*
     * Hello message.
     */
    System.out.println(this.getAID().getLocalName() + ": begin operation");

    /*
     * Request sent to the tour guide. It uses TourGuideInitiator class to
     * make communication easier.
     */
    ACLMessage initTourRequest = new ACLMessage(ACLMessage.REQUEST);
    initTourRequest.setProtocol(FIPANames.InteractionProtocol.FIPA_REQUEST);
    initTourRequest.setContent("request-tour-guide");

    /*
     * The Profiler looks for the registered Tour Guides.
     */

    DFAgentDescription template = new DFAgentDescription();
    ServiceDescription sd = new ServiceDescription();
    sd.setType("tour-guide");
    template.addServices(sd);
    try {
      DFAgentDescription[] result = DFService.search(this, template);
      for (int i = 0; i < result.length; ++i) {
        initTourRequest.addReceiver(result[i].getName());
      }
    } catch (FIPAException fe) {
      fe.printStackTrace();
    }

    TourGuideInitiator initGuide = new TourGuideInitiator(this, initTourRequest);

    /*
     * Same as above, but with curator agent.
     */
    ACLMessage detailTourRequest = new ACLMessage(ACLMessage.REQUEST);
    detailTourRequest.setProtocol(FIPANames.InteractionProtocol.FIPA_REQUEST);
    detailTourRequest.setContent("request-tour-details");

    /*
     * The Profiler looks for the registered curators.
     */

    template = new DFAgentDescription();
    sd = new ServiceDescription();
    sd.setType("curator");
    template.addServices(sd);
    try {
      DFAgentDescription[] result = DFService.search(this, template);
      for (int i = 0; i < result.length; ++i) {
        detailTourRequest.addReceiver(result[i].getName());
      }
    } catch (FIPAException fe) {
      fe.printStackTrace();
    }

    CuratorInitiator initCurator = new CuratorInitiator(this, detailTourRequest);

    /*
     * State machine consists of two states:
     * 1. Communication with tour guide agent
     * 2. Communication with curator agent
     * 3. Final state
     *
     * It is constructed below.
     */
    OneShotBehaviour lastState =
        new OneShotBehaviour(this) {
          public void action() {}
        };

    FSMBehaviour fsm = new FSMBehaviour(this);
    fsm.registerFirstState(initGuide, STATE_GET_GUIDE);
    fsm.registerState(initCurator, STATE_GET_DETAILS);
    fsm.registerLastState(lastState, STATE_LAST);
    fsm.registerTransition(STATE_GET_GUIDE, STATE_GET_DETAILS, 0);
    fsm.registerTransition(STATE_GET_GUIDE, STATE_LAST, 1);
    fsm.registerDefaultTransition(STATE_GET_DETAILS, STATE_LAST);

    /*
     * Sequential behavior is constructed and added as default agent
     * behavior.
     */
    SequentialBehaviour seqBeh = new SequentialBehaviour(this);
    seqBeh.addSubBehaviour(fsm);
    seqBeh.addSubBehaviour(
        new OneShotBehaviour(this) {
          public void action() {
            System.out.println(myAgent.getAID().getLocalName() + ": closing");
          }

          public int onEnd() {
            myAgent.doDelete();
            return super.onEnd();
          }
        });
    addBehaviour(seqBeh);
  }
Пример #27
0
  /*
   * Method that register the room agent to the df and defines requests managment
   */
  protected void registerRoom() {
    // Create the agent description.
    DFAgentDescription dfd = new DFAgentDescription();
    dfd.setName(getAID());

    // Create the services description.
    ServiceDescription deviceListSD = new ServiceDescription();
    deviceListSD.setType(HomeAutomation.SERVICE_ROOM_DEVICE_LIST);
    deviceListSD.setName("JADE-room-device-list");

    ServiceDescription deviceRegistrationSD = new ServiceDescription();
    deviceRegistrationSD.setType("room-device-registration");
    deviceRegistrationSD.setType(HomeAutomation.SERVICE_ROOM_DEVICE_REGISTRATION);
    deviceRegistrationSD.setName("JADE-room-device-registration");

    // Add the services description to the agent description.
    // TODO add here other Sevice Descriptions
    dfd.addServices(deviceListSD);
    dfd.addServices(deviceRegistrationSD);

    try {
      // Register the service
      log(
          "Registering '"
              + deviceListSD.getType()
              + "' service named '"
              + deviceListSD.getName()
              + "'"
              + "to the default DF...");

      DFService.register(this, dfd);

      log("Waiting for request...");
    } catch (FIPAException fe) {
      fe.printStackTrace();
    }

    // Add the behaviour serving queries from controller agents.
    MessageTemplate template =
        AchieveREResponder.createMessageTemplate(FIPANames.InteractionProtocol.FIPA_REQUEST);
    addBehaviour(
        new AchieveREResponder(this, template) {

          @Override
          protected ACLMessage handleRequest(ACLMessage request)
              throws NotUnderstoodException, RefuseException {

            log("Handle request with content");
            return new ACLMessage(ACLMessage.AGREE);
          }

          @Override
          protected ACLMessage prepareResultNotification(ACLMessage request, ACLMessage response) {

            //						log("Prepare result notification with content: " + request.getContent());
            response.setPerformative(ACLMessage.INFORM);

            Message message = null;
            try {
              message = (Message) request.getContentObject();

            } catch (UnreadableException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }

            if (message != null) {
              if (message.getService().equals(HomeAutomation.SERVICE_ROOM_DEVICE_LIST)) {
                try {
                  // send device array
                  response.setContentObject(devices);

                } catch (IOException e) {
                  e.printStackTrace();
                }
              } else if (message
                  .getService()
                  .equals(HomeAutomation.SERVICE_ROOM_DEVICE_REGISTRATION)) {
                RegistrationMessage regMessage = (RegistrationMessage) message;

                if (regMessage.getParentId().equals(id)) {
                  AgentMessage agentDesc =
                      new AgentMessage(
                          regMessage.getAid(),
                          regMessage.getParentId(),
                          regMessage.getName(),
                          regMessage.getDescription());
                  devices.add(agentDesc);

                  log(
                      "Device "
                          + request.getSender()
                          + " successfully added to room's device list.");
                } else {
                  // send refuse..
                  log("Wrong room!!");
                  response.setPerformative(ACLMessage.REFUSE);
                }
              }
            }

            return response;
          }
        });
  }