addToResponse(response, nettyResponse);
final Object obj = response.direct;
File file = null;
ChunkedInput stream = null;
InputStream is = null;
if (obj instanceof File) {
file = (File) obj;
} else if (obj instanceof InputStream) {
is = (InputStream) obj;
} else if (obj instanceof ChunkedInput) {
// Streaming we don't know the content length
stream = (ChunkedInput) obj;
}
final boolean keepAlive = isKeepAlive(nettyRequest);
if (file != null && file.isFile()) {
try {
nettyResponse = addEtag(nettyRequest, nettyResponse, file);
if (nettyResponse.getStatus().equals(HttpResponseStatus.NOT_MODIFIED)) {
Channel ch = ctx.getChannel();
// Write the initial line and the header.
ChannelFuture writeFuture = ch.write(nettyResponse);
if (!keepAlive) {
// Close the connection when the whole content is written out.
writeFuture.addListener(ChannelFutureListener.CLOSE);
}
} else {
nettyResponse.setHeader(CONTENT_TYPE, MimeTypes.getContentType(file.getName(), "text/plain"));
final RandomAccessFile raf = new RandomAccessFile(file, "r");
try {
long fileLength = raf.length();
if (!nettyResponse.getStatus().equals(HttpResponseStatus.NOT_MODIFIED)) {
if (Logger.isTraceEnabled()) {
Logger.trace("file length is [" + fileLength + "]");
}
setContentLength(nettyResponse, fileLength);
}
Channel ch = ctx.getChannel();
// Write the initial line and the header.
ChannelFuture writeFuture = ch.write(nettyResponse);
// Write the content.
// If it is not a HEAD
if (!nettyRequest.getMethod().equals(HttpMethod.HEAD)) {
writeFuture = ch.write(new ChunkedFile(raf, 0, fileLength, 8192));
} else {
raf.close();
}
if (!keepAlive) {
// Close the connection when the whole content is written out.
writeFuture.addListener(ChannelFutureListener.CLOSE);
}
} catch (Throwable exx) {
try {
raf.close();
} catch (Throwable ex) { /* Left empty */ }
try {
ctx.getChannel().close();
} catch (Throwable ex) { /* Left empty */ }
}
}
} catch (Exception e) {
throw e;
}
} else if (is != null) {
ChannelFuture writeFuture = ctx.getChannel().write(nettyResponse);
if (!nettyRequest.getMethod().equals(HttpMethod.HEAD) && !nettyResponse.getStatus().equals(HttpResponseStatus.NOT_MODIFIED)) {
writeFuture = ctx.getChannel().write(new ChunkedStream(is));
} else {
is.close();
}
if (!keepAlive) {
writeFuture.addListener(ChannelFutureListener.CLOSE);
}
} else if (stream != null) {
ChannelFuture writeFuture = ctx.getChannel().write(nettyResponse);
if (!nettyRequest.getMethod().equals(HttpMethod.HEAD) && !nettyResponse.getStatus().equals(HttpResponseStatus.NOT_MODIFIED)) {
writeFuture = ctx.getChannel().write(stream);
} else {
stream.close();
}
if (!keepAlive) {
writeFuture.addListener(ChannelFutureListener.CLOSE);
}
} else {