Skip to content

Commit 63e6c68

Browse files
authored
Undertow examples (StubbornJava#3)
* Add simple undertow examples * remove comments
1 parent e760352 commit 63e6c68

14 files changed

Lines changed: 329 additions & 22 deletions

File tree

‎build.gradle‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,13 @@ def jacksonV = '2.8.5'
1111
def okhttpV = '3.4.1'
1212
def slf4jV = '1.7.21'
1313
def logbackV = '1.1.8'
14-
def undertowV = '1.3.22.Final'
14+
def undertowV = '1.4.7.Final'
1515
def metricsV = '3.1.2'
1616
def guavaV = '19.0'
1717
def typesafeConfigV = '1.3.1'
18+
def handlebarsV = '4.0.5'
19+
def htmlcompressorV = '1.4'
20+
1821
// Test
1922
def junitV = '4.12'
2023

@@ -39,7 +42,12 @@ ext {
3942
]
4043
guavaLib = [[group: 'com.google.guava', name: 'guava', version: guavaV]]
4144
typesafeConfigLib = [[group: 'com.typesafe', name: 'config', version: typesafeConfigV]]
42-
45+
handlebarsLib = [
46+
[group: 'com.github.jknack', name: 'handlebars', version: handlebarsV]
47+
, [group: 'com.github.jknack', name: 'handlebars-jackson2', version: handlebarsV]
48+
, [group: 'com.googlecode.htmlcompressor', name: 'htmlcompressor', version: htmlcompressorV]
49+
]
50+
4351
junitLib = [[group: 'junit', name: 'junit', version: junitV]]
4452
}
4553

‎settings.gradle‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
rootProject.name = 'stubbornjava-parent'
22

3-
include 'stubbornjava-undertow', 'stubbornjava-common'
3+
include 'stubbornjava-undertow', 'stubbornjava-common', 'stubbornjava-examples'

‎stubbornjava-common/build.gradle‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,5 +16,7 @@ dependencies {
1616
// Configuration
1717
compile typesafeConfigLib
1818

19+
compile handlebarsLib
20+
1921
testCompile junitLib
2022
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package com.stubbornjava.common.server;
2+
3+
import org.slf4j.Logger;
4+
import org.slf4j.LoggerFactory;
5+
6+
import io.undertow.Undertow;
7+
import io.undertow.UndertowOptions;
8+
import io.undertow.server.HttpHandler;
9+
10+
public class SimpleServer {
11+
private static final Logger logger = LoggerFactory.getLogger(SimpleServer.class);
12+
private static final int DEFAULT_PORT = 8080;
13+
private static final String DEFAULT_HOST = "localhost";
14+
15+
private final Undertow undertow;
16+
private SimpleServer(Undertow undertow) {
17+
this.undertow = undertow;
18+
}
19+
20+
/*
21+
* As you can see this class is not meant to abstract away the Undertow server,
22+
* its goal is simply to have some common configurations. We expose Undertow
23+
* if a different service needs to modify it in any way before we call start.
24+
*/
25+
public Undertow getUndertow() {
26+
return undertow;
27+
}
28+
29+
public void start() {
30+
undertow.start();
31+
/*
32+
* Undertow logs this on its own but we generally set 3rd party
33+
* default logger levels to warn so we log it here. If it wasn't using the
34+
* io.undertow context we could turn on just that logger but no big deal.
35+
*/
36+
undertow.getListenerInfo()
37+
.stream()
38+
.forEach(listenerInfo -> logger.debug(listenerInfo.toString()));
39+
}
40+
41+
public static SimpleServer simpleServer(HttpHandler handler) {
42+
Undertow undertow = Undertow.builder()
43+
/*
44+
* This setting is needed if you want to allow '=' as a value in a cookie.
45+
* If you base64 encode any cookie values you probably want it on.
46+
*/
47+
.setServerOption(UndertowOptions.ALLOW_EQUALS_IN_COOKIE_VALUE, true)
48+
.addHttpListener(DEFAULT_PORT, DEFAULT_HOST, handler)
49+
.build()
50+
;
51+
return new SimpleServer(undertow);
52+
}
53+
}

‎stubbornjava-examples/build.gradle‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
dependencies {
2+
compile project(':stubbornjava-undertow')
3+
compile project(':stubbornjava-common')
4+
5+
// The production code uses the SLF4J logging API at compile time
6+
compile loggingLib
7+
8+
// Jackson libs
9+
compile jacksonLib
10+
11+
// Metrics
12+
compile metricsLib
13+
14+
// Guava
15+
compile guavaLib
16+
17+
// Configuration
18+
compile typesafeConfigLib
19+
20+
compile undertowLib
21+
22+
testCompile junitLib
23+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
rootProject.name = 'stubbornjava-examples'
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package com.stubbornjava.examples.undertow.contenttypes;
2+
3+
import io.undertow.server.HttpServerExchange;
4+
import io.undertow.util.Headers;
5+
6+
public class ContentTypeHandlers {
7+
private static final String fileName = "helloworld.txt";
8+
9+
// @WhereAreAllMyAnnotations??
10+
// @DecoupledLogicFromRoutingIsNice!
11+
public static void helloWorldText(HttpServerExchange exchange) {
12+
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
13+
exchange.getResponseSender().send("Hello World");
14+
}
15+
16+
public static void helloWorldHtml(HttpServerExchange exchange) {
17+
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/html");
18+
exchange.getResponseSender().send("<h1>Hello World</h1>");
19+
}
20+
21+
public static void helloWorldFileDownload(HttpServerExchange exchange) {
22+
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/octet-stream");
23+
exchange.getResponseHeaders().put(Headers.CONTENT_DISPOSITION, "inline; filename=\"" + fileName + "\"");
24+
exchange.getResponseSender().send("Hello World");
25+
}
26+
27+
public static void helloWorldJson(HttpServerExchange exchange) {
28+
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");
29+
exchange.getResponseSender().send("{\"message\": \"Hello World\"}");
30+
}
31+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.stubbornjava.examples.undertow.contenttypes;
2+
3+
import com.stubbornjava.common.server.SimpleServer;
4+
5+
import io.undertow.server.HttpHandler;
6+
import io.undertow.server.RoutingHandler;
7+
8+
public class ContentTypesServer {
9+
10+
/*
11+
* Pretty clean am I right? Unless you REALLY REALLY love annotations
12+
* and the magic that comes with them. Don't forget about the copious
13+
* rabbit holes just trying to figure out what code executes because of
14+
* the annotation. This approach all code is just a few clicks away in
15+
* your IDE of choice. Your time is better spent writing code than pretending
16+
* to be a CSI cyber crimes specialist ripping apart some code for a clue to
17+
* whatever it does.
18+
*/
19+
private static final HttpHandler ROUTES = new RoutingHandler()
20+
.get("/helloWorldText", ContentTypeHandlers::helloWorldText)
21+
.get("/helloWorldHtml", ContentTypeHandlers::helloWorldHtml)
22+
.get("/helloWorldFileDownload", ContentTypeHandlers::helloWorldFileDownload)
23+
.get("/helloWorldJson", ContentTypeHandlers::helloWorldJson)
24+
;
25+
26+
public static void main(String[] args) {
27+
SimpleServer server = SimpleServer.simpleServer(ROUTES);
28+
server.start();
29+
}
30+
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package com.stubbornjava.examples.undertow.helloworld;
2+
3+
import org.slf4j.Logger;
4+
import org.slf4j.LoggerFactory;
5+
6+
import io.undertow.Undertow;
7+
import io.undertow.server.HttpServerExchange;
8+
import io.undertow.util.Headers;
9+
10+
public class HelloWorldServer {
11+
private static final Logger logger = LoggerFactory.getLogger(HelloWorldServer.class);
12+
13+
/*
14+
* Creating HttpHandlers as a method and passing it as a method reference is pretty clean.
15+
* This also helps reduce accidentally adding state to handlers.
16+
*/
17+
public static void helloWorldHandler(HttpServerExchange exchange) {
18+
exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, "text/plain");
19+
exchange.getResponseSender().send("Hello World!");
20+
}
21+
22+
public static void main(String[] args) {
23+
int port = 8080;
24+
/*
25+
* "localhost" will ONLY listen on local host.
26+
* If you want the server reachable from the outside you need to set "0.0.0.0"
27+
*/
28+
String host = "localhost";
29+
30+
/*
31+
* If you really want to abstract out the server construction you can.
32+
* StubbornJava recommends to only use abstractions / wrappers on very simple APIs.
33+
* When you abstract over something like an HTTP server its very difficult to have
34+
* an abstraction that covers the nuances of each webserver. Instead accept it and let
35+
* the framework bleed out a bit. Realistically you shouldn't be changing your web server
36+
* all that often. Even if you did fully abstract it out your custom logic tends to bleed
37+
* out eventually, embrace it and move on. You could also just have a static method or
38+
* factory that created the server with your common configurations and allows further
39+
* customization later.
40+
*/
41+
Undertow server = Undertow.builder()
42+
// Add the helloWorldHandler as a method reference.
43+
.addHttpListener(port, host, HelloWorldServer::helloWorldHandler)
44+
.build();
45+
logger.debug("starting on http://" + host + ":" + port);
46+
server.start();
47+
}
48+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package com.stubbornjava.examples.undertow.routing;
2+
3+
import io.undertow.server.HttpHandler;
4+
import io.undertow.server.HttpServerExchange;
5+
import io.undertow.util.Headers;
6+
7+
public class ConstantStringHandler implements HttpHandler {
8+
private final String value;
9+
public ConstantStringHandler(String value) {
10+
this.value = value;
11+
}
12+
13+
@Override
14+
public void handleRequest(HttpServerExchange exchange) throws Exception {
15+
exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
16+
exchange.getResponseSender().send(value);
17+
}
18+
}

0 commit comments

Comments
 (0)