use of io.divolte.server.js.GzippableHttpBody in project divolte-collector by divolte.
the class JavaScriptHandler method handleRequest.
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("Requested received for {} from {}", resource.getResourceName(), exchange.getSourceAddress().getHostString());
}
// Start with headers that we always set the same way.
final HeaderMap responseHeaders = exchange.getResponseHeaders();
responseHeaders.put(Headers.CACHE_CONTROL, CACHE_CONTROL_HEADER_VALUE);
// Figure out if we possibly need to deal with a compressed response,
// based on client capability.
final GzippableHttpBody uncompressedBody = resource.getEntityBody();
final Optional<HttpBody> gzippedBody = uncompressedBody.getGzippedBody();
final HttpBody bodyToSend;
if (gzippedBody.isPresent()) {
/*
* Compressed responses can use Content-Encoding and/or Transfer-Encoding.
* The semantics differ slightly, but it is suffice to say that most user
* agents don't advertise their Transfer-Encoding support.
* So for now we only support the Content-Encoding mechanism.
* Some other notes:
* - Some clients implement 'deflate' incorrectly. Hence we only support 'gzip',
* despite it having slightly more overhead.
* - We don't use Undertow's built-in compression support because we've
* pre-calculated the compressed response and expect to serve it up
* repeatedly, instead of calculating it on-the-fly for every request.
*/
responseHeaders.put(Headers.VARY, Headers.ACCEPT_ENCODING_STRING);
final HeaderValues acceptEncoding = exchange.getRequestHeaders().get(Headers.ACCEPT_ENCODING);
if (null != acceptEncoding && acceptEncoding.stream().anyMatch((header) -> Iterables.contains(HEADER_SPLITTER.split(header), "gzip"))) {
responseHeaders.put(Headers.CONTENT_ENCODING, "gzip");
bodyToSend = gzippedBody.get();
} else {
bodyToSend = uncompressedBody;
}
} else {
bodyToSend = uncompressedBody;
}
// Now we know which version of the entity is visible to this user-agent,
// figure out if the client already has the current version or not.
final ETag eTag = bodyToSend.getETag();
responseHeaders.put(Headers.ETAG, eTag.toString());
if (ETagUtils.handleIfNoneMatch(exchange, eTag, true)) {
final ByteBuffer entityBody = bodyToSend.getBody();
responseHeaders.put(Headers.CONTENT_TYPE, "application/javascript");
exchange.getResponseSender().send(entityBody);
} else {
exchange.setStatusCode(StatusCodes.NOT_MODIFIED);
exchange.endExchange();
}
}
Aggregations