Class Response
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 Summary
FieldsModifier and TypeFieldDescriptionstatic final longDefault cap on the bytes of a streamed response body: 64 MiB.static final DurationLongest lifetime of a stream (seewithStreamLifetime(java.time.Duration)): one day. -
Method Summary
Modifier and TypeMethodDescriptionbody()Returns body value, with a defensive copy for byte arrays.booleaninthashCode()headers()Returns immutable, case-insensitive header map.booleanReports whether the body is produced by aStreamBody.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.static ResponseCreates a response with the supplied status and body.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.static ResponseCreates a redirect without a body.Returns the known total length of a sliced stream, or null for any other response.static Responsesse(long maxBytes, EventStreamBody body) Creates a server-sent event stream: a streamed 200 response of typetext/event-streamfor browsers'EventSource.static Responsesse(EventStreamBody body) Creates a server-sent event stream with the default byte cap.intstatus()Returns final HTTP status.static Responsestream(int status, String contentType, long maxBytes, StreamBody body) Creates a streamed response.static Responsestream(int status, String contentType, StreamBody body) Creates a streamed response with the default byte cap.Returns the body writer of a streamed response.Returns the observer that tells every observer added withonStreamEnd(java.util.function.Consumer<com.jsgalactic.axiom.http.StreamOutcome>)how the body ended.Returns the longest time a streamed response may run once its head is sent.longReturns the byte cap of a streamed response.toString()Describes the response for diagnostics.withHeader(String name, String value) Returns a copy, replacing any existing value for the header regardless of case.withLocation(String location) Returns a copy with a Location header, for example after 201 Created.Returns a copy without a body, preserving status and headers (for HEAD).withStreamLifetime(Duration lifetime) Returns a streamed response that may run for its own time instead of the request deadline.
-
Field Details
-
MAX_STREAM_LIFETIME
Longest lifetime of a stream (seewithStreamLifetime(java.time.Duration)): one day. -
DEFAULT_STREAM_LIMIT
public static final long DEFAULT_STREAM_LIMITDefault cap on the bytes of a streamed response body: 64 MiB.- See Also:
-
-
Method Details
-
of
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 usestream(int, java.lang.String, com.jsgalactic.axiom.http.StreamBody)for aStreamBody
-
stream
Creates a streamed response with the default byte cap.- Parameters:
status- final HTTP status (200-599) other than 204, 205 and 304contentType- Content-Type header valuebody- 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
Creates a streamed response. The head is sent first, then the runtime callsbodyon 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 andbodyis not called. AnyContent-Lengthheader is ignored.Once the head is sent the status cannot change. A body that throws, exceeds
maxBytesor outlives the deadline ends the response by closing the connection, so the client sees a truncated body, never a second response. SeeBodyWriter.- Parameters:
status- final HTTP status (200-599) other than 204, 205 and 304contentType- Content-Type header valuemaxBytes- most body bytes the stream may write; positivebody- 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
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
Creates a server-sent event stream with the default byte cap. Seesse(long, EventStreamBody).- Parameters:
body- sends the events after the head has been sent- Returns:
- a streamed
text/event-streamresponse
-
sse
Creates a server-sent event stream: a streamed 200 response of typetext/event-streamfor browsers'EventSource. It carriesCache-Control: no-store, no-transformandX-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 ofstream(int, String, long, StreamBody), including the cap, the deadline and what happens when the client leaves. UseEventSink.keepAlive()while idle. Replace headers withwithHeader(java.lang.String, java.lang.String).- Parameters:
maxBytes- most bytes the stream may send; positivebody- sends the events after the head has been sent- Returns:
- a streamed
text/event-streamresponse - Throws:
IllegalArgumentException- if the cap is not positive
-
redirect
Creates a redirect without a body.- Parameters:
status- 301, 302, 303, 307 or 308location- target URI reference; validated as bywithLocation(String)- Returns:
- redirect response
- Throws:
IllegalArgumentException- for another status or an invalid location
-
withLocation
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
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 aStreamBody.- Returns:
- true for a response made by
stream(int, java.lang.String, com.jsgalactic.axiom.http.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
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
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 tolifetimefrom that moment if that is later, so the stream is aborted withTIMEOUTwhen 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 outliveapp.requestTimeout.- Parameters:
lifetime- positive, at mostMAX_STREAM_LIFETIME- Returns:
- a copy with the lifetime
- Throws:
IllegalStateException- if the response is not streamingIllegalArgumentException- if the lifetime is not positive or is longer than one day
-
mapStream
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 wrappingBodyWritershould delegateshutdownRequestedandonShutdownto 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
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
Returns the observer that tells every observer added withonStreamEnd(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
Returns immutable, case-insensitive header map.- Returns:
- immutable, case-insensitive header map
-
withHeader
Returns a copy, replacing any existing value for the header regardless of case.- Parameters:
name- HTTP header tokenvalue- header value without control characters (horizontal tabs are allowed)- Returns:
- a response with the header
-
equals
-
hashCode
public int hashCode() -
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. -
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)
-