Interface Request
- All Superinterfaces:
 Attributes, Content.Source
- All Known Subinterfaces:
 Request.ServeAs, ServerUpgradeRequest, ServerUpgradeRequest
- All Known Implementing Classes:
 ContextHandler.CoreContextRequest, ContextHandler.CoreContextRequest, ContextRequest, ErrorHandler.ErrorRequest, GzipRequest, HeaderWrappingRequest, PathMappingsHandler.PathSpecRequest, Request.AttributesWrapper, Request.Wrapper, RewriteEncodingRule.EncodingHandler, RewriteEncodingRule.VaryHandler, RewriteLanguageRule.LanguageHandler, RewriteLanguageRule.VaryHandler, Rule.Handler, Rule.HttpURIHandler, SecureRequestCustomizer.SecureRequest, SecureRequestCustomizer.SecureRequestWithSslSessionData, ServletContextRequest, ServletContextRequest, ServletCoreRequest, ServletCoreRequest, ServletCoreRequest, ServletCoreRequest, SessionHandler.SessionRequest, StatisticsHandler.MinimumDataRateHandler.MinimumDataRateRequest
The representation of an HTTP request, for any protocol version (HTTP/1.1, HTTP/2, HTTP/3).
The typical idiom to read request content is the following:
public boolean handle(Request request, Response response, Callback callback)
{
    // Reject requests not appropriate for this handler.
    if (!request.getHttpURI().getPath().startsWith("/yourPath"))
        return false;
    while (true)
    {
        Content.Chunk chunk = request.read();
        if (chunk == null)
        {
            // The chunk is not currently available, demand to be called back.
            request.demand(() -> handle(request, response, callback));
            return true;
        }
        if (Content.Chunk.isError(chunk))
        {
            Throwable failure = error.getCause();
            // Handle errors.
            // If the chunk is not last, then the error can be ignored and reading can be tried again.
            // Otherwise, if the chunk is last, or we do not wish to ignore a non-last error, then
            // mark the handling as complete, either generating a custom
            // response and succeeding the callback, or failing the callback.
            callback.failed(failure);
            return true;
        }
        if (chunk instanceof Trailers trailers)
        {
            HttpFields fields = trailers.getTrailers();
            // Handle trailers.
            // Generate a response.
            // Mark the handling as complete.
            callback.succeeded();
            return true;
        }
        // Normal chunk, process it.
        processChunk(chunk);
        // Release the content after processing.
        chunk.release();
        // Reached end-of-file?
        if (chunk.isLast())
        {
            // Generate a response.
            // Mark the handling as complete.
            callback.succeeded();
            return true;
        }
    }
}
- 
Nested Class Summary
Nested ClassesModifier and TypeInterfaceDescriptionstatic classARequest.Wrapperthat separately provides the requestAttributes.static interfaceA minimal Authentication interface, primarily used for logging.static interfaceA handler for an HTTP request and response.static interfaceThis interface will be detected by theRequest.ServeAs.wrap(Request, HttpURI)static method to wrap the request changing its target to a given path.static classA wrapper forRequestinstances.Nested classes/interfaces inherited from interface Attributes
Attributes.Layer, Attributes.Lazy, Attributes.Mapped, Attributes.SyntheticNested classes/interfaces inherited from interface Content.Source
Content.Source.Factory - 
Field Summary
FieldsFields inherited from interface Attributes
NULL - 
Method Summary
Modifier and TypeMethodDescriptionstatic voidaddCompletionListener(Request request, Consumer<Throwable> listener) Adds a completion listener that is an optimized equivalent to overriding theCallback.succeeded()andCallback.failed(Throwable)methods of aHttpStream.Wrappercreated by a call toaddHttpStreamWrapper(Function).voidaddFailureListener(Consumer<Throwable> onFailure) Adds a listener for asynchronous fatal failures.voidaddHttpStreamWrapper(Function<HttpStream, HttpStream> wrapper) Add aHttpStream.Wrapperto the currentHttpStream.voidaddIdleTimeoutListener(Predicate<TimeoutException> onIdleTimeout) Adds a listener for idle timeouts.static <T> TUnwrap a Request back to the given type.static <T extends Request>
TasInContext(Request request, Class<T> type) Unwrap a Request back to the given type, ensuring that we do not cross a context boundary (as might be the case during cross-context dispatch).static InputStreamasInputStream(Request request) static RequestasReadOnly(Request request) Returns a copy of the request that throwsUnsupportedOperationExceptionfrom all mutative methods.booleanConsume any available content.voidDemands to invoke the given demand callback parameter when a chunk of content is available.static FieldsextractQueryParameters(Request request) static FieldsextractQueryParameters(Request request, Charset charset) static <T,R> R static Request.AuthenticationStategetAuthenticationState(Request request) longGet the nanoTime at which the request arrived to a connector, obtained viaSystem.nanoTime().static CharsetgetCharset(Request request) Get aCharsetfrom the requestHttpHeader.CONTENT_TYPE, if any.static longgetContentBytesRead(Request request) Get theContextassociated with thisRequest.static StringgetContextPath(Request request) Get the context path of thisRequest.static List<HttpCookie> getCookies(Request request) longGet the nanoTime at which the request headers were parsed, obtained viaSystem.nanoTime().static StringgetHostName(InetSocketAddress inetSocketAddress) getId()an ID unique within the lifetime scope of theConnectionMetaData.getId()).static StringgetLocalAddr(Request request) getLocales(Request request) static intgetLocalPort(Request request) static MultiPartConfig.BuildergetMultiPartConfig(Request request, Path location) Get aMultiPartConfig.Buildergiven aRequestand a location.static FieldsgetParameters(Request request) static CompletableFuture<Fields> getParametersAsync(Request request) Deprecated, for removal: This API element is subject to removal in a future version.static StringgetPathInContext(Request request) Returns the canonically encoded path of the URI, scoped to the current context.static StringgetRemoteAddr(Request request) static intgetRemotePort(Request request) static StringgetServerName(Request request) Get the logical name the request was sent to, which may be from the authority of the request; the configured server authority; the actual network name of the server;static intgetServerPort(Request request) Get the logical port a request was received on, which may be from the authority of the request; the configured server authority; the default port for the scheme; or the actual network port.getSession(boolean create) Get aSessionassociated with the request.static longgetTimeStamp(Request request) Get the millisecond timestamp at which the request was created, obtained withSystem.currentTimeMillis().booleanisSecure()static HttpURInewHttpURIFrom(Request request, String newEncodedPathInContext) Creates a newHttpURIfrom the given Request's HttpURI and the given path in context.static voidonParameters(Request request, Promise.Invocable<Fields> promise) Asynchronous version ofgetParameters(Request).default voidpush(MetaData.Request resource) Pushes the givenresourceto the client.read()Reads a chunk of content.static RequestReturn a request with itsHttpURIchanged to the supplied target.static voidsetAuthenticationState(Request request, Request.AuthenticationState state) static StringtoRedirectURI(Request request, String location) Deprecated.static RequestMethods inherited from interface Attributes
asAttributeMap, clearAttributes, equals, getAttribute, getAttributeNameSet, hashCode, removeAttribute, setAttributeMethods inherited from interface Content.Source
fail, fail, getLength, rewind 
- 
Field Details
- 
LOG
static final org.slf4j.Logger LOG - 
COOKIE_ATTRIBUTE
- See Also:
 
 - 
