use of io.milton.http.entity.CompressedResourceEntity in project lobcder by skoulouzis.
the class CompressingResponseHandler method respondContent.
@Override
public void respondContent(Resource resource, Response response, Request request, Map<String, String> params) throws NotAuthorizedException, BadRequestException, NotFoundException {
if (resource instanceof GetableResource) {
GetableResource r = (GetableResource) resource;
String acceptableContentTypes = request.getAcceptHeader();
String contentType = r.getContentType(acceptableContentTypes);
// Experimental support for already compressed content...
String acceptableEncodings = request.getAcceptEncodingHeader();
if (r instanceof CompressedResource) {
CompressedResource compressedResource = (CompressedResource) r;
String acceptableEncoding = compressedResource.getSupportedEncoding(acceptableEncodings);
if (acceptableEncoding != null) {
response.setContentTypeHeader(contentType);
cacheControlHelper.setCacheControl(r, response, request.getAuthorization());
Long contentLength = compressedResource.getCompressedContentLength(acceptableEncoding);
response.setContentLengthHeader(contentLength);
response.setContentEncodingHeader(Response.ContentEncoding.GZIP);
response.setVaryHeader("Accept-Encoding");
response.setEntity(new CompressedResourceEntity(compressedResource, params, contentType, acceptableEncoding));
return;
}
}
if (canCompress(r, contentType, acceptableEncodings)) {
log.trace("respondContent: compressable");
// get the zipped content before sending so we can determine its
// compressed size
BufferingOutputStream tempOut = new BufferingOutputStream(maxMemorySize);
try {
OutputStream gzipOut = new GZIPOutputStream(tempOut);
r.sendContent(gzipOut, null, params, contentType);
gzipOut.flush();
gzipOut.close();
tempOut.flush();
} catch (NotFoundException e) {
throw e;
} catch (Exception ex) {
tempOut.deleteTempFileIfExists();
throw new RuntimeException(ex);
} finally {
FileUtils.close(tempOut);
}
log.trace("respondContent-compressed: " + resource.getClass());
setRespondContentCommonHeaders(response, resource, Response.Status.SC_OK, request.getAuthorization());
response.setContentEncodingHeader(Response.ContentEncoding.GZIP);
response.setVaryHeader("Accept-Encoding");
Long contentLength = tempOut.getSize();
if (contentLength != null) {
response.setContentLengthHeader(contentLength);
}
response.setContentTypeHeader(contentType);
cacheControlHelper.setCacheControl(r, response, request.getAuthorization());
response.setEntity(new InputStreamEntity(tempOut.getInputStream()));
} else {
log.trace("respondContent: not compressable");
// We really should set this header, but it causes IE to not cache files (eg images)
// response.setVaryHeader( "Accept-Encoding" );
wrapped.respondContent(resource, response, request, params);
}
} else {
throw new RuntimeException("Cant generate content for non-Getable resource: " + resource.getClass());
}
}
Aggregations