コード例 #1
0
 public static void respond(
     HttpExchange exchange, String redirectUrl, String name, Optional<String> message)
     throws IOException {
   LOG.finer(
       () ->
           "Redirecting to "
               + name
               + " ["
               + redirectUrl
               + "]"
               + message.map(m -> ": " + m).orElse(""));
   exchange.getResponseHeaders().set("Location", redirectUrl);
   exchange.sendResponseHeaders(302, 0);
   if ("HEAD".equals(exchange.getRequestMethod())) return;
   try (PrintStream out = new PrintStream(exchange.getResponseBody())) {
     HeaderResponse.send(out, SessionFilter.getSession(exchange), "Redirection to " + name);
     out.println("<DIV>");
     message.ifPresent(m -> out.printf("%s<BR>\n", m));
     out.printf("Go to: <A href=\"%s\"><B>%s</B></A>", redirectUrl, name);
     out.println("</DIV>");
   } catch (Exception e) {
     LOG.log(Level.SEVERE, e, () -> "Failed generating redirection to '" + name + "': ");
     throw (e);
   }
 }
コード例 #2
0
  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();
  }
コード例 #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();
  }
コード例 #4
0
 @Override
 public String respond(HttpExchange httpExchange) {
   String method = httpExchange.getRequestMethod();
   String uri = httpExchange.getRequestURI().getPath();
   logger.log(method + " " + uri + " " + stringify(httpExchange.getRequestBody()));
   return NO_CONTENT;
 }
コード例 #5
0
ファイル: ParameterFilter.java プロジェクト: TheNewDrive/API
  private void parsePostParameters(HttpExchange exchange) throws IOException {

    if ("post".equalsIgnoreCase(exchange.getRequestMethod())) {
      @SuppressWarnings("unchecked")
      Map<String, Object> parameters = (Map<String, Object>) exchange.getAttribute("parameters");
      InputStreamReader isr = new InputStreamReader(exchange.getRequestBody(), "utf-8");
      BufferedReader br = new BufferedReader(isr);
      String query = br.readLine();
      parseQuery(query, parameters);
      br.close();
      isr.close();
    }
  }
コード例 #6
0
 @Override
 public void handle(HttpExchange httpExchange) throws IOException {
   try {
     String method = httpExchange.getRequestMethod();
     if ("GET".equals(method)) {
       doGet(httpExchange);
     } else if ("POST".equals(method)) {
       doPost(httpExchange);
     }
   } catch (Exception e) {
     HawkException.catchException(e);
   } finally {
     httpExchange.close();
   }
 }
コード例 #7
0
    @Override
    public String respond(HttpExchange httpExchange) {
      InputStream body = httpExchange.getRequestBody();

      try {

        Order order = objectMapper.readValue(body, Order.class);
        logger.error(order.toString());

        Integer perc = COUNTRIES.get(order.getCountry());

        //     Optional<Reduction> reduction = Reduction.valueOfFrom(order.getReduction());

        if ("STANDARD".equalsIgnoreCase(order.getReduction()) && perc != null) {
          Double total = order.totalWithPerc(perc);

          total = getTotalWithReduction(total);
          String totalResponse = generateAndLog(total);
          return totalResponse;

        } else if ("HALF PRICE".equals(order.getReduction()) && perc != null) {
          Double total = order.totalWithPerc(perc);

          total = total / 2;
          String totalResponse = generateAndLog(total);
          return totalResponse;

        } else if ("PAY THE PRICE".equals(order.getReduction()) && perc != null) {
          Double total = order.totalWithPerc(perc);
          String totalResponse = generateAndLog(total);
          return totalResponse;
        } else {

          logger.error("ATTENTION NON GERE : ");
          String method = httpExchange.getRequestMethod();
          String uri = httpExchange.getRequestURI().getPath();
          logger.log(method + " " + uri + " " + stringify(httpExchange.getRequestBody()));
        }

        //                logger.log(message.getType() + ": " + message.getContent());
      } catch (IOException exception) {
        logger.error(exception.getMessage());
      }

      return NO_CONTENT;
    }
コード例 #8
0
    @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();
    }
コード例 #9
0
    // 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();
    }
コード例 #10
0
  /** Processes the incoming Burlap request and creates a Burlap response. */
  @Override
  public void handle(HttpExchange exchange) throws IOException {
    if (!"POST".equals(exchange.getRequestMethod())) {
      exchange.getResponseHeaders().set("Allow", "POST");
      exchange.sendResponseHeaders(405, -1);
      return;
    }

    ByteArrayOutputStream output = new ByteArrayOutputStream(1024);
    try {
      invoke(exchange.getRequestBody(), output);
    } catch (Throwable ex) {
      exchange.sendResponseHeaders(500, -1);
      logger.error("Burlap skeleton invocation failed", ex);
    }

    exchange.sendResponseHeaders(200, output.size());
    FileCopyUtils.copy(output.toByteArray(), exchange.getResponseBody());
  }