DEFAULT_LOCALES
 
 - 
 - 
Method Details
- 
getId
String getId()an ID unique within the lifetime scope of theConnectionMetaData.getId()). This may be a protocol ID (e.g. HTTP/2 stream ID) or it may be unrelated to the protocol.- See Also:
 
 - 
getComponents
Components getComponents()- Returns:
 - the 
Componentsto be used with thisRequest. 
 - 
getConnectionMetaData
ConnectionMetaData getConnectionMetaData()- Returns:
 - the 
ConnectionMetaDataassociated to thisRequest 
 - 
getMethod
String getMethod()- Returns:
 - the HTTP method of this 
Request 
 - 
getHttpURI
HttpURI getHttpURI()- Returns:
 - the HTTP URI of this 
Request - See Also:
 
 - 
getContext
Context getContext()Get theContextassociated with thisRequest.Note that a
Requestshould always have an associatedContextsince if theRequestis not being handled by aContextHandlerthen theContextfromServer.getContext()will be used.- Returns:
 - the 
Contextassociated with thisRequest. Nevernull. - See Also:
 
 - 
getContextPath
 - 
getPathInContext
Returns the canonically encoded path of the URI, scoped to the current context.
For example, when the request has a
ContextwithcontextPath=/ctxand the request'sHttpURIcanonical path iscanonicalPath=/ctx/foo, thenpathInContext=/foo.- Returns:
 - The part of the canonically encoded path of the URI after any context path prefix has been removed.
 - See Also:
 
 - 
