public static String getCookie(String name, HttpExchange t) {
   String cstr = t.getRequestHeaders().getFirst("Cookie");
   if (!StringUtils.isEmpty(cstr)) {
     name += "=";
     for (String str : cstr.trim().split("\\s*;\\s*")) {
       if (str.startsWith(name)) {
         return str.substring(name.length());
       }
     }
   }
   LOGGER.debug("Cookie '{}' not found: {}", name, t.getRequestHeaders().get("Cookie"));
   return null;
 }
  public void handle(HttpExchange exchange) throws IOException {
    InputStream is = exchange.getRequestBody();
    BufferedReader in = new BufferedReader(new InputStreamReader(is));
    String requestMethod = exchange.getRequestMethod();

    CharBuffer cb = CharBuffer.allocate(256);

    // read characters into a char buffer
    in.read(cb);

    // flip the char buffer
    cb.flip();

    // print the char buffer

    Headers responseHeaders = exchange.getResponseHeaders();
    responseHeaders.set("Content-Type", "application/json");
    responseHeaders.set("Access-Control-Allow-Origin", "http://minecraft-social.de");

    exchange.sendResponseHeaders(200, 0);
    OutputStream responseBody = exchange.getResponseBody();
    Headers requestHeaders = exchange.getRequestHeaders();

    responseBody.write(getOnlineUser().getBytes());
    responseBody.close();
  }
Example #3
0
  public void handle(HttpExchange x) throws IOException {
    /* Only allow GET */
    if (!"GET".equals(x.getRequestMethod())) {
      x.sendResponseHeaders(501, -1);
      return;
    }

    /* If they supply the right ETag, let them know
     *  the content hasn't changed.
     */
    List<String> inm = x.getRequestHeaders().get("If-None-Match");
    if (inm != null && inm.contains(etag)) {
      x.sendResponseHeaders(304, 0);
      x.getResponseBody().close();
      return;
    }

    /* Provide the content */
    x.getResponseHeaders().add("Content-Type", "text/plain");
    x.getResponseHeaders().add("ETag", etag);
    x.sendResponseHeaders(200, 0);

    InputStream in = content.openStream();

    OutputStream bdy = x.getResponseBody();

    byte[] buffer = new byte[65535];

    int l;

    while ((l = in.read(buffer)) >= 0) {
      bdy.write(buffer, 0, l);
    }
    bdy.close();
  }
