If you want to use akka-camel or any other modules that have their own "Bootable"'s you'll need to write your own Initializer, which is _ultra_ simple, see below for an example on how to include Akka-camel.
The *Mist* layer was developed to provide a direct connection between the servlet container and Akka actors with the goal of handling the incoming HTTP request as quickly as possible in an asynchronous manner. The motivation came from the simple desire to treat REST calls as completable futures, that is, effectively passing the request along an actor message chain to be resumed at the earliest possible time. The primary constraint was to not block any existing threads and secondarily, not create additional ones. Mist is very simple and works both with Jetty Continuations as well as with Servlet API 3.0 (tested using Jetty-8.0.0.M1). When the servlet handles a request, a message is created typed to represent the method (e.g. Get, Post, etc.), the request is suspended and the message is sent (fire-and-forget) to the *root endpoint* actor. That's it. There are no POJOs required to host the service endpoints and the request is treated as any other. The message can be resumed (completed) using a number of helper methods that set the proper HTTP response status code.
Complete runnable example can be found here: `<https://github.com/buka/akka-mist-sample>`_
Endpoints are actors that handle request messages. Minimally there must be an instance of the *RootEndpoint* and then at least one more (to implement your services).
In this example, we'll use the built-in *RootEndpoint* class and implement our own service from that. Here the services are started in the boot loader and attached to the top level supervisor.
// in this particular case, just boot the built-in default root endpoint
//
Supervise(
actorOf[RootEndpoint],
Permanent) ::
Supervise(
actorOf[SimpleAkkaAsyncHttpService],
Permanent)
::Nil))
factory.newInstance.start
}
**Defining the Endpoint**
The service is an actor that mixes in the *Endpoint* trait. Here the dispatcher is taken from the Akka configuration file which allows for custom tuning of these actors, though naturally, any dispatcher can be used.
URI Handling
************
Rather than use traditional annotations to pair HTTP request and class methods, Mist uses hook and provide functions. This offers a great deal of flexibility in how a given endpoint responds to a URI. A hook function is simply a filter, returning a Boolean to indicate whether or not the endpoint will handle the URI. This can be as simple as a straight match or as fancy as you need. If a hook for a given URI returns true, the matching provide function is called to obtain an actor to which the message can be delivered. Notice in the example below, in one case, the same actor is returned and in the other, a new actor is created and returned. Note that URI hooking is non-exclusive and a message can be delivered to multiple actors (see next example).
Plumbing
********
Hook and provider functions are attached to a parent endpoint, in this case the root, by sending it the **Endpoint.Attach** message.
Finally, bind the *handleHttpRequest* function of the *Endpoint* trait to the actor's *receive* function and we're done.
..code-block:: scala
class SimpleAkkaAsyncHttpService extends Actor with Endpoint {
final val ServiceRoot = "/simple/"
final val ProvideSameActor = ServiceRoot + "same"
final val ProvideNewActor = ServiceRoot + "new"
//
// use the configurable dispatcher
//
self.dispatcher = Endpoint.Dispatcher
//
// there are different ways of doing this - in this case, we'll use a single hook function
// and discriminate in the provider; alternatively we can pair hooks & providers
Messages are handled just as any other that are received by your actor. The servlet requests and response are not hidden and can be accessed directly as shown below.
..code-block:: scala
/**
* Define a service handler to respond to some HTTP requests
*/
class BoringActor extends Actor {
import java.util.Date
import javax.ws.rs.core.MediaType
var gets = 0
var posts = 0
var lastget: Option[Date] = None
var lastpost: Option[Date] = None
def receive = {
// handle a get request
case get: Get =>
// the content type of the response.
// similar to @Produces annotation
get.response.setContentType(MediaType.TEXT_HTML)
//
// "work"
//
gets += 1
lastget = Some(new Date)
//
// respond
//
val res = "<p>Gets: "+gets+" Posts: "+posts+"</p><p>Last Get: "+lastget.getOrElse("Never").toString+" Last Post: "+lastpost.getOrElse("Never").toString+"</p>"
get.OK(res)
// handle a post request
case post:Post =>
// the expected content type of the request
// similar to @Consumes
if (post.request.getContentType startsWith MediaType.APPLICATION_FORM_URLENCODED) {
// the content type of the response.
// similar to @Produces annotation
post.response.setContentType(MediaType.TEXT_HTML)
// "work"
posts += 1
lastpost = Some(new Date)
// respond
val res = "<p>Gets: "+gets+" Posts: "+posts+"</p><p>Last Get: "+lastget.getOrElse("Never").toString+" Last Post: "+lastpost.getOrElse("Never").toString+"</p>"
post.OK(res)
} else {
post.UnsupportedMediaType("Content-Type request header missing or incorrect (was '" + post.request.getContentType + "' should be '" + MediaType.APPLICATION_FORM_URLENCODED + "')")
}
}
case other: RequestMethod =>
other.NotAllowed("Invalid method for this endpoint")
}
}
**Timeouts**
Messages will expire according to the default timeout (specified in akka.conf). Individual messages can also be updated using the *timeout* method. One thing that may seem unexpected is that when an expired request returns to the caller, it will have a status code of OK (200). Mist will add an HTTP header to such responses to help clients, if applicable. By default, the header will be named "Async-Timeout" with a value of "expired" - both of which are configurable.
As noted above, hook functions are non-exclusive. This means multiple actors can handle the same request if desired. In this next example, the hook functions are identical (yes, the same one could have been reused) and new instances of both A and B actors will be created to handle the Post. A third mediator is inserted to coordinate the results of these actions and respond to the caller.
..code-block:: scala
package sample.mist
import akka.actor._
import akka.actor.Actor._
import akka.http._
import javax.servlet.http.HttpServletResponse
class InterestingService extends Actor with Endpoint {
final val ServiceRoot = "/interesting/"
final val Multi = ServiceRoot + "multi/"
// use the configurable dispatcher
self.dispatcher = Endpoint.Dispatcher
//
// The "multi" endpoint shows forking off multiple actions per request
// It is triggered by POSTing to http://localhost:9998/interesting/multi/{foo}
// Try with/without a header named "Test-Token"
// Try with/without a form parameter named "Data"
def hookMultiActionA(uri: String): Boolean = uri startsWith Multi