Esempio n. 1
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();
    }
 /** 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
    @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();
    }
Esempio n. 4
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();
 }
Esempio n. 5
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();
 }
 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. 8
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();
  }
  @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. 10
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. 11
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 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. 13
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();
    }
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;
    }

    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 setResponseHeaders(Map<String, List<String>> headers) {
   Headers r = httpExchange.getResponseHeaders();
   r.clear();
   for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
     String name = entry.getKey();
     List<String> values = entry.getValue();
     if (name.equalsIgnoreCase("Content-Length") || name.equalsIgnoreCase("Content-Type")) {
       continue; // ignore headers that interfere with our correct operations
     } else {
       r.put(name, new ArrayList<String>(values));
     }
   }
 }
Esempio n. 16
0
 public static void respond(HttpExchange t, byte[] response, int status, String mime) {
   if (response != null) {
     if (mime != null) {
       Headers hdr = t.getResponseHeaders();
       hdr.add("Content-Type", mime);
     }
     try (OutputStream os = t.getResponseBody()) {
       t.sendResponseHeaders(status, response.length);
       os.write(response);
       os.close();
     } catch (Exception e) {
       LOGGER.debug("Error sending response: " + e);
     }
   }
 }
  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();
  }
Esempio n. 19
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();
  }
Esempio n. 21
0
  private void sendResponse(HttpExchange httpExchange, Response response) {
    try (OutputStream os = httpExchange.getResponseBody()) {
      byte[] bytes = response.getBody().getBytes();

      Headers headers = httpExchange.getResponseHeaders();
      headers.add(Constants.REQUEST_HEADER_ACCESS_CONTROL_ORIGIN, "*");
      httpExchange.sendResponseHeaders(response.getStatusCode(), bytes.length);

      os.write(bytes);
      // there is no need to close stream manually
      // as try-catch with auto-closable is used
      /**
       * {@see http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html}
       */
    } catch (IOException e) {
      logger.error("Could not send response", e);
    }
  }