getHeaders
HttpFields getHeaders()- Returns:
 - the HTTP headers of this 
Request 
 - 
demand
Demands to invoke the given demand callback parameter when a chunk of content is available.
See how to use this method idiomatically.
Implementations guarantee that calls to this method are safely reentrant so that stack overflows are avoided in the case of mutual recursion between the execution of the
Runnablecallback and a call to this method. Invocations of the passedRunnableare serialized and a callback fordemandcall is not invoked until any previousdemandcallback has returned. Thus theRunnableshould not block waiting for a callback of a future demand call.The demand callback may be invoked spuriously: a subsequent call to
Content.Source.read()may returnnull.Calling this method establishes a pending demand, which is fulfilled when the demand callback is invoked.
Calling this method when there is already a pending demand results in an
IllegalStateExceptionto be thrown.If the invocation of the demand callback throws an exception, then
Content.Source.fail(Throwable)is called.- Specified by:
 demandin interfaceContent.Source- Parameters:
 demandCallback- the demand callback to invoke when there is a content chunk available.- See Also:
 
 - 
getTrailers
HttpFields getTrailers()- Returns:
 - the HTTP trailers of this 
Request, ornullif they are not present 
 - 
getTimeStamp
Get the millisecond timestamp at which the request was created, obtained with
System.currentTimeMillis(). This method should be used for wall clock time, rather thangetHeadersNanoTime(), which is appropriate for measuring latencies.- Returns:
 - The timestamp that the request was received/created in milliseconds
 
 - 
getBeginNanoTime
long getBeginNanoTime()Get the nanoTime at which the request arrived to a connector, obtained via
System.nanoTime(). This method can be used when measuring latencies.- Returns:
 - The nanoTime at which the request was received/created in nanoseconds
 
 - 
getHeadersNanoTime
long getHeadersNanoTime()Get the nanoTime at which the request headers were parsed, obtained via
System.nanoTime(). This method can be used when measuring latencies.- Returns:
 - The nanoTime at which the request was ready in nanoseconds
 
 - 
isSecure
boolean isSecure() - 
read
Content.Chunk read()Reads a chunk of content.
See how to use this method idiomatically.
The returned chunk could be:
null, to signal that there isn't a chunk of content available- an 
Content.Chunkinstance with non nullContent.Chunk.getFailure(), to signal that there was a failure trying to produce a chunk of content, or that the content production has beenfailedexternally - a 
Content.Chunkinstance, containing the chunk of content. 
Once a read returns an
Content.Chunkinstance with non-nullContent.Chunk.getFailure()then if the failure islastfurther reads will continue to return the same failure chunk instance, otherwise furtherread()operations may return different non-failure chunks.Once a read returns a
last chunk, further reads will continue to return a last chunk (although the instance may be different).The content reader code must ultimately arrange for a call to
Retainable.release()on the returnedContent.Chunk.Additionally, prior to the ultimate call to
Retainable.release(), the reader code may make additional calls toRetainable.retain(), that must ultimately be matched by a correspondent number of calls toRetainable.release().Concurrent reads from different threads are not recommended, as they are inherently in a race condition.
Reads performed outside the invocation context of a
demand callbackare allowed. However, reads performed with a pending demand are inherently in a race condition (the thread that reads with the thread that invokes the demand callback).In addition, the returned
Content.Chunkmay be aTrailersinstance, in case of request content trailers.- Specified by:
 readin interfaceContent.Source- Returns:
 - a chunk of content, possibly a failure instance, or 
