routing with undertow - Skullabs/kikaha GitHub Wiki

Routing with Undertow

Undertow is the Kikaha's HTTP engine. Behind the scenes all method mapped through the uRouting API will be delegated to an undertow's HttpHandler implementation. Developers who are familiar with this API could use Kikaha to auto-deploy its HttpHandler's routes.

import io.undertow.server.*;
import io.undertow.utils.*;
import kikaha.core.api.*;
import javax.inject.*;

@Singleton
@WebResource( value="/hello/world", method="GET" )
public class HelloWorldResource implements HttpHandler {
  @Override
  public void handleRequest(final HttpServerExchange exchange) throws Exception {
    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
    exchange.getResponseSender().send("Hello World");
  }
}

The above sample code produces the same result as the example code found at the undertow.io documentation page. The kikaha.core.modules.http.WebResource maps the resource to a endpoint location and HTTP method. But, unlike what happens with regular uRouting methods (and classes), this implementation needs to be managed.

Simplified Undertow API

All information available during a HTTP request could be retrieved by the HttpServerExchange object, exposed by the Undertow's HttpHandler interface. It is also an object which you can send response back to the HTTP client. Designed to be flexible, it a low-level API which could also make code a little verbose. Kikaha provide an out-of-box abstraction that a few convenient methods that avoid developers to write verbose code. The following sample code show how is possible to use this simplified API.

import kikaha.urouting.*;
import javax.inject.*;
import io.undertow.server.*;

@Singleton
public class MySampleRedirectHttpHandler implements HttpHandler {

  @Inject UndertowHelper requestHelper;

  @Override
  public void handleRequest(final HttpServerExchange exchange) throws Exception {
    // A wrapper for HttpServerExchange
    SimpleExchange simplified = requestHelper.simplify( exchange );
    String newLocation = simplified.getRelativePath() + "/" + simplified.getQueryParam( "id", Long.class );
    simplified.sendResponse( DefaultResponse.seeOther( newLocation ) );
  }
}

In order to use the Simplified API, you should import the kikaha-urouting module on your project.

⚠️ **GitHub.com Fallback** ⚠️