private void sendResourceFile(HttpExchange exchange) {
    StringBuilder response = new StringBuilder();

    String path = exchange.getRequestURI().getPath();
    if (path.contains("resources")) {
      path = path.substring(path.indexOf("resources") + 9);
    }
    InputStream is = MyBaseHandler.class.getResourceAsStream(path);
    if (is == null) {
      writeResponse(exchange, "File not found", 404);
      return;
    }
    InputStreamReader reader = new InputStreamReader(is);

    try {
      BufferedReader bufferedReader = new BufferedReader(reader);

      String tmp;
      while ((tmp = bufferedReader.readLine()) != null) {
        response.append(tmp);
        response.append("\n");
      }
    } catch (NullPointerException e) {
      response.append("Resource file not found");
      writeResponse(exchange, response.toString(), 404);
    } catch (IOException e) {
      response.append("Error while reading from file");
      writeResponse(exchange, response.toString(), 400);
    }
    writeResponse(exchange, response.toString(), 200);
  }
    @Override
    public void handle(HttpExchange t) throws IOException {
      LOGGER.debug("root req " + t.getRequestURI());
      if (RemoteUtil.deny(t)) {
        throw new IOException("Access denied");
      }
      if (t.getRequestURI().getPath().contains("favicon")) {
        RemoteUtil.sendLogo(t);
        return;
      }

      HashMap<String, Object> vars = new HashMap<>();
      vars.put("logs", getLogs(true));
      if (configuration.getUseCache()) {
        vars.put(
            "cache",
            "http://"
                + PMS.get().getServer().getHost()
                + ":"
                + PMS.get().getServer().getPort()
                + "/console/home");
      }

      String response = parent.getResources().getTemplate("doc.html").execute(vars);
      RemoteUtil.respond(t, response, 200, "text/html");
    }
 public static String getId(String path, HttpExchange t) {
   String id = "0";
   int pos = t.getRequestURI().getPath().indexOf(path);
   if (pos != -1) {
     id = t.getRequestURI().getPath().substring(pos + path.length());
   }
   return id;
 }
