Tags/Libraries:

There comes a time when you want some form of functionality to run for every single request to your webserver. You might also want some more fine grained control and possibly run some slightly different logic for each individual route. This can be called middleware, filtering, interceptors, decorators, whatever you want to call it. Undertows composition gives you total control over how you handle this. You can build simple or complex route trees, deep trees or shallow trees. Some examples would be Access Logging, Exception Handling, gzipping, blocking, authorization, authentication, metrics / timing, rate limiting, caching and many more. Undertow supplies many of these out of the box.

Routes

/* * Notice how we have route level middleware here with the timed HttpHandler. */ private static final HttpHandler ROUTES = new RoutingHandler() .get("/textFast", timed("textFast", MiddlewareServer::textFast)) .get("/textSlow", timed("textSlow", MiddlewareServer::textSlow)) .get("/throwException", timed("throwException", MiddlewareServer::throwException)) .get("/metrics", timed("metrics", MiddlewareServer::metrics)) .setFallbackHandler(timed("notFound", MiddlewareServer::notFound)) ;

Handlers

private static void textFast(HttpServerExchange exchange) { Exchange.body().sendText(exchange, "Fast!"); } private static void textSlow(HttpServerExchange exchange) { // Sure whatever just sleep. try { Thread.sleep(300L); } catch (InterruptedException e) { e.printStackTrace(); } Exchange.body().sendText(exchange, "Slow!!!"); } private static void throwException(HttpServerExchange exchange) { throw new RuntimeException("Error, I hope you handled it!"); } private static void notFound(HttpServerExchange exchange) { exchange.setStatusCode(404); Exchange.body().sendText(exchange, "Not Found"); } private static void metrics(HttpServerExchange exchange) { Exchange.body().sendJson(exchange, Metrics.registry()); }

Middleware

This is where the magic happens! We added a few new classes feel free to follow the code in github its all there.

private static HttpHandler exceptionHandler(HttpHandler next) { return Handlers.exceptionHandler(next) .addExceptionHandler(Throwable.class, ExceptionHandlers::handleAllExceptions); } private static HttpHandler wrapWithMiddleware(HttpHandler handler) { /* * Undertow has I/O threads for handling inbound connections and non blocking IO. * If you are doing any blocking you should use the BlockingHandler. This * will push work into a separate Executor with customized thread pool * which is made for blocking work. I am blocking immediately here because I am lazy. * Don't block if you don't need to. Remember you can configure only certain routes block. * When looking at logs you can tell if you are blocking or not by the thread name. * I/O non blocking thread - [XNIO-1 I/O-{threadnum}] - You should NOT be blocking here. * Blocking task threads - [XNIO-1 task-{threadnum}] This pool is made for blocking. */ return MiddlewareBuilder.begin(BlockingHandler::new) .next(CustomHandlers::gzip) .next(CustomHandlers::accessLog) .next(CustomHandlers::statusCodeMetrics) .next(MiddlewareServer::exceptionHandler) .complete(handler); }

Server

public static void main(String[] args) { // Wrapping routes with middleware here! SimpleServer server = SimpleServer.simpleServer(wrapWithMiddleware(ROUTES)); server.start(); }

Logs

23:41:12.022 [XNIO-1 task-30] INFO com.stubbornjava.accesslog - 127.0.0.1 - - [12/Jan/2017:23:41:12 -0500] "GET /throwException HTTP/1.1" 500 42 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36" 23:41:12.221 [XNIO-1 task-31] INFO com.stubbornjava.accesslog - 127.0.0.1 - - [12/Jan/2017:23:41:12 -0500] "GET /throwException HTTP/1.1" 500 42 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36" 23:41:15.086 [XNIO-1 task-21] INFO com.stubbornjava.accesslog - 127.0.0.1 - - [12/Jan/2017:23:41:15 -0500] "GET /favicon.ico HTTP/1.1" 404 9 "http://localhost:8080/throwException" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36" 23:41:52.880 [XNIO-1 task-31] INFO com.stubbornjava.accesslog - 127.0.0.1 - - [12/Jan/2017:23:41:52 -0500] "GET /metrics HTTP/1.1" 200 1004 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36"

gzip

curl -v --compressed localhost:8080/metrics * Trying ::1... * connect to ::1 port 8080 failed: Connection refused * Trying 127.0.0.1... * Connected to localhost (127.0.0.1) port 8080 (#0) > GET /metrics HTTP/1.1 > Host: localhost:8080 > User-Agent: curl/7.49.1 > Accept: */* > Accept-Encoding: deflate, gzip > < HTTP/1.1 200 OK < Content-Encoding: gzip < Connection: keep-alive < Content-Type: application/json < Content-Length: 1012 < Date: Fri, 13 Jan 2017 04:56:20 GMT

Metrics

Hit GET /metrics and woah! Push this data to statsd or cloudwatch and make some useful graphs or alarms. DropwizardMetrics probably even has a reporter already built for you. We can monitor fluctuations in status code rates or stats for individual routes.