Interface Chain
-
- All Known Subinterfaces:
GroovyChain
- All Known Implementing Classes:
GroovyChainAction
public interface ChainA chain is a write only builder for composing handlers.A chain object can't be used to handle requests. It can be thought of as a Domain Specific Language (DSL), or API, for constructing a
List<Handler>.To understand the concept of a all chain, it is important to understand that a
Handlercan do one of three things:- Respond to the request (terminating processing);
Insert handlersand delegate processing;- Delegate to the
next handler.
Methods like
Handlers.chain(ServerConfig, ratpack.func.Action)take a function that acts on aChain, and return aHandler. The returned handler effectively just performs an insert of the handlers added to the chain during the action..It is very common to use this API to declare the handlers for an application as part of startup via the
RatpackServerSpec.handlers(Action)method.Registry
Chains may be backed by a
registry, depending on how the chain was constructed. TheRatpackServerSpec.handlers(Action)method backs the chain instance with the server registry. The backing registry can be obtained viagetRegistry()on the chain instance.This mechanism allows access to “supporting objects” while building the chain. Methods such as
all(Class)also allow obtaining all implementations from the registry to use. This can be useful when using the Guice integration (or similar) to allow all instance to be dependency injected through Guice.Adding handlers
The most basic method of Chain API is the
all(Handler)method. The word “all” represents that all requests reaching this point in the chain will flow through the given handler. This is in contrast to methods such aspath(String, Handler)that will only the request through the given handler if the request path matches.Methods such as
path(String, Handler),when(Predicate, Action)etc. are merely more convenient forms ofall(Handler)and use of the static methods ofHandlers.For each method that takes a literal
Handler, there exists a variant that takes aClass<? extends Handler>. Such methods obtain an instance of the given handler by asking the chain registry for an instance of the given type. This is generally most useful if the chain registry is backed by some kind of dependency injection mechanism (like Google Guice) that can construct the handler and inject its dependencies as needed.Path Binding
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 allowPathTokensto 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 binding symbols 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.MoreObjects; 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 " + MoreObjects.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." + MoreObjects.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 }); } }HTTP Method binding
Methods such as
get(Handler),post(Handler)etc. bind based on the HTTP method of the request. They are effectively a combination of the use ofpath(String, Handler)and theContext.byMethod(Action)construct to declare that the given path ONLY responds to the specified method.The following two code snippets are identical:
import ratpack.test.embed.EmbeddedApp; import static org.junit.Assert.*; public class Example { public static void main(String... args) throws Exception { EmbeddedApp.fromHandlers(c -> c .path("foo", ctx -> ctx.byMethod(m -> m .get(() -> ctx.render("ok")) ) ) ).test(httpClient -> { assertEquals("ok", httpClient.getText("foo")); assertEquals(405, httpClient.post("foo").getStatusCode()); }); } }import ratpack.test.embed.EmbeddedApp; import static org.junit.Assert.*; public class Example { public static void main(String... args) throws Exception { EmbeddedApp.fromHandlers(c -> c .get("foo", ctx -> ctx.render("ok")) ).test(httpClient -> { assertEquals("ok", httpClient.getText("foo")); assertEquals(405, httpClient.post("foo").getStatusCode()); }); } }That is, methods such as
get(String, Handler),get(Handler)etc. terminate processing with a405(method not supported) client error if the request path matches but the HTTP method does not. They should not be used for URLs that respond differently depending on the method. The correct way to do this is to usepath(String, Handler)andContext.byMethod(Action).import ratpack.test.embed.EmbeddedApp; import static org.junit.Assert.*; public class Example { public static void main(String... args) throws Exception { EmbeddedApp.fromHandlers(c -> c .path("foo", ctx -> ctx.byMethod(m -> m .get(() -> ctx.render("GET")) .post(() -> ctx.render("POST")) ) ) ).test(httpClient -> { assertEquals("GET", httpClient.getText("foo")); assertEquals("POST", httpClient.postText("foo")); assertEquals(405, httpClient.delete("foo").getStatusCode()); }); } }Given the following, a POST to /foo will yield a 405 response.
import ratpack.test.embed.EmbeddedApp; import static org.junit.Assert.assertEquals; public class Example { public static void main(String... args) throws Exception { EmbeddedApp.fromHandlers(c -> c .get("foo", ctx -> ctx.render("GET")) .post("foo", ctx -> ctx.render("POST")) ).test(httpClient -> { assertEquals("GET", httpClient.getText("foo")); // NOTE: returns 405, not 200 and "POST" assertEquals(405, httpClient.post("foo").getStatusCode()); }); } }All methods that match HTTP methods, are synonyms for
path(String, Class)in terms of path binding. That is,get(Handler)behaves the same way with regard to path binding aspath(Handler), and notall(Handler).
-
-
Method Summary
All Methods Instance Methods Abstract Methods Default Methods Modifier and Type Method Description default Chainall(java.lang.Class<? extends Handler> handler)Chainall(Handler handler)Adds the given handler to this.default Handlerchain(java.lang.Class<? extends Action<? super Chain>> action)default Handlerchain(Action<? super Chain> action)Constructs a handler using the given action to define a chain.default Chaindelete(java.lang.Class<? extends Handler> handler)default Chaindelete(java.lang.String path, java.lang.Class<? extends Handler> handler)default Chaindelete(java.lang.String path, Handler handler)Adds a handler that delegates to the given handler if the relativepathmatches the givenpathand therequestHTTPMethodisDELETE.default Chaindelete(Handler handler)Adds a handler that delegates to the given handler if therequestHTTPMethodisDELETEand thepathis at the current root.default Chainfiles()files(Action), using the default config.default Chainfiles(Action<? super FileHandlerSpec> config)Adds a handler that serves files from the file system.default ChainfileSystem(java.lang.String path, java.lang.Class<? extends Action<? super Chain>> action)default ChainfileSystem(java.lang.String path, Action<? super Chain> action)Adds a handler to this chain that changes theFileSystemBindingfor the given handler chain.default Chainget(java.lang.Class<? extends Handler> handler)default Chainget(java.lang.String path, java.lang.Class<? extends Handler> handler)default Chainget(java.lang.String path, Handler handler)Adds a handler that delegates to the given handler if the relativepathmatches the givenpathand therequestHTTPMethodisGET.default Chainget(Handler handler)Adds a handler that delegates to the given handler if therequestHTTPMethodisGETand thepathis at the current root.RegistrygetRegistry()The registry that backs this chain.ServerConfiggetServerConfig()The server config of the application that this chain is being created for.default Chainhost(java.lang.String hostName, java.lang.Class<? extends Action<? super Chain>> action)default Chainhost(java.lang.String hostName, Action<? super Chain> action)Adds a handler to the chain that delegates to the given handler chain if the request has aHostheader that matches the given value exactly.default Chaininsert(java.lang.Class<? extends Action<? super Chain>> action)default Chaininsert(Action<? super Chain> action)Inserts the given nested handler chain.default ChainnotFound()Raises a 404Context.clientError(int).default ChainonlyIf(Predicate<? super Context> test, java.lang.Class<? extends Handler> handler)default ChainonlyIf(Predicate<? super Context> test, Handler handler)Invokes the given handler only if the predicate passes.default Chainoptions(java.lang.Class<? extends Handler> handler)default Chainoptions(java.lang.String path, java.lang.Class<? extends Handler> handler)default Chainoptions(java.lang.String path, Handler handler)Adds a handler that delegates to the given handler if the relativepathmatches the givenpathand therequestHTTPMethodisOPTIONS.default Chainoptions(Handler handler)Adds a handler that delegates to the given handler if therequestHTTPMethodisOPTIONSand thepathis at the current root.default Chainpatch(java.lang.Class<? extends Handler> handler)default Chainpatch(java.lang.String path, java.lang.Class<? extends Handler> handler)default Chainpatch(java.lang.String path, Handler handler)Adds a handler that delegates to the given handler if the relativepathmatches the givenpathand therequestHTTPMethodisPATCH.default Chainpatch(Handler handler)Adds a handler that delegates to the given handler if therequestHTTPMethodisPATCHand thepathis at the current root.default Chainpath(java.lang.Class<? extends Handler> handler)default Chainpath(java.lang.String path, java.lang.Class<? extends Handler> handler)default Chainpath(java.lang.String path, Handler handler)Adds a handler that delegates to the given handler if the relativepathmatches the givenpathexactly.default Chainpath(Handler handler)default Chainpost(java.lang.Class<? extends Handler> handler)default Chainpost(java.lang.String path, java.lang.Class<? extends Handler> handler)default Chainpost(java.lang.String path, Handler handler)Adds a handler that delegates to the given handler if the relativepathmatches the givenpathand therequestHTTPMethodisPOST.default Chainpost(Handler handler)Adds a handler that delegates to the given handler if therequestHTTPMethodisPOSTand thepathis at the current root.default Chainprefix(java.lang.String prefix, java.lang.Class<? extends Action<? super Chain>> action)default Chainprefix(java.lang.String prefix, Action<? super Chain> action)Adds a handler that delegates to the given handlers if the relative path starts with the givenprefix.default Chainput(java.lang.Class<? extends Handler> handler)default Chainput(java.lang.String path, java.lang.Class<? extends Handler> handler)default Chainput(java.lang.String path, Handler handler)Adds a handler that delegates to the given handler if the relativepathmatches the givenpathand therequestHTTPMethodisPUT.default Chainput(Handler handler)Adds a handler that delegates to the given handler if therequestHTTPMethodisPUTand thepathis at the current root.default Chainredirect(int code, java.lang.String location)Sends an HTTP redirect to the specified location.default Chainregister(Action<? super RegistrySpec> action)Builds a new registry via the given action, then registers it viaregister(Registry).default Chainregister(Action<? super RegistrySpec> registryAction, java.lang.Class<? extends Action<? super Chain>> action)default Chainregister(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 viaContext.insert(ratpack.registry.Registry, Handler...).default Chainregister(Registry registry)Makes the contents of the given registry available for downstream handlers of the same nesting level.default Chainregister(Registry registry, java.lang.Class<? extends Action<? super Chain>> action)default Chainregister(Registry registry, Action<? super Chain> action)Adds a handler that inserts the given handler chain with the given registry viaContext.insert(ratpack.registry.Registry, Handler...).default Chainwhen(boolean test, java.lang.Class<? extends Action<? super Chain>> action)Inlines the given chain iftestistrue.default Chainwhen(boolean test, java.lang.Class<? extends Action<? super Chain>> onTrue, java.lang.Class<? extends Action<? super Chain>> onFalse)Inlines the appropriate chain based on the giventest.default Chainwhen(boolean test, Action<? super Chain> action)Inlines the given chain iftestistrue.default Chainwhen(boolean test, Action<? super Chain> onTrue, Action<? super Chain> onFalse)Inlines the appropriate chain based on the giventest.default Chainwhen(Predicate<? super Context> test, java.lang.Class<? extends Action<? super Chain>> action)default Chainwhen(Predicate<? super Context> test, java.lang.Class<? extends Action<? super Chain>> onTrue, java.lang.Class<? extends Action<? super Chain>> onFalse)default Chainwhen(Predicate<? super Context> test, Action<? super Chain> action)default Chainwhen(Predicate<? super Context> test, Action<? super Chain> onTrue, Action<? super Chain> onFalse)
-
-
-
Method Detail
-
files
default Chain files(Action<? super FileHandlerSpec> config) throws java.lang.Exception
Adds a handler that serves files from the file system.The given action configures how and what files will be served. The handler binds to a
request pathand adirectorywithin the current filesystem binding. The portion of the request path past the path binding identifies the target file within the directory.import ratpack.test.embed.EphemeralBaseDir; import ratpack.test.embed.EmbeddedApp; import static org.junit.Assert.assertEquals; public class Example { public static void main(String... args) throws Exception { EphemeralBaseDir.tmpDir().use(baseDir -> { baseDir.write("public/some.text", "foo"); baseDir.write("public/index.html", "bar"); EmbeddedApp.of(s -> s .serverConfig(c -> c.baseDir(baseDir.getRoot())) .handlers(c -> c .files(f -> f.dir("public").indexFiles("index.html")) ) ).test(httpClient -> { assertEquals("foo", httpClient.getText("some.text")); assertEquals("bar", httpClient.getText()); assertEquals(404, httpClient.get("no-file-here").getStatusCode()); }); }); } }- Parameters:
config- the file handler configuration- Returns:
this- Throws:
java.lang.Exception- any thrown byconfig- See Also:
Handlers.files(ServerConfig, Action),FileHandlerSpec
-
files
default Chain files()
files(Action), using the default config.- Returns:
this
-
chain
default Handler chain(Action<? super Chain> action) throws java.lang.Exception
Constructs a handler using the given action to define a chain.- Parameters:
action- The action that defines the all chain- Returns:
- A all representing the chain
- Throws:
java.lang.Exception- any thrown byaction
-
chain
default Handler chain(java.lang.Class<? extends Action<? super Chain>> action) throws java.lang.Exception
- Throws:
java.lang.Exception
-
delete
default Chain delete(java.lang.String path, Handler handler)
Adds a handler that delegates to the given handler if the relativepathmatches the givenpathand therequestHTTPMethodisDELETE.- Parameters:
path- the relative path to match onhandler- the handler to delegate to- Returns:
- this
- See Also:
get(String, Handler),post(String, Handler),put(String, Handler),patch(String, Handler),path(String, Handler)
-
delete
default Chain delete(Handler handler)
Adds a handler that delegates to the given handler if therequestHTTPMethodisDELETEand thepathis at the current root.- Parameters:
handler- the handler to delegate to- Returns:
- this
- See Also:
get(Handler),post(Handler),put(Handler),patch(Handler)
-
fileSystem
default Chain fileSystem(java.lang.String path, Action<? super Chain> action) throws java.lang.Exception
Adds a handler to this chain that changes theFileSystemBindingfor the given handler chain.- Parameters:
path- the relative path to the new file system binding pointaction- the definition of the all chain- Returns:
- this
- Throws:
java.lang.Exception- any thrown byaction
-
fileSystem
default Chain fileSystem(java.lang.String path, java.lang.Class<? extends Action<? super Chain>> action) throws java.lang.Exception
- Throws:
java.lang.Exception
-
get
default Chain get(java.lang.String path, Handler handler)
Adds a handler that delegates to the given handler if the relativepathmatches the givenpathand therequestHTTPMethodisGET.- Parameters:
path- the relative path to match onhandler- the handler to delegate to- Returns:
- this
- See Also:
post(String, Handler),put(String, Handler),patch(String, Handler),delete(String, Handler),path(String, Handler)
-
get
default Chain get(Handler handler)
Adds a handler that delegates to the given handler if therequestHTTPMethodisGETand thepathis at the current root.- Parameters:
handler- the handler to delegate to- Returns:
- this
- See Also:
post(Handler),put(Handler),patch(Handler),delete(Handler)
-
getServerConfig
ServerConfig getServerConfig()
The server config of the application that this chain is being created for.- Returns:
- The server config of the application that this chain is being created for.
-
getRegistry
Registry getRegistry() throws java.lang.IllegalStateException
The registry that backs this chain.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.- Returns:
- The registry that backs this
- Throws:
java.lang.IllegalStateException- if there is no backing registry for this chain- See Also:
Handlers.chain(ServerConfig, Registry, Action)
-
all
Chain all(Handler handler)
Adds the given handler to this.- Parameters:
handler- the handler to add- Returns:
- this
-
path
default Chain path(java.lang.String path, Handler handler)
Adds a handler that delegates to the given handler if the relativepathmatches the givenpathexactly.Nesting
pathhandlers will not work due to the exact matching, use a combination ofpathandprefixinstead. Seeprefix(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 all 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 howpathis interpreted.- Parameters:
path- the relative path to match exactly onhandler- the handler to delegate to- Returns:
- this
- See Also:
post(String, Handler),get(String, Handler),put(String, Handler),patch(String, Handler),delete(String, Handler)
-
host
default Chain host(java.lang.String hostName, Action<? super Chain> action) throws java.lang.Exception
Adds a handler to the chain that delegates to the given handler chain if the request has aHostheader that matches the given value exactly.chain. host("foo.com", new Action<Chain>() { public void execute(Chain hostChain) { hostChain.all(new Handler() { public void handle(Context context) { context.getResponse().send("Host Handler"); } }); } });- Parameters:
hostName- the name of the HTTP Header to match onaction- the handler chain to delegate to if the host matches- Returns:
- this
- Throws:
java.lang.Exception- any thrown byaction
-
host
default Chain host(java.lang.String hostName, java.lang.Class<? extends Action<? super Chain>> action) throws java.lang.Exception
- Throws:
java.lang.Exception
-
insert
default Chain insert(Action<? super Chain> action) throws java.lang.Exception
Inserts the given nested handler chain.Shorter form of
all(Handler)handler}(chain(action).- Parameters:
action- the handler chain to insert- Returns:
- this
- Throws:
java.lang.Exception- any thrown byaction
-
insert
default Chain insert(java.lang.Class<? extends Action<? super Chain>> action) throws java.lang.Exception
- Throws:
java.lang.Exception
-
patch
default Chain patch(java.lang.String path, Handler handler)
Adds a handler that delegates to the given handler if the relativepathmatches the givenpathand therequestHTTPMethodisPATCH.- Parameters:
path- the relative path to match onhandler- the handler to delegate to- Returns:
- this
- See Also:
get(String, Handler),post(String, Handler),put(String, Handler),delete(String, Handler),path(String, Handler)
-
patch
default Chain patch(Handler handler)
Adds a handler that delegates to the given handler if therequestHTTPMethodisPATCHand thepathis at the current root.- Parameters:
handler- the handler to delegate to- Returns:
- this
- See Also:
get(Handler),post(Handler),put(Handler),delete(Handler)
-
options
default Chain options(java.lang.String path, Handler handler)
Adds a handler that delegates to the given handler if the relativepathmatches the givenpathand therequestHTTPMethodisOPTIONS.- Parameters:
path- the relative path to match onhandler- the handler to delegate to- Returns:
- this
- Since:
- 1.1
- See Also:
get(String, Handler),post(String, Handler),put(String, Handler),delete(String, Handler),path(String, Handler)
-
options
default Chain options(java.lang.String path, java.lang.Class<? extends Handler> handler)
- Parameters:
path- the path to bind tohandler- a handler- Returns:
this- Since:
- 1.1
-
options
default Chain options(Handler handler)
Adds a handler that delegates to the given handler if therequestHTTPMethodisOPTIONSand thepathis at the current root.- Parameters:
handler- the handler to delegate to- Returns:
- this
- Since:
- 1.1
- See Also:
get(Handler),post(Handler),put(Handler),delete(Handler)
-
options
default Chain options(java.lang.Class<? extends Handler> handler)
- Parameters:
handler- a handler- Returns:
- {code this}
- Since:
- 1.1
-
post
default Chain post(java.lang.String path, Handler handler)
Adds a handler that delegates to the given handler if the relativepathmatches the givenpathand therequestHTTPMethodisPOST.- Parameters:
path- the relative path to match onhandler- the handler to delegate to- Returns:
- this
- See Also:
get(String, Handler),put(String, Handler),patch(String, Handler),delete(String, Handler),path(String, Handler)
-
post
default Chain post(Handler handler)
Adds a handler that delegates to the given handler if therequestHTTPMethodisPOSTand thepathis at the current root.- Parameters:
handler- the handler to delegate to- Returns:
- this
- See Also:
get(Handler),put(Handler),patch(Handler),delete(Handler)
-
prefix
default Chain prefix(java.lang.String prefix, Action<? super Chain> action) throws java.lang.Exception
Adds a handler that delegates to the given handlers if the relative path starts with the givenprefix.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 theprefixstring.- Parameters:
prefix- the relative path to match onaction- the handler chain to delegate to if the prefix matches- Returns:
- this
- Throws:
java.lang.Exception- any thrown byaction
-
prefix
default Chain prefix(java.lang.String prefix, java.lang.Class<? extends Action<? super Chain>> action) throws java.lang.Exception
- Throws:
java.lang.Exception
-
put
default Chain put(java.lang.String path, Handler handler)
Adds a handler that delegates to the given handler if the relativepathmatches the givenpathand therequestHTTPMethodisPUT.- Parameters:
path- the relative path to match onhandler- the handler to delegate to- Returns:
- this
- See Also:
get(String, Handler),post(String, Handler),patch(String, Handler),delete(String, Handler),path(String, Handler)
-
put
default Chain put(Handler handler)
Adds a handler that delegates to the given handler if therequestHTTPMethodisPUTand thepathis at the current root.- Parameters:
handler- the handler to delegate to- Returns:
- this
- See Also:
get(Handler),post(Handler),patch(Handler),delete(Handler)
-
redirect
default Chain redirect(int code, java.lang.String location)
Sends an HTTP redirect to the specified location.The handler to add is created via
Handlers.redirect(int, String).- Parameters:
code- the 3XX HTTP status code.location- the URL to set in the Location response header- Returns:
- this
- See Also:
Handlers.redirect(int, String)
-
register
default Chain register(Registry registry)
Makes the contents of the given registry available for downstream handlers of the same nesting level.The registry is inserted via the
Context.next(Registry)method.- Parameters:
registry- the registry whose contents should be made available to downstream handlers- Returns:
- this
-
register
default Chain register(Action<? super RegistrySpec> action) throws java.lang.Exception
Builds a new registry via the given action, then registers it viaregister(Registry).- Parameters:
action- the definition of a registry- Returns:
- this
- Throws:
java.lang.Exception- any thrown byaction
-
register
default Chain register(Registry registry, Action<? super Chain> action) throws java.lang.Exception
Adds a handler that inserts the given handler chain with the given registry viaContext.insert(ratpack.registry.Registry, Handler...).- Parameters:
registry- the registry to insertaction- the definition of the handler chain- Returns:
- this
- Throws:
java.lang.Exception- any thrown byaction
-
register
default Chain register(Registry registry, java.lang.Class<? extends Action<? super Chain>> action) throws java.lang.Exception
- Throws:
java.lang.Exception
-
register
default Chain register(Action<? super RegistrySpec> registryAction, Action<? super Chain> action) throws java.lang.Exception
Adds a handler that inserts the given handler chain with a registry built by the given action viaContext.insert(ratpack.registry.Registry, Handler...).- Parameters:
registryAction- the definition of the registry to insert]action- the definition of the handler chain- Returns:
- this
- Throws:
java.lang.Exception- any thrown byaction
-
register
default Chain register(Action<? super RegistrySpec> registryAction, java.lang.Class<? extends Action<? super Chain>> action) throws java.lang.Exception
- Throws:
java.lang.Exception
-
when
default Chain when(Predicate<? super Context> test, Action<? super Chain> action) throws java.lang.Exception
- Throws:
java.lang.Exception
-
when
default Chain when(Predicate<? super Context> test, java.lang.Class<? extends Action<? super Chain>> action) throws java.lang.Exception
- Throws:
java.lang.Exception
-
when
default Chain when(boolean test, Action<? super Chain> action) throws java.lang.Exception
Inlines the given chain iftestistrue.This is literally just sugar for wrapping the given action in an
ifstatement. It can be useful when conditionally adding handlers based on state available when building the chain.import ratpack.test.embed.EmbeddedApp; import static org.junit.Assert.assertEquals; public class Example { public static void main(String... args) throws Exception { EmbeddedApp.of(a -> a .registryOf(r -> r.add(1)) .handlers(c -> c .when(c.getRegistry().get(Integer.class) == 0, i -> i .get(ctx -> ctx.render("ok")) ) ) ).test(httpClient -> assertEquals(httpClient.get().getStatusCode(), 404) ); EmbeddedApp.of(a -> a .registryOf(r -> r.add(0)) .handlers(c -> c .when(c.getRegistry().get(Integer.class) == 0, i -> i .get(ctx -> ctx.render("ok")) ) ) ).test(httpClient -> assertEquals(httpClient.getText(), "ok") ); } }- Parameters:
test- whether to include the given chain actionaction- the chain action to maybe include- Returns:
- this
- Throws:
java.lang.Exception- any thrown byaction- Since:
- 1.4
-
when
default Chain when(boolean test, java.lang.Class<? extends Action<? super Chain>> action) throws java.lang.Exception
Inlines the given chain iftestistrue.Similar to
when(boolean, Action), except obtains the action instance from the registry by the given type.- Parameters:
test- whether to include the given chain actionaction- the chain action to maybe include- Returns:
- this
- Throws:
java.lang.Exception- any thrown byaction- Since:
- 1.4
-
when
default Chain when(Predicate<? super Context> test, Action<? super Chain> onTrue, Action<? super Chain> onFalse) throws java.lang.Exception
- Throws:
java.lang.Exception
-
when
default Chain when(Predicate<? super Context> test, java.lang.Class<? extends Action<? super Chain>> onTrue, java.lang.Class<? extends Action<? super Chain>> onFalse) throws java.lang.Exception
- Throws:
java.lang.Exception
-
when
default Chain when(boolean test, Action<? super Chain> onTrue, Action<? super Chain> onFalse) throws java.lang.Exception
Inlines the appropriate chain based on the giventest.This is literally just sugar for wrapping the given action in an
if/elsestatement. It can be useful when conditionally adding handlers based on state available when building the chain.import ratpack.test.embed.EmbeddedApp; import static org.junit.Assert.assertEquals; public class Example { public static void main(String... args) throws Exception { EmbeddedApp.of(a -> a .registryOf(r -> r.add(1)) .handlers(c -> c .when(c.getRegistry().get(Integer.class) == 0, i -> i.get(ctx -> ctx.render("ok")), i -> i.get(ctx -> ctx.render("ko")) ) ) ).test(httpClient -> assertEquals(httpClient.getText(), "ko") ); EmbeddedApp.of(a -> a .registryOf(r -> r.add(0)) .handlers(c -> c .when(c.getRegistry().get(Integer.class) == 0, i -> i.get(ctx -> ctx.render("ok")), i -> i.get(ctx -> ctx.render("ko")) ) ) ).test(httpClient -> assertEquals(httpClient.getText(), "ok") ); } }- Parameters:
test- predicate to decide which action includeonTrue- the chain action to include when the predicate is trueonFalse- the chain action to include when the predicate is false- Returns:
- this
- Throws:
java.lang.Exception- any thrown byaction- Since:
- 1.5
-
when
default Chain when(boolean test, java.lang.Class<? extends Action<? super Chain>> onTrue, java.lang.Class<? extends Action<? super Chain>> onFalse) throws java.lang.Exception
Inlines the appropriate chain based on the giventest.Similar to
when(boolean, Action, Action), except obtains the action instance from the registry by the given type.- Parameters:
test- predicate to decide which action to includeonTrue- the chain action to include when the predicate is trueonFalse- the chain action to include when the predicate is false- Returns:
- this
- Throws:
java.lang.Exception- any thrown byaction- Since:
- 1.5
-
onlyIf
default Chain onlyIf(Predicate<? super Context> test, Handler handler)
Invokes the given handler only if the predicate passes.This method differs from
when()in that it does not insert the handler; but directly calls itsHandler.handle(Context)method.- Parameters:
test- the predicatehandler- the handler- Returns:
this
-
onlyIf
default Chain onlyIf(Predicate<? super Context> test, java.lang.Class<? extends Handler> handler)
-
notFound
default Chain notFound()
Raises a 404Context.clientError(int).This can be used to effectively terminate processing early. This is sometimes useful when using a scoped client error handler.
import ratpack.error.ClientErrorHandler; import ratpack.test.embed.EmbeddedApp; import static org.junit.Assert.assertEquals; public class Example { public static void main(String... args) throws Exception { EmbeddedApp.of(s -> s .registryOf(r -> r .add(ClientErrorHandler.class, (ctx, code) -> ctx.render("global")) ) .handlers(c -> c .prefix("api", api -> api .register(r -> r.add(ClientErrorHandler.class, (ctx, code) -> ctx.render("scoped"))) .get("foo", ctx -> ctx.render("foo")) .notFound() ) ) ).test(http -> { assertEquals(http.getText("not-there"), "global"); assertEquals(http.getText("api/foo"), "foo"); assertEquals(http.getText("api/not-there"), "scoped"); }); } }- Returns:
this- Since:
- 1.1
-
-