null - See Also:
 
 - 
consumeAvailable
boolean consumeAvailable()Consume any available content. This bypasses any request wrappers to process the content inread()and reads directly from theHttpStream. This reads until there is no content currently available, or it reaches EOF. TheHttpConfiguration.setMaxUnconsumedRequestContentReads(int)configuration can be used to configure how many reads will be attempted by this method.- Returns:
 - true if the content was fully consumed.
 
 - 
push
Pushes the given
resourceto the client.- Parameters:
 resource- the resource to push- Throws:
 UnsupportedOperationException- if the push functionality is not supported- See Also:
 
 - 
addIdleTimeoutListener
Adds a listener for idle timeouts.
The listener is a predicate function that should return
trueto indicate that the idle timeout should be handled by the container as a fatal failure (seeaddFailureListener(Consumer)); orfalseto ignore that specific timeout and for another timeout to occur after another idle period.Idle timeout listeners are only invoked if there are no pending
demand(Runnable)orResponse.write(boolean, ByteBuffer, Callback)operations.Listeners are processed in the same order they are added, and the first that returns
truestops the processing of subsequent listeners, which are therefore not invoked.- Parameters:
 onIdleTimeout- the idle timeout listener as a predicate function- See Also:
 
 - 
addFailureListener
Adds a listener for asynchronous fatal failures.
When a listener is called, the effects of the failure have already taken place:
- Pending 
demand(Runnable)have been woken up. - Calls to 
read()will return theThrowablefailure. - Pending and new 
Response.write(boolean, ByteBuffer, Callback)calls will be failed by callingCallback.failed(Throwable)on the callback passed toResponse.write(boolean, ByteBuffer, Callback). 
Listeners are processed in the same order they are added.
- Parameters:
 onFailure- the failure listener as a consumer function- See Also:
 
 - Pending 
 - 
getTunnelSupport
TunnelSupport getTunnelSupport() - 
addHttpStreamWrapper
Add aHttpStream.Wrapperto the currentHttpStream.- Parameters:
 wrapper- A function that wraps the passed stream.- See Also:
 
 - 
addCompletionListener
Adds a completion listener that is an optimized equivalent to overriding the
Callback.succeeded()andCallback.failed(Throwable)methods of aHttpStream.Wrappercreated by a call toaddHttpStreamWrapper(Function).Because adding completion listeners relies on
HttpStreamwrapping, the completion listeners are invoked in reverse order they are added.In the case of a failure, the
Throwablecause is passed to the listener, but unlikeaddFailureListener(Consumer)listeners, which are called when the failure occurs, completion listeners are called only once theHttpStreamis completed at the very end of processing. - 
getSession
Get a
Sessionassociated with the request. Sessions may not be supported by a given configuration, in which casenullwill be returned.- Parameters:
 create- True if the session should be created for the request.- Returns:
 - The session associated with the request or 
null. 
 - 
asReadOnly
Returns a copy of the request that throwsUnsupportedOperationExceptionfrom all mutative methods.- Returns:
 - a copy of the request
 
 - 
getHostName
 - 
getLocalAddr
 - 
getLocalPort
 - 
getRemoteAddr
 - 
getRemotePort
 - 
getServerName
Get the logical name the request was sent to, which may be from the authority of the request; the configured server authority; the actual network name of the server;- Parameters:
 request- The request to get the server name of- Returns:
 - The logical server name or null if it cannot be determined.
 
 - 
