Example #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();
   }
 }
  /**
   * 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");

  }
Example #4
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();
    }
  @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");
  }
 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();
  }
Example #8
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();
 }
Example #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 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();
 }
Example #11
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();
    }
Example #12
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();
  }
 @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();
 }
Example #14
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();
  }
Example #15
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);
   }
 }
Example #16
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();
 }
Example #18
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();
 }
 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");
 }
    // 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 #21
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();
   }
 }
 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();
 }
Example #23
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 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 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);
    }
Example #26
0
  @Override
  protected void doGet(HttpExchange exchange, QueryData data, Config config) throws IOException {
    Compilation compilation = getCompilation(exchange, data, config);
    if (compilation == null) {
      return;
    }

    String configId = config.getId();
    List<JsInput> inputs;
    if (compilation.usesModules()) {
      ModuleConfig moduleConfig = config.getModuleConfig();
      Map<String, List<JsInput>> moduleToInputs;
      try {
        moduleToInputs = moduleConfig.partitionInputsIntoModules(config.getManifest());
      } catch (CompilationException e) {
        throw new RuntimeException(e);
      }

      String module = data.getParam("module");
      inputs = moduleToInputs.get(module);
    } else {
      try {
        inputs = config.getManifest().getInputsInCompilationOrder();
      } catch (CompilationException e) {
        HttpUtil.writeErrorMessageResponse(exchange, e.getMessage());
        return;
      }
    }

    // Build up the list of hyperlinks.
    Function<JsInput, String> converter =
        InputFileHandler.createInputNameToUriConverter(server, exchange, configId);
    SoyListData inputData = new SoyListData();
    for (JsInput input : inputs) {
      SoyMapData inputDatum = new SoyMapData();
      inputDatum.put("href", converter.apply(input));
      inputDatum.put("name", input.getName());
      inputData.add(inputDatum);
    }
    SoyMapData soyData = new SoyMapData();
    soyData.put("inputs", inputData);
    soyData.put("configId", configId);

    // Write the response.
    Headers responseHeaders = exchange.getResponseHeaders();
    responseHeaders.set("Content-Type", "text/html");
    String html = TOFU.newRenderer("org.plovr.list").setData(soyData).render();
    exchange.sendResponseHeaders(200, html.length());
    Writer responseBody = new OutputStreamWriter(exchange.getResponseBody());
    responseBody.write(html);
    responseBody.close();
  }
  @Override
  public void handle(HttpExchange t) throws IOException {

    Map<String, String> param = Util.getParam(t);
    Double interest = Bank.INSTANCE.calculateInterest(Integer.parseInt(param.get("accNum")));

    String response = "Your Bank Interest is :" + interest;

    t.sendResponseHeaders(200, response.length());
    OutputStream os = t.getResponseBody();
    os.write(response.getBytes());
    os.close();
  }
Example #28
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();
 }
Example #29
0
  @Override
  public void handle(HttpExchange exchange) throws IOException {
    JoinGameRequest requestJoin =
        Converter.fromJson(exchange.getRequestBody(), JoinGameRequest.class);

    try {
      UserInfo user = getUserCookie(exchange);

      ServerGamesFacade.getInstance().verifyUserInformation(user);

      Game response = ServerGamesFacade.getInstance().joinGame(user, requestJoin);

      setGameCookie(exchange, requestJoin.getGameID());

      exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0);
      exchange.getResponseBody().write(Converter.toJson(response).getBytes());
    } catch (ServerException e) {
      exchange.sendResponseHeaders(HttpURLConnection.HTTP_BAD_REQUEST, 0);
      exchange.getResponseBody().write(Converter.toJson(e.getReason()).getBytes());
    }

    exchange.getResponseBody().close();
  }
 // overrideable as well
 public void handleAccess(HttpExchange he, AbstractCommand cmd) throws Exception {
   if (action == FilterAction.Action.ALLOW) {
     continueHandle(cmd); // <-- OVERRIDE THIS IN SUBCLASS
   } else if (action == FilterAction.Action.DENY) {
     // send Access Denied
     OutputStream ps = he.getResponseBody();
     String html = "Access Denied";
     Header.setHeaders(he, Header.HeaderType.TEXT);
     he.sendResponseHeaders(401, html.length());
     ps.write(html.getBytes());
     ps.close();
   } else {
     // just close the connection
   }
 }