Example #4
0
  public static MultivaluedMap<String, String> extractRequestHeaders(HttpExchange request) {
    Headers<String> requestHeaders = new Headers<String>();

    for (Map.Entry<String, List<String>> header : request.getRequestHeaders().entrySet()) {
      for (String val : header.getValue()) {
        requestHeaders.add(header.getKey(), val);
      }
    }
    return requestHeaders;
  }
 public static WebRender matchRenderer(String user, HttpExchange t) {
   int browser = WebRender.getBrowser(t.getRequestHeaders().getFirst("User-agent"));
   String confName = WebRender.getBrowserName(browser);
   RendererConfiguration r =
       RendererConfiguration.find(confName, t.getRemoteAddress().getAddress());
   return ((r instanceof WebRender)
           && (StringUtils.isBlank(user) || user.equals(((WebRender) r).getUser())))
       ? (WebRender) r
       : null;
 }
  public void handle(HttpExchange xchg) throws IOException {
    Headers headers = xchg.getRequestHeaders();
    Set<Map.Entry<String, List<String>>> entries = headers.entrySet();

    StringBuffer response = new StringBuffer();
    for (Map.Entry<String, List<String>> entry : entries) response.append(entry.toString() + "\n");

    xchg.sendResponseHeaders(200, response.length());
    OutputStream os = xchg.getResponseBody();
    os.write(response.toString().getBytes());
    os.close();
  }
  public static LinkedHashSet<String> getLangs(HttpExchange t) {
    String hdr = t.getRequestHeaders().getFirst("Accept-language");
    LinkedHashSet<String> result = new LinkedHashSet<>();
    if (StringUtils.isEmpty(hdr)) {
      return result;
    }

    String[] tmp = hdr.split(",");
    for (String language : tmp) {
      String[] l1 = language.split(";");
      result.add(l1[0]);
    }
    return result;
  }
    @Override
    public void handle(HttpExchange httpExchange) throws IOException {
      ++testConnectionTimeoutCount;
      Logger.info(
          this,
          "testCommonResponseHandler testConnectionTimeoutCount: " + testConnectionTimeoutCount);

      Logger.info(
          this, String.format("request headers:%s", httpExchange.getRequestHeaders().entrySet()));
      Logger.info(this, String.format("request method:%s", httpExchange.getRequestMethod()));
      Logger.info(this, String.format("request uri:%s", httpExchange.getRequestURI()));
      Logger.info(this, String.format("request body:%s", httpExchange.getRequestBody()));

      String resp = "OK";
      httpExchange.sendResponseHeaders(200, resp.getBytes().length);
      httpExchange.getResponseBody().write(resp.getBytes());
      httpExchange.close();
    }
    // Handles all incoming webhook notifications
    public void handle(HttpExchange t) throws IOException {

      System.out.println("Request received");

      // Reject non-POST requests
      if (!t.getRequestMethod().equals("POST")) {
        t.sendResponseHeaders(405, 0);
        t.getResponseBody().close();
      }

      Headers requestHeaders = t.getRequestHeaders();
      String callbackSignature = requestHeaders.get("X-square-signature").get(0);
      String callbackBody = IOUtils.toString(t.getRequestBody(), (String) null);

      if (!isValidCallback(callbackBody, callbackSignature)) {
        System.out.println("Webhook event with invalid signature detected!");
        t.sendResponseHeaders(200, 0);
        t.getResponseBody().close();
        return;
      }

      JSONObject requestBody = new JSONObject(callbackBody);
      if (requestBody.has("event_type")
          && requestBody.getString("event_type").equals("PAYMENT_UPDATED")) {

        // Get the ID of the updated payment
        String paymentId = requestBody.getString("entity_id");

        // Get the ID of the payment's associated location
        String locationId = requestBody.getString("location_id");
        HttpResponse<JsonNode> response;
        try {
          response =
              Unirest.get(_connectHost + "/v1/" + locationId + "/payments/" + paymentId).asJson();
        } catch (UnirestException e) {
          System.out.println("Failed to retrieve payment details");
          return;
        }
        System.out.println(response.getBody().getObject());
      }

      t.sendResponseHeaders(200, 0);
      t.getResponseBody().close();
    }
