// Output stream to write to when buffering is needed.
OutputStream buos = null;
// The buffer.
ByteArrayOutputStream baos = null;
// Filter on top of the buffer when gzip:ing.
GZIPOutputStream gzos = null;
final int contentLength = resource.getContentLength();
if (contentLength > 0 && !useGzip) {
response.setContentLength(contentLength);
} else {
final int size = contentLength>0 ? contentLength+25 : 512;
buos = baos = new ByteArrayOutputStream(size);
if (useGzip) {
gzos = new GZIPOutputStream(baos);
buos = gzos;
}
}
final InputStream is = resource.getInputStream();
final OutputStream os = response.getOutputStream();
int bytesRead = 0;
final byte buffer[] = new byte[512];
while((bytesRead = is.read(buffer)) != -1) {
if (null==buos) {
os.write(buffer, 0, bytesRead);
} else {
// Buffer data to be able to compute the true content length
buos.write(buffer, 0, bytesRead);
totalBytesRead += bytesRead;
}
}
if (null!=buos) {
if (null!=gzos) { //Content-Encoding: gzip
gzos.finish();
response.addHeader(HeaderBase.CONTENT_ENCODING, "gzip");
response.setContentLength(baos.size());
baos.writeTo(os);
} else { // Initially unknown content length.
if(totalBytesRead > 0) {