package examples;
import io.vertx.codegen.annotations.DataObject;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.eventbus.EventBus;
import io.vertx.core.http.*;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.auth.JWTOptions;
import io.vertx.ext.auth.KeyStoreOptions;
import io.vertx.ext.auth.User;
import io.vertx.ext.auth.authentication.AuthenticationProvider;
import io.vertx.ext.auth.authorization.AuthorizationProvider;
import io.vertx.ext.auth.authorization.PermissionBasedAuthorization;
import io.vertx.ext.auth.authorization.RoleBasedAuthorization;
import io.vertx.ext.auth.jwt.JWTAuth;
import io.vertx.ext.auth.jwt.JWTAuthOptions;
import io.vertx.ext.auth.oauth2.OAuth2Auth;
import io.vertx.ext.auth.oauth2.OAuth2FlowType;
import io.vertx.ext.auth.oauth2.OAuth2Options;
import io.vertx.ext.auth.oauth2.providers.GithubAuth;
import io.vertx.ext.auth.webauthn.*;
import io.vertx.ext.bridge.BridgeEventType;
import io.vertx.ext.bridge.PermittedOptions;
import io.vertx.ext.web.*;
import io.vertx.ext.web.common.template.TemplateEngine;
import io.vertx.ext.web.handler.*;
import io.vertx.ext.web.handler.sockjs.SockJSBridgeOptions;
import io.vertx.ext.web.handler.sockjs.SockJSHandler;
import io.vertx.ext.web.handler.sockjs.SockJSHandlerOptions;
import io.vertx.ext.web.sstore.ClusteredSessionStore;
import io.vertx.ext.web.sstore.LocalSessionStore;
import io.vertx.ext.web.sstore.SessionStore;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
public class WebExamples {
public void example1(Vertx vertx) {
HttpServer server = vertx.createHttpServer();
server.requestHandler(request -> {
HttpServerResponse response = request.response();
response.putHeader("content-type", "text/plain");
response.end("Hello World!");
});
server.listen(8080);
}
public void example2(Vertx vertx) {
HttpServer server = vertx.createHttpServer();
Router router = Router.router(vertx);
router.route().handler(ctx -> {
HttpServerResponse response = ctx.response();
response.putHeader("content-type", "text/plain");
response.end("Hello World from Vert.x-Web!");
});
server.requestHandler(router).listen(8080);
}
public void example3(Router router) {
Route route = router.route().path("/some/path/");
route.handler(ctx -> {
});
Route route2 = router.route().path("/some/path");
route2.handler(ctx -> {
});
}
public void example3_1(Router router) {
Route route = router.route().path("/some/path/*");
route.handler(ctx -> {
});
}
public void example4(Router router) {
Route route = router.route("/some/path/*");
route.handler(ctx -> {
});
}
public void example4_1(Router router) {
router
.route(HttpMethod.POST, "/catalogue/products/:productType/:productID/")
.handler(ctx -> {
String productType = ctx.pathParam("productType");
String productID = ctx.pathParam("productID");
});
}
public void example5(Router router) {
Route route = router.route().pathRegex(".*foo");
route.handler(ctx -> {
});
}
public void example6(Router router) {
Route route = router.routeWithRegex(".*foo");
route.handler(ctx -> {
});
}
public void example6_1(Router router) {
Route route = router.routeWithRegex(".*foo");
route.pathRegex("\\/([^\\/]+)\\/([^\\/]+)").handler(ctx -> {
String productType = ctx.pathParam("param0");
String productID = ctx.pathParam("param1");
});
}
public void example6_2(Router router) {
router
.routeWithRegex("\\/(?<productType>[^\\/]+)\\/(?<productID>[^\\/]+)")
.handler(ctx -> {
String productType = ctx.pathParam("productType");
String productID = ctx.pathParam("productID");
});
}
public void example7(Router router) {
Route route = router.route().method(HttpMethod.POST);
route.handler(ctx -> {
});
}
public void example8(Router router) {
Route route = router.route(HttpMethod.POST, "/some/path/");
route.handler(ctx -> {
});
}
public void example8_1(Router router) {
router.get().handler(ctx -> {
});
router.get("/some/path/").handler(ctx -> {
});
router.getWithRegex(".*foo").handler(ctx -> {
});
}
public void example9(Router router) {
Route route = router.route().method(HttpMethod.POST).method(HttpMethod.PUT);
route.handler(ctx -> {
});
}
public void example9_1(Router router) {
Route route = router.route()
.method(HttpMethod.valueOf("MKCOL"))
.handler(ctx -> {
});
}
public void example10(Router router) {
router
.route("/some/path/")
.handler(ctx -> {
HttpServerResponse response = ctx.response();
response.setChunked(true);
response.write("route1\n");
ctx.next();
});
router
.route("/some/path/")
.handler(ctx -> {
HttpServerResponse response = ctx.response();
response.write("route2\n");
ctx.next();
});
router
.route("/some/path/")
.handler(ctx -> {
HttpServerResponse response = ctx.response();
response.write("route3");
ctx.response().end();
});
}
public void example11(Router router) {
router
.route("/some/path/")
.order(1)
.handler(ctx -> {
HttpServerResponse response = ctx.response();
response.write("route1\n");
ctx.next();
});
router
.route("/some/path/")
.order(0)
.handler(ctx -> {
HttpServerResponse response = ctx.response();
response.setChunked(true);
response.write("route2\n");
ctx.next();
});
router
.route("/some/path/")
.order(2)
.handler(ctx -> {
HttpServerResponse response = ctx.response();
response.write("route3");
ctx.response().end();
});
}
public void example12(Router router) {
router.route()
.consumes("text/html")
.handler(ctx -> {
});
}
public void example13(Router router) {
router.route()
.consumes("text/html")
.consumes("text/plain")
.handler(ctx -> {
});
}
public void example14(Router router) {
router.route()
.consumes("text/*")
.handler(ctx -> {
});
}
public void example15(Router router) {
router.route()
.consumes("*/json")
.handler(ctx -> {
});
}
public void example16(Router router, String someJSON) {
router.route()
.produces("application/json")
.handler(ctx -> {
HttpServerResponse response = ctx.response();
response.putHeader("content-type", "application/json");
response.end(someJSON);
});
}
public void example17(Router router, String whatever) {
router.route()
.produces("application/json")
.produces("text/html")
.handler(ctx -> {
HttpServerResponse response = ctx.response();
String acceptableContentType = ctx.getAcceptableContentType();
response.putHeader("content-type", acceptableContentType);
response.end(whatever);
});
}
public void example18(Router router) {
router.route(HttpMethod.PUT, "myapi/orders")
.consumes("application/json")
.produces("application/json")
.handler(ctx -> {
});
}
public void example20(Router router) {
Route route = router.route("/some/path/");
route.handler(ctx -> {
HttpServerResponse response = ctx.response();
response.setChunked(true);
response.write("route1\n");
ctx.vertx().setTimer(5000, tid -> ctx.next());
});
route.handler(ctx -> {
HttpServerResponse response = ctx.response();
response.write("route2\n");
ctx.vertx().setTimer(5000, tid -> ctx.next());
});
route.handler(ctx -> {
HttpServerResponse response = ctx.response();
response.write("route3");
ctx.response().end();
});
}
public void example20_1(Router router, SomeLegacyService service) {
router.route().blockingHandler(ctx -> {
service.doSomethingThatBlocks();
ctx.next();
});
}
public void example20_2(Router router) {
router.post("/some/endpoint").handler(ctx -> {
ctx.request().setExpectMultipart(true);
ctx.next();
}).blockingHandler(ctx -> {
});
}
interface SomeLegacyService {
void doSomethingThatBlocks();
}
public void example21(Router router) {
router.get("/some/path").handler(ctx -> {
ctx.put("foo", "bar");
ctx.next();
});
router.get("/some/path/other").handler(ctx -> {
String bar = ctx.get("foo");
ctx.response().end();
});
}
public void example22(Vertx vertx, String productJSON) {
Router restAPI = Router.router(vertx);
restAPI.get("/products/:productID").handler(ctx -> {
ctx.response().write(productJSON);
});
restAPI.put("/products/:productID").handler(ctx -> {
ctx.response().end();
});
restAPI.delete("/products/:productID").handler(ctx -> {
ctx.response().end();
});
}
public void example23(Vertx vertx, Handler<RoutingContext> myStaticHandler, Handler<RoutingContext> myTemplateHandler) {
Router mainRouter = Router.router(vertx);
mainRouter.route("/static/*").handler(myStaticHandler);
mainRouter.route(".*\\.templ").handler(myTemplateHandler);
}
public void example24(Router mainRouter, Router restAPI) {
mainRouter.mountSubRouter("/productsAPI", restAPI);
}
public void example25(Router router) {
Route route = router.get("/somepath/*");
route.failureHandler(ctx -> {
});
}
public void example26(Router router) {
Route route1 = router.get("/somepath/path1/");
route1.handler(ctx -> {
throw new RuntimeException("something happened!");
});
Route route2 = router.get("/somepath/path2");
route2.handler(ctx -> {
ctx.fail(403);
});
Route route3 = router.get("/somepath/*");
route3.failureHandler(failureRoutingContext -> {
int statusCode = failureRoutingContext.statusCode();
HttpServerResponse response = failureRoutingContext.response();
response.setStatusCode(statusCode).end("Sorry! Not today");
});
}
public void example27(Router router) {
router.route().handler(BodyHandler.create());
}
public void example27_1(Router router) {
router.route().handler(ctx -> {
HttpServerRequest request = ctx.request();
request.pause();
someAsyncCall(result -> {
request.resume();
ctx.next();
});
});
router.route().handler(BodyHandler.create());
}
private void someAsyncCall(Handler<Void> handler) {
}
public void example28(Router router) {
router.route().handler(BodyHandler.create());
router.post("/some/path/uploads").handler(ctx -> {
Set<FileUpload> uploads = ctx.fileUploads();
});
}
public void example30(RoutingContext ctx) {
Cookie someCookie = ctx.getCookie("mycookie");
String cookieValue = someCookie.getValue();
ctx.addCookie(Cookie.cookie("othercookie", "somevalue"));
}
public void example31(Vertx vertx) {
SessionStore store1 = LocalSessionStore.create(vertx);
SessionStore store2 = LocalSessionStore.create(
vertx,
"myapp3.sessionmap");
SessionStore store3 = LocalSessionStore.create(
vertx,
"myapp3.sessionmap",
10000);
}
public void example32() {
Vertx.clusteredVertx(new VertxOptions(), res -> {
Vertx vertx = res.result();
SessionStore store1 = ClusteredSessionStore.create(vertx);
SessionStore store2 = ClusteredSessionStore.create(
vertx,
"myclusteredapp3.sessionmap");
});
}
public void example33(Vertx vertx) {
Router router = Router.router(vertx);
SessionStore store = ClusteredSessionStore.create(vertx);
SessionHandler sessionHandler = SessionHandler.create(store);
sessionHandler.setCookieSameSite(CookieSameSite.STRICT);
router.route().handler(sessionHandler);
router.route("/somepath/blah/").handler(ctx -> {
Session session = ctx.session();
session.put("foo", "bar");
});
}
public void example34(SessionHandler sessionHandler, Router router) {
router.route().handler(sessionHandler);
router.route("/somepath/blah").handler(ctx -> {
Session session = ctx.session();
session.put("foo", "bar");
int age = session.get("age");
JsonObject obj = session.remove("myobj");
});
}
public void example37(Vertx vertx, AuthenticationProvider authProvider, Router router) {
router.route().handler(SessionHandler.create(LocalSessionStore.create(vertx)));
AuthenticationHandler basicAuthHandler = BasicAuthHandler.create(authProvider);
}
public void example38(Vertx vertx, AuthenticationProvider authProvider, Router router) {
router.route().handler(SessionHandler.create(LocalSessionStore.create(vertx)));
AuthenticationHandler basicAuthHandler = BasicAuthHandler.create(authProvider);
router.route("/private/*").handler(basicAuthHandler);
router.route("/someotherpath").handler(ctx -> {
});
router.route("/private/somepath").handler(ctx -> {
boolean isAuthenticated = ctx.user() != null;
});
}
public void example39(Vertx vertx, AuthenticationProvider authProvider, Router router) {
router.route().handler(SessionHandler.create(LocalSessionStore.create(vertx)));
router
.route("/private/*")
.handler(RedirectAuthHandler.create(authProvider));
router.post("/login").handler(FormLoginHandler.create(authProvider));
router.route().handler(StaticHandler.create());
router
.route("/someotherpath")
.handler(ctx -> {
});
router
.route("/private/somepath")
.handler(ctx -> {
boolean isAuthenticated = ctx.user() != null;
});
}
public void example40_a(AuthorizationProvider authProvider, Router router) {
router.route().handler(
AuthorizationHandler.create(
PermissionBasedAuthorization.create("can-do-work"))
.addAuthorizationProvider(authProvider));
}
public void example40(AuthorizationProvider authProvider, Router router) {
router.route("/listproducts/*").handler(
AuthorizationHandler.create(
PermissionBasedAuthorization.create("list_products"))
.addAuthorizationProvider(authProvider));
router.route("/private/settings/*").handler(
AuthorizationHandler.create(
RoleBasedAuthorization.create("admin"))
.addAuthorizationProvider(authProvider));
}
public void example41(Router router) {
router.route("/static/*").handler(StaticHandler.create());
}
public void example41_0_1(Router router) {
router.route()
.handler(
CorsHandler.create("vertx\\.io")
.allowedMethod(HttpMethod.GET));
router.route().handler(ctx -> {
});
}
public void example41_2(Router router, TemplateEngine engine) {
TemplateHandler handler = TemplateHandler.create(engine);
router.get("/dynamic").handler(ctx -> {
ctx.put("request_path", ctx.request().path());
ctx.put("session_data", ctx.session().data());
ctx.next();
});
router.get("/dynamic/").handler(handler);
}
public void example41_3(Vertx vertx, Router router) {
router.route("/somepath/").failureHandler(ErrorHandler.create(vertx));
}
public void example42(Router router) {
router.route("/foo/").handler(TimeoutHandler.create(5000));
}
public void example43(Vertx vertx) {
Router router = Router.router(vertx);
SockJSHandlerOptions options = new SockJSHandlerOptions()
.setHeartbeatInterval(2000);
SockJSHandler sockJSHandler = SockJSHandler.create(vertx, options);
}
public void example44(Vertx vertx) {
Router router = Router.router(vertx);
SockJSHandlerOptions options = new SockJSHandlerOptions()
.setHeartbeatInterval(2000);
SockJSHandler sockJSHandler = SockJSHandler.create(vertx, options);
router.mountSubRouter("/myapp", sockJSHandler.socketHandler(sockJSSocket -> {
sockJSSocket.handler(sockJSSocket::write);
}));
}
public void sockJsWriteHandler(Vertx vertx) {
Router router = Router.router(vertx);
SockJSHandlerOptions options = new SockJSHandlerOptions().setRegisterWriteHandler(true);
SockJSHandler sockJSHandler = SockJSHandler.create(vertx, options);
router.mountSubRouter("/myapp", sockJSHandler.socketHandler(sockJSSocket -> {
String writeHandlerID = sockJSSocket.writeHandlerID();
}));
}
public void sockJsSendBufferEventBus(EventBus eventBus, String writeHandlerID) {
eventBus.send(writeHandlerID, Buffer.buffer("foo"));
}
public void example45(Vertx vertx) {
Router router = Router.router(vertx);
SockJSHandler sockJSHandler = SockJSHandler.create(vertx);
SockJSBridgeOptions options = new SockJSBridgeOptions();
router.mountSubRouter("/eventbus", sockJSHandler.bridge(options));
}
public void example46(Vertx vertx) {
Router router = Router.router(vertx);
SockJSHandler sockJSHandler = SockJSHandler.create(vertx);
PermittedOptions inboundPermitted1 = new PermittedOptions()
.setAddress("demo.orderMgr");
PermittedOptions inboundPermitted2 = new PermittedOptions()
.setAddress("demo.persistor")
.setMatch(new JsonObject().put("action", "find")
.put("collection", "albums"));
PermittedOptions inboundPermitted3 = new PermittedOptions()
.setMatch(new JsonObject().put("wibble", "foo"));
PermittedOptions outboundPermitted1 = new PermittedOptions()
.setAddress("ticker.mystock");
PermittedOptions outboundPermitted2 = new PermittedOptions()
.setAddressRegex("news\\..+");
SockJSBridgeOptions options = new SockJSBridgeOptions().
addInboundPermitted(inboundPermitted1).
addInboundPermitted(inboundPermitted1).
addInboundPermitted(inboundPermitted3).
addOutboundPermitted(outboundPermitted1).
addOutboundPermitted(outboundPermitted2);
router.mountSubRouter("/eventbus", sockJSHandler.bridge(options));
}
public void example47() {
PermittedOptions inboundPermitted = new PermittedOptions()
.setAddress("demo.orderService");
inboundPermitted.setRequiredAuthority("place_orders");
SockJSBridgeOptions options = new SockJSBridgeOptions()
.addInboundPermitted(inboundPermitted);
}
public void example48(Vertx vertx, AuthenticationProvider authProvider) {
Router router = Router.router(vertx);
PermittedOptions inboundPermitted = new PermittedOptions()
.setAddress("demo.orderService");
inboundPermitted.setRequiredAuthority("place_orders");
SockJSHandler sockJSHandler = SockJSHandler.create(vertx);
router.route().handler(SessionHandler.create(LocalSessionStore.create(vertx)));
AuthenticationHandler basicAuthHandler = BasicAuthHandler.create(authProvider);
router.route("/eventbus/*").handler(basicAuthHandler);
router.mountSubRouter(
"/eventbus",
sockJSHandler.bridge(new SockJSBridgeOptions()
.addInboundPermitted(inboundPermitted)));
}
public void example48_1(Vertx vertx) {
Router router = Router.router(vertx);
PermittedOptions inboundPermitted = new PermittedOptions()
.setAddress("demo.orderService");
SockJSHandler sockJSHandler = SockJSHandler.create(vertx);
SockJSBridgeOptions options = new SockJSBridgeOptions()
.addInboundPermitted(inboundPermitted);
router.mountSubRouter(
"/eventbus",
sockJSHandler.bridge(options, be -> {
if (
be.type() == BridgeEventType.PUBLISH ||
be.type() == BridgeEventType.SEND) {
JsonObject headers = new JsonObject()
.put("header1", "val")
.put("header2", "val2");
JsonObject rawMessage = be.getRawMessage();
rawMessage.put("headers", headers);
be.setRawMessage(rawMessage);
}
be.complete(true);
}));
}
public void example49(Vertx vertx) {
Router router = Router.router(vertx);
PermittedOptions inboundPermitted = new PermittedOptions()
.setAddress("demo.someService");
SockJSHandler sockJSHandler = SockJSHandler.create(vertx);
SockJSBridgeOptions options = new SockJSBridgeOptions()
.addInboundPermitted(inboundPermitted);
router
.mountSubRouter("/eventbus", sockJSHandler
.bridge(options, be -> {
if (be.type() == BridgeEventType.PUBLISH ||
be.type() == BridgeEventType.RECEIVE) {
if (be.getRawMessage().getString("body").equals("armadillos")) {
be.complete(false);
return;
}
}
be.complete(true);
}));
}
public void handleSocketIdle(Vertx vertx, PermittedOptions inboundPermitted) {
Router router = Router.router(vertx);
SockJSHandler sockJSHandler = SockJSHandler.create(vertx);
SockJSBridgeOptions options = new SockJSBridgeOptions()
.addInboundPermitted(inboundPermitted)
.setPingTimeout(5000);
router
.mountSubRouter("/eventbus", sockJSHandler.bridge(options, be -> {
if (be.type() == BridgeEventType.SOCKET_IDLE) {
}
be.complete(true);
}));
}
public void example50(Vertx vertx) {
Router router = Router.router(vertx);
JWTAuthOptions authConfig = new JWTAuthOptions()
.setKeyStore(new KeyStoreOptions()
.setType("jceks")
.setPath("keystore.jceks")
.setPassword("secret"));
JWTAuth jwt = JWTAuth.create(vertx, authConfig);
router.route("/login").handler(ctx -> {
if (
"paulo".equals(ctx.request().getParam("username")) &&
"secret".equals(ctx.request().getParam("password"))) {
ctx.response()
.end(jwt.generateToken(new JsonObject().put("sub", "paulo")));
} else {
ctx.fail(401);
}
});
}
public void example51(Vertx vertx) {
Router router = Router.router(vertx);
JWTAuthOptions authConfig = new JWTAuthOptions()
.setKeyStore(new KeyStoreOptions()
.setType("jceks")
.setPath("keystore.jceks")
.setPassword("secret"));
JWTAuth authProvider = JWTAuth.create(vertx, authConfig);
router.route("/protected/*").handler(JWTAuthHandler.create(authProvider));
router.route("/protected/somepage").handler(ctx -> {
});
}
public void example52(Vertx vertx) {
JWTAuthOptions authConfig = new JWTAuthOptions()
.setKeyStore(new KeyStoreOptions()
.setType("jceks")
.setPath("keystore.jceks")
.setPassword("secret"));
JWTAuth authProvider = JWTAuth.create(vertx, authConfig);
authProvider
.generateToken(
new JsonObject()
.put("sub", "paulo")
.put("someKey", "some value"),
new JWTOptions());
}
public void example53(Vertx vertx) {
Handler<RoutingContext> handler = ctx -> {
String theSubject = ctx.user().principal().getString("sub");
String someKey = ctx.user().principal().getString("someKey");
};
}
public void example54(Vertx vertx, Router router) {
router.route().handler(CSRFHandler.create(vertx, "abracadabra"));
router.route().handler(ctx -> {
});
}
public void example55(Router router) {
router.get("/some/path").handler(ctx -> {
ctx.put("foo", "bar");
ctx.next();
});
router
.get("/some/path/B")
.handler(ctx -> ctx.response().end());
router
.get("/some/path")
.handler(ctx -> ctx.reroute("/some/path/B"));
}
public void example55b(Router router) {
router.get("/my-pretty-notfound-handler").handler(ctx -> ctx.response()
.setStatusCode(404)
.end("NOT FOUND fancy html here!!!"));
router.get().failureHandler(ctx -> {
if (ctx.statusCode() == 404) {
ctx.reroute("/my-pretty-notfound-handler");
} else {
ctx.next();
}
});
}
public void example55c(Router router) {
router.get("/final-target").handler(ctx -> {
});
router.get().handler(ctx -> ctx.reroute("/final-target?variable=value"));
router.get().handler(ctx -> ctx
.put("variable", "value")
.reroute("/final-target"));
}
public void example56(Router router) {
router.route().virtualHost("*.vertx.io").handler(ctx -> {
});
}
public void example57(Router router) {
Route route = router.get("/localized").handler(ctx -> {
for (LanguageHeader language : ctx.acceptableLanguages()) {
switch (language.tag()) {
case "en":
ctx.response().end("Hello!");
return;
case "fr":
ctx.response().end("Bonjour!");
return;
case "pt":
ctx.response().end("Olá!");
return;
case "es":
ctx.response().end("Hola!");
return;
}
}
ctx.response().end("Sorry we don't speak: " + ctx.preferredLanguage());
});
}
public void example58(Vertx vertx, Router router) {
OAuth2Auth authProvider = GithubAuth
.create(vertx, "CLIENT_ID", "CLIENT_SECRET");
OAuth2AuthHandler oauth2 = OAuth2AuthHandler
.create(vertx, authProvider, "https://myserver.com/callback");
oauth2.setupCallback(router.route());
router.route("/protected/*").handler(oauth2);
router
.route("/protected/somepage")
.handler(ctx -> ctx.response().end("Welcome to the protected resource!"));
router
.get("/")
.handler(ctx -> ctx.response()
.putHeader("content-type", "text/html")
.end("Hello<br><a href=\"/protected/somepage\">Protected by Github</a>"));
}
public void example59(Vertx vertx, Router router) {
OAuth2Auth authProvider = OAuth2Auth.create(vertx, new OAuth2Options()
.setClientID("CLIENT_ID")
.setClientSecret("CLIENT_SECRET")
.setFlow(OAuth2FlowType.AUTH_CODE)
.setSite("https://accounts.google.com")
.setTokenPath("https://www.googleapis.com/oauth2/v3/token")
.setAuthorizationPath("/o/oauth2/auth"));
OAuth2AuthHandler oauth2 = OAuth2AuthHandler
.create(vertx, authProvider, "http://localhost:8080");
oauth2.withScope("profile");
oauth2.setupCallback(router.get("/callback"));
router.route("/protected/*").handler(oauth2);
router
.route("/protected/somepage")
.handler(ctx -> ctx.response().end("Welcome to the protected resource!"));
router
.get("/")
.handler(ctx -> ctx.response()
.putHeader("content-type", "text/html")
.end("Hello<br><a href=\"/protected/somepage\">Protected by Google</a>"));
}
public void example61(Vertx vertx, Router router, OAuth2Auth provider) {
OAuth2AuthHandler oauth2 = OAuth2AuthHandler
.create(vertx, provider, "https://myserver.com:8447/callback");
oauth2.setupCallback(router.route());
}
public void example62(Vertx vertx, Router router) {
OAuth2Auth authProvider =
GithubAuth
.create(vertx, "CLIENTID", "CLIENT SECRET");
router.route()
.handler(SessionHandler.create(LocalSessionStore.create(vertx)));
router.route("/protected").handler(
OAuth2AuthHandler.create(vertx, authProvider)
.setupCallback(router.route("/callback"))
.withScope("user:email")
);
router.get("/").handler(ctx -> ctx.response()
.putHeader("Content-Type", "text/html")
.end(
"<html>\n" +
" <body>\n" +
" <p>\n" +
" Well, hello there!\n" +
" </p>\n" +
" <p>\n" +
" We're going to the protected resource, if there is no\n" +
" user in the session we will talk to the GitHub API. Ready?\n" +
" <a href=\"/protected\">Click here</a> to begin!</a>\n" +
" </p>\n" +
" <p>\n" +
" <b>If that link doesn't work</b>, remember to provide your\n" +
" own <a href=\"https://github.com/settings/applications/new\">\n" +
" Client ID</a>!\n" +
" </p>\n" +
" </body>\n" +
"</html>"));
router.get("/protected").handler(ctx -> {
User user = ctx.user();
ctx.response().end(user.toString());
});
}
public void manualContentType(Router router) {
router
.get("/api/books")
.produces("application/json")
.handler(ctx -> findBooks()
.onSuccess(books -> ctx.response()
.putHeader("Content-Type", "application/json")
.end(toJson(books))).onFailure(ctx::fail));
}
public void contentTypeHandler(Router router) {
router.route("/api/*").handler(ResponseContentTypeHandler.create());
router
.get("/api/books")
.produces("application/json")
.handler(ctx -> findBooks()
.onSuccess(books -> ctx.response()
.end(toJson(books))).onFailure(ctx::fail));
}
private Future<List<Book>> findBooks() {
throw new UnsupportedOperationException();
}
static class Book {
}
Buffer toJson(List<Book> books) {
throw new UnsupportedOperationException();
}
Buffer toXML(List<Book> books) {
throw new UnsupportedOperationException();
}
public void mostAcceptableContentTypeHandler(Router router) {
router.route("/api/*").handler(ResponseContentTypeHandler.create());
router
.get("/api/books")
.produces("text/xml")
.produces("application/json")
.handler(ctx -> findBooks()
.onSuccess(books -> {
if (ctx.getAcceptableContentType().equals("text/xml")) {
ctx.response().end(toXML(books));
} else {
ctx.response().end(toJson(books));
}
})
.onFailure(ctx::fail));
}
public void example63(Router router, AuthenticationProvider provider) {
ChainAuthHandler chain = ChainAuthHandler.any();
chain.add(BasicAuthHandler.create(provider));
chain.add(RedirectAuthHandler.create(provider));
router.route("/secure/resource").handler(chain);
router.route("/secure/resource").handler(ctx -> {
});
}
public void example64(Router router) {
router.route().handler(MethodOverrideHandler.create());
router.route(HttpMethod.GET, "/").handler(ctx -> {
});
router.route(HttpMethod.POST, "/").handler(ctx -> {
});
}
public void example65(Router router) {
router.route().handler(MethodOverrideHandler.create(false));
router.route(HttpMethod.GET, "/").handler(ctx -> {
});
router.route(HttpMethod.POST, "/").handler(ctx -> {
});
}
public void example66(RoutingContext ctx, Buffer pdfBuffer) {
ctx
.attachment("weekly-report.pdf")
.end(pdfBuffer);
}
public void example67(RoutingContext ctx) {
ctx.redirect("https://securesite.com/");
ctx.redirect("back");
}
public void example68(RoutingContext ctx, Object someObject) {
ctx.json(new JsonObject().put("hello", "vert.x"));
ctx.json(new JsonArray().add("vertx").add("web"));
ctx.json(someObject);
}
public void example69(RoutingContext ctx) {
ctx.is("html");
ctx.is("text/html");
ctx.is("application/json");
ctx.is("html");
}
public void example70(RoutingContext ctx) {
ctx.lastModified("Wed, 13 Jul 2011 18:30:00 GMT");
if (ctx.isFresh()) {
}
}
public void example71(RoutingContext ctx, Buffer buffer) {
ctx.etag("W/123456789");
ctx.lastModified("Wed, 13 Jul 2011 18:30:00 GMT");
ctx.end();
ctx.end("body");
ctx.end(buffer);
}
public void example72(Router router) {
router.route().handler(MultiTenantHandler.create("X-Tenant"));
}
public void example73() {
MultiTenantHandler.create("X-Tenant")
.addTenantHandler("tenant-A", ctx -> {
})
.addTenantHandler("tenant-B", ctx -> {
})
.addDefaultHandler(ctx -> {
});
}
public void example74(Vertx vertx, Router router) {
OAuth2Auth gitHubAuthProvider = GithubAuth
.create(vertx, "CLIENT_ID", "CLIENT_SECRET");
OAuth2AuthHandler githubOAuth2 = OAuth2AuthHandler.create(
vertx,
gitHubAuthProvider,
"https://myserver.com/github-callback");
githubOAuth2.setupCallback(router.route());
OAuth2Auth googleAuthProvider = OAuth2Auth.create(vertx, new OAuth2Options()
.setClientID("CLIENT_ID")
.setClientSecret("CLIENT_SECRET")
.setFlow(OAuth2FlowType.AUTH_CODE)
.setSite("https://accounts.google.com")
.setTokenPath("https://www.googleapis.com/oauth2/v3/token")
.setAuthorizationPath("/o/oauth2/auth"));
OAuth2AuthHandler googleOAuth2 = OAuth2AuthHandler.create(
vertx,
googleAuthProvider,
"https://myserver.com/google-callback");
googleOAuth2.setupCallback(router.route());
router.route().handler(
MultiTenantHandler.create("X-Tenant")
.addTenantHandler("github", githubOAuth2)
.addTenantHandler("google", googleOAuth2)
.addDefaultHandler(ctx -> ctx.fail(401)));
}
public void example81(Router router) {
router.route().handler(ctx -> {
String tenant = ctx.get(MultiTenantHandler.TENANT);
switch(tenant) {
case "google":
break;
case "github":
break;
}
});
}
public void example75(Vertx vertx, Router router, Function<Authenticator, Future<List<Authenticator>>> fetcher, Function<Authenticator, Future<Void>> updater) {
WebAuthn webAuthn = WebAuthn.create(
vertx,
new WebAuthnOptions()
.setRelyingParty(new RelyingParty().setName("Vert.x WebAuthN Demo"))
.setAuthenticatorAttachment(AuthenticatorAttachment.CROSS_PLATFORM)
.setAuthenticatorAttachment(AuthenticatorAttachment.PLATFORM)
.setUserVerification(UserVerification.REQUIRED))
.authenticatorFetcher(fetcher)
.authenticatorUpdater(updater);
router.post()
.handler(BodyHandler.create());
router.route()
.handler(SessionHandler
.create(LocalSessionStore.create(vertx)));
WebAuthnHandler webAuthNHandler = WebAuthnHandler.create(webAuthn)
.setOrigin("https://192.168.178.74.xip.io:8443")
.setupCallback(router.post("/webauthn/response"))
.setupCredentialsCreateCallback(router.post("/webauthn/register"))
.setupCredentialsGetCallback(router.post("/webauthn/login"));
router.route().handler(webAuthNHandler);
}
public void example76(Vertx vertx, Router router) {
router.allowForward(AllowForwardHeaders.FORWARD);
router.allowForward(AllowForwardHeaders.X_FORWARD);
router.allowForward(AllowForwardHeaders.ALL);
}
public void example77(Vertx vertx, Router router) {
router.allowForward(AllowForwardHeaders.NONE);
}
public void example78(Router router, AuthenticationHandler authNHandlerA, AuthenticationHandler authNHandlerB, AuthenticationHandler authNHandlerC) {
ChainAuthHandler chain =
ChainAuthHandler.any()
.add(authNHandlerA)
.add(ChainAuthHandler.all()
.add(authNHandlerB)
.add(authNHandlerC));
router.route("/secure/resource").handler(chain);
router.route("/secure/resource").handler(ctx -> {
});
}
public void example78(Router router, SessionHandler sessionHandler) {
router.route().handler(ctx -> sessionHandler.flush(ctx)
.onSuccess(v -> ctx.end("Success!"))
.onFailure(err -> {
}));
}
public void example79(Router router, SessionStore store) {
router.route()
.handler(SessionHandler.create(store).setCookieless(true));
}
public void example80(Router router) {
router.route().handler(HSTSHandler.create());
}
@DataObject
static class Pojo {}
public void example82(Router router) {
router
.get("/some/path")
.respond(
ctx -> Future.succeededFuture(new JsonObject().put("hello", "world")));
router
.get("/some/path")
.respond(
ctx -> Future.succeededFuture(new Pojo()));
}
public void example83(Router router) {
router
.get("/some/path")
.respond(
ctx -> ctx
.response()
.putHeader("Content-Type", "text/plain")
.end("hello world!"));
router
.get("/some/path")
.respond(
ctx -> ctx
.response()
.setChunked(true)
.write("Write some text..."));
}
public void example84(Router router) {
router.route().handler(
CSPHandler.create()
.addDirective("default-src", "*.trusted.com"));
}
}