Пример #1
0
  public void handle(ClientData clientData) {
    HttpServerRequest req = clientData.getRequest();
    HttpServerResponse res = req.response;
    String requestedFileName = clientData.getPath();
    String resourceRootDir = getRootDir();

    File rootDir = new File(requestedFileName);
    if (!rootDir.exists()) {
      copyFilesToDir();
    }

    switch (requestedFileName) {
      case "/static/flashsocket/WebSocketMainInsecure.swf":
        res.sendFile(resourceRootDir + "/WebSocketMainInsecure.swf");
        break;
      case "/static/flashsocket/WebSocketMain.swf":
        res.sendFile(resourceRootDir + "/WebSocketMain.swf");
        break;
      case "/socket.io.js":
        res.sendFile(resourceRootDir + "/socket.io.js");
        break;
      case "/socket.io.min.js":
        res.sendFile(resourceRootDir + "/socket.io.min.js");
        break;
      default:
        throw new IllegalArgumentException(requestedFileName);
    }
    res.close();
  }
Пример #2
0
  @Override
  public OutputStream getOutputStream() throws IOException {
    response.setChunked(true);
    return new OutputStream() {
      @Override
      public void write(int b) throws IOException {
        Buffer buffer = new Buffer(1);
        buffer.appendByte((byte) b);
        response.write(buffer);
      }

      @Override
      public void write(byte[] b, int off, int len) throws IOException {
        Buffer buffer = new Buffer(len);
        buffer.appendBytes(b, off, len);
        response.write(buffer);
      }
    };
  }
Пример #3
0
 protected void sendInvalidJSON(HttpServerResponse response) {
   response.statusCode = 500;
   response.end("Broken JSON encoding.");
 }
  /** text/javascript text/css text/html; charset=GBK */
  @Override
  public void handle(final HttpServerRequest req) {

    final HttpServerResponse res = req.response();

    String uri = req.path().substring(1);

    if (uri.startsWith("web")) {
      uri = uri.substring(4);
    }
    if (uri.isEmpty()) {
      uri = indexPage;
    }
    String ext = Utils.getFileExtWithDot(uri);
    if (".js".equals(ext) || ".css".equals(ext) || ".html".equals(ext)) {
      int i = 0;
      if (".css".equals(ext)) {
        i = 1;
      } else {
        i = 2;
      }
      res.headers().set("content-type", ctary[i]);
      String finalFile = webRootPath.resolve(uri).toString();

      //      if(fileSystem.existsSync(finalFile)){
      //        fileSystem.readFile(finalFile, new AsyncResultHandler<Buffer>() {
      //          public void handle(AsyncResult<Buffer> ar) {
      //            if (ar.succeeded()) {
      //              res.headers().set("content-length", ar.result().length() + "");
      //              res.end(ar.result());
      //            } else {
      //              logger.error("Failed to open file", ar.cause());
      //              res.end("File Read Error!");
      //            }
      //          }
      //        });
      //      } else {
      //        res.end("File Not Found!");
      //      }

      fileSystem.open(
          finalFile,
          new AsyncResultHandler<AsyncFile>() {
            public void handle(AsyncResult<AsyncFile> ar) {
              if (ar.succeeded()) {
                AsyncFile asyncFile = ar.result();
                res.setChunked(true);
                Pump.createPump(asyncFile, res).start();
                asyncFile.endHandler(
                    new VoidHandler() {
                      public void handle() {
                        res.end();
                      }
                    });
              } else {
                logger.error("Failed to open file", ar.cause());
                res.end("File Not Found!");
              }
            }
          });
    } else {
      res.sendFile(webRootPath.resolve(uri).toString());
    }
  }
Пример #5
0
 @Override
 public void sendRedirect(String url) throws IOException {
   response.putHeader("Location", url);
   response.setStatusCode(301);
 }
Пример #6
0
 @Override
 public void setStatus(int status) throws IOException {
   response.setStatusCode(status);
 }
Пример #7
0
 @Override
 public void sendError(int errorStatus) throws IOException {
   response.setStatusCode(errorStatus);
 }
