public class WebContext extends Object implements sirius.kernel.async.SubContext
This can be used to obtain all infos received for a HTTP request and also to create an appropriate response.
This context can either be passed along as variable or be accessed using CallContext.get(Class)
Modifier and Type | Field and Description |
---|---|
protected static boolean |
addP3PHeader |
protected long |
committed |
protected sirius.kernel.commons.Callback<sirius.kernel.async.CallContext> |
completionCallback |
protected Attribute |
content |
protected ContentHandler |
contentHandler |
protected static String |
contentSecurityPolicy |
protected Map<String,Cookie> |
cookiesOut |
protected static boolean |
corsAllowAll |
protected static boolean |
forceHSTS |
protected boolean |
hidePost |
protected static int |
hstsMaxAge |
static String |
HTTP_DATE_FORMAT
Date format used by HTTP date headers
|
protected String |
microtimingKey |
protected InterfaceHttpPostRequestDecoder |
postDecoder |
protected HttpRequest |
request |
protected boolean |
responseCommitted |
protected boolean |
responseCompleted |
protected Boolean |
ssl |
protected long |
started |
protected UserAgent |
userAgent |
Constructor and Description |
---|
WebContext() |
Modifier and Type | Method and Description |
---|---|
void |
addFileToCleanup(File file)
Adds a file to the cleanup list.
|
void |
cacheUserMessages()
Caches user messages to show them with the next request.
|
void |
clearCachedUserMessages()
Clears all previously cached user messages
|
void |
clearSession()
Clears (invalidated) the client session by removing all values.
|
static UserMessageCache |
createDistributedReadOnceCache(String name)
Creates a distributed
UserMessageCache if a DistributedUserMessageCacheFactory is implemented and can be
injected. |
void |
deleteCookie(String name)
Removes the given cookie from the cookies sent back to the client.
|
void |
detach() |
static InetAddress |
determineRemoteIP(ChannelHandlerContext ctx,
HttpRequest request)
Tries to determine the effective remote IP for the given context and request.
|
WebContext |
enableTiming(String key)
Enables microtiming for this request.
|
boolean |
ensureSafePOST()
Determines if the current request is a POST request with checking for a valid CSRF-token.
|
sirius.kernel.async.SubContext |
fork() |
long |
generateLocalId()
Generates an ID (numeric value) which is unique withing this HTTP request.
|
sirius.kernel.commons.Value |
get(String key)
Returns a value or parameter supplied by the request.
|
String |
getBaseURL()
Returns the base url (the protocol + host) for which this request was made.
|
InputStream |
getContent()
Provides the body of the request as stream.
|
File |
getContentAsCopy()
Returns the content of the HTTP request as file on disk.
|
File |
getContentAsFile()
Returns the content of the HTTP request as file on disk.
|
Charset |
getContentCharset()
Returns the charset of the body of the request
|
long |
getContentSize()
Returns the size in bytes of the body of the request.
|
Cookie |
getCookie(String name)
Returns a cookie with the given name, sent by the client
|
Collection<Cookie> |
getCookies()
Returns all cookies submitted by the client
|
String |
getCookieValue(String name)
Returns the data of the given client cookie wrapped as Value
|
ChannelHandlerContext |
getCtx()
Provides access to the underlying ChannelHandlerContext
|
long |
getDateHeader(CharSequence header)
Returns the value of a date header as UNIX timestamp in milliseconds.
|
String |
getDynamicAssetToken()
Returns a token which can be added to dynamic asset-URLS (/asset/dynamic/TOKEN/...) to force a reload of the
specified resource.
|
FileUpload |
getFileData(String key)
Returns the file upload supplied for the given key.
|
sirius.kernel.commons.Value |
getFirstFilled(String... keys)
Returns the first non empty value for the given keys.
|
String |
getHeader(CharSequence header)
Returns the request header with the given name
|
sirius.kernel.commons.Value |
getHeaderValue(CharSequence header)
Returns the request header wrapped as Value
|
HttpData |
getHttpData(String key)
Returns the posted part with the given key.
|
com.alibaba.fastjson.JSONObject |
getJSONContent()
Returns the body of the HTTP request as JSON data.
|
String |
getLang()
Returns the accepted language of the client as two-letter language code.
|
protected Collection<Cookie> |
getOutCookies()
Returns all cookies to be sent to the client.
|
String |
getParameter(String key)
Returns the query string or POST parameter with the given name.
|
Collection<String> |
getParameterNames()
Returns a collection of all parameters names.
|
List<String> |
getParameters(String key)
Returns all query string or POST parameters with the given name.
|
InterfaceHttpPostRequestDecoder |
getPostDecoder()
Returns the post decoder used to decode the posted data.
|
String |
getQueryString()
Returns the original query string sent by the client.
|
String |
getRawRequestedURI()
Returns the raw undecoded requested URI of the underlying HTTP request, without the query string
|
InetAddress |
getRemoteIP()
Returns the remote address which sent the request
|
HttpRequest |
getRequest()
Provides access to the underlying netty HttpRequest
|
String |
getRequestedURI()
Returns the decoded requested URI of the underlying HTTP request, without the query string
|
String |
getRequestedURL()
Returns the complete URL as requested by the browser.
|
Charset |
getRequestEncoding()
Tries to determine the charset used for the INCOMING request.
|
List<String> |
getSessionKeys()
Returns a list of all known session keys for the current session
|
sirius.kernel.commons.Value |
getSessionValue(String key)
Loads a value from the client session
|
UserAgent |
getUserAgent()
Returns
UserAgent for easy access to the user agent used for this request. |
sirius.kernel.xml.StructuredInput |
getXMLContent()
Returns the body of the HTTP request as XML data.
|
boolean |
hasContent()
Determines if a content is available for this request.
|
boolean |
hasParameter(String key)
Determines if the parameter with the given name is contained in the request.
|
void |
hidePost()
Hide the fact that this request is a POST request.
|
boolean |
isContentProbablyXML()
Determines if the content body might contain XML (rather than JSON).
|
static boolean |
isCurrentRequestSSL()
Determines if the current request is secured by SSL.
|
boolean |
isLongCall()
Determines if this request was marked as long call.
|
boolean |
isPOST()
Deprecated.
use
isUnsafePOST() and isSafePOST() instead |
boolean |
isResponseCommitted()
Determines if a response was already committed.
|
boolean |
isSafePOST()
Determines if the current request is a POST request with checking for a valid CSRF-token.
|
boolean |
isSSL()
Determines if this is an HTTPS (SSL protected) call.
|
boolean |
isTrusted()
Determines if the request is from a trusted IP.
|
boolean |
isUnsafePOST()
Determines if the current request is a POST request without checking for a valid CSRF-token.
|
boolean |
isValid()
Determines if this context is attached to a request or not.
|
void |
markAsLongCall()
Marks the request as long call.
|
void |
onComplete(sirius.kernel.commons.Callback<sirius.kernel.async.CallContext> onComplete)
Used to provide a handle which is invoked once the call is completely handled.
|
sirius.kernel.commons.Value |
require(String... keys)
Returns the value provided for the given key(s) or reports an error if no non empty value was found.
|
Response |
respondWith()
Creates a response for this request.
|
void |
restoreCachedMessages()
Invoked by
UserContext.getMessages() to fetch and apply all previously cached message. |
void |
setAttribute(String key,
Object value)
Sets an attribute for the current request.
|
void |
setClientCookie(String name,
String value,
long maxAgeSeconds)
Sets a cookie value to be sent back to the client.
|
void |
setContentCharset(Charset charset)
Sets the charset of the body of the request.
|
void |
setContentHandler(ContentHandler handler)
Can be set from within
WebDispatcher.preparePreDispatch(WebContext) to manually handle incoming content. |
void |
setCookie(Cookie cookie)
Sets the given cookie to be sent back to the client
|
void |
setCookie(String name,
String value,
long maxAgeSeconds)
Sets a http only cookie value to be sent back to the client.
|
protected void |
setCtx(ChannelHandlerContext ctx)
Sets the ChannelHandlerContext for this context.
|
void |
setCustomSessionCookieTTL(Duration customSessionCookieTTL)
Sets an explicit session cookie TTL (time to live).
|
void |
setHTTPSessionCookie(String name,
String value)
Sets a http only cookie value to be sent back to the client.
|
protected void |
setRequest(HttpRequest request)
Sets the underlying HttpRequest
|
void |
setSessionCookie(String name,
String value)
Sets a cookie value to be sent back to the client
The generated cookie will be a session cookie and varnish once the user agent is closed
|
void |
setSessionValue(String key,
Object value)
Stores a value in the client session.
|
String |
toString() |
sirius.kernel.commons.Tuple<String,String> |
tryBasicAuthentication(String realm)
Tries to perform a HTTP Basic authentication by parsing the Authorization header.
|
WebContext |
withCustomPath(String path)
Overwrites the path with the given one.
|
WebContext |
withCustomURI(String uri)
Overwrites the uri with the given one.
|
protected HttpRequest request
protected InterfaceHttpPostRequestDecoder postDecoder
protected boolean hidePost
protected Attribute content
protected String microtimingKey
protected volatile boolean responseCommitted
protected volatile boolean responseCompleted
protected sirius.kernel.commons.Callback<sirius.kernel.async.CallContext> completionCallback
protected Boolean ssl
protected ContentHandler contentHandler
protected volatile long started
protected volatile long committed
protected UserAgent userAgent
protected static boolean addP3PHeader
protected static String contentSecurityPolicy
protected static boolean corsAllowAll
protected static boolean forceHSTS
protected static int hstsMaxAge
public static final String HTTP_DATE_FORMAT
public ChannelHandlerContext getCtx()
public WebContext enableTiming(String key)
If null is passed in as key, the request uri is used.
If the microtiming was already enabled, it will remain enabled, with the original key
key
- the key used to pass to the microtiming framework.public boolean isValid()
public void onComplete(sirius.kernel.commons.Callback<sirius.kernel.async.CallContext> onComplete)
Note that calling this method, removes the last completion handler.
onComplete
- the handler to be invoked once the request is completely handledprotected void setCtx(ChannelHandlerContext ctx)
ctx
- the channel handler context to usepublic HttpRequest getRequest()
protected void setRequest(HttpRequest request)
request
- the request on which this context is basedpublic boolean isLongCall()
This will effectively disable the idle timeout for this request.
public void markAsLongCall()
This will disable all idle timeout checks for this request.
public void setContentHandler(ContentHandler handler)
WebDispatcher.preparePreDispatch(WebContext)
to manually handle incoming content.handler
- the handler to be supplied with content. If null, the default (memory/disk buffering)
handler is applied.@Nonnull public sirius.kernel.commons.Value get(String key)
This method first checks if an attribute with the given key exists. If not, the query string is scanned. After that, the posted content is looked through to find an appropriate value.
key
- the key used to look for the valuepublic sirius.kernel.commons.Value getFirstFilled(String... keys)
This is a boilerplate method for get(String)
in case the same value could be sent via different
parameter names.
keys
- the keys to checkpublic boolean hasParameter(String key)
key
- the parameter to check forpublic sirius.kernel.commons.Value require(String... keys)
The first non empty value is used. If all values are empty, an exception is thrown.
keys
- the keys to check for a valuepublic HttpData getHttpData(String key)
key
- used to specify which part of the post request should be returned.public FileUpload getFileData(String key)
key
- used to specify which part of the post request should be used.public long generateLocalId()
This can be used to create IDs for HTML elements and the like.
Long.MAX_VALUE
IDs are requested.public void setAttribute(String key, Object value)
Attributes are neither stored nor transmitted to the client. Therefore they are only visible during the processing of this request.
key
- name of the attributevalue
- value of the attributepublic void setCustomSessionCookieTTL(@Nullable Duration customSessionCookieTTL)
If a non null value is given, this will overwrite defaultSessionCookieTTL
for this request/response.
customSessionCookieTTL
- the new TTL for the client session cookie.public void setSessionValue(String key, Object value)
As this session is transmitted to the client, the given value should not be large and needs a parseable string representation
key
- the name of th value to setvalue
- the value to setpublic sirius.kernel.commons.Value getSessionValue(String key)
key
- the name of the value to loadpublic List<String> getSessionKeys()
public void clearSession()
public void cacheUserMessages()
In some interaction patterns, we cannot directly show generated messages to a user. Therefore these are cached and retrieved with the next "full" request.
When sending a redirect or performing an ajax call + a refresh, it is not possible to show messages to a user.
Therefore we cache those messages and return them with the next call to UserContext.getMessages()
.
public static UserMessageCache createDistributedReadOnceCache(String name)
UserMessageCache
if a DistributedUserMessageCacheFactory
is implemented and can be
injected. A LocalUserMessageCache
otherwise.
Considers the config cache.[name].ttl for the cache.
name
- The cache name.public void restoreCachedMessages()
UserContext.getMessages()
to fetch and apply all previously cached message.public void clearCachedUserMessages()
public String getRequestedURI()
public String getRawRequestedURI()
public String getBaseURL()
public String getRequestedURL()
public InetAddress getRemoteIP()
public static InetAddress determineRemoteIP(ChannelHandlerContext ctx, HttpRequest request)
This is the remote address of the channel. However, if recognized as a proxy, we use the last IP address given in the X-Forarded-For header.
ctx
- the channel context used to determine the physical IPrequest
- the request used to read the appropriate headers for reverse proxiespublic boolean isTrusted()
WebServer.trustedIPs
), false
otherwisepublic boolean isSSL()
public static boolean isCurrentRequestSSL()
This is boilerplate for: CallContext.getCurrent().get(WebContext.class).isSSL()
public String getParameter(String key)
If a POST request with query string is present, parameters in the query string have precedence.
key
- the name of the parameter to fetchpublic List<String> getParameters(String key)
If a POST request with query string is present, parameters in the query string have precedence. If values in the query string are found, the POST parameters are discarded and not added to the resulting list.
key
- the name of the parameter to fetchpublic WebContext withCustomURI(String uri)
This can be used to control dispatching or to even re-dispatch a request for another destination.
Note however, that only the the requestedURI, queryString and the rawRequestedURI are overwritten, not the one of the underlying request.
uri
- the new uri to use. The uri and its query string will be parsed and the internal fields are updated
accordingly.public WebContext withCustomPath(String path)
This can be used to control dispatching or to even re-dispatch a request for another destination.
Note however, that the original query string and its parameters remain.
path
- the new path to usepublic Collection<Cookie> getCookies()
public Cookie getCookie(String name)
name
- the cookie to fetch@Nullable public String getCookieValue(String name)
name
- the cookie to fetchpublic void setCookie(Cookie cookie)
cookie
- the cookie to send to the clientpublic void setSessionCookie(String name, String value)
The generated cookie will be a session cookie and varnish once the user agent is closed
name
- the cookie to createvalue
- the contents of the cookiepublic void setHTTPSessionCookie(String name, String value)
The generated cookie will be a session cookie and varnish once the user agent is closed. Also this cookie will not be accessible by JavaScript and therefore slightly more secure.
name
- the cookie to createvalue
- the contents of the cookiepublic void setClientCookie(String name, String value, long maxAgeSeconds)
Note that his cookie is also available to JavaScript which is inherent less secure.
name
- the cookie to createvalue
- the contents of the cookiemaxAgeSeconds
- contains the max age of this cookie in secondspublic void setCookie(String name, String value, long maxAgeSeconds)
name
- the cookie to createvalue
- the contents of the cookiemaxAgeSeconds
- contains the max age of this cookie in secondspublic void deleteCookie(@Nonnull String name)
name
- the cookie to deleteprotected Collection<Cookie> getOutCookies()
Response
to construct an appropriate header.public String getLang()
public Response respondWith()
public boolean isResponseCommitted()
If a response is committed a HTTP state and some headers have already been sent. Therefore a new / other response cannot be created to this request.
@Nullable public String getHeader(CharSequence header)
header
- name of the header to fetch.@Nonnull public sirius.kernel.commons.Value getHeaderValue(CharSequence header)
header
- name of the header to fetch.public long getDateHeader(CharSequence header)
header
- the name of the header to fetch@Nullable public sirius.kernel.commons.Tuple<String,String> tryBasicAuthentication(String realm)
If no such header is found or if the contents are malformed, an 401 UNAUTHORIZED response will be generated
(Response.unauthorized(String)
) and null will be returned.
In case the username and password returned by this method are invalid, use
Response.unauthorized(String)
to notify the client.
realm
- the realm to report to the client in case of missing or malformed credentialspublic Collection<String> getParameterNames()
This will combine both, the query string and POST parameters.
@Nonnull public String getQueryString()
This will not include the initial question mark.
public InterfaceHttpPostRequestDecoder getPostDecoder()
@Deprecated public boolean isPOST()
isUnsafePOST()
and isSafePOST()
insteadA POST request signal the server to alter its state, knowing that side effects will occur.
public boolean isSafePOST()
A POST request signal the server to alter its state, knowing that side effects will occur.
public boolean isUnsafePOST()
A POST request signal the server to alter its state, knowing that side effects will occur.
@CheckReturnValue public boolean ensureSafePOST()
isSafePOST()
.
A POST request signal the server to alter its state, knowing that side effects will occur.
public void hidePost()
Sometimes it is useful to make isPOST()
return false even if the
current request is a POST requests. Login forms woule be one example. As
a login request is sent to any URL, we don't want a common POST handler to
trigger on that post data.
public InputStream getContent() throws IOException
IOException
- in case of an io errorpublic void setContentCharset(Charset charset)
charset
- the charset to be applied to the body of the requestpublic Charset getContentCharset()
public long getContentSize()
public File getContentAsFile() throws IOException
Note that the file will be deleted once the request is completely handled.
IOException
- in case of an IO error@Nullable public File getContentAsCopy() throws IOException
Note that the file will NOT be deleted once the request is completely handled. Therefore the caller must delete this file once it has been processed.
IOException
- in case of an IO errorpublic void addFileToCleanup(File file)
All files in this list will be deleted once the request is completely handled. This can be used to wipe any intermediate files created while handling this request.
file
- the file to be deleted once the request is completed.public sirius.kernel.xml.StructuredInput getXMLContent()
Note that all data is loaded into the heap. Therefore certain limits apply. If the data is too large, an exception will be thrown.
public com.alibaba.fastjson.JSONObject getJSONContent()
Note that all data is loaded into the heap. Therefore certain limits apply. If the data is too large, an exception will be thrown.
public Charset getRequestEncoding()
This is not to be confused with the desired charset of the outgoing data (specified via Accept-Charset).
public boolean hasContent()
public boolean isContentProbablyXML()
The detection is kind of crude as we only check if the first non whitespace character is a <
public String getDynamicAssetToken()
public UserAgent getUserAgent()
UserAgent
for easy access to the user agent used for this request. Also it provides access to
some assumptions based on the user agent e.g. which device was used.public sirius.kernel.async.SubContext fork()
fork
in interface sirius.kernel.async.SubContext
public void detach()
detach
in interface sirius.kernel.async.SubContext
Copyright © 2018. All rights reserved.