예제 #1
1
  // Called by a starting up container.
  void beginContainer() {
    myLogger.log(
        Logger.INFO,
        "----------------------------------\n"
            + getCopyrightNotice()
            + "----------------------------------------");
    if (activeContainers == 0) {
      // Initialize and start up the timer dispatcher
      TimerDispatcher theDispatcher = TimerDispatcher.getTimerDispatcher();

      // #MIDP_EXCLUDE_BEGIN
      // Set up group and attributes for time critical threads
      criticalThreads = new ThreadGroup("JADE time-critical threads");
      criticalThreads.setMaxPriority(Thread.MAX_PRIORITY);
      Thread t = new Thread(criticalThreads, theDispatcher);
      t.setPriority(criticalThreads.getMaxPriority());
      t.setName("JADE Timer dispatcher");
      // #MIDP_EXCLUDE_END
      /*#MIDP_INCLUDE_BEGIN
      Thread t = new Thread(theDispatcher);
      #MIDP_INCLUDE_END*/
      theDispatcher.setThread(t);
      // TimerDispatcher.setTimerDispatcher(theDispatcher);
      theDispatcher.start();
    }
    ++activeContainers;
  }
    /**
     * Overrides the TickerBehaviour, defining how to update the location on the df (registration to
     * DF has already been performed during agent setup). Three properties are defined for storing
     * latitude/longitude/altitude. Only latitude and longitude are used, though.
     */
    protected void onTick() {

      try {
        MsnAgent agent = (MsnAgent) myAgent;
        DFAgentDescription description = agent.getAgentDescription();

        ServiceDescription serviceDescription =
            (ServiceDescription) description.getAllServices().next();
        serviceDescription.clearAllProperties();

        // retrieve
        ContactLocation curMyLoc = ContactManager.getInstance().getMyContactLocation();
        if (!curMyLoc.equals(myContactLocation)) {

          Property p = new Property(PROPERTY_NAME_LOCATION_LAT, new Double(curMyLoc.getLatitude()));
          serviceDescription.addProperties(p);
          p = new Property(PROPERTY_NAME_LOCATION_LONG, new Double(curMyLoc.getLongitude()));
          serviceDescription.addProperties(p);
          p = new Property(PROPERTY_NAME_LOCATION_ALT, new Double(curMyLoc.getAltitude()));
          serviceDescription.addProperties(p);
          DFService.modify(myAgent, description);
          myContactLocation = curMyLoc;
        }

      } catch (FIPAException fe) {
        myLogger.log(Logger.SEVERE, "Error in updating DF", fe);
      } catch (Exception e) {
        myLogger.log(
            Logger.SEVERE,
            "***  Uncaught Exception for agent " + myAgent.getLocalName() + "  ***",
            e);
      }
    }
예제 #3
0
  /** Handle a connection DROP_DOWN request from the FE. */
  protected void handleDropDown(Connection c, JICPPacket pkt, InetAddress addr, int port) {
    if (myLogger.isLoggable(Logger.INFO)) {
      myLogger.log(Logger.INFO, myID + ": DROP_DOWN request received.");
    }

    try {
      // If the INP connection is down or we have some postponed command
      // to flush, refuse dropping the connection
      if (inpManager.isConnected() && inpManager.isEmpty()) {
        JICPPacket rsp =
            new JICPPacket(JICPProtocol.RESPONSE_TYPE, JICPProtocol.DEFAULT_INFO, null);
        c.writePacket(rsp);

        inpManager.resetConnection();
        outManager.resetConnection();
        connectionDropped = true;
      } else {
        myLogger.log(Logger.WARNING, myID + ": DROP_DOWN request refused.");
        JICPPacket rsp = new JICPPacket(JICPProtocol.ERROR_TYPE, getReconnectInfo(), null);
        c.writePacket(rsp);
      }
    } catch (Exception e) {
      myLogger.log(Logger.WARNING, myID + ": Error writing DROP_DOWN response. " + e);
    }
  }
