public class Response extends Object
Responses are created by calling WebContext.respondWith()
.
WebContext
Modifier and Type | Field and Description |
---|---|
protected static com.ning.http.client.AsyncHttpClient |
asyncClient |
static int |
BUFFER_SIZE
Size of the internally used transfer buffers
|
protected Integer |
cacheSeconds |
protected ChannelHandlerContext |
ctx |
protected boolean |
download |
static int |
HTTP_CACHE
Default cache duration for responses which can be cached
|
static int |
HTTP_CACHE_INFINITE
Expires value used to indicate that a resource can be infinitely long cached
|
protected boolean |
isPrivate |
protected String |
name |
protected boolean |
responseChunked |
protected WebContext |
wc |
Modifier | Constructor and Description |
---|---|
protected |
Response(WebContext wc)
Creates a new response for the given request.
|
Modifier and Type | Method and Description |
---|---|
Response |
addHeader(CharSequence name,
Object value)
Adds the specified header.
|
Response |
addHeaderIfNotExists(CharSequence name,
Object value)
Only adds the given header if no header with the given name does exist yet.
|
Response |
cached()
Marks this response as cachable.
|
Response |
cachedForSeconds(int numberOfSeconds)
Marks this response as cachable for the given amount of time.
|
protected boolean |
canBeCompressed(String contentType) |
protected static void |
closeAsyncClient() |
protected ChannelFuture |
commit(HttpResponse response) |
protected ChannelFuture |
commit(HttpResponse response,
boolean flush) |
protected void |
complete(ChannelFuture future) |
protected void |
contentionAwareWrite(Object message)
Writes the given message probably a chunk of output data into the channel.
|
protected DefaultHttpResponse |
createChunkedResponse(HttpResponseStatus status,
boolean keepalive) |
protected DefaultFullHttpResponse |
createFullResponse(HttpResponseStatus status,
boolean keepalive,
ByteBuf buffer) |
protected DefaultHttpResponse |
createResponse(HttpResponseStatus status,
boolean keepalive) |
void |
direct(HttpResponseStatus status,
String content)
Directly sends the given string as response, without any content type.
|
Response |
download(String name)
Instructs the browser to treat the response as download with the given file name.
|
void |
error(HttpResponseStatus status)
Sends the given HTTP status as error.
|
void |
error(HttpResponseStatus status,
sirius.kernel.health.HandledException t)
Sends the given HTTP status as error.
|
void |
error(HttpResponseStatus status,
String message)
Sends the given HTTP status as error.
|
void |
file(File file)
Sends the given file as response.
|
protected static com.ning.http.client.AsyncHttpClient |
getAsyncClient() |
protected SimpleDateFormat |
getHTTPDateFormat() |
boolean |
handleIfModifiedSince(long lastModifiedInMillis)
Determines if the given modified date is past the If-Modified-Since header of the request.
|
protected HttpHeaders |
headers() |
Response |
headers(sirius.kernel.commons.MultiMap<String,Object> inputHeaders)
Adds all given headers
|
Response |
infinitelyCached()
Marks this response as infinitely cachable.
|
Response |
inline(String name)
Instructs the browser to treat the response as inline-download with the given file name.
|
protected void |
installChunkedWriteHandler() |
protected void |
internalServerError(String debugMessage,
Throwable t) |
JSONStructuredOutput |
json()
Creates a JSON output which can be used to generate well formed json.
|
Response |
named(String name)
Forces the use of a given name.
|
Response |
noKeepalive()
Disables keep-alive protocol (even if it would have been otherwise supported).
|
Response |
notCached()
Marks this response as not-cachable.
|
OutputStream |
outputStream(HttpResponseStatus status,
String contentType)
Creates an OutputStream which is sent to the client.
|
Response |
privateCached()
Marks this response as only privately cachable (only the browser may cache it, but not a proxy etc.)
|
void |
redirectPermanently(String url)
Sends a 301 (permanent redirect) to the given url as result.
|
void |
redirectTemporarily(String url)
Sends a 307 (temporary redirect) or 302 (found) to the given url as result, depending on the given HTTP
protocol in the request.
|
void |
redirectToGet(String url)
Sends 302 (found) to the given url as result.
|
void |
resource(URLConnection urlConnection)
Sends the given resource (potentially from classpath) as result.
|
void |
sendContent(String name)
|
protected void |
sendTemplateContent(HttpResponseStatus status,
String name,
String content) |
protected void |
setContentDisposition(String name,
boolean download) |
protected void |
setContentTypeHeader(String name) |
protected void |
setDateAndCacheHeaders(long lastModifiedMillis,
int cacheSeconds,
boolean isPrivate) |
Response |
setHeader(CharSequence name,
Object value)
Sets the specified header.
|
void |
status(HttpResponseStatus status)
Completes this response by sending the given status code without any content
|
void |
template(HttpResponseStatus status,
String name,
Object... params)
Renders the given template and sends the output as response.
|
void |
template(HttpResponseStatus status,
Template template,
Object... params)
Renders the given Rythm template and sends the output as response.
|
void |
template(String name,
Object... params)
Renders the given template and sends the output as response.
|
String |
toString() |
void |
tunnel(String url)
Tunnels the contents retrieved from the given URL as result of this response.
|
void |
tunnel(String url,
Consumer<Integer> failureHandler)
Tunnels the contents retrieved from the given URL as result of this response.
|
void |
unauthorized(String realm)
Sends an 401 UNAUTHORIZED response with a WWW-Authenticate header for the given realm.
|
sirius.kernel.xml.XMLStructuredOutput |
xml()
Creates a XML output which can be used to generate well formed XML.
|
public static final int HTTP_CACHE
public static final int HTTP_CACHE_INFINITE
public static final int BUFFER_SIZE
protected WebContext wc
protected ChannelHandlerContext ctx
protected Integer cacheSeconds
protected boolean isPrivate
protected boolean download
protected String name
protected boolean responseChunked
protected static com.ning.http.client.AsyncHttpClient asyncClient
protected Response(WebContext wc)
wc
- the context representing the request for which this response is createdprotected DefaultFullHttpResponse createFullResponse(HttpResponseStatus status, boolean keepalive, ByteBuf buffer)
protected DefaultHttpResponse createResponse(HttpResponseStatus status, boolean keepalive)
protected DefaultHttpResponse createChunkedResponse(HttpResponseStatus status, boolean keepalive)
protected ChannelFuture commit(HttpResponse response)
protected ChannelFuture commit(HttpResponse response, boolean flush)
public Response noKeepalive()
protected void complete(ChannelFuture future)
public boolean handleIfModifiedSince(long lastModifiedInMillis)
lastModifiedInMillis
- the modification date of the resource being deliveredpublic Response named(String name)
name
- the file name to usepublic Response download(@Nullable String name)
name
- the file name to send to the browser. If the given name is null nothing happens (We
won't force a download).public Response inline(String name)
name
- the file name to send to the browserpublic Response notCached()
public Response privateCached()
public Response cachedForSeconds(int numberOfSeconds)
numberOfSeconds
- the number of seconds the response might be cachedpublic Response cached()
public Response infinitelyCached()
This suggests that it will never change.
public Response setHeader(CharSequence name, Object value)
name
- name of the headervalue
- value of the headerprotected HttpHeaders headers()
public Response addHeader(CharSequence name, Object value)
In contrast to setHeader(CharSequence, Object)
this method can be called multiple times for the same
header and its values will be concatenated as specified in the HTTP protocol.
name
- name of the headervalue
- value of the headerpublic Response addHeaderIfNotExists(CharSequence name, Object value)
name
- name of the headervalue
- value of the headerpublic Response headers(sirius.kernel.commons.MultiMap<String,Object> inputHeaders)
inputHeaders
- headers to addpublic void status(HttpResponseStatus status)
status
- the HTTP status to sentpublic void redirectTemporarily(String url)
If contrast to redirectToGet(String)
, this uses 307 as status code - if possible (HTTP 1.1).
This will re-issue the same request method which was made to trigger the original request.
url
- the URL to redirect topublic void redirectToGet(String url)
In contrast to redirectTemporarily(String)
, which uses 307 as HTTP response code, a 302 will
cause the browser to always GET as method to access the new URL. A 307 preserves the method and e.g.
keeps a POST as being a POST.
url
- the URL to redirect topublic void redirectPermanently(String url)
url
- the URL to redirect toprotected boolean canBeCompressed(String contentType)
protected void installChunkedWriteHandler()
public void file(File file)
Based on the file, full HTTP caching is supported, taking care of If-Modified-Since headers etc.
If the request does not use HTTPS, the server tries to support a zero-copy approach leading to maximal throughput as no copying between user space and kernel space buffers is required.
file
- the file to sendprotected void setDateAndCacheHeaders(long lastModifiedMillis, int cacheSeconds, boolean isPrivate)
protected SimpleDateFormat getHTTPDateFormat()
protected void setContentDisposition(String name, boolean download)
protected void setContentTypeHeader(String name)
public void sendContent(String name)
Resource
using
the Resources
lookup framework.
Sends the resource found or a 404 NOT_FOUND otherwise.
name
- the path of the resource to lookuppublic void resource(URLConnection urlConnection)
This will support HTTP caching if enabled (default).
urlConnection
- the connection to get the data from.public void unauthorized(String realm)
This will generally force the client to perform a HTTP Basic authentication.
realm
- the realm to report to the client. This will be used to select an appropriate username
and passwordpublic void error(HttpResponseStatus status)
If possible a specific template /view/errors/ERRORCODE.html. If not available, /view/errors/default.html will be rendered.
status
- the HTTP status to send.public void error(HttpResponseStatus status, sirius.kernel.health.HandledException t)
If possible a specific template /view/errors/ERRORCODE.html. If not available, /view/errors/default.html will be rendered.
status
- the HTTP status to sendt
- the exception to display. Use Exceptions
to create a
handled exception.public void error(HttpResponseStatus status, String message)
If possible a specific template /view/errors/ERRORCODE.html. If not available, /view/errors/default.html will be rendered.
status
- the HTTP status to sendmessage
- A message or description of what went wrongpublic void direct(HttpResponseStatus status, String content)
This should only be used when really required (meaning when you really know what you're doing. The encoding used will be UTF-8).
status
- the HTTP status to sendcontent
- the string contents to send.public void template(String name, Object... params)
By default caching will be disabled. If the file ends with .html, text/html; charset=UTF-8 will be set as content type. Otherwise the content type will be guessed from the filename.
name
- the name of the template to render. It's recommended to use files in /templates/... and to place
them in the resources directory.params
- contains the parameters sent to the templatepublic void template(HttpResponseStatus status, String name, Object... params)
By default caching will be disabled. If the file ends with .html, text/html; charset=UTF-8 will be set as content type. Otherwise the content type will be guessed from the filename.
status
- the HTTP status to send. HttpResponseStatus.OK
would be appropriate in most cases.name
- the name of the template to render. It's recommended to use files in /templates/... and to place
them in the resources directory.params
- contains the parameters sent to the templatetemplate(String, Object...)
public void template(HttpResponseStatus status, Template template, Object... params)
By default caching will be disabled. If the file ends with .html, text/html; charset=UTF-8 will be set as content type. Otherwise the content type will be guessed from the filename.
status
- the HTTP status to send. HttpResponseStatus.OK
would be appropriate in most cases.template
- the template to renderparams
- contains the parameters sent to the templatetemplate(HttpResponseStatus, String, Object...)
protected void sendTemplateContent(HttpResponseStatus status, String name, String content)
protected static com.ning.http.client.AsyncHttpClient getAsyncClient()
protected static void closeAsyncClient()
public void tunnel(String url)
Caching and range headers will be forwarded and adhered.
Uses non-blocking APIs in order to maximize throughput. Therefore this can be called in an unforked dispatcher.
url
- the url to tunnel through.public void tunnel(String url, @Nullable Consumer<Integer> failureHandler)
Caching and range headers will be forwarded and adhered.
Uses non-blocking APIs in order to maximize throughput. Therefore this can be called in an unforked dispatcher.
If the called URL returns an error (>= 400) and the given failureHandler is non null, it is supplied with the status code and can re-try or answer the request by itself.
url
- the url to tunnel through.failureHandler
- supplies a handler which is invoked if the called URL fails. The handler is provided with
the HTTP status code and can (and must) handle the request on its own. It is save to
call WebContext.respondWith()
again for the request, as no response was created
yet.public JSONStructuredOutput json()
By default, caching will be disabled. If the generated JSON is small enough, it will be transmitted in one go. Otherwise a chunked response will be sent.
public sirius.kernel.xml.XMLStructuredOutput xml()
By default, caching will be disabled. If the generated XML is small enough, it will be transmitted in one go. Otherwise a chunked response will be sent.
public OutputStream outputStream(HttpResponseStatus status, @Nullable String contentType)
If the contents are small enough, everything will be sent in one response. Otherwise a chunked response
will be sent. The size of the underlying buffer will be determined by BUFFER_SIZE
.
By default, caching will be supported.
status
- the HTTP status to sendcontentType
- the content type to use. If null, we rely on a previously set header.protected void contentionAwareWrite(Object message)
If the channel buffer is full (not writeable anymore) we need to trigger a flush, so that the data is shovelled into the network. If this doesn't clear up the buffer immediatelly, we block the current thread to throttle the application until free space is available again.
Note that this method must not be invoked in the event loop as otherwise a deadlock might occur. Therefore all dispatchers now always for a new thread to handle requests.
message
- the data to sentCopyright © 2018. All rights reserved.