示例#1
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);
    }
  }
示例#2
0
 /** Slet en person baseret på ID */
 private void deletePerson() {
   int ID = inputManager.inputInteger("Indtast ID: ");
   if (personCtr.deletePerson(ID)) {
     inputManager.setLastAction("Person med ID " + ID + " er slettet");
   } else {
     inputManager.setLastAction("Person med ID " + ID + " blev ikke fundet");
   }
 }
示例#3
0
 /** Finder en Person baseret på ID */
 private void findPerson() {
   int requestID = inputManager.inputInteger("Indtast ID for person du ønsker at finde: ");
   if (personCtr.findPerson(requestID) != null) {
     Person person = personCtr.findPerson(requestID);
     inputManager.setLastAction("Der er fundet en person med navn: " + person.getName());
   } else {
     inputManager.setLastAction("Det lykkedes ikke at finde en person med ID: " + requestID);
   }
 }
示例#4
0
 /** Opretter en Person */
 private void createPerson() {
   String name = inputManager.inputString("Navn: ", false);
   int phone = inputManager.inputInteger("Telefon nr.:");
   String address = inputManager.inputString("Adresse: ", false);
   String city = inputManager.inputString("By:", false);
   // Opretter en ny person i model laget igennem kontrol laget
   Person p =
       personCtr.createCustomer(name, phone, address, city, ModelLayer.Customer.Type.PRIVATE);
   if (p != null) {
     inputManager.setLastAction("Der er oprettet en ny kunde med ID: " + p.getID());
   } else {
     System.out.println("Det lykkedes ikke at oprette en ny kunde");
   }
 }
示例#5
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();
      }
    }
  }
示例#6
0
 private final byte getReconnectInfo() {
   byte info = JICPProtocol.DEFAULT_INFO;
   // If the inpConnection is null request the FrontEnd to reconnect
   if (!inpManager.isConnected()) {
     info |= JICPProtocol.RECONNECT_INFO;
   }
   return info;
 }
示例#7
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
       }
     }
   }
 }
示例#8
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();
  }
示例#9
0
  /** Printer Person menuen og returnere dit valg */
  private int printPersonMenu() {
    inputManager.clearConsole();
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Sidste handling: " + inputManager.getLastAction());
    System.out.println(" Person Menu");
    System.out.println("");
    System.out.println(" (1) Opret Person");
    System.out.println(" (2) Find Person");
    System.out.println(" (3) Opdater Person");
    System.out.println(" (4) Slet Person");
    System.out.println(" (0) Gå tilbage til hovedmenu");
    System.out.println("\n Vælg en af disse: ");
    System.out.println("");

    int choise;

    while (!keyboard.hasNextInt()) {
      System.out.println("Det er ikke et tal!");
      keyboard.next();
    }
    choise = keyboard.nextInt();
    return choise;
  }
示例#10
0
 //////////////////////////////////////////
 // Dispatcher interface implementation
 //////////////////////////////////////////
 public byte[] dispatch(byte[] payload, boolean flush) throws ICPException {
   if (connectionDropped) {
     // Move from DROPPED state to DISCONNECTED state and wait
     // for the FE to reconnect
     droppedToDisconnected();
     requestRefresh();
     throw new ICPException("Connection dropped");
   } else {
     // Normal dispatch
     JICPPacket pkt =
         new JICPPacket(JICPProtocol.COMMAND_TYPE, JICPProtocol.DEFAULT_INFO, payload);
     pkt = inpManager.dispatch(pkt, flush);
     return pkt.getData();
   }
 }
