Class Request

  • All Implemented Interfaces:
    io.vertx.ext.web.impl.RoutingContextInternal, io.vertx.ext.web.RoutingContext

    public class Request
    extends io.vertx.ext.web.impl.RoutingContextDecorator
    Request handling wrapper which adds some useful routines for API writers. Can serve as a basis for local context parsers that API writers can use to expose path arguments from parent prefixes
    Author:
    odeda
    • Field Summary

      Fields 
      Modifier and Type Field Description
      static String USE_JSON_PRETTY_ENCODER  
      • Fields inherited from interface io.vertx.ext.web.impl.RoutingContextInternal

        BODY_HANDLER, CORS_HANDLER, CSRF_HANDLER, SESSION_HANDLER
    • Constructor Summary

      Constructors 
      Constructor Description
      Request​(io.vertx.ext.web.RoutingContext outerContext)
      Create a new request wrapper as a RoutingContextDecorator around the specified parent routing context (what vertx-web calls "inner context").
    • Method Summary

      All Methods Static Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      void fail​(int statusCode)  
      void fail​(Throwable throwable)  
      void fail​(HttpError httpError)
      Fail helper that wraps Irked HTTP errors in Vert.x-web (final?!) HttpException class that is better handled by the RoutingContextImpl
      static Controller.WebHandler failureHandler()
      Helper to easily configure standard failure handlers.
      <G extends Throwable>
      G
      findFailure​(Class<G> failureType)
      When looking at a failed routing context, try to find a specific type of exception from the failure and cause chain.
      AuthorizationToken getAuthorization()
      Helper for authorization header parsing
      <T> T getBodyAs​(Class<T> type)
      Convert request body to an instance of the specified POJO Currently the followed request body content types are supported: * application/json - the body is read using RoutingContext.getBodyAsJson() then mapped to the bean type using JsonObject.mapTo(Class) * application/x-www-form-urlencoded - the body is read using HttpServerRequest.formAttributes() into a JsonObject as keys with string values, then mapped to the bean type using JsonObject.mapTo(Class).
      Void handleFailure​(Throwable throwable)
      Helper failure handler for Promise/CompletableFuture users.
      <V> V handlePossibleFailure​(V successValue, Throwable throwable)
      Helper failure handler for CompletableFuture users.
      boolean isHead()
      Check if this request is a HEAD request, in which case sendContent(Buffer, HttpError, String) will not send any content (but will send all headers including content-type and content-length).
      boolean needUpgrade()
      Check if the client requested a connection upgrade, regardless which type of upgrade is required.
      boolean needUpgrade​(String type)
      check if the client requested a specific connection upgrade.
      void next()  
      <T> void next​(T value)
      Helper to attach next() to Vert.x Future.onSuccess(io.vertx.core.Handler) handler.
      io.vertx.core.http.HttpServerResponse response​(HttpError status)
      Helper method to generate response with the specified HTTP status
      io.vertx.core.Future<Void> send​(io.vertx.core.buffer.Buffer buffer)
      Helper method to terminate request processing with an HTTP OK and a application/octet-stream response
      io.vertx.core.Future<Void> send​(io.vertx.core.json.JsonArray list)
      Helper method to terminate request processing with an HTTP OK and a JSON response
      io.vertx.core.Future<Void> send​(io.vertx.core.json.JsonObject object)
      Helper method to terminate request processing with an HTTP OK and a JSON response
      io.vertx.core.Future<Void> send​(Object object)
      Helper method to terminate request processing with an HTTP OK and a JSON response
      io.vertx.core.Future<Void> send​(String content)
      Helper method to terminate request processing with an HTTP OK and a text/plain response
      io.vertx.core.Future<Void> send​(HttpError status)
      Helper method to terminate request processing with a non-OK HTTP response with default text
      io.vertx.core.Future<Void> sendContent​(io.vertx.core.buffer.Buffer content, HttpError status, String contentType)
      Helper method to terminate request processing with a custom response containing some data and the specified status line.
      io.vertx.core.Future<Void> sendContent​(String content)
      Helper method to terminate request processing with a custom response containing some text and the specifeid status line.
      io.vertx.core.Future<Void> sendContent​(String content, String contentType)
      Helper method to terminate request processing with a custom response containing some text and the specifeid status line.
      io.vertx.core.Future<Void> sendContent​(String content, HttpError status)
      Helper method to terminate request processing with a custom response containing some text and the specifeid status line.
      io.vertx.core.Future<Void> sendContent​(String content, HttpError status, String contentType)
      Helper method to terminate request processing with a custom response containing some text and the specified status line.
      io.vertx.core.Future<Void> sendError​(HttpError status)
      Helper method to terminate request processing with an HTTP error (non-200 OK) response.
      io.vertx.core.Future<Void> sendJSON​(io.vertx.core.json.JsonArray json)
      Helper method to terminate request processing with a success (200 OK) response containing a JSON body.
      io.vertx.core.Future<Void> sendJSON​(io.vertx.core.json.JsonArray json, HttpError status)
      Helper method to terminate request processing with a custom response containing a JSON body and the specified status line.
      io.vertx.core.Future<Void> sendJSON​(io.vertx.core.json.JsonObject json)
      Helper method to terminate request processing with a success (200 OK) response containing a JSON body.
      io.vertx.core.Future<Void> sendJSON​(io.vertx.core.json.JsonObject json, HttpError status)
      Helper method to terminate request processing with a custom response containing a JSON body and the specified status line.
      <G> io.vertx.core.Future<Void> sendList​(List<G> list)
      Helper method to terminate request processing with an HTTP OK and an application/json response containing a list of Json-encoded objects
      io.vertx.core.Future<Void> sendObject​(Object data)
      Helper method to terminate a request processing with a success (200 OK) response containing a JSON object mapped from the specified POJO
      io.vertx.core.Future<Void> sendObject​(Object data, HttpError status)
      Helper method to terminate a request processing with a custom response containing a JSON object mapped from the specified POJO and the specified status line.
      <T> io.vertx.core.Future<Void> sendOrFail​(io.vertx.core.AsyncResult<T> result)
      Helper method to terminate request processing with either an HTTP OK (or whatever response status is currently set) using send(Object) if the result is a successful result, or handle the failure using handleFailure(Throwable) if the result is of a failure.
      <G> io.vertx.core.Future<Void> sendStream​(Stream<G> stream)
      Helper method to terminate request processing with an HTTP OK and an application/json response containing a stream of Json-encoded objects.
      Request setJsonEncoding​(boolean usePrettyEncoder)
      Set the built-in JSON encoding behavior of Request to use either the Json.encodePrettily(Object) behavior instead of the standard compact encoding, or not.
      Request setSpecificFailure​(Throwable failure)
      Store a specific exception type, supposedly that was found by am @OnFail(exception) processor so it can be efficiently retrieved by findFailure(Class).
      HttpError statusFromResponseCode()  
      HttpError statusFromResponseCode​(int statusCode)  
      HttpError statusFromResponseCode​(int statusCode, String statusMessage)  
      • Methods inherited from class io.vertx.ext.web.impl.RoutingContextDecorator

        addBodyEndHandler, addCookie, addEndHandler, addHeadersEndHandler, body, cancelAndCleanupFileUploads, clearUser, cookieCount, cookieMap, currentRoute, currentRouter, data, fail, failed, failure, fileUploads, get, get, getAcceptableContentType, getCookie, isSessionAccessed, mountPoint, normalizedMatch, normalizedPath, parent, parsedHeaders, pathParam, pathParams, put, queryParam, queryParams, queryParams, remove, removeBodyEndHandler, removeCookie, removeEndHandler, removeHeadersEndHandler, request, reroute, response, restIndex, seenHandler, session, setAcceptableContentType, setBody, setMatchFailure, setSession, setUser, statusCode, user, userContext, vertx, visitHandler
      • Methods inherited from interface io.vertx.ext.web.RoutingContext

        acceptableLanguages, addEndHandler, attachment, end, end, end, end, end, end, etag, getBody, getBodyAsJson, getBodyAsJson, getBodyAsJsonArray, getBodyAsJsonArray, getBodyAsString, getBodyAsString, is, isFresh, json, json, lastModified, lastModified, normalisedPath, preferredLanguage, redirect, redirect, removeCookie, reroute
      • Methods inherited from interface io.vertx.ext.web.impl.RoutingContextInternal

        basePath
    • Constructor Detail

      • Request

        public Request​(io.vertx.ext.web.RoutingContext outerContext)
        Create a new request wrapper as a RoutingContextDecorator around the specified parent routing context (what vertx-web calls "inner context"). This is an internal constructor to be used by Router - use at your own risk.
        Parameters:
        outerContext - parent routing context to wrap
    • Method Detail

      • setJsonEncoding

        public Request setJsonEncoding​(boolean usePrettyEncoder)
        Set the built-in JSON encoding behavior of Request to use either the Json.encodePrettily(Object) behavior instead of the standard compact encoding, or not. To enable this behavior to an entire controller hierarchy, use it in the controller's Controller.getRequestContext(Request) override.
        Parameters:
        usePrettyEncoder - set to true to enable the pretty encoder
        Returns:
        itself for fluent calls
      • next

        public void next()
        Specified by:
        next in interface io.vertx.ext.web.RoutingContext
        Overrides:
        next in class io.vertx.ext.web.impl.RoutingContextDecorator
      • next

        public <T> void next​(T value)
        Helper to attach next() to Vert.x Future.onSuccess(io.vertx.core.Handler) handler. The input value is ignored and it is just defined so that you can do asyncAPI().onSuccess(r::next) You often will want to store the result on the routing context for use in the next handler, so a more complete example might look like this:
        
         asyncAPI()
         .onSuccess(data -> r.put("data", data))
         .onSuccess(r::next)
         .onFailure(r::handleFailure);
         
        Type Parameters:
        T - Type of value provided by handler caller, that will be ignored
        Parameters:
        value - result provided by handler caller, that will be ignored
      • fail

        public void fail​(int statusCode)
        Specified by:
        fail in interface io.vertx.ext.web.RoutingContext
        Overrides:
        fail in class io.vertx.ext.web.impl.RoutingContextDecorator
      • fail

        public void fail​(HttpError httpError)
        Fail helper that wraps Irked HTTP errors in Vert.x-web (final?!) HttpException class that is better handled by the RoutingContextImpl
        Parameters:
        httpError - error to fail with
      • fail

        public void fail​(Throwable throwable)
        Specified by:
        fail in interface io.vertx.ext.web.RoutingContext
        Overrides:
        fail in class io.vertx.ext.web.impl.RoutingContextDecorator
      • handleFailure

        public Void handleFailure​(Throwable throwable)
        Helper failure handler for Promise/CompletableFuture users. Use at the end of an async chain to succinctly propagate exceptions, such as: .onFailure(r::handleFailure) or .exceptionally(req::handleFailure). This method will call fail(Throwable) after unwrapping RuntimeExceptions as needed.
        Parameters:
        throwable - A Throwable error to fail on
        Returns:
        null
      • handlePossibleFailure

        public <V> V handlePossibleFailure​(V successValue,
                                           Throwable throwable)
        Helper failure handler for CompletableFuture users. Use in the middle an async chain to succinctly propagate exceptions, or success values as thus: .whenComplete(req::handlePossibleFailure). This method will call fail(Throwable) if a failure occurred, after unwrapping RuntimeExceptions as needed. It will also pass on the success value (or null if there was a failure) for the next async element. Subsequent code can check whether a failure was propagated by calling RoutingContextDecorator.failed()
        Type Parameters:
        V - the type of previous completion value that will be returned as the completion value for completion stages running this method
        Parameters:
        successValue - successful completion value to return in case no failure occurred
        throwable - A Throwable error to fail on
        Returns:
        null
      • failureHandler

        public static Controller.WebHandler failureHandler()
        Helper to easily configure standard failure handlers. This handler will convert failed requests (contexts with a failure set) to HTTP error responses, and will issue RoutingContext.next() for all other context, including context for which the response has already been sent.
        Returns:
        a WebHandler that sends Irked status exceptions as HTTP responses
      • getBodyAs

        public <T> T getBodyAs​(Class<T> type)
        Convert request body to an instance of the specified POJO Currently the followed request body content types are supported: * application/json - the body is read using RoutingContext.getBodyAsJson() then mapped to the bean type using JsonObject.mapTo(Class) * application/x-www-form-urlencoded - the body is read using HttpServerRequest.formAttributes() into a JsonObject as keys with string values, then mapped to the bean type using JsonObject.mapTo(Class). If the same key is present multiple times, the values will be stored into the JsonObject as a JsonArray with string values. If no content-type header is specified in the request, application/json is assumed. If no body is present, this method will throw an unchecked MissingBodyException - i.e. a "Bad Request" HTTP error with the text "Required request body is missing".
        Type Parameters:
        T - Result type into which the body will be decoded
        Parameters:
        type - The class from which an instance should be created to hold the body content
        Returns:
        An object of the specified type that was initialized using the Vert.x JSON decoder API
        Throws:
        RuntimeException - in case of a JSON decoding problem. The thrown exception wraps a BadRequest exception with a REST API friendly error message (so it can be handled automatically by handleFailure(Throwable)) and that wraps the original DecodeException if the caller wants to extract it and parse it themselves
        API Note:
        this API is very similar to the Vert.x 4.3 API RequestBody.asPojo(Class). The notable difference is that this implementation checks the request Content-Type and if its a form POST, it will read the form post fields to mimic a JSON object. This may or may not be a desired behavior.
      • sendJSON

        public io.vertx.core.Future<Void> sendJSON​(io.vertx.core.json.JsonObject json)
        Helper method to terminate request processing with a success (200 OK) response containing a JSON body.
        Parameters:
        json - JsonObject containing the output to encode
        Returns:
        a promise that will complete when the body was sent successfully
      • sendObject

        public io.vertx.core.Future<Void> sendObject​(Object data)
        Helper method to terminate a request processing with a success (200 OK) response containing a JSON object mapped from the specified POJO
        Parameters:
        data - POJO containing the data to map to a JSON encoded object
        Returns:
        a promise that will complete when the body was sent successfully
      • sendJSON

        public io.vertx.core.Future<Void> sendJSON​(io.vertx.core.json.JsonArray json)
        Helper method to terminate request processing with a success (200 OK) response containing a JSON body.
        Parameters:
        json - JsonArray containing the output to encode
        Returns:
        a promise that will complete when the body was sent successfully
      • sendJSON

        public io.vertx.core.Future<Void> sendJSON​(io.vertx.core.json.JsonObject json,
                                                   HttpError status)
        Helper method to terminate request processing with a custom response containing a JSON body and the specified status line.
        Parameters:
        json - JsonObject containing the output to encode
        status - An HttpError object representing the HTTP status to be sent
        Returns:
        a promise that will complete when the body was sent successfully
      • sendObject

        public io.vertx.core.Future<Void> sendObject​(Object data,
                                                     HttpError status)
        Helper method to terminate a request processing with a custom response containing a JSON object mapped from the specified POJO and the specified status line.
        Parameters:
        data - POJO containing the data to map to a JSON encoded object
        status - An HttpError object representing the HTTP status to be sent
        Returns:
        a promise that will complete when the body was sent successfully
      • sendJSON

        public io.vertx.core.Future<Void> sendJSON​(io.vertx.core.json.JsonArray json,
                                                   HttpError status)
        Helper method to terminate request processing with a custom response containing a JSON body and the specified status line.
        Parameters:
        json - JsonArray containing the output to encode
        status - HTTP status to send
        Returns:
        a promise that will complete when the body was sent successfully
      • sendContent

        public io.vertx.core.Future<Void> sendContent​(String content,
                                                      HttpError status,
                                                      String contentType)
        Helper method to terminate request processing with a custom response containing some text and the specified status line.
        Parameters:
        content - Text content to send in the response
        status - An HttpError object representing the HTTP status to be sent
        contentType - The MIME Content-Type to be set for the response
        Returns:
        a promise that will complete when the body was sent successfully
      • sendContent

        public io.vertx.core.Future<Void> sendContent​(io.vertx.core.buffer.Buffer content,
                                                      HttpError status,
                                                      String contentType)
        Helper method to terminate request processing with a custom response containing some data and the specified status line.
        Parameters:
        content - Binary content to send in the response
        status - An HttpError object representing the HTTP status to be sent
        contentType - The MIME Content-Type to be set for the response
        Returns:
        a promise that will resolve when the body was sent successfully
      • sendContent

        public io.vertx.core.Future<Void> sendContent​(String content,
                                                      String contentType)
        Helper method to terminate request processing with a custom response containing some text and the specifeid status line.
        Parameters:
        content - Text content to send in the response
        contentType - The MIME Content-Type to be set for the response
        Returns:
        a promise that will complete when the body was sent successfully
      • sendContent

        public io.vertx.core.Future<Void> sendContent​(String content,
                                                      HttpError status)
        Helper method to terminate request processing with a custom response containing some text and the specifeid status line.
        Parameters:
        content - Text content to send in the response
        status - An HttpError object representing the HTTP status to be sent
        Returns:
        a promise that will complete when the body was sent successfully
      • sendContent

        public io.vertx.core.Future<Void> sendContent​(String content)
        Helper method to terminate request processing with a custom response containing some text and the specifeid status line.
        Parameters:
        content - Text content to send in the response
        Returns:
        a promise that will complete when the body was sent successfully
      • sendError

        public io.vertx.core.Future<Void> sendError​(HttpError status)
        Helper method to terminate request processing with an HTTP error (non-200 OK) response. The resulting HTTP response will have the correct status line and an application/json content with a JSON encoded object containing the fields "status" set to "false" and "message" set to the HttpError's message.
        Parameters:
        status - An HttpError object representing the HTTP status to be sent
        Returns:
        a promise that will complete when the body was sent successfully
      • send

        public io.vertx.core.Future<Void> send​(io.vertx.core.json.JsonObject object)
        Helper method to terminate request processing with an HTTP OK and a JSON response
        Parameters:
        object - JsonObject of data to send
        Returns:
        a promise that will complete when the body was sent successfully
      • send

        public io.vertx.core.Future<Void> send​(io.vertx.core.json.JsonArray list)
        Helper method to terminate request processing with an HTTP OK and a JSON response
        Parameters:
        list - JsonArray of a list of data to send
        Returns:
        a promise that will complete when the body was sent successfully
      • send

        public io.vertx.core.Future<Void> send​(String content)
        Helper method to terminate request processing with an HTTP OK and a text/plain response
        Parameters:
        content - text to send
        Returns:
        a promise that will complete when the body was sent successfully
      • send

        public io.vertx.core.Future<Void> send​(io.vertx.core.buffer.Buffer buffer)
        Helper method to terminate request processing with an HTTP OK and a application/octet-stream response
        Parameters:
        buffer - binary data to send
        Returns:
        a promise that will complete when the body was sent successfully
      • send

        public io.vertx.core.Future<Void> send​(HttpError status)
        Helper method to terminate request processing with a non-OK HTTP response with default text
        Parameters:
        status - HttpError to send
        Returns:
        a promise that will complete when the body was sent successfully
      • sendList

        public <G> io.vertx.core.Future<Void> sendList​(List<G> list)
        Helper method to terminate request processing with an HTTP OK and an application/json response containing a list of Json-encoded objects
        Type Parameters:
        G - type of objects in the list
        Parameters:
        list - List to convert to a JSON array for sending
        Returns:
        a promise that will complete when the body was sent successfully
      • sendStream

        public <G> io.vertx.core.Future<Void> sendStream​(Stream<G> stream)
        Helper method to terminate request processing with an HTTP OK and an application/json response containing a stream of Json-encoded objects. Please note that the response will be buffered in memory using a JsonArray based collector.
        Type Parameters:
        G - type of objects in the stream
        Parameters:
        stream - Stream to convert to a JSON array for sending
        Returns:
        a promise that will complete when the body was sent successfully
      • send

        public io.vertx.core.Future<Void> send​(Object object)
        Helper method to terminate request processing with an HTTP OK and a JSON response
        Parameters:
        object - any object that make sense to convert to JSON for sending. Converts lists and streams to arrays using sendList(List) and sendStream(Stream); exceptions and HttpErrors to HTTP status descriptions using sendError(HttpError) and everything else maps to JSON using sendObject(java.lang.Object).
        Returns:
        a promise that will complete when the body was sent successfully
      • sendOrFail

        public <T> io.vertx.core.Future<Void> sendOrFail​(io.vertx.core.AsyncResult<T> result)
        Helper method to terminate request processing with either an HTTP OK (or whatever response status is currently set) using send(Object) if the result is a successful result, or handle the failure using handleFailure(Throwable) if the result is of a failure. This can be used as a shorthand for the common pattern of .compose(req::send).onFailure(req::handleFailure), instead the request processing chain can be terminated using either of these patterns:
        • … .onComplete(req::sendOrFail);
        • … .andThen(req::sendOrFail);
        • … .transform(req::sendOrFail);

        In the first two cases, the sendOrFail(AsyncResult) method has no side effects for the composition. In the last case, the result of the transform is a Future<Void> that will fail if either the previous step has failed - with the original cause - or if the send(Object) has failed - with the send failure cause - or will succeed if the send(Object) has succeeded. But you will probably not care about the difference if you use this as a terminal operation.

        Type Parameters:
        T - Type of value in a successful result
        Parameters:
        result - a possible success or failure result
        Returns:
        a promise that will fail if the result has failed or if sending a successful result has failed, or will succeed if sending the successful result has succeeded.
      • response

        public io.vertx.core.http.HttpServerResponse response​(HttpError status)
        Helper method to generate response with the specified HTTP status
        Parameters:
        status - HTTP status code and text to set on the response
        Returns:
        HTTP response created using RoutingContext.response()
      • needUpgrade

        public boolean needUpgrade()
        Check if the client requested a connection upgrade, regardless which type of upgrade is required.
        Returns:
        true if the request includes a 'Connection: upgrade' header.
      • needUpgrade

        public boolean needUpgrade​(String type)
        check if the client requested a specific connection upgrade.
        Parameters:
        type - What upgrade type to test against, case insensitive
        Returns:
        true if the request includes a 'Connection: upgrade' header and an 'Upgrade' header with the specified type.
      • isHead

        public boolean isHead()
        Check if this request is a HEAD request, in which case sendContent(Buffer, HttpError, String) will not send any content (but will send all headers including content-type and content-length).
        Returns:
        whether the request is a HEAD request
      • findFailure

        public <G extends Throwable> G findFailure​(Class<G> failureType)
        When looking at a failed routing context, try to find a specific type of exception from the failure and cause chain. This helper makes the @OnFail(exception) annotation useful by allowing the user to quickly extract the specific exception instance they are looking for.
        Type Parameters:
        G - Type of exception to extract
        Parameters:
        failureType - the class of the exception to extract
        Returns:
        The top-most exception of the specified type from the failure and cause chain, or null if this request has not failed yet or the specified type isn't found in the failure chain
      • setSpecificFailure

        public Request setSpecificFailure​(Throwable failure)
        Store a specific exception type, supposedly that was found by am @OnFail(exception) processor so it can be efficiently retrieved by findFailure(Class).
        Parameters:
        failure - specific failure found by the @OnFail(exception) processor
        Returns:
        itself, for fleunt access
      • statusFromResponseCode

        public HttpError statusFromResponseCode()
      • statusFromResponseCode

        public HttpError statusFromResponseCode​(int statusCode)
      • statusFromResponseCode

        public HttpError statusFromResponseCode​(int statusCode,
                                                String statusMessage)