Skip to content

Instantly share code, notes, and snippets.

@thecodingrobot
Last active March 2, 2017 14:35
Show Gist options
  • Select an option

  • Save thecodingrobot/bac054d17e6d124ae8de636a861fcfb2 to your computer and use it in GitHub Desktop.

Select an option

Save thecodingrobot/bac054d17e6d124ae8de636a861fcfb2 to your computer and use it in GitHub Desktop.
import io.undertow.Handlers;
import io.undertow.Undertow;
import io.undertow.server.handlers.*;
import io.undertow.util.Headers;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class UndertowServer {
public static void main(String[] args) {
Logger logger = LogManager.getLogger(UndertowServer.class);
PathHandler pathHandler = Handlers.path()
.addExactPath("/", exchange -> {
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
exchange.getResponseSender().send("Hello World");
})
.addExactPath("/err", exchange -> {
throw new IllegalArgumentException("Error");
});
ExceptionHandler exceptionHandler = Handlers.exceptionHandler(pathHandler)
.addExceptionHandler(Exception.class, exchange -> {
Throwable attachment = exchange.getAttachment(ExceptionHandler.THROWABLE);
exchange.getResponseSender().send("Exception handled: " + attachment.getMessage());
});
GracefulShutdownHandler rootHandler = Handlers.gracefulShutdown(new StuckThreadDetectionHandler.Wrapper().wrap(exceptionHandler));
Undertow undertow = Undertow.builder()
.addHttpListener(8080, "localhost")
.setHandler(rootHandler)
.build();
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
logger.info("Shutdown");
rootHandler.shutdown();
rootHandler.addShutdownListener(isSuccessful -> undertow.stop());
try {
rootHandler.awaitShutdown();
} catch (InterruptedException e) {
e.printStackTrace();
}
logger.info("Done");
}));
undertow.start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment