Interface Context

  • All Superinterfaces:
    ratpack.registry.Registry

    public interface Context
    extends ratpack.registry.Registry
    The context of an individual Handler invocation.

    It provides:

    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:

    • Field Summary

      Fields 
      Modifier and Type Field Description
      static com.google.common.reflect.TypeToken<Context> TYPE
      A type token for this type.
    • Method Summary

      All Methods Instance Methods Abstract Methods Default Methods 
      Modifier and Type Method Description
      void byContent​(ratpack.func.Action<? super ByContentSpec> action)
      Respond to the request based on the requested content type (i.e.
      void byMethod​(ratpack.func.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​(java.lang.Throwable throwable)
      Handles any error thrown during request handling.
      java.nio.file.Path file​(java.lang.String path)
      Gets the file relative to the contextual FileSystemBinding.
      default PathTokens getAllPathTokens()
      The contextual path tokens of the current PathBinding.
      Context getContext()
      Returns this.
      DirectChannelAccess getDirectChannelAccess()
      Provides direct access to the backing Netty channel.
      ratpack.exec.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 current PathBinding.
      Request getRequest()
      The HTTP request.
      Response getResponse()
      The HTTP response.
      ServerConfig getServerConfig()
      The server configuration for the application.
      default java.util.Optional<java.lang.String> header​(java.lang.CharSequence name)
      Returns the request header with the specified name.
      default Context header​(java.lang.CharSequence name, java.lang.Object... values)
      Sets a response header.
      void insert​(Handler... handlers)
      Inserts some handlers into the pipeline, then delegates to the first.
      void insert​(ratpack.registry.Registry registry, Handler... handlers)
      Inserts some handlers into the pipeline to execute with the given registry, then delegates to the first.
      void lastModified​(java.time.Instant lastModified, java.lang.Runnable serve)
      Convenience method for handling last-modified based HTTP caching.
      default void lastModified​(java.util.Date lastModified, java.lang.Runnable serve)
      Convenience method for handling last-modified based HTTP caching.
      void next()
      Delegate handling to the next handler in line.
      void next​(ratpack.registry.Registry registry)
      Invokes the next handler, after adding the given registry.
      default void notFound()
      Issues a 404 client error.
      void onClose​(ratpack.func.Action<? super RequestOutcome> onClose)
      Registers a callback to be notified when the request for this context is “closed” (i.e.
      <T> ratpack.exec.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 of NullParseOpts as the options).
      <T,​O>
      ratpack.exec.Promise<T>
      parse​(com.google.common.reflect.TypeToken<T> type, O options)
      Constructs a Parse from the given args and delegates to parse(Parse).
      <T> ratpack.exec.Promise<T> parse​(java.lang.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>
      ratpack.exec.Promise<T>
      parse​(java.lang.Class<T> type, O options)
      Constructs a Parse from the given args and delegates to parse(Parse).
      <T,​O>
      T
      parse​(TypedData body, Parse<T,​O> parse)
      Parses the provided request body into an object.
      <T,​O>
      ratpack.exec.Promise<T>
      parse​(Parse<T,​O> parse)
      Parses the request body into an object.
      void redirect​(int code, java.lang.Object to)
      Sends a redirect response to the given location, and with the given status code.
      default void redirect​(int code, java.lang.String to)
      Sends a redirect response to the given location, and with the given status code.
      default void redirect​(int code, java.net.URI to)
      Sends a redirect response to the given location, and with the given status code.
      void redirect​(java.lang.Object to)
      Sends a temporary redirect response (i.e.
      default void redirect​(java.lang.String to)
      Sends a temporary redirect response (i.e.
      default void redirect​(java.net.URI to)
      Sends a temporary redirect response (i.e.
      void render​(java.lang.Object object)
      Render the given object, using the rendering framework.
      • Methods inherited from interface ratpack.registry.Registry

        first, first, get, get, getAll, getAll, join, maybeGet, maybeGet
    • 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

        ratpack.exec.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​(ratpack.registry.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.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());
             });
           }
         }
         
        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​(ratpack.registry.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 insert
        registry - The registry for the inserted handlers
      • byMethod

        @NonBlocking
        void byMethod​(ratpack.func.Action<? super ByMethodSpec> action)
               throws java.lang.Exception
        Respond to the request based on the request method.
        
         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.

        Parameters:
        action - the specification of how to handle the request based on the request method
        Throws:
        java.lang.Exception - any thrown by action
      • byContent

        void byContent​(ratpack.func.Action<? super ByContentSpec> action)
                throws java.lang.Exception
        Respond to the request based on the requested content type (i.e. the request Accept header). For more details, see ByContentSpec.
        Parameters:
        action - the specification of how to handle the request based on the clients preference of content type
        Throws:
        java.lang.Exception - any thrown by action
      • error

        @NonBlocking
        void error​(java.lang.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, the clientError(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 ratpack.registry.NotInRegistryException
        Forwards the error to the 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.
        Parameters:
        statusCode - The 4xx range status code that indicates the error type
        Throws:
        ratpack.registry.NotInRegistryException - if no ClientErrorHandler can be found in the service
      • render

        @NonBlocking
        void render​(java.lang.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 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:

        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 java.util.Optional<java.lang.String> header​(java.lang.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​(java.lang.CharSequence name,
                               java.lang.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 set
        values - the header values
        Returns:
        this
        Since:
        1.4
        See Also:
        MutableHeaders.set(CharSequence, Iterable)
      • redirect

        default void redirect​(java.lang.String to)
        Sends a temporary redirect response (i.e. 302) to the client using the specified redirect location.

        This method is effectively deprecated and will be removed in Ratpack 2.0. Note, this method simply delegates to redirect(Object) which is the replacement. It is not formally marked as deprecated as the replacement is source compatible, and a generalising overload of this method.

        Parameters:
        to - the location to redirect to
        See Also:
        redirect(Object)
      • redirect

        default void redirect​(int code,
                              java.lang.String to)
        Sends a redirect response to the given location, and with the given status code.

        This method is effectively deprecated and will be removed in Ratpack 2.0. Note, this method simply delegates to redirect(int, Object) which is the replacement. It is not formally marked as deprecated as the replacement is source compatible, and a generalising overload of this method.

        Parameters:
        code - the redirect response status code
        to - the location to redirect to
        See Also:
        redirect(int, Object)
      • redirect

        default void redirect​(java.net.URI to)
        Sends a temporary redirect response (i.e. 302) to the client using the specified redirect location.

        This method is effectively deprecated and will be removed in Ratpack 2.0. Note, this method simply delegates to redirect(Object) which is the replacement. It is not formally marked as deprecated as the replacement is source compatible, and a generalising overload of this method.

        Parameters:
        to - the location to redirect to
        Since:
        1.2
        See Also:
        redirect(Object)
      • redirect

        default void redirect​(int code,
                              java.net.URI to)
        Sends a redirect response to the given location, and with the given status code.

        This method is effectively deprecated and will be removed in Ratpack 2.0. Note, this method simply delegates to redirect(int, Object) which is the replacement. It is not formally marked as deprecated as the replacement is source compatible, and a generalising overload of this method.

        Parameters:
        code - the redirect response status code
        to - the location to redirect to
        See Also:
        redirect(int, Object)
      • redirect

        void redirect​(java.lang.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,
                      java.lang.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 with this context.

        Parameters:
        code - The status code of the redirect
        to - the redirect location URL
        Since:
        1.3
        See Also:
        Redirector
      • lastModified

        @NonBlocking
        default void lastModified​(java.util.Date lastModified,
                                  java.lang.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 response
        serve - the response sending action if the response needs to be sent
      • lastModified

        @NonBlocking
        void lastModified​(java.time.Instant lastModified,
                          java.lang.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 response
        serve - the response sending action if the response needs to be sent
        Since:
        1.4
      • parse

        <T> ratpack.exec.Promise<T> parse​(java.lang.Class<T> type)
        Parse the request into the given type, using no options (or more specifically an instance of 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)).

        Type Parameters:
        T - the type to parse to
        Parameters:
        type - the type to parse to
        Returns:
        a promise for the parsed object
      • parse

        <T> ratpack.exec.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 of 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)).

        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> ratpack.exec.Promise<T> parse​(java.lang.Class<T> type,
                                                  O options)
        Constructs a Parse from the given args and delegates to parse(Parse).
        Type Parameters:
        T - The type to parse to
        O - The type of the parse opts
        Parameters:
        type - The type to parse to
        options - The parse options
        Returns:
        a promise for the parsed object
      • parse

        <T,​O> ratpack.exec.Promise<T> parse​(com.google.common.reflect.TypeToken<T> type,
                                                  O options)
        Constructs a Parse from the given args and delegates to parse(Parse).
        Type Parameters:
        T - The type to parse to
        O - The type of the parse opts
        Parameters:
        type - The type to parse to
        options - The parse options
        Returns:
        a promise for the parsed object
      • parse

        <T,​O> ratpack.exec.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:

        1. All parsers are retrieved from the context registry (i.e. getAll(Parser.class));
        2. Found parsers are checked (in order returned by getAll()) for compatibility with the options type;
        3. If a parser is found that is compatible, its Parser.parse(Context, TypedData, Parse) method is called;
        4. If the parser returns null the next parser will be tried, if it returns a value it will be returned by this method;
        5. 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:

        Core Parsers

        Ratpack core provides parsers for Form, and JSON (see Jackson).

        Example Usage

        
         import ratpack.handling.Handler;
         import ratpack.handling.Context;
         import ratpack.form.Form;
         import ratpack.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 into
        O - 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
      • parse

        <T,​O> T parse​(TypedData body,
                            Parse<T,​O> parse)
                     throws java.lang.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 into
        O - The type of the parse options object
        Parameters:
        body - The request body
        parse - The specification of how to parse the request
        Returns:
        a promise for the parsed object
        Throws:
        java.lang.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.
      • getPathTokens

        default PathTokens getPathTokens()
                                  throws ratpack.registry.NotInRegistryException
        The contextual path tokens of the current PathBinding.

        Shorthand for getPathBinding().getPathTokens().

        Returns:
        The contextual path tokens of the current PathBinding.
        Throws:
        ratpack.registry.NotInRegistryException - if there is no PathBinding in the current service
      • getAllPathTokens

        default PathTokens getAllPathTokens()
                                     throws ratpack.registry.NotInRegistryException
        The contextual path tokens of the current PathBinding.

        Shorthand for getPathBinding().getAllPathTokens().

        Returns:
        The contextual path tokens of the current PathBinding.
        Throws:
        ratpack.registry.NotInRegistryException - if there is no PathBinding in the current service
      • onClose

        void onClose​(ratpack.func.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

        java.nio.file.Path file​(java.lang.String path)
                         throws ratpack.registry.NotInRegistryException
        Gets the file relative to the contextual 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.

        Parameters:
        path - The path to pass to the FileSystemBinding.file(String) method.
        Returns:
        The file relative to the contextual FileSystemBinding
        Throws:
        ratpack.registry.NotInRegistryException - if there is no FileSystemBinding 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