Beispiel #1
0
 /**
  * Returns an array of the URI strings of all the connected brokers.
  *
  * @return Array of broker URI strings of all the connected brokers.
  */
 protected String[] getBrokerURIList() {
   String[] brokerList = new String[brokerStates.size()];
   int i = 0;
   for (NodeAddress addr : brokerStates.keySet()) {
     brokerList[i++] = addr.getNodeURI();
   }
   return brokerList;
 }
Beispiel #2
0
  /**
   * Connects to a broker with the given URI. The given URI should conform to an accepted
   * communication protocol format.
   *
   * @param brokerURI URI of the broker to connect to.
   * @return A BrokerState data structure to keep track of the state of the connection and related
   *     operation
   * @throws ClientException In case the given URI is malformated, a connection already exists to
   *     the specified broker, or a communication error is occurred.
   * @see BrokerState, NodeAddress
   */
  public BrokerState connect(String brokerURI) throws ClientException {
    try {
      NodeAddress brokerAddr = ConnectionHelper.getAddress(brokerURI);
      if (brokerStates.containsKey(brokerAddr)) {
        throw new ClientException("Server connection already exists");
      } else {
        if (brokerStates.size() == 0) setDefaultBrokerAddress(brokerAddr);
        MessageSender msgSender = commSystem.getMessageSender(brokerURI);
        BrokerState bState = addBrokerState(brokerAddr, msgSender);

        msgSender.connect(
            MessageDestination.formatClientDestination(clientID, brokerAddr.getNodeURI()),
            msgListener);
        return bState;
      }
    } catch (CommunicationException e) {
      exceptionLogger.error("Could not connect to broker: " + e);
      throw new ClientException("Could not connect to broker: " + e.getMessage(), e);
    }
  }
Beispiel #3
0
  public static NodeAddress lookupNode(byte[] id, NodeAddress seedNodeAddress, int serverPort)
      throws Exception {
    // start up a server socket to accept the connection
    ServerSocket serverSocket = new ServerSocket(serverPort);

    // send store data message to random node
    LookupNodeMsg lookupNodeMsg =
        new LookupNodeMsg(id, new NodeAddress("StoreData", null, serverPort), 0);
    lookupNodeMsg.addHop(seedNodeAddress);
    Socket seedSocket = new Socket(seedNodeAddress.getInetAddress(), seedNodeAddress.getPort());
    ObjectOutputStream seedOut = new ObjectOutputStream(seedSocket.getOutputStream());
    seedOut.writeObject(lookupNodeMsg);

    seedSocket.close();
    LOGGER.info(
        "Sent lookup node message with id '"
            + HexConverter.convertBytesToHex(id)
            + "' to node "
            + seedNodeAddress);

    // receive connection on server socket from node where data should reside
    Socket nodeSocket = serverSocket.accept();
    Message replyMsg = (Message) new ObjectInputStream(nodeSocket.getInputStream()).readObject();

    // ensure we get a node info message
    if (replyMsg.getMsgType() == Message.ERROR_MSG) {
      throw new Exception(((ErrorMsg) replyMsg).getMsg());
    } else if (replyMsg.getMsgType() != Message.NODE_INFO_MSG) {
      throw new Exception("Recieved an unexpected message type '" + replyMsg.getMsgType() + "'.");
    }

    // parse reply message
    NodeInfoMsg nodeInfoMsg = (NodeInfoMsg) replyMsg;
    if (nodeInfoMsg.getNodeAddress().getInetAddress() == null) {
      nodeInfoMsg.getNodeAddress().setInetAddress(nodeSocket.getInetAddress());
    }

    serverSocket.close();
    nodeSocket.close();
    return nodeInfoMsg.getNodeAddress();
  }