getServerPort
Get the logical port a request was received on, which may be from the authority of the request; the configured server authority; the default port for the scheme; or the actual network port.- Parameters:
 request- The request to get the port of- Returns:
 - The port for the request if it can be determined, otherwise -1
 
 - 
getLocales
 - 
asInputStream
 - 
getCharset
static Charset getCharset(Request request) throws IllegalCharsetNameException, UnsupportedCharsetException Get aCharsetfrom the requestHttpHeader.CONTENT_TYPE, if any.- Parameters:
 request- The request.- Returns:
 - A 
Charsetor null - Throws:
 IllegalCharsetNameException- If the charset name is illegalUnsupportedCharsetException- If no support for the charset is available
 - 
extractQueryParameters
 - 
extractQueryParameters
 - 
getParameters
 - 
getParametersAsync
@Deprecated(forRemoval=true, since="12.0.16") static CompletableFuture<Fields> getParametersAsync(Request request) Deprecated, for removal: This API element is subject to removal in a future version.useonParameters(Request, Promise.Invocable)instead. - 
onParameters
Asynchronous version ofgetParameters(Request).- Parameters:
 request- the requestpromise- the promise that will be completed with the parameters
 - 
getCookies
 - 
getMultiPartConfig
Get a
MultiPartConfig.Buildergiven aRequestand a location.If the location is null this will extract the
Contexttemp directory from the request. ThemaxHeaderSize,MultiPartCompliance,ComplianceViolation.Listenerare also extracted from the request. Additional settings can be configured through theMultiPartConfig.Builderwhich is returned.- Parameters:
 request- the request.location- the temp directory location, or null to use the context default.- Returns:
 - a 
MultiPartConfigwith settings extracted from the request. 
 - 
toRedirectURI
Deprecated.Generate a proper "Location" header for redirects.- Parameters:
 request- the request the redirect should be based on (needed when relative locations are provided, so that server name, scheme, port can be built out properly)location- the location URL to redirect to (can be a relative path)- Returns:
 - the full redirect "Location" URL (including scheme, host, port, path, etc...)
 
 - 
serveAs
Return a request with itsHttpURIchanged to the supplied target. If the passed request or any of the requests that it wraps implementsRequest.ServeAsthenRequest.ServeAs.wrap(Request, HttpURI)will be used to do the wrap, otherwise a simpleRequest.Wrappermay be returned.- Parameters:
 request- the original request.uri- the new URI to target.- Returns:
 - the possibly wrapped request to target the new URI.
 
 - 
as
 - 
asInContext
Unwrap a Request back to the given type, ensuring that we do not cross a context boundary (as might be the case during cross-context dispatch).- Parameters:
 request- the possibly wrapped request to unwraptype- the type to unwrap to- Returns:
 - the request unwrapped back to the given type, or null if it cannot be unwrapped to that type or a context boundary is crossed.
 
 - 
get
 - 
unWrap
 - 
getContentBytesRead
 - 
newHttpURIFrom
Creates a new
HttpURIfrom the given Request's HttpURI and the given path in context.For example, for
contextPath=/ctx,request.httpURI=http://host/ctx/path?a=b, andnewPathInContext=/newPath, the returned HttpURI ishttp://host/ctx/newPath?a=b.- Parameters:
 request- The request to base the new HttpURI on.newEncodedPathInContext- The new path in context for the new HttpURI- Returns:
 - A new immutable HttpURI with the path in context replaced, but query string and path parameters retained.
 
 - 
getAuthenticationState
- Parameters:
 request- The request to enquire.- Returns:
 - the minimal 
Request.AuthenticationStateof the request, or null if no authentication in process. 
 - 
setAuthenticationState
- Parameters:
 request- The request to enquire.state- theRequest.AuthenticationStateof the request, or null if no authentication in process.
 
 - 
 
onParameters(Request, Promise.Invocable)instead.