コード例 #11
0
ファイル: ServerHandler.java プロジェクト: ruslanvcooper/BSU
 private Response dispatch(HttpExchange httpExchange) {
   if (Constants.REQUEST_METHOD_GET.equals(httpExchange.getRequestMethod())) {
     return doGet(httpExchange);
   } else if (Constants.REQUEST_METHOD_POST.equals(httpExchange.getRequestMethod())) {
     return doPost(httpExchange);
   } else if (Constants.REQUEST_METHOD_PUT.equals(httpExchange.getRequestMethod())) {
     return doPut(httpExchange);
   } else if (Constants.REQUEST_METHOD_DELETE.equals(httpExchange.getRequestMethod())) {
     return doDelete(httpExchange);
   } else if (Constants.REQUEST_METHOD_OPTIONS.equals(httpExchange.getRequestMethod())) {
     return doOptions(httpExchange);
   } else {
     return new Response(
         Constants.RESPONSE_CODE_METHOD_NOT_ALLOWED,
         String.format("Unsupported http method %s", httpExchange.getRequestMethod()));
   }
 }
コード例 #12
0
ファイル: GamesHandler.java プロジェクト: Brc509/Settlers
 private void joinGame(HttpExchange exchange) throws IOException {
   Server.println("\n" + this.getClass().getSimpleName() + ":");
   System.out.println("Request type: " + exchange.getRequestMethod().toUpperCase());
   if (!HandlerUtils.authorizeUser(exchange)) {
     Server.println("  Unauthorized request to /games/join.");
     HandlerUtils.sendEmptyBody(exchange, HttpURLConnection.HTTP_UNAUTHORIZED);
     return;
   }
   String formdataStr = HandlerUtils.inputStreamToString(exchange.getRequestBody());
   Map<String, String> formdata = HandlerUtils.decodeQueryString(formdataStr);
   String color = formdata.get("color");
   int gameID = Integer.parseInt(formdata.get("id"));
   String name = HandlerUtils.getCookie(exchange).getUsername();
   GamesJoinCommand command =
       new GamesJoinCommand(HandlerUtils.getCookie(exchange).getId(), gameID, color, name);
   if (command.execute(null)) {
     HandlerUtils.addCookie(exchange, "catan.game", String.valueOf(gameID));
     HandlerUtils.sendString(
         exchange, HttpURLConnection.HTTP_OK, "Success! You have joined the game.");
   } else {
     HandlerUtils.sendString(
         exchange, HttpURLConnection.HTTP_INTERNAL_ERROR, "Failed to join game.");
   }
 }
コード例 #13
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);
  }
コード例 #14
0
 @Override
 @Property(MessageContext.HTTP_REQUEST_METHOD)
 public @NotNull String getRequestMethod() {
   return httpExchange.getRequestMethod();
 }
コード例 #15
0
ファイル: EBHTTPServer.java プロジェクト: balsick/EBServer
  public void handleEvent(HttpExchange he) {
    try {
      CCActivityServer.logger.info("received something");
      final Headers headers = he.getResponseHeaders();
      for (List<String> list : headers.values())
        for (String s : list) CCActivityServer.logger.info(s);
      final String requestMethod = he.getRequestMethod().toUpperCase();
      CCActivityServer.logger.info(requestMethod);
      switch (requestMethod) {
        case METHOD_GET:
          final Map<String, List<String>> requestParameters =
              getRequestParameters(he.getRequestURI());
          for (String key : requestParameters.keySet()) {
            CCActivityServer.logger.info("Chiave: " + key + "\nvalori:");
            for (String s : requestParameters.get(key)) CCActivityServer.logger.info(s);
          }
          ClientServerResult result;
          CCActivityServer.logger.info(he.getHttpContext().getPath());

          switch (he.getHttpContext().getPath()) {
            case "/selectTest":
              try {
                result = DBManager.select(requestParameters, this);
              } catch (Exception e) {
                result = null;
                e.printStackTrace();
              }
              break;
            case API_PATH + API_FANTAPLAYERS:
              FootballParser fp = new FootballParser();
              System.out.println(
                  "parsing\t" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()));
              fp.parse();
              System.out.println(
                  "parsed\t" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()));
              fp.setToList(
                  requestParameters.get("options") != null
                      && requestParameters.get("options").contains("list"));
              Object players = fp.getPlayers(requestParameters.get("players"));
              try {
                result = ClientServerGenericResult.createResult(players);
                break;
              } catch (IllegalArgumentException ex) {
                ex.printStackTrace();
              }
            default:
              result = ClientServerGenericResult.createResult("");
              result.resultType = ClientServerResult.RESULTFAIL;
          }
          final String responseBody = JSonParser.getJSon(result, false);
          CCActivityServer.logger.info(responseBody);
          headers.set(HEADER_CONTENT_TYPE, String.format("application/json; charset=%s", CHARSET));
          final byte[] rawResponseBody = responseBody.getBytes(CHARSET);
          he.sendResponseHeaders(STATUS_OK, rawResponseBody.length);
          he.getResponseBody().write(rawResponseBody);
          System.out.println(
              "finito\t" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()));
          break;
        case METHOD_OPTIONS:
          headers.set(HEADER_ALLOW, ALLOWED_METHODS);
          he.sendResponseHeaders(STATUS_OK, NO_RESPONSE_LENGTH);
          break;
        default:
          headers.set(HEADER_ALLOW, ALLOWED_METHODS);
          he.sendResponseHeaders(STATUS_METHOD_NOT_ALLOWED, NO_RESPONSE_LENGTH);
          break;
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      he.close();
    }
  }
コード例 #16
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();
    }
  }
コード例 #17
0
ファイル: MyIPHandler.java プロジェクト: eamonnmag/Peergos
 @Override
 public void handle(HttpExchange httpExchange) throws IOException {
   if (httpExchange.getRequestMethod().equals("GET")) {
     handleGet(httpExchange);
   }
 }