Пример #1
0
 // -----------------------------------------------------------
 public static void sendArgs(Socket s, String[] args, int numArgs, MessageType type)
     throws GenericException {
   Message m = new Message(type);
   m.addPayload(args[0].getBytes());
   try {
     m.send(s);
   } catch (IOException e) {
     throw new GenericException(e.getMessage());
   }
   for (int i = 1; i < numArgs; i++) {
     Message rr = Message.receive(s);
     if (rr.getMessageType() != MessageType.SEND_NEXT_PARAM) {
       throw new GenericException(
           "Got type: "
               + rr.getMessageType().toString()
               + " when "
               + MessageType.SEND_NEXT_PARAM.toString()
               + " was expected");
     }
     m = new Message(MessageType.NEXT_PARAM_RQT);
     m.addPayload(args[i].getBytes());
     try {
       m.send(s);
     } catch (IOException e) {
       throw new GenericException(e.getMessage());
     }
   }
 }
Пример #2
0
 public void removeMessagesOfType(int type) {
   Iterator<Message> it = iterator();
   while (it.hasNext()) {
     Message message = it.next();
     if (message.getMessageType() == type) it.remove();
   }
 }
  static void validateRequiredMessagePropertiesArePresent(Message message) {

    if (message.getMessageId() == null) {
      throw new MessageFormatException(
          Message.MESSAGE_ID_HEADER_NAME + " is missing but is a required message header.");
    }
    if (message.getMessageTimestamp() == null) {
      throw new MessageFormatException(
          Message.MESSAGE_TIMESTAMP_HEADER_NAME + " is missing but is a required message header.");
    }
    if (message.getMessageType() == null) {
      throw new MessageFormatException(
          Message.MESSAGE_TYPE_HEADER_NAME + " is missing but is a required message header.");
    }
    if (message.getOriginSystemId() == null) {
      throw new MessageFormatException(
          Message.ORIGIN_SYSTEM_ID_HEADER_NAME + " is missing but is a required message header.");
    }
    if (message.getContentType() == null) {
      throw new MessageFormatException(
          Message.CONTENT_TYPE_HEADER_NAME + " is missing but is a required message header.");
    }
    if (Strings.isNullOrEmpty(message.getMessageBody())) {
      throw new MessageFormatException("Message body is missing but is a required.");
    }
  }
Пример #4
0
 // -----------------------------------------------------------
 public static void getPutFileRequest(Socket s, String[] args, int numArgs, byte type)
     throws GenericException {
   byte[] myPayload = new byte[4];
   myPayload[0] = (byte) ((numArgs >> 24) & 0xff);
   myPayload[1] = (byte) ((numArgs >> 16) & 0xff);
   myPayload[2] = (byte) ((numArgs >> 8) & 0xff);
   myPayload[3] = (byte) (numArgs & 0xff);
   Message m = new Message(MessageType.findType(type));
   m.addPayload(myPayload);
   try {
     m.send(s);
     m = Message.receive(s);
     if (m.getMessageType() != MessageType.SEND_NEXT_PARAM) {
       System.out.println("Error, unexpected type returned");
       throw new GenericException("Received wrong type");
     }
   } catch (IOException e) {
     throw new GenericException(e.getMessage());
   }
   try {
     sendArgs(s, args, numArgs, MessageType.NEXT_PARAM_RQT);
   } catch (GenericException e) {
     throw new GenericException("Error " + e);
   }
 }
Пример #5
0
 public void keepOnlyMessagesOfType(int type) {
   Iterator it = iterator();
   while (it.hasNext()) {
     Message message = (Message) it.next();
     if (message.getMessageType() != type) it.remove();
   }
 }
  public void getRequestToken(Message msg) {
    if (msg.getMessageType() != MTRequest) {
      System.err.println("??? (getRequestToken)");
      return;
    }

    int originator = Integer.parseInt(msg.getParam());
    try {
      this.mutex.acquire();

      if (this.parent == -1) {
        if (holding) {
          node.send(MTToken, originator, "");
          this.holding = false;
        } else {
          this.deferred = originator;
        }
      } else {
        node.send(MTRequest, parent, msg.getParam());
      }
      this.parent = msg.getSource();

      this.mutex.release();
    } catch (InterruptedException ex) {
      System.err.println("Error (getRequestToken " + node.getId() + "): " + ex.getMessage());
    }
  }
Пример #7
0
 /**
  * returns the appropriate connection based on message type. returns null if a connection could
  * not be established.
  */
 OutboundTcpConnection getConnection(Message msg) {
   Stage stage = msg.getMessageType();
   return stage == Stage.REQUEST_RESPONSE
           || stage == Stage.INTERNAL_RESPONSE
           || stage == Stage.GOSSIP
       ? ackCon
       : cmdCon;
 }
Пример #8
0
 public boolean containsMessagesOfType(int type) {
   Iterator<Message> it = iterator();
   while (it.hasNext()) {
     Message message = it.next();
     if (message.getMessageType() == type) return true;
   }
   return false;
 }
Пример #9
0
 public List<Message> getMessagesOfType(int type) {
   List<Message> result = new ArrayList<Message>();
   for (Message message : this) {
     if (message.getMessageType() == type) {
       result.add(message);
     }
   }
   return result;
 }
Пример #10
0
 // -----------------------------------------------------------
 // receive a terminateResponse message
 public static void terminateResponse(Socket s) throws GenericException {
   Message m = Message.receive(s);
   MessageType t = m.getMessageType();
   if (t == MessageType.TERM_RSP) return;
   else if (t == MessageType.TERM_ERR) throw new GenericException(t.getDescription());
   else if (t.isErrorType())
     throw new GenericException("Server encountered an " + t.getDescription());
   else throw new GenericException("Server's response is of an unexpected type.");
 }
Пример #11
0
 public static void sendArg(Socket s, byte[] arg, MessageType type) throws GenericException {
   Message m = new Message(type);
   m.addPayload(arg);
   try {
     m.send(s);
   } catch (IOException e) {
     throw new GenericException(e.getMessage());
   }
   Message rr = Message.receive(s);
   if (rr.getMessageType() != MessageType.SEND_NEXT_PARAM) {
     System.out.println("Got a " + rr.getMessageType() + " message");
     throw new GenericException(
         "Got type: "
             + rr.getMessageType().toString()
             + " when "
             + MessageType.SEND_NEXT_PARAM.toString()
             + " was expected");
   }
 }
Пример #12
0
 // -----------------------------------------------------------
 // receive an initResponse message
 public static void initResponse(Socket s) throws GenericException {
   System.out.println("Receiving init");
   Message m = Message.receive(s);
   System.out.println("Init received");
   MessageType t = m.getMessageType();
   if (t == MessageType.INIT_RSP) return;
   else if (t.isErrorType())
     throw new GenericException("Server encountered an " + t.getDescription());
   else throw new GenericException("Server's response is of an unexpected type: " + t.name());
 }
Пример #13
0
 public List getMessagesOfType(int type) {
   List l = new ArrayList();
   Iterator it = iterator();
   while (it.hasNext()) {
     Message message = (Message) it.next();
     if (message.getMessageType() == type) {
       l.add(message);
     }
   }
   return l;
 }
Пример #14
0
 // -----------------------------------------------------------
 // --------------------HANDSHAKING FUNCTIONS------------------
 public static byte[] transactionAddedResponse(Socket s) throws GenericException {
   Message m = Message.receive(s);
   if (m.getMessageType() == MessageType.TRANS_ADDED_RSP) {
     System.out.println(m.getPayload().toString());
     // long tid = (long)(m.getPayload()[0]<<24) +
     // (long)(m.getPayload()[1]<<16) + (long)(m.getPayload()[2]<<8) +
     // (long)(m.getPayload()[3]);
     // if(m.getPayload().length > 4) {
     // }
     // return tid;
     return m.getPayload();
   } else {
     System.out.println(
         "Error, got "
             + m.getMessageType()
             + " when "
             + MessageType.TRANS_ADDED_RSP
             + " was expected.");
     throw new GenericException(m.getMessageType().getDescription());
   }
 }
