Package tech.greenfield.vertx.irked
Class Request
- java.lang.Object
-
- io.vertx.ext.web.impl.RoutingContextDecorator
-
- tech.greenfield.vertx.irked.Request
-
- All Implemented Interfaces:
io.vertx.ext.web.impl.RoutingContextInternal,io.vertx.ext.web.RoutingContext
public class Request extends io.vertx.ext.web.impl.RoutingContextDecoratorRequest 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 StringUSE_JSON_PRETTY_ENCODER
-
Constructor Summary
Constructors Constructor Description Request(io.vertx.ext.web.RoutingContext outerContext)Create a new request wrapper as aRoutingContextDecoratoraround 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 voidfail(int statusCode)voidfail(Throwable throwable)voidfail(HttpError httpError)Fail helper that wraps Irked HTTP errors in Vert.x-web (final?!) HttpException class that is better handled by the RoutingContextImplstatic Controller.WebHandlerfailureHandler()Helper to easily configure standard failure handlers.<G extends Throwable>
GfindFailure(Class<G> failureType)When looking at a failed routing context, try to find a specific type of exception from the failure and cause chain.AuthorizationTokengetAuthorization()Helper for authorization header parsing<T> TgetBodyAs(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 usingRoutingContext.getBodyAsJson()then mapped to the bean type usingJsonObject.mapTo(Class)*application/x-www-form-urlencoded- the body is read usingHttpServerRequest.formAttributes()into aJsonObjectas keys with string values, then mapped to the bean type usingJsonObject.mapTo(Class).VoidhandleFailure(Throwable throwable)Helper failure handler for Promise/CompletableFuture users.<V> VhandlePossibleFailure(V successValue, Throwable throwable)Helper failure handler for CompletableFuture users.booleanisHead()Check if this request is a HEAD request, in which casesendContent(Buffer, HttpError, String)will not send any content (but will send all headers including content-type and content-length).booleanneedUpgrade()Check if the client requested a connection upgrade, regardless which type of upgrade is required.booleanneedUpgrade(String type)check if the client requested a specific connection upgrade.voidnext()<T> voidnext(T value)Helper to attachnext()to Vert.xFuture.onSuccess(io.vertx.core.Handler)handler.io.vertx.core.http.HttpServerResponseresponse(HttpError status)Helper method to generate response with the specified HTTP statusio.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 responseio.vertx.core.Future<Void>send(io.vertx.core.json.JsonArray list)Helper method to terminate request processing with an HTTP OK and a JSON responseio.vertx.core.Future<Void>send(io.vertx.core.json.JsonObject object)Helper method to terminate request processing with an HTTP OK and a JSON responseio.vertx.core.Future<Void>send(Object object)Helper method to terminate request processing with an HTTP OK and a JSON responseio.vertx.core.Future<Void>send(String content)Helper method to terminate request processing with an HTTP OK and a text/plain responseio.vertx.core.Future<Void>send(HttpError status)Helper method to terminate request processing with a non-OK HTTP response with default textio.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 ofJson-encoded objectsio.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 POJOio.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) usingsend(Object)if the result is a successful result, or handle the failure usinghandleFailure(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 ofJson-encoded objects.RequestsetJsonEncoding(boolean usePrettyEncoder)Set the built-in JSON encoding behavior of Request to use either theJson.encodePrettily(Object)behavior instead of the standard compact encoding, or not.RequestsetSpecificFailure(Throwable failure)Store a specific exception type, supposedly that was found by am@OnFail(exception)processor so it can be efficiently retrieved byfindFailure(Class).HttpErrorstatusFromResponseCode()HttpErrorstatusFromResponseCode(int statusCode)HttpErrorstatusFromResponseCode(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 class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
-
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
-
-
-
-
Field Detail
-
USE_JSON_PRETTY_ENCODER
public static final String USE_JSON_PRETTY_ENCODER
- See Also:
- Constant Field Values
-
-
Constructor Detail
-
Request
public Request(io.vertx.ext.web.RoutingContext outerContext)
Create a new request wrapper as aRoutingContextDecoratoraround the specified parent routing context (what vertx-web calls "inner context"). This is an internal constructor to be used byRouter- 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 theJson.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'sController.getRequestContext(Request)override.- Parameters:
usePrettyEncoder- set totrueto enable the pretty encoder- Returns:
- itself for fluent calls
-
next
public void next()
- Specified by:
nextin interfaceio.vertx.ext.web.RoutingContext- Overrides:
nextin classio.vertx.ext.web.impl.RoutingContextDecorator
-
next
public <T> void next(T value)
Helper to attachnext()to Vert.xFuture.onSuccess(io.vertx.core.Handler)handler. The input value is ignored and it is just defined so that you can doasyncAPI().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:
failin interfaceio.vertx.ext.web.RoutingContext- Overrides:
failin classio.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:
failin interfaceio.vertx.ext.web.RoutingContext- Overrides:
failin classio.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 callfail(Throwable)after unwrappingRuntimeExceptions as needed.- Parameters:
throwable- AThrowableerror 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 callfail(Throwable)if a failure occurred, after unwrappingRuntimeExceptions 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 callingRoutingContextDecorator.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 occurredthrowable- AThrowableerror 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 issueRoutingContext.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 usingRoutingContext.getBodyAsJson()then mapped to the bean type usingJsonObject.mapTo(Class)*application/x-www-form-urlencoded- the body is read usingHttpServerRequest.formAttributes()into aJsonObjectas keys with string values, then mapped to the bean type usingJsonObject.mapTo(Class). If the same key is present multiple times, the values will be stored into the JsonObject as aJsonArraywith string values. If no content-type header is specified in the request,application/jsonis assumed. If no body is present, this method will throw an uncheckedMissingBodyException- 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 byhandleFailure(Throwable)) and that wraps the originalDecodeExceptionif 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-JsonObjectcontaining 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-JsonArraycontaining 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-JsonObjectcontaining the output to encodestatus- 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 objectstatus- 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-JsonArraycontaining the output to encodestatus- 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 responsestatus- An HttpError object representing the HTTP status to be sentcontentType- 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 responsestatus- An HttpError object representing the HTTP status to be sentcontentType- 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 responsecontentType- 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 responsestatus- 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 theHttpError'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-JsonObjectof 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-JsonArrayof 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-HttpErrorto 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 ofJson-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 ofJson-encoded objects. Please note that the response will be buffered in memory using aJsonArraybased 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 andHttpErrors 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) usingsend(Object)if the result is a successful result, or handle the failure usinghandleFailure(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.
-
getAuthorization
public AuthorizationToken getAuthorization()
Helper for authorization header parsing- Returns:
- A parsed
AuthorizationToken
-
isHead
public boolean isHead()
Check if this request is a HEAD request, in which casesendContent(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
nullif 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 byfindFailure(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)
-
-