Example #10
0
  @Override
  public boolean handle(final HttpExchange t) throws IOException {
    LOGGER.info(
        "Handling {} from {}", t.getRequestMethod(), t.getRequestHeaders().getFirst("Host"));

    JSONObject response = null;
    // We default to error status in order to guarantee that HTTP_OK is only
    // responded if everything went well
    int responseStatus = QueryHandlerHelper.HTTP_INTERNAL_SERVER_ERROR;

    try {
      // Only process POST requests
      final String requestMethod = t.getRequestMethod();
      if (!requestMethod.equalsIgnoreCase("POST")) {
        LOGGER.info("Received {}, but only POST is allowed", requestMethod);
        t.getResponseHeaders().add("Allow", "POST");
        response = new JSONObject();
        response.put("error", "Only POSTs will be processed.");
        responseStatus = QueryHandlerHelper.HTTP_METHOD_NOT_ALLOWED;
        return true;
      }

      // Parse the request
      InfoQueryParameters parameters = null;
      try {
        final String requestBody = IOUtils.toString(t.getRequestBody());
        parameters = InfoQueryParameters.getParametersFromJson(requestBody);
      } catch (final RuntimeException e) {
        LOGGER.info("Bad request: {}", e.getMessage());
        if (e.getCause() != null) {
          LOGGER.info("Cause: {}", e.getCause().toString());
        }
        response = new JSONObject();
        response.put("error", e.getMessage());
        responseStatus = QueryHandlerHelper.HTTP_BAD_REQUEST;
        return true;
      }

      LOGGER.info("Received query: {}", parameters.QUERY);
      LOGGER.info("Using evaluator with index: {}", parameters.EVALUATOR_INDEX);
      LOGGER.info("Requested AST format is: {}", parameters.AST_FORMAT);

      if (this.RIF_EVALUATION) {
        LOGGER.info("Starting processing RIF");
      } else {
        LOGGER.info("Starting processing SPARQL");
      }
      Triple<GraphWrapper, String, GraphWrapper> result = null;
      try {
        // Use the magic getCompileInfo method
        result =
            EvaluationHelper.getCompileInfo(
                parameters.EVALUATOR_INDEX, this.RIF_EVALUATION, parameters.QUERY);
      } catch (TokenMgrError
          | ParseException
          | QueryParseException
          | MalformedQueryException
          | lupos.rif.generated.parser.ParseException
          | lupos.rif.generated.parser.TokenMgrError e) {
        LOGGER.info("Malformed query: {}", e.getMessage());
        final Triple<Integer, Integer, String> detailedError =
            EvaluationHelper.dealWithThrowableFromQueryParser(e);
        final Integer line = detailedError.getFirst();
        final Integer column = detailedError.getSecond();
        final String error = detailedError.getThird();

        final JSONObject errorJson = new JSONObject();
        if (line != -1) {
          errorJson.put("line", line);
        }
        if (column != -1) {
          errorJson.put("column", column);
        }
        errorJson.put("errorMessage", error);
        response = new JSONObject();
        response.put("queryError", errorJson);
        // We send HTTP_OK, because the actual HTTP request was correct
        responseStatus = QueryHandlerHelper.HTTP_OK;
        return true;
      }
      LOGGER.info("Finished processing");

      final JSONObject responseTmp = new JSONObject();
      if (result == null) {
        responseTmp.put("info", "Compiler does not provide additional information.");
      } else {
        if (this.RIF_EVALUATION) {
          final GraphWrapperASTRIF ast = (GraphWrapperASTRIF) result.getFirst();
          final GraphWrapperRules astRules = (GraphWrapperRules) result.getThird();
          if (ast != null) {
            responseTmp.put("AST", GraphSerialization.rifAstToJson(ast, parameters.AST_FORMAT));
          }
          if (astRules != null) {
            responseTmp.put(
                "rulesAST", GraphSerialization.rulesAstToJson(astRules, parameters.AST_FORMAT));
          }
        } else {
          final GraphWrapperAST ast = (GraphWrapperAST) result.getFirst();
          final String coreQuery = result.getSecond();
          final GraphWrapperAST coreAst = (GraphWrapperAST) result.getThird();
          if (ast != null) {
            responseTmp.put("AST", GraphSerialization.astToJson(ast, parameters.AST_FORMAT));
          }
          if (coreQuery != null) {
            responseTmp.put("coreSPARQL", result.getSecond());
          }
          if (coreAst != null) {
            responseTmp.put(
                "coreAST", GraphSerialization.astToJson(coreAst, parameters.AST_FORMAT));
          }
        }
      }
      responseStatus = QueryHandlerHelper.HTTP_OK;
      response = responseTmp;
    } catch (final Exception e) {
      LOGGER.error("Encountered exception {}", e.toString(), e);
      response = new JSONObject();
      response.put("error", e.toString());
      responseStatus = QueryHandlerHelper.HTTP_OK;
    } finally {
      QueryHandlerHelper.sendResponse(t, response, responseStatus);
    }
    return (t != null);
  }
  public RootFolder getRoot(String user, boolean create, HttpExchange t) {
    String groupTag = getTag(user);
    String cookie = RemoteUtil.getCookie("UMS", t);
    RootFolder root;
    synchronized (roots) {
      root = roots.get(cookie);
      if (root == null) {
        // Double-check for cookie errors
        WebRender valid = RemoteUtil.matchRenderer(user, t);
        if (valid != null) {
          // A browser of the same type and user is already connected at
          // this ip but for some reason we didn't get a cookie match.
          RootFolder validRoot = valid.getRootFolder();
          // Do a reverse lookup to see if it's been registered
          for (Map.Entry<String, RootFolder> entry : roots.entrySet()) {
            if (entry.getValue() == validRoot) {
              // Found
              root = validRoot;
              cookie = entry.getKey();
              LOGGER.debug(
                  "Allowing browser connection without cookie match: {}: {}",
                  valid.getRendererName(),
                  t.getRemoteAddress().getAddress());
              break;
            }
          }
        }
      }

      if (!create || (root != null)) {
        t.getResponseHeaders().add("Set-Cookie", "UMS=" + cookie + ";Path=/");
        return root;
      }

      ArrayList<String> tag = new ArrayList<>();
      tag.add(user);
      if (!groupTag.equals(user)) {
        tag.add(groupTag);
      }

      tag.add(t.getRemoteAddress().getHostString());
      tag.add("web");
      root = new RootFolder(tag);
      try {
        WebRender render = new WebRender(user);
        root.setDefaultRenderer(render);
        render.setRootFolder(root);
        render.associateIP(t.getRemoteAddress().getAddress());
        render.associatePort(t.getRemoteAddress().getPort());
        if (configuration.useWebSubLang()) {
          render.setSubLang(StringUtils.join(RemoteUtil.getLangs(t), ","));
        }
        //				render.setUA(t.getRequestHeaders().getFirst("User-agent"));
        render.setBrowserInfo(
            RemoteUtil.getCookie("UMSINFO", t), t.getRequestHeaders().getFirst("User-agent"));
        PMS.get().setRendererFound(render);
      } catch (ConfigurationException e) {
        root.setDefaultRenderer(RendererConfiguration.getDefaultConf());
      }
      // root.setDefaultRenderer(RendererConfiguration.getRendererConfigurationByName("web"));
      root.discoverChildren();
      cookie = UUID.randomUUID().toString();
      t.getResponseHeaders().add("Set-Cookie", "UMS=" + cookie + ";Path=/");
      roots.put(cookie, root);
    }
    return root;
  }