Пример #15
0
  @Override
  public void cmdExecute(Message msg, ServerConnection servConn, long start) throws IOException {
    // requiresResponse = true; NOT NEEDED... ALWAYS SEND ERROR RESPONSE

    logger.fatal(
        LocalizedMessage.create(
            LocalizedStrings.Default_0_UNKNOWN_MESSAGE_TYPE_1_WITH_TX_2_FROM_3,
            new Object[] {
              servConn.getName(),
              MessageType.getString(msg.getMessageType()),
              Integer.valueOf(msg.getTransactionId()),
              servConn.getSocketString()
            }));
    writeErrorResponse(msg, MessageType.UNKNOWN_MESSAGE_TYPE_ERROR, servConn);
    // responded = true; NOT NEEDED... ALWAYS SEND ERROR RESPONSE
  }
Пример #16
0
 // -----------------------------------------------------------
 public static GetFileReturnType getFileResponse(Socket s) throws GenericException {
   // GOELogger log = new GOELogger("/home/arbab/storageLogs/ws.log");
   // System.out.println("INITIALIZED THE LOGGER");
   GetFileReturnType r = new GetFileReturnType();
   Message m = Message.receive(s);
   byte[] payload;
   // IP
   if (m.getMessageType() != MessageType.GET_FILE_RSP)
     throw new GenericException("Error, received invalid type: " + m.getMessageType());
   else payload = m.getPayload();
   r.IP = payload.toString();
   System.out.println("IP: " + r.IP);
   // Port
   m = new Message(MessageType.SEND_NEXT_PARAM);
   try {
     m.send(s);
   } catch (IOException e) {
     throw new GenericException("error " + e);
   }
   m = Message.receive(s);
   if (m.getMessageType() != MessageType.NEXT_PARAM_RQT) {
     throw new GenericException("Error, received invalid type: " + m.getMessageType());
   } else {
     payload = m.getPayload();
     r.Port = (payload[0] << 8) + payload[1];
   }
   // tid
   m = new Message(MessageType.SEND_NEXT_PARAM);
   try {
     m.send(s);
   } catch (IOException e) {
     throw new GenericException("error " + e);
   }
   m = Message.receive(s);
   if (m.getMessageType() != MessageType.NEXT_PARAM_RQT) {
     throw new GenericException("Error, received invalid type: " + m.getMessageType());
   } else {
     payload = m.getPayload();
     // r.tid = (long)(payload[0] << 24) + (long)(payload[1] << 16) +
     // (long)(payload[2] << 8) + (long)payload[3];
     // log.write("%%%%%% " + (long)payload[0] + " " + (long)payload[1] + " " +
     // (long)payload[2] + " " + (long)payload[3] + "\n", false);
     // log.write( (0x000000FF & ((long)payload[0])) + "\n",false);
     // log.write( (0x000000FF & ((long)payload[1])) + "\n",false);
     // log.write( (0x000000FF & ((long)payload[2])) + "\n",false);
     // log.write( (0x000000FF & ((long)payload[3])) + "\n",false);
     r.tid =
         (0x000000FF & ((long) payload[0] << 24))
             + (0x000000FF & ((long) payload[1] << 16))
             + (0x000000FF & ((long) payload[2] << 8))
             + (0x000000FF & ((long) payload[3]));
   }
   return r;
 }
