Examples

Hello World

Basic example application that demonstrates:

public class HelloWorld {

    public static void main(String[] args) {

        new HttpServer()
            .register(GET, "/",
                req -> ok().body(render("index")).toFuture()
            )
            .register(POST, "/hello",
                req -> {
                    String name = req.body().asForm().getString("name", "Stranger");
                    String color = req.body().asForm().getString("color", "black");
                    return ok().body(render(new HelloView(name, color))).toFuture();
                }
            )
            .register(GET, "/*path", webJarResourceService())
            .start();

    }

}

complete source | download


Tweet Map

This a very simple demonstration pushing Tweet event from the server to the browser using Server-Sent-Events.

public class TweetMap {

    public static void main(String[] args) throws Exception {
        new TwitterFactory().getInstance().verifyCredentials();

        TweetEventSource eventSource = new TweetEventSource();

        new HttpServer()
            .register(GET, "/data", req -> eventSource.newSubscription())
            .register(GET, "/*path", publicResourceService())
            .start();
    }

}

complete source | download | live demo


Chat

A simple Chat application using WebSockets

public class Chat {

    public static void main(String[] args) {

        ChatBroadcast chat = new ChatBroadcast();

        new HttpServer()
            .register(GET, "/chat", req -> webSocket(chat.newSubscriber(req.queryParams().getString("nick"))))
            .register(GET, "/*path", h(publicResourceService(), webJarResourceService()))
            .start();

    }

}

complete source | download