Class HttpServerExchange

java.lang.Object
io.undertow.util.AbstractAttachable
io.undertow.server.HttpServerExchange
All Implemented Interfaces:
Attachable

public final class HttpServerExchange extends AbstractAttachable
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, Richard Opalka
  • Field Details

    • REQUEST_ATTRIBUTES

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

      public static final AttachmentKey<String> REMOTE_USER
      Attachment key that can be used to hold a remotely authenticated user
    • SECURE_REQUEST

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

      protected io.undertow.server.HttpServerExchange.ReadDispatchChannel requestChannel
      The actual request channel. May be null if it has not been created yet.
  • Constructor Details

  • Method Details

    • getProtocol

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

      public HttpServerExchange setProtocol(HttpString protocol)
      Sets the http protocol
      Parameters:
      protocol -
    • isHttp09

      public boolean isHttp09()
      Determine whether this request conforms to HTTP 0.9.
      Returns:
      true if the request protocol is equal to Protocols.HTTP_0_9, false otherwise
    • isHttp10

      public boolean isHttp10()
      Determine whether this request conforms to HTTP 1.0.
      Returns:
      true if the request protocol is equal to Protocols.HTTP_1_0, false otherwise
    • isHttp11

      public boolean isHttp11()
      Determine whether this request conforms to HTTP 1.1.
      Returns:
      true if the request protocol is equal to Protocols.HTTP_1_1, false otherwise
    • isSecure

      public boolean isSecure()
    • getRequestMethod

      public HttpString getRequestMethod()
      Get the HTTP request method. Normally this is one of the strings listed in Methods.
      Returns:
      the HTTP request method
    • setRequestMethod

      public HttpServerExchange setRequestMethod(HttpString 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
    • getRequestURI

      public String getRequestURI()
      The original request URI. This will include the host name, protocol 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)
      Set query string. Leading ? char will be removed automatically.
    • 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.

    • getRequestCharset

      public String getRequestCharset()
      Returns the request charset. If none was explicitly specified it will return "ISO-8859-1", which is the default charset for HTTP requests.
      Returns:
      The character encoding
    • getResponseCharset

      public String getResponseCharset()
      Returns the response charset. If none was explicitly specified it will return "ISO-8859-1", which is the default charset for HTTP requests.
      Returns:
      The character encoding
    • 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
    • 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
    • getConnection

      public ServerConnection getConnection()
      Get the underlying HTTP connection.
      Returns:
      the underlying HTTP connection
    • isPersistent

      public boolean isPersistent()
    • isInIoThread

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

      public boolean isUpgrade()
      Returns:
      True if this exchange represents an upgrade response
    • 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

      @Deprecated public HttpServerExchange dispatch()
      Deprecated.
      dispatch(Executor, Runnable) should be used instead of this method, as it is hard to use safely. Use SameThreadExecutor.INSTANCE if you do not want to dispatch to another thread.
      Returns:
      this exchange
    • 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
    • upgradeChannel

      public HttpServerExchange upgradeChannel(HttpUpgradeListener 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 from AbstractServerConnection.getChannel()
      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, HttpUpgradeListener 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 from AbstractServerConnection.getChannel()
      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
    • acceptConnectRequest

      public HttpServerExchange acceptConnectRequest(HttpUpgradeListener connectListener)
      Parameters:
      connectListener -
      Returns:
    • 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
    • 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
    • getRequestHeaders

      public HeaderMap getRequestHeaders()
      Get the request headers.
      Returns:
      the request headers
    • getRequestContentLength

      public long getRequestContentLength()
      Returns:
      The content length of the request, or -1 if it has not been set
    • getResponseHeaders

      public HeaderMap getResponseHeaders()
      Get the response headers.
      Returns:
      the response headers
    • getResponseContentLength

      public long getResponseContentLength()
      Returns:
      The content length of the response, or -1 if it has not been set
    • 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

      @Deprecated public Map<String,Cookie> getRequestCookies()
      Deprecated.
      Returns:
      A mutable map of request cookies
    • setRequestCookie

      public HttpServerExchange setRequestCookie(Cookie cookie)
      Sets a request cookie
      Parameters:
      cookie - The cookie
    • getRequestCookie

      public Cookie getRequestCookie(String name)
    • requestCookies

      public Iterable<Cookie> requestCookies()
      Returns unmodifiable enumeration of request cookies.
      Returns:
      A read-only enumeration of request cookies
    • setResponseCookie

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

      @Deprecated public Map<String,Cookie> getResponseCookies()
      Deprecated.
      use either responseCookies() or setResponseCookie(Cookie) methods instead
      Returns:
      A mutable map of response cookies
    • responseCookies

      public Iterable<Cookie> responseCookies()
      Returns unmodifiable enumeration of response cookies.
      Returns:
      A read-only enumeration of response cookies
    • isResponseStarted

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

      public org.xnio.channels.StreamSourceChannel getRequestChannel()
      Get the inbound request. If there is no request body, calling this method may cause the next request to immediately be processed. The Channel.close() or SuspendableReadChannel.shutdownReads() method must be called at some point after the request is processed to prevent resource leakage and to allow the next request to proceed. Any unread content will be discarded.
      Returns:
      the channel for the inbound request, or null if another party already acquired the channel
    • isRequestChannelAvailable

      public boolean isRequestChannelAvailable()
    • isComplete

      public boolean isComplete()
      Returns true if the completion handler for this exchange has been invoked, and the request is considered finished.
    • isRequestComplete

      public boolean isRequestComplete()
      Returns true if all data has been read from the request, or if there was not data.
      Returns:
      true if the request is complete
    • isResponseComplete

      public boolean isResponseComplete()
      Returns:
      true if the responses is complete
    • getResponseChannel

      public org.xnio.channels.StreamSinkChannel getResponseChannel()
      Get the response channel. The channel must be closed and fully flushed before the next response can be started. In order to close the channel you must first call SuspendableWriteChannel.shutdownWrites(), and then call SuspendableWriteChannel.flush() until it returns true. Alternatively you can call endExchange(), which will close the channel as part of its cleanup.

      Closing a fixed-length response before the corresponding number of bytes has been written will cause the connection to be reset and subsequent requests to fail; thus it is important to ensure that the proper content length is delivered when one is specified. The response channel may not be writable until after the response headers have been sent.

      If this method is not called then an empty or default response body will be used, depending on the response code set.

      The returned channel will begin to write out headers when the first write request is initiated, or when SuspendableWriteChannel.shutdownWrites() is called on the channel with no content being written. Once the channel is acquired, however, the response code and headers may not be modified.

      Returns:
      the response channel, or null if another party already acquired the channel
    • getResponseSender

      public Sender getResponseSender()
      Get the response sender.

      For blocking exchanges this will return a sender that uses the underlying output stream.

      Returns:
      the response sender, or null if another party already acquired the channel or the sender
      See Also:
    • getRequestReceiver

      public Receiver getRequestReceiver()
    • isResponseChannelAvailable

      public boolean isResponseChannelAvailable()
      Returns:
      true if getResponseChannel() has not been called
    • getResponseCode

      @Deprecated public int getResponseCode()
      Deprecated.
      Get the status code.
      Returns:
      the status code
      See Also:
    • setResponseCode

      @Deprecated public HttpServerExchange setResponseCode(int statusCode)
      Deprecated.
      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
      See Also:
    • getStatusCode

      public int getStatusCode()
      Get the status code.
      Returns:
      the status code
    • 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
    • setReasonPhrase

      public HttpServerExchange setReasonPhrase(String message)
      Sets the HTTP reason phrase. Depending on the protocol this may or may not be honoured. In particular HTTP2 has removed support for the reason phrase. This method should only be used to interact with legacy frameworks that give special meaning to the reason phrase.
      Parameters:
      message - The status message
      Returns:
      this exchange
    • getReasonPhrase

      public String getReasonPhrase()
      Returns:
      The current reason phrase
    • addRequestWrapper

      public HttpServerExchange addRequestWrapper(ConduitWrapper<org.xnio.conduits.StreamSourceConduit> wrapper)
      Adds a ConduitWrapper to the request wrapper chain.
      Parameters:
      wrapper - the wrapper
    • addResponseWrapper

      public HttpServerExchange addResponseWrapper(ConduitWrapper<org.xnio.conduits.StreamSinkConduit> wrapper)
      Adds a ConduitWrapper to the response wrapper chain.
      Parameters:
      wrapper - the wrapper
    • startBlocking

      public BlockingHttpExchange startBlocking()
      Calling this method puts the exchange in blocking mode, and creates a BlockingHttpExchange object to store 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.

      Returns:
      The existing blocking exchange, if any
    • startBlocking

      public BlockingHttpExchange startBlocking(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.

      Returns:
      The existing blocking exchange, if any
    • isBlocking

      public boolean isBlocking()
      Returns true if startBlocking() or startBlocking(BlockingHttpExchange) has been called.
      Returns:
      true If this is a blocking HTTP server exchange
    • getInputStream

      public InputStream getInputStream()
      Returns:
      The input stream
      Throws:
      IllegalStateException - if startBlocking() has not been called
    • getOutputStream

      public OutputStream getOutputStream()
      Returns:
      The output stream
      Throws:
      IllegalStateException - if startBlocking() has not been called
    • getRequestStartTime

      public long getRequestStartTime()
      Returns:
      The request start time using the JVM's high-resolution time source, in nanoseconds, or -1 if this was not recorded
      See Also:
    • 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 org.xnio.XnioIoThread 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
    • toString

      public String toString()
      Overrides:
      toString in class Object