Пример #17
0
 // -----------------------------------------------------------
 public static void deleteDirectoryRequest(
     Socket s, String username, String password, String directory) throws GenericException {
   try {
     Message m = new Message(MessageType.DELETE_DIR_RQT);
     byte[] myPayload = {0, 0, 0, 3};
     m.addPayload(myPayload);
     m.send(s);
     Message rr = Message.receive(s);
     if (rr.getMessageType() != MessageType.SEND_NEXT_PARAM) {
       throw new GenericException(
           "Got type: "
               + rr.getMessageType().toString()
               + " when "
               + MessageType.SEND_NEXT_PARAM.toString()
               + " was expected");
     }
     m = new Message(MessageType.NEXT_PARAM_RQT);
     m.addPayload(username.getBytes());
     m.send(s);
     rr = Message.receive(s);
     if (rr.getMessageType() != MessageType.SEND_NEXT_PARAM) {
       throw new GenericException(
           "Got type: "
               + rr.getMessageType().toString()
               + " when "
               + MessageType.SEND_NEXT_PARAM.toString()
               + " was expected");
     }
     m = new Message(MessageType.NEXT_PARAM_RQT);
     m.addPayload(password.getBytes());
     m.send(s);
     rr = Message.receive(s);
     if (rr.getMessageType() != MessageType.SEND_NEXT_PARAM) {
       throw new GenericException(
           "Got type: "
               + rr.getMessageType().toString()
               + " when "
               + MessageType.SEND_NEXT_PARAM.toString()
               + " was expected");
     }
     m = new Message(MessageType.NEXT_PARAM_RQT);
     m.addPayload(directory.getBytes());
     m.send(s);
   } catch (IOException e) {
     throw new GenericException(e.getMessage());
   }
 }
Пример #18
0
 // -----------------------------------------------------------
 public static void copyFileRequest(Socket s, String username, String origName, String copyName)
     throws GenericException {
   try {
     Message m = new Message(MessageType.COPY_FILE_RQT);
     byte[] myPayload = {0, 0, 0, 3};
     m.addPayload(myPayload);
     m.send(s);
     Message rr = Message.receive(s);
     if (rr.getMessageType() != MessageType.SEND_NEXT_PARAM) {
       throw new GenericException(
           "Got type: "
               + rr.getMessageType().toString()
               + " when "
               + MessageType.SEND_NEXT_PARAM.toString()
               + " was expected");
     }
     m = new Message(MessageType.NEXT_PARAM_RQT);
     m.addPayload(username.getBytes());
     m.send(s);
     rr = Message.receive(s);
     if (rr.getMessageType() != MessageType.SEND_NEXT_PARAM) {
       throw new GenericException(
           "Got type: "
               + rr.getMessageType().toString()
               + " when "
               + MessageType.SEND_NEXT_PARAM.toString()
               + " was expected");
     }
     m = new Message(MessageType.NEXT_PARAM_RQT);
     m.addPayload(origName.getBytes());
     m.send(s);
     rr = Message.receive(s);
     if (rr.getMessageType() != MessageType.SEND_NEXT_PARAM) {
       throw new GenericException(
           "Got type: "
               + rr.getMessageType().toString()
               + " when "
               + MessageType.SEND_NEXT_PARAM.toString()
               + " was expected");
     }
     m = new Message(MessageType.NEXT_PARAM_RQT);
     m.addPayload(copyName.getBytes());
     m.send(s);
   } catch (IOException e) {
     throw new GenericException(e.getMessage());
   }
 }
Пример #19
0
 // -----------------------------------------------------------
 public static listFilesRequestType listFilesResponse(Socket s) throws GenericException {
   byte[] payload;
   int numFiles;
   Message m = Message.receive(s);
   if (m.getMessageType() != MessageType.LIST_FILES_RSP)
     throw new GenericException("Error, received invalid type: " + m.getMessageType());
   else {
     payload = m.getPayload();
     numFiles = (payload[0] << 24) + (payload[1] << 16) + (payload[2] << 8) + payload[3];
   }
   System.out.println(numFiles + " files to be received");
   listFilesRequestType fileList = new listFilesRequestType(numFiles);
   for (int i = 0; i < numFiles; i++) {
     // m.setMessageType(MessageType.SEND_NEXT_PARAM);
     m = new Message(MessageType.SEND_NEXT_PARAM);
     try {
       m.send(s);
     } catch (IOException e) {
       throw new GenericException("error " + e);
     }
     m = Message.receive(s);
     if (m.getMessageType() != MessageType.FILE_NAME_RQT
         && m.getMessageType() != MessageType.DIR_NAME_RQT) {
       throw new GenericException("Error, received invalid type: " + m.getMessageType());
     } else {
       payload = m.getPayload();
       fileList.name[i] = byteArrayToString(payload);
       if (m.getMessageType() == MessageType.FILE_NAME_RQT) {
         fileList.isDir[i] = false;
         System.out.println("File: " + fileList.name[i]);
       } else {
         fileList.isDir[i] = true;
         System.out.println("Directory: " + fileList.name[i]);
       }
     }
   } // end for
   return (fileList);
 }
