Interface Context

    • 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​(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​(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.
      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​(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​(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 of NullParseOpts as the options).
      <T,​O>
      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> 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>
      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>
      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.
    • 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.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​(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​(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​(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
      • 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> 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> 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> 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> 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> 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.
      • 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
      • 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