예제 #4
0
  /** Send a CONNECT_MEDIATOR packet to the BackEnd to check if it is reachable */
  private boolean ping(int cnt) throws ICPException {
    // Try first with the current transport address, then with the various backup addresses
    for (int i = -1; i < backEndAddresses.length; i++) {
      if (i >= 0) {
        // Set the mediator address to a new address..
        String addr = backEndAddresses[i];
        int colonPos = addr.indexOf(':');
        String host = addr.substring(0, colonPos);
        String port = addr.substring(colonPos + 1, addr.length());
        mediatorTA = new JICPAddress(host, port, myMediatorID, "");
      }

      try {
        myLogger.log(
            Logger.FINE,
            "Ping " + mediatorTA.getHost() + ":" + mediatorTA.getPort() + "(" + cnt + ")...");
        JICPPacket pkt =
            new JICPPacket(JICPProtocol.CONNECT_MEDIATOR_TYPE, JICPProtocol.DEFAULT_INFO, null);
        pkt = deliver(pkt);
        if (pkt.getType() == JICPProtocol.ERROR_TYPE) {
          // Communication OK, but there was a JICP error.
          String errorMsg = new String(pkt.getData());
          if (errorMsg.equals(JICPProtocol.NOT_FOUND_ERROR)) {
            // Back-end not found: either the max disconnection time expired server side or there
            // was a fault and restart
            // --> Try to recreate the Back-end
            myLogger.log(
                Logger.WARNING,
                "Communication OK, but Back-end no longer present. Try to recreate it");
            if (myConnectionListener != null) {
              myConnectionListener.handleConnectionEvent(ConnectionListener.BE_NOT_FOUND, null);
            }
            try {
              createBackEnd();
            } catch (IMTPException imtpe) {
              myLogger.log(Logger.WARNING, "Error re-creating the Back-end.");
              return false;
            }
          } else {
            // Generic JICP error. No need to go on
            throw new ICPException("JICP error. " + errorMsg);
          }
        }
        return true;
      } catch (IOException ioe) {
        // Ignore it, and try the next address...
        myLogger.log(Logger.FINE, "Ping KO", ioe);
      }
    }

    // No address succeeded.
    return false;
  }
예제 #5
0
 @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();
 }
