}
// Rather than write the input stream directly to the response, write it to an
// buffered output stream so that the length can be calculated for the
// Content-Length header. See: http://issues.liferay.com/browse/FACES-1207
ResourceOutputStream resourceOutputStream = getResourceOutputStream(resource, bufferSize);
int responseContentLength = 0;
readableByteChannel = Channels.newChannel(inputStream);
writableByteChannel = Channels.newChannel(resourceOutputStream);
int bytesRead = readableByteChannel.read(byteBuffer);
if (logger.isTraceEnabled()) {
// Surround with isTraceEnabled check in order to avoid unnecessary conversion of
// int to String.
logger.trace("Handling - bytesRead=[{0}]", Integer.toString(bytesRead));
}
int bytesWritten = 0;
while (bytesRead != -1) {
byteBuffer.rewind();
byteBuffer.limit(bytesRead);
do {
bytesWritten += writableByteChannel.write(byteBuffer);
}
while (bytesWritten < responseContentLength);
byteBuffer.clear();
responseContentLength += bytesRead;
bytesRead = readableByteChannel.read(byteBuffer);
if (logger.isTraceEnabled()) {
// Surround with isTraceEnabled check in order to avoid unnecessary conversion
// of int to String.
logger.trace("Handling - MORE bytesRead=[{0}]", Integer.toString(bytesRead));
}
}
if (resourceOutputStream instanceof Filterable) {
Filterable filterable = (Filterable) resourceOutputStream;
filterable.filter();
}
responseContentLength = resourceOutputStream.size();
// Now that we know how big the file is, set the response Content-Length header and the status.
externalContext.setResponseContentLength(responseContentLength);
externalContext.setResponseStatus(HttpServletResponse.SC_OK);
// Set the response buffer size.
externalContext.setResponseBufferSize(responseContentLength);
if (logger.isTraceEnabled()) {
// Surround with isTraceEnabled check in order to avoid unnecessary conversion of
// int to String.
logger.trace("Handling - responseBufferSize=[{0}]", Integer.toString(responseContentLength));
}
// Write the data to the response.
resourceOutputStream.writeTo(externalContext.getResponseOutputStream());
resourceOutputStream.flush();
resourceOutputStream.close();
if (logger.isDebugEnabled()) {
logger.debug(
"HANDLED (SC_OK) resourceName=[{0}], libraryName[{1}], responseContentType=[{4}], responseContentLength=[{5}]",
new Object[] { resourceName, libraryName, responseContentType, responseContentLength });