Пример #20
0
 // -----------------------------------------------------------
 public static void copyFileResponse(Socket s) throws GenericException {
   Message m = Message.receive(s);
   if (m.getMessageType() == MessageType.COPY_FILE_RSP) return;
   else throw new GenericException(m.getMessageType().getDescription());
 }
  @Override
  public void run() {
    while (true) {
      try {
        is = new BufferedReader(new InputStreamReader(player.getSocket().getInputStream()));
        line = is.readLine();
        if (line != null) {
          int type = Message.getMessageType(line);
          System.out.println("Message type : " + type);
          List<String> message = Message.getMessage(line);

          switch (type) {

              // USER CONNECT WITH USERNAME
            case 0:
              {
                player.setNickName(message.get(1));
                System.out.println("Player set name " + message.get(1));
                player.sendMessage("user," + player.getId());

                // Client State --> Room Screen, Server Send List Room
                String roomList = "";
                for (Room r : Server.rooms) {
                  roomList +=
                      "," + r.getId() + "," + r.getName() + "," + r.getClients().size() + ", true";
                }
                player.sendMessage("roomlist" + roomList);
                break;
              }

              // USER MOVE
            case 1:
              {
                List<Player> clients = player.getRoom().getClients();
                Room room = player.getRoom();

                int row = Integer.parseInt(message.get(1));
                int col = Integer.parseInt(message.get(2));

                room.Board[row][col] = player.getId();
                List<int[]> res = room.checkWin(row, col, player.getId());

                // This user win
                String converted = "";
                if (!res.isEmpty()) {
                  for (int[] cell : res) {
                    converted += "," + cell[0] + "," + cell[1];
                  }
                  //				room.broadcastMessageWithEx(player, "win," + player.getNickName()+converted
                  // );
                  player.sendMessage("youwin" + converted);
                  player
                      .getRoom()
                      .broadcastMessageWithEx(player, "win," + player.getNickName() + converted);
                  System.out.println("Hasil :" + converted);
                }

                Player turn = clients.get((clients.indexOf(player) + 1) % clients.size());
                room.broadcastMessageToAll(
                    "move,"
                        + message.get(1)
                        + ","
                        + message.get(2)
                        + ","
                        + player.getId()
                        + ","
                        + turn.getId()
                        + ","
                        + turn.getNickName());
                System.out.println(
                    player.getNickName() + " Move to ROW : " + row + " COL : " + col);
                break;
              }

              // USER JOIN ROOM
            case 2:
              {
                Room theRoom = Server.getRoomById(Integer.parseInt(message.get(1)));
                player.setRoom(theRoom);
                player.sendMessage("user," + player.getId());
                theRoom.broadcastMessageWithEx(
                    player, "message,Server," + player.getNickName() + " joins this room ");
                if (theRoom.isStart()) {
                  theRoom.getCreator().sendMessage("canstart");
                }
                System.out.println(
                    "USer  " + player.getNickName() + " join room, room : " + theRoom.getName());
                break;
              }
              // USER CREATE ROOM
            case 3:
              {
                String roomName = message.get(1);
                player.createRoom(roomName);
                player.sendMessage("user," + player.getId());
                System.out.println(player.getNickName() + " create room, room name " + roomName);
                String roomList = "";
                for (Room r : Server.rooms) {
                  roomList +=
                      "," + r.getId() + "," + r.getName() + "," + r.getClients().size() + ", true";
                }
                Server.broadcastMessage("roomlist" + roomList);

                Room theRoom = player.getRoom();
                if (theRoom.isStart()) {
                  theRoom.getCreator().sendMessage("canstart");
                }
                break;
              }
              // PLAYER DISCONNECT
            case 4:
              {
                Room room = player.getRoom();
                try {
                  room.deleteClient(player);
                  room.broadcastMessageToAll("disconnect," + player.getNickName());
                  Server.deleteClient(this);
                  if (room.getClients().isEmpty()) {
                    Server.deletRoom(room);
                    System.out.println("Current Rooms on Server :" + Server.rooms);
                  } else if (message.get(1).equals("ingame")) {
                    List<Player> clients = room.getClients();
                    Player turn = clients.get((clients.indexOf(player) + 1) % clients.size());
                    room.broadcastMessageToAll("turn," + turn.getId() + "," + turn.getNickName());
                  } else if (room.isCreator(player)) {
                    // Change the creator
                    Player newCreator =
                        room.getClients().get(room.getClients().indexOf(player) + 1);
                    room.setCreator(newCreator);
                    newCreator.sendMessage("newcreator");
                  } else {
                    // Check the number to start still sufficient
                    if (room.isStart()) {
                      room.getCreator().sendMessage("canstart");
                    } else {
                      room.getCreator().sendMessage("cantstart");
                    }
                  }

                } catch (NullPointerException ex) {
                  System.out.println(player.getNickName() + " has Disconnected");
                }
                System.out.println(player.getNickName() + " Has DISCONNECTED");
                break;
              }

              // GET START SIGNAL FROM CREATOR
            case 5:
              {
                System.out.println("Get Start Game Signal");
                Room room = player.getRoom();
                room.broadcastMessageToAll("start," + player.getId() + "," + player.getNickName());
                break;
              }

              //			 JOIN ROOM TO SPECTATE
            case 6:
              {
                Room theRoom = Server.getRoomById(Integer.parseInt(message.get(1)));
                player.setRoomAsSpectator(theRoom);
                player.sendMessage("spectate," + player.getId());
                theRoom.broadcastMessageToSpectatorsWithEx(
                    player, "message,Server," + player.getNickName() + " Spectates This Room ");
                System.out.println(
                    "Uuer  "
                        + player.getNickName()
                        + " spectate room, room : "
                        + theRoom.getName());
                break;
              }

              // Spectator Disconnect
            case 7:
              {
                Room room = player.getRoom();
                try {
                  room.deleteSpectator(player);
                  room.broadcastMessageToSpectators("disconnect," + player.getNickName());
                  Server.deleteClient(this);
                } catch (NullPointerException ex) {
                  System.out.println(player.getNickName() + " has Disconnected");
                }
                System.out.println(player.getNickName() + " Has DISCONNECTED");
                break;
              }

              // CHAT WITH OTHER SPECTATORS
            case 8:
              {
                Room room = player.getRoom();
                room.broadcastMessageToSpectators(
                    "message," + player.getNickName() + "," + message.get(1));
                System.out.println("BroadCast Message SPECTATOR " + message.get(1));
                break;
              }

            case -1:
              {
                Room room = player.getRoom();
                room.broadcastMessageToPlayers(
                    "message," + player.getNickName() + "," + message.get(0));
                System.out.println("BroadCast Message " + message.get(0));
                break;
              }
          }
          // Stop thread
          if (type == 4 || type == 7) {
            break;
          }
        }
      } catch (IOException ex) {
        ex.printStackTrace();
        System.out.println("I/O fail");
        System.exit(-1);
      }
    }
  }