Beispiel #4
0
  /**
   * Send a subscription to a broker with the given URI. In case the brokerURI is null, the
   * subscription will be sent to the default broker.
   *
   * @param sub The subscription to be sent.
   * @param brokerURI The broker to which the subscription is to be sent.
   * @return The SubscriptionMessage containing the given subscription.
   * @throws ClientException Upon the following situations:
   *     <ul>
   *       <li>The client is not connected to the specified broker.
   *       <li>Given brokerURI is badly formated.
   *       <li>There is an error in sending the subscription message.
   *     </ul>
   */
  public SubscriptionMessage subscribe(Subscription sub, String brokerURI) throws ClientException {
    if (!isConnected()) throw new ClientException("Not connected to any broker");
    try {
      if (brokerURI == null || brokerURI.equals("")) brokerURI = defaultBrokerAddress.getNodeURI();
      BrokerState brokerState = getBrokerState(brokerURI);
      if (brokerState == null) {
        throw new ClientException("Not connected to broker " + brokerURI);
      }
      MessageDestination clientDest =
          MessageDestination.formatClientDestination(
              clientID, brokerState.getBrokerAddress().getNodeURI());
      SubscriptionMessage subMsg =
          new SubscriptionMessage(
              sub, getNextMessageID(brokerState.getBrokerAddress().getNodeURI()), clientDest);

      // TODO: fix this hack for historic queries
      Map<String, Predicate> predMap = subMsg.getSubscription().getPredicateMap();
      if (predMap.get("_start_time") != null) {
        SimpleDateFormat timeFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
        try {
          Date startTime = timeFormat.parse((String) (predMap.get("_start_time")).getValue());
          predMap.remove("_start_time");
          subMsg.setStartTime(startTime);
        } catch (java.text.ParseException e) {
          exceptionLogger.error("Fail to convert Date format : " + e);
        }
      }
      if (predMap.get("_end_time") != null) {
        SimpleDateFormat timeFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
        try {
          Date endTime = timeFormat.parse((String) (predMap.get("_end_time")).getValue());
          predMap.remove("_end_time");
          subMsg.setEndTime(endTime);
        } catch (java.text.ParseException e) {
          exceptionLogger.error("Fail to convert Date format : " + e);
        }
      }

      String msgID = brokerState.getMsgSender().send(subMsg, HostType.CLIENT);
      subMsg.setMessageID(msgID);
      if (clientConfig.detailState) brokerState.addSubMsg(subMsg);
      return subMsg;
    } catch (CommunicationException e) {
      throw new ClientException(e.getMessage());
    }
  }
Beispiel #5
0
 public PublicationMessage publish(Publication pub, String brokerURI) throws ClientException {
   if (!isConnected()) throw new ClientException("Not connected to any broker");
   try {
     if (brokerURI == null || brokerURI.trim().length() == 0)
       brokerURI = defaultBrokerAddress.getNodeURI();
     BrokerState brokerState = getBrokerState(brokerURI);
     if (brokerState == null) {
       throw new ClientException("Not connected to broker " + brokerURI);
     }
     MessageDestination clientDest =
         MessageDestination.formatClientDestination(
             clientID, brokerState.getBrokerAddress().getNodeURI());
     PublicationMessage pubMsg =
         new PublicationMessage(
             pub, getNextMessageID(brokerState.getBrokerAddress().getNodeURI()), clientDest);
     pubCount++;
     String msgID = brokerState.getMsgSender().send(pubMsg, HostType.CLIENT);
     pubMsg.setMessageID(msgID);
     return pubMsg;
   } catch (CommunicationException e) {
     throw new ClientException(e.getMessage());
   }
 }
