Ejemplo n.º 1
0
  /**
   * When data is available on the socket, this method is called to run the command or throw an
   * error if it can't.
   *
   * @throws SocketServerException
   */
  private void handleClientData() throws SocketServerException {
    try {
      input.setLength(0); // clear

      String res;
      int a;
      // (char) -1 is not equal to -1.
      // ready is checked to ensure the read call doesn't block.
      while ((a = in.read()) != -1 && in.ready()) {
        input.append((char) a);
      }
      String inputString = input.toString();
      Logger.debug("Got data from client: " + inputString);
      try {
        AndroidCommand cmd = getCommand(inputString);
        Logger.debug("Got command of type " + cmd.commandType().toString());
        res = runCommand(cmd);
        Logger.debug("Returning result: " + res);
      } catch (final CommandTypeException e) {
        res = new AndroidCommandResult(WDStatus.UNKNOWN_ERROR, e.getMessage()).toString();
      } catch (final JSONException e) {
        res =
            new AndroidCommandResult(WDStatus.UNKNOWN_ERROR, "Error running and parsing command")
                .toString();
      }
      out.write(res);
      out.flush();
    } catch (final IOException e) {
      throw new SocketServerException(
          "Error processing data to/from socket (" + e.toString() + ")");
    }
  }
Ejemplo n.º 2
0
 /**
  * When {@link #handleClientData()} has valid data, this method delegates the command.
  *
  * @param cmd AndroidCommand
  * @return Result
  */
 private String runCommand(final AndroidCommand cmd) {
   AndroidCommandResult res;
   if (cmd.commandType() == AndroidCommandType.SHUTDOWN) {
     keepListening = false;
     res = new AndroidCommandResult(WDStatus.SUCCESS, "OK, shutting down");
   } else if (cmd.commandType() == AndroidCommandType.ACTION) {
     try {
       res = executor.execute(cmd);
     } catch (
         final Exception
             e) { // Here we catch all possible exceptions and return a JSON Wire Protocol
       // UnknownError
       // This prevents exceptions from halting the bootstrap app
       res = new AndroidCommandResult(WDStatus.UNKNOWN_ERROR, e.getMessage());
     }
   } else {
     // this code should never be executed, here for future-proofing
     res =
         new AndroidCommandResult(
             WDStatus.UNKNOWN_ERROR, "Unknown command type, could not execute!");
   }
   return res.toString();
 }