Example #12
0
  /**
   * creates a new command based on which /move/ method is called and executes that command one the
   * correct game.
   *
   * @post the command is executed correctly. If invalid params, returns 400. If error in server,
   *     returns 500.
   */
  @Override
  public void handle(HttpExchange exchange) throws IOException {
    String extension = "";
    System.out.println("move handler");
    String json = jsonStringFromExchange(exchange.getRequestBody());
    System.out.println(json);
    Input input = new Gson().fromJson(json, Input.class);
    switch (input.getMethod()) {
      case "/moves/sendChat":
        extension = "sent a chat";
        command = new SendChatCommand();
        break;
      case "/moves/rollNumber":
        extension = "rolled a ";
        System.out.println(extension);
        command = new RollNumberCommand();
        break;
      case "/moves/robPlayer":
        extension = "burgled a player";
        command = new RobPlayerCommand();
        break;
      case "/moves/finishTurn":
        extension = "finished his/her turn";
        command = new FinishTurnCommand();
        break;
      case "/moves/buyDevCard":
        extension = "bought a dev card";
        command = new BuyDevCardCommand();
        break;
      case "/moves/Year_of_Plenty":
        extension = "cast Year-of-Plenty";
        command = new PlayYearOfPlentyCommand();
        break;
      case "/moves/Road_Building":
        extension = "cast Road-Building";
        command = new PlayRoadBuildingCommand();
        break;
      case "/moves/Soldier":
        extension = "Sent a Chat";
        command = new PlaySoldierCommand();
        break;
      case "/moves/Monument":
        extension = "cast Monument";
        command = new PlayMonumentCommand();
        break;
      case "/moves/Monopoly":
        extension = "cast Monopoly";
        command = new PlayMonopolyCommand();
        break;
      case "/moves/buildRoad":
        extension = "built a road";
        command = new BuildRoadCommand();
        break;
      case "/moves/buildCity":
        extension = "built a city";
        command = new BuildCityCommand();
        break;
      case "/moves/buildSettlement":
        extension = "built a settlement";
        command = new BuildSettlementCommand();
        break;
      case "/moves/offerTrade":
        extension = "offered a trade";
        command = new OfferTradeCommand();
        break;
      case "/moves/acceptTrade":
        extension = "accepted a trade";
        command = new AcceptTradeCommand();
        break;
      case "/moves/maritimeTrade":
        extension = "traded with pirates";
        command = new MaritimeTradeCommand();
        break;
      case "/moves/discardCards":
        extension = "sent his cards to the graveyard";
        command = new DiscardCardsCommand();
        break;
    }

    String cookie = exchange.getRequestHeaders().getFirst("Cookie");
    String[] cookieArray = cookie.split(";");

    if (command != null && cookieArray.length == 2) {
      try {
        System.out.println("q");
        String gameCookie = cookieArray[1].trim();
        StringBuilder temp = new StringBuilder(gameCookie);
        System.out.println("w");
        int index = temp.lastIndexOf("catan.game=") + 11;
        int gameId = Integer.parseInt(temp.substring(index, temp.length()));
        System.out.println("e");
        GameModel model = GameHub.getInstance().getModel(gameId);
        System.out.println("r");
        MoveCommand moveCommand = (MoveCommand) command;
        moveCommand.setGameModel(model);
        moveCommand.setInput(json);
        System.out.println("t");
        GameModel updatedModel = (GameModel) moveCommand.execute(json);
        GameHub.getInstance().updateModel(updatedModel);
        System.out.println("y");
        // add log to GameHistory
        gameCookie = cookieArray[0].trim();
        temp = new StringBuilder(gameCookie);
        System.out.println("u");
        index = temp.lastIndexOf("catan.user="******"i");
        if (extension.equals("rolled a ")) {
          System.out.println("o");
          RollNumberInput rollInput = new ObjectMapper().readValue(json, RollNumberInput.class);
          extension = extension + rollInput.getNumber();
        }
        if (extension.equals("accepted a trade")) {
          System.out.println("p");
          AcceptTradeInput atinput = new ObjectMapper().readValue(json, AcceptTradeInput.class);
          if (!atinput.isWillAccept()) extension = "rejected a trade";
        }
        System.out.println("a");
        String message = name + " " + extension + ".";
        System.out.printf("message %s and id %d\n", message, pId);
        LogEntry le = new LogEntry(cc, message);
        GameHub.getInstance().getModel(gameId).getLogs().add(le);
        // finished with log

        exchange.getResponseHeaders().set("Content-Type", "text/html");
        exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0);

        // write to response body
        Writer writer = new OutputStreamWriter(exchange.getResponseBody());
        String toWrite = new ObjectMapper().writeValueAsString(updatedModel);
        writer.write(toWrite);
        writer.close();

        exchange.getResponseBody().close();

        // add command to persistence
        GameHub.getInstance().getGameDAO().addCommand(gameId, moveCommand);

      } catch (ServerException e) {
        exchange.sendResponseHeaders(HttpURLConnection.HTTP_BAD_REQUEST, -1);
      }
    } else {
      exchange.sendResponseHeaders(HttpURLConnection.HTTP_BAD_REQUEST, -1);
    }
  }
 @Override
 @Property(value = {MessageContext.HTTP_REQUEST_HEADERS, Packet.INBOUND_TRANSPORT_HEADERS})
 public @NotNull Map<String, List<String>> getRequestHeaders() {
   return httpExchange.getRequestHeaders();
 }
