public interface Chain
A handler chain can be constructed using the Handlers.chain(ServerConfig, ratpack.func.Action)
like methods.
Chains may be backed by a registry
, depending on how the chain was constructed.
For example, the Ratpack Guice module makes it possible to create a Guice backed registry that can be used to
construct dependency injected handlers. See the ratpack-guice
library for details.
A Groovy specific subclass of this interface is provided by the Groovy module that overloads methods here with Closure
based variants.
See the ratpack-groovy
library for details.
Methods such as get(String, Handler)
, prefix(String, Action)
, accept a string argument as a request path binding specification.
These strings can contain symbols that allow PathTokens
to be captured and for path binding to be dynamic.
For example, the path string "foo/:val"
will match paths such as "foo/bar"
, "foo/123"
or indeed "foo/«anything»"
.
The following table describes the types of symbols that can be used in path strings…
Path Type | Syntax | Example |
---|---|---|
Literal | foo |
"foo" |
Regular Expression Literal | ::«regex» |
"foo/::\d+" |
Optional Path Token | :«token-name»? |
"foo/:val?" |
Mandatory Path Token | :«token-name» |
"foo/:val" |
Optional Regular Expression Path Token | :«token-name»?:«regex» |
"foo/:val?:\d+" |
Mandatory Regular Expression Path Token | :«token-name»:«regex» |
"foo/:val:\d+" |
The following example shows different kinds of binding paths in action.
import ratpack.test.embed.EmbeddedApp;
import com.google.common.base.Objects;
import com.google.common.io.BaseEncoding;
import java.util.Arrays;
import java.util.Locale;
import static org.junit.Assert.*;
public class Example {
public static void main(String... args) throws Exception {
EmbeddedApp.fromHandlers(c -> c
.get("favorites/food", ctx -> ctx.render("pizza")) // Literal
.get("favorites/::colou?r", ctx -> ctx.render("blue")) // Regular expression literal
.get("optionalToken/:tkn?", ctx -> ctx.render(ctx.getPathTokens().toString())) // Optional path token
.get("greeting/:name?", ctx -> // Optional path token with default handling
ctx.render("Hello " + Objects.firstNonNull(ctx.getPathTokens().get("name"), "world"))
)
.get("convert/hex/:tkn", ctx -> // Mandatory path token
ctx.render("Hello " + BaseEncoding.base64().encode(ctx.getPathTokens().get("tkn").getBytes("UTF-8")))
)
.get("pi/:precision?:[\\d]+", ctx -> // Optional regular expression path token
ctx.render(String.format(Locale.ENGLISH, "%1." + Objects.firstNonNull(ctx.getPathTokens().get("precision"), "5") + "f", Math.PI))
)
.get("sum/:num1:[\\d]+/:num2:[\\d]+", ctx -> // Mandatory regular expression path tokens
ctx.render(
Arrays.asList("num1", "num2")
.stream()
.map(it -> ctx.getPathTokens().get(it))
.mapToInt(Integer::valueOf)
.sum() + ""
)
)
).test(httpClient -> {
assertEquals("pizza", httpClient.getText("favorites/food")); // Literal value matched
assertEquals("blue", httpClient.getText("favorites/color")); // Regular expression literal matched
assertEquals("blue", httpClient.getText("favorites/colour")); // Regular expression literal matched
assertEquals("{tkn=val}", httpClient.getText("optionalToken/val")); // Optional path token with value specified
assertEquals("{tkn=}", httpClient.getText("optionalToken/")); // Optional path token with trailing slash treated as empty string
assertEquals("{}", httpClient.getText("optionalToken")); // Optional path token without trailing slash treated as missing
assertEquals("Hello Ratpack", httpClient.getText("greeting/Ratpack")); // Optional path token with value specified
assertEquals("Hello world", httpClient.getText("greeting")); // Optional path token with default handling
assertEquals("Hello UmF0cGFjaw==", httpClient.getText("convert/hex/Ratpack")); // Mandatory path token
assertEquals("3.14159", httpClient.getText("pi")); // Optional regular expression path token with default handling
assertEquals("3.14", httpClient.getText("pi/2")); // Optional regular expression path token with value specified
assertEquals("3.1415927", httpClient.getText("pi/7")); // Optional regular expression path token with value specified
assertEquals("42", httpClient.getText("sum/13/29")); // Mandatory regular expression path tokens
});
}
}
Modifier and Type | Method and Description |
---|---|
Chain |
assets(String path,
String... indexFiles)
Adds a handler that serves static assets at the given file system path, relative to the contextual file system binding.
|
Handler |
chain(Action<? super Chain> action)
Constructs a handler using the given action to define a chain.
|
default Handler |
chain(Class<? extends Action<? super Chain>> action) |
default Chain |
delete(Class<? extends Handler> handler) |
Chain |
delete(Handler handler)
Adds a handler that delegates to the given handler if
the
request HTTPMethod is DELETE and the path is at the current root. |
default Chain |
delete(String path,
Class<? extends Handler> handler) |
Chain |
delete(String path,
Handler handler)
Adds a handler that delegates to the given handler if
the relative
path matches the given path and the request HTTPMethod
is DELETE . |
Chain |
fileSystem(String path,
Action<? super Chain> action)
Adds a handler to this chain that changes the
FileSystemBinding for the given handler chain. |
default Chain |
fileSystem(String path,
Class<? extends Action<? super Chain>> action) |
default Chain |
get(Class<? extends Handler> handler) |
Chain |
get(Handler handler)
Adds a handler that delegates to the given handler
if the
request HTTPMethod is GET and the path is at the
current root. |
default Chain |
get(String path,
Class<? extends Handler> handler) |
Chain |
get(String path,
Handler handler)
Adds a handler that delegates to the given handler
if the relative
path matches the given path and the request
HTTPMethod is GET . |
Registry |
getRegistry()
The registry that backs this chain.
|
ServerConfig |
getServerConfig()
The server config of the application that this chain is being created for.
|
default Chain |
handler(Class<? extends Handler> handler) |
Chain |
handler(Handler handler)
Adds the given handler to this.
|
default Chain |
handler(String path,
Class<? extends Handler> handler) |
Chain |
handler(String path,
Handler handler)
Adds a handler that delegates to the given handler if the relative
path
matches the given path exactly. |
default Chain |
header(String headerName,
String headerValue,
Class<? extends Handler> handler) |
Chain |
header(String headerName,
String headerValue,
Handler handler)
Adds a handler to the chain that delegates to the given handler if the request has a header with the given name and a its value matches the given value exactly.
|
Chain |
host(String hostName,
Action<? super Chain> action)
Adds a handler to the chain that delegates to the given handler chain if the request has a
Host header that matches the given value exactly. |
default Chain |
host(String hostName,
Class<? extends Action<? super Chain>> action) |
Chain |
insert(Action<? super Chain> action)
Inserts the given nested handler chain.
|
default Chain |
insert(Class<? extends Action<? super Chain>> action) |
default Chain |
patch(Class<? extends Handler> handler) |
Chain |
patch(Handler handler)
Adds a handler that delegates to the given handler if
the
request HTTPMethod is PATCH and the path is at the current root. |
default Chain |
patch(String path,
Class<? extends Handler> handler) |
Chain |
patch(String path,
Handler handler)
Adds a handler that delegates to the given handler if
the relative
path matches the given path and the request HTTPMethod
is PATCH . |
default Chain |
post(Class<? extends Handler> handler) |
Chain |
post(Handler handler)
Adds a handler that delegates to the given handler if
the
request HTTPMethod is POST and the path is at the current root. |
default Chain |
post(String path,
Class<? extends Handler> handler) |
Chain |
post(String path,
Handler handler)
Adds a handler that delegates to the given handler if
the relative
path matches the given path and the request HTTPMethod
is POST . |
Chain |
prefix(String prefix,
Action<? super Chain> action)
Adds a handler that delegates to the given handlers if the
relative path starts with the given
prefix . |
default Chain |
prefix(String prefix,
Class<? extends Action<? super Chain>> action) |
default Chain |
put(Class<? extends Handler> handler) |
Chain |
put(Handler handler)
Adds a handler that delegates to the given handler if
the
request HTTPMethod is PUT and the path is at the current root. |
default Chain |
put(String path,
Class<? extends Handler> handler) |
Chain |
put(String path,
Handler handler)
Adds a handler that delegates to the given handler if
the relative
path matches the given path and the request HTTPMethod
is PUT . |
Chain |
redirect(int code,
String location)
Sends an HTTP redirect to the specified location.
|
Chain |
register(Action<? super RegistrySpec> action)
Builds a new registry via the given action, then registers it via
register(Registry) . |
Chain |
register(Action<? super RegistrySpec> registryAction,
Action<? super Chain> action)
Adds a handler that inserts the given handler chain with a registry built by the given action via
Context.insert(ratpack.registry.Registry, Handler...) . |
default Chain |
register(Action<? super RegistrySpec> registryAction,
Class<? extends Action<? super Chain>> action) |
Chain |
register(Registry registry)
Makes the contents of the given registry available for downstream handlers of the same nesting level.
|
Chain |
register(Registry registry,
Action<? super Chain> action)
Adds a handler that inserts the given handler chain with the given registry via
Context.insert(ratpack.registry.Registry, Handler...) . |
default Chain |
register(Registry registry,
Class<? extends Action<? super Chain>> action) |
Chain assets(String path, String... indexFiles)
See Handlers.assets(ServerConfig, String, java.util.List)
for more details on the handler created
prefix("foo") { assets("d1", "index.html", "index.xhtml") }In the above configuration a request like "/foo/app.js" will return the static file "app.js" that is located in the directory "d1".
If the request matches a directory e.g. "/foo", an index file may be served. The indexFiles
array specifies the names of files to look for in order to serve.
path
- the relative path to the location of the assets to serveindexFiles
- the index files to try if the request is for a directoryHandler chain(Action<? super Chain> action) throws Exception
action
- The action that defines the handler chainException
- any thrown by action
default Handler chain(Class<? extends Action<? super Chain>> action) throws Exception
Exception
Chain delete(String path, Handler handler)
path
matches the given path
and the request
HTTPMethod
is DELETE
.path
- the relative path to match onhandler
- the handler to delegate toget(String, Handler)
,
post(String, Handler)
,
put(String, Handler)
,
patch(String, Handler)
,
handler(String, Handler)
Chain delete(Handler handler)
request
HTTPMethod
is DELETE
and the path
is at the current root.handler
- the handler to delegate toget(Handler)
,
post(Handler)
,
put(Handler)
,
patch(Handler)
Chain fileSystem(String path, Action<? super Chain> action) throws Exception
FileSystemBinding
for the given handler chain.path
- the relative path to the new file system binding pointaction
- the definition of the handler chainException
- any thrown by action
default Chain fileSystem(String path, Class<? extends Action<? super Chain>> action) throws Exception
Exception
Chain get(String path, Handler handler)
path
matches the given path
and the request
HTTPMethod
is GET
.
path
- the relative path to match onhandler
- the handler to delegate topost(String, Handler)
,
put(String, Handler)
,
patch(String, Handler)
,
delete(String, Handler)
,
handler(String, Handler)
Chain get(Handler handler)
request
HTTPMethod
is GET
and the path
is at the
current root.handler
- the handler to delegate topost(Handler)
,
put(Handler)
,
patch(Handler)
,
delete(Handler)
ServerConfig getServerConfig()
Registry getRegistry() throws IllegalStateException
What the registry is depends on how the chain was created.
The Handlers.chain(ServerConfig, Registry, Action)
allows the registry to be specified.
For a Guice based application, the registry is backed by Guice.
IllegalStateException
- if there is no backing registry for this chainHandlers.chain(ServerConfig, Registry, Action)
Chain handler(Handler handler)
handler
- the handler to addChain handler(String path, Handler handler)
path
matches the given path
exactly.
Nesting path
handlers will not work due to the exact matching, use a combination of path
and prefix
instead. See prefix(String, ratpack.func.Action)
for details.
// this will not work path("person/:id") { path("child/:childId") { // a request of /person/2/child/1 will not get passed the first handler as it will try // to match "person/2/child/1" with "person/2" which does not match } // this will work prefix("person/:id") { path("child/:childId") { // a request of /person/2/child/1 will work this time } }
See Handlers.path(String, Handler)
for the details on how path
is interpreted.
path
- the relative path to match exactly onhandler
- the handler to delegate topost(String, Handler)
,
get(String, Handler)
,
put(String, Handler)
,
patch(String, Handler)
,
delete(String, Handler)
Chain header(String headerName, String headerValue, Handler handler)
chain. header("foo", "bar", new Handler() { public void handle(Context context) { context.getResponse().send("Header Handler"); } });
headerName
- the name of the HTTP Header to match onheaderValue
- the value of the HTTP Header to match onhandler
- the handler to delegate todefault Chain header(String headerName, String headerValue, Class<? extends Handler> handler)
Chain host(String hostName, Action<? super Chain> action) throws Exception
Host
header that matches the given value exactly.
chain. host("foo.com", new Action<Chain>() { public void execute(Chain hostChain) { hostChain.handler(new Handler() { public void handle(Context context) { context.getResponse().send("Host Handler"); } }); } });
hostName
- the name of the HTTP Header to match onaction
- the handler chain to delegate to if the host matchesException
- any thrown by action
default Chain host(String hostName, Class<? extends Action<? super Chain>> action) throws Exception
Exception
Chain insert(Action<? super Chain> action) throws Exception
Shorter form of handler(Handler)
handler}(chain
(action
).
action
- the handler chain to insertException
- any thrown by action
default Chain insert(Class<? extends Action<? super Chain>> action) throws Exception
Exception
Chain patch(String path, Handler handler)
path
matches the given path
and the request
HTTPMethod
is PATCH
.path
- the relative path to match onhandler
- the handler to delegate toget(String, Handler)
,
post(String, Handler)
,
put(String, Handler)
,
delete(String, Handler)
,
handler(String, Handler)
Chain patch(Handler handler)
request
HTTPMethod
is PATCH
and the path
is at the current root.handler
- the handler to delegate toget(Handler)
,
post(Handler)
,
put(Handler)
,
delete(Handler)
Chain post(String path, Handler handler)
path
matches the given path
and the request
HTTPMethod
is POST
.
path
- the relative path to match onhandler
- the handler to delegate toget(String, Handler)
,
put(String, Handler)
,
patch(String, Handler)
,
delete(String, Handler)
,
handler(String, Handler)
Chain post(Handler handler)
request
HTTPMethod
is POST
and the path
is at the current root.
handler
- the handler to delegate toget(Handler)
,
put(Handler)
,
patch(Handler)
,
delete(Handler)
Chain prefix(String prefix, Action<? super Chain> action) throws Exception
prefix
.
All path based handlers become relative to the given prefix
.
chain .prefix("person/:id", new Action<Chain>() { public void execute(Chain personChain) throws Exception { personChain .get("info", new Handler() { public void handle(Context context) { // e.g. /person/2/info } }) .post("save", new Handler() { public void handle(Context context) { // e.g. /person/2/save } }) .prefix("child/:childId", new Action<Chain>() { public void execute(Chain childChain) { childChain .get("info", new Handler() { public void handle(Context context) { // e.g. /person/2/child/1/info } }); } }); } });
See Handlers.prefix(String, Handler)
for format details on the prefix
string.
prefix
- the relative path to match onaction
- the handler chain to delegate to if the prefix matchesException
- any thrown by action
default Chain prefix(String prefix, Class<? extends Action<? super Chain>> action) throws Exception
Exception
Chain put(String path, Handler handler)
path
matches the given path
and the request
HTTPMethod
is PUT
.path
- the relative path to match onhandler
- the handler to delegate toget(String, Handler)
,
post(String, Handler)
,
patch(String, Handler)
,
delete(String, Handler)
,
handler(String, Handler)
Chain put(Handler handler)
request
HTTPMethod
is PUT
and the path
is at the current root.handler
- the handler to delegate toget(Handler)
,
post(Handler)
,
patch(Handler)
,
delete(Handler)
Chain redirect(int code, String location)
The handler to add is created via Handlers.redirect(int, String)
.
code
- the 3XX HTTP status code.location
- the URL to set in the Location response headerHandlers.redirect(int, String)
Chain register(Registry registry)
The registry is inserted via the Context.next(Registry)
method.
registry
- the registry whose contents should be made available to downstream handlersChain register(Action<? super RegistrySpec> action) throws Exception
register(Registry)
.action
- the definition of a registryException
- any thrown by action
Chain register(Registry registry, Action<? super Chain> action) throws Exception
Context.insert(ratpack.registry.Registry, Handler...)
.registry
- the registry to insertaction
- the definition of the handler chainException
- any thrown by action
default Chain register(Registry registry, Class<? extends Action<? super Chain>> action) throws Exception
Exception
Chain register(Action<? super RegistrySpec> registryAction, Action<? super Chain> action) throws Exception
Context.insert(ratpack.registry.Registry, Handler...)
.registryAction
- the definition of the registry to insert]action
- the definition of the handler chainException
- any thrown by action