HTTP (REST and RPC)
The embeddable HTTP server for Reactive REST backed by XOOM Actors and XOOM Wire.

Reactive REST

The XOOM HTTP component supports reactive, scalable, and resilient HTTP servers and REST services running as a small, fast, embedded server. Thus, this component does not run standalone, but is meant to provide very lightweight and high-performing HTTP support within a application- or microservice-based runtime, such as a Bounded Context. The server supports REST and RPC dispatching to implementations of fluent APIs.
It is common for developers to think of REST over HTTP in terms of CRUD because the primary methods provided by the protocol are: POST, GET, PUT, and DELETE. If taken at face value, these verbs are CRUD through and through. Yet, almost no one uses the methods to map directly from browser to a database. Most contemporary applications instead map the HTTP methods to procedures (i.e. a method on a Java or C# class) within the application. Those procedures are responsible for adapting path parameters, headers, and the request body to a form that can be consumed by the inner application components.
The procedure to which the HTTP request is mapped need not represent a CRUD operation at all. When you consider that POST, GET, PUT, DELETE, and others such as PATCH, are message categories that map to procedures, not only ways to perform CRUD operations on data, it makes for a lot more flexibility in how HTTP can be used.
For example, a POST method would always be used with the intention to create some entity resource, such as a product; that is, POST is in the procedure category of creation. Yet, there is no reason for the procedure to which that HTTP request is mapped to be named postProduct() or even the "obvious" createProduct(). Instead, the procedure could be named something more in line with the language spoken by the business, such a catalogProduct(). Here catalog is used as a verb; that is, our company is not in the business of creating new products. The products come to the company already created by a manufacturer. Our company sells products through catalogs. For us, products need to be cataloged (verb) for them to be accessible for purchase through a catalog (noun). With that in mind, establishing a new kind of catalog for a kind of product might be thought of as defining a catalog. Thus, the procedure would be named defineCatalog().
Given this line of reasoning, the ways that HTTP methods are mapped are virtually unlimited, and all the while still honoring the REST way of doing things. The older SOAP protocol used to implement RPC-based APIs, was known to those who could cut through the jargon as "XML over HTTP." Thus, if XML over HTTP can be used to implement RPC, certainly it stands to reason that JSON over HTTP could be used in the same way.
The following sections demonstrate the flexibility of using HTTP as a means to support far more than CRUD. Avoid pedantic opinions that limit creativity. Such opinions are generally held by those who think only in terms of technology and expect the business to speak their language, which is composed mostly of CRUD and collection-oriented (add, insert, remove) terminology.
Consider the overall architecture of our HTTP server. It is highly Reactive by employing actors at every major operational junction.
A request is received and processed asynchronously from beginning through to response.
REST over HTTP is quite commonly employed to support user interfaces, service integrations, and even distribution of event streams. Of course, we don't suggest that your services should be primarily REST-based, we provide our HTTP server for when REST it is useful. Even RPC can be supported. See the above information box. Since REST over HTTP is the most common contemporary use case, the documentation mostly refers to REST rather than RPC, but everything herein is equally applicable to RPC using the style discussed in the above information box.

Use With Domain-Driven Design Context Mapping Patterns

With any use of the XOOM HTTP server, which might be with a REST flavor as more so as RPC, the use of a few Domain-Driven Design patterns are common. Among the Context Mapping patterns, the Open-Host Service and Published Language patterns naturally support these API styles. The Open-Host Service is the well defined API that is open for public use, with the possible requirement of client credentials. The Published Language is the REST resources or RPC response values that are provided.

Overview

Our HTTP component can help you create REST-based services rapidly and with great simplicity. One glance at the REST request mappings to Java objects is all it takes to understand this. The following demonstrates both file-based and code-based fluent request handler mappings.
1
action.user.register.method = POST
2
action.user.register.uri = /users
3
action.user.register.to = register(body:sample.user.UserData userData)
4
5
action.user.contact.method = PATCH
6
action.user.contact.uri = /users/{userId}/contact
7
action.user.contact.to = changeContact(String userId, body:sample.user.ContactData contactData)
Copied!
The above declarations are made in the vlingo-http.properties file. The following is the resource handler implementation to match it.
1
public class UserResource extends ResourceHandler {
2
public void register(final UserData userData) {
3
final User user =
4
User.from(
5
Name.from(userData.nameData.given, userData.nameData.family),
6
Contact.from(userData.contactData.emailAddress, userData.contactData.telephoneNumber));
7
8
repository.save(user);
9
10
completes().with(Response.of(Created, headers(of(Location, userLocation(user.id))), serialized(UserData.from(user))));
11
}
12
13
public void changeContact(final String userId, final ContactData contactData) {
14
final User user = repository.userOf(userId);
15
if (user.doesNotExist()) {
16
completes().with(Response.of(NotFound, userLocation(userId)));
17
return;
18
}
19
20
final User changedUser = user.withContact(new Contact(contactData.emailAddress, contactData.telephoneNumber));
21
22
repository.save(changedUser);
23
24
completes().with(Response.of(Ok, serialized(UserData.from(changedUser))));
25
}
26
}
Copied!
By means of the ResourceHandler base class, there are several Request parts available: URI, headers, body, and any query parameters. You may also access the default ContentType, which may be overridden. See the following queryUsers() handler method.
1
public Completes<Response> queryUsers() {
2
final String page = context().request().queryParameters().valuesOf("page");
3
final String contentType = context().contentType();
4
...
5
}
Copied!
The above is from file-based request/response resource mappings defined in the properties filevlingo-http.properties. Yet, our versatile API also supports fluent mappings in source code.
1
public class UserResource {
2
...
3
public Resource<?> routes() {
4
return resource("User Resource",
5
post("/users")
6
.body(UserData.class)
7
.handle(this::register),
8
patch("/users/{userId}/contact")
9
.param(String.class)
10
.body(ContactData.class)
11
.handle(this::changeContact));
12
}
13
}
Copied!
In the above example only the routes() is shown, and would replace the file-based route mappings previously shown. Also note in this example, when using the fluent routes API your resource class should not extend ResourceHandler. Although you may do so, at time of execution its state will be hollow because the runtime does not support ResourceHandler. Instead, to get similar base class state and behavior with dynamic resources created with the fluent API, use the optional DynamicResourceHandler.
1
public class UserResource extends DynamicResourceHandler {
2
private static final AtomicInteger nextId = new AtomicInteger(0);
3
private final int id;
4
5
public UserResource(final Stage stage) {
6
super(stage);
7
8
this.id = nextId.incrementAndGet();
9
10
logger().info("UserResource: Pooled instance created: " + this.id);
11
}
12
13
public Completes<Response> register(final UserData data) {
14
final String userType = context().request().queryParameters().valuesOf("userType");
15
final String contentType = context().contentType();
16
...
17
}
18
19
...
20
@Override
21
public Resource<?> routes() {
22
logger().info("UserResource: wiring resources for: " + this.id);
23
24
return resource("User Resource", this,
25
post("/users")
26
.body(UserData.class)
27
.handle(this::register),
28
patch("/users/{userId}/contact")
29
.param(String.class)
30
.body(ContactData.class)
31
.handle(this::changeContact));
32
}
33
}
Copied!
By extending DynamicResourceHandler your resource may use the Stage managing this resource, the Logger and Scheduler of that Stage, and the Context with the current Request. The Request provides various request parts such as the URI, headers, body, and any query parameters. You may also access the default ContentType, which may be overridden. See the register(UserData) handler method for an example accessing the query parameters and ContentType.
Query parameters may be mapped more naturally using the fluent API as seen below.
The concrete resource handler must provide a Stage to the DynamicResourceHandler constructor. It is assumed that the concrete resource handler's constructor will take at least the Stage as a parameter. The DynamicResourceHandler declares the routes() method abstract, so it must be overridden in the concrete extender. As you can see above, routes() returns resource()with an optional parameter of the DynamicResourceHandler as thethis object, which is to be given the current request Context before each handler invocation.
In the following sections you will learn how to quickly set up and start your server with resources handlers.

Setting Up the Server

If you will use the file-based configuration you must create vlingo-http.properties. Otherwise you will write source code to define the server configuration. First the file-based configuration is explained, and then the source code and fluent API approach.

File-Based Configuration

Create the file vlingo-http.properties and place it into the project directory hierarchy used for resources. For Maven that would be src/main/resources for production and if you are defining the properties for test, it would be src/test/resources. In this file create the following properties. Your values may differ.
1
#=====================================
2
# server
3
#=====================================
4
5
server.http.port = 8080
6
server.dispatcher.pool = 10
7
server.buffer.pool.size = 100
8
server.message.buffer.size = 65535
9
server.probe.interval = 10
10
server.probe.timeout = 2
11
server.processor.pool.size = 10
12
server.request.missing.content.timeout = 100
13
14
#=====================================
15
# generated resource dispatchers
16
#=====================================
17
18
resource.dispatcher.generated.sources.main = target/generated-sources/
19
resource.dispatcher.generated.sources.test = target/generated-test-sources/
20
resource.dispatcher.generated.classes.main = target/classes/
21
resource.dispatcher.generated.classes.test = target/test-classes/
Copied!
This is the basic minimum configuration necessary to start the server. There are other properties that you will learn about later. The following summarizes these properties.
    1.
    server.http.port: the socket port to be used by the server, which here is 8080.
    2.
    server.dispatcher.pool: the server uses a pool of actors to dispatch incoming requests asynchronous. Here the dispatcher pool size is 10.
    3.
    server.buffer.pool.size: used by the server to create a pool of reusable ByteBuffer instances to use for incoming requests and outgoing resources. There will be at least 100 buffers in this pool. Yet, the elastic pool design enables it to grow dynamically under heavy load and contract back down to 100 buffers as load diminishes.
    4.
    server.message.buffer.size: used by the server when creating the buffer pool to allocate each buffer with this many bytes. Here the buffers will each be 65,535 bytes. (a) This does not limit the overall size of a given incoming message because these may be read in chunks and span multiple buffers. (b) This also does not limit the size of outgoing responses because a non-pooled buffer will be temporarily allocated to send payloads larger than this maximum. Serving larger responses should be the exception rather than common, otherwise performance will suffer. If a common occurrence consider setting this buffer limit to the largest common payload size.
    5.
    server.probe.interval: determines the number of milliseconds between each socket channel probe to receive new connections and requests, and to send new responses. Be careful with this value as various O/S and JDKs deal differently with intervals, possibly being too fast to too slow.
    6.
    server.probe.timeout: the amount of time in milliseconds that the socket channel probe will wait for new connections and requests, and to check for writable status used for sending responses. Be careful with this value as when there are no new requests, it causes the actor's thread to block inside the socket channel probe until this timeout is reached.
    7.
    server.processor.pool.size: used by the server to size the pool of socket channel processors. Here the processor pool size is 10. There will be 10 total actors created and used in round-robin order as new connections are accepted, which will each read from and write to every newly accepted client socket channel connection.
    8.
    server.request.missing.content.timeout: as previously indicated, very large incoming request messages of byte length greater than server.message.buffer.size will require spanning two or more total buffers. This value indicates how long the incomplete message will be retained in the server before it is considered a bad request (missing bytes). This example indicates that such an incomplete request may be retained for a maximum of 100 milliseconds in anticipation of remaining bytes being received.
    9.
    resource.dispatcher.generated.sources.???: These four properties define where generated source code is to be saved as Java source files and where class files are save after dynamic compilation. This example uses the Maven target layout and defines both main and test areas.
In addition to this, it only makes sense to include the description of at least one resource handler (a.k.a. endpoint or controller).
1
#=====================================
2
# user resources
3
#=====================================
4
5
resource.name.user = [register, contact, name, queryUser, queryUsers, queryUserError]
6
7
resource.user.handler = io.vlingo.xoom.http.sample.user.UserResource
8
resource.user.pool = 10
9
resource.user.disallowPathParametersWithSlash = true
10
11
action.user.register.method = POST
12
action.user.register.uri = /users
13
action.user.register.to = register(body:io.vlingo.xoom.http.sample.user.UserData userData)
14
15
action.user.contact.method = PATCH
16
action.user.contact.uri = /users/{userId}/contact
17
action.user.contact.to = changeContact(String userId, body:io.vlingo.xoom.http.sample.user.ContactData contactData)
18
19
action.user.name.method = PATCH
20
action.user.name.uri = /users/{userId}/name
21
action.user.name.to = changeName(String userId, body:io.vlingo.xoom.http.sample.user.NameData nameData)
22
23
action.user.queryUser.method = GET
24
action.user.queryUser.uri = /users/{userId}
25
action.user.queryUser.to = queryUser(String userId)
26
27
action.user.queryUsers.method = GET
28
action.user.queryUsers.uri = /users
29
action.user.queryUsers.to = queryUsers()
30
31
action.user.queryUserError.method = GET
32
action.user.queryUserError.uri = /user/{userId}/error
33
action.user.queryUserError.to = queryUserError(String userId)
Copied!
This is a more complete resource routing definition. The properties are summarized next.
    1.
    resource.name.{name}: The first property of any resource handler is the name, which above is resource.name.user. This says, here is a resource named user. The property's value is an array of method names that are used as individual route request handlers. Each of these names must have a corresponding set of action.{name}... properties, which are documented in a following numbered descriptions. If you do not list a name in this array for every route request handler, the corresponding handler action definition will not be found for the missing name.
    2.
    All properties associated with the named resource are in the form resource.name.property, such as resource.user.handler.
    3.
    resource.{name}.handler: the fully-qualified class name of the concrete ResourceHandler extender. The server will dispatch to actions matching the URI patterns to the methods in this ResourceHandler. The above example references the UserResource, but along with it's package name.
    4.
    resource.{name}.pool: used to create a pool of actors for ResourceHandler instances of the type defined by the resource.{name}.handler property. Individual requests are handled in a round-robin fashion. In this example the resource.user.pool defines a pool size of 10. Note that this pool is created for each server.dispatcher.pool, meaning that there will be a total of server.dispatcher.pool * resource.name.pool actors to handle requests to this named resource.
    5.
    resource.{name}.disallowPathParametersWithSlash: deprecated and must always be true. Above is for the resource named user, as in resource.user.disallow...
    6.
    action.{name}.{endpoint}.method: used to define the HTTP method to be used to make a matching request to the given URI. Here {name} and {endpoint} are placeholders for the actual names. In the first example above {name} is user and the {endpoint} method is register. Note that this property's value may be one of: POST, GET, PUT, PATCH, DELETE, HEAD, TRACE, OPTIONS, or CONNECT.
    7.
    action.{name}.{endpoint}.uri: used to define the URI that will map to the given endpoint. Here {name} and {endpoint} are placeholders for the actual names. In the first example above {name} is user and the {endpoint} method is register. Path parameters, if any, are surrounded by curly braces, such as in /users/{userId}/contact, where the parameter name is userId. In the actual URI, userId must be replaced with some sort of identity, such as may be mapped to a String value.
    8.
    action.{name}.{endpoint}.to: used to define the method name and signature to which this route mapping will dispatch to on the given resource.{name}.handler class instance. Here {name} and {endpoint} are placeholders for the actual names. In the first example above {name} is user and the {endpoint} method is register. When the HTTP method is POST and the URI is /users then the match will route to the given Java method, such as register(UserData userData). In the above example the body: keyword indicates that the UserData will be found in the request body. Depending on the content type, which is by default JSON, the body will be automatically deserialized into an instance of the given type, such as UserData. Note that when the URI contains one or more path parameters, the {paramName} will be mapped to the matching Java method parameter with the same name, and automatically deserialized into the given Java parameter type. In the above example the /users/{userId}/contact maps to the Java method parameter String userId.
When using the file-based configuration there is no limit to the number of path parameters. However, the greater the number of parameters the more complex the Java method will be to create and maintain.
It is quite simple to start a server from file-based configuration.
1
final World world = World.startWithDefaults("server");
2
3
final Server server = Server.startWith(world.stage());
Copied!
Using the above examples, this Server is started on port 8080 and has a single resource handler, UserResource. The remaining properties are applied to the server as previously explained.
The ResourceHandler and DynamicResourceHandler base classes provide access to several request parts, such as headers, query parameters, and other environmental objects.

Provided By ResourceHandler and DynamicResourceHandler:

Type Accessor
Description
Context context()
The Context type provides numerous details. This contains the Request, which in turn contains Method, URL, Version, Headers, and Body. This gives you access to all parts of the request.
ContentType contentType()
The details about the content type of the request. (only on ResourceHandler)
Logger logger()
The means to log debug, error, and informational messages.
Scheduler scheduler()
Use to manage the scheduling of future tasks.
Stage stage()
The Stage of this request.

Source Code Configuration

The following provides a very simple example of source code configuration along with the XOOM HTTP fluent route mapping API. This provides the minimum code to create an endpoint that responds with "Hello, World!". Both Java and Kotlin examples are available. The tutorial descriptions refer to the Java code.
Create a new project with your favorite editor/IDE and create a Bootstrap class with the following content.
Java
Kotlin
Bootstrap.java
1
import io.vlingo.xoom.actors.World;
2
import io.vlingo.xoom.common.Completes;
3
import io.vlingo.xoom.http.Response;
4
import io.vlingo.xoom.http.resource.Configuration.Sizing;
5
import io.vlingo.xoom.http.resource.Configuration.Timing;
6
import io.vlingo.xoom.http.resource.Resource;
7
import io.vlingo.xoom.http.resource.Resources;
8
import io.vlingo.xoom.http.resource.Server;
9
10
import static io.vlingo.xoom.http.resource.ResourceBuilder.get;
11
import static io.vlingo.xoom.http.resource.ResourceBuilder.resource;
12
13
public class Bootstrap {
14
private final static int PORT = 8080;
15
private static Bootstrap instance;
16
17
public final Server server;
18
public final World world;
19
20
private Bootstrap() {
21
this.world = World.startWithDefaults("hello world example java");
22
23
final Resources resources = Resources.are(helloWorldResource());
24
25
this.server =
26
Server.startWith(
27
world.stage(),
28
resources,
29
PORT,
30
Sizing.define(),
31
Timing.define());
32
}
33
34
private Resource helloWorldResource() {
35
return resource("Hello World",
36
get("/helloworld")
37
.handle(() -> withSuccess(of(Ok, "Hello, World!")))
38
);
39
}
40
41
public static final Bootstrap instance() {
42
if (instance == null) {
43
instance = new Bootstrap();
44
}
45
return instance;
46
}
47
48
public static void main(final String[] args) throws Exception {
49
System.out.println("=========================================");
50
System.out.println("service: started at http://localhost:" + Bootstrap.PORT);
51
System.out.println("try: curl http://localhost:" + Bootstrap.PORT + "/helloworld");
52
System.out.println("=========================================");
53
Bootstrap.instance();
54
}
55
}
Copied!
Bootstrap.kt
1
import io.vlingo.actors.World
2
import io.vlingo.common.Completes.withSuccess
3
import io.vlingo.http.Response.of
4
import io.vlingo.http.Response.Status.Ok
5
import io.vlingo.http.resource.Configuration.Sizing
6
import io.vlingo.http.resource.Configuration.Timing
7
import io.vlingo.http.resource.Resource
8
import io.vlingo.http.resource.ResourceBuilder.get
9
import io.vlingo.http.resource.ResourceBuilder.resource
10
import io.vlingo.http.resource.Resources
11
import io.vlingo.http.resource.Server
12
13
class Bootstrap {
14
private val world = World.startWithDefaults("hello world example kotlin")
15
private val server: Server
16
17
init {
18
val resources = Resources.are(helloWorldResource())
19
20
server = Server.startWith(world.stage(),
21
resources,
22
PORT,
23
Sizing.define(),
24
Timing.define())
25
}
26
27
private fun helloWorldResource(): Resource<*> {
28
return resource("hello world resource",
29
get("/helloworld")
30
.handle { withSuccess(of(Ok, "Hello World")) })
31
}
32
33
companion object {
34
const val PORT = 8080
35
}
36
}
37
38
fun main(args: Array<String>) {
39
println("=========================================")
40
println("service: started at http://localhost:" + Bootstrap.PORT)
41
println("check out http://localhost:" + Bootstrap.PORT + "/helloworld")
42
println("=========================================")
43
Bootstrap()
44
}
Copied!
Compile and run the server by means of the Java main() method. Check the results by running the following command-line.
1
> curl http://localhost:8080/helloworld
Copied!
The curl command should print the following text into the terminal window: Hello, World!
The Server logs informational output by means of the World standard Logger configuration.
The Resources(23) is the set of HTTP endpoints, which in this case is only one. The Server instance (25) is where the Resources are held and used to match and dispatch on requests. To start a Server you simply provide a Stage and the Resources. When created, the Server starts listening on port 8080 for HTTP requests.
Sizing (30) is the configuration parameter with the processor pool size, dispatcher pool size, max buffer pool size, and max message size. Timing (31) is the configuration with the probe interval and timeout parameters. For now, we use the default configuration.
The next sections use the previous code as starting point.

Configuring Special Features

There are some additional features available through configuration: static file resources, server-sent events, and feed resources.

Static File Resources

Static file resources are ordinary content in disk files, such as HTML, images, and video. To serve static file resources use the vlingo-http.properties file-based configuration.
1
#=====================================
2
# static file resources
3
#=====================================
4
5
static.files.resource.pool = 5
6
static.files.resource.root = /siteroot/content
7
static.files.resource.subpaths = [/, /css, /js, /views]
Copied!
This configuration auto-creates io.vlingo.xoom.http.resource.StaticFilesResource that serves files from the resource root /siteroot/content directory structure. Any request URI that begins with the static.files.resource.subpaths list will be served.
Virtual URI
Physical URI
/{file}
/siteroot/content/{file}
/css/{file}
/siteroot/content/css/{file}
/js/{file}
/siteroot/content/js/{file}
/views/{file}
/siteroot/content/views/{file}

Server-Sent Events (SSE)

You may create a pre-packaged SSE resource using the following configuration.
1
#=====================================
2
# server-sent events
3
#=====================================
4
5
sse.stream.name.all = /eventstreams/all
6
sse.stream.all.feed.class = io.vlingo.xoom.http.sample.user.AllSseFeedActor
7
sse.stream.all.feed.payload = 50
8
sse.stream.all.feed.interval = 1000
9
sse.stream.all.feed.default.id = -1
10
sse.stream.all.pool = 10
Copied!
This enables clients to register for a long-lasting stream of events from the server. The URI used by clients is the value of sse.stream.name.{name}. In the above example the name is all and the URL is /eventstreams/all.
The sse.stream.all.feed.class is provided by the custom service/application, and in this case is io.vlingo.xoom.http.sample.user.AllSseFeedActor. The fully-qualified class name must be given. There may be up to 50 events in a single feed (one send to a client) with an interval of 1,000 milliseconds between feeds. If the client does not provide an id for the starting event, the default.id is used. In this case it is -1. There will be 10 total feed instances created in the pool.
A client makes a request to subscribe, such as the following.
1
final Request subscribe =
2
Request
3
.method(Method.GET)
4
.uri("/eventstreams/all")
5
.and(RequestHeader.host("StreamsRUs.co"))
6
.and(RequestHeader.accept("text/event-stream;charset=utf-8"));
7
8
client
9
.requestWith(subscribe)
10
.andThenConsume(response -> {
11
switch (response.status) {
12
case Ok:
13
processEvents(response);
14
break;
15
default:
16
logger().error("Unexpected: " + response.status);
17
break;
18
}
19
})
20
.repeat();
Copied!
In the above example the asynchronous io.vlingo.xoom.http.resource.Client will continue to receive responses as feeds occur because it tells the Completes<Response> to repeat() after every feed is received.
The following is a skeleton of class AllSseFeedActor.
1
public class AllSseFeedActor extends Actor implements SseFeed {
2
3
public AllSseFeedActor(final String streamName, final int feedPayload, final String feedDefaultId) {
4
...
5
}
6
7
@Override
8
public void to(final Collection<SseSubscriber> subscribers) {
9
...
10
}
11
}
Copied!
In the above example the custom feed actor is class AllSseFeedActor, which must extend Actor and implement io.vlingo.xoom.http.resource.sse.SseFeed. See the io.vlingo.xoom.http.resource.sse.SseStreamResource that manages the feed generation process, using the custom SseFeed actor when needed.
The feed must follow the SSE standard definition. The following is one example, but not the only possibility.
1
event: SecurityTokenIssued
2
data: {"username": "jclifford", "token": "je;[email protected]"}
3
4
event: SecurityTokenIssued
5
data: {"username": "l.mary", "token": "l9928**)^^322nandquot;}
6
7
event: SecurityTokenIssued
8
data: {"username": "camerontyrone", "token": "pdpjehrhfks'//&dh+a"}
Copied!
There is a complete example in the xoom-http-frontservice and xoom-http-backservice in the Github repository vlingo/xoom-examples.

Feed Resources

There is another kind of feed resource, one that is not a SSE stream, but has similar characteristics. It is a stream of any kind and defines its own response body payload. You might think of such as Atom feeds, or similar.
1
#=====================================
2
# feed resources
3
#=====================================
4
5
feed.resource.name.events = /feeds/events
6
feed.resource.events.producer.class = io.vlingo.xoom.http.resource.feed.EventsFeedProducerActor
7
feed.resource.events.elements = 20
8
feed.resource.events.pool = 10
Copied!
The feed has a name, in this case feed.resource.name.events, which is the URI /feeds/events. Clients may request a feed region by providing an id. The ...elements property indicates the maximum number of 20 elements may be in a given feed. There will be 10 total feed instances created in the pool.
1
public class EventsFeedProducerActor extends Actor implements FeedProducer {
2
...
3
@Override
4
public void produceFeedFor(final FeedProductRequest request) {
5
...
6
}
7
}
Copied!
In the above example the custom feed actor is class EventsFeedProducerActor, which must extend Actor and implement io.vlingo.xoom.http.resource.feed.FeedProducer. The format of the feed itself is not standardized, but may be JSON, XML, or otherwise follow the Atom standard. The EventsFeedProducerActor itself may be backed by the XOOM Lattice exchange feed type, which may stream from a XOOM Symbio Journal, or any kind of EntryReader for the storage types ObjectStore and StateStore.
1
package io.vlingo.xoom.lattice.exchange.feed.Feed;
2
3
import io.vlingo.xoom.actors.Actor;
4
import io.vlingo.xoom.actors.Stage;
5
import io.vlingo.xoom.symbio.Entry;
6
import io.vlingo.xoom.symbio.Source;
7
import io.vlingo.xoom.symbio.store.EntryReader;
8
9
/**
10
* Provides support utilities for {@code Feed} and related types.
11
* Every {@code Feed} has an {@code exchangeName}.
12
*/
13
public interface Feed {
14
/** The default number of messages per feed. */
15
static final int DefaultMessagesPerFeedItem = 20;
16
17
/**
18
* Answer a new {@code Feed} with the given properties.
19
* @param stage the Stage used to create my Feeder
20
* @param exchangeName the String name of my exchange
21
* @param feederType the Actor type of my Feeder
22
* @param entryReaderType the EntryReader that my Feeder uses
23
* @return Feed
24
*/
25
static Feed defaultFeedWith(final Stage stage, final String exchangeName, final Class<? extends Actor> feederType, final EntryReader<?> entryReaderType) {
26
return new DefaultFeed(stage, exchangeName, feederType, entryReaderType);
27
}
28
29
...
30
}
Copied!
The above DefaultFeed is a factory for actor-based Feeder types. Invoking the Feed::feeder() will return a new actor-based Feeder of feederType with the given entryReaderType.
There is a default Feeder , the TextEntryReaderFeeder, that can consume text entries from any XOOM Symbio EntryReader implementation and produce simple feeds.
1
package io.vlingo.xoom.lattice.exchange.feed;
2
3
import java.util.ArrayList;
4
import java.util.List;
5
6
import io.vlingo.xoom.actors.Actor;
7
import io.vlingo.xoom.symbio.BaseEntry.TextEntry;
8
import io.vlingo.xoom.symbio.store.EntryReader;
9
10
/**
11
* The {@code Feeder} serving {@code TextEntry} instances.
12
*/
13
public class TextEntryReaderFeeder extends Actor implements Feeder {
14
private final EntryReader<TextEntry> entryReader;
15
private final Feed feed;
16
17
/**
18
* Construct my default state.
19
* @param feed the Feed that I serve
20
* @param entryReader the {@code EntryReader<TextEntry>} from which content is read
21
*/
22
public TextEntryReaderFeeder(final Feed feed, final EntryReader<TextEntry> entryReader) {
23
this.feed = feed;
24
this.entryReader = entryReader;
25
}
26
27
/**
28
* @see io.vlingo.xoom.lattice.exchange.feed.Feeder#feedItemTo(io.vlingo.lattice.exchange.feed.FeedItemId, io.vlingo.lattice.exchange.feed.FeedConsumer)
29
*/
30
@Override
31
public void feedItemTo(final FeedItemId feedItemId, final FeedConsumer feedInterest) {
32
final long feedId = feedItemId.toLong();
33
final long id = (feedId - 1L) * feed.messagesPerFeedItem() + 1;
34
35
entryReader
36
.readNext(String.valueOf(id), feed.messagesPerFeedItem())
37
.andThen(entries -> {
38
feedInterest.consumeFeedItem(toFeedItem(feedItemId, entries));
39
return entries;
40
});
41
}
42
43
/**
44
* Answer a new {@code FeedItem} from converted {@code entries}.
45
* @param feedItemId the FeedItemId of the current item
46
* @param entries the List<TextEntry> to convert
47
* @return FeedItem
48
*/
49
private FeedItem toFeedItem(final FeedItemId feedItemId, final List<TextEntry> entries) {
50
final List<FeedMessage> messages = new ArrayList<>(entries.size());
51
for (final TextEntry entry : entries) {
52
final FeedMessageBody body = FeedMessageBody.with(entry.entryData());
53
final FeedMessage message = FeedMessage.with(entry.id(), body, entry.typeName(), entry.typeVersion());
54
messages.add(message);
55
}
56
57
if (feed.messagesPerFeedItem() == entries.size()) {
58
return FeedItem.archivedFeedItemWith(feedItemId, feedItemId.next(), feedItemId.previous(), messages);
59
} else {
60
return FeedItem.currentFeedWith(feedItemId, feedItemId.previous(), messages);
61
}
62
}
63
}
Copied!
It should be clear how you can stitch together a number of feeds to provide HTTP feeds of event streams: Response <- http-Feed <- lattice-Feed <- symbio-EntryReader

Request and Response Filters

You can register filters with the Server for both requests and responses. The following is an example of how to start the Server with any number and type of filters:
1
Filters filters =
2
Filters.are(
3
Arrays.asList(new DateRequestFilter()),
4
Arrays.asList(new DateResponseFilter()));
5
6
Server server =
7
Server.startWith(
8
world.stage(),
9
resources,
10
filters,
11
PORT,
12
Sizing.define(),
13
Timing.define());
Copied!
The following is an example of a RequestFilter that is used to ensure that every request has a Date header:
1
public class DateHeaderFilter extends RequestFilter {
2
@Override
3
public Tuple2<Request, Boolean> filter(final Request request) {
4
if (request.headerValueOr(RequestHeader.Date, null) == null) {
5
request.header(RequestHeader.Date, Instant.now().toString());
6
}
7
return Tuple2.from(request, true);
8
}
9
}
Copied!
The return type of Tuple2<Request, Boolean> provides both the Request results of the filter and a Boolean to indicate whether the filter chain should continue (true) or short circuit (false).
The following ResponseFilter does the same as the previous, but for responses:
1
public class DateHeaderFilter extends ResponseFilter {
2
@Override
3
public Tuple2<Request, Boolean> filter(final Response response) {
4
if (response.headerValueOr(ResponseHeader.Date, null) == null) {
5
response.header(ResponseHeader.Date, Instant.now().toString());
6
}
7
return Tuple2.from(response, true);
8
}
9
}
Copied!
The return type is the same as for the RequestFilter and has the same meaning.
There is a special ResponseFilter that supports CORS request-response from cross-origin clients:
1
final CORSResponseFilter filter = new CORSResponseFilter();
2
3
final List<ResponseHeader> headers =
4
Arrays.asList(
5
ResponseHeader.of(ResponseHeader.AccessControlAllowOrigin, "*"),
6
ResponseHeader.of(ResponseHeader.AccessControlAllowHeaders, "Content-Type, Content-Length"),
7
ResponseHeader.of(ResponseHeader.AccessControlAllowMethods, "POST,GET"));
8
9
filter.originHeadersFor(headerAcceptOriginAny, headers);
10
11
final Filters filters = Filters.are(Filters.noRequestFilters(), Arrays.asList(filter));
12
13
Server server =
14
Server.startWith(
15
world.stage(),
16
resources,
17
filters,
18
PORT,
19
Sizing.define(),
20
Timing.define());
Copied!
Register the kinds of access control headers that are supported by the receiving application. There must always be an Access-Control-Allow-Origin header, which is used to match that sent by the client agent. The matching string may be "*" for any origin or some well-know URI of a acceptable application. Other headers are as follows, and each has a corresponding constant in class ResponseHeader:
Header
Constant in Class ResponseHeader
Access-Control-Allow-Origin
AccessControlAllowOrigin
Access-Control-Allow-Credentials
AccessControlAllowCredentials
Access-Control-Expose-Headers
AccessControlExposeHeaders
Access-Control-Max-Age
AccessControlMaxAge
Access-Control-Allow-Methods
AccessControlAllowMethods
Access-Control-Allow-Headers
AccessControlAllowHeaders

Defining Dynamic Resources

XOOM HTTP provides a fluent API to define HTTP endpoints and corresponding Java handler methods. These kinds of resources are different than those loaded from the file vlingo-http.properties. You had a brief introduction to the handler methods at the outset of this chapter. Here you will see them in more detail.
The following is the ResourceBuilder used to fluently create route mappings.
1
ResourceBuilder.resource(final String name, final RequestHandler... requestHandlers)
Copied!
You give the Resource a name and a varargs list of RequestHandler definitions. This method returns a Resource. The Server needs a set of Resource instances to match and route HTTP requests to handlers that respond. Each of the RequestHandler instances are mapped by means of declaring HTTP methods, as next discussed.

HTTP Methods

The fluent API supports the following HTTP methods.
    ResourceBuilder.post(final String uri)
    ResourceBuilder.get(final String uri)
    ResourceBuilder.put(final String uri)
    ResourceBuilder.patch(final String uri)
    ResourceBuilder.delete(final String uri)
    ResourceBuilder.head(final String uri)
    ResourceBuilder.options(final String uri)
    ResourceBuilder.trace(final String uri)
    ResourceBuilder.connect(final String uri)
All of the above methods answer a new resource handler instance, whether or not it extends the base class DynamicRequestHandler. We recommend using static imports for the most fluent use of the API.
1
import static io.vlingo.xoom.common.serialization.JsonSerialization.serialized;
2
import static io.vlingo.xoom.http.Response.Status.Created;
3
import static io.vlingo.xoom.http.Response.Status.NotFound;
4
import static io.vlingo.xoom.http.Response.Status.Ok;
5
import static io.vlingo.xoom.http.ResponseHeader.Location;
6
import static io.vlingo.xoom.http.ResponseHeader.headers;
7
import static io.vlingo.xoom.http.ResponseHeader.of;
8
import static io.vlingo.xoom.http.resource.ResourceBuilder.get;
9
import static io.vlingo.xoom.http.resource.ResourceBuilder.patch;
10
import static io.vlingo.xoom.http.resource.ResourceBuilder.post;
11
import static io.vlingo.xoom.http.resource.ResourceBuilder.resource;
Copied!
The above shows other common static imports besides those needed for fluent resource wiring.

Request Handler

The request handler enforces type safety on the handler function method definition through the declaration of expected parameters. There are several mapping options, so consider each.

Path Parameters

Map path parameters by identifying them in the URI as a {variable} and then indicate the type in the path() method to be used by your handler.
Java
Kotlin
1
get("/user/{userId}")
2
.path(String.class)
3
.handler((userId) -> /* */);
Copied!
Here the userId will be mapped to a String because the method path(String.class) specifies that type. You can specify parameter mappings to any of the following types.
    String
    Long
    Integer
    Float
    Double
    Boolean
    Short
    Character
The path() method must be used before any other route mapping method, otherwise an exception will be thrown when the Server starts.
When using path() be sure you have the same path variable in the URI between brackets {<variable>} as the path() methods reference.

Body Parameter

The body() method maps the HTTP body into the type you specify.
Java
Kotlin
1
post("/user")
2
.body(NameData.class)
3
.handler((nameData) -> /* */);
Copied!
1
Copied!

Query Parameters

You may use query parameters in the expected way. For example, page=5 is a query parameter in this curl command.
1
> curl http://localhost:8080/user?page=5
Copied!
You may map this specific query parameter fluently in three different ways.
Java
Kotlin
1
get("/user")
2
.query("page")
3
.handler((page) -> /* */);
4
5
get("/user")
6
.query("page", Integer.class)
7
.handler((page) -> /* */);
8
9
get("/user")
10
.query("page", Integer.class, 0 /* default value */)
11
.handler((page) -> /* */);
Copied!
1
get("/user")
2
.query("page")
3
.handler((page) -> /* */);
Copied!
By default, the type of all query parameters is String. When the query parameter isn't present, the value is null. It's good practice to always specify a default value for query parameters to avoid unexpected behavior.

Request Headers

You may access request headers as expected.
Java
Kotlin
1
get("/user")
2
.header("Location")
3
.handler((location) -> /* */);
Copied!

Combining Them All

The following is an example showing all of the above parameter options.
Java
Kotlin