Class Response

java.lang.Object
com.jsgalactic.axiom.http.Response

public final class Response extends Object
A response value before wire encoding. Header maps and byte arrays are defensively copied. Buffered responses never retain arbitrary application objects. Header names are case-insensitive. One value per header is supported at this stage.

Buffered bodies may be null, a String, or a byte[]. Encode application objects with Context.json or Context.encode before constructing a response. Two responses are equal when their statuses, headers (names compared case-insensitively), and bodies are equal, comparing byte arrays by content and other bodies with Object.equals(Object).

A response can instead be a stream (see stream(int, java.lang.String, com.jsgalactic.axiom.http.StreamBody)): its bytes are produced by a StreamBody while the connection is open rather than held in memory. body() returns that StreamBody; it is never encoded by a codec.

  • Field Details

  • Method Details

    • of

      public static Response of(int status, Object body)
      Creates a response with the supplied status and body.
      Parameters:
      status - final HTTP status (200-599)
      body - body value or null
      Returns:
      a response with a content type for String or byte[] bodies
      Throws:
      IllegalArgumentException - for any other body type; encode objects first, and use stream(int, java.lang.String, com.jsgalactic.axiom.http.StreamBody) for a StreamBody
    • stream

      public static Response stream(int status, String contentType, StreamBody body)
      Creates a streamed response with the default byte cap.
      Parameters:
      status - final HTTP status (200-599) other than 204, 205 and 304
      contentType - Content-Type header value
      body - writes the body after the head has been sent
      Returns:
      a streamed response
      Throws:
      IllegalArgumentException - for a status that cannot carry a body or an invalid content type
      See Also:
    • stream

      public static Response stream(int status, String contentType, long maxBytes, StreamBody body)
      Creates a streamed response. The head is sent first, then the runtime calls body on the handler's virtual thread, so the admission slot and the request deadline apply until it returns. On HTTP/1.1 the body is sent with chunked transfer encoding; on HTTP/1.0 it ends with the connection. A HEAD request receives the head only and body is not called. Any Content-Length header is ignored.

      Once the head is sent the status cannot change. A body that throws, exceeds maxBytes or outlives the deadline ends the response by closing the connection, so the client sees a truncated body, never a second response. See BodyWriter.

      Parameters:
      status - final HTTP status (200-599) other than 204, 205 and 304
      contentType - Content-Type header value
      maxBytes - most body bytes the stream may write; positive
      body - writes the body after the head has been sent
      Returns:
      a streamed response
      Throws:
      IllegalArgumentException - for a status that cannot carry a body, a non-positive cap or an invalid content type
    • representationLength

      public Long representationLength()
      Returns the known total length of a sliced stream, or null for any other response. A transport may use this to decide whether a stream can be compressed without buffering it; applications can use it to describe the representation they are about to write.
      Returns:
      the total representation length in bytes, or null when it is not known
    • sse

      public static Response sse(EventStreamBody body)
      Creates a server-sent event stream with the default byte cap. See sse(long, EventStreamBody).
      Parameters:
      body - sends the events after the head has been sent
      Returns:
      a streamed text/event-stream response
    • sse

      public static Response sse(long maxBytes, EventStreamBody body)
      Creates a server-sent event stream: a streamed 200 response of type text/event-stream for browsers' EventSource. It carries Cache-Control: no-store, no-transform and X-Accel-Buffering: no, so caches do not keep it and intermediaries do not buffer or compress it; the server itself never compresses a response. Events are written with the semantics of stream(int, String, long, StreamBody), including the cap, the deadline and what happens when the client leaves. Use EventSink.keepAlive() while idle. Replace headers with withHeader(java.lang.String, java.lang.String).
      Parameters:
      maxBytes - most bytes the stream may send; positive
      body - sends the events after the head has been sent
      Returns:
      a streamed text/event-stream response
      Throws:
      IllegalArgumentException - if the cap is not positive
    • redirect

      public static Response redirect(int status, String location)
      Creates a redirect without a body.
      Parameters:
      status - 301, 302, 303, 307 or 308
      location - target URI reference; validated as by withLocation(String)
      Returns:
      redirect response
      Throws:
      IllegalArgumentException - for another status or an invalid location
    • withLocation

      public Response withLocation(String location)
      Returns a copy with a Location header, for example after 201 Created. The location must be a URI reference (absolute URI, absolute path or relative reference) of at most 2048 characters using only visible ASCII characters allowed by RFC 3986, with well-formed percent-escapes; spaces, quotes, angle brackets, backslashes, control characters and therefore CR/LF header injection are rejected. Validation does not judge whether the target is safe to redirect to: never redirect to an unchecked client-supplied URL.
      Parameters:
      location - URI reference
      Returns:
      a response with the Location header
      Throws:
      IllegalArgumentException - for an invalid location
    • status

      public int status()
      Returns final HTTP status.
      Returns:
      final HTTP status
    • body

      public Object body()
      Returns body value, with a defensive copy for byte arrays.
      Returns:
      body value, with a defensive copy for byte arrays
    • isStreaming

      public boolean isStreaming()
      Reports whether the body is produced by a StreamBody.
      Returns:
      true for a response made by stream(int, java.lang.String, com.jsgalactic.axiom.http.StreamBody)
    • streamBody

      public StreamBody streamBody()
      Returns the body writer of a streamed response.
      Returns:
      the writer, or null when the response is not streaming
    • streamLimit

      public long streamLimit()
      Returns the byte cap of a streamed response.
      Returns:
      the cap, or zero when the response is not streaming
    • streamLifetime

      public Duration streamLifetime()
      Returns the longest time a streamed response may run once its head is sent.
      Returns:
      the lifetime set with withStreamLifetime(java.time.Duration), or null when the stream is bound by the request deadline (or the response is not streaming)
    • withStreamLifetime

      public Response withStreamLifetime(Duration lifetime)
      Returns a streamed response that may run for its own time instead of the request deadline. The deadline of ordinary requests is not changed. When the runtime has sent the head, the request's deadline moves to lifetime from that moment if that is later, so the stream is aborted with TIMEOUT when it passes, and the request keeps its admission slot until then. A lifetime shorter than what remains of the deadline changes nothing: this extends a stream, it never cuts one short. Use it for server-sent event streams and large downloads that outlive app.requestTimeout.
      Parameters:
      lifetime - positive, at most MAX_STREAM_LIFETIME
      Returns:
      a copy with the lifetime
      Throws:
      IllegalStateException - if the response is not streaming
      IllegalArgumentException - if the lifetime is not positive or is longer than one day
    • mapStream

      public Response mapStream(UnaryOperator<StreamBody> wrapper)
      Returns a streamed response whose body is replaced by a wrapper of the current one, for example to time it, count bytes or transform what it writes. The wrapper runs where the original would: after the head is sent, on the handler's thread. A wrapping BodyWriter should delegate shutdownRequested and onShutdown to the writer it wraps.
      Parameters:
      wrapper - receives the current body and returns the body to run
      Returns:
      a copy with the wrapped body
      Throws:
      IllegalStateException - if the response is not streaming
    • onStreamEnd

      public Response onStreamEnd(Consumer<StreamOutcome> observer)
      Returns a streamed response that tells an observer how its body ended, so middleware can record the outcome of a stream, which is only known after the middleware returned. Observers run once, on the handler's thread, after the body returned or failed and before the connection is finished; the first added runs first, so an observer added by inner middleware runs before one added by outer middleware. They must be quick and must not block, because the request still holds its admission slot. An observer that throws is logged and ignored; the others still run. They are not called when the body never ran: a HEAD request, or a response refused before its head was sent. They cannot change the response or the status.
      Parameters:
      observer - receives the outcome
      Returns:
      a copy with the observer added
      Throws:
      IllegalStateException - if the response is not streaming
    • streamEndObserver

      public Consumer<StreamOutcome> streamEndObserver()
      Returns the observer that tells every observer added with onStreamEnd(java.util.function.Consumer<com.jsgalactic.axiom.http.StreamOutcome>) how the body ended. For the runtime, which calls it once per stream that ran. An observer that throws does not stop the others; the first exception is rethrown after all have run.
      Returns:
      the combined observer, which does nothing for a response that is not streaming
    • headers

      public Map<String,String> headers()
      Returns immutable, case-insensitive header map.
      Returns:
      immutable, case-insensitive header map
    • withHeader

      public Response withHeader(String name, String value)
      Returns a copy, replacing any existing value for the header regardless of case.
      Parameters:
      name - HTTP header token
      value - header value without control characters (horizontal tabs are allowed)
      Returns:
      a response with the header
    • equals

      public boolean equals(Object other)
      Overrides:
      equals in class Object
    • hashCode

      public int hashCode()
      Overrides:
      hashCode in class Object
    • toString

      public String toString()
      Describes the response for diagnostics. Text bodies longer than 80 characters are truncated, byte arrays are shown by length, and other bodies by their class name.
      Overrides:
      toString in class Object
      Returns:
      a diagnostic description
    • withoutBody

      public Response withoutBody()
      Returns a copy without a body, preserving status and headers (for HEAD).
      Returns:
      a copy without a body, preserving status and headers (for HEAD)