Esempio n. 1
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();
  }
 /** Play Monument Handler for the server */
 @Override
 public void handle(HttpExchange exchange) throws IOException {
   exchange.getResponseHeaders().set("Content-type", "application/json");
   try {
     int gameID = checkCookie(exchange);
     if (gameID == -1) {
       System.err.print("\nInvalid Cookie. Thowing Error");
       throw new Exception("INVALID COOKIE!");
     }
     Gson gson = new Gson();
     StringWriter writer = new StringWriter();
     IOUtils.copy(exchange.getRequestBody(), writer);
     shared.communication.toServer.moves.Monument_ move =
         gson.fromJson(writer.toString(), Monument_.class);
     server.commands.Monument command = new server.commands.Monument(gameID);
     command.setParams(move);
     command.execute(server);
     this.addCommand(command, gameID);
     exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0);
     OutputStreamWriter output = new OutputStreamWriter(exchange.getResponseBody());
     output.write(server.getModel(gameID));
     output.flush();
     exchange.getResponseBody().close();
     exchange.close();
   } catch (Exception e) {
     exchange.sendResponseHeaders(HttpURLConnection.HTTP_BAD_REQUEST, -1);
     exchange.getResponseBody().close();
     exchange.close();
   }
 }
Esempio n. 3
0
  /**
   * Receives the BuyDevCard Params and constructs the appropriate command and passes it to the
   * Server Facade after decoding the object.
   */
  @Override
  public void handle(HttpExchange exchange) throws IOException {
    // logger.entering("server.handlers.BuyDevCard", "handle");
    // Handling Login http exchange.

    String job;
    BuyDevCard_Params request;
    BuyDevCard_Result result;

    LinkedList<String> cookies = extractCookies(exchange);

    String check = validateCookies(cookies);

    swaggerize(exchange);

    if (check.equals("VALID")) {

      User user = gson.fromJson(cookies.getFirst(), User.class);
      int gameID = Integer.parseInt(cookies.get(1));

      job = getExchangeBody(exchange); // get json string from exchange.
      request = gson.fromJson(job, BuyDevCard_Params.class); // deserialize request from json

      BuyDevCard_Command command = new BuyDevCard_Command(request, gameID, user.getPlayerID());

      command.execute(); // Execute the command

      result = command.getResult(); // Get result from command		

      if (result.isValid()) {
        exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0); // Everything's okay

        ClientModel cm = result.getModel();
        job = gson.toJson(cm); // serialize result to json
      } else {
        exchange.sendResponseHeaders(HttpURLConnection.HTTP_BAD_REQUEST, 0);
        job = "COMMAND FAILURE";
      }
    } else {
      job = check;
      exchange.sendResponseHeaders(HttpURLConnection.HTTP_BAD_REQUEST, 0); // User invalid		
    }

    OutputStreamWriter sw = new OutputStreamWriter(exchange.getResponseBody());
    sw.write(job); // Write result to stream.
    sw.flush();

    exchange.getResponseBody().close();
    //	logger.exiting("server.handlers.BuyDevCard", "handle");

  }
Esempio n. 4
0
 @Override
 public synchronized void handle(HttpExchange exchange) throws IOException {
   String path = exchange.getRequestURI().getRawPath();
   String response = pathResponses.get(path);
   OutputStream os = exchange.getResponseBody();
   if (response == null) {
     response = "No response mapped for path " + path;
     exchange.sendResponseHeaders(500, response.length());
   } else {
     exchange.sendResponseHeaders(200, response.length());
   }
   os.write(response.getBytes(StandardCharsets.UTF_8));
   os.close();
 }
  @Override
  public void handle(HttpExchange httpExchange) throws IOException {
    logger.info("Active endpoint Call Start");

    // execute query
    logger.debug("Getting executor...");
    Executor ex = this.getExecutor();
    logger.debug("Using Executor " + ex.toString());

    // ex.execute(new SetOfStatementsImpl(statements), this.getPathId());
    ex.execute(new SetOfStatementsImpl(), this.getPathId());

    SetOfStatements st = ex.getNextResults(this.getPathId());

    StringBuffer sResponse = new StringBuffer();
    sResponse.append(HTML_PART1 + generateEvents(st) + "</body></html>");

    Headers responseHeaders = httpExchange.getResponseHeaders();
    responseHeaders.set("Content-Type", "text/html");
    httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, sResponse.length());
    // send back OK response
    httpExchange.getResponseBody().write(sResponse.toString().getBytes());
    httpExchange.getResponseBody().close();
    logger.info("PushEndpoint Call End");
  }