示例#4
0
 @Override
 public void handle(HttpExchange exchange) throws IOException {
   // TODO CHECK FOR BAD REQUESTS
   String endpoint = exchange.getRequestURI().getPath();
   System.out.println(endpoint);
   try {
     switch (endpoint) {
       case "/games/list":
         if (HandlerUtils.checkRequestMethod("GET", exchange)) {
           listGames(exchange);
         }
         break;
       case "/games/create":
         if (HandlerUtils.checkRequestMethod("POST", exchange)) {
           createGame(exchange);
         }
         break;
       case "/games/join":
         if (HandlerUtils.checkRequestMethod("POST", exchange)) {
           joinGame(exchange);
         }
         break;
       default:
         System.out.println("gameHandler. Endpoint: " + endpoint + ". Sent Bad Request");
         HandlerUtils.sendEmptyBody(exchange, HttpURLConnection.HTTP_BAD_REQUEST);
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
示例#5
0
 private void doGet(HttpExchange httpExchange) throws Exception {
   String uriQuery = httpExchange.getRequestURI().getQuery();
   if (uriQuery != null && uriQuery.length() > 0) {
     uriQuery = URLDecoder.decode(uriQuery, "UTF-8");
     onRecvProtocol(httpExchange, uriQuery);
   }
 }
示例#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();
    }
 @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;
 }
  @Override
  protected void wrappedHandle(HttpExchange t, String[] path, LinkedHashMap<String, String> query)
      throws Exception {
    l.info(
        "GET "
            + t.getRequestURI()
            + " "
            + t.getRemoteAddress()); // TODO - create a special logger for this!

    String[] longestMatch = getLongestMatch(path);
    LazyInstantiator<SafeHttpHandler> handler = handlers.get(longestMatch);
    if (handler == null) {
      String failMessage = "No handler found for: " + Arrays.toString(path);
      l.info(failMessage);
      sendText(t, failMessage);
      return;
    }

    TimedLogRecordStart start = new TimedLogRecordStart("calling " + handler);
    l.log(start);

    int startIndex = longestMatch.length;
    String[] truncatedPath = Arrays.copyOfRange(path, startIndex, path.length);
    handler.cachedInstance().wrappedHandle(t, truncatedPath, query);

    l.log(start.finishedNow());
  }
示例#9
0
    /**
     * Parse the parameters of a connection into a CoreNLP properties file that can be passed into
     * {@link StanfordCoreNLP}, and used in the I/O stages.
     *
     * @param httpExchange The http exchange; effectively, the request information.
     * @return A {@link Properties} object corresponding to a combination of default and passed
     *     properties.
     * @throws UnsupportedEncodingException Thrown if we could not decode the key/value pairs with
     *     UTF-8.
     */
    private Properties getProperties(HttpExchange httpExchange)
        throws UnsupportedEncodingException {
      // Load the default properties
      Properties props = new Properties();
      defaultProps
          .entrySet()
          .stream()
          .forEach(
              entry -> props.setProperty(entry.getKey().toString(), entry.getValue().toString()));

      // Try to get more properties from query string.
      Map<String, String> urlParams = getURLParams(httpExchange.getRequestURI());
      if (urlParams.containsKey("properties")) {
        StringUtils.decodeMap(URLDecoder.decode(urlParams.get("properties"), "UTF-8"))
            .entrySet()
            .forEach(entry -> props.setProperty(entry.getKey(), entry.getValue()));
      } else if (urlParams.containsKey("props")) {
        StringUtils.decodeMap(URLDecoder.decode(urlParams.get("properties"), "UTF-8"))
            .entrySet()
            .forEach(entry -> props.setProperty(entry.getKey(), entry.getValue()));
      }

      // Make sure the properties compile
      props.setProperty(
          "annotators",
          StanfordCoreNLP.ensurePrerequisiteAnnotators(
              props.getProperty("annotators").split("[, \t]+")));

      return props;
    }
示例#10
0
  public static ResteasyUriInfo extractUriInfo(HttpExchange exchange) {
    String host = exchange.getLocalAddress().getHostName();
    if (exchange.getLocalAddress().getPort() != 80 && exchange.getLocalAddress().getPort() != 443) {
      host += ":" + exchange.getLocalAddress().getPort();
    }
    String uri = exchange.getRequestURI().toString();

    String protocol =
        exchange.getHttpContext().getServer() instanceof HttpsServer ? "https" : "http";

    URI absoluteURI = URI.create(protocol + "://" + host + uri);

    String contextPath = exchange.getHttpContext().getPath();
    String path = PathHelper.getEncodedPathInfo(absoluteURI.getRawPath(), contextPath);
    if (!path.startsWith("/")) {
      path = "/" + path;
    }

    URI baseURI = absoluteURI;
    if (!path.trim().equals("")) {
      String tmpContextPath = contextPath;
      if (!tmpContextPath.endsWith("/")) tmpContextPath += "/";
      baseURI =
          UriBuilder.fromUri(absoluteURI).replacePath(tmpContextPath).replaceQuery(null).build();
    } else {
      baseURI = UriBuilder.fromUri(absoluteURI).replaceQuery(null).build();
    }
    URI relativeURI = UriBuilder.fromUri(path).replaceQuery(absoluteURI.getRawQuery()).build();
    // System.out.println("path: " + path);
    // System.out.println("query string: " + request.getQueryString());
    ResteasyUriInfo uriInfo = new ResteasyUriInfo(baseURI, relativeURI);
    return uriInfo;
  }
示例#11
0
  @Override
  protected void handleGet(HttpExchange exchange) throws IOException {
    String path = exchange.getRequestURI().getPath();
    if (path.equals("/")) {
      handleListBuckets(exchange);
      return;
    }

    Matcher bucketPatternMatcher = BUCKET_PATTERN.matcher(path);
    if (bucketPatternMatcher.matches()) {
      String bucketName = bucketPatternMatcher.group(1);
      handleListObjects(exchange, bucketName);
    }

    Matcher requestPathPatternMatcher = REQUEST_PATH_PATTERN.matcher(path);
    if (!requestPathPatternMatcher.matches()) {
      respondErrorAndClose(exchange, ErrorResponse.INVALID_URI);
      return;
    }
    String bucketName = requestPathPatternMatcher.group(1);
    String keyName = requestPathPatternMatcher.group(2);

    if (DOUBLE_DOT_PATTERN.matcher(keyName).matches()) {
      respondErrorAndClose(exchange, ErrorResponse.INVALID_URI);
      return;
    }

    handleGetObject(exchange, bucketName, keyName);
  }
示例#12
0
 private Response doGet(HttpExchange httpExchange) {
   String query = httpExchange.getRequestURI().getQuery();
   if (query == null) {
     return Response.badRequest("Absent query in request");
   }
   Map<String, String> map = queryToMap(query);
   String token = map.get(Constants.REQUEST_PARAM_TOKEN);
   if (StringUtils.isEmpty(token)) {
     return Response.badRequest("Token query parameter is required");
   }
   try {
     int index = MessageHelper.parseToken(token);
     if (index > messageStorage.size()) {
       return Response.badRequest(
           String.format(
               "Incorrect token in request: %s. Server does not have so many messages", token));
     }
     Portion portion = new Portion(index);
     List<Message> messages = messageStorage.getPortion(portion);
     String responseBody = MessageHelper.buildServerResponseBody(messages, messageStorage.size());
     return Response.ok(responseBody);
   } catch (InvalidTokenException e) {
     return Response.badRequest(e.getMessage());
   }
 }
示例#13
0
  private void parseGetParameters(HttpExchange exchange) throws UnsupportedEncodingException {

    Map<String, Object> parameters = new HashMap<String, Object>();
    URI requestedUri = exchange.getRequestURI();
    String query = requestedUri.getRawQuery();
    parseQuery(query, parameters);
    exchange.setAttribute("parameters", parameters);
  }
示例#14
0
 private void handleListObjects(HttpExchange exchange, String bucketName) throws IOException {
   if (buckets.containsKey(bucketName)) {
     String prefix = getQueryParamValue(exchange.getRequestURI(), PREFIX_QUERY_PARAMETER);
     respondListObjectsAndClose(exchange, bucketName, prefix);
   } else {
     respondErrorAndClose(exchange, ErrorResponse.NO_SUCH_BUCKET);
   }
 }
 @Override
 @Property(MessageContext.QUERY_STRING)
 public String getQueryString() {
   URI requestUri = httpExchange.getRequestURI();
   String query = requestUri.getQuery();
   if (query != null) return query;
   return null;
 }
 private void addNewPlayer(HttpExchange t) throws IOException {
   String nick;
   String[] queries = t.getRequestURI().getQuery().split("&");
   String[] temp = queries[0].split("=");
   nick = temp[1];
   // System.out.println("here : " + nick);
   screen.addFighter(nick);
 }
示例#17
0
    @Override
    public void handle(HttpExchange t) throws IOException {
      LOGGER.debug("root req " + t.getRequestURI());
      if (RemoteUtil.deny(t)) {
        throw new IOException("Access denied");
      }
      if (t.getRequestURI().getPath().contains("favicon")) {
        RemoteUtil.sendLogo(t);
        return;
      }

      HashMap<String, Object> vars = new HashMap<>();
      vars.put("serverName", configuration.getServerName());
      vars.put("profileName", configuration.getProfileName());

      String response = parent.getResources().getTemplate("start.html").execute(vars);
      RemoteUtil.respond(t, response, 200, "text/html");
    }
 @Override
 @Property(MessageContext.PATH_INFO)
 public String getPathInfo() {
   URI requestUri = httpExchange.getRequestURI();
   String reqPath = requestUri.getPath();
   String ctxtPath = httpExchange.getHttpContext().getPath();
   if (reqPath.length() > ctxtPath.length()) {
     return reqPath.substring(ctxtPath.length());
   }
   return null;
 }
 private void sendIcon(HttpExchange exchange) {
   String hashCode = exchange.getRequestURI().getPath();
   hashCode = hashCode.substring(hashCode.indexOf("fticons/") + 8);
   BufferedImage bi = null;
   try {
     bi = iconHelper.getIconFromMap(Integer.parseInt(hashCode));
   } catch (NoSuchAlgorithmException e) {
     writeResponse(exchange, "Impossible to generate MD% hash for save an image" + hashCode, 400);
   }
   writeImageToStream(bi, exchange);
 }
示例#20
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();
    }
 private void sendImageFile(HttpExchange exchange) {
   String path = exchange.getRequestURI().getPath();
   if (path.contains("resources")) {
     path = path.substring(path.indexOf("resources") + 9);
   }
   BufferedImage bi;
   try {
     bi = ImageIO.read(MyBaseHandler.class.getResourceAsStream(path));
     writeImageToStream(bi, exchange);
   } catch (IOException e) {
     LOG.error(e);
   }
 }
 protected boolean parseRequest(HttpExchange exchange) {
   String param = exchange.getRequestURI().getQuery();
   if (param != null) {
     if (param.contains("file=highlighting.js")) {
       sendResourceFile(exchange);
       return true;
     } else if (param.contains("file=dialog.js")) {
       sendResourceFile(exchange);
       return true;
     } else if (param.contains("type=jquery_lib")) {
       sendResourceFile(exchange);
       return true;
     } else if (param.contains("type=css")) {
       writeResponse(exchange, generateCssStyles(param), 200);
       return true;
     } else if (param.contains("file_type=autocomplete")) {
       sendJsonData(exchange);
       return true;
     }
   } else {
     param = exchange.getRequestURI().toString();
     if (param.contains("fticons")) {
       sendIcon(exchange);
       return true;
     } else if (param.contains(".png")) {
       sendImageFile(exchange);
       return true;
     } else if (param.equals("/")) {
       sendModuleList(exchange);
       return true;
     } else if (param.contains(".css")
         && (param.contains("jquery.ui") || param.contains("jquery-ui"))) {
       sendResourceFile(exchange);
       return true;
     }
   }
   return false;
 }