示例#11
0
 /** Denne metode bruges til at ændre i variablerne knyttet til en person i personContainer */
 private void updatePerson() {
   int ID = inputManager.inputInteger("Indtast ID for person: ");
   if (personCtr.findPerson(ID) != null) {
     Person person = personCtr.findPerson(ID);
     // Print nuv�rerende info om person
     System.out.println(
         "\n"
             + "Der er fundet en person: "
             + person.getName()
             + "\n"
             + "Telefon: "
             + person.getPhone()
             + "\n"
             + "Adresse: "
             + person.getAddress()
             + "\n"
             + "By: "
             + person.getCity());
     // Modtag input for nye info om person
     String name = inputManager.inputString("Navn ændres til: ", false);
     int tlf = inputManager.inputInteger("Telefon nr ændres til: ");
     String adresse = inputManager.inputString("Adresse ændres til:", false);
     String by = inputManager.inputString("By ændres til: ", false);
     // Opdater person info
     Person updatePerson = personCtr.updatePerson(name, tlf, adresse, by, person, ID);
     // Skriv i konsollen
     inputManager.setLastAction(
         "Der er opdateret en kunde: "
             + updatePerson.getName()
             + "\n"
             + "Telefon: "
             + updatePerson.getPhone()
             + "\n"
             + "Adresse: "
             + updatePerson.getAddress()
             + "\n"
             + "By: "
             + updatePerson.getCity());
   } else {
     inputManager.setLastAction("Det lykkedes ikke at opdater info om en kunde!");
   }
 }
示例#12
0
  /**
   * Overloaded version of the handleJICPPacket() method including the <code>Connection</code> the
   * incoming JICPPacket was received from. This information is important since, unlike normal
   * mediators, a NIOMediator may not read packets from connections on its own (the
   * JICPMediatorManager does that in general).
   */
  public JICPPacket handleJICPPacket(Connection c, JICPPacket pkt, InetAddress addr, int port)
      throws ICPException {
    if (pkt.getType() == JICPProtocol.DROP_DOWN_TYPE) {
      // Note that the return packet is written inside the handleDropDown()
      // method since the connection must be closed after the response has
      // been sent back.
      handleDropDown(c, pkt, addr, port);
      return null;
    }

    checkTerminatedInfo(pkt);

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

    byte type = pkt.getType();
    if (type == JICPProtocol.COMMAND_TYPE) {
      if (peerActive) {
        return outManager.handleCommand(c, pkt);
      } else {
        // The remote FrontEnd has terminated spontaneously -->
        // Kill the above container (this will also kill this NIOBEDispatcher).
        kill();
        return null;
      }
    } else if (type == JICPProtocol.KEEP_ALIVE_TYPE) {
      if (enableServerKeepAlive) {
        inpManager.sendServerKeepAlive();
      }
      return outManager.handleKeepAlive(c, pkt);
    } /* Asynch-reply
      else if (type == JICPProtocol.RESPONSE_TYPE || type == JICPProtocol.ERROR_TYPE) {
      inpManager.handleResponse(c, pkt);
      return null;
      }*/ else {
      throw new ICPException("Unexpected packet type " + type);
    }
  }
示例#13
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;
    }
  }
示例#14
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();
   }
 }
示例#15
0
 @Override
 public void update(GameManager gameManager) {
   if (!this.enabled) {
     return;
   }
   InputManager inputManager = gameManager.getInputManager();
   if (inputManager.eventHasOccurred()) {
     float x = inputManager.getTouchX(), y = inputManager.getTouchY();
     if (inputManager.downOccurred()) {
       this.btDown = (x > this.x && x < this.x + this.w && y > this.y && y < this.y + this.h);
     }
     if (inputManager.moveOccurred()) {
       this.btDown =
           this.btDown & (x > this.x && x < this.x + this.w && y > this.y && y < this.y + this.h);
     }
     if (inputManager.upOccurred()) {
       if (this.btDown) {
         this.btDown = false;
         this.onClick(gameManager);
       }
     }
   }
 }
