public interface Context extends ExecContext, 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:
LaunchConfig
FileSystemBinding
that is the application LaunchConfig.getBaseDir()
MimeTypes
implementationServerErrorHandler
ClientErrorHandler
FileRenderer
BindAddress
PublicAddress
Redirector
ExecContext.Supplier
Modifier and Type | Method and Description |
---|---|
void |
addExecInterceptor(ExecInterceptor execInterceptor,
Action<? super Context> action) |
<T> Promise<T> |
blocking(Callable<T> blockingOperation)
Executes a blocking operation, returning a promise for its result.
|
void |
clientError(int statusCode)
Forwards the error to the
ClientErrorHandler in this service. |
void |
error(Exception exception)
Forwards the exception to the
ServerErrorHandler in this service. |
Path |
file(String path)
Gets the file relative to the contextual
FileSystemBinding . |
<O> O |
get(Class<O> type)
Provides an object of the specified type, or throws an exception if no object of that type is available.
|
<O> O |
get(com.google.common.reflect.TypeToken<O> type)
Provides an object of the specified type, or throws an exception if no object of that type is available.
|
<O> List<O> |
getAll(Class<O> type)
Returns all of the objects whose declared type is assignment compatible with the given type.
|
<O> List<O> |
getAll(com.google.common.reflect.TypeToken<O> type)
Returns all of the objects whose declared type is assignment compatible with the given type.
|
PathTokens |
getAllPathTokens()
The contextual path tokens of the current
PathBinding . |
BindAddress |
getBindAddress()
The address that this request was received on.
|
ByContentHandler |
getByContent()
A buildable handler useful for performing content negotiation.
|
ByMethodHandler |
getByMethod()
A buildable handler for conditional processing based on the HTTP request method.
|
Context |
getContext()
Returns this.
|
DirectChannelAccess |
getDirectChannelAccess()
Provides direct access to the backing Netty channel.
|
ExecController |
getExecController()
The execution controller.
|
HttpClient |
getHttpClient() |
List<ExecInterceptor> |
getInterceptors()
The execution interceptors.
|
LaunchConfig |
getLaunchConfig()
The application launch config.
|
PathTokens |
getPathTokens()
The contextual path tokens of the current
PathBinding . |
Request |
getRequest()
The HTTP request.
|
Response |
getResponse()
The HTTP response.
|
ExecContext.Supplier |
getSupplier()
The supplier of the effective context for the current execution.
|
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.
|
<O> O |
maybeGet(Class<O> type)
Does the same thing as
Registry.get(Class) , except returns null instead of throwing an exception. |
<O> O |
maybeGet(com.google.common.reflect.TypeToken<O> type)
Does the same thing as
Registry.get(Class) , except returns null instead of throwing an exception. |
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> 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.
|
void |
respond(Handler handler)
Convenience method for delegating to a single handler.
|
Context getContext()
getContext
in interface ExecContext
ExecContext.Supplier getSupplier()
getSupplier
in interface ExecContext
ExecContext.Supplier
LaunchConfig getLaunchConfig()
ExecContext
getLaunchConfig
in interface ExecContext
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.handling.Handler; import ratpack.handling.Handlers; import ratpack.handling.Chain; import ratpack.handling.ChainAction; import ratpack.handling.Context; import ratpack.launch.HandlerFactory; import ratpack.launch.LaunchConfig; import ratpack.launch.LaunchConfigBuilder; import ratpack.func.Factory; import static ratpack.registry.Registries.just; public interface SomeThing {} public class SomeThingImpl implements SomeThing {} public class UpstreamHandler implements Handler { public void handle(Context context) { context.next(just(SomeThing.class, new SomeThingImpl())); } } public class DownstreamHandler implements Handler { public void handle(Context context) { SomeThing someThing = context.get(SomeThing.class); // instance provided upstream assert someThing instanceof SomeThingImpl; // … } } LaunchConfigBuilder.baseDir(new File("base")).build(new HandlerFactory() { public Handler create(LaunchConfig launchConfig) { return Handlers.chain(launchConfig, new ChainAction() { protected void execute() { handler(new UpstreamHandler()); handler(new DownstreamHandler()); } }); } });
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 respond(Handler handler)
Designed to be used in conjunction with the getByMethod()
and getByContent()
methods.
handler
- The handler to invokeByContentHandler
,
ByMethodHandler
ByMethodHandler getByMethod()
ByContentHandler getByContent()
@NonBlocking void error(Exception exception)
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.
error
in interface ExecContext
exception
- 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 SuccessPromise.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 promise(Action)
.
import ratpack.handling.*; import ratpack.func.Action; import java.util.concurrent.Callable; public class BlockingJavaHandler implements Handler { void handle(final Context context) { context.blocking(new Callable<String>() { public String call() { // perform some kind of blocking IO in here, such as accessing a database return "hello world!"; } }).then(new Action<String>() { public void execute(String result) { context.render(result); } }); } } public class BlockingGroovyHandler implements Handler { void handle(final Context context) { context.blocking { "hello world!" } then { String result -> context.render(result) } } } // Test (Groovy) … import static ratpack.groovy.test.TestHttpClients.testHttpClient import static ratpack.groovy.test.embed.EmbeddedApplications.embeddedApp def app = embeddedApp { handlers { get("java", new BlockingJavaHandler()) get("groovy", new BlockingGroovyHandler()) } } def client = testHttpClient(app) assert client.getText("java") == "hello world!" assert client.getText("groovy") == "hello world!" app.close()
blocking
in interface ExecContext
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(Exception)
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.handling.*; import ratpack.exec.Fulfiller; import ratpack.func.Action; public class PromiseUsingJavaHandler implements Handler { public void handle(final Context context) { context.promise(new Action<Fulfiller<String>>() { public void execute(final Fulfiller<String> fulfiller) { new Thread(new Runnable() { public void run() { fulfiller.success("hello world!"); } }).start(); } }).then(new Action<String>() { public void execute(String string) { context.render(string); } }); } } class PromiseUsingGroovyHandler implements Handler { void handle(Context context) { context.promise { Fulfiller<String> fulfiller -> Thread.start { fulfiller.success("hello world!") } } then { String string -> context.render(string) } } } // Test (Groovy) … import static ratpack.groovy.test.TestHttpClients.testHttpClient import static ratpack.groovy.test.embed.EmbeddedApplications.embeddedApp def app = embeddedApp { handlers { get("java", new PromiseUsingJavaHandler()) get("groovy", new PromiseUsingGroovyHandler()) } } def client = testHttpClient(app) assert client.getText("java") == "hello world!" assert client.getText("groovy") == "hello world!" app.close()
promise
in interface ExecContext
promise
in interface ExecControl
T
- the type of value promisedaction
- an action that invokes an asynchronous API, forwarding the result to the given fulfiller.Fulfiller
,
Fulfillment
@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)
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(Exception)
.
If a renderer throws an exception during its execution it will be wrapped in a RendererException
and given to error(Exception)
.
Ratpack has built in support for rendering the following types:
Path
(see FileRenderer
)CharSequence
(see CharSequenceRenderer
)
See Renderer
for more on how to contribute to the rendering framework.
object
- The object to rendervoid 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 NoSuchParserException, ParserException
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 toNoSuchParserException
- if no suitable parser could be found in the registryParserException
- if a suitable parser was found, but it threw an exception while parsing<T,O> T parse(Class<T> type, O options) throws NoSuchParserException, ParserException
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 optionsNoSuchParserException
- if no suitable parser could be found in the registryParserException
- if a suitable parser was found, but it threw an exception while parsing<T,O> T parse(Parse<T,O> parse) throws NoSuchParserException, ParserException
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 requestNoSuchParserException
- if no suitable parser could be found in the registryParserException
- if a suitable parser was found, but it threw an exception while parsingparse(Class)
,
parse(Class, Object)
,
Parser
DirectChannelAccess getDirectChannelAccess()
General only useful for low level extensions. Avoid if possible.
BindAddress getBindAddress()
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 serviceExecController getExecController()
getExecController
in interface ExecContext
List<ExecInterceptor> getInterceptors()
getInterceptors
in interface ExecContext
HttpClient getHttpClient()
getHttpClient
in interface ExecContext
<O> O get(Class<O> type) throws NotInRegistryException
get
in interface Registry
O
- The type of the object to providetype
- The type of the object to provideNotInRegistryException
- If no object of this type can be returned@Nullable <O> O maybeGet(Class<O> type)
Registry.get(Class)
, except returns null instead of throwing an exception.<O> List<O> getAll(Class<O> type)
<O> O get(com.google.common.reflect.TypeToken<O> type) throws NotInRegistryException
get
in interface Registry
O
- The type of the object to providetype
- The type of the object to provideNotInRegistryException
- If no object of this type can be returned@Nullable <O> O maybeGet(com.google.common.reflect.TypeToken<O> type)
Registry.get(Class)
, except returns null instead of throwing an exception.<O> List<O> getAll(com.google.common.reflect.TypeToken<O> type)
void addExecInterceptor(ExecInterceptor execInterceptor, Action<? super Context> action) throws Exception
Exception