Пример #22
0
 // -----------------------------------------------------------
 public static void makeDirectoryResponse(Socket s) throws GenericException {
   Message m = Message.receive(s);
   if (m.getMessageType() == MessageType.MK_DIR_RSP) return;
   else throw new GenericException(m.getMessageType().getDescription());
 }
Пример #23
0
 // ------------------------------------------------------------
 private boolean respondToDatagram(
     DatagramPacket receivePacket,
     ServerDescription[] validServers,
     boolean addToFile,
     int expectedServers)
     throws IOException {
   boolean serverAdded = false;
   StorageServer serv = new StorageServer();
   try {
     if (receivePacket.getData()[0] == MessageType.ADD_SERV_RQT.getType()) {
       extractPacketData(serv, receivePacket);
       int servNo = findServer(validServers, serv.IP, serv.port);
       int index = servAlreadyConnected(serv);
       /*
        * if(expectedServers == 0) { Message m = new
        * Message(MessageType.COPY_FILE_RQT); m.send(serv.sock); return(false);
        * } else if(expectedServers == 1) { Message m = new
        * Message(MessageType.COPY_FILE_RSP); m.send(serv.sock); return(false);
        * } else if(expectedServers == 2) { Message m = new
        * Message(MessageType.DELETE_DIR_RQT); m.send(serv.sock);
        * return(false); } else { Message m = new
        * Message(MessageType.DELETE_DIR_RSP); m.send(serv.sock); }
        * if(expectedServers > 2) { return false; }
        */
       if (servNo > 0 || addToFile) {
         if (index >= 0) {
           System.out.println("Reconnection of a server, removing stale values");
           serverList.remove(index);
         }
         Message m = new Message(MessageType.SEND_NEXT_PARAM);
         m.send(serv.sock);
         m = Message.receive(serv.sock);
         if (m.getMessageType() != MessageType.NEXT_PARAM_RQT) {
           m = new Message(MessageType.ERR_UNEXPECTED_CLT);
           m.send(serv.sock);
           return (false);
         } else {
           byte[] payload = new byte[2];
           payload = m.getPayload();
           serv.httpPort = payload[0] & 0xff;
           serv.httpPort <<= 8;
           serv.httpPort += payload[1] & 0xff;
           if (servNo > 0) {
             serv.servNo = servNo;
           }
           if (servNo < 0) {
             try {
               validServers[expectedServers].IP = ServerDescription.IPStrToByteArr(serv.IP);
               validServers[expectedServers].port = serv.port;
               validServers[expectedServers].serverNumber = findMinUnusedServNum(validServers);
               serv.servNo = validServers[expectedServers].serverNumber;
               addToFile(serv, validServers[expectedServers].serverNumber);
               serverAdded = true;
             } catch (GenericException e) {
               m = new Message(MessageType.ERR_UNEXPECTED_CLT);
               m.send(serv.sock);
               return (false);
             }
           }
           // By default, external IP = internal IP
           serv.externalName = serv.IP;
           Iterator itr = ipPairs.iterator();
           // if we find an external IP that is associated with the
           // internal IP for this server, change the external IP
           // address for this server to match
           while (itr.hasNext()) {
             String[] pair = (String[]) itr.next();
             // mylog.write("pair[0]: " + pair[0] + "servIP: " + serv.IP +
             // "\n", true);
             if (pair[0].equals(serv.IP)) {
               // mylog.write("found ext int match\n", true);
               serv.externalName = pair[1];
               /*
                * Runtime runtime = Runtime.getRuntime(); String[] args = new
                * String[]{"sh", "-c", "ssh -f -i " + keyfile + " root@" + gwIP
                * + " \"perl stoptcppr.pl " + serv.externalIP + "\""}; Process
                * proc = runtime.exec(args); args = new String[]{"sh", "-c",
                * "ssh -f -i " + keyfile + " root@" + gwIP +
                * " \"perl tcppr.pl " + serv.externalIP + " " + serv.IP +
                * "\""}; proc = runtime.exec(args);
                */
               break;
             }
           }
           serverList.add(serv);
           m = new Message(MessageType.ADD_SERV_RSP);
           payload[0] = (byte) ((servNo >> 8) & 0xff);
           payload[1] = (byte) (servNo & 0xff);
           m.addPayload(payload);
           m.send(serv.sock);
         }
       } else {
         Message m = new Message(MessageType.ERR_UNEXPECTED_CLT);
         m.send(serv.sock);
       }
     }
     return (serverAdded);
   } catch (IOException e) {
     Message m = new Message(MessageType.INTERNAL_SERVER_ERR);
     m.send(serv.sock);
     throw new IOException(e);
   } catch (GenericException e) {
     Message m = new Message(MessageType.INTERNAL_SERVER_ERR);
     m.send(serv.sock);
     throw new IOException(e.getMessage());
   }
 }
Пример #24
0
 public static void receive(Message message) {
   enqueueRunnable(message.getMessageType(), new MessageDeliveryTask(message));
 }