Package ratpack.http

Interface Request

    • Field Summary

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

      All Methods Instance Methods Abstract Methods 
      Modifier and Type Method Description
      <O> Request add​(com.google.common.reflect.TypeToken<O> type, O object)
      Adds a registry entry that is available by the given type.
      <O> Request add​(java.lang.Class<O> type, O object)
      Adds a registry entry that is available by the given type.
      Request add​(java.lang.Object object)
      Adds a registry entry.
      <O> Request addLazy​(com.google.common.reflect.TypeToken<O> type, java.util.function.Supplier<? extends O> supplier)
      Adds a lazily created entry to the registry.
      <O> Request addLazy​(java.lang.Class<O> type, java.util.function.Supplier<? extends O> supplier)
      Adds a lazily created entry to the registry.
      Promise<TypedData> getBody()
      The body of the request.
      Promise<TypedData> getBody​(long maxContentLength)
      The body of the request allowing up to the provided size for the content.
      Promise<TypedData> getBody​(long maxContentLength, Block onTooLarge)
      The body of the request allowing up to the provided size for the content.
      Promise<TypedData> getBody​(Block onTooLarge)
      The body of the request.
      TransformablePublisher<? extends io.netty.buffer.ByteBuf> getBodyStream()
      Allows reading the body as a stream, with back pressure.
      TransformablePublisher<? extends io.netty.buffer.ByteBuf> getBodyStream​(long maxContentLength)
      Allows reading the body as a stream, with back pressure.
      java.util.Optional<javax.security.cert.X509Certificate> getClientCertificate()
      The client's verified certificate if the connection was made with HTTPS and client authentication is enabled.
      long getContentLength()
      The advertised content length of the request body.
      MediaType getContentType()
      The type of the data as specified in the "content-type" header.
      java.util.Set<io.netty.handler.codec.http.cookie.Cookie> getCookies()
      The cookies that were sent with the request.
      Headers getHeaders()
      The request headers.
      com.google.common.net.HostAndPort getLocalAddress()
      The address of the local network interface that received the request.
      long getMaxContentLength()
      The max allowed content length for the request body.
      HttpMethod getMethod()
      The method of the request.
      java.lang.String getPath()
      The URI without the query string and leading forward slash.
      java.lang.String getProtocol()
      The HTTP protocol of the request.
      java.lang.String getQuery()
      The query string component of the request URI, without the "?".
      MultiValueMap<java.lang.String,​java.lang.String> getQueryParams()
      TBD.
      java.lang.String getRawUri()
      The raw URI of the request.
      com.google.common.net.HostAndPort getRemoteAddress()
      The address of the client that initiated the request.
      java.time.Instant getTimestamp()
      The timestamp for when this request was received.
      java.lang.String getUri()
      The complete URI of the request (path + query string).
      boolean isAjaxRequest()
      A flag representing whether or not the request originated via AJAX.
      boolean isChunkedTransfer()
      Whether this request contains a Transfer-Encoding: chunked header.
      boolean isExpectsContinue()
      Whether this request contains a Expect: 100-Continue header.
      java.lang.String oneCookie​(java.lang.String name)
      Returns the value of the cookie with the specified name if it was sent.
      void setIdleTimeout​(java.time.Duration idleTimeout)
      Overrides the idle timeout for this connection.
      void setMaxContentLength​(long maxContentLength)
      Sets the allowed max content length for the request body.
    • 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

        java.lang.String getProtocol()
        The HTTP protocol of the request.

        e.g. "HTTP/1.1

        Returns:
        The HTTP protocol of the request.
      • getRawUri

        java.lang.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

        java.lang.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

        java.lang.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

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

        MultiValueMap<java.lang.String,​java.lang.String> getQueryParams()
        TBD.
        Returns:
        TBD.
      • getCookies

        java.util.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
        java.lang.String oneCookie​(java.lang.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​(java.time.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 transmitted 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.

        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 transmitted content is larger than the provided maxContentLength, an 413 client error will be issued.

        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 transmitted 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.

        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.

        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 org.junit.Assert;
         import ratpack.exec.Promise;
         import ratpack.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;
        
         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));
                 Assert.assertEquals(response.getBody().getText(), "ok");
        
                 String fileContents = Files.asCharSource(file.toFile(), StandardCharsets.UTF_8).read();
                 Assert.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

        java.time.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)
      • getClientCertificate

        java.util.Optional<javax.security.cert.X509Certificate> getClientCertificate()
        The client's verified certificate if the connection was made with HTTPS and client authentication is enabled.
        Returns:
        the client's certificate
        Since:
        1.5
      • add

        <O> Request add​(java.lang.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​(java.lang.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​(java.lang.Class<O> type,
                            java.util.function.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,
                            java.util.function.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