public static void main(String[] args) { Vertx vertx = Vertx.vertx(); Router router = Router.router(vertx); router.get("/").handler(rc -> rc.response().end("Hello")); router.get("/:name").handler(rc -> rc.response().end("Hello " + rc.pathParam("name"))); vertx.createHttpServer() .requestHandler(router) .listen(8080); } }
Router router = Router.router(vertx); router.route().handler(BodyHandler.create()); .addPathParam("pathParam", ParameterType.FLOAT); router.post("/hello/:pathParam") .handler(validationHandler) .handler((routingContext) -> { .failureHandler((routingContext) -> { Throwable failure = routingContext.failure(); if (failure instanceof ValidationException) { router.post("/jsonUploader") .handler(HTTPRequestValidationHandler.create().addJsonBodySchema("{type: string}")) .handler((routingContext -> { RequestParameters params = routingContext.get("parsedParameters"); JsonObject body = params.body().getJsonObject(); router.get("/superAwesomeParameter") .handler(HTTPRequestValidationHandler.create() .handler((routingContext -> { RequestParameters params = routingContext.get("parsedParameters"); Integer primeNumber = params.queryParameter("primeNumber").getInteger();
@Override public void start() throws Exception { Router router = Router.router(vertx); router.route().blockingHandler(routingContext -> { // Blocking handlers are allowed to block the calling thread // So let's simulate a blocking action or long running operation try { Thread.sleep(5000); } catch (Exception ignore) { } // Now call the next handler routingContext.next(); }, false); router.route().handler(routingContext -> { routingContext.response().putHeader("content-type", "text/html").end("Hello World!"); }); vertx.createHttpServer().requestHandler(router).listen(8080); } }
Router router = Router.router(vertx); router.route().handler(BodyHandler.create()); router.route("/products*").handler(routingContext -> client.getConnection(res -> { if (res.failed()) { routingContext.fail(res.cause()); } else { SQLConnection conn = res.result(); routingContext.put("conn", conn); routingContext.addHeadersEndHandler(done -> conn.close(v -> { })); routingContext.next(); })).failureHandler(routingContext -> { SQLConnection conn = routingContext.get("conn"); if (conn != null) { router.get("/products/:productID").handler(that::handleGetProduct); router.post("/products").handler(that::handleAddProduct); router.get("/products").handler(that::handleListProducts);
@Test public void testFailureHandler2CallFail() throws Exception { String path = "/blah"; router.route(path).handler(rc -> rc.fail(400)); router.route("/bl*").failureHandler(frc -> { assertEquals(400, frc.statusCode()); frc.response().setStatusCode(400).setStatusMessage("oh dear").end(); }); testRequest(HttpMethod.GET, path, 400, "oh dear"); }
@Test public void testAcceptDotisAnyCharacter2() throws Exception { router.route().handler(CorsHandler.create("vertx.io")); // dot matches any character - watch out! router.route().handler(context -> context.response().end()); testRequest(HttpMethod.GET, "/", req -> req.headers().add("origin", "vertx.io"), resp -> checkHeaders(resp, "vertx.io", null, null, null), 200, "OK", null); }
@Test public void testProducesAll2() throws Exception { router.route().produces("application/json").handler(rc -> { rc.response().setStatusMessage(rc.getAcceptableContentType()); rc.response().end(); }); testRequestWithAccepts(HttpMethod.GET, "/foo", "*", 200, "application/json"); }
@Test public void testRoutePathAndMultipleMethodBuilder() throws Exception { String path = "/blah"; router.route().path(path).method(HttpMethod.GET).method(HttpMethod.POST).handler(rc -> rc.response().setStatusCode(200).setStatusMessage(rc.request().path()).end()); testPathExact(HttpMethod.GET, path); testPathExact(HttpMethod.POST, path); testRequest(HttpMethod.PUT, path, 404, "Not Found"); }
@Override public void start() throws Exception { Router router = Router.router(vertx); allowedMethods.add(HttpMethod.PUT); router.route().handler(CorsHandler.create("*").allowedHeaders(allowedHeaders).allowedMethods(allowedMethods)); router.get("/access-control-with-get").handler(ctx -> { HttpServerResponse httpServerResponse = ctx.response(); httpServerResponse.setChunked(true); MultiMap headers = ctx.request().headers(); for (String key : headers.names()) { httpServerResponse.write(key + ": "); httpServerResponse.write(headers.get(key)); httpServerResponse.write("<br>"); }); router.post("/access-control-with-post-preflight").handler(ctx -> { HttpServerResponse httpServerResponse = ctx.response(); httpServerResponse.setChunked(true); MultiMap headers = ctx.request().headers(); for (String key : headers.names()) { httpServerResponse.write(key + ": "); httpServerResponse.write(headers.get(key)); router.route().handler(StaticHandler.create());
@Test public void testFailureinHandlingFailureWithInvalidStatusMessage() throws Exception { String path = "/blah"; router.route(path).handler(rc -> { throw new RuntimeException("ouch!"); }).failureHandler(frc -> frc.response().setStatusMessage("Hello\nWorld").end()); testRequest(HttpMethod.GET, path, 500, "Internal Server Error"); }
@Override public void start() throws Exception { Router router = Router.router(vertx); router.get("/api/newToken").handler(ctx -> { List<String> authorities = new ArrayList<>(); router.route("/api/protected*").handler(JWTAuthHandler.create(jwt)); router.get("/api/protected").handler(ctx -> { router.get("/api/protected/defcon1").handler(ctx -> { ctx.user().isAuthorised("defcon1", allowed -> { }); router.get("/api/protected/defcon2").handler(ctx -> { ctx.user().isAuthorised("defcon2", allowed -> { }); router.get("/api/protected/defcon3").handler(ctx -> { ctx.user().isAuthorised("defcon3", allowed -> { router.route().handler(StaticHandler.create());
router.get("/api/newToken").handler(ctx -> { router.route("/api/protected").handler(JWTAuthHandler.create(jwt)); router.get("/api/protected").handler(ctx -> { ctx.response().putHeader("Content-Type", "text/plain"); ctx.response().end("this secret is not defcon!"); }); router.route("/api/protected/defcon1").handler(JWTAuthHandler.create(jwt).addAuthority("defcon1")); router.get("/api/protected/defcon1").handler(ctx -> { ctx.response().putHeader("Content-Type", "text/plain"); ctx.response().end("this secret is defcon1!"); router.route("/api/protected/defcon2").handler(JWTAuthHandler.create(jwt).addAuthority("defcon2")); router.get("/api/protected/defcon2").handler(ctx -> { ctx.response().putHeader("Content-Type", "text/plain"); ctx.response().end("this secret is defcon2!"); router.route("/api/protected/defcon3").handler(JWTAuthHandler.create(jwt).addAuthority("defcon3")); router.get("/api/protected/defcon3").handler(ctx -> { ctx.response().putHeader("Content-Type", "text/plain"); ctx.response().end("this secret is defcon3!"); router.route().handler(StaticHandler.create());
@Override public void start() throws Exception { Router router = Router.router(vertx); router.route().handler(BodyHandler.create()); router.route("/").handler(routingContext -> { routingContext.response().putHeader("content-type", "text/html").end( "<form action=\"/form\" method=\"post\">\n" + " <div>\n" + router.post("/form").handler(ctx -> { ctx.response().putHeader(HttpHeaders.CONTENT_TYPE, "text/plain"); ctx.response().end("Hello " + ctx.request().getParam("name") + "!"); });
@Override public void start() throws Exception { Router router = Router.router(vertx); router.route().handler(BodyHandler.create().setUploadsDirectory("uploads")); router.route("/").handler(routingContext -> { routingContext.response().putHeader("content-type", "text/html").end( "<form action=\"/form\" method=\"post\" enctype=\"multipart/form-data\">\n" + " <div>\n" + router.post("/form").handler(ctx -> { ctx.response().putHeader("Content-Type", "text/plain"); ctx.response().setChunked(true); for (FileUpload f : ctx.fileUploads()) {
@Override public void start() throws Exception { Router router = Router.router(vertx); router.route().handler(CookieHandler.create()); router.route().handler(BodyHandler.create()); router.route().handler(SessionHandler.create(LocalSessionStore.create(vertx))); router.route().handler(UserSessionHandler.create(authProvider)); router.route("/private/*").handler(RedirectAuthHandler.create(authProvider, "/loginpage.html")); router.route("/private/*").handler(StaticHandler.create().setCachingEnabled(false).setWebRoot("private")); router.route("/loginhandler").handler(FormLoginHandler.create(authProvider)); router.route("/logout").handler(context -> { context.clearUser(); context.response().putHeader("location", "/").setStatusCode(302).end(); }); router.route().handler(StaticHandler.create());
@Override public void start() { Router router = Router.router(vertx); router.get("/").handler(rc -> { String param = rc.request().getParam("name"); if (param == null) { param = "world"; } vertx.eventBus().<String>send("request", param, reply -> { if (reply.failed()) { rc.response().setStatusCode(400).end(reply.cause().getMessage()); } else { String content = reply.result().body(); rc.response().end(content); } }); }); vertx.createHttpServer() .requestHandler(router) .listen(8080); } }
@Test public void testProducesWithParameter() throws Exception { router.route().produces("text/html;boo=ya").handler(rc -> rc.response().end()); testRequestWithAccepts(HttpMethod.GET, "/foo", "text/html;boo=ya", 200, "OK"); testRequestWithAccepts(HttpMethod.GET, "/foo", "text/html;boo", 404, "Not Found"); testRequestWithAccepts(HttpMethod.GET, "/foo", "text/html", 404, "Not Found"); }
@Test public void testSubRouteRegex() throws Exception { Router subRouter = Router.router(vertx); router.routeWithRegex("/foo/.*").handler(subRouter::handleContext).failureHandler(subRouter::handleFailure); subRouter.route("/blah").handler(rc -> rc.response().setStatusMessage("sausages").end()); testRequest(HttpMethod.GET, "/foo/blah", 500, "Internal Server Error"); }