Esempio n. 6
0
    @Override
    public void handle(HttpExchange t) throws IOException {

      String fileId = t.getRequestURI().getPath().replaceFirst("/header/", "");
      System.out.println("fileId: " + fileId);
      InputStream is = new FileInputStream("C:\\Users\\vadim\\Downloads\\15496_1#45.cram");
      CramHeader cramHeader = CramIO.readCramHeader(is);

      t.getResponseHeaders().add(HttpHeaders.CONTENT_TYPE, "SAM_HEADER");

      t.getResponseHeaders()
          .add(
              "CRAM_VERSION",
              String.format("%d.%d", cramHeader.getMajorVersion(), cramHeader.getMinorVersion()));
      t.sendResponseHeaders(200, 0);

      ByteArrayOutputStream headerBodyOS = new ByteArrayOutputStream();
      OutputStreamWriter w = new OutputStreamWriter(headerBodyOS);
      new SAMTextHeaderCodec().encode(w, cramHeader.getSamFileHeader());
      try {
        w.close();
      } catch (IOException e) {
        throw new RuntimeException(e);
      }

      OutputStream os = t.getResponseBody();
      os.write(headerBodyOS.toByteArray());
      os.close();
    }
Esempio n. 7
0
    @Override
    public void handle(HttpExchange arg0) throws IOException {
      byte[] utf8b = org.apache.commons.io.ByteOrderMark.UTF_8.getBytes();

      String l = "a\tb\tc\t\nb\th\tj\n";

      ByteArrayOutputStream ous = new ByteArrayOutputStream();

      ous.write(utf8b);
      ous.write(l.getBytes("UTF-8"));
      ous.close();

      byte[] k = ous.toByteArray();

      Headers hdrs = arg0.getResponseHeaders();

      hdrs.set("Content-Type", "application/csv");
      hdrs.set("Content-Disposition", "attachment; filename=genome.csv");
      hdrs.set("Content-Encoding", "binary");
      hdrs.set("Charset", "utf-8");

      arg0.sendResponseHeaders(200, k.length);

      arg0.getResponseBody().write(k);
      arg0.getResponseBody().close();
    }
 public void handle(HttpExchange t) throws IOException {
   String response = "<h3>Happy New Year 2007!--Chinajash</h3>";
   t.sendResponseHeaders(200, response.length());
   OutputStream os = t.getResponseBody();
   os.write(response.getBytes());
   os.close();
 }
Esempio n. 9
0
 @Override
 public void handle(HttpExchange httpExchange) throws IOException {
   httpExchange.getResponseHeaders().set("Content-Type", "text/html");
   httpExchange.sendResponseHeaders(HTTP_OK, content.getBytes().length);
   httpExchange.getResponseBody().write(content.getBytes());
   httpExchange.close();
 }
 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);
   }
 }
  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();
  }
Esempio n. 12
0
 private static void writePostReply(HttpExchange msg, byte[] buf) throws Exception {
   msg.getResponseHeaders().add("Content-Type", "text/xml");
   msg.sendResponseHeaders(200, buf.length);
   OutputStream out = msg.getResponseBody();
   out.write(buf);
   out.close();
 }
  @Override
  public void handle(HttpExchange t) throws IOException {
    OutputStream os = t.getResponseBody();
    URI uri = t.getRequestURI();

    if (!uri.toString().startsWith("/")) {
      /* suspecting path traversal attack */
      String response = "403 (Forbidden)\n";
      t.sendResponseHeaders(403, response.getBytes().length);
      os.write(response.getBytes());
      os.close();
      return;
    }

    ContentType contentType;
    if (uri.toString().equals("/")) {
      contentType = ContentType.HTML;
    } else {
      contentType = ContentType.getContentType(uri.toString());
    }
    if (contentType != ContentType.REQUEST) {
      handleFile(t, contentType);
      return;
    }

    // Presentation layer on of VCenterPluginResp
    // Accept with response code 200.
    t.sendResponseHeaders(200, 0);
    Headers h = t.getResponseHeaders();

    h.set("Content-Type", contentType.toString());
    StringBuilder s =
        new StringBuilder()
            .append("<?xml-stylesheet type=\"")
            .append(ContentType.XSL)
            .append("\" href=\"")
            .append(styleSheet)
            .append("\"?>");

    // serialize the actual response object in XML
    VCenterPluginReq req = new VCenterPluginReq(uri);
    VCenterPluginResp resp = new VCenterPluginResp(req);
    resp.writeObject(s);

    os.write(s.toString().getBytes());
    os.close();
  }
