Interface Context

    • 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 insert
        registry - 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 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:
        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, see ByContentSpec.
        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, 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 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 set
        values - 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 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​(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 response
        serve - 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 response
        serve - 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 of NullParseOpts 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 of NullParseOpts 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 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.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 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 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:
        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