Esempio n. 22
0
 /** Write the given resource as an http response body. */
 public boolean write(String filename, HttpExchange t) throws IOException {
   InputStream stream = getInputStream(filename);
   if (stream != null) {
     Headers headers = t.getResponseHeaders();
     if (!headers.containsKey("Content-Type")) {
       String mime = getContentType(filename);
       if (mime != null) {
         headers.add("Content-Type", mime);
       }
     }
     // Note: available() isn't officially guaranteed to return the full
     // stream length but effectively seems to do so in our context.
     t.sendResponseHeaders(200, stream.available());
     dump(stream, t.getResponseBody());
     return true;
   }
   return false;
 }
  /** 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());
  }
Esempio n. 24
0
 @Override
 public void handle(HttpExchange t) throws IOException {
   if (RemoteUtil.deny(t)) {
     throw new IOException("Access denied");
   }
   String id = RemoteUtil.getId("thumb/", t);
   LOGGER.trace("web thumb req " + id);
   if (id.contains("logo")) {
     RemoteUtil.sendLogo(t);
     return;
   }
   RootFolder root = parent.getRoot(RemoteUtil.userName(t), t);
   if (root == null) {
     LOGGER.debug("weird root in thumb req");
     throw new IOException("Unknown root");
   }
   final DLNAResource r = root.getDLNAResource(id, root.getDefaultRenderer());
   if (r == null) {
     // another error
     LOGGER.debug("media unknown");
     throw new IOException("Bad id");
   }
   InputStream in;
   if (!configuration.isShowCodeThumbs() && !r.isCodeValid(r)) {
     // we shouldn't show the thumbs for coded objects
     // unless the code is entered
     in = r.getGenericThumbnailInputStream(null);
   } else {
     r.checkThumbnail();
     in = r.getThumbnailInputStream();
   }
   Headers hdr = t.getResponseHeaders();
   hdr.add("Content-Type", r.getThumbnailContentType());
   hdr.add("Accept-Ranges", "bytes");
   hdr.add("Connection", "keep-alive");
   t.sendResponseHeaders(200, in.available());
   OutputStream os = t.getResponseBody();
   LOGGER.trace("input is {} output is {}", in, os);
   RemoteUtil.dump(in, os);
 }
  public @NotNull OutputStream getOutput() throws IOException {
    assert !outputWritten;
    outputWritten = true;

    List<String> lenHeader = httpExchange.getResponseHeaders().get("Content-Length");
    int length = (lenHeader != null) ? Integer.parseInt(lenHeader.get(0)) : 0;
    httpExchange.sendResponseHeaders(getStatus(), length);

    // Light weight http server's OutputStream.close() throws exception if
    // all the bytes are not read on the client side(StreamMessage on the client
    // side doesn't read all bytes.
    return new FilterOutputStream(httpExchange.getResponseBody()) {
      @Override
      public void close() throws IOException {
        try {
          super.close();
        } catch (IOException ioe) {
          // Ignoring purposefully.
        }
      }
    };
  }
    @Override
    public void handle(HttpExchange httpExchange) throws IOException {
      Map<String, String> params =
          EncodingHelper.parseKeyValueList(httpExchange.getRequestURI().getQuery(), '&', true);

      if (params == null
          || !params.containsKey(STATUS_PARAM_NAME)
          || !params.containsKey(DATA_PARAM_NAME)
          || !params.get(STATUS_PARAM_NAME).equals(STATUS_SUCCESS)) {

        httpExchange.sendResponseHeaders(400, -1);
        if (authCodeCallback != null) {
          authCodeCallback.onAuthCodeReceived(null, params);
        }
        return;
      }

      code = params.get(DATA_PARAM_NAME);

      // setup response headers
      Headers headers = httpExchange.getResponseHeaders();
      headers.add("Content-Type", "text/html");
      httpExchange.sendResponseHeaders(200, 0);

      // send browser response
      InputStream input = getClass().getClassLoader().getResourceAsStream("auth-response.html");
      OutputStream output = httpExchange.getResponseBody();
      ByteStreams.copy(input, output);
      output.close();
      input.close();

      // raise the notification for the code
      if (authCodeCallback != null) {
        authCodeCallback.onAuthCodeReceived(code, params);
      }
    }
Esempio n. 27
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);
  }
Esempio n. 28
0
  public RootFolder getRoot(String user, boolean create, HttpExchange t) {
    String groupTag = getTag(user);
    String cookie = RemoteUtil.getCookie("UMS", t);
    RootFolder root;
    synchronized (roots) {
      root = roots.get(cookie);
      if (root == null) {
        // Double-check for cookie errors
        WebRender valid = RemoteUtil.matchRenderer(user, t);
        if (valid != null) {
          // A browser of the same type and user is already connected at
          // this ip but for some reason we didn't get a cookie match.
          RootFolder validRoot = valid.getRootFolder();
          // Do a reverse lookup to see if it's been registered
          for (Map.Entry<String, RootFolder> entry : roots.entrySet()) {
            if (entry.getValue() == validRoot) {
              // Found
              root = validRoot;
              cookie = entry.getKey();
              LOGGER.debug(
                  "Allowing browser connection without cookie match: {}: {}",
                  valid.getRendererName(),
                  t.getRemoteAddress().getAddress());
              break;
            }
          }
        }
      }

      if (!create || (root != null)) {
        t.getResponseHeaders().add("Set-Cookie", "UMS=" + cookie + ";Path=/");
        return root;
      }

      ArrayList<String> tag = new ArrayList<>();
      tag.add(user);
      if (!groupTag.equals(user)) {
        tag.add(groupTag);
      }

      tag.add(t.getRemoteAddress().getHostString());
      tag.add("web");
      root = new RootFolder(tag);
      try {
        WebRender render = new WebRender(user);
        root.setDefaultRenderer(render);
        render.setRootFolder(root);
        render.associateIP(t.getRemoteAddress().getAddress());
        render.associatePort(t.getRemoteAddress().getPort());
        if (configuration.useWebSubLang()) {
          render.setSubLang(StringUtils.join(RemoteUtil.getLangs(t), ","));
        }
        //				render.setUA(t.getRequestHeaders().getFirst("User-agent"));
        render.setBrowserInfo(
            RemoteUtil.getCookie("UMSINFO", t), t.getRequestHeaders().getFirst("User-agent"));
        PMS.get().setRendererFound(render);
      } catch (ConfigurationException e) {
        root.setDefaultRenderer(RendererConfiguration.getDefaultConf());
      }
      // root.setDefaultRenderer(RendererConfiguration.getRendererConfigurationByName("web"));
      root.discoverChildren();
      cookie = UUID.randomUUID().toString();
      t.getResponseHeaders().add("Set-Cookie", "UMS=" + cookie + ";Path=/");
      roots.put(cookie, root);
    }
    return root;
  }
Esempio n. 29
0
  /**
   * creates a new command based on which /move/ method is called and executes that command one the
   * correct game.
   *
   * @post the command is executed correctly. If invalid params, returns 400. If error in server,
   *     returns 500.
   */
  @Override
  public void handle(HttpExchange exchange) throws IOException {
    String extension = "";
    System.out.println("move handler");
    String json = jsonStringFromExchange(exchange.getRequestBody());
    System.out.println(json);
    Input input = new Gson().fromJson(json, Input.class);
    switch (input.getMethod()) {
      case "/moves/sendChat":
        extension = "sent a chat";
        command = new SendChatCommand();
        break;
      case "/moves/rollNumber":
        extension = "rolled a ";
        System.out.println(extension);
        command = new RollNumberCommand();
        break;
      case "/moves/robPlayer":
        extension = "burgled a player";
        command = new RobPlayerCommand();
        break;
      case "/moves/finishTurn":
        extension = "finished his/her turn";
        command = new FinishTurnCommand();
        break;
      case "/moves/buyDevCard":
        extension = "bought a dev card";
        command = new BuyDevCardCommand();
        break;
      case "/moves/Year_of_Plenty":
        extension = "cast Year-of-Plenty";
        command = new PlayYearOfPlentyCommand();
        break;
      case "/moves/Road_Building":
        extension = "cast Road-Building";
        command = new PlayRoadBuildingCommand();
        break;
      case "/moves/Soldier":
        extension = "Sent a Chat";
        command = new PlaySoldierCommand();
        break;
      case "/moves/Monument":
        extension = "cast Monument";
        command = new PlayMonumentCommand();
        break;
      case "/moves/Monopoly":
        extension = "cast Monopoly";
        command = new PlayMonopolyCommand();
        break;
      case "/moves/buildRoad":
        extension = "built a road";
        command = new BuildRoadCommand();
        break;
      case "/moves/buildCity":
        extension = "built a city";
        command = new BuildCityCommand();
        break;
      case "/moves/buildSettlement":
        extension = "built a settlement";
        command = new BuildSettlementCommand();
        break;
      case "/moves/offerTrade":
        extension = "offered a trade";
        command = new OfferTradeCommand();
        break;
      case "/moves/acceptTrade":
        extension = "accepted a trade";
        command = new AcceptTradeCommand();
        break;
      case "/moves/maritimeTrade":
        extension = "traded with pirates";
        command = new MaritimeTradeCommand();
        break;
      case "/moves/discardCards":
        extension = "sent his cards to the graveyard";
        command = new DiscardCardsCommand();
        break;
    }

    String cookie = exchange.getRequestHeaders().getFirst("Cookie");
    String[] cookieArray = cookie.split(";");

    if (command != null && cookieArray.length == 2) {
      try {
        System.out.println("q");
        String gameCookie = cookieArray[1].trim();
        StringBuilder temp = new StringBuilder(gameCookie);
        System.out.println("w");
        int index = temp.lastIndexOf("catan.game=") + 11;
        int gameId = Integer.parseInt(temp.substring(index, temp.length()));
        System.out.println("e");
        GameModel model = GameHub.getInstance().getModel(gameId);
        System.out.println("r");
        MoveCommand moveCommand = (MoveCommand) command;
        moveCommand.setGameModel(model);
        moveCommand.setInput(json);
        System.out.println("t");
        GameModel updatedModel = (GameModel) moveCommand.execute(json);
        GameHub.getInstance().updateModel(updatedModel);
        System.out.println("y");
        // add log to GameHistory
        gameCookie = cookieArray[0].trim();
        temp = new StringBuilder(gameCookie);
        System.out.println("u");
        index = temp.lastIndexOf("catan.user="******"i");
        if (extension.equals("rolled a ")) {
          System.out.println("o");
          RollNumberInput rollInput = new ObjectMapper().readValue(json, RollNumberInput.class);
          extension = extension + rollInput.getNumber();
        }
        if (extension.equals("accepted a trade")) {
          System.out.println("p");
          AcceptTradeInput atinput = new ObjectMapper().readValue(json, AcceptTradeInput.class);
          if (!atinput.isWillAccept()) extension = "rejected a trade";
        }
        System.out.println("a");
        String message = name + " " + extension + ".";
        System.out.printf("message %s and id %d\n", message, pId);
        LogEntry le = new LogEntry(cc, message);
        GameHub.getInstance().getModel(gameId).getLogs().add(le);
        // finished with log

        exchange.getResponseHeaders().set("Content-Type", "text/html");
        exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0);

        // write to response body
        Writer writer = new OutputStreamWriter(exchange.getResponseBody());
        String toWrite = new ObjectMapper().writeValueAsString(updatedModel);
        writer.write(toWrite);
        writer.close();

        exchange.getResponseBody().close();

        // add command to persistence
        GameHub.getInstance().getGameDAO().addCommand(gameId, moveCommand);

      } catch (ServerException e) {
        exchange.sendResponseHeaders(HttpURLConnection.HTTP_BAD_REQUEST, -1);
      }
    } else {
      exchange.sendResponseHeaders(HttpURLConnection.HTTP_BAD_REQUEST, -1);
    }
  }
  @Override
  public void handle(HttpExchange t) throws IOException {
    // System.out.println("LOG" + t.getRequestURI().getPath());
    System.out.println("LOG" + t.getRequestURI().getQuery());
    String path = t.getRequestURI().getPath();
    String[] paths = path.split("/"); // paths[0] é vazio , paths[1] é sempre
    // canvas senão não chega a esta
    // função
    switch (paths[2]) {
      case "newPlayer":
        addNewPlayer(t);
        break;
      case "move":
        String nick;
        String[] queries = t.getRequestURI().getQuery().split("&");
        String[] temp = queries[0].split("=");
        nick = temp[1];
        temp = queries[1].split("=");
        String ac = temp[1];
        Fighter tempf;
        switch (ac) {
          case "leftdown":
            tempf = screen.getFighter(nick);
            if (tempf != null) {
              tempf.keyDown(Keys.A);
            }
            break;
          case "rightdown":
            tempf = screen.getFighter(nick);
            if (tempf != null) {
              tempf.keyDown(Keys.D);
            }
            break;
          case "updown":
            tempf = screen.getFighter(nick);
            if (tempf != null) {
              tempf.keyDown(Keys.W);
            }
            break;
          case "atackdown":
            tempf = screen.getFighter(nick);
            if (tempf != null) {
              tempf.keyDown(Keys.SPACE);
            }
            break;
          case "leftup":
            tempf = screen.getFighter(nick);
            if (tempf != null) {
              tempf.keyUp(Keys.A);
            }
            break;
          case "rightup":
            tempf = screen.getFighter(nick);
            if (tempf != null) {
              tempf.keyUp(Keys.D);
            }
            break;
          case "upup":
            tempf = screen.getFighter(nick);
            if (tempf != null) {
              tempf.keyUp(Keys.W);
            }
            break;
          case "atackup":
            tempf = screen.getFighter(nick);
            if (tempf != null) {
              tempf.keyUp(Keys.SPACE);
            }
            break;
        }
        break;
      default:
        break;
    }

    String response = "success";

    t.getResponseHeaders().add("Access-Control-Allow-Origin", "*");
    t.sendResponseHeaders(200, response.length());
    OutputStream os = t.getResponseBody();
    os.write(response.getBytes());

    os.close();
  }