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.

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);
}

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.