Esempio n. 14
0
  @Override
  protected void doGet(HttpExchange exchange, QueryData data, Config config) throws IOException {
    Compilation compilation = getCompilation(exchange, data, config);
    if (compilation == null) {
      return;
    }
    if (!compilation.usesModules()) {
      HttpUtil.writeErrorMessageResponse(exchange, "This configuration does not use modules");
      return;
    }

    // Get the size of each module.
    ModuleConfig moduleConfig = config.getModuleConfig();
    Map<String, List<String>> invertedDependencyTree = moduleConfig.getInvertedDependencyTree();
    Function<String, String> moduleNameToUri = moduleConfig.createModuleNameToUriFunction();
    ImmutableMap.Builder<String, Pair<Integer, Integer>> builder = ImmutableMap.builder();
    final boolean isDebugMode = false;
    for (String module : invertedDependencyTree.keySet()) {
      // The file size is in bytes, assuming UTF-8 input.
      String compiledCode = compilation.getCodeForModule(module, isDebugMode, moduleNameToUri);
      int uncompressedSize = compiledCode.getBytes(Charsets.UTF_8).length;
      int gzippedSize = GzipUtil.getGzipSize(compiledCode);
      builder.put(module, Pair.of(uncompressedSize, gzippedSize));
    }
    Map<String, Pair<Integer, Integer>> moduleSizes = builder.build();

    // Construct the SVG.
    SetMultimap<Integer, String> moduleDepths =
        calculateModuleDepths(moduleConfig.getRootModule(), invertedDependencyTree);
    Map<String, List<JsInput>> moduleToInputs;
    try {
      moduleToInputs = moduleConfig.partitionInputsIntoModules(config.getManifest());
    } catch (CompilationException e) {
      throw new RuntimeException(e);
    }
    Pair<String, Dimension> svg =
        generateSvg(
            config.getId(), moduleDepths, invertedDependencyTree, moduleSizes, moduleToInputs);

    // Populate Soy template.
    Dimension svgDimension = svg.getSecond();
    SoyMapData mapData =
        new SoyMapData(
            ImmutableMap.<String, Object>builder()
                .put("configId", config.getId())
                .put("svg", svg.getFirst())
                .put("svgWidth", svgDimension.width)
                .put("svgHeight", svgDimension.height)
                .build());
    String xhtml = TOFU.newRenderer("org.plovr.modules").setData(mapData).render();

    // Write the response.
    Headers responseHeaders = exchange.getResponseHeaders();
    responseHeaders.set("Content-Type", "text/xml");
    exchange.sendResponseHeaders(200, xhtml.length());
    Writer responseBody = new OutputStreamWriter(exchange.getResponseBody());
    responseBody.write(xhtml);
    responseBody.close();
  }
Esempio n. 15
0
  /* (non-Javadoc)
   * @see com.sun.net.httpserver.HttpHandler#handle(com.sun.net.httpserver.HttpExchange)
   */
  @Override
  public void handle(HttpExchange exchange) throws IOException {
    Search_Params params = (Search_Params) xmlStream.fromXML(exchange.getRequestBody());
    Search_Result results = new Search_Result();

    try {
      results = ServerFacade.search(params);
    } catch (ServerException e) {
      logger.log(Level.SEVERE, e.getMessage(), e);
      exchange.sendResponseHeaders(HttpURLConnection.HTTP_INTERNAL_ERROR, -1);
      return;
    }

    exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0);
    xmlStream.toXML(results, exchange.getResponseBody());
    exchange.getResponseBody().close();
  }
  @Override
  public void handle(HttpExchange exchange) throws IOException {

    UpdateContact_Params params =
        (UpdateContact_Params) xmlStream.fromXML(exchange.getRequestBody());
    Contact contact = params.getContact();

    try {
      ServerFacade.updateContact(contact);
    } catch (ServerException e) {
      logger.log(Level.SEVERE, e.getMessage(), e);
      exchange.sendResponseHeaders(HttpURLConnection.HTTP_INTERNAL_ERROR, -1);
      return;
    }

    exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, -1);
  }
    @Override
    public void handle(HttpExchange httpExchange) throws IOException {
      if (closedCallback != null) {
        closedCallback.onClosed();
      }

      httpExchange.sendResponseHeaders(200, -1);
    }
 @Override
 public void handle(HttpExchange httpExchange) throws IOException {
   String response = respond(httpExchange);
   httpExchange.sendResponseHeaders(200, response.length());
   OutputStream os = httpExchange.getResponseBody();
   os.write(response.getBytes());
   os.close();
 }