예제 #6
0
  /**
   * This is periodically called by the JICPMediatorManager and is used by this NIOMediator to
   * evaluate the elapsed time without the need of a dedicated thread or timer.
   */
  public final void tick(long currentTime) {
    if (active && !connectionDropped) {
      // 1) If there is a blocking read operation in place check the
      // response timeout
      inpManager.checkResponseTime(currentTime);

      // 2) Evaluate the keep alive
      if (keepAliveTime > 0) {
        if ((currentTime - lastReceivedTime) > (keepAliveTime + RESPONSE_TIMEOUT)) {
          // Missing keep-alive.
          // The OUT connection is no longer valid
          if (outManager.isConnected()) {
            myLogger.log(Logger.WARNING, myID + ": Missing keep-alive");
            outManager.resetConnection();
          }
          // Check the INP connection. Since this method must return
          // asap, does it in a separated Thread
          if (inpManager.isConnected()) {
            Thread t =
                new Thread() {

                  public void run() {
                    try {
                      // JICPPacket pkt = new JICPPacket(JICPProtocol.KEEP_ALIVE_TYPE,
                      // JICPProtocol.DEFAULT_INFO, null);
                      // inpManager.dispatch(pkt, false);
                      inpManager.sendServerKeepAlive();
                      if (myLogger.isLoggable(Logger.CONFIG)) {
                        myLogger.log(Logger.CONFIG, myID + ": IC valid");
                      }
                    } catch (Exception e) {
                      // Just do nothing: the INP connection has been reset
                    }
                  }
                };
            t.start();
          }
        }
      }

      // 3) Evaluate the max disconnection time
      if (outManager.checkMaxDisconnectionTime(currentTime)) {
        myLogger.log(Logger.SEVERE, myID + ": Max disconnection time expired.");
        // Consider as if the FrontEnd has terminated spontaneously -->
        // Kill the above container (this will also kill this NIOBEDispatcher).
        kill();
      }
    }
  }
  /**
   * 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();
    }
  }
예제 #8
0
 // #APIDOC_EXCLUDE_BEGIN
 public static void notifyFailureToSender(ACLMessage msg, String sender, String error) {
   if (myFrontEnd != null) {
     // Send back a failure message
     try {
       Iterator it = msg.getAllReceiver();
       while (it.hasNext()) {
         AID receiver = (AID) it.next();
         // If this receiver is local, the message has certainly been delivered
         // successfully --> Do not send any FAILURE back for this receiver
         if (myFrontEnd.getLocalAgent(receiver.getLocalName()) == null) {
           ACLMessage failure = msg.createReply();
           failure.setPerformative(ACLMessage.FAILURE);
           failure.setSender(myFrontEnd.getAMS());
           failure.setLanguage(FIPANames.ContentLanguage.FIPA_SL);
           String content = "( (action " + sender;
           content = content + " (ACLMessage) ) (MTS-error " + receiver + " \"" + error + "\") )";
           failure.setContent(content);
           myFrontEnd.messageIn(failure, sender);
         }
       }
     } catch (Exception e1) {
       logger.log(Logger.SEVERE, "Error delivering FAILURE message.", e1);
     }
   }
 }
예제 #9
0
  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);
    }
  }
예제 #10
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);
  }
예제 #11
0
 @Override
 protected void setup() {
   this.capacityOfRooms = new HashMap<>();
   this.roomsOfSubjects = new HashMap<>();
   initLogger();
   logger.log(Level.INFO, "DataBaseAgent run");
   addBehaviour(new RoomsInitBehaviour(this, logger));
 }
예제 #12
0
 private final void checkTerminatedInfo(JICPPacket pkt) {
   if ((pkt.getInfo() & JICPProtocol.TERMINATED_INFO) != 0) {
     peerActive = false;
     if (myLogger.isLoggable(Logger.INFO)) {
       myLogger.log(Logger.INFO, myID + ": Peer termination notification received");
     }
   }
 }
예제 #13
0
  @Override
  protected void onDestroy() {
    super.onDestroy();

    unregisterReceiver(myReceiver);

    logger.log(Level.INFO, "Destroy activity!");
  }
예제 #14
0
 private BackEndManager initBEManager() {
   try {
     return BackEndManager.getInstance(null);
   } catch (Exception e) {
     myLogger.log(Logger.WARNING, "Cannot retrieve BackEndManager. " + e);
     e.printStackTrace();
   }
   return null;
 }
예제 #15
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;
      }
    }
  }
예제 #16
0
  private void killAgentImages() {
    AID[] ids = getAgentImages();
    for (int i = 0; i < ids.length; ++i) {
      handleEnd(ids[i]);
    }

    if (agentImages.size() > 0) {
      myLogger.log(Logger.WARNING, "# " + agentImages.size() + " zombie agent images found.");
      agentImages.clear();
    }
  }
예제 #17
0
 /**
  * Notify this NIOMediator that an error occurred on one of the Connections it was using. This
  * information is important since, unlike normal mediators, a NIOMediator typically does not read
  * packets from connections on its own (the JICPMediatorManager does that in general).
  */
 public void handleConnectionError(Connection c, Exception e) {
   myLogger.log(Level.WARNING, "connection error", e);
   if (active && peerActive) {
     // Try assuming it is the input connection
     try {
       inpManager.checkConnection(c);
       myLogger.log(Logger.WARNING, myID + ": IC Disconnection detected");
       inpManager.resetConnection();
     } catch (ICPException icpe) {
       // Then try assuming it is the output connection
       try {
         outManager.checkConnection(c);
         myLogger.log(Logger.WARNING, myID + ": OC Disconnection detected");
         outManager.resetConnection();
       } catch (ICPException icpe2) {
         // Ignore it
       }
     }
   }
 }
예제 #18
0
 public final void action() {
   ACLMessage msg = myAgent.receive(template);
   if (msg != null) {
     if (myLogger.isLoggable(Logger.FINER)) {
       myLogger.log(
           Logger.FINER, "Agent " + myAgent.getName() + " - Serving incoming message " + msg);
     }
     handleMessage(msg);
   } else {
     block();
   }
 }
예제 #19
0
  /** Make this NIOBEDispatcher terminate. */
  public void shutdown() {
    active = false;
    if (myLogger.isLoggable(Logger.INFO)) {
      myLogger.log(Logger.INFO, myID + ": shutting down");
    }

    // Deregister from the JICPServer
    if (myID != null) {
      myMediatorManager.deregisterMediator(myID);
    }

    inpManager.shutdown();
    outManager.shutdown();
  }
