Interface Request

    • Field Detail

      • TYPE

        static final com.google.common.reflect.TypeToken<Request> TYPE
        A type token for this type.
        Since:
        1.1
    • Method Detail

      • getMethod

        HttpMethod getMethod()
        The method of the request.
        Returns:
        The method of the request.
      • getProtocol

        String getProtocol()
        The HTTP protocol of the request.

        e.g. "HTTP/1.1

        Returns:
        The HTTP protocol of the request.
      • getRawUri

        String getRawUri()
        The raw URI of the request.

        This value may be an absolute URI or an absolute path.

        Returns:
        The raw URI of the request.
      • getUri

        String getUri()
        The complete URI of the request (path + query string).

        This value is always absolute (i.e. begins with "/").

        Returns:
        The complete URI of the request (path + query string).
      • getQuery

        String getQuery()
        The query string component of the request URI, without the "?".

        If the request does not contain a query component, an empty string will be returned.

        Returns:
        The query string component of the request URI, without the "?".
      • getPath

        String getPath()
        The URI without the query string and leading forward slash.
        Returns:
        The URI without the query string and leading forward slash
      • getCookies

        Set<io.netty.handler.codec.http.cookie.Cookie> getCookies()
        The cookies that were sent with the request.

        An empty set will be returned if no cookies were sent.

        Returns:
        The cookies that were sent with the request.
      • oneCookie

        @Nullable
        String oneCookie​(String name)
        Returns the value of the cookie with the specified name if it was sent.

        If there is more than one cookie with this name, this method will throw an exception.

        Parameters:
        name - The name of the cookie to get the value of
        Returns:
        The cookie value, or null if not present
      • getBody

        Promise<TypedData> getBody()
        The body of the request.

        If this request does not have a body, a non null object is still returned but it effectively has no data.

        If the transmitted content is larger than provided ServerConfig.getMaxContentLength(), the given block will be invoked. If the block completes successfully, the promise will be terminated. If the block errors, the promise will carry the failure.

        If the body is larger then getMaxContentLength(), a RequestBodyTooLargeException will be propagated.

        Returns:
        the body of the request
      • setIdleTimeout

        void setIdleTimeout​(Duration idleTimeout)
        Overrides the idle timeout for this connection.

        The default is set as part of server config via ServerConfigBuilder.idleTimeout(Duration).

        The override strictly applies to only the request/response exchange that this request is involved in.

        Parameters:
        idleTimeout - the idle timeout (Duration.ZERO = no timeout, must not be negative, must not be null)
        Since:
        1.5
        See Also:
        ServerConfig.getIdleTimeout()
      • getBody

        Promise<TypedData> getBody​(Block onTooLarge)
        The body of the request.

        If this request does not have a body, a non null object is still returned but it effectively has no data.

        If the body content is larger than provided maxContentLength, the given block will be invoked. If the block completes successfully, the promise will be terminated. If the block errors, the promise will carry the failure.

        If the body content is larger than the provided maxContentLength, a 413 status will be issued and the connection will be closed, regardless of any other attempts to render a response.

        Parameters:
        onTooLarge - the action to take if the request body exceeds the given maxContentLength
        Returns:
        the body of the request
        Since:
        1.1
      • getBody

        Promise<TypedData> getBody​(long maxContentLength)
        The body of the request allowing up to the provided size for the content.

        If this request does not have a body, a non null object is still returned but it effectively has no data.

        If the body content is larger than the provided maxContentLength, a 413 status will be issued and the connection will be closed, regardless of any other attempts to render a response.

        Parameters:
        maxContentLength - the maximum number of bytes allowed for the request.
        Returns:
        the body of the request.
        Since:
        1.1
      • getBody

        Promise<TypedData> getBody​(long maxContentLength,
                                   Block onTooLarge)
        The body of the request allowing up to the provided size for the content.

        If this request does not have a body, a non null object is still returned but it effectively has no data.

        If the body content is larger than the provided maxContentLength, the given block will be invoked. If the block completes successfully, the promise will be terminated. If the block errors, the promise will carry the failure.

        If the body content is larger than the provided maxContentLength, a 413 status will be issued and the connection will be closed, regardless of any other attempts to render a response.

        Parameters:
        maxContentLength - the maximum number of bytes allowed for the request.
        onTooLarge - the action to take if the request body exceeds the given maxContentLength
        Returns:
        the body of the request.
        Since:
        1.1
      • getBodyStream

        TransformablePublisher<? extends io.netty.buffer.ByteBuf> getBodyStream​(long maxContentLength)
        Allows reading the body as a stream, with back pressure.

        The returned publisher emits the body as ByteBufs. The subscriber MUST release() each emitted byte buf. Failing to do so will leak memory.

        If the request body is larger than the given maxContentLength, a RequestBodyTooLargeException will be emitted. If the request body has already been read, a RequestBodyAlreadyReadException will be emitted.

        If the body content is larger than the provided maxContentLength, a 413 status will be issued and the connection will be closed, regardless of any other attempts to render a response.

        The returned publisher is bound to the calling execution via Streams.bindExec(Publisher). If your subscriber's onNext(), onComplete() or onError() methods are asynchronous they MUST use Promise, Blocking or similar execution control constructs.

        The following demonstrates how to use this method to stream the request body to a file, using asynchronous IO.

        
         import com.google.common.io.Files;
         import io.netty.buffer.ByteBuf;
         import org.apache.commons.lang3.RandomStringUtils;
         import org.reactivestreams.Subscriber;
         import org.reactivestreams.Subscription;
         import ratpack.exec.Promise;
         import ratpack.core.http.client.ReceivedResponse;
         import ratpack.test.embed.EmbeddedApp;
         import ratpack.test.embed.EphemeralBaseDir;
        
         import java.io.IOException;
         import java.nio.channels.AsynchronousFileChannel;
         import java.nio.charset.StandardCharsets;
         import java.nio.file.Path;
         import java.nio.file.StandardOpenOption;
        
         import static org.junit.jupiter.api.Assertions.*;
        
         public class Example {
           public static void main(String[] args) throws Exception {
             EphemeralBaseDir.tmpDir().use(dir -> {
               String string = RandomStringUtils.random(1024 * 1024);
               int length = string.getBytes(StandardCharsets.UTF_8).length;
        
               Path file = dir.path("out.txt");
        
               EmbeddedApp.fromHandler(ctx ->
                 ctx.getRequest().getBodyStream(length).subscribe(new Subscriber<ByteBuf>() {
        
                   private Subscription subscription;
                   private AsynchronousFileChannel out;
                   long written;
        
                   @Override
                   public void onSubscribe(Subscription s) {
                     subscription = s;
                     try {
                       this.out = AsynchronousFileChannel.open(
                         file, StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING
                       );
                       subscription.request(1);
                     } catch (IOException e) {
                       subscription.cancel();
                       ctx.error(e);
                     }
                   }
        
                   @Override
                   public void onNext(ByteBuf byteBuf) {
                     Promise.<Integer>async(down ->
                       out.write(byteBuf.nioBuffer(), written, null, down.completionHandler())
                     ).onError(error -> {
                       byteBuf.release();
                       subscription.cancel();
                       out.close();
                       ctx.error(error);
                     }).then(bytesWritten -> {
                       byteBuf.release();
                       written += bytesWritten;
                       subscription.request(1);
                     });
                   }
        
                   @Override
                   public void onError(Throwable t) {
                     ctx.error(t);
                     try {
                       out.close();
                     } catch (IOException ignore) {
                       // ignore
                     }
                   }
        
                   @Override
                   public void onComplete() {
                     try {
                       out.close();
                     } catch (IOException ignore) {
                       // ignore
                     }
                     ctx.render("ok");
                   }
                 })
               ).test(http -> {
                 ReceivedResponse response = http.request(requestSpec -> requestSpec.method("POST").getBody().text(string));
                 assertEquals(response.getBody().getText(), "ok");
        
                 String fileContents = Files.asCharSource(file.toFile(), StandardCharsets.UTF_8).read();
                 assertEquals(fileContents, string);
               });
             });
           }
         }
         
        Returns:
        a publisher of the request body
        Since:
        1.2
        See Also:
        getBodyStream(long)
      • getHeaders

        Headers getHeaders()
        The request headers.
        Returns:
        The request headers.
      • getContentType

        MediaType getContentType()
        The type of the data as specified in the "content-type" header.

        If no "content-type" header is specified, an empty MediaType is returned.

        Returns:
        The type of the data.
        See Also:
        MediaType.isEmpty()
      • getRemoteAddress

        com.google.common.net.HostAndPort getRemoteAddress()
        The address of the client that initiated the request.
        Returns:
        the address of the client that initiated the request
      • getLocalAddress

        com.google.common.net.HostAndPort getLocalAddress()
        The address of the local network interface that received the request.
        Returns:
        the address of the network interface that received the request
      • isAjaxRequest

        boolean isAjaxRequest()
        A flag representing whether or not the request originated via AJAX.
        Returns:
        A flag representing whether or not the request originated via AJAX.
      • isExpectsContinue

        boolean isExpectsContinue()
        Whether this request contains a Expect: 100-Continue header.

        You do not need to send the 100 Continue status response. It will be automatically sent when the body is read via getBody() or getBodyStream(long) (or variants). Ratpack will not emit a 417 Expectation Failed response if the body is not read. The response specified by the handling code will not be altered, as per normal.

        If the header is present for the request, this method will return true before and after the 100 Continue response has been sent.

        Returns:
        whether this request includes the Expect: 100-Continue header
        Since:
        1.2
      • getContentLength

        long getContentLength()
        The advertised content length of the request body.

        Will return -1 if no Content-Length header is present, or is not valid long value.

        Returns:
        the advertised content length of the request body.
        Since:
        1.2
      • getTimestamp

        Instant getTimestamp()
        The timestamp for when this request was received. Specifically, this is the timestamp of creation of the request object.
        Returns:
        the instant timestamp for the request.
      • setMaxContentLength

        void setMaxContentLength​(long maxContentLength)
        Sets the allowed max content length for the request body.

        This setting will be used when getBody() or getBodyStream() are called, and when implicitly reading the request body in order to respond (e.g. when issuing a response without trying to read the body).

        Parameters:
        maxContentLength - the maximum request body length in bytes
        Since:
        1.5
      • getMaxContentLength

        long getMaxContentLength()
        The max allowed content length for the request body.
        Returns:
        the maximum request body length in bytes
        Since:
        1.5
        See Also:
        setMaxContentLength(long)
      • getSslSession

        Optional<SSLSession> getSslSession()
        The client SSL session if the connection was made with HTTPS.

        If client authentication is enabled, the client's certificate can be obtained via SSLSession.getPeerCertificates()

        Returns:
        the client's SSL session
        Since:
        2.0
      • add

        <O> Request add​(Class<O> type,
                        O object)
        Adds a registry entry that is available by the given type.
        Specified by:
        add in interface RegistrySpec
        Type Parameters:
        O - the public type of the registry entry
        Parameters:
        type - the public type of the registry entry
        object - the actual registry entry
        Returns:
        this
      • add

        <O> Request add​(com.google.common.reflect.TypeToken<O> type,
                        O object)
        Adds a registry entry that is available by the given type.
        Specified by:
        add in interface RegistrySpec
        Type Parameters:
        O - the public type of the registry entry
        Parameters:
        type - the public type of the registry entry
        object - the actual registry entry
        Returns:
        this
      • add

        Request add​(Object object)
        Adds a registry entry.
        Specified by:
        add in interface RegistrySpec
        Parameters:
        object - the object to add to the registry
        Returns:
        this
      • addLazy

        <O> Request addLazy​(Class<O> type,
                            Supplier<? extends O> supplier)
        Adds a lazily created entry to the registry.

        The supplier will be invoked exactly once, when a query is made to the registry of a compatible type of the given type.

        Specified by:
        addLazy in interface RegistrySpec
        Type Parameters:
        O - the public type of the registry entry
        Parameters:
        type - the public type of the registry entry
        supplier - the supplier for creating the object when needed
        Returns:
        this
      • addLazy

        <O> Request addLazy​(com.google.common.reflect.TypeToken<O> type,
                            Supplier<? extends O> supplier)
        Adds a lazily created entry to the registry.

        The supplier will be invoked exactly once, when a query is made to the registry of a compatible type of the given type.

        Specified by:
        addLazy in interface RegistrySpec
        Type Parameters:
        O - the public type of the registry entry
        Parameters:
        type - the public type of the registry entry
        supplier - the supplier for creating the object when needed
        Returns:
        this