Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,13 @@ def jacksonV = '2.8.5'
def okhttpV = '3.4.1'
def slf4jV = '1.7.21'
def logbackV = '1.1.8'
def undertowV = '1.3.22.Final'
def undertowV = '1.4.7.Final'
def metricsV = '3.1.2'
def guavaV = '19.0'
def typesafeConfigV = '1.3.1'
def handlebarsV = '4.0.5'
def htmlcompressorV = '1.4'

// Test
def junitV = '4.12'

Expand All @@ -39,7 +42,12 @@ ext {
]
guavaLib = [[group: 'com.google.guava', name: 'guava', version: guavaV]]
typesafeConfigLib = [[group: 'com.typesafe', name: 'config', version: typesafeConfigV]]

handlebarsLib = [
[group: 'com.github.jknack', name: 'handlebars', version: handlebarsV]
, [group: 'com.github.jknack', name: 'handlebars-jackson2', version: handlebarsV]
, [group: 'com.googlecode.htmlcompressor', name: 'htmlcompressor', version: htmlcompressorV]
]

junitLib = [[group: 'junit', name: 'junit', version: junitV]]
}

Expand Down
2 changes: 1 addition & 1 deletion settings.gradle
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
rootProject.name = 'stubbornjava-parent'

include 'stubbornjava-undertow', 'stubbornjava-common'
include 'stubbornjava-undertow', 'stubbornjava-common', 'stubbornjava-examples'
2 changes: 2 additions & 0 deletions stubbornjava-common/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,7 @@ dependencies {
// Configuration
compile typesafeConfigLib

compile handlebarsLib

testCompile junitLib
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package com.stubbornjava.common.server;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.undertow.Undertow;
import io.undertow.UndertowOptions;
import io.undertow.server.HttpHandler;

public class SimpleServer {
private static final Logger logger = LoggerFactory.getLogger(SimpleServer.class);
private static final int DEFAULT_PORT = 8080;
private static final String DEFAULT_HOST = "localhost";

private final Undertow undertow;
private SimpleServer(Undertow undertow) {
this.undertow = undertow;
}

/*
* As you can see this class is not meant to abstract away the Undertow server,
* its goal is simply to have some common configurations. We expose Undertow
* if a different service needs to modify it in any way before we call start.
*/
public Undertow getUndertow() {
return undertow;
}

public void start() {
undertow.start();
/*
* Undertow logs this on its own but we generally set 3rd party
* default logger levels to warn so we log it here. If it wasn't using the
* io.undertow context we could turn on just that logger but no big deal.
*/
undertow.getListenerInfo()
.stream()
.forEach(listenerInfo -> logger.debug(listenerInfo.toString()));
}

public static SimpleServer simpleServer(HttpHandler handler) {
Undertow undertow = Undertow.builder()
/*
* This setting is needed if you want to allow '=' as a value in a cookie.
* If you base64 encode any cookie values you probably want it on.
*/
.setServerOption(UndertowOptions.ALLOW_EQUALS_IN_COOKIE_VALUE, true)
.addHttpListener(DEFAULT_PORT, DEFAULT_HOST, handler)
.build()
;
return new SimpleServer(undertow);
}
}
23 changes: 23 additions & 0 deletions stubbornjava-examples/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
dependencies {
compile project(':stubbornjava-undertow')
compile project(':stubbornjava-common')

// The production code uses the SLF4J logging API at compile time
compile loggingLib

// Jackson libs
compile jacksonLib

// Metrics
compile metricsLib

// Guava
compile guavaLib

// Configuration
compile typesafeConfigLib

compile undertowLib

testCompile junitLib
}
1 change: 1 addition & 0 deletions stubbornjava-examples/settings.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
rootProject.name = 'stubbornjava-examples'
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package com.stubbornjava.examples.undertow.contenttypes;

import io.undertow.server.HttpServerExchange;
import io.undertow.util.Headers;

public class ContentTypeHandlers {
private static final String fileName = "helloworld.txt";

// @WhereAreAllMyAnnotations??
// @DecoupledLogicFromRoutingIsNice!
public static void helloWorldText(HttpServerExchange exchange) {
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
exchange.getResponseSender().send("Hello World");
}

public static void helloWorldHtml(HttpServerExchange exchange) {
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/html");
exchange.getResponseSender().send("<h1>Hello World</h1>");
}

public static void helloWorldFileDownload(HttpServerExchange exchange) {
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/octet-stream");
exchange.getResponseHeaders().put(Headers.CONTENT_DISPOSITION, "inline; filename=\"" + fileName + "\"");
exchange.getResponseSender().send("Hello World");
}

public static void helloWorldJson(HttpServerExchange exchange) {
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");
exchange.getResponseSender().send("{\"message\": \"Hello World\"}");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.stubbornjava.examples.undertow.contenttypes;

import com.stubbornjava.common.server.SimpleServer;

import io.undertow.server.HttpHandler;
import io.undertow.server.RoutingHandler;

public class ContentTypesServer {

/*
* Pretty clean am I right? Unless you REALLY REALLY love annotations
* and the magic that comes with them. Don't forget about the copious
* rabbit holes just trying to figure out what code executes because of
* the annotation. This approach all code is just a few clicks away in
* your IDE of choice. Your time is better spent writing code than pretending
* to be a CSI cyber crimes specialist ripping apart some code for a clue to
* whatever it does.
*/
private static final HttpHandler ROUTES = new RoutingHandler()
.get("/helloWorldText", ContentTypeHandlers::helloWorldText)
.get("/helloWorldHtml", ContentTypeHandlers::helloWorldHtml)
.get("/helloWorldFileDownload", ContentTypeHandlers::helloWorldFileDownload)
.get("/helloWorldJson", ContentTypeHandlers::helloWorldJson)
;

public static void main(String[] args) {
SimpleServer server = SimpleServer.simpleServer(ROUTES);
server.start();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package com.stubbornjava.examples.undertow.helloworld;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.undertow.Undertow;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.Headers;

public class HelloWorldServer {
private static final Logger logger = LoggerFactory.getLogger(HelloWorldServer.class);

/*
* Creating HttpHandlers as a method and passing it as a method reference is pretty clean.
* This also helps reduce accidentally adding state to handlers.
*/
public static void helloWorldHandler(HttpServerExchange exchange) {
exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, "text/plain");
exchange.getResponseSender().send("Hello World!");
}

public static void main(String[] args) {
int port = 8080;
/*
* "localhost" will ONLY listen on local host.
* If you want the server reachable from the outside you need to set "0.0.0.0"
*/
String host = "localhost";

/*
* If you really want to abstract out the server construction you can.
* StubbornJava recommends to only use abstractions / wrappers on very simple APIs.
* When you abstract over something like an HTTP server its very difficult to have
* an abstraction that covers the nuances of each webserver. Instead accept it and let
* the framework bleed out a bit. Realistically you shouldn't be changing your web server
* all that often. Even if you did fully abstract it out your custom logic tends to bleed
* out eventually, embrace it and move on. You could also just have a static method or
* factory that created the server with your common configurations and allows further
* customization later.
*/
Undertow server = Undertow.builder()
// Add the helloWorldHandler as a method reference.
.addHttpListener(port, host, HelloWorldServer::helloWorldHandler)
.build();
logger.debug("starting on http://" + host + ":" + port);
server.start();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.stubbornjava.examples.undertow.routing;

import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.Headers;

public class ConstantStringHandler implements HttpHandler {
private final String value;
public ConstantStringHandler(String value) {
this.value = value;
}

@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
exchange.getResponseSender().send(value);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package com.stubbornjava.examples.undertow.routing;

import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.Headers;

public class RoutingHandlers {

/*
* Creating static factory methods to construct handlers let's you keep
* them better organized and reduce some boilerplate. This will be shown
* in future examples.
*/
public static HttpHandler constantStringHandler(String value) {
return new ConstantStringHandler(value);
}

/*
* Alternate way to create constantStringHandler using an anonymous HttpHandler.
* This is fine for simple handlers but more complex ones might be better off
* in their own file.
*/
public static HttpHandler constantStringHandlerAlt(String value) {
return (HttpServerExchange exchange) -> {
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
exchange.getResponseSender().send(value);
};
}

/*
* This is a 3rd approach to creating HttpHandlers and is heavily utilized
* in StubbornJava. We can use Java 8 method references for this approach.
* Notice how the void return type and single HttpServerExchange parameter
* fulfill the HttpHandler interface.
*
* This approach is most commonly used for the actual business logic and generally
* is responsible for sending the response. Any handlers that chain / delegate
* to other handlers are not a great fit for this style.
*/
public static void notFoundHandler(HttpServerExchange exchange) {
exchange.setStatusCode(404);
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
exchange.getResponseSender().send("Page Not Found!!");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package com.stubbornjava.examples.undertow.routing;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.stubbornjava.common.server.SimpleServer;

import io.undertow.Undertow;
import io.undertow.server.HttpHandler;
import io.undertow.server.RoutingHandler;

public class RoutingServer {
private static final Logger logger = LoggerFactory.getLogger(RoutingServer.class);

/*
* Utilize Undertow's RoutingHandler for HTTP Verb / path routing.
* We can utilize the fallback handler for the not found handler.
*
* Using the RoutingHandler we can generally achieve a single line per route.
* It also decouples the HttpHander from the route which encourages reuse.
* A good example would be a single error handler or not found handler that can
* be passed to multiple routes or nodes in the routing tree as it gets more complex.
* For instance you can have an ExceptionHandler that handles 404's by delegating to the
* notFoundHandler and you can also use the same notFoundHandler as the RoutingHandlers
* fallbackHandler.
*
* How you organize your routes is entirely up to you and Undertow is very flexible
* in this regard. StubbornJava tends to use a single file for routing even if it gets
* to 100+ routes. It is very convenient for searching code and trying to track down the
* code that is executed for a given route. Also using the method reference style there
* should be almost no logic in the file so readability isn't a major concern.
*
* If you do prefer splitting your routes out for reuse take a look at RoutingHandlers
* addAll method. This allows you to pass a RoutingHandler into a RoutingHandler to add
* all of its routes. Using this approach when you construct the server you can create a
* new RoutingHandler and pass in each individual RoutingHandler. This can also be great
* for common routes across services like health checks or system diagnostic routes.
*
* You might want to split the Routes into their own file separate from the server
* initialization code.
*/
private static final HttpHandler ROUTES = new RoutingHandler()
.get("/", RoutingHandlers.constantStringHandler("GET - My Homepage"))
.get("/myRoute", RoutingHandlers.constantStringHandler("GET - My Route"))
.post("/myRoute", RoutingHandlers.constantStringHandler("POST - My Route"))
.get("/myOtherRoute", RoutingHandlers.constantStringHandler("GET - My Other Route"))
//.get("/myRoutePrefix*", RoutingHandlers.constantStringHandler("GET - My Prefixed Route"))

// Pass a handler as a method reference.
.setFallbackHandler(RoutingHandlers::notFoundHandler)
;

public static void main(String[] args) {
/*
* You caught us! We changed our mind and decided to add a small abstraction.
* Notice however we have zero intention of hiding Undertow. We have embraced
* Undertow as our web server and will allow it to be leaked out. This is a conscious
* design decision to improve developer productivity.
*/
SimpleServer server = SimpleServer.simpleServer(ROUTES);
// See we have access to it here!
Undertow undertow = server.getUndertow();
server.start();
}
}
3 changes: 2 additions & 1 deletion stubbornjava-undertow/build.gradle
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
// In this section you declare the dependencies for your production and test code
dependencies {
// The production code uses the SLF4J logging API at compile time
compile(undertowLib)
compile undertowLib
compile loggingLib

// Declare the dependency for your favourite test framework you want to use in your tests.
// TestNG is also supported by the Gradle Test task. Just change the
Expand Down
18 changes: 0 additions & 18 deletions stubbornjava-undertow/settings.gradle
Original file line number Diff line number Diff line change
@@ -1,19 +1 @@
/*
* This settings file was auto generated by the Gradle buildInit task
* by 'billoneil' at '12/31/16 1:47 PM' with Gradle 2.14.1
*
* The settings file is used to specify which projects to include in your build.
* In a single project build this file can be empty or even removed.
*
* Detailed information about configuring a multi-project build in Gradle can be found
* in the user guide at https://docs.gradle.org/2.14.1/userguide/multi_project_builds.html
*/

/*
// To declare projects as part of a multi-project build use the 'include' method
include 'shared'
include 'api'
include 'services:webservice'
*/

rootProject.name = 'stubbornjava-undertow'