public interface Context extends ExecControl, 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 |
addInterceptor(ExecInterceptor execInterceptor,
Block continuation)
Adds an interceptor that wraps the rest of the current execution segment and all future segments of this execution.
|
<T> Promise<T> |
blocking(Callable<T> blockingOperation)
Executes a blocking operation, returning a promise for its result.
|
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 . |
ExecBuilder |
fork()
Forks a new execution, detached from the current.
|
PathTokens |
getAllPathTokens()
The contextual path tokens of the current
PathBinding . |
Context |
getContext()
Returns this.
|
ExecController |
getController() |
DirectChannelAccess |
getDirectChannelAccess()
Provides direct access to the backing Netty channel.
|
Execution |
getExecution()
The execution of handling this request.
|
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> 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> T |
parse(Class<T> type,
O options)
Constructs a
Parse from the given args and delegates to parse(Parse) . |
<T,O> T |
parse(Parse<T,O> parse)
Parses the request body into an object.
|
<T> 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> T |
parse(TypeToken<T> type,
O options)
Constructs a
Parse from the given args and delegates to parse(Parse) . |
<T> Promise<T> |
promise(Action<? super Fulfiller<T>> action)
Creates a promise of a value that will made available asynchronously.
|
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.
|
<T> TransformablePublisher<T> |
stream(Publisher<T> publisher)
Process streams of data asynchronously with non-blocking back pressure.
|
blockingOperation, current, execControl, failedPromise, nest, nest, operation, promiseFrom, promiseOf, wrap
Context getContext()
Execution getExecution()
getExecution
in interface ExecControl
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.Registries;
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
.handler(ctx -> ctx.next(Registries.just("foo")))
.handler(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
.handler("a", ctx -> {
String val = "a";
ctx.byMethod(m -> m
.get(() -> ctx.render(val + " - " + "GET"))
.post(() -> ctx.render(val + " - " + "POST"))
);
})
.handler("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<T> Promise<T> blocking(Callable<T> blockingOperation)
This method executes asynchronously, in that it does not invoke the operation
before returning the promise.
When the returned promise is subscribed to (i.e. its Promise.then(Action)
method is called),
the given operation
will be submitted to a thread pool that is different to the request handling thread pool.
Therefore, if the returned promise is never subscribed to, the operation
will never be initiated.
The promise returned by this method, has the same default error handling strategy as those returned by ExecControl.promise(ratpack.func.Action)
.
import ratpack.test.embed.EmbeddedApp;
import static org.junit.Assert.assertEquals;
public class Example {
public static void main(String... args) throws Exception {
EmbeddedApp.fromHandler(ctx ->
ctx.blocking(() ->
// ok to perform blocking operations in here
"hello world"
).then(ctx::render)
).test(httpClient -> {
assertEquals("hello world", httpClient.getText());
});
}
}
blocking
in interface ExecControl
T
- The type of result object that the operation producesblockingOperation
- The operation to perform<T> Promise<T> promise(Action<? super Fulfiller<T>> action)
The action
given to this method receives a Fulfiller
, which can be used to fulfill the promise at any time in the future.
The action
is not required to fulfill the promise during the execution of the execute()
method (i.e. it can be asynchronous).
The action
MUST call one of the fulfillment methods.
Otherwise, the promise will go unfulfilled.
There is no time limit or timeout on fulfillment.
The promise returned has a default error handling strategy of forwarding exceptions to error(Throwable)
of this context.
To use a different error strategy, supply it to the Promise.onError(Action)
method.
The promise will always be fulfilled on a thread managed by Ratpack.
import ratpack.test.embed.EmbeddedApp;
import static org.junit.Assert.assertEquals;
public class Example {
public static void main(String... args) throws Exception {
EmbeddedApp.fromHandler(ctx ->
ctx.promise((f) ->
new Thread(() -> f.success("hello world")).start()
).then(ctx::render)
).test(httpClient -> {
assertEquals("hello world", httpClient.getText());
});
}
}
promise
in interface ExecControl
T
- the type of promised valueaction
- the initiation of the asynchronous actionFulfiller
,
Fulfillment
ExecBuilder fork()
This can be used to launch a one time background job during request processing. The forked execution does not inherit anything from the current execution.
Forked executions MUST NOT write to the response or participate in the handler pipeline at all.
That is, they should not call methods like next()
or insert(Handler...)
.
When using forking to process work in parallel, use ExecControl.promise(ratpack.func.Action)
to continue request handling when the parallel work is done.
import ratpack.handling.Handler;
import ratpack.handling.Context;
import ratpack.func.Action;
import ratpack.exec.Fulfiller;
import java.util.Collections;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import ratpack.test.handling.HandlingResult;
import ratpack.test.handling.RequestFixture;
import static org.junit.Assert.assertEquals;
public class Example {
public static class ForkingHandler implements Handler {
public void handle(Context context) {
final int numJobs = 3;
final Integer failOnIteration = context.getPathTokens().asInt("failOn");
context.promise(new Action<Fulfiller<Integer>>() {
private final AtomicInteger counter = new AtomicInteger();
private final AtomicReference<Throwable> error = new AtomicReference<>();
private void completeJob(Fulfiller<Integer> fulfiller) {
if (counter.incrementAndGet() == numJobs) {
Throwable throwable = error.get();
if (throwable == null) {
fulfiller.success(numJobs);
} else {
fulfiller.error(throwable);
}
}
}
public void execute(Fulfiller<Integer> fulfiller) {
for (int i = 0; i < numJobs; ++i) {
final int iteration = i;
context.fork()
.onError(throwable -> {
error.compareAndSet(null, throwable); // just take the first error
completeJob(fulfiller);
})
.start(execution -> {
if (failOnIteration != null && failOnIteration == iteration) {
throw new Exception("bang!");
} else {
completeJob(fulfiller);
}
});
}
}
})
.then(i -> context.render(i.toString()));
}
}
public static void main(String[] args) throws Exception {
HandlingResult result = RequestFixture.handle(new ForkingHandler(), Action.noop());
assertEquals("3", result.rendered(String.class));
result = RequestFixture.handle(new ForkingHandler(), new Action<RequestFixture>() {
public void execute(RequestFixture fixture) {
fixture.pathBinding(Collections.singletonMap("failOn", "2"));
}
});
assertEquals("bang!", result.exception(Exception.class).getMessage());
}
}
fork
in interface ExecControl
ExecController getController()
getController
in interface ExecControl
void addInterceptor(ExecInterceptor execInterceptor, Block continuation) throws Exception
ExecControl
The given action is executed immediately (i.e. as opposed to being queued to be executed as the next execution segment). Any code executed after a call to this method in the same execution segment WILL NOT be intercepted. Therefore, it is advisable to not execute any code after calling this method in a given execution segment.
See ExecInterceptor
for example use of an interceptor.
addInterceptor
in interface ExecControl
execInterceptor
- the execution interceptor to addcontinuation
- the rest of the code to be executedException
- any thrown by continuation
ExecInterceptor
<T> TransformablePublisher<T> stream(Publisher<T> publisher)
ExecControl
This method allows the processing of elements (onNext) or termination signals (onError, onComplete) to happen outside of the execution stack of the Publisher. In other words these "events" are executed asynchronously, on a Ratpack managed thread, without blocking the Publisher.
stream
in interface ExecControl
T
- the type of streamed elementspublisher
- the provider of a potentially unbounded number of sequenced elements, publishing them according to the demand
received from its Subscriber(s)@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(ExecControl, 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> T parse(Class<T> type) throws Exception
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) { Form form = context.parse(Form.class); 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 toException
- any thrown by the eventual parser implementation<T> T parse(TypeToken<T> type) throws Exception
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) { Form form = context.parse(new TypeToken<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 toException
- any thrown by the eventual parser implementation<T,O> T parse(Class<T> type, O options) throws Exception
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 optionsException
- any thrown by the eventual parser implementation<T,O> T parse(TypeToken<T> type, O options) throws Exception
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 optionsException
- any thrown by the eventual parser implementation<T,O> T parse(Parse<T,O> parse) throws Exception
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) { Form form = context.parse(Parse.of(Form.class)); 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 requestException
- any thrown by the eventual parser implementationparse(Class)
,
parse(Class, Object)
,
Parser
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 service