示例#16
0
  /** Create a BackEnd in the fixed network and return a stub to communicate with it */
  public BackEnd getBackEnd(FrontEnd fe, Properties p) throws IMTPException {
    props = p;

    beAddrsText = props.getProperty(FrontEnd.REMOTE_BACK_END_ADDRESSES);
    backEndAddresses = parseBackEndAddresses(beAddrsText);

    // Host
    String host = props.getProperty("host");
    if (host == null) {
      host = "localhost";
    }
    // Port
    int port = JICPProtocol.DEFAULT_PORT;
    try {
      port = Integer.parseInt(props.getProperty("port"));
    } catch (NumberFormatException nfe) {
      // Use default
    }
    // Compose URL. Note that we build a JICPAddress just to avoid loading the HTTPAddress class.
    mediatorTA = JICPProtocol.getInstance().buildAddress(host, String.valueOf(port), null, null);

    // Mediator class
    String tmp = props.getProperty(JICPProtocol.MEDIATOR_CLASS_KEY);
    if (tmp != null) {
      myMediatorClass = tmp;
    } else {
      // Set the default mediator class since this must be propagated to the mediator.
      props.setProperty(JICPProtocol.MEDIATOR_CLASS_KEY, myMediatorClass);
    }

    // Read re-connection retry time
    long retryTime = JICPProtocol.DEFAULT_RETRY_TIME;
    try {
      retryTime = Long.parseLong(props.getProperty(JICPProtocol.RECONNECTION_RETRY_TIME_KEY));
    } catch (Exception e) {
      // Use default
    }

    // Read Max disconnection time
    maxDisconnectionTime = JICPProtocol.DEFAULT_MAX_DISCONNECTION_TIME;
    try {
      maxDisconnectionTime =
          Long.parseLong(props.getProperty(JICPProtocol.MAX_DISCONNECTION_TIME_KEY));
    } catch (Exception e) {
      // Use default
      props.setProperty(
          JICPProtocol.MAX_DISCONNECTION_TIME_KEY, String.valueOf(maxDisconnectionTime));
    }

    // Read Keep-alive time
    keepAliveTime = JICPProtocol.DEFAULT_KEEP_ALIVE_TIME;
    try {
      keepAliveTime = Long.parseLong(props.getProperty(JICPProtocol.KEEP_ALIVE_TIME_KEY));
    } catch (Exception e) {
      // Use default
      props.setProperty(JICPProtocol.KEEP_ALIVE_TIME_KEY, String.valueOf(keepAliveTime));
    }

    if (myLogger.isLoggable(Logger.CONFIG)) {
      myLogger.log(Logger.CONFIG, "Remote URL = http://" + host + ":" + port);
      myLogger.log(Logger.CONFIG, "Mediator class = " + myMediatorClass);
      myLogger.log(Logger.CONFIG, "Reconnection retry time = " + retryTime);
      myLogger.log(Logger.CONFIG, "Max disconnection time = " + maxDisconnectionTime);
      myLogger.log(Logger.CONFIG, "Keep-alive time = " + keepAliveTime);
    }

    myDisconnectionManager = new DisconnectionManager(retryTime, maxDisconnectionTime);
    myKeepAliveManager = new KeepAliveManager(keepAliveTime);
    myInputManager = new InputManager();

    // Read the owner if any
    owner = props.getProperty("owner");

    // Create the BackEnd stub and the FrontEnd skeleton
    myStub = new BackEndStub(this);
    mySkel = new FrontEndSkel(fe);

    // Start the InputManager
    myInputManager.start();

    // Create the remote BackEnd
    createBackEnd();

    return myStub;
  }
 // Maps the escape key to the gameaction escape
 public void createGameActions() {
   exit = new GameAction("exit", GameAction.DETECT_INITAL_PRESS_ONLY);
   inputManager.mapToKey(exit, KeyEvent.VK_ESCAPE);
 }
示例#18
0
 /**
  * Return a stub of the remote FrontEnd that is connected to the local BackEnd.
  *
  * @param be The local BackEnd
  * @param props Additional (implementation dependent) connection configuration properties.
  * @return A stub of the remote FrontEnd.
  */
 public FrontEnd getFrontEnd(BackEnd be, Properties props) throws IMTPException {
   return inpManager.getStub();
 }
示例#19
0
 public boolean isConnected() {
   return inpManager.isConnected() && outManager.isConnected();
 }
示例#20
0
 /** Kontruktøren der kalder inputManageren samt person controlleren */
 public PersonUI() {
   personCtr = new PersonCtr();
   inputManager = InputManager.getInstance();
 }