use of io.netty.handler.codec.http2.Http2DataChunkedInput in project netty by netty.
the class Http2StaticFileServerHandler method channelRead.
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof Http2HeadersFrame) {
Http2HeadersFrame headersFrame = (Http2HeadersFrame) msg;
this.stream = headersFrame.stream();
if (!GET.toString().equals(headersFrame.headers().method().toString())) {
sendError(ctx, METHOD_NOT_ALLOWED);
return;
}
final String uri = headersFrame.headers().path().toString();
final String path = sanitizeUri(uri);
if (path == null) {
sendError(ctx, FORBIDDEN);
return;
}
File file = new File(path);
if (file.isHidden() || !file.exists()) {
sendError(ctx, NOT_FOUND);
return;
}
if (file.isDirectory()) {
if (uri.endsWith("/")) {
sendListing(ctx, file, uri);
} else {
sendRedirect(ctx, uri + '/');
}
return;
}
if (!file.isFile()) {
sendError(ctx, FORBIDDEN);
return;
}
// Cache Validation
CharSequence ifModifiedSince = headersFrame.headers().get(HttpHeaderNames.IF_MODIFIED_SINCE);
if (ifModifiedSince != null && !ifModifiedSince.toString().isEmpty()) {
SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince.toString());
// Only compare up to the second because the datetime format we send to the client
// does not have milliseconds
long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
long fileLastModifiedSeconds = file.lastModified() / 1000;
if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
sendNotModified(ctx);
return;
}
}
RandomAccessFile raf;
try {
raf = new RandomAccessFile(file, "r");
} catch (FileNotFoundException ignore) {
sendError(ctx, NOT_FOUND);
return;
}
long fileLength = raf.length();
Http2Headers headers = new DefaultHttp2Headers();
headers.status("200");
headers.setLong(HttpHeaderNames.CONTENT_LENGTH, fileLength);
setContentTypeHeader(headers, file);
setDateAndCacheHeaders(headers, file);
// Write the initial line and the header.
ctx.writeAndFlush(new DefaultHttp2HeadersFrame(headers).stream(stream));
// Write the content.
ChannelFuture sendFileFuture;
sendFileFuture = ctx.writeAndFlush(new Http2DataChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192), stream), ctx.newProgressivePromise());
sendFileFuture.addListener(new ChannelProgressiveFutureListener() {
@Override
public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) {
if (total < 0) {
// total unknown
System.err.println(future.channel() + " Transfer progress: " + progress);
} else {
System.err.println(future.channel() + " Transfer progress: " + progress + " / " + total);
}
}
@Override
public void operationComplete(ChannelProgressiveFuture future) {
System.err.println(future.channel() + " Transfer complete.");
}
});
} else {
// Unsupported message type
System.out.println("Unsupported message type: " + msg);
}
}
Aggregations