Esempio n. 19
0
 @Override
 public void handle(HttpExchange exchange) throws IOException {
   byte[] json = mapper.writeValueAsString(get()).getBytes("UTF-8");
   exchange.sendResponseHeaders(200, json.length);
   try (OutputStream out = exchange.getResponseBody()) {
     out.write(json);
   }
 }
  private void handleFile(HttpExchange t, ContentType contentType)
      throws IOException, FileNotFoundException {

    OutputStream os = t.getResponseBody();

    String fileName = t.getRequestURI().toString();

    if (fileName.equals("/")) {
      fileName = "/vcenter-plugin.html";
    }
    File file = new File(VCenterHttpServer.INSTANCE.getWebRoot() + fileName).getCanonicalFile();

    if (!file.getPath().startsWith(VCenterHttpServer.INSTANCE.getWebRoot())) {
      // Suspected path traversal attack: reject with 403 error.
      String response = "403 (Forbidden)\n";
      t.sendResponseHeaders(403, response.getBytes().length);
      os.write(response.getBytes());
      os.close();
      return;
    }
    if (!file.isFile()) {
      // Object does not exist or is not a file: reject with 404 error.
      // s_logger.error(" Cannot load " + fileName);
      String response = "404 (Not Found)\n";
      t.sendResponseHeaders(404, response.length());
      os.write(response.getBytes());
      os.close();
      return;
    }

    // Object exists and is a file: accept with response code 200.
    Headers h = t.getResponseHeaders();
    h.set("Content-Type", contentType.toString());
    t.sendResponseHeaders(200, 0);

    FileInputStream fs = new FileInputStream(file);
    final byte[] buffer = new byte[0x100000];
    int count = 0;
    while ((count = fs.read(buffer)) >= 0) {
      os.write(buffer, 0, count);
    }
    fs.close();

    os.close();
  }
Esempio n. 21
0
 public static void dumpFile(File f, HttpExchange t) throws IOException {
   LOGGER.debug("file " + f + " " + f.length());
   if (!f.exists()) {
     throw new IOException("no file");
   }
   t.sendResponseHeaders(200, f.length());
   dump(new FileInputStream(f), t.getResponseBody());
   LOGGER.debug("dump of " + f.getName() + " done");
 }
Esempio n. 22
0
    public void handlFailure(HttpExchange t, String errorMsg) throws IOException {
      LOG.error(errorMsg);

      byte[] data = errorMsg.getBytes();
      t.sendResponseHeaders(HttpURLConnection.HTTP_BAD_REQUEST, data.length);
      OutputStream os = t.getResponseBody();
      os.write(data);
      os.close();
    }
 public void handle(HttpExchange t) throws IOException {
   Headers h = t.getResponseHeaders();
   h.add("Content-Type", "text/xml");
   String response = "This is Response status code test case";
   t.sendResponseHeaders(200, response.length());
   OutputStream os = t.getResponseBody();
   os.write(response.getBytes());
   os.close();
 }
Esempio n. 24
0
 @Override
 public void handle(HttpExchange httpExchange) throws IOException {
   // Return a simple text message that says pong.
   httpExchange.getResponseHeaders().set("Content-Type", "text/plain");
   String response = "pong\n";
   httpExchange.sendResponseHeaders(HTTP_OK, response.getBytes().length);
   httpExchange.getResponseBody().write(response.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();
    }
  /** 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());
  }
 public void handle(HttpExchange t) throws IOException {
   ++testConnectionCount;
   Logger.info(this, "testConnectionCountHandler testConnectionCount: " + testConnectionCount);
   // InputStream is = t.getRequestBody();
   // read(is); // .. read the request body
   String response = getClass().getSimpleName();
   t.sendResponseHeaders(200, response.length());
   OutputStream os = t.getResponseBody();
   os.write(response.getBytes());
   os.close();
 }
Esempio n. 28
0
 public static void send404(HttpExchange exchange) throws IOException {
   // SEND 404
   String response = "404 (Not Found)\n";
   exchange.sendResponseHeaders(404, response.length());
   OutputStream os = exchange.getResponseBody();
   try {
     os.write(response.getBytes());
   } finally {
     os.close();
   }
 }
Esempio n. 29
0
    @Override
    public void handle(HttpExchange t) throws IOException {

      String response = "This is the response";
      t.getResponseHeaders().add(HttpHeaders.CONTENT_TYPE, "CRAM");
      t.sendResponseHeaders(200, 0);
      System.out.println(t.getRequestURI());

      OutputStream os = t.getResponseBody();
      os.write(response.getBytes());
      os.close();
    }
    public void handle(HttpExchange t) throws IOException {

      Hazelcast.shutdownAll();

      String response = "Shutting down";
      t.sendResponseHeaders(200, response.length());
      OutputStream os = t.getResponseBody();
      os.write(response.getBytes());
      os.close();

      System.exit(-1);
    }