Interface Context


public interface Context
Request-scoped view and response settings for one handler invocation.

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 Type
    Method
    Description
    default Response
    Returns the answer the application gives an OPTIONS request that no route serves: 204 with no body and an Allow header listing every method registered on any template that matches the request path, HEAD wherever GET is, and OPTIONS, sorted alphabetically (for OPTIONS *, every registered method).
    <T> T
    body(Class<T> type)
    Decodes the request body with the installed codec for its Content-Type.
    default BodyReader
    Returns the incremental reader for this request's body, when the runtime supplied one.
    default String
    Describes this request for a log message without a thread-local map: the framework's request ID, followed by trace=<trace id> when the caller sent a valid traceparent.
    default Response
    encode(String contentType, Object value)
    Encodes an object with the installed codec for the supplied Content-Type during this call.
    Returns immutable identity and deadline metadata for this invocation.
    default Optional<String>
    header(String name)
    Returns a request header value, matching the name case-insensitively.
    Returns the authenticated caller of this request, if authentication middleware attached one.
    default Context
    Attaches the authenticated caller to this request.
    default Response
    json(Object value)
    Maps a value to a JSON response using the current status (200 by default).
    default Optional<Route>
    Returns the matched route identity, or empty when the router answers the request itself (404, 405, automatic OPTIONS, OPTIONS *, 501).
    default String
    Returns the case-sensitive HTTP method.
    default Response
    Returns a 204 response with no body.
    default String
    Returns the raw path, without decoding or normalization.
    path(String name)
    Reads a raw path capture without percent-decoding or normalization.
    default String
    Reads a path capture with strict, single-pass UTF-8 percent-decoding.
    default int
    Reads a raw path capture as an int, with the rules of queryInt(String).
    default long
    Reads a raw path capture as a long; see pathInt(String).
    Returns all raw captures in template order.
    default UUID
    Reads a raw path capture as a UUID, with the rules of queryUuid(String); see pathInt(String) for the failure.
    default Response
    Builds the standard problem response for an exception: its status, the typed headers it carries (Allow, Retry-After, WWW-Authenticate), application/problem+json and 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.
    default Optional<String>
    query(String name)
    Returns the first value of a query parameter, percent-decoded as strict UTF-8 with + decoded as a space.
    default List<String>
    Returns every value of a query parameter in request order, decoded as by query(String).
    default Optional<Integer>
    Returns the first value of a query parameter as an int.
    default Optional<Long>
    Returns the first value of a query parameter as a long, with the rules and the failure of queryInt(String).
    default Optional<UUID>
    Returns the first value of a query parameter as a UUID.
    default Response
    redirect(int status, String location)
    Returns a redirect without a body.
    Returns the immutable request metadata.
    Maps a body using the current status (200 by default).
    Returns the matched route identity, including its template rather than request values.
    status(int status)
    Sets the status for subsequent response mapping.
    default Response
    text(String text)
    Creates a text response using the current settings.
    Returns the W3C trace context the caller sent in a traceparent header, if it is valid, with the tracestate that came with it (empty if absent or invalid).
    default <T> T
    validatedBody(Class<T> type, BodyValidator<? super T> validator)
    Decodes the request body as body(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

      default Optional<SecurityIdentity> 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

      default Context identity(SecurityIdentity identity)
      Attaches the authenticated caller to this request. Authentication middleware call this once credentials have been verified; handlers and inner middleware then read it with identity(). 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 set
      UnsupportedOperationException - if this context cannot hold an identity (the runtime's contexts can; this default exists for application test doubles)
    • traceContext

      default Optional<TraceContext> traceContext()
      Returns the W3C trace context the caller sent in a traceparent header, if it is valid, with the tracestate that came with it (empty if absent or invalid). Parsing is strict (see TraceContext and TraceState); 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

      default String correlation()
      Describes this request for a log message without a thread-local map: the framework's request ID, followed by trace=<trace id> when the caller sent a valid traceparent. It is the text the framework puts in its own log messages, for example logger.log(INFO, "charged " + ctx.correlation()). The trace id is the caller's choice (validated, but not trusted), so it is for correlation only.
      Returns:
      requestId or requestId trace=traceId
    • method

      default String method()
      Returns the case-sensitive HTTP method.
      Returns:
      the case-sensitive HTTP method
    • path

      default String path()
      Returns the raw path, without decoding or normalization.
      Returns:
      the raw path, without decoding or normalization
    • header

      default Optional<String> header(String name)
      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

      default Optional<String> query(String name)
      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

      default List<String> queryAll(String name)
      Returns every value of a query parameter in request order, decoded as by query(String).
      Parameters:
      name - decoded parameter name
      Returns:
      immutable values; empty when the parameter is absent
      See Also:
    • queryInt

      default Optional<Integer> queryInt(String name)
      Returns the first value of a query parameter as an int. 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 an int (including the empty value and one out of range) is the client's error: the failure is a BadRequestException with code invalid_query_parameter, answered 400 like any other AxiomException; it never carries the value or the name. A repeated parameter uses its first value, as query(String) does.
      Parameters:
      name - decoded parameter name
      Returns:
      the value, if the parameter is present
      Throws:
      BadRequestException - if the value is not an int
    • queryLong

      default Optional<Long> queryLong(String name)
      Returns the first value of a query parameter as a long, with the rules and the failure of queryInt(String).
      Parameters:
      name - decoded parameter name
      Returns:
      the value, if the parameter is present
      Throws:
      BadRequestException - with code invalid_query_parameter if the value is not a long
    • queryUuid

      default Optional<UUID> queryUuid(String name)
      Returns the first value of a query parameter as a UUID. Accepts only the canonical 36-character form, 8-4-4-4-12 hexadecimal digits in either case, and nothing else (the lenient forms of UUID.fromString(java.lang.String) are rejected). The failure is as for queryInt(String).
      Parameters:
      name - decoded parameter name
      Returns:
      the value, if the parameter is present
      Throws:
      BadRequestException - with code invalid_query_parameter if the value is not a UUID
    • pathInt

      default int pathInt(String name)
      Reads a raw path capture as an int, with the rules of queryInt(String). A capture that is not an int is the client's error: a BadRequestException with code invalid_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 route
      BadRequestException - if the capture is not an int
    • pathLong

      default long pathLong(String name)
      Reads a raw path capture as a long; see pathInt(String).
      Parameters:
      name - capture name declared in the route template
      Returns:
      the value
      Throws:
      IllegalArgumentException - if the name is not declared by the matched route
      BadRequestException - with code invalid_path_parameter if the capture is not a long
    • pathUuid

      default UUID pathUuid(String name)
      Reads a raw path capture as a UUID, with the rules of queryUuid(String); see pathInt(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 route
      BadRequestException - with code invalid_path_parameter if the capture is not a UUID
    • bodyReader

      default BodyReader bodyReader()
      Returns the incremental reader for this request's body, when the runtime supplied one. A reader is supplied to handlers registered as StreamingHandler and to every request executed through the test client or Application.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, and Request.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

      <T> T body(Class<T> type)
      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 with UnsupportedMediaTypeException (missing_content_type, 415); a charset parameter other than UTF-8 fails with code unsupported_charset (415); a media type without an installed codec fails with unsupported_media_type (415); content the codec cannot decode into the type fails with a DecodeException (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

      default <T> T validatedBody(Class<T> type, BodyValidator<? super T> validator)
      Decodes the request body as body(Class) does, then checks it.
      
       var order = ctx.validatedBody(Order.class, ORDER_RULES);
       
      Decoding failures come first and the validator then does not run. When the validator reports violations this throws 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 record
      validator - thread-safe check, such as an axiom-validation Validator
      Returns:
      the decoded, valid value, never null
      Throws:
      ValidationException - if the validator reports violations
      IllegalStateException - if the validator returns null or a null violation
    • json

      default Response json(Object value)
      Maps a value to a JSON response using the current status (200 by default). The value is encoded by the installed application/json codec during this call. Keep the value stable until the call returns; later mutations cannot change the response. A String or byte[] value is sent verbatim as already-encoded JSON. An object without an installed JSON codec fails immediately with IllegalStateException.
      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

      default Response encode(String contentType, Object value)
      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 parameters
      value - non-null body value
      Returns:
      response using the current status and supplied Content-Type
      Throws:
      IllegalArgumentException - for an invalid content type
      IllegalStateException - if an object has no codec, encoding fails or the status cannot carry a body
      UnsupportedOperationException - if a custom context does not implement object encoding
    • status

      Context status(int 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 calling response(Object) or text(String)) fails with an IllegalStateException that 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 use matchedRoute().
      Returns:
      matched route
      Throws:
      IllegalStateException - if no route matched this request
    • matchedRoute

      default Optional<Route> 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

      String path(String name)
      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

      default String pathDecoded(String name)
      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 a BadRequestException with code invalid_path_encoding, answered 400 like any other AxiomException; 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 route
      BadRequestException - if the value is malformed UTF-8 or would decode to a separator, NUL or dot segment
    • pathParameters

      Map<String,String> 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

      default Response automaticOptions()
      Returns the answer the application gives an OPTIONS request that no route serves: 204 with no body and an Allow header listing every method registered on any template that matches the request path, HEAD wherever GET is, and OPTIONS, sorted alphabetically (for OPTIONS *, 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 /*any would 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:

      
       app.options("/*any", ctx -> isPreflight(ctx) ? preflightAnswer(ctx) : ctx.automaticOptions());
       
      Call it for OPTIONS requests; for another method the list is still the path's.
      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

      default Response problem(AxiomException failure)
      Builds the standard problem response for an exception: its status, the typed headers it carries (Allow, Retry-After, WWW-Authenticate), application/problem+json and 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. An ErrorHandler uses it to decorate the standard answer instead of replacing it:
      
       app.error(AxiomException.class, (ctx, failure) ->
               ctx.problem(failure).withHeader("Cache-Control", "no-store"));
       
      It does not log, and it is independent of the context's status.
      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

      Response response(Object body)
      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; use json(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 body
      IllegalArgumentException - if the body is not String, byte[] or null
    • text

      default Response text(String text)
      Creates a text response using the current settings.
      Parameters:
      text - non-null text
      Returns:
      a response using the current status
    • redirect

      default Response redirect(int status, String location)
      Returns a redirect without a body. Use Response.withLocation(String) for 201 Created, for example ctx.status(201).json(item).withLocation("/items/" + id).
      Parameters:
      status - 301, 302, 303, 307 or 308
      location - target URI reference, validated against header injection
      Returns:
      redirect response
      Throws:
      IllegalArgumentException - for another status or an invalid location
    • noContent

      default Response noContent()
      Returns a 204 response with no body.
      Returns:
      a 204 response with no body