public DefaultSockJSServer(final VertxInternal vertx, final HttpServer httpServer) {
    this.vertx = vertx;
    this.sessions = vertx.sharedData().getMap("_vertx.sockjssessions");
    // Any previous request and websocket handlers will become default handlers
    // if nothing else matches
    rm.noMatch(httpServer.requestHandler());
    wsMatcher.noMatch(
        new Handler<WebSocketMatcher.Match>() {
          Handler<ServerWebSocket> wsHandler = httpServer.websocketHandler();

          public void handle(WebSocketMatcher.Match match) {
            if (wsHandler != null) {
              wsHandler.handle(match.ws);
            }
          }
        });
    httpServer.requestHandler(
        new Handler<HttpServerRequest>() {
          @Override
          public void handle(HttpServerRequest req) {
            if (log.isTraceEnabled()) {
              log.trace("Got request in sockjs server: " + req.uri);
            }
            rm.handle(req);
          }
        });
    httpServer.websocketHandler(wsMatcher);
  }
 @Override
 public void handle(HttpServerRequest request) {
   if (!config.isAuthenticationEnabled() || authenticate(request)) {
     super.handle(request);
   } else {
     notAuthorised(request.response());
   }
 }
Beispiel #3
0
  public void start() {

    RouteMatcher rm = new RouteMatcher();

    rm.get(
        "/details/:user/:id",
        new Handler<HttpServerRequest>() {
          public void handle(HttpServerRequest req) {
            req.response.end(
                "User: "******"user") + " ID: " + req.getAllParams().get("id"));
          }
        });

    // Catch all - serve the index page
    rm.getWithRegEx(
        ".*",
        new Handler<HttpServerRequest>() {
          public void handle(HttpServerRequest req) {
            req.response.sendFile("route_match/index.html");
          }
        });

    server = new HttpServer().requestHandler(rm).listen(8080);
  }
  public DefaultSockJSServer(final VertxInternal vertx, final HttpServer httpServer) {
    this.vertx = vertx;
    this.sessions = vertx.sharedData().getMap("_vertx.sockjssessions");
    // Any previous request and websocket handlers will become default handlers
    // if nothing else matches
    rm.noMatch(httpServer.requestHandler());
    wsMatcher.noMatch(
        new Handler<WebSocketMatcher.Match>() {
          Handler<ServerWebSocket> wsHandler = httpServer.websocketHandler();

          public void handle(WebSocketMatcher.Match match) {
            wsHandler.handle(match.ws);
          }
        });

    httpServer.requestHandler(rm);
    httpServer.websocketHandler(wsMatcher);
  }
  public void installApp(JsonObject config, final Handler<SockJSSocket> sockHandler) {

    config = setDefaults(config);

    String prefix = config.getString("prefix");

    if (prefix == null || prefix.equals("") || prefix.endsWith("/")) {
      throw new IllegalArgumentException("Invalid prefix: " + prefix);
    }

    // Base handler for app

    rm.getWithRegEx(
        prefix + "\\/?",
        new Handler<HttpServerRequest>() {
          public void handle(HttpServerRequest req) {
            if (log.isTraceEnabled()) log.trace("Returning welcome response");
            req.response.headers().put("Content-Type", "text/plain; charset=UTF-8");
            req.response.end("Welcome to SockJS!\n");
          }
        });

    // Iframe handlers
    String iframeHTML =
        IFRAME_TEMPLATE.replace("{{ sockjs_url }}", config.getString("library_url"));
    Handler<HttpServerRequest> iframeHandler = createIFrameHandler(iframeHTML);

    // Request exactly for iframe.html
    rm.getWithRegEx(prefix + "\\/iframe\\.html", iframeHandler);

    // Versioned
    rm.getWithRegEx(prefix + "\\/iframe-[^\\/]*\\.html", iframeHandler);

    // Chunking test
    rm.postWithRegEx(prefix + "\\/chunking_test", createChunkingTestHandler());
    rm.optionsWithRegEx(
        prefix + "\\/chunking_test",
        BaseTransport.createCORSOptionsHandler(config, "OPTIONS, POST"));

    // Info
    rm.getWithRegEx(prefix + "\\/info", BaseTransport.createInfoHandler(config));
    rm.optionsWithRegEx(
        prefix + "\\/info", BaseTransport.createCORSOptionsHandler(config, "OPTIONS, GET"));

    // Transports

    Set<String> enabledTransports = new HashSet<>();
    enabledTransports.add(Transport.EVENT_SOURCE.toString());
    enabledTransports.add(Transport.HTML_FILE.toString());
    enabledTransports.add(Transport.JSON_P.toString());
    enabledTransports.add(Transport.WEBSOCKET.toString());
    enabledTransports.add(Transport.XHR.toString());
    for (Object tr : config.getArray("disabled_transports", new JsonArray())) {
      enabledTransports.remove(tr);
    }

    if (enabledTransports.contains(Transport.XHR.toString())) {
      new XhrTransport(vertx, rm, prefix, sessions, config, sockHandler);
    }
    if (enabledTransports.contains(Transport.EVENT_SOURCE.toString())) {
      new EventSourceTransport(vertx, rm, prefix, sessions, config, sockHandler);
    }
    if (enabledTransports.contains(Transport.HTML_FILE.toString())) {
      new HtmlFileTransport(vertx, rm, prefix, sessions, config, sockHandler);
    }
    if (enabledTransports.contains(Transport.JSON_P.toString())) {
      new JsonPTransport(vertx, rm, prefix, sessions, config, sockHandler);
    }
    if (enabledTransports.contains(Transport.WEBSOCKET.toString())) {
      new WebSocketTransport(vertx, wsMatcher, rm, prefix, sessions, config, sockHandler);
      new RawWebSocketTransport(vertx, wsMatcher, rm, prefix, sockHandler);
    }
    // Catch all for any other requests on this app

    rm.getWithRegEx(
        prefix + "\\/.+",
        new Handler<HttpServerRequest>() {
          public void handle(HttpServerRequest req) {
            if (log.isTraceEnabled())
              log.trace("Request: " + req.uri + " does not match, returning 404");
            req.response.statusCode = 404;
            req.response.end();
          }
        });
  }
  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");
  }