示例#23
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();
 }
示例#24
0
 private Response doDelete(HttpExchange httpExchange) {
   String query = httpExchange.getRequestURI().getQuery();
   if (query == null) {
     return Response.badRequest("Absent query in request");
   }
   Map<String, String> map = queryToMap(query);
   String messageId = map.get(Constants.REQUEST_PARAM_MESSAGE_ID);
   if (StringUtils.isEmpty(messageId)) {
     return Response.badRequest("Message id query parameter is required");
   }
   if (messageStorage.removeMessage(messageId)) {
     return Response.ok();
   }
   return Response.badRequest("This message does not exist");
 }
  public void doHandle(HttpExchange t) throws Exception {
    String path = t.getRequestURI().getPath();
    int i = path.indexOf("/", 1);
    String cmd = path.substring(i + 1);
    s_logger.info("Get CMD request for " + cmd);
    if (cmd.equals("getstatus")) {
      ConsoleProxyClientStatsCollector statsCollector = ConsoleProxy.getStatsCollector();

      Headers hds = t.getResponseHeaders();
      hds.set("Content-Type", "text/plain");
      t.sendResponseHeaders(200, 0);
      OutputStreamWriter os = new OutputStreamWriter(t.getResponseBody(), "UTF-8");
      statsCollector.getStatsReport(os);
      os.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();
  }
    @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;
    }
示例#28
0
 @Override
 public void handle(HttpExchange httpExchange) throws IOException {
   Map<String, String> urlParams = getURLParams(httpExchange.getRequestURI());
   httpExchange.getResponseHeaders().set("Content-Type", "text/plain");
   boolean doExit = false;
   String response = "Invalid shutdown key\n";
   if (urlParams.containsKey("key") && urlParams.get("key").equals(shutdownKey)) {
     response = "Shutdown successful!\n";
     doExit = true;
   }
   httpExchange.sendResponseHeaders(HTTP_OK, response.getBytes().length);
   httpExchange.getResponseBody().write(response.getBytes());
   httpExchange.close();
   if (doExit) {
     System.exit(0);
   }
 }
  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();
  }
    @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();
    }