Class ServerResponseBase<T extends ServerResponseBase<T>>
- Type Parameters:
T- type of the response extending this class to allow fluent API
- All Implemented Interfaces:
RoutingResponse, ServerResponse
-
Field Summary
FieldsModifier and TypeFieldDescriptionprotected static final HeaderNameStream result trailer name.protected static final HeaderStream result OK.protected static final HeaderStream status trailers. -
Constructor Summary
ConstructorsModifierConstructorDescriptionprotectedServerResponseBase(ConnectionContext ctx, ServerRequest request) Create server response. -
Method Summary
Modifier and TypeMethodDescriptionprotected voidExecute after send runnables.protected final OutputStreamapplyStreamFilters(OutputStream outputStream) Apply configured output stream filters.automaticContentEncoding(boolean enabled) Configure whether the WebServer response layer may automatically encode the response entity using the listener content encoding context.protected voidExecute before send runnables.beforeSend(Runnable listener) Executed right before the first byte is written to the socket (including response status and headers).protected Consumer<ServerResponseTrailers> Gets consumer for server response trailers if registered on this response.beforeTrailers(Consumer<ServerResponseTrailers> beforeTrailers) Callback to update any last minute trailers before they are written to the output stream.protected OutputStreamcontentEncode(OutputStream outputStream) Encode content using requested/default content encoder.protected OutputStreamcontentEncode(OutputStream outputStream, boolean allowAutomaticEncoding) Encode content using an explicitly configured encoder, or an automatic encoder when allowed.contentEncoder(ContentEncoder encoder) Configure an explicit response content encoder.protected final <X extends Sink<?>>
XcreateSink(SinkProvider<?> provider, ServerRequest request, ConnectionContext connectionContext, Function<Runnable, Optional<OutputStream>> entityOutputStreamProvider, Runnable closeRunnable, Runnable flushHeadersRunnable) Create a sink using the shared provider context and protocol-specific callbacks.voidentityBeforeSend(Runnable listener) Register an infrastructure listener associated with the current response entity.protected byte[]entityBytes(byte[] configuredEntity) Entity bytes encoded using content encoding.protected byte[]entityBytes(byte[] configuredEntity, int position, int length) Entity bytes encoded using content encoding.voidentityStreamFilter(UnaryOperator<OutputStream> filterFunction) Configure an infrastructure output stream filter associated with the current response entity.protected final SinkProvider<?> findSinkProvider(GenericType<? extends Sink<?>> sinkType, ServerRequest request) Find a sink provider for the requested sink type.protected final booleanWhether this response has any output stream filters.booleanisNexted()Whether this request is nexted (ServerResponse.next()was called).booleanWhether this response has already been handled by the application.protected MediaContextGets media context for this response.next()Continue processing with the next route (and if none found, return aStatus.NOT_FOUND_404).protected final voidDiscard entity stream filters and suppress an implicit content length for aHEADresponse.Re-route using a different path.Re-route using a different path and query.reroutePrologue(HttpPrologue prologue) A new, rerouted prologue.protected voidReset response-layer automatic content encoding to its default behavior.protected voidReset all response-layer content encoding state to its defaults.booleanReset the response entity so an unsent response can be replaced while preserving response metadata unrelated to the entity, such as CORS, cookies, cache controls, andVaryheaders.voidReset routing information (nexted, rerouted etc.).voidsend()Send a response with no entity.voidSend an entity, aMediaContextwill be used to serialize the entity.booleanShould we reroute this exchange.status()Configured HTTP status, if not configured, returnsStatus.OK_200.Status of the response.voidstreamFilter(UnaryOperator<OutputStream> filterFunction) Configure a custom output stream to wrap the output stream of the response.protected final booleansuppressImplicitContentLength(int length) Whether the protocol implementation should suppress an implicit content length.Completed when last byte is buffered for socket write.Methods inherited from class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface RoutingResponse
commit, hasEntity, reset, resetStreamModifier and TypeMethodDescriptionvoidcommit()Commit the response.booleanWhether this request has an entity.booleanreset()Return true if the underlying response buffers and headers can be reset and a new response can be sent.default booleanReturn true if the underlying response buffers can be reset and a new response can be sent.Methods inherited from interface ServerResponse
bytesWritten, contentLength, header, header, header, headers, isSent, outputStream, send, send, send, sink, status, streamResult, trailersModifier and TypeMethodDescriptionlongNumber of bytes written to response.default voidcontentLength(long length) Configure a content length header for this response.Set header with a value.default ServerResponseheader(HeaderName name, String... values) Set a header.default ServerResponseNot optimized method for setting a header.headers()Response headers (mutable).booleanisSent()Whether this response has been sent.Alternative way to send an entity, using an output stream.voidsend(byte[] bytes) Send a byte array response.default voidsend(byte[] bytes, int position, int length) Send a byte array response.default voidSend an entity if present, throwNotFoundExceptionif empty.default <T extends Sink<?>>
Tsink(GenericType<T> sinkType) Returns a sink from this response based on the sink type.default ServerResponsestatus(int status) Status of the response.voidstreamResult(String result) Description of the result of output stream processing.trailers()Response trailers (mutable).
-
Field Details
-
STREAM_RESULT_NAME
Stream result trailer name. -
STREAM_RESULT_OK
Stream result OK. -
STREAM_TRAILERS
Stream status trailers.
-
-
Constructor Details
-
ServerResponseBase
Create server response.- Parameters:
ctx- contextrequest- server request
-
-
Method Details
-
status
Description copied from interface:ServerResponseStatus of the response.The status is mutable response metadata. Once configured, it remains on this response unless later application code or error handling changes it. Calling
ServerResponse.next(), callingServerResponse.reroute(String), or throwing an exception does not clear the configured status automatically.Configure the status before calling
ServerResponse.send()orServerResponse.outputStream()when it should apply to the response emitted by this route.- Specified by:
statusin interfaceServerResponse- Parameters:
status- HTTP status- Returns:
- this instance
-
status
Description copied from interface:ServerResponseConfigured HTTP status, if not configured, returnsStatus.OK_200.- Specified by:
statusin interfaceServerResponse- Returns:
- status
-
send
public void send()Description copied from interface:ServerResponseSend a response with no entity. Use this method for aHEADresponse after configuring the representation metadata in the response headers.- Specified by:
sendin interfaceServerResponse
-
send
Description copied from interface:ServerResponseSend an entity, aMediaContextwill be used to serialize the entity.- Specified by:
sendin interfaceServerResponse- Parameters:
entity- entity object
-
beforeSend
Description copied from interface:ServerResponseExecuted right before the first byte is written to the socket (including response status and headers). Response can be modified (i.e. headers, status) at this point, though modifying the entity may not be done, as this method is most likely called from within one of theServerResponse.send()methods. Changing the response status is supported only if the new status has the same response entity semantics. For example, changing between an entity-bearing status and a status without an entity may leave response framing inconsistent and break the response. The listener remains registered if error handling replaces the unsent response entity.Note: this method is implemented as a default method that does nothing, for backward compatibility.
- Specified by:
beforeSendin interfaceServerResponse- Parameters:
listener- lister to add to the list of listeners that will be triggered before the response is sent- Returns:
- this instance
-
entityBeforeSend
Description copied from interface:RoutingResponseRegister an infrastructure listener associated with the current response entity.Implementations which distinguish entity-scoped listeners remove the listener if error handling replaces the unsent entity. Application listeners should use
ServerResponse.beforeSend(Runnable)so they also apply to a replacement error response. The default fallback registers the listener through the public method and therefore retains it.- Specified by:
entityBeforeSendin interfaceRoutingResponse- Parameters:
listener- listener invoked before the response is sent
-
automaticContentEncoding
Description copied from interface:RoutingResponseConfigure whether the WebServer response layer may automatically encode the response entity using the listener content encoding context. This does not remove or rewrite any explicitly configuredContent-Encodingheader. Repeated calls replace the previous setting until response content encoding is selected.- Specified by:
automaticContentEncodingin interfaceRoutingResponse- Specified by:
automaticContentEncodingin interfaceServerResponse- Parameters:
enabled- whether automatic response content encoding is enabled- Returns:
- this instance
-
contentEncoder
Description copied from interface:RoutingResponseConfigure an explicit response content encoder. Repeated calls replace the previous encoder until response content encoding is selected. The selected encoder's headers are applied once during selection.- Specified by:
contentEncoderin interfaceRoutingResponse- Specified by:
contentEncoderin interfaceServerResponse- Parameters:
encoder- content encoder- Returns:
- this instance
-
whenSent
Description copied from interface:ServerResponseCompleted when last byte is buffered for socket write.- Specified by:
whenSentin interfaceServerResponse- Parameters:
listener- listener to add to the list of listeners that will be triggered once the response is sent- Returns:
- this instance
-
reroute
Description copied from interface:ServerResponseRe-route using a different path. Configured response status and headers remain on this response unless later handling changes them.- Specified by:
reroutein interfaceServerResponse- Parameters:
newPath- new path to use- Returns:
- this instance
-
reroute
Description copied from interface:ServerResponseRe-route using a different path and query. Configured response status and headers remain on this response unless later handling changes them.- Specified by:
reroutein interfaceServerResponse- Parameters:
path- new pathquery- new query- Returns:
- this instance
- See Also:
-
next
Description copied from interface:ServerResponseContinue processing with the next route (and if none found, return aStatus.NOT_FOUND_404). If any entity method was called, this method will throw an exception. Configured response status and headers remain on this response unless later handling changes them.- Specified by:
nextin interfaceServerResponse- Returns:
- this instance
-
resetRouting
public void resetRouting()Description copied from interface:RoutingResponseReset routing information (nexted, rerouted etc.).- Specified by:
resetRoutingin interfaceRoutingResponse
-
shouldReroute
public boolean shouldReroute()Description copied from interface:RoutingResponseShould we reroute this exchange.- Specified by:
shouldReroutein interfaceRoutingResponse- Returns:
- whether rerouting was requested
-
reroutePrologue
Description copied from interface:RoutingResponseA new, rerouted prologue.- Specified by:
rerouteProloguein interfaceRoutingResponse- Parameters:
prologue- current prologue- Returns:
- prologue to use when rerouting
-
isNexted
public boolean isNexted()Description copied from interface:RoutingResponseWhether this request is nexted (ServerResponse.next()was called).- Specified by:
isNextedin interfaceRoutingResponse- Returns:
- if nexted
-
isResponseHandled
public boolean isResponseHandled()Description copied from interface:ServerResponseWhether this response has already been handled by the application.This method is intended for generated or framework code that may send a default response only when user code has not already sent an entity, obtained an output stream, or selected another routing action. Header and status changes alone do not handle the response.
The default implementation returns
ServerResponse.isSent().- Specified by:
isResponseHandledin interfaceServerResponse- Returns:
- whether response handling was already selected
-
resetEntity
public boolean resetEntity()Description copied from interface:RoutingResponseReset the response entity so an unsent response can be replaced while preserving response metadata unrelated to the entity, such as CORS, cookies, cache controls, andVaryheaders.This method is intended for Helidon infrastructure that replaces a failed response entity.
Implementations that track entity metadata must override this method to reset entity buffers and remove framing, representation, validator, range, and trailer headers. Implementations with separate trailer state must reset that state as well. This method does not change the response status. An error handler that replaces the entity is responsible for configuring or deliberately retaining an appropriate status before sending the replacement response.
For compatibility with existing
RoutingResponseimplementations, the default implementation callsRoutingResponse.resetStream().- Specified by:
resetEntityin interfaceRoutingResponse- Returns:
trueif reset was successful and a new entity can be created instead of the existing one,falseif reset failed and status and headers (and maybe entity bytes) were already sent
-
streamFilter
Description copied from interface:ServerResponseConfigure a custom output stream to wrap the output stream of the response. The filter remains registered if error handling replaces the unsent response entity. A filter that changes representation metadata, such asContent-Encoding, must useServerResponse.beforeSend(Runnable)to configure the matching headers for each entity that is sent.- Specified by:
streamFilterin interfaceServerResponse- Parameters:
filterFunction- the function to replace output stream of this response with a user provided one
-
entityStreamFilter
Description copied from interface:RoutingResponseConfigure an infrastructure output stream filter associated with the current response entity.Implementations which distinguish entity-scoped filters remove the filter if error handling replaces the unsent entity. Application filters should use
ServerResponse.streamFilter(UnaryOperator)so they also apply to a replacement error response. The default fallback registers the filter through the public method and therefore retains it.- Specified by:
entityStreamFilterin interfaceRoutingResponse- Parameters:
filterFunction- function that wraps the response output stream
-
beforeTrailers
Description copied from interface:ServerResponseCallback to update any last minute trailers before they are written to the output stream. The callback is associated with the current response entity and is cleared if error handling replaces that entity before it is sent. A response-scoped policy should useServerResponse.beforeSend(Runnable)to register a fresh callback for each entity.- Specified by:
beforeTrailersin interfaceServerResponse- Parameters:
beforeTrailers- consumer of mutable trailers- Returns:
- this instance
-
beforeTrailers
Gets consumer for server response trailers if registered on this response.- Returns:
- consumer if registered or
nullotherwise
-
findSinkProvider
protected final SinkProvider<?> findSinkProvider(GenericType<? extends Sink<?>> sinkType, ServerRequest request) Find a sink provider for the requested sink type.- Parameters:
sinkType- sink typerequest- server request- Returns:
- matching sink provider
-
createSink
protected final <X extends Sink<?>> X createSink(SinkProvider<?> provider, ServerRequest request, ConnectionContext connectionContext, Function<Runnable, Optional<OutputStream>> entityOutputStreamProvider, Runnable closeRunnable, Runnable flushHeadersRunnable) Create a sink using the shared provider context and protocol-specific callbacks.- Type Parameters:
X- sink type- Parameters:
provider- sink providerrequest- server requestconnectionContext- connection contextentityOutputStreamProvider- protocol entity stream providercloseRunnable- protocol close callbackflushHeadersRunnable- protocol header flush callback- Returns:
- created sink
-
hasStreamFilter
protected final boolean hasStreamFilter()Whether this response has any output stream filters.- Returns:
- whether an output stream filter is configured
-
prepareFilteredHeadResponse
protected final void prepareFilteredHeadResponse()Discard entity stream filters and suppress an implicit content length for aHEADresponse. -
suppressImplicitContentLength
protected final boolean suppressImplicitContentLength(int length) Whether the protocol implementation should suppress an implicit content length.- Parameters:
length- response entity length- Returns:
- whether to suppress the implicit content length
-
applyStreamFilters
Apply configured output stream filters.- Parameters:
outputStream- output stream to wrap- Returns:
- filtered output stream
-
mediaContext
Gets media context for this response.- Returns:
- the media context
-
entityBytes
protected byte[] entityBytes(byte[] configuredEntity) Entity bytes encoded using content encoding. Automatic encoding is skipped for an empty entity. An explicitly configured encoder is applied unless the response status does not allow an entity.- Parameters:
configuredEntity- plain bytes- Returns:
- encoded bytes or same entity array if encoding is disabled
-
entityBytes
protected byte[] entityBytes(byte[] configuredEntity, int position, int length) Entity bytes encoded using content encoding. Automatic encoding is skipped for an empty entity. An explicitly configured encoder is applied unless the response status does not allow an entity.- Parameters:
configuredEntity- plain bytesposition- starting positionlength- number of bytes- Returns:
- encoded bytes or same entity array if encoding is disabled
-
contentEncode
Encode content using requested/default content encoder.- Parameters:
outputStream- output stream to write encoded data to- Returns:
- output stream to write plain data to
-
contentEncode
Encode content using an explicitly configured encoder, or an automatic encoder when allowed.- Parameters:
outputStream- output stream to write encoded data toallowAutomaticEncoding- whether automatic encoding may be selected- Returns:
- output stream to write plain data to
-
resetAutomaticContentEncoding
protected void resetAutomaticContentEncoding()Reset response-layer automatic content encoding to its default behavior. -
resetContentEncoding
protected void resetContentEncoding()Reset all response-layer content encoding state to its defaults. -
beforeSend
protected void beforeSend()Execute before send runnables. -
afterSend
protected void afterSend()Execute after send runnables.
-