Beispiel #6
0
 /**
  * Sends an advertisement to a given broker.
  *
  * @param adv The advertisement to be sent. It is an {@link Advertisement} object.
  * @param brokerURI The URI of the broker to where the advertisement is sent.
  * @return The {@link AdvertisementMessage} produced by the given advertisement. The message ID of
  *     the message is returned by the broker.
  * @throws ClientException If the given URI is malformatted, the client is not connected to the
  *     broker, or there is a communication error while sending the advertisement.
  */
 public AdvertisementMessage advertise(Advertisement adv, String brokerURI)
     throws ClientException {
   if (!isConnected()) throw new ClientException("Not connected to any broker");
   try {
     if (brokerURI == null || brokerURI.equals("")) brokerURI = defaultBrokerAddress.getNodeURI();
     BrokerState brokerState = getBrokerState(brokerURI);
     if (brokerState == null) {
       throw new ClientException("Not connected to broker " + brokerURI);
     }
     MessageDestination clientDest =
         MessageDestination.formatClientDestination(
             clientID, brokerState.getBrokerAddress().getNodeURI());
     AdvertisementMessage advMsg =
         new AdvertisementMessage(
             adv, getNextMessageID(brokerState.getBrokerAddress().getNodeURI()), clientDest);
     String msgID = brokerState.getMsgSender().send(advMsg, HostType.CLIENT);
     advMsg.setMessageID(msgID);
     if (clientConfig.detailState) brokerState.addAdvMsg(advMsg);
     return advMsg;
   } catch (CommunicationException e) {
     throw new ClientException(e.getMessage());
   }
 }
Beispiel #7
0
 public CompositeSubscriptionMessage subscribeCS(CompositeSubscription cs, String brokerURI)
     throws ClientException {
   if (!isConnected()) throw new ClientException("Not connected to any broker");
   try {
     if (brokerURI == null || brokerURI.trim().equals(""))
       brokerURI = defaultBrokerAddress.getNodeURI();
     BrokerState brokerState = getBrokerState(brokerURI);
     if (brokerState == null) {
       throw new ClientException("Not connected to broker " + brokerURI);
     }
     MessageDestination clientDest =
         MessageDestination.formatClientDestination(
             clientID, brokerState.getBrokerAddress().getNodeURI());
     CompositeSubscriptionMessage newCSMsg =
         new CompositeSubscriptionMessage(
             cs, getNextMessageID(brokerState.getBrokerAddress().getNodeURI()), clientDest);
     String msgID = brokerState.getMsgSender().send(newCSMsg, HostType.CLIENT);
     newCSMsg.setMessageID(msgID);
     if (clientConfig.detailState) brokerState.addCSSubMsg(newCSMsg);
     return newCSMsg;
   } catch (CommunicationException e) {
     throw new ClientException(e.getMessage());
   }
 }