Example #14
0
  public void handle(HttpExchange exchange) throws IOException {

    String requestMethod = exchange.getRequestMethod();

    if (requestMethod.equalsIgnoreCase("GET")) {
      Headers responseHeaders = exchange.getResponseHeaders();
      InetSocketAddress cIP = exchange.getRemoteAddress();
      OutputStream responseBody = exchange.getResponseBody();
      Headers requestHeaders = exchange.getRequestHeaders();
      Set<String> keySet = requestHeaders.keySet();
      URI path = exchange.getRequestURI();

      System.out.println("GET " + path.toString() + " " + cIP.toString());

      String urlParts[] = path.toString().split("/");
      String response = "";
      // System.out.println(urlParts.length);

      if (urlParts.length == 8) {

        String[] clrt = StringUtils.split(urlParts[7], ".");
        if (clrt[1].equalsIgnoreCase("json")
            || clrt[1].equalsIgnoreCase("xml")
            || clrt[1].equalsIgnoreCase("plain")) {
          HTTPCassandra CassInterface = new HTTPCassandra();

          String res[] = CassInterface.handleGET(urlParts);

          if (res[0].equals("200")) {
            response = res[1];
            responseHeaders.set("Content-Type", res[2]);
            exchange.sendResponseHeaders(200, response.length());
          } else {
            responseHeaders.set("Content-Type", "text/html");
            response = "<h1>" + res[1] + "</h1>";
            exchange.sendResponseHeaders(Integer.parseInt(res[0]), response.length());
          }
        } else {
          responseHeaders.set("Content-Type", "text/html");
          response = "<h1>Unsupported Media Type</h1>";
          exchange.sendResponseHeaders(415, response.length());
        }

      } else if (urlParts.length == 0) {
        if (path.toString().equals("/")) {
          String str, page = "";
          try {
            Process p = Runtime.getRuntime().exec("pwd");
            String s = null;
            BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

            BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

            // read the output from the command
            while ((s = stdInput.readLine()) != null) {
              System.out.println(s);
            }

            BufferedReader in = new BufferedReader(new FileReader("../html/test.htm"));
            while ((str = in.readLine()) != null) {
              page = page + str;
            }
            in.close();
          } catch (IOException e) {
            System.out.println("Failed to read in file");
          }
          response = page;
          responseHeaders.set("Content-Type", "text/html");
          exchange.sendResponseHeaders(200, response.length());
        } else {
          responseHeaders.set("Content-Type", "text/html");
          response = "<H1>RESTandra - 400 Bad Request</H1>";
          exchange.sendResponseHeaders(400, response.length());
        }
      } else {
        responseHeaders.set("Content-Type", "text/html");
        String error[] = lengthError(urlParts.length);
        response = error[1];
        exchange.sendResponseHeaders(Integer.parseInt(error[0]), response.length());
      }
      responseBody.write(response.getBytes());
      responseBody.close();
    } else if (requestMethod.equalsIgnoreCase("POST")) {
      Headers responseHeaders = exchange.getResponseHeaders();
      InetSocketAddress cIP = exchange.getRemoteAddress();
      OutputStream responseBody = exchange.getResponseBody();
      Headers requestHeaders = exchange.getRequestHeaders();
      URI path = exchange.getRequestURI();
      BufferedReader in = null;
      in = new BufferedReader(new InputStreamReader(exchange.getRequestBody()));
      String reqBody = "";
      String response = "";

      // Log Request
      System.out.println("POST Request from: " + cIP.toString() + " Path: " + path.toString());
      // Read POST variables/Request body

      String urlParts[] = path.toString().split("/");

      reqBody = in.readLine();

      if (reqBody != null) {
        if (urlParts.length == 8) {

          HTTPCassandra CassInterface = new HTTPCassandra();
          // todo: url decode
          String[] vars = reqBody.toString().split("&");
          String res[] = CassInterface.handlePOST(urlParts, vars);

          if (res[0].equals("201")) {
            response = res[1];
            responseHeaders.set("Content-Type", "text/html");
            exchange.sendResponseHeaders(201, response.length());
          } else {
            responseHeaders.set("Content-Type", "text/html");
            response = "<h1>" + res[1] + "</h1>";
            exchange.sendResponseHeaders(Integer.parseInt(res[0]), response.length());
          }
        } else {

          responseHeaders.set("Content-Type", "text/html");
          String error[] = lengthError(urlParts.length);
          response = error[1];
          System.out.println(response + " " + response.length());
          exchange.sendResponseHeaders(Integer.parseInt(error[0]), response.length());
        }

      } else {
        System.out.println("Empty POST request");

        responseHeaders.set("Content-Type", "text/html");
        response = "<H1>Empty POST Request</H1> ";

        exchange.sendResponseHeaders(400, 0);
      }

      responseBody.write(response.getBytes());
      responseBody.close();

    } else if (requestMethod.equalsIgnoreCase("PUT")) {
      Headers responseHeaders = exchange.getResponseHeaders();
      InetSocketAddress cIP = exchange.getRemoteAddress();
      OutputStream responseBody = exchange.getResponseBody();
      Headers requestHeaders = exchange.getRequestHeaders();
      URI path = exchange.getRequestURI();
      BufferedReader in = null;
      in = new BufferedReader(new InputStreamReader(exchange.getRequestBody()));
      String reqBody = "";
      String response = "";

      // Log Request
      System.out.println("POST Request from: " + cIP.toString() + " Path: " + path.toString());
      // Read POST variables/Request body

      String urlParts[] = path.toString().split("/");

      reqBody = in.readLine();

      if (reqBody != null) {
        if (urlParts.length == 8) {

          HTTPCassandra CassInterface = new HTTPCassandra();
          // todo: url decode
          String[] vars = reqBody.toString().split("&");
          String res[] = CassInterface.handlePOST(urlParts, vars);

          if (res[0].equals("201")) {
            response = res[1];
            responseHeaders.set("Content-Type", "text/html");
            exchange.sendResponseHeaders(201, response.length());
          } else {
            responseHeaders.set("Content-Type", "text/html");
            response = "<h1>" + res[1] + "</h1>";
            exchange.sendResponseHeaders(Integer.parseInt(res[0]), response.length());
          }
        } else {

          responseHeaders.set("Content-Type", "text/html");
          String error[] = lengthError(urlParts.length);
          response = error[1];
          System.out.println(response + " " + response.length());
          exchange.sendResponseHeaders(Integer.parseInt(error[0]), response.length());
        }

      } else {
        System.out.println("Empty PUT request");

        responseHeaders.set("Content-Type", "text/html");
        response = "<H1>Empty PUT Request</H1> ";

        exchange.sendResponseHeaders(400, 0);
      }

      responseBody.write(response.getBytes());
      responseBody.close();
    } else if (requestMethod.equalsIgnoreCase("DELETE")) {
      Headers responseHeaders = exchange.getResponseHeaders();
      InetSocketAddress cIP = exchange.getRemoteAddress();
      OutputStream responseBody = exchange.getResponseBody();
      Headers requestHeaders = exchange.getRequestHeaders();
      URI path = exchange.getRequestURI();
      BufferedReader in = null;
      in = new BufferedReader(new InputStreamReader(exchange.getRequestBody()));
      String reqBody = "";
      String response = "";
      String urlParts[] = path.toString().split("/");

      // Log Request
      System.out.println("DELETE Request from: " + cIP.toString() + " Path: " + path.toString());

      HTTPCassandra CassInterface = new HTTPCassandra();
      String res[] = CassInterface.handleDELETE(urlParts);

      System.out.println(res[1]);

      responseHeaders.set("Content-Type", "text/html");
      String testResponse = "<H1>DELETE</H1>";

      exchange.sendResponseHeaders(200, 0);
      responseBody.write(testResponse.getBytes());

      responseBody.close();
    }
  }
 @Override
 public String getRequestHeader(String headerName) {
   return httpExchange.getRequestHeaders().getFirst(headerName);
 }
  @Override
  public void handle(HttpExchange t) throws IOException {
    if (RemoteUtil.deny(t)) {
      throw new IOException("Access denied");
    }
    RootFolder root = parent.getRoot(RemoteUtil.userName(t), t);
    if (root == null) {
      throw new IOException("Unknown root");
    }
    Headers h = t.getRequestHeaders();
    for (String h1 : h.keySet()) {
      LOGGER.debug("key " + h1 + "=" + h.get(h1));
    }
    String id = RemoteUtil.getId(path, t);
    id = RemoteUtil.strip(id);
    RendererConfiguration r = render;
    if (render == null) {
      r = root.getDefaultRenderer();
    }
    DLNAResource dlna = root.getDLNAResource(id, r);
    if (dlna == null) {
      // another error
      LOGGER.debug("media unkonwn");
      throw new IOException("Bad id");
    }
    if (!dlna.isCodeValid(dlna)) {
      LOGGER.debug("coded object with invalid code");
      throw new IOException("Bad code");
    }
    DLNAMediaSubtitle sid = null;
    long len = dlna.length();
    Range range = RemoteUtil.parseRange(t.getRequestHeaders(), len);
    String mime = root.getDefaultRenderer().getMimeType(dlna.mimeType());
    // DLNAResource dlna = res.get(0);
    WebRender render = (WebRender) r;
    DLNAMediaInfo m = dlna.getMedia();
    if (m == null) {
      m = new DLNAMediaInfo();
      dlna.setMedia(m);
    }
    if (mime.equals(FormatConfiguration.MIMETYPE_AUTO) && m.getMimeType() != null) {
      mime = m.getMimeType();
    }
    int code = 200;
    dlna.setDefaultRenderer(r);
    if (dlna.getFormat().isVideo()) {
      if (flash) {
        mime = "video/flash";
      } else if (!RemoteUtil.directmime(mime) || RemoteUtil.transMp4(mime, m)) {
        mime = render != null ? render.getVideoMimeType() : RemoteUtil.transMime();
        if (FileUtil.isUrl(dlna.getSystemName())) {
          dlna.setPlayer(new FFmpegWebVideo());
        } else {
          dlna.setPlayer(new FFMpegVideo());
        }
        // code = 206;
      }
      if (PMS.getConfiguration().getWebSubs()
          && dlna.getMediaSubtitle() != null
          && dlna.getMediaSubtitle().isExternal()) {
        // fetched on the side
        sid = dlna.getMediaSubtitle();
        dlna.setMediaSubtitle(null);
      }
    }

    if (!RemoteUtil.directmime(mime) && dlna.getFormat().isAudio()) {
      dlna.setPlayer(new FFmpegAudio());
      code = 206;
    }

    m.setMimeType(mime);
    LOGGER.debug("dumping media " + mime + " " + dlna);
    InputStream in = dlna.getInputStream(range, root.getDefaultRenderer());
    Headers hdr = t.getResponseHeaders();
    hdr.add("Content-Type", mime);
    hdr.add("Accept-Ranges", "bytes");
    if (range != null) {
      long end = range.asByteRange().getEnd();
      long start = range.asByteRange().getStart();
      String rStr = start + "-" + end + "/*";
      hdr.add("Content-Range", "bytes " + rStr);
      if (start != 0) {
        code = 206;
      }
    }
    hdr.add("Server", PMS.get().getServerName());
    hdr.add("Connection", "keep-alive");
    t.sendResponseHeaders(code, 0);
    OutputStream os = t.getResponseBody();
    render.start(dlna);
    if (sid != null) {
      dlna.setMediaSubtitle(sid);
    }
    RemoteUtil.dump(in, os, render);
  }
  @Override
  public void handle(HttpExchange he) throws IOException {

    try {

      String uri = he.getRequestURI().getPath();
      if (uri != null && uri.startsWith("/")) {
        // For the time being, the URI is split up this way:
        /* /s/play/My%20Song.mp3 =
           /s = context (1)
           /play = command (2)
           /100 = song id in internal db (3)
           /My%20Song.mp3 (4) // friendly name for players that can't read extended M3u info
        */
        String[] cmdargs = uri.split("/", 4);
        String context = cmdargs[1]; // TODO - should we do anything with this?
        String cmdStr = cmdargs[2];
        path = "";
        if (cmdargs.length > 3) {
          StringBuilder sb = new StringBuilder();
          for (int x = 3; x < cmdargs.length; x++) sb.append(cmdargs[x]);

          path = sb.toString();
        }

        if (cmdStr != null) {
          hr = he.getRequestHeaders();

          String remotehost = he.getRemoteAddress().getHostString();

          FilterAction fa = clientlist.filterActionFor(remotehost);
          action = clientlist.getDefaultAction();
          options = null;

          if (fa != null) {
            action = fa.getAction();
            options = fa.getOptions();
          }

          stats.countStat("CLIENT_ACTION", action.toString());
          stats.countStat("CLIENT", remotehost);

          final AbstractCommand cmd;
          if (allowedCommands != null) {
            Command.Type cmdStrType = Command.Type.get(cmdStr);
            if (Arrays.asList(allowedCommands).contains(cmdStrType)) {
              cmd = factory.create(cmdStrType, he, rootdir);
              handleAccess(he, cmd);
            } else {
              throw new IllegalArgumentException(
                  "This type of handler doesn't support the '" + cmdStr + "' command");
            }
          }
        }
      }

    } catch (Exception e) {
      LOG.log(Level.SEVERE, "Problem handling request", e);
    } finally {
      he.close();
    }
  }