Пример #8
0
 @Override
 public void setHeader(String header, String value) {
   response.putHeader(header, value);
 }
Пример #9
0
  public void start() {

    container.deployVerticle(StoreRepositoryVerticle.class.getName());
    container.deployWorkerVerticle(StaticFilesVerticle.class.getName());

    RouteMatcher matcher = new RouteMatcher();
    matcher.get(
        "/todos",
        (httpServerRequest) -> {
          vertx
              .eventBus()
              .send(
                  StoreRepositoryVerticle.GET_ALL,
                  "",
                  (Message<JsonArray> event) -> {
                    httpServerRequest
                        .response()
                        .putHeader("Content-Type", "application/json")
                        .setStatusCode(200)
                        .end(event.body().encodePrettily());
                  });
        });

    matcher.post(
        "/todos",
        (httpServerRequest) -> {
          httpServerRequest.bodyHandler(
              (buffer) -> {
                String body = buffer.toString();

                vertx
                    .eventBus()
                    .sendWithTimeout(
                        StoreRepositoryVerticle.SAVE,
                        new JsonObject(body),
                        1000,
                        (AsyncResult<Message<JsonObject>> event) -> {
                          HttpServerResponse response = httpServerRequest.response();
                          if (event.failed()) {
                            ReplyException rx = (ReplyException) event.cause();
                            response.setStatusCode(500).setStatusMessage(rx.getMessage()).end();
                          } else {
                            response.setStatusCode(201).end(event.result().body().encodePrettily());
                          }
                        });
              });
        });

    matcher.put(
        "/todos/:id",
        (httpServerRequest) -> {
          httpServerRequest.bodyHandler(
              (buffer) -> {
                String body = buffer.toString();

                vertx
                    .eventBus()
                    .sendWithTimeout(
                        StoreRepositoryVerticle.UPDATE,
                        new JsonObject(body),
                        1000,
                        (AsyncResult<Message<JsonObject>> event) -> {
                          HttpServerResponse response = httpServerRequest.response();
                          if (event.failed()) {
                            ReplyException rx = (ReplyException) event.cause();
                            response.setStatusCode(500).setStatusMessage(rx.getMessage()).end();
                          } else {
                            response.setStatusCode(204).end();
                          }
                        });
              });
        });

    matcher.delete(
        "/todos/:id",
        (httpServerRequest) -> {
          String todoId = httpServerRequest.params().get("id");
          vertx
              .eventBus()
              .sendWithTimeout(
                  StoreRepositoryVerticle.DELETE,
                  todoId,
                  1000,
                  (event) -> {
                    HttpServerResponse response = httpServerRequest.response();
                    if (event.failed()) {
                      ReplyException rx = (ReplyException) event.cause();
                      response.setStatusCode(500).setStatusMessage(rx.getMessage());
                    } else {
                      response.setStatusCode(204);
                    }
                    response.end();
                  });
        });

    matcher.getWithRegEx(
        ".*",
        (req) -> {
          String path;
          if (req.path().equals("/")) {
            path = "/index.html";
          } else {
            path = req.path();
          }
          container.logger().info("Static file for path " + path);

          vertx
              .eventBus()
              .sendWithTimeout(
                  StaticFilesVerticle.HANDLER_NAME,
                  path,
                  3000,
                  (AsyncResult<Message<String>> event) -> {
                    if (event.failed()) {
                      ReplyException ex = (ReplyException) event.cause();
                      req.response().setStatusCode(404).end(ex.getMessage());
                      return;
                    }

                    req.response().end(event.result().body());
                  });
        });

    vertx.createHttpServer().requestHandler(matcher).listen(8888);
    container.logger().info("TodoMVCVerticle started");
  }
Пример #10
0
 private void notAuthorised(HttpServerResponse response) {
   response.setStatusCode(HttpResponseStatus.UNAUTHORIZED.code());
   response.setStatusMessage(HttpResponseStatus.UNAUTHORIZED.reasonPhrase());
   response.end();
 }