Beispiel #8
0
  public static void main(String[] args) {
    int port = 0;
    String discoveryNodeAddr = null;
    int discoveryNodePort = 0;

    try {
      port = Integer.parseInt(args[0]);
      discoveryNodeAddr = args[1];
      discoveryNodePort = Integer.parseInt(args[2]);
    } catch (Exception e) {
      System.out.println("Usage: Client port controllerHosName controllerPort");
      System.exit(1);
    }

    String input = "";
    Scanner scanner = new Scanner(System.in);
    while (true) {
      try {
        System.out.print("Options\nS) Store File\nR) Retrieve File\nQ) Quit\nInput:");
        input = scanner.nextLine();

        if (input.equalsIgnoreCase("Q")) {
          break;
        } else if (!input.equalsIgnoreCase("S") && !input.equalsIgnoreCase("R")) {
          LOGGER.severe("Unknown input. Please reenter.");
          continue;
        }

        // read in the filename
        byte[] id = null;
        System.out.print("\tFilename:");
        File file = new File(scanner.nextLine());

        // read in id
        System.out.print("\tID (leave blank to auto generate one):");
        String idStr = scanner.nextLine();
        if (!idStr.equals("")) {
          id = HexConverter.convertHexToBytes(idStr);
        } else {
          short idValue = (short) (file.getName().hashCode() % (int) Short.MAX_VALUE);
          id = new byte[2];
          id[0] = (byte) (idValue & 0xff);
          id[1] = (byte) ((idValue >> 8) & 0xff);
        }

        // get random node
        NodeAddress seedNodeAddress = getRandomNode(discoveryNodeAddr, discoveryNodePort);

        // lookup id in cluster
        NodeAddress nodeAddress = lookupNode(id, seedNodeAddress, port);

        if (input.equalsIgnoreCase("S")) {
          if (!file.exists()) {
            throw new Exception("File '" + file.getName() + "' does not exist.");
          }

          // read data into buffer
          FileInputStream in = new FileInputStream(file);
          byte[] data = new byte[(int) file.length()];
          if (in.read(data) != data.length) {
            LOGGER.severe("Error reading data into buffer.");
            return;
          }

          in.close();

          // write data to the node
          WriteDataMsg writeDataMsg = new WriteDataMsg(id, data);
          Socket socket = new Socket(nodeAddress.getInetAddress(), nodeAddress.getPort());
          ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
          out.writeObject(writeDataMsg);

          socket.close();
          LOGGER.info(
              "Sent data with id '"
                  + HexConverter.convertBytesToHex(id)
                  + "' to node "
                  + nodeAddress
                  + ".");
        } else if (input.equalsIgnoreCase("R")) {
          // read in storage directory
          System.out.print("\tStorage Directory:");
          file = new File(scanner.nextLine() + File.separator + file.getName());
          file.getParentFile().mkdirs();

          // request file from node
          ReadDataMsg readDataMsg = new ReadDataMsg(id);
          Socket socket = new Socket(nodeAddress.getInetAddress(), nodeAddress.getPort());
          ObjectOutputStream socketOut = new ObjectOutputStream(socket.getOutputStream());
          socketOut.writeObject(readDataMsg);

          // parse reply message
          Message replyMsg = (Message) new ObjectInputStream(socket.getInputStream()).readObject();
          socket.close();

          if (replyMsg.getMsgType() == Message.ERROR_MSG) {
            throw new Exception(((ErrorMsg) replyMsg).getMsg());
          } else if (replyMsg.getMsgType() != Message.WRITE_DATA_MSG) {
            throw new Exception(
                "Recieved an unexpected message type '" + replyMsg.getMsgType() + "'.");
          }

          WriteDataMsg writeDataMsg = (WriteDataMsg) replyMsg;

          // write file contents
          FileOutputStream out = new FileOutputStream(file);
          for (byte b : writeDataMsg.getData()) {
            out.write(b);
          }

          out.close();
          LOGGER.info("Wrote data to file '" + file.getCanonicalPath() + "'.");
        } else if (!input.equalsIgnoreCase("Q")) {
          LOGGER.severe("Unknown input. Please reenter.");
        }
      } catch (Exception e) {
        e.printStackTrace();
        LOGGER.severe(e.getMessage());
      }
    }
  }
Beispiel #9
0
 /**
  * To specify the default broker of the client. When no broker is specified, all pub/sub
  * operations will be carried out through this broker.
  *
  * @param brokerAddress
  */
 public void setDefaultBrokerAddress(NodeAddress brokerAddress) {
   defaultBrokerAddress = brokerAddress;
   defaultClientDest =
       MessageDestination.formatClientDestination(clientID, defaultBrokerAddress.getNodeURI());
 }
Beispiel #10
0
 /**
  * To set the ID of the client. Note the presence of a unique/invariant client ID is important for
  * the correct operation of a client. Therefore, if you are using this method, make sure that you
  * are using it before any of the pub/sub operation is used.
  *
  * <p>To be on the same side, don't use this method if you are not absolutely sure of what you are
  * doing.
  *
  * @param id
  */
 public void setClientID(String id) {
   clientID = id;
   if (defaultBrokerAddress != null)
     defaultClientDest =
         MessageDestination.formatClientDestination(clientID, defaultBrokerAddress.getNodeURI());
 }