Interface Context
A context is thread-confined: use it only on the thread that invoked the handler and
only until the handler returns. It holds mutable response settings (status(int)) without
synchronization and must not be shared with, or retained by, other threads. To hand work to
application tasks, pass the immutable execution() and request() values or the
extracted captures instead.
-
Method Summary
Modifier and TypeMethodDescriptiondefault ResponseReturns the answer the application gives an OPTIONS request that no route serves: 204 with no body and anAllowheader listing every method registered on any template that matches the request path,HEADwhereverGETis, andOPTIONS, sorted alphabetically (forOPTIONS *, every registered method).<T> TDecodes the request body with the installed codec for its Content-Type.default BodyReaderReturns the incremental reader for this request's body, when the runtime supplied one.default StringDescribes this request for a log message without a thread-local map: the framework's request ID, followed bytrace=<trace id>when the caller sent a validtraceparent.default ResponseEncodes an object with the installed codec for the supplied Content-Type during this call.Returns immutable identity and deadline metadata for this invocation.Returns a request header value, matching the name case-insensitively.default Optional<SecurityIdentity> identity()Returns the authenticated caller of this request, if authentication middleware attached one.default Contextidentity(SecurityIdentity identity) Attaches the authenticated caller to this request.default ResponseMaps a value to a JSON response using the current status (200 by default).Returns the matched route identity, or empty when the router answers the request itself (404, 405, automatic OPTIONS,OPTIONS *, 501).default Stringmethod()Returns the case-sensitive HTTP method.default ResponseReturns a 204 response with no body.default Stringpath()Returns the raw path, without decoding or normalization.Reads a raw path capture without percent-decoding or normalization.default StringpathDecoded(String name) Reads a path capture with strict, single-pass UTF-8 percent-decoding.default intReads a raw path capture as anint, with the rules ofqueryInt(String).default longReads a raw path capture as along; seepathInt(String).Returns all raw captures in template order.default UUIDReads a raw path capture as aUUID, with the rules ofqueryUuid(String); seepathInt(String)for the failure.default Responseproblem(AxiomException failure) Builds the standard problem response for an exception: its status, the typed headers it carries (Allow,Retry-After,WWW-Authenticate),application/problem+jsonand a body of only status, code, this request's ID and the violations, exactly what the runtime sends for it when no error handler is registered.Returns the first value of a query parameter, percent-decoded as strict UTF-8 with+decoded as a space.Returns every value of a query parameter in request order, decoded as byquery(String).Returns the first value of a query parameter as anint.Returns the first value of a query parameter as along, with the rules and the failure ofqueryInt(String).Returns the first value of a query parameter as aUUID.default ResponseReturns a redirect without a body.request()Returns the immutable request metadata.Maps a body using the current status (200 by default).route()Returns the matched route identity, including its template rather than request values.status(int status) Sets the status for subsequent response mapping.default ResponseCreates a text response using the current settings.default Optional<TraceContext> Returns the W3C trace context the caller sent in atraceparentheader, if it is valid, with thetracestatethat came with it (empty if absent or invalid).default <T> TvalidatedBody(Class<T> type, BodyValidator<? super T> validator) Decodes the request body asbody(Class)does, then checks it.
-
Method Details
-
request
Request request()Returns the immutable request metadata.- Returns:
- the immutable request metadata
-
execution
ExecutionContext execution()Returns immutable identity and deadline metadata for this invocation. The request ID in it is a correlation value that appears in response headers, problem bodies and logs; it is predictable and must never be used as a secret or credential.- Returns:
- execution context, safe to share with application tasks
-
identity
Returns the authenticated caller of this request, if authentication middleware attached one. Empty means anonymous: no authenticator ran, or the request carried no credentials. Error handlers see the identity set before the failure.- Returns:
- the request's identity, if any
-
identity
Attaches the authenticated caller to this request. Authentication middleware call this once credentials have been verified; handlers and inner middleware then read it withidentity(). The identity can be set at most once per request, so code that runs later in the chain cannot replace a verified identity with another one. It lives as long as the context: it is never shared with other requests and is gone when the request ends.- Parameters:
identity- verified identity- Returns:
- this context
- Throws:
IllegalStateException- if an identity is already setUnsupportedOperationException- if this context cannot hold an identity (the runtime's contexts can; this default exists for application test doubles)
-
traceContext
Returns the W3C trace context the caller sent in atraceparentheader, if it is valid, with thetracestatethat came with it (empty if absent or invalid). Parsing is strict (seeTraceContextandTraceState); an absent, malformed or unsupported header yields empty and never fails the request. The value is caller-chosen: use it to correlate logs and downstream calls, never for authorization, and do not use it as a metric tag.ctx.execution().requestId()remains the framework's own identity.- Returns:
- the caller's trace context, if any
-
correlation
Describes this request for a log message without a thread-local map: the framework's request ID, followed bytrace=<trace id>when the caller sent a validtraceparent. It is the text the framework puts in its own log messages, for examplelogger.log(INFO, "charged " + ctx.correlation()). The trace id is the caller's choice (validated, but not trusted), so it is for correlation only.- Returns:
requestIdorrequestId trace=traceId
-
method
Returns the case-sensitive HTTP method.- Returns:
- the case-sensitive HTTP method
-
path
Returns the raw path, without decoding or normalization.- Returns:
- the raw path, without decoding or normalization
-
header
Returns a request header value, matching the name case-insensitively. Header values are untrusted client input.- Parameters:
name- header name- Returns:
- value, if present
-
query
Returns the first value of a query parameter, percent-decoded as strict UTF-8 with+decoded as a space. Names match exactly after decoding. A parameter without=has an empty value. The query was validated when the request was created, so decoding cannot fail here. Values are untrusted client input.- Parameters:
name- decoded parameter name- Returns:
- first value, if the parameter is present
- See Also:
-
queryAll
Returns every value of a query parameter in request order, decoded as byquery(String).- Parameters:
name- decoded parameter name- Returns:
- immutable values; empty when the parameter is absent
- See Also:
-
queryInt
Returns the first value of a query parameter as anint. Accepts an optional leading-and one to 19 ASCII digits (no+, spaces, separators or exponent); leading zeros are accepted within that length. An absent parameter is empty. A parameter that is present but not anint(including the empty value and one out of range) is the client's error: the failure is aBadRequestExceptionwith codeinvalid_query_parameter, answered 400 like any otherAxiomException; it never carries the value or the name. A repeated parameter uses its first value, asquery(String)does.- Parameters:
name- decoded parameter name- Returns:
- the value, if the parameter is present
- Throws:
BadRequestException- if the value is not anint
-
queryLong
Returns the first value of a query parameter as along, with the rules and the failure ofqueryInt(String).- Parameters:
name- decoded parameter name- Returns:
- the value, if the parameter is present
- Throws:
BadRequestException- with codeinvalid_query_parameterif the value is not along
-
queryUuid
Returns the first value of a query parameter as aUUID. Accepts only the canonical 36-character form,8-4-4-4-12hexadecimal digits in either case, and nothing else (the lenient forms ofUUID.fromString(java.lang.String)are rejected). The failure is as forqueryInt(String).- Parameters:
name- decoded parameter name- Returns:
- the value, if the parameter is present
- Throws:
BadRequestException- with codeinvalid_query_parameterif the value is not a UUID
-
pathInt
Reads a raw path capture as anint, with the rules ofqueryInt(String). A capture that is not anintis the client's error: aBadRequestExceptionwith codeinvalid_path_parameter, answered 400, which never carries the value. Captures are not percent-decoded first, so an escaped digit is not a number.- Parameters:
name- capture name declared in the route template- Returns:
- the value
- Throws:
IllegalArgumentException- if the name is not declared by the matched routeBadRequestException- if the capture is not anint
-
pathLong
Reads a raw path capture as along; seepathInt(String).- Parameters:
name- capture name declared in the route template- Returns:
- the value
- Throws:
IllegalArgumentException- if the name is not declared by the matched routeBadRequestException- with codeinvalid_path_parameterif the capture is not along
-
pathUuid
Reads a raw path capture as aUUID, with the rules ofqueryUuid(String); seepathInt(String)for the failure.- Parameters:
name- capture name declared in the route template- Returns:
- the value
- Throws:
IllegalArgumentException- if the name is not declared by the matched routeBadRequestException- with codeinvalid_path_parameterif the capture is not a UUID
-
bodyReader
Returns the incremental reader for this request's body, when the runtime supplied one. A reader is supplied to handlers registered asStreamingHandlerand to every request executed through the test client orApplication.handle(Request, ExecutionContext, BodyReader). It is valid only on this thread until the handler returns; the runtime closes it when the exchange ends. Reading it to the end is how a streaming handler consumes the body, andRequest.body()is empty for those requests.- Returns:
- the body reader, never null when supplied
- Throws:
UnsupportedOperationException- if this context has no reader, for example an application test double or a buffered route outside the test client
-
body
Decodes the request body with the installed codec for its Content-Type.Checks run in this order: an empty or missing body fails with
DecodeException(empty_body, 400); a missing or malformed Content-Type fails withUnsupportedMediaTypeException(missing_content_type, 415); acharsetparameter other than UTF-8 fails with codeunsupported_charset(415); a media type without an installed codec fails withunsupported_media_type(415); content the codec cannot decode into the type fails with aDecodeException(400). These exceptions become error responses when they leave the handler. The body has already passed the application's size limit.- Type Parameters:
T- target type- Parameters:
type- target type, for example a record- Returns:
- decoded value, never null
-
validatedBody
Decodes the request body asbody(Class)does, then checks it.
Decoding failures come first and the validator then does not run. When the validator reports violations this throwsvar order = ctx.validatedBody(Order.class, ORDER_RULES);ValidationException, answered 422 with a problem body that lists only each violation's field and code (at most the first 100).- Type Parameters:
T- target type- Parameters:
type- target type, for example a recordvalidator- thread-safe check, such as anaxiom-validationValidator- Returns:
- the decoded, valid value, never null
- Throws:
ValidationException- if the validator reports violationsIllegalStateException- if the validator returns null or a null violation
-
json
Maps a value to a JSON response using the current status (200 by default). The value is encoded by the installedapplication/jsoncodec during this call. Keep the value stable until the call returns; later mutations cannot change the response. AStringorbyte[]value is sent verbatim as already-encoded JSON. An object without an installed JSON codec fails immediately withIllegalStateException.- Parameters:
value- non-null value to encode- Returns:
- response with
Content-Type: application/json - Throws:
IllegalStateException- if the status set on this context cannot carry a body
-
encode
Encodes an object with the installed codec for the supplied Content-Type during this call. The response owns a snapshot of the encoded bytes. Keep the value stable until this method returns; codecs must not retain it. Strings and byte arrays are already encoded and bypass the codec. Accept negotiation still occurs after middleware returns.- Parameters:
contentType- response Content-Type, including optional parametersvalue- non-null body value- Returns:
- response using the current status and supplied Content-Type
- Throws:
IllegalArgumentException- for an invalid content typeIllegalStateException- if an object has no codec, encoding fails or the status cannot carry a bodyUnsupportedOperationException- if a custom context does not implement object encoding
-
status
Sets the status for subsequent response mapping. Statuses 204, 205, and 304 cannot carry a body: after setting one, mapping a non-null body (returning it from the handler or callingresponse(Object)ortext(String)) fails with anIllegalStateExceptionthat names the route and status. Over HTTP that failure is a 500 like any other handler failure.- Parameters:
status- final HTTP status (200-599)- Returns:
- this context
- Throws:
IllegalArgumentException- if the status is not a final status
-
route
Route route()Returns the matched route identity, including its template rather than request values. Handlers, group middleware and route middleware always have one. Global middleware also run for answers the router produces itself (404, 405, automatic OPTIONS, 501), where no route matched; there this method throws, so global middleware should usematchedRoute().- Returns:
- matched route
- Throws:
IllegalStateException- if no route matched this request
-
matchedRoute
Returns the matched route identity, or empty when the router answers the request itself (404, 405, automatic OPTIONS,OPTIONS *, 501). Never throws, so global middleware can use it for every request, for example to log the route template.- Returns:
- matched route, if any
-
path
Reads a raw path capture without percent-decoding or normalization. Captures are untrusted client input. A wildcard remainder may contain/and must not be used as a file system path without the application's own containment checks.- Parameters:
name- capture name declared in the route template- Returns:
- captured segment or wildcard remainder (which may be empty)
- Throws:
IllegalArgumentException- if the name is not declared by the matched route
-
pathDecoded
Reads a path capture with strict, single-pass UTF-8 percent-decoding. Each segment is decoded once; a decoded value is never decoded again. Wildcard remainders keep their raw/separators. Decoding fails rather than producing a/, backslash, or NUL inside a segment, a.or..segment, or malformed UTF-8. The result is still untrusted client input. A capture that cannot be decoded safely is the client's error: the failure is aBadRequestExceptionwith codeinvalid_path_encoding, answered 400 like any otherAxiomException; it never carries the capture.- Parameters:
name- capture name declared in the route template- Returns:
- decoded capture
- Throws:
IllegalArgumentException- if the name is not declared by the matched routeBadRequestException- if the value is malformed UTF-8 or would decode to a separator, NUL or dot segment
-
pathParameters
Returns all raw captures in template order. The map is extracted when the route matches and is immutable, so it may be shared with other threads.- Returns:
- immutable parameter map; empty for a static route
-
automaticOptions
Returns the answer the application gives an OPTIONS request that no route serves: 204 with no body and anAllowheader listing every method registered on any template that matches the request path,HEADwhereverGETis, andOPTIONS, sorted alphabetically (forOPTIONS *, every registered method). It ignores the status set on this context.An explicit OPTIONS route replaces the automatic answer for every path it matches, so a wildcard route such as
/*anywould hide the accurate list of the paths it shares with other templates. A handler of such a route returns this answer for the requests it does not handle itself:
Call it for OPTIONS requests; for another method the list is still the path's.app.options("/*any", ctx -> isPreflight(ctx) ? preflightAnswer(ctx) : ctx.automaticOptions());- Returns:
- 204 response with the Allow header
- Throws:
UnsupportedOperationException- if this context cannot compute it (the runtime's contexts can; this default exists for application test doubles)
-
problem
Builds the standard problem response for an exception: its status, the typed headers it carries (Allow,Retry-After,WWW-Authenticate),application/problem+jsonand a body of only status, code, this request's ID and the violations, exactly what the runtime sends for it when no error handler is registered. AnErrorHandleruses it to decorate the standard answer instead of replacing it:
It does not log, and it is independent of the context's status.app.error(AxiomException.class, (ctx, failure) -> ctx.problem(failure).withHeader("Cache-Control", "no-store"));- Parameters:
failure- the exception to answer, possibly one the handler built itself- Returns:
- the problem response
- Throws:
UnsupportedOperationException- if this context cannot build it (the runtime's contexts can; this default exists for application test doubles)
-
response
Maps a body using the current status (200 by default). Strings use UTF-8 text and byte arrays use application/octet-stream. Other objects are rejected immediately; usejson(Object)to encode them with the JSON codec. Null without an explicit status produces 204.- Parameters:
body- returned body, or null- Returns:
- a response snapshot
- Throws:
IllegalStateException- if the status set on this context cannot carry a bodyIllegalArgumentException- if the body is not String, byte[] or null
-
text
Creates a text response using the current settings.- Parameters:
text- non-null text- Returns:
- a response using the current status
-
redirect
Returns a redirect without a body. UseResponse.withLocation(String)for 201 Created, for examplectx.status(201).json(item).withLocation("/items/" + id).- Parameters:
status- 301, 302, 303, 307 or 308location- target URI reference, validated against header injection- Returns:
- redirect response
- Throws:
IllegalArgumentException- for another status or an invalid location
-
noContent
Returns a 204 response with no body.- Returns:
- a 204 response with no body
-