public interface Context extends Registry
Handler
invocation.
It provides:
request
and response
next()
and insert(ratpack.handling.Handler...)
family of methods)
A context is also a Registry
of objects.
Arbitrary objects can be "pushed" into the context for use by downstream handlers.
There are some significant contextual objects that drive key infrastructure.
For example, error handling is based on informing the contextual ServerErrorHandler
of exceptions.
The error handling strategy for an application can be changed by pushing a new implementation of this interface into the context that is used downstream.
See insert(Handler...)
for more on how to do this.
There is also a set of default objects that are made available via the Ratpack infrastructure:
FileSystemBinding
that is the application ServerConfig.getBaseDir()
MimeTypes
implementationServerErrorHandler
ClientErrorHandler
PublicAddress
Redirector
Modifier and Type | Method and Description |
---|---|
void |
byContent(Action<? super ByContentSpec> action)
Respond to the request based on the requested content type (i.e.
|
void |
byMethod(Action<? super ByMethodSpec> action)
Respond to the request based on the request method.
|
void |
clientError(int statusCode)
Forwards the error to the
ClientErrorHandler in this service. |
void |
error(Throwable throwable)
Forwards the exception to the
ServerErrorHandler in this service. |
Path |
file(String path)
Gets the file relative to the contextual
FileSystemBinding . |
PathTokens |
getAllPathTokens()
The contextual path tokens of the current
PathBinding . |
Context |
getContext()
Returns this.
|
DirectChannelAccess |
getDirectChannelAccess()
Provides direct access to the backing Netty channel.
|
Execution |
getExecution()
The execution of handling this request.
|
default FileSystemBinding |
getFileSystemBinding() |
PathTokens |
getPathTokens()
The contextual path tokens of the current
PathBinding . |
Request |
getRequest()
The HTTP request.
|
Response |
getResponse()
The HTTP response.
|
ServerConfig |
getServerConfig()
The server configuration for the application.
|
void |
insert(Handler... handlers)
Inserts some handlers into the pipeline, then delegates to the first.
|
void |
insert(Registry registry,
Handler... handlers)
Inserts some handlers into the pipeline to execute with the given registry, then delegates to the first.
|
void |
lastModified(Date date,
Runnable runnable)
Convenience method for handling last-modified based HTTP caching.
|
void |
next()
Delegate handling to the next handler in line.
|
void |
next(Registry registry)
Invokes the next handler, after adding the given registry.
|
void |
onClose(Action<? super RequestOutcome> onClose)
Registers a callback to be notified when the request for this context is “closed” (i.e.
|
<T> Promise<T> |
parse(Class<T> type)
Parse the request into the given type, using no options (or more specifically an instance of
NullParseOpts as the options). |
<T,O> Promise<T> |
parse(Class<T> type,
O options)
Constructs a
Parse from the given args and delegates to parse(Parse) . |
<T,O> Promise<T> |
parse(Parse<T,O> parse)
Parses the request body into an object.
|
<T,O> T |
parse(TypedData body,
Parse<T,O> parse)
Parses the provided request body into an object.
|
<T> Promise<T> |
parse(TypeToken<T> type)
Parse the request into the given type, using no options (or more specifically an instance of
NullParseOpts as the options). |
<T,O> Promise<T> |
parse(TypeToken<T> type,
O options)
Constructs a
Parse from the given args and delegates to parse(Parse) . |
void |
redirect(int code,
String location)
Sends a redirect response location URL and status code (which should be in the 3xx range).
|
void |
redirect(String location)
Sends a temporary redirect response (i.e.
|
void |
render(Object object)
Render the given object, using the rendering framework.
|
Context getContext()
Execution getExecution()
ServerConfig getServerConfig()
Request getRequest()
Response getResponse()
@NonBlocking void next()
The request and response of this object should not be accessed after this method is called.
@NonBlocking void next(Registry registry)
The given registry is appended to the existing. This means that it can shadow objects previously available.
import ratpack.registry.Registry;
import ratpack.test.embed.EmbeddedApp;
import static org.junit.Assert.assertEquals;
public class Example {
public static void main(String... args) throws Exception {
EmbeddedApp.fromHandlers(chain -> chain
.all(ctx -> ctx.next(Registry.single("foo")))
.all(ctx -> ctx.render(ctx.get(String.class)))
).test(httpClient -> {
assertEquals("foo", httpClient.getText());
});
}
}
registry
- The registry to make available for subsequent handlers.@NonBlocking void insert(Handler... handlers)
The request and response of this object should not be accessed after this method is called.
handlers
- The handlers to insert.@NonBlocking void insert(Registry registry, Handler... handlers)
The given registry is only applicable to the inserted handlers.
Almost always, the registry should be a super set of the current registry.
handlers
- The handlers to insertregistry
- The registry for the inserted handlers@NonBlocking void byMethod(Action<? super ByMethodSpec> action) throws Exception
import ratpack.test.embed.EmbeddedApp;
import static org.junit.Assert.*;
public class Example {
public static void main(String[] args) throws Exception {
EmbeddedApp.fromHandlers(chain -> chain
.path("a", ctx -> {
String val = "a";
ctx.byMethod(m -> m
.get(() -> ctx.render(val + " - " + "GET"))
.post(() -> ctx.render(val + " - " + "POST"))
);
})
.path("b", ctx -> {
String val = "b";
ctx.byMethod(m -> m
.get(() -> ctx.render(val + " - " + "GET"))
.post(() -> ctx.render(val + " - " + "POST"))
);
})
).test(httpClient -> {
assertEquals("a - GET", httpClient.getText("a"));
assertEquals("a - POST", httpClient.postText("a"));
assertEquals("b - GET", httpClient.getText("b"));
assertEquals("b - POST", httpClient.postText("b"));
});
}
}
Only the last added handler for a method will be used. Adding a subsequent handler for the same method will replace the previous.
If no handler has been registered for the actual request method, a 405
will be issued by clientError(int)
.
If the handler only needs to respond to one HTTP method it can be more convenient to use Chain.get(Handler)
and friends.
action
- the specification of how to handle the request based on the request methodException
- any thrown by actionvoid byContent(Action<? super ByContentSpec> action) throws Exception
This is useful when a given handler can provide content of more than one type (i.e. content negotiation).
The handler to use will be selected based on parsing the "Accept" header, respecting quality weighting and wildcard matching. The order that types are specified is significant for wildcard matching. The earliest registered type that matches the wildcard will be used.
import ratpack.test.embed.EmbeddedApp;
import ratpack.http.client.ReceivedResponse;
import static org.junit.Assert.*;
public class Example {
public static void main(String[] args) throws Exception {
EmbeddedApp.fromHandler(ctx -> {
String message = "hello!";
ctx.byContent(m -> m
.json(() -> ctx.render("{\"msg\": \"" + message + "\"}"))
.html(() -> ctx.render("<p>" + message + "</p>"))
);
}).test(httpClient -> {
ReceivedResponse response = httpClient.requestSpec(s -> s.getHeaders().add("Accept", "application/json")).get();
assertEquals("{\"msg\": \"hello!\"}", response.getBody().getText());
assertEquals("application/json", response.getBody().getContentType().getType());
response = httpClient.requestSpec(s -> s.getHeaders().add("Accept", "text/plain; q=1.0, text/html; q=0.8, application/json; q=0.7")).get();
assertEquals("<p>hello!</p>", response.getBody().getText());
assertEquals("text/html", response.getBody().getContentType().getType());
});
}
}
If there is no type registered, or if the client does not accept any of the given types, by default a 406
will be issued with clientError(int)
.
If you want a different behavior, use ByContentSpec.noMatch(ratpack.func.Block)
.
Only the last specified handler for a type will be used. That is, adding a subsequent handler for the same type will replace the previous.
action
- the specification of how to handle the request based on the clients preference of content typeException
- any thrown by action@NonBlocking void error(Throwable throwable)
ServerErrorHandler
in this service.
The default configuration of Ratpack includes a ServerErrorHandler
in all contexts.
A NotInRegistryException
will only be thrown if a very custom service setup is being used.
throwable
- The exception that occurredNotInRegistryException
- if no ServerErrorHandler
can be found in the service@NonBlocking void clientError(int statusCode) throws NotInRegistryException
ClientErrorHandler
in this service.
The default configuration of Ratpack includes a ClientErrorHandler
in all contexts.
A NotInRegistryException
will only be thrown if a very custom service setup is being used.statusCode
- The 4xx range status code that indicates the error typeNotInRegistryException
- if no ClientErrorHandler
can be found in the service@NonBlocking void render(Object object) throws NoSuchRendererException
The first Renderer
, that is able to render the given object will be delegated to.
If the given argument is null
, this method will have the same effect as clientError(404)
.
If no renderer can be found for the given type, a NoSuchRendererException
will be given to error(Throwable)
.
If a renderer throws an exception during its execution it will be wrapped in a RendererException
and given to error(Throwable)
.
Ratpack has built in support for rendering the following types:
Path
CharSequence
Promise
(renders the promised value, using this render()
method)Publisher
(converts the publisher to a promise using Streams.toPromise(Publisher)
and renders it)
See Renderer
for more on how to contribute to the rendering framework.
The object-to-render will be decorated by all registered RenderableDecorator
whose type is exactly equal to the type of the object-to-render, before being passed to the selected renderer.
object
- The object-to-renderNoSuchRendererException
- if no suitable renderer can be foundvoid redirect(String location) throws NotInRegistryException
location
- the redirect location URLNotInRegistryException
- if there is no Redirector
in the current service but one is provided by defaultvoid redirect(int code, String location) throws NotInRegistryException
code
- The status code of the redirectlocation
- the redirect location URLNotInRegistryException
- if there is no Redirector
in the current service but one is provided by default@NonBlocking void lastModified(Date date, Runnable runnable)
The given date is the "last modified" value of the response. If the client sent an "If-Modified-Since" header that is of equal or greater value than date, a 304 will be returned to the client. Otherwise, the given runnable will be executed (it should send a response) and the "Last-Modified" header will be set by this method.
date
- The effective last modified date of the responserunnable
- The response sending action if the response needs to be sent<T> Promise<T> parse(Class<T> type)
NullParseOpts
as the options).
The code sample is functionally identical to the sample given for the parse(Parse)
variant…
import ratpack.handling.Handler;
import ratpack.handling.Context;
import ratpack.form.Form;
public class FormHandler implements Handler {
public void handle(Context context) {
context.parse(Form.class).then(form -> context.render(form.get("someFormParam")));
}
}
That is, it is a convenient form of parse(Parse.of(T))
.
T
- the type to parse totype
- the type to parse to<T> Promise<T> parse(TypeToken<T> type)
NullParseOpts
as the options).
The code sample is functionally identical to the sample given for the parse(Parse)
variant…
import ratpack.handling.Handler;
import ratpack.handling.Context;
import ratpack.form.Form;
import com.google.common.reflect.TypeToken;
public class FormHandler implements Handler {
public void handle(Context context) {
context.parse(new TypeToken<Form>() {}).then(form -> context.render(form.get("someFormParam")));
}
}
That is, it is a convenient form of parse(Parse.of(T))
.
T
- the type to parse totype
- the type to parse to<T,O> Promise<T> parse(Class<T> type, O options)
Parse
from the given args and delegates to parse(Parse)
.T
- The type to parse toO
- The type of the parse optstype
- The type to parse tooptions
- The parse options<T,O> Promise<T> parse(TypeToken<T> type, O options)
Parse
from the given args and delegates to parse(Parse)
.T
- The type to parse toO
- The type of the parse optstype
- The type to parse tooptions
- The parse options<T,O> Promise<T> parse(Parse<T,O> parse)
How to parse the request is determined by the given Parse
object.
Parser resolution happens as follows:
parsers
are retrieved from the context registry (i.e. getAll(Parser.class)
);getAll()
) for compatibility with the current request content type and options type;Parser.parse(Context, ratpack.http.TypedData, Parse)
method is called;null
the next parser will be tried, if it returns a value it will be returned by this method;NoSuchParserException
will be thrown.A parser is compatible if all of the following hold true:
Parser.getContentType()
is exactly equal to getRequest().getBody().getContentType().getType()
parse
object is an instanceof
its Parser.getOptsType()
()}Parser.parse(Context, ratpack.http.TypedData, Parse)
method returns a non null value.
If the request has no declared content type, text/plain
will be assumed.
Ratpack core provides implicit no opt parsers
for the following types and content types:
Form
import ratpack.handling.Handler;
import ratpack.handling.Context;
import ratpack.form.Form;
import ratpack.parse.Parse;
import ratpack.parse.NullParseOpts;
public class FormHandler implements Handler {
public void handle(Context context) {
context.parse(Parse.of(Form.class)).then(form -> context.render(form.get("someFormParam")));
}
}
T
- The type of object the request is parsed intoO
- the type of the parse options objectparse
- The specification of how to parse the requestparse(Class)
,
parse(Class, Object)
,
Parser
<T,O> T parse(TypedData body, Parse<T,O> parse)
This variant can be used when a reference to the request body has already been obtained.
For example, this can be used during the implementation of a Parser
that needs to delegate to another parser.
From within a handler, it is more common to use parse(Parse)
or similar.
T
- The type of object the request is parsed intoO
- The type of the parse options objectbody
- The request bodyparse
- The specification of how to parse the requestparse(Parse)
DirectChannelAccess getDirectChannelAccess()
General only useful for low level extensions. Avoid if possible.
PathTokens getPathTokens() throws NotInRegistryException
PathBinding
.
Shorthand for get(PathBinding.class).getPathTokens()
.
PathBinding
.NotInRegistryException
- if there is no PathBinding
in the current servicePathTokens getAllPathTokens() throws NotInRegistryException
PathBinding
.
Shorthand for get(PathBinding.class).getAllPathTokens()
.
PathBinding
.NotInRegistryException
- if there is no PathBinding
in the current servicevoid onClose(Action<? super RequestOutcome> onClose)
onClose
- A notification callbackPath file(String path) throws NotInRegistryException
FileSystemBinding
.
Shorthand for get(FileSystemBinding.class).file(path)
.
The default configuration of Ratpack includes a FileSystemBinding
in all contexts.
A NotInRegistryException
will only be thrown if a very custom service setup is being used.
path
- The path to pass to the FileSystemBinding.file(String)
method.FileSystemBinding
NotInRegistryException
- if there is no FileSystemBinding
in the current servicedefault FileSystemBinding getFileSystemBinding() throws NotInRegistryException
NotInRegistryException