예제 #20
0
  // generates and sends messages
  @Override
  void generate() {
    if (rand.nextDouble() < sprob) {
      try {
        int i = rand.nextInt(myUser.getReceivers().size());
        ACLMessage msgL3 = new ACLMessage(ACLMessage.INFORM);
        msgL3.setContentObject(new Integer(1));
        msgL3.addReceiver(myUser.getReceivers().get(i));
        msgL3.setSender(myUser.getAID());

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

        log.log(
            Logger.INFO,
            myUser.getLocalName()
                + "# sended message to "
                + myUser.getReceivers().get(i).getLocalName());
        myUser.send(msgL2);
      } catch (IOException e) {
        log.log(Logger.SEVERE, "problems with output stream exception: ", e);
      } catch (IllegalArgumentException e) {
        log.log(
            Logger.WARNING,
            "User "
                + myUser.getLocalName()
                + " must have at least one destination user to generate traffic",
            e);
        block();
      } catch (Exception e) {
        log.log(Logger.SEVERE, "Exception", e);
      }
    }
  }
예제 #21
0
  /**
   * Passes to this JICPMediator the connection opened by the mediated entity. This is called by the
   * JICPMediatorManager this Mediator is attached to as soon as the mediated entity (re)connects.
   *
   * @param c the connection to the mediated entity
   * @param pkt the packet that was sent by the mediated entity when opening this connection
   * @param addr the address of the mediated entity
   * @param port the local port used by the mediated entity
   * @return an indication to the JICPMediatorManager to keep the connection open.
   */
  public boolean handleIncomingConnection(
      Connection c, JICPPacket pkt, InetAddress addr, int port) {
    checkTerminatedInfo(pkt);

    if (peerActive) {
      if (connectionDropped) {
        droppedToDisconnected();
      }

      // Update keep-alive info
      lastReceivedTime = System.currentTimeMillis();

      boolean inp = false;
      byte[] data = pkt.getData();
      if (data.length == 1) {
        inp = (data[0] == 1);
      }
      if (inp) {
        inpManager.setConnection((NIOJICPConnection) c);
        if (myLogger.isLoggable(Logger.CONFIG)) {
          myLogger.log(Logger.CONFIG, myID + ": New INP Connection establishd");
        }
      } else {
        outManager.setConnection(c);
        if (myLogger.isLoggable(Logger.CONFIG)) {
          myLogger.log(Logger.CONFIG, myID + ": New OUT Connection establishd");
        }
      }

      return true;
    } else {
      // The remote FrontEnd has terminated spontaneously -->
      // Kill the above container (this will also kill this NIOBEDispatcher).
      kill();
      return false;
    }
  }
예제 #22
0
  /**
   * Dispatch a serialized command to the BackEnd and get back a serialized response. Mutual
   * exclusion with itself to preserve dispatching order
   */
  public synchronized byte[] dispatch(byte[] payload, boolean flush) throws ICPException {
    // Note that we don't even try to dispatch packets while the
    // device is not reachable to preserve dispatching order.
    // If dispatching succeeded in fact this command would overcome
    // any postponed command waiting to be flushed.
    if (myDisconnectionManager.isReachable()) {
      // The following check preserves dispatching order when the
      // device has just reconnected but flushing has not started yet
      if (waitingForFlush && !flush) {
        throw new ICPException("Upsetting dispatching order");
      }
      waitingForFlush = false;

      int sid = outCnt;
      outCnt = (outCnt + 1) & 0x0f;
      myLogger.log(Logger.FINE, "Issuing outgoing command " + sid);
      try {
        JICPPacket pkt =
            new JICPPacket(JICPProtocol.COMMAND_TYPE, JICPProtocol.DEFAULT_INFO, payload);
        pkt.setSessionID((byte) sid);
        pkt = deliver(pkt);
        myLogger.log(Logger.FINE, "Response received " + pkt.getSessionID());
        if (pkt.getType() == JICPProtocol.ERROR_TYPE) {
          // Communication OK, but there was a JICP error on the peer
          throw new ICPException(new String(pkt.getData()));
        }
        return pkt.getData();
      } catch (IOException ioe) {
        // Can't reach the BackEnd. Assume we are unreachable
        myLogger.log(Logger.WARNING, "IOException on output connection", ioe);
        myDisconnectionManager.setUnreachable(false);
        throw new ICPException("Dispatching error.", ioe);
      }
    } else {
      throw new ICPException("Unreachable");
    }
  }
