Class HttpServerExchange

java.lang.Object
io.undertow.util.AbstractAttachable
io.undertow.server.HttpServerExchange
All Implemented Interfaces:
io.undertow.httpcore.BufferAllocator, io.undertow.httpcore.CompletedListener, io.undertow.httpcore.InputChannel, io.undertow.httpcore.OutputChannel, io.undertow.httpcore.PreCommitListener, Attachable, AutoCloseable

public final class HttpServerExchange extends AbstractAttachable implements io.undertow.httpcore.BufferAllocator, io.undertow.httpcore.OutputChannel, io.undertow.httpcore.InputChannel, io.undertow.httpcore.CompletedListener, io.undertow.httpcore.PreCommitListener
An HTTP server request/response exchange. An instance of this class is constructed as soon as the request headers are fully parsed.
Author:
David M. Lloyd
  • Field Details

    • REQUEST_ATTRIBUTES

      public static final AttachmentKey<Map<String,String>> REQUEST_ATTRIBUTES
      Attachment key that can be used to hold additional request attributes
    • SECURE_REQUEST

      public static final AttachmentKey<Boolean> SECURE_REQUEST
      Attachment key that can be used as a flag of secure attribute
  • Constructor Details

    • HttpServerExchange

      public HttpServerExchange(io.undertow.httpcore.HttpExchange delegate, long maxEntitySize)
  • Method Details

    • getProtocol

      public String getProtocol()
      Get the request getProtocol string. Normally this is one of the strings listed in HttpProtocolNames.
      Returns:
      the request getProtocol string
    • protocol

      public HttpServerExchange protocol(String protocol)
      Sets the http getProtocol
      Parameters:
      protocol -
    • isSecure

      public boolean isSecure()
    • getRequestMethod

      public String getRequestMethod()
      Get the HTTP request method. Normally this is one of the strings listed in HttpMethodNames.
      Returns:
      the HTTP request method
    • requestMethod

      public HttpServerExchange requestMethod(String requestMethod)
      Set the HTTP request method.
      Parameters:
      requestMethod - the HTTP request method
    • getRequestScheme

      public String getRequestScheme()
      Get the request URI scheme. Normally this is one of http or https.
      Returns:
      the request URI scheme
    • setRequestScheme

      public HttpServerExchange setRequestScheme(String requestScheme)
      Set the request URI scheme.
      Parameters:
      requestScheme - the request URI scheme
    • getRequestId

      public String getRequestId()
    • getRequestURI

      public String getRequestURI()
      The original request URI. This will include the host name, getProtocol etc if it was specified by the client.

      This is not decoded in any way, and does not include the query string.

      Examples: GET http://localhost:8080/myFile.jsf?foo=bar HTTP/1.1 -> 'http://localhost:8080/myFile.jsf' POST /my+File.jsf?foo=bar HTTP/1.1 -> '/my+File.jsf'

    • setRequestURI

      public HttpServerExchange setRequestURI(String requestURI)
      Sets the request URI
      Parameters:
      requestURI - The new request URI
    • setRequestURI

      public HttpServerExchange setRequestURI(String requestURI, boolean containsHost)
      Sets the request URI
      Parameters:
      requestURI - The new request URI
      containsHost - If this is true the request URI contains the host part
    • isHostIncludedInRequestURI

      public boolean isHostIncludedInRequestURI()
      If a request was submitted to the server with a full URI instead of just a path this will return true. For example:

      GET http://localhost:8080/b/../my+File.jsf?foo=bar HTTP/1.1 -> true POST /my+File.jsf?foo=bar HTTP/1.1 -> false

      Returns:
      true If the request URI contains the host part of the URI
    • getRequestPath

      public String getRequestPath()
      The request path. This will be decoded by the server, and does not include the query string.

      This path is not canonicalised, so care must be taken to ensure that escape attacks are not possible.

      Examples: GET http://localhost:8080/b/../my+File.jsf?foo=bar HTTP/1.1 -> '/b/../my+File.jsf' POST /my+File.jsf?foo=bar HTTP/1.1 -> '/my File.jsf'

    • setRequestPath

      public HttpServerExchange setRequestPath(String requestPath)
      Set the request URI path.
      Parameters:
      requestPath - the request URI path
    • getRelativePath

      public String getRelativePath()
      Get the request relative path. This is the path which should be evaluated by the current handler.

      If the CanonicalPathHandler is installed in the current chain then this path with be canonicalized

      Returns:
      the request relative path
    • setRelativePath

      public HttpServerExchange setRelativePath(String relativePath)
      Set the request relative path.
      Parameters:
      relativePath - the request relative path
    • getResolvedPath

      public String getResolvedPath()
      Get the resolved path.
      Returns:
      the resolved path
    • setResolvedPath

      public HttpServerExchange setResolvedPath(String resolvedPath)
      Set the resolved path.
      Parameters:
      resolvedPath - the resolved path
    • getQueryString

      public String getQueryString()
      Returns:
      The query string, without the leading ?
    • setQueryString

      public HttpServerExchange setQueryString(String queryString)
    • getRequestURL

      public String getRequestURL()
      Reconstructs the complete URL as seen by the user. This includes scheme, host name etc, but does not include query string.

      This is not decoded.

    • getRequestContentLength

      public long getRequestContentLength()
    • getResponseContentLength

      public long getResponseContentLength()
      Returns:
      The content length of the response, or -1 if it has not been set
    • getHostName

      public String getHostName()
      Return the host that this request was sent to, in general this will be the value of the Host header, minus the port specifier.

      If this resolves to an IPv6 address it will not be enclosed by square brackets. Care must be taken when constructing URLs based on this method to ensure IPv6 URLs are handled correctly.

      Returns:
      The host part of the destination address
    • getHostAndPort

      public String getHostAndPort()
      Return the host, and also the port if this request was sent to a non-standard port. In general this will just be the value of the Host header.

      If this resolves to an IPv6 address it *will* be enclosed by square brackets. The return value of this method is suitable for inclusion in a URL.

      Returns:
      The host and port part of the destination address
    • getDelegate

      public io.undertow.httpcore.HttpExchange getDelegate()
    • getHostPort

      public int getHostPort()
      Return the port that this request was sent to. In general this will be the value of the Host header, minus the host name.
      Returns:
      The port part of the destination address
    • isPersistent

      public boolean isPersistent()
    • isInIoThread

      public boolean isInIoThread()
      Returns:
      true If the current thread in the IO thread for the exchange
    • getResponseBytesSent

      public long getResponseBytesSent()
      Returns:
      The number of bytes sent in the entity body
    • setPersistent

      public HttpServerExchange setPersistent(boolean persistent)
    • isDispatched

      public boolean isDispatched()
    • unDispatch

      public HttpServerExchange unDispatch()
    • dispatch

      public HttpServerExchange dispatch(Runnable runnable)
      Dispatches this request to the XNIO worker thread pool. Once the call stack returns the given runnable will be submitted to the executor.

      In general handlers should first check the value of isInIoThread() before calling this method, and only dispatch if the request is actually running in the IO thread.

      Parameters:
      runnable - The task to run
      Throws:
      IllegalStateException - If this exchange has already been dispatched
    • dispatch

      public HttpServerExchange dispatch(Executor executor, Runnable runnable)
      Dispatches this request to the given executor. Once the call stack returns the given runnable will be submitted to the executor.

      In general handlers should first check the value of isInIoThread() before calling this method, and only dispatch if the request is actually running in the IO thread.

      Parameters:
      runnable - The task to run
      Throws:
      IllegalStateException - If this exchange has already been dispatched
    • dispatch

      public HttpServerExchange dispatch(HttpHandler handler)
    • dispatch

      public HttpServerExchange dispatch(Executor executor, HttpHandler handler)
    • setDispatchExecutor

      public HttpServerExchange setDispatchExecutor(Executor executor)
      Sets the executor that is used for dispatch operations where no executor is specified.
      Parameters:
      executor - The executor to use
    • getDispatchExecutor

      public Executor getDispatchExecutor()
      Gets the current executor that is used for dispatch operations. This may be null
      Returns:
      The current dispatch executor
    • addExchangeCompleteListener

      public HttpServerExchange addExchangeCompleteListener(ExchangeCompletionListener listener)
    • addDefaultResponseListener

      public HttpServerExchange addDefaultResponseListener(DefaultResponseListener listener)
    • getSourceAddress

      public InetSocketAddress getSourceAddress()
      Get the source address of the HTTP request.
      Returns:
      the source address of the HTTP request
    • isComplete

      public boolean isComplete()
    • isRequestComplete

      public boolean isRequestComplete()
    • isResponseComplete

      public boolean isResponseComplete()
    • setSourceAddress

      public HttpServerExchange setSourceAddress(InetSocketAddress sourceAddress)
      Sets the source address of the HTTP request. If this is not explicitly set the actual source address of the channel is used.
      Parameters:
      sourceAddress - The address
    • getDestinationAddress

      public InetSocketAddress getDestinationAddress()
      Get the destination address of the HTTP request.
      Returns:
      the destination address of the HTTP request
    • setDestinationAddress

      public HttpServerExchange setDestinationAddress(InetSocketAddress destinationAddress)
      Sets the destination address of the HTTP request. If this is not explicitly set the actual destination address of the channel is used.
      Parameters:
      destinationAddress - The address
    • setResponseContentLength

      public HttpServerExchange setResponseContentLength(long length)
      Sets the response content length
      Parameters:
      length - The content length
    • getQueryParameters

      public Map<String,Deque<String>> getQueryParameters()
      Returns a mutable map of query parameters.
      Returns:
      The query parameters
    • addQueryParam

      public HttpServerExchange addQueryParam(String name, String param)
    • getPathParameters

      public Map<String,Deque<String>> getPathParameters()
      Returns a mutable map of path parameters
      Returns:
      The path parameters
    • addPathParam

      public HttpServerExchange addPathParam(String name, String param)
    • getRequestCookies

      public Map<String,Cookie> getRequestCookies()
      Returns:
      A mutable map of request cookies
    • setResponseCookie

      public HttpServerExchange setResponseCookie(Cookie cookie)
      Sets a response cookie
      Parameters:
      cookie - The cookie
    • getResponseCookies

      public Map<String,Cookie> getResponseCookies()
      Returns:
      A mutable map of response cookies
    • isResponseStarted

      public boolean isResponseStarted()
      Returns:
      true If the response has already been started
    • readBlocking

      public io.netty.buffer.ByteBuf readBlocking() throws IOException
      Reads some data. If all data has been read it will return null.
      Specified by:
      readBlocking in interface io.undertow.httpcore.InputChannel
      Returns:
      Throws:
      IOException - on failure
    • send1ContinueIfRequired

      public void send1ContinueIfRequired()
    • writeAsync

      public void writeAsync(String data)
      Writes the given UTF-8 data and ends the exchange
      Specified by:
      writeAsync in interface io.undertow.httpcore.OutputChannel
      Parameters:
      data - The data to write
    • writeAsync

      public void writeAsync(String data, Charset charset)
      Writes the given data in the provided charset and ends the exchange
      Specified by:
      writeAsync in interface io.undertow.httpcore.OutputChannel
      Parameters:
      data - The data to write
    • writeAsync

      public <T> void writeAsync(String data, Charset charset, boolean last, io.undertow.httpcore.IoCallback<T> callback, T context)
      Writes the given data in the provided charset and invokes the provided callback on completion
      Specified by:
      writeAsync in interface io.undertow.httpcore.OutputChannel
      Parameters:
      data - The data to write
    • writeAsync

      public <T> void writeAsync(io.netty.buffer.ByteBuf data, boolean last, io.undertow.httpcore.IoCallback<T> callback, T context)
      Specified by:
      writeAsync in interface io.undertow.httpcore.OutputChannel
    • writeBlocking

      public void writeBlocking(io.netty.buffer.ByteBuf data, boolean last) throws IOException
      Specified by:
      writeBlocking in interface io.undertow.httpcore.OutputChannel
      Throws:
      IOException
    • getStatusCode

      public int getStatusCode()
      Get the status code.
      Returns:
      the status code
    • getRequestHeader

      public String getRequestHeader(String name)
    • getRequestHeaders

      public List<String> getRequestHeaders(String name)
    • containsRequestHeader

      public boolean containsRequestHeader(String name)
    • removeRequestHeader

      public void removeRequestHeader(String name)
    • setRequestHeader

      public void setRequestHeader(String name, String value)
    • getRequestHeaderNames

      public Collection<String> getRequestHeaderNames()
    • addRequestHeader

      public void addRequestHeader(String name, String value)
    • clearRequestHeaders

      public void clearRequestHeaders()
    • clearResponseHeaders

      public void clearResponseHeaders()
    • getResponseHeader

      public String getResponseHeader(String name)
    • getResponseHeaders

      public List<String> getResponseHeaders(String name)
    • containsResponseHeader

      public boolean containsResponseHeader(String name)
    • removeResponseHeader

      public void removeResponseHeader(String name)
    • setResponseHeader

      public void setResponseHeader(String name, String value)
    • getResponseHeaderNames

      public Collection<String> getResponseHeaderNames()
    • addResponseHeader

      public void addResponseHeader(String name, String value)
    • setStatusCode

      public HttpServerExchange setStatusCode(int statusCode)
      Change the status code for this response. If not specified, the code will be a 200. Setting the status code after the response headers have been transmitted has no effect.
      Parameters:
      statusCode - the new code
      Throws:
      IllegalStateException - if a response or upgrade was already sent
    • startBlocking

      public void startBlocking(io.undertow.httpcore.BlockingHttpExchange httpExchange)
      Calling this method puts the exchange in blocking mode, using the given blocking exchange as the source of the streams.

      When an exchange is in blocking mode the input stream methods become available, other than that there is presently no major difference between blocking an non-blocking modes.

      Note that this method may be called multiple times with different exchange objects, to allow handlers to modify the streams that are being used.

    • getInputStream

      public InputStream getInputStream()
      Returns:
      The input stream
    • getOutputStream

      public OutputStream getOutputStream()
    • getRequestStartTime

      public long getRequestStartTime()
      Returns:
      The request start time, or -1 if this was not recorded
    • endExchange

      public HttpServerExchange endExchange()
      Ends the exchange by fully draining the request channel, and flushing the response channel.

      This can result in handoff to an XNIO worker, so after this method is called the exchange should not be modified by the caller.

      If the exchange is already complete this method is a noop

    • getIoThread

      public io.netty.util.concurrent.EventExecutor getIoThread()
    • getMaxEntitySize

      public long getMaxEntitySize()
      Returns:
      The maximum entity size for this exchange
    • setMaxEntitySize

      public HttpServerExchange setMaxEntitySize(long maxEntitySize)
      Sets the max entity size for this exchange. This cannot be modified after the request channel has been obtained.
      Parameters:
      maxEntitySize - The max entity size
    • getSecurityContext

      public SecurityContext getSecurityContext()
    • setSecurityContext

      public void setSecurityContext(SecurityContext securityContext)
    • addResponseCommitListener

      public void addResponseCommitListener(ResponseCommitListener listener)
      Adds a listener that will be invoked on response commit
      Parameters:
      listener - The response listener
    • readAsync

      public io.netty.buffer.ByteBuf readAsync() throws IOException
      Specified by:
      readAsync in interface io.undertow.httpcore.InputChannel
      Throws:
      IOException
    • isReadable

      public boolean isReadable()
      Specified by:
      isReadable in interface io.undertow.httpcore.InputChannel
    • setReadHandler

      public <T> void setReadHandler(BiConsumer<io.undertow.httpcore.InputChannel,T> handler, T context)
      Specified by:
      setReadHandler in interface io.undertow.httpcore.InputChannel
    • readBytesAvailable

      public int readBytesAvailable()
      Specified by:
      readBytesAvailable in interface io.undertow.httpcore.InputChannel
    • allocateBuffer

      public io.netty.buffer.ByteBuf allocateBuffer()
      Specified by:
      allocateBuffer in interface io.undertow.httpcore.BufferAllocator
    • allocateBuffer

      public io.netty.buffer.ByteBuf allocateBuffer(boolean direct)
      Specified by:
      allocateBuffer in interface io.undertow.httpcore.BufferAllocator
    • allocateBuffer

      public io.netty.buffer.ByteBuf allocateBuffer(int bufferSize)
      Specified by:
      allocateBuffer in interface io.undertow.httpcore.BufferAllocator
    • allocateBuffer

      public io.netty.buffer.ByteBuf allocateBuffer(boolean direct, int bufferSize)
      Specified by:
      allocateBuffer in interface io.undertow.httpcore.BufferAllocator
    • getBufferSize

      public int getBufferSize()
      Specified by:
      getBufferSize in interface io.undertow.httpcore.BufferAllocator
    • discardRequest

      public void discardRequest()
      Used to terminate the request in an async manner, the actual mechanism will depend on the underlying getProtocol, for example HTTP/2 may send a RST_STREAM stream if there is more data coming.

      This may result in an unclean close if it is called on a non multiplexed getProtocol

    • upgradeChannel

      public HttpServerExchange upgradeChannel(Consumer<Object> listener)
      Upgrade the channel to a raw socket. This method set the response code to 101, and then marks both the request and response as terminated, which means that once the current request is completed the raw channel can be obtained
      Throws:
      IllegalStateException - if a response or upgrade was already sent, or if the request body is already being read
    • upgradeChannel

      public HttpServerExchange upgradeChannel(String productName, Consumer<Object> listener)
      Upgrade the channel to a raw socket. This method set the response code to 101, and then marks both the request and response as terminated, which means that once the current request is completed the raw channel can be obtained
      Parameters:
      productName - the product name to report to the client
      Throws:
      IllegalStateException - if a response or upgrade was already sent, or if the request body is already being read
    • resetRequestChannel

      public void resetRequestChannel()
    • setSslSessionInfo

      public void setSslSessionInfo(io.undertow.httpcore.SSLSessionInfo info)
    • getSslSessionInfo

      public io.undertow.httpcore.SSLSessionInfo getSslSessionInfo()
    • close

      public void close()
      Specified by:
      close in interface AutoCloseable
    • getWorker

      public Executor getWorker()
    • getUndertowOptions

      public io.undertow.httpcore.UndertowOptionMap getUndertowOptions()
    • isPushSupported

      public boolean isPushSupported()
    • pushResource

      public void pushResource(String path, String method, Map<String,List<String>> requestHeaders)
    • isRequestTrailerFieldsSupported

      public boolean isRequestTrailerFieldsSupported()
    • completed

      public void completed(io.undertow.httpcore.HttpExchange exchange)
      Specified by:
      completed in interface io.undertow.httpcore.CompletedListener
    • beginExecutingHandlerChain

      public void beginExecutingHandlerChain()
    • endExecutingHandlerChain

      public void endExecutingHandlerChain()
    • runResumeReadWrite

      public void runResumeReadWrite()
    • getOutputChannel

      public io.undertow.httpcore.OutputChannel getOutputChannel()
    • getInputChannel

      public io.undertow.httpcore.InputChannel getInputChannel()
    • toString

      public String toString()
      Overrides:
      toString in class Object
    • preCommit

      public void preCommit(io.undertow.httpcore.HttpExchange exchange)
      Specified by:
      preCommit in interface io.undertow.httpcore.PreCommitListener
    • addWriteFunction

      public void addWriteFunction(io.undertow.httpcore.WriteFunction function)