/** 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();
   }
 }
 @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();
 }
 @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();
 }
Exemple #4
0
 protected void handleGet(HttpExchange exchange) throws IOException {
   try {
     InputStream in = exchange.getRequestBody();
     ByteArrayOutputStream bout = new ByteArrayOutputStream();
     byte[] buf = new byte[4096];
     int read;
     while ((read = in.read(buf)) >= 0) {
       bout.write(buf, 0, read);
     }
     in.close();
     InetSocketAddress source = exchange.getRemoteAddress();
     byte[] raw = source.getHostName().getBytes();
     exchange.sendResponseHeaders(200, raw.length);
     exchange.getResponseBody().write(raw);
     exchange.close();
   } catch (Exception e) {
     e.printStackTrace();
     exchange.sendResponseHeaders(400, 0);
     exchange.close();
   }
 }
 @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();
   }
 }
 @Override
 public void handle(HttpExchange httpExchange) throws IOException {
   ++testConnectionTimeoutCount;
   Logger.info(
       this,
       "testNoHttpResponseExceptionHandler testConnectionTimeoutCount: "
           + testConnectionTimeoutCount);
   try {
     Thread.sleep(3000);
   } catch (InterruptedException e) {
     throw new RuntimeException(e);
   }
   Logger.info(this, "==========testNoHttpResponseExceptionHandler sleep 3s after.");
   //            httpExchange.sendResponseHeaders(200, 0);//no response
   httpExchange.close();
 }
 @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);
   }
 }
    @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();
    }
 @Override
 public void handle(HttpExchange t) throws IOException {
   try {
     Thread.currentThread()
         .setName("Cmd Thread " + Thread.currentThread().getId() + " " + t.getRemoteAddress());
     s_logger.info("CmdHandler " + t.getRequestURI());
     doHandle(t);
   } catch (Exception e) {
     s_logger.error(e.toString(), e);
     String response = "Not found";
     t.sendResponseHeaders(404, response.length());
     OutputStream os = t.getResponseBody();
     os.write(response.getBytes());
     os.close();
   } catch (OutOfMemoryError e) {
     s_logger.error("Unrecoverable OutOfMemory Error, exit and let it be re-launched");
     System.exit(1);
   } catch (Throwable e) {
     s_logger.error(e.toString(), e);
   } finally {
     t.close();
   }
 }
Exemple #10
0
  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();
    }
  }
    @Override
    public void handle(HttpExchange httpExchange) throws IOException {
      // Set common response headers
      httpExchange.getResponseHeaders().add("Access-Control-Allow-Origin", "*");

      Future<String> json =
          corenlpExecutor.submit(
              () -> {
                try {
                  // Get the document
                  Properties props =
                      new Properties() {
                        {
                          setProperty("annotators", "tokenize,ssplit,pos,lemma,ner,depparse");
                        }
                      };
                  Annotation doc = getDocument(props, httpExchange);
                  if (!doc.containsKey(CoreAnnotations.SentencesAnnotation.class)) {
                    StanfordCoreNLP pipeline = mkStanfordCoreNLP(props);
                    pipeline.annotate(doc);
                  }

                  // Construct the matcher
                  Map<String, String> params = getURLParams(httpExchange.getRequestURI());
                  // (get the pattern)
                  if (!params.containsKey("pattern")) {
                    respondError("Missing required parameter 'pattern'", httpExchange);
                    return "";
                  }
                  String pattern = params.get("pattern");
                  // (get whether to filter / find)
                  String filterStr = params.getOrDefault("filter", "false");
                  final boolean filter =
                      filterStr.trim().isEmpty()
                          || "true".equalsIgnoreCase(filterStr.toLowerCase());
                  // (create the matcher)
                  final SemgrexPattern regex = SemgrexPattern.compile(pattern);

                  // Run TokensRegex
                  return JSONOutputter.JSONWriter.objectToJSON(
                      (docWriter) -> {
                        if (filter) {
                          // Case: just filter sentences
                          docWriter.set(
                              "sentences",
                              doc.get(CoreAnnotations.SentencesAnnotation.class)
                                  .stream()
                                  .map(
                                      sentence ->
                                          regex
                                              .matcher(
                                                  sentence.get(
                                                      SemanticGraphCoreAnnotations
                                                          .CollapsedCCProcessedDependenciesAnnotation
                                                          .class))
                                              .matches())
                                  .collect(Collectors.toList()));
                        } else {
                          // Case: find matches
                          docWriter.set(
                              "sentences",
                              doc.get(CoreAnnotations.SentencesAnnotation.class)
                                  .stream()
                                  .map(
                                      sentence ->
                                          (Consumer<JSONOutputter.Writer>)
                                              (JSONOutputter.Writer sentWriter) -> {
                                                SemgrexMatcher matcher =
                                                    regex.matcher(
                                                        sentence.get(
                                                            SemanticGraphCoreAnnotations
                                                                .CollapsedCCProcessedDependenciesAnnotation
                                                                .class));
                                                int i = 0;
                                                while (matcher.find()) {
                                                  sentWriter.set(
                                                      Integer.toString(i),
                                                      (Consumer<JSONOutputter.Writer>)
                                                          (JSONOutputter.Writer matchWriter) -> {
                                                            IndexedWord match = matcher.getMatch();
                                                            matchWriter.set("text", match.word());
                                                            matchWriter.set(
                                                                "begin", match.index() - 1);
                                                            matchWriter.set("end", match.index());
                                                            for (String capture :
                                                                matcher.getNodeNames()) {
                                                              matchWriter.set(
                                                                  "$" + capture,
                                                                  (Consumer<JSONOutputter.Writer>)
                                                                      groupWriter -> {
                                                                        IndexedWord node =
                                                                            matcher.getNode(
                                                                                capture);
                                                                        groupWriter.set(
                                                                            "text", node.word());
                                                                        groupWriter.set(
                                                                            "begin",
                                                                            node.index() - 1);
                                                                        groupWriter.set(
                                                                            "end", node.index());
                                                                      });
                                                            }
                                                          });
                                                  i += 1;
                                                }
                                                sentWriter.set("length", i);
                                              }));
                        }
                      });
                } catch (Exception e) {
                  e.printStackTrace();
                  try {
                    respondError(e.getClass().getName() + ": " + e.getMessage(), httpExchange);
                  } catch (IOException ignored) {
                  }
                }
                return "";
              });

      // Send response
      byte[] response = new byte[0];
      try {
        response = json.get(5, TimeUnit.SECONDS).getBytes();
      } catch (InterruptedException | ExecutionException | TimeoutException e) {
        respondError("Timeout when executing Semgrex query", httpExchange);
      }
      if (response.length > 0) {
        httpExchange.getResponseHeaders().add("Content-Type", "text/json");
        httpExchange.getResponseHeaders().add("Content-Length", Integer.toString(response.length));
        httpExchange.sendResponseHeaders(HTTP_OK, response.length);
        httpExchange.getResponseBody().write(response);
        httpExchange.close();
      }
    }
    @Override
    public void handle(HttpExchange httpExchange) throws IOException {
      // Set common response headers
      httpExchange.getResponseHeaders().add("Access-Control-Allow-Origin", "*");

      // Get sentence.
      Properties props;
      Annotation ann;
      StanfordCoreNLP.OutputFormat of;
      log("[" + httpExchange.getRemoteAddress() + "] Received message");
      try {
        props = getProperties(httpExchange);
        ann = getDocument(props, httpExchange);
        of =
            StanfordCoreNLP.OutputFormat.valueOf(
                props.getProperty("outputFormat", "json").toUpperCase());
        // Handle direct browser connections (i.e., not a POST request).
        if (ann.get(CoreAnnotations.TextAnnotation.class).length() == 0) {
          log("[" + httpExchange.getRemoteAddress() + "] Interactive connection");
          staticPageHandle.handle(httpExchange);
          return;
        }
        log("[" + httpExchange.getRemoteAddress() + "] API call");
      } catch (Exception e) {
        // Return error message.
        e.printStackTrace();
        String response = e.getMessage();
        httpExchange.getResponseHeaders().add("Content-Type", "text/plain");
        httpExchange.sendResponseHeaders(HTTP_BAD_INPUT, response.length());
        httpExchange.getResponseBody().write(response.getBytes());
        httpExchange.close();
        return;
      }

      try {
        // Annotate
        StanfordCoreNLP pipeline = mkStanfordCoreNLP(props);
        Future<Annotation> completedAnnotationFuture =
            corenlpExecutor.submit(
                () -> {
                  pipeline.annotate(ann);
                  return ann;
                });
        Annotation completedAnnotation = completedAnnotationFuture.get(5, TimeUnit.SECONDS);

        // Get output
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        StanfordCoreNLP.createOutputter(props, AnnotationOutputter.getOptions(pipeline))
            .accept(completedAnnotation, os);
        os.close();
        byte[] response = os.toByteArray();

        httpExchange.getResponseHeaders().add("Content-Type", getContentType(props, of));
        httpExchange.getResponseHeaders().add("Content-Length", Integer.toString(response.length));
        httpExchange.sendResponseHeaders(HTTP_OK, response.length);
        httpExchange.getResponseBody().write(response);
        httpExchange.close();
      } catch (TimeoutException e) {
        respondError("CoreNLP request timed out", httpExchange);
      } catch (Exception e) {
        // Return error message.
        respondError(e.getClass().getName() + ": " + e.getMessage(), httpExchange);
      }
    }
 /**
  * A helper function to respond to a request with an error.
  *
  * @param response The description of the error to send to the user.
  * @param httpExchange The exchange to send the error over.
  * @throws IOException Thrown if the HttpExchange cannot communicate the error.
  */
 private void respondError(String response, HttpExchange httpExchange) throws IOException {
   httpExchange.getResponseHeaders().add("Content-Type", "text/plain");
   httpExchange.sendResponseHeaders(HTTP_ERR, response.length());
   httpExchange.getResponseBody().write(response.getBytes());
   httpExchange.close();
 }
  @Override
  public void handle(HttpExchange he) throws IOException {

    try {

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

          path = sb.toString();
        }

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

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

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

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

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

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

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