예제 #23
0
 /**
  * Make this HTTPFEDispatcher terminate. Note that when the BackEnd receives the termination
  * notification (explicitly sent in case of a self-initiated shutdown or attached to the response
  * to the EXIT command), it closes the input connection. The InputManager gets an exception and,
  * since it has been killed, terminates.
  */
 public void shutdown() {
   terminator = Thread.currentThread();
   myLogger.log(
       Logger.INFO,
       "Dispatcher shutting down. Self-initiated = " + (terminator != myInputManager));
   if (terminator != myInputManager) {
     // Self-initiated shut down
     // If connected, explicitly notify the BackEnd.
     if (myDisconnectionManager.isReachable()) {
       JICPPacket pkt =
           new JICPPacket(JICPProtocol.COMMAND_TYPE, (byte) (JICPProtocol.DEFAULT_INFO), null);
       myLogger.log(Logger.INFO, "Pushing termination notification");
       try {
         deliver(pkt);
       } catch (IOException ioe) {
         // When the BackEnd receives the termination notification,
         // it just closes the connection --> we always have this exception
         myLogger.log(Logger.FINE, "BackEnd closed");
       }
     }
     // Kill the InputManager
     myInputManager.kill();
   }
 }
예제 #24
0
 public List removePendingMessages(MessageTemplate template, boolean notifyFailure) {
   List pendingMsg = ((jade.imtp.leap.FrontEndStub) myFrontEnd).removePendingMessages(template);
   if (pendingMsg.size() > 0) {
     myLogger.log(
         Logger.INFO, "Removed " + pendingMsg.size() + " pending messages from BackEnd queue.");
   }
   if (notifyFailure) {
     Iterator it = pendingMsg.iterator();
     while (it.hasNext()) {
       try {
         Object[] removed = (Object[]) it.next();
         ACLMessage msg = (ACLMessage) removed[0];
         AID receiver = new AID((String) removed[1], AID.ISLOCALNAME);
         ServiceFinder myFinder = getServiceFinder();
         MessagingService msgSvc = (MessagingService) myFinder.findService(MessagingSlice.NAME);
         msgSvc.notifyFailureToSender(
             new GenericMessage(msg), receiver, new InternalError("Agent dead"));
       } catch (Exception e) {
         myLogger.log(Logger.WARNING, "Cannot send AMS FAILURE. " + e);
       }
     }
   }
   return pendingMsg;
 }
예제 #25
0
 protected void handleNotUnderstood(ContentException ce, ACLMessage msg) {
   myLogger.log(
       Logger.WARNING,
       "Agent "
           + myAgent.getName()
           + " - Error decoding "
           + ACLMessage.getPerformative(msg.getPerformative())
           + " message. Sender is "
           + msg.getSender().getName(),
       ce);
   if (performativesRequiringReply.contains(msg.getPerformative())) {
     ACLMessage reply = msg.createReply();
     reply.setPerformative(ACLMessage.NOT_UNDERSTOOD);
     myAgent.send(reply);
   }
 }
예제 #26
0
 protected void handleUnsupported(Object keyCel, ACLMessage msg) {
   myLogger.log(
       Logger.WARNING,
       "Agent "
           + myAgent.getName()
           + " - Unsupported content-element "
           + keyCel.getClass().getName()
           + ". Sender is "
           + msg.getSender().getName());
   if (performativesRequiringReply.contains(msg.getPerformative())) {
     ACLMessage reply = msg.createReply();
     reply.setPerformative(ACLMessage.REFUSE);
     reply.setContent(
         "((" + ExceptionVocabulary.UNSUPPORTEDACT + " " + keyCel.getClass().getName() + "))");
     myAgent.send(reply);
   }
 }
예제 #27
0
 protected void handleServingFailure(Throwable t, Object cel, ACLMessage msg) {
   myLogger.log(
       Logger.SEVERE,
       "Agent "
           + myAgent.getName()
           + " - Unexpected error serving content-element "
           + cel.getClass().getName()
           + ". Sender is "
           + msg.getSender().getName(),
       t);
   if (performativesRequiringReply.contains(msg.getPerformative())) {
     ACLMessage reply = msg.createReply();
     reply.setPerformative(ACLMessage.FAILURE);
     reply.setContent("((" + ExceptionVocabulary.INTERNALERROR + " \"" + t + "\"))");
     myAgent.send(reply);
   }
 }
예제 #28
0
  private void handleModMsg(ACLMessage msg) {
    myConnector.allmodelagents--;
    try {
      if (myConnector.mode) {
        UserModData data = (UserModData) msg.getContentObject();
        myConnector.usermodset.add(data);
      } else {
        RouterModData data = (RouterModData) msg.getContentObject();
        myConnector.routermodset.add(data);
      }
    } catch (Exception e) {
      log.log(Logger.SEVERE, "Exception:", e);
    }

    if (myConnector.allmodelagents == 0) {
      myConnector.finishModeling();
    }
  }
예제 #29
0
  /** Deliver a packet over a given connection and get back a response */
  private JICPPacket deliver(JICPPacket pkt, Connection c) throws IOException {
    boolean lastPacket = false;
    if (Thread.currentThread() == terminator) {
      pkt.setTerminatedInfo(true);
      lastPacket = true;
    }
    pkt.setRecipientID(mediatorTA.getFile());
    byte type = pkt.getType();

    int status = 0;
    try {
      c.writePacket(pkt);
      status = 1;
      /*#MIDP_INCLUDE_BEGIN
      lock();
      if (type == JICPProtocol.RESPONSE_TYPE) {
      	TimerDispatcher.getTimerDispatcher().add(new Timer(System.currentTimeMillis()+5000, this));
      }
      #MIDP_INCLUDE_END*/
      pkt = c.readPacket();

      status = 2;
      if (lastPacket && (pkt.getInfo() & JICPProtocol.TERMINATED_INFO) != 0) {
        // When we send a packet marked with the terminated-info, the back-end may either close
        // the connection (in this case we would have got an Exception) or reply with another
        // packet marked with the terminated-info --> throws an Exception to expose a uniform
        // behaviour
        myLogger.log(Logger.INFO, "Termination notification ACK received");
        throw new IOException("Terminated-info");
      }
      return pkt;
    } catch (IOException ioe) {
      // Re-throw the exception adding the status
      throw new IOException(ioe.getMessage() + '[' + status + ']');
    } finally {
      /*#MIDP_INCLUDE_BEGIN
      if (type != JICPProtocol.RESPONSE_TYPE) {
      	// If we delivered a RESPONSE unlock() is already called by the TimerDispatcher
      	unlock();
      }
      #MIDP_INCLUDE_END*/
    }
  }
예제 #30
0
  // Called by a terminating container.
  void endContainer() {
    --activeContainers;
    if (activeContainers == 0) {
      // Start a new Thread that calls all terminators one after
      // the other
      Thread t =
          new Thread(
              new Runnable() {
                public void run() {
                  for (int i = 0; i < terminators.size(); ++i) {
                    Runnable r = (Runnable) terminators.get(i);
                    r.run();
                  }
                  // Clear the terminators list at the end
                  terminators.clear();
                }
              });
      // #MIDP_EXCLUDE_BEGIN
      t.setDaemon(false);
      // #MIDP_EXCLUDE_END

      // Terminate the TimerDispatcher and release its resources
      TimerDispatcher.getTimerDispatcher().stop();

      // Reset mode
      mode = UNKNOWN_MODE;
      theContainer = null;

      // #MIDP_EXCLUDE_BEGIN
      try {
        criticalThreads.destroy();
      } catch (IllegalThreadStateException itse) {
        myLogger.log(Logger.WARNING, "Time-critical threads still active: ");
        criticalThreads.list();
      } finally {
        criticalThreads = null;
      }
      // #MIDP_EXCLUDE_END
      t.start();
    }
  }