Interface Context
-
- All Superinterfaces:
Registry
- All Known Subinterfaces:
GroovyContext
public interface Context extends Registry
The context of an individualHandler
invocation.It provides:
- Access the HTTP
request
andresponse
- Delegation (via the
next()
andinsert(ratpack.core.handling.Handler...)
family of methods) - Access to contextual objects (see below)
- Convenience for common handler operations
Contextual objects
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.Default contextual objects
There is also a set of default objects that are made available via the Ratpack infrastructure:
- A
FileSystemBinding
that is the applicationServerConfig.getBaseDir()
- A
MimeTypes
implementation - A
ServerErrorHandler
- A
ClientErrorHandler
- A
PublicAddress
- A
Redirector
-
-
Method Summary
All Methods Instance Methods Abstract Methods Default Methods Modifier and Type Method 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 theClientErrorHandler
in this service.void
error(Throwable throwable)
Handles any error thrown during request handling.Path
file(String path)
Gets the file relative to the contextualFileSystemBinding
.default PathTokens
getAllPathTokens()
The contextual path tokens of the currentPathBinding
.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()
Returns the current filesystem binding from the context registry.PathBinding
getPathBinding()
The current request path binding.default PathTokens
getPathTokens()
The contextual path tokens of the currentPathBinding
.Request
getRequest()
The HTTP request.Response
getResponse()
The HTTP response.ServerConfig
getServerConfig()
The server configuration for the application.default Optional<String>
header(CharSequence name)
Returns the request header with the specified name.default Context
header(CharSequence name, Object... values)
Sets a response header.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(Instant lastModified, Runnable serve)
Convenience method for handling last-modified based HTTP caching.default void
lastModified(Date lastModified, Runnable serve)
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.default void
notFound()
Issues a 404 client error.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(com.google.common.reflect.TypeToken<T> type)
Parse the request into the given type, using no options (or more specifically an instance ofNullParseOpts
as the options).<T,O>
Promise<T>parse(com.google.common.reflect.TypeToken<T> type, O options)
Constructs aParse
from the given args and delegates toparse(Parse)
.<T> Promise<T>
parse(Class<T> type)
Parse the request into the given type, using no options (or more specifically an instance ofNullParseOpts
as the options).<T,O>
Promise<T>parse(Class<T> type, O options)
Constructs aParse
from the given args and delegates toparse(Parse)
.<T,O>
Tparse(TypedData body, Parse<T,O> parse)
Parses the provided request body into an object.<T,O>
Promise<T>parse(Parse<T,O> parse)
Parses the request body into an object.void
redirect(int code, Object to)
Sends a redirect response to the given location, and with the given status code.void
redirect(Object to)
Sends a temporary redirect response (i.e.void
render(Object object)
Render the given object, using the rendering framework.
-
-
-
Field Detail
-
TYPE
static final com.google.common.reflect.TypeToken<Context> TYPE
A type token for this type.- Since:
- 1.1
-
-
Method Detail
-
getContext
Context getContext()
Returns this.- Returns:
- this.
-
getExecution
Execution getExecution()
The execution of handling this request.- Returns:
- the execution of handling this request
-
getServerConfig
ServerConfig getServerConfig()
The server configuration for the application.- Returns:
- the server configuration for the application
-
getRequest
Request getRequest()
The HTTP request.- Returns:
- The HTTP request.
-
getResponse
Response getResponse()
The HTTP response.- Returns:
- The HTTP response.
-
next
@NonBlocking void next()
Delegate handling to the next handler in line.The request and response of this object should not be accessed after this method is called.
-
next
@NonBlocking void next(Registry registry)
Invokes the next handler, after adding the given registry.The given registry is appended to the existing. This means that it can shadow objects previously available.
import ratpack.exec.registry.Registry; import ratpack.test.embed.EmbeddedApp; import static org.junit.jupiter.api.Assertions.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()); }); } }
- Parameters:
registry
- The registry to make available for subsequent handlers.
-
insert
@NonBlocking void insert(Handler... handlers)
Inserts some handlers into the pipeline, then delegates to the first.The request and response of this object should not be accessed after this method is called.
- Parameters:
handlers
- The handlers to insert.
-
insert
@NonBlocking void insert(Registry registry, Handler... handlers)
Inserts some handlers into the pipeline to execute with the given registry, then delegates to the first.The given registry is only applicable to the inserted handlers.
Almost always, the registry should be a super set of the current registry.
- Parameters:
handlers
- The handlers to insertregistry
- The registry for the inserted handlers
-
byMethod
@NonBlocking void byMethod(Action<? super ByMethodSpec> action) throws Exception
Respond to the request based on the request method.import ratpack.test.embed.EmbeddedApp; import static org.junit.jupiter.api.Assertions.*; 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 byclientError(int)
.If the handler only needs to respond to one HTTP method it can be more convenient to use
Chain.get(Handler)
and friends.- Parameters:
action
- the specification of how to handle the request based on the request method- Throws:
Exception
- any thrown by action
-
byContent
void byContent(Action<? super ByContentSpec> action) throws Exception
Respond to the request based on the requested content type (i.e. the request Accept header). For more details, seeByContentSpec
.- Parameters:
action
- the specification of how to handle the request based on the clients preference of content type- Throws:
Exception
- any thrown by action
-
error
@NonBlocking void error(Throwable throwable)
Handles any error thrown during request handling.Uncaught exceptions that are thrown any time during request handling will end up here.
Forwards the exception to the
ServerErrorHandler
within the current registry. Add an implementation of this interface to the registry to handle errors. The default implementation is not suitable for production usage.If the exception is-a
ClientErrorException
, theclientError(int)
method will be called with the exception's status code instead of being forward to the server error handler.- Parameters:
throwable
- The exception that occurred
-
clientError
@NonBlocking void clientError(int statusCode) throws NotInRegistryException
Forwards the error to theClientErrorHandler
in this service. The default configuration of Ratpack includes aClientErrorHandler
in all contexts. ANotInRegistryException
will only be thrown if a very custom service setup is being used.- Parameters:
statusCode
- The 4xx range status code that indicates the error type- Throws:
NotInRegistryException
- if noClientErrorHandler
can be found in the service
-
render
@NonBlocking void render(Object object) throws NoSuchRendererException
Render the given object, using the rendering framework.The first
Renderer
, that is able to render the given object will be delegated to. If the given argument isnull
, this method will have the same effect asclientError(404)
.If no renderer can be found for the given type, a
NoSuchRendererException
will be given toerror(Throwable)
.If a renderer throws an exception during its execution it will be wrapped in a
RendererException
and given toerror(Throwable)
.Ratpack has built in support for rendering the following types:
Path
CharSequence
JsonRender
(Typically created viaJackson.json(Object)
)Promise
(renders the promised value, using thisrender()
method)Publisher
(converts the publisher to a promise usingStreams.toPromise(Publisher)
and renders it)Renderable
(Delegates to theRenderable.render(Context)
method of the object)
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.- Parameters:
object
- The object-to-render- Throws:
NoSuchRendererException
- if no suitable renderer can be found
-
header
default Optional<String> header(CharSequence name)
Returns the request header with the specified name.If there is more than value for the specified header, the first value is returned.
Shorthand for
getRequest().getHeaders().get(String)
.- Parameters:
name
- the case insensitive name of the header to get retrieve the first value of- Returns:
- the header value or
null
if there is no such header - Since:
- 1.4
-
header
default Context header(CharSequence name, Object... values)
Sets a response header.Any previously set values for the header will be removed.
Shorthand for
getResponse().getHeaders().set(CharSequence, Iterable)
.- Parameters:
name
- the name of the header to setvalues
- the header values- Returns:
this
- Since:
- 1.4
- See Also:
MutableHeaders.set(CharSequence, Iterable)
-
redirect
void redirect(Object to)
Sends a temporary redirect response (i.e. 302) to the client using the specified redirect location.- Parameters:
to
- the location to redirect to- Since:
- 1.3
- See Also:
redirect(int, Object)
-
redirect
void redirect(int code, Object to)
Sends a redirect response to the given location, and with the given status code.This method retrieves the
Redirector
from the registry, and forwards the given arguments along withthis
context.- Parameters:
code
- The status code of the redirectto
- the redirect location URL- Since:
- 1.3
- See Also:
Redirector
-
lastModified
@NonBlocking default void lastModified(Date lastModified, Runnable serve)
Convenience method for handling last-modified based HTTP caching.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.
- Parameters:
lastModified
- the effective last modified date of the responseserve
- the response sending action if the response needs to be sent
-
lastModified
@NonBlocking void lastModified(Instant lastModified, Runnable serve)
Convenience method for handling last-modified based HTTP caching.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.
- Parameters:
lastModified
- the effective last modified date of the responseserve
- the response sending action if the response needs to be sent- Since:
- 1.4
-
parse
<T> Promise<T> parse(Class<T> type)
Parse the request into the given type, using no options (or more specifically an instance ofNullParseOpts
as the options).The code sample is functionally identical to the sample given for the
parse(Parse)
variant…import ratpack.core.handling.Handler; import ratpack.core.handling.Context; import ratpack.core.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))
.- Type Parameters:
T
- the type to parse to- Parameters:
type
- the type to parse to- Returns:
- a promise for the parsed object
-
parse
<T> Promise<T> parse(com.google.common.reflect.TypeToken<T> type)
Parse the request into the given type, using no options (or more specifically an instance ofNullParseOpts
as the options).The code sample is functionally identical to the sample given for the
parse(Parse)
variant…import ratpack.core.handling.Handler; import ratpack.core.handling.Context; import ratpack.core.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))
.- Type Parameters:
T
- the type to parse to- Parameters:
type
- the type to parse to- Returns:
- a promise for the parsed object
-
parse
<T,O> Promise<T> parse(Class<T> type, O options)
Constructs aParse
from the given args and delegates toparse(Parse)
.- Type Parameters:
T
- The type to parse toO
- The type of the parse opts- Parameters:
type
- The type to parse tooptions
- The parse options- Returns:
- a promise for the parsed object
-
parse
<T,O> Promise<T> parse(com.google.common.reflect.TypeToken<T> type, O options)
Constructs aParse
from the given args and delegates toparse(Parse)
.- Type Parameters:
T
- The type to parse toO
- The type of the parse opts- Parameters:
type
- The type to parse tooptions
- The parse options- Returns:
- a promise for the parsed object
-
parse
<T,O> Promise<T> parse(Parse<T,O> parse)
Parses the request body into an object.How to parse the request is determined by the given
Parse
object.Parser Resolution
Parser resolution happens as follows:
- All
parsers
are retrieved from the context registry (i.e.getAll(Parser.class)
); - Found parsers are checked (in order returned by
getAll()
) for compatibility with the options type; - If a parser is found that is compatible, its
Parser.parse(Context, TypedData, Parse)
method is called; - If the parser returns
null
the next parser will be tried, if it returns a value it will be returned by this method; - If no compatible parser could be found, a
NoSuchParserException
will be thrown.
Parser Compatibility
A parser is compatible if all of the following hold true:
- The opts of the given
parse
object is aninstanceof
itsParser.getOptsType()
, or the opts arenull
. - The
Parser.parse(Context, TypedData, Parse)
method returns a non null value.
Core Parsers
Ratpack core provides parsers for
Form
, and JSON (seeJackson
).Example Usage
import ratpack.core.handling.Handler; import ratpack.core.handling.Context; import ratpack.core.form.Form; import ratpack.core.parse.NullParseOpts; public class FormHandler implements Handler { public void handle(Context context) { context.parse(Form.class).then(form -> context.render(form.get("someFormParam"))); } }
- Type Parameters:
T
- The type of object the request is parsed intoO
- the type of the parse options object- Parameters:
parse
- The specification of how to parse the request- Returns:
- a promise for the parsed object
- See Also:
parse(Class)
,parse(Class, Object)
,Parser
- All
-
parse
<T,O> T parse(TypedData body, Parse<T,O> parse) throws Exception
Parses the provided request body into an object.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.- Type Parameters:
T
- The type of object the request is parsed intoO
- The type of the parse options object- Parameters:
body
- The request bodyparse
- The specification of how to parse the request- Returns:
- a promise for the parsed object
- Throws:
Exception
- any thrown by the parser- See Also:
parse(Parse)
-
getDirectChannelAccess
DirectChannelAccess getDirectChannelAccess()
Provides direct access to the backing Netty channel.General only useful for low level extensions. Avoid if possible.
- Returns:
- Direct access to the underlying channel.
-
getPathBinding
PathBinding getPathBinding()
The current request path binding.The request path binding represents successful “matches” of the request path to handlers that only respond to certain kinds of request paths. Such handlers can be added with
Chain.path(String, Handler)
,Chain.prefix(String, Action)
,Chain.post(String, Handler)
etc.- Returns:
- the current request path binding
- Since:
- 1.4
-
getPathTokens
default PathTokens getPathTokens() throws NotInRegistryException
The contextual path tokens of the currentPathBinding
.Shorthand for
getPathBinding().getPathTokens()
.- Returns:
- The contextual path tokens of the current
PathBinding
. - Throws:
NotInRegistryException
- if there is noPathBinding
in the current service
-
getAllPathTokens
default PathTokens getAllPathTokens() throws NotInRegistryException
The contextual path tokens of the currentPathBinding
.Shorthand for
getPathBinding().getAllPathTokens()
.- Returns:
- The contextual path tokens of the current
PathBinding
. - Throws:
NotInRegistryException
- if there is noPathBinding
in the current service
-
onClose
void onClose(Action<? super RequestOutcome> onClose)
Registers a callback to be notified when the request for this context is “closed” (i.e. responded to).- Parameters:
onClose
- A notification callback
-
file
Path file(String path) throws NotInRegistryException
Gets the file relative to the contextualFileSystemBinding
.Shorthand for
get(FileSystemBinding.class).file(path)
.The default configuration of Ratpack includes a
FileSystemBinding
in all contexts. ANotInRegistryException
will only be thrown if a very custom service setup is being used.- Parameters:
path
- The path to pass to theFileSystemBinding.file(String)
method.- Returns:
- The file relative to the contextual
FileSystemBinding
- Throws:
NotInRegistryException
- if there is noFileSystemBinding
in the current service
-
getFileSystemBinding
default FileSystemBinding getFileSystemBinding()
Returns the current filesystem binding from the context registry.- Returns:
- the current filesystem binding from the context registry
-
notFound
default void notFound()
Issues a 404 client error.This method is literally a shorthand for
clientError(404)
.This is a terminal handler operation.
- Since:
- 1.1
-
-