Beliebte Suchanfragen

Cloud Native

DevOps

IT-Security

Agile Methoden

Java

//

Fine tuning embedded jetty inside of spark framework.

5.7.2017 | 2 minutes of reading time

Tech is easy when complexity is hidden away. Hiding complexity means some things are either unreachable anymore or at least hard to reach. One example of easy tech is the spark framework (not to confuse with Apache Spark). Spark lets you build HTTP-services with literally minimal code. The following one-line example is a typical starting point of a application using spark:

1import static spark.Spark.get;
2 
3public class HelloWorld {
4    public static void main(String[] args) {
5        get("/hello", (req, res) -> "Hello World");
6    }
7}

Spark deals with most of your http-related need in a similar concise way. Its features are well documented, except when you need to access the hidden complexity I have been talking about. One such feature I consider hidden complexity of spark is its embedded jetty server. In most cases you won’t even notice your are running on top of jetty when using spark. But then there are those rare cases, where you need to change the default configuration for jetty used by spark. Thats where you use the EmbeddedServers class to construct a custom instance of jetty. It is not so well documented (as of time of writing at least), but the example below should give you a good starting point.

For example changing the name of cookie holding the session id form JSESSIONID to something else is done like this:

1public class Main {
2    public static void main(String ...args) throws Exception {
3        EmbeddedServers.add(EmbeddedServers.Identifiers.JETTY, (Routes routeMatcher, StaticFilesConfiguration staticFilesConfiguration, boolean hasMultipleHandler) -> {
4            JettyHandler handler = setupHandler(routeMatcher, staticFilesConfiguration, hasMultipleHandler);
5            handler.getSessionCookieConfig().setName("XSESSION");
6            return new EmbeddedJettyServer((int maxThreads, int minThreads, int threadTimeoutMillis) -> new Server(), handler);
7        });
8 
9        get("/hello", (req, res) -> {
10            req.session(true);
11            return "Hello World";
12        });
13    }
14 
15    /**
16     * setup handler in the same manner spark does in {@code EmbeddedJettyFactory.create()}.
17     *
18     * @see <a href="https://github.com/perwendel/spark/blob/master/src/main/java/spark/embeddedserver/jetty/EmbeddedJettyFactory.java#L39">EmbeddedJettyFactory.java</a>
19     */
20    private static JettyHandler setupHandler(Routes routeMatcher, StaticFilesConfiguration staticFilesConfiguration, boolean hasMultipleHandler) {
21        MatcherFilter matcherFilter = new MatcherFilter(routeMatcher, staticFilesConfiguration, false, hasMultipleHandler);
22        matcherFilter.init(null);
23 
24        return new JettyHandler(matcherFilter);
25    }
26}

You construct a custom instance of jetty using its api. This is where you leave the “easy tech” land, but jetty and spark provide you with enough well thought out default values so you never feel overwhelmed by the amount of code you have to write. In the example a instance of jetty is constructed in the same way spark does it by default (i.e. MatcherFilter + JettyHandler). I only added the line where the name of session-id holding cookie is changed to XSESSION. This way I do not break functionality provided by spark (routing, filtering, etc.).

Final words.

As usual with spark you must pay attention to order in which you configure spark and setup your routing. Calls to EmbeddedServers.add() must take place before calling Spark.get() for the first time. Once Spark.get() or any other method related to routing is called the lazy initialization kicks in and spark looks for the server constructing factory you have not provided yet.

share post

Likes

0

//

More articles in this subject area

Discover exciting further topics and let the codecentric world inspire you.

//

Gemeinsam bessere Projekte umsetzen.

Wir helfen deinem Unternehmen.

Du stehst vor einer großen IT-Herausforderung? Wir sorgen für eine maßgeschneiderte Unterstützung. Informiere dich jetzt.

Hilf uns, noch besser zu werden.

Wir sind immer auf der Suche nach neuen Talenten. Auch für dich ist die passende Stelle dabei.