Example usage for io.netty.channel DefaultFileRegion DefaultFileRegion

List of usage examples for io.netty.channel DefaultFileRegion DefaultFileRegion

Introduction

In this page you can find the example usage for io.netty.channel DefaultFileRegion DefaultFileRegion.

Prototype

public DefaultFileRegion(File f, long position, long count) 

Source Link

Document

Create a new instance using the given File .

Usage

From source file:com.king.platform.net.http.netty.request.FileHttpBody.java

License:Apache License

private ChannelFuture writeStreamedContent(ChannelHandlerContext ctx) {
    Channel channel = ctx.channel();
    return channel.write(new DefaultFileRegion(file, 0, file.length()), channel.newProgressivePromise());
}

From source file:com.king.platform.net.http.netty.request.FileRegionHttpBody.java

License:Apache License

@Override
public ChannelFuture writeContent(ChannelHandlerContext ctx) throws IOException {
    Channel channel = ctx.channel();
    return channel.write(new DefaultFileRegion(file, 0, file.length()), channel.newProgressivePromise());
}

From source file:com.netty.fileTest.file.FileSenderServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    String filePath = "c:\\abc.msi";
    RandomAccessFile raf = null;//w  w  w.j a v  a  2 s .c  o  m
    long length = -1;
    try {
        raf = new RandomAccessFile(filePath, "r");
        length = raf.length();
    } catch (Exception e) {
        ctx.writeAndFlush("ERR: " + e.getClass().getSimpleName() + ": " + e.getMessage() + '\n');
        return;
    } finally {
        if (length < 0 && raf != null) {
            raf.close();
        }
    }

    ctx.write("OK: " + raf.length() + '\n');

    // SSL not enabled - can use zero-copy file transfer.
    ChannelFuture writeFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, length));
    writeFuture.addListener(new ChannelProgressiveFutureListener() {

        @Override
        public void operationComplete(ChannelProgressiveFuture future) throws Exception {
            System.out.printf("file sender completed!");
        }

        @Override
        public void operationProgressed(ChannelProgressiveFuture future, long progress, long total)
                throws Exception {
            System.out.printf("now:" + progress + " total:" + total);

        }
    });

    ctx.writeAndFlush("\n");
}

From source file:com.netty.fileTest.http.download.HttpStaticFileServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (!request.getDecoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);/*from w w  w .  j  av a2s  .c o m*/
        return;
    }

    if (request.getMethod() != GET) {
        sendError(ctx, METHOD_NOT_ALLOWED);
        return;
    }

    final String uri = request.getUri();
    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);
        } else {
            sendRedirect(ctx, uri + '/');
        }
        return;
    }

    if (!file.isFile()) {
        sendError(ctx, FORBIDDEN);
        return;
    }

    // Cache Validation
    String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE);
    if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
        SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
        Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);

        // 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();

    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    HttpHeaders.setContentLength(response, fileLength);
    setContentTypeHeader(response, file);
    setDateAndCacheHeaders(response, file);
    if (HttpHeaders.isKeepAlive(request)) {
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }

    // Write the initial line and the header.
    ctx.write(response);

    // Write the content.
    ChannelFuture sendFileFuture;
    ChannelFuture lastContentFuture;
    if (ctx.pipeline().get(SslHandler.class) == null) {
        sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength),
                ctx.newProgressivePromise());
        // Write the end marker.
        lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    } else {
        sendFileFuture = ctx.write(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)),
                ctx.newProgressivePromise());
        // HttpChunkedInput will write the end marker (LastHttpContent) for us.
        lastContentFuture = sendFileFuture;
    }

    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.");
        }
    });

    // Decide whether to close the connection or not.
    if (!HttpHeaders.isKeepAlive(request)) {
        // Close the connection when the whole content is written out.
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.ociweb.pronghorn.adapter.netty.impl.HttpStaticFileServerHandler.java

License:Apache License

public static void sendFile(ChannelHandlerContext ctx, FullHttpRequest request, File file)
        throws ParseException, IOException {

    long lastModified = file.lastModified();
    String path = file.getPath();

    // Cache Validation
    String ifModifiedSince = request.headers().get(HttpHeaderNames.IF_MODIFIED_SINCE);
    if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
        SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
        Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);

        // 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 = lastModified / 1000;
        if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
            sendNotModified(ctx);/*from  w  w w  .  j a  v  a  2 s.  c o m*/
            return;
        }
    }

    RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException ignore) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    long fileLength = file.length();

    beginHTTPResponse(ctx, request, lastModified, path, fileLength);

    // Write the content.
    ChannelFuture sendFileFuture;
    ChannelFuture lastContentFuture;
    if (ctx.pipeline().get(SslHandler.class) == null) {
        sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength),
                ctx.newProgressivePromise());
        // Write the end marker.
        lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    } else {
        FileInputStream input = new FileInputStream(file);

        byte[] data = new byte[(int) fileLength]; //big hack to convert into byteBuf        
        int pos = 0;
        int remaining = (int) fileLength;
        while (remaining > 0) {
            int len = input.read(data, pos, remaining);
            remaining -= len;
            pos += len;
        }

        sendFileFuture = ctx.write(Unpooled.wrappedBuffer(data), ctx.newProgressivePromise());
        lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    }

    progressAndClose(request, sendFileFuture, lastContentFuture);
}

From source file:com.phei.netty.nio.http.file.HttpStaticFileServerHandler.java

License:Apache License

@Override
public void messageReceived(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (!request.decoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);//from w w w  . j a  va 2s  .  c  o m
        return;
    }

    if (request.method() != GET) {
        sendError(ctx, METHOD_NOT_ALLOWED);
        return;
    }

    final String uri = request.uri();
    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);
        } else {
            sendRedirect(ctx, uri + '/');
        }
        return;
    }

    if (!file.isFile()) {
        sendError(ctx, FORBIDDEN);
        return;
    }

    // Cache Validation
    String ifModifiedSince = request.headers().getAndConvert(IF_MODIFIED_SINCE);
    if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
        SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
        Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);

        // 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();

    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    HttpHeaderUtil.setContentLength(response, fileLength);
    setContentTypeHeader(response, file);
    setDateAndCacheHeaders(response, file);
    if (HttpHeaderUtil.isKeepAlive(request)) {
        response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }

    // Write the initial line and the header.
    ctx.write(response);

    // Write the content.
    ChannelFuture sendFileFuture;
    ChannelFuture lastContentFuture;
    if (ctx.pipeline().get(SslHandler.class) == null) {
        sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength),
                ctx.newProgressivePromise());
        // Write the end marker.
        lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    } else {
        sendFileFuture = ctx.write(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)),
                ctx.newProgressivePromise());
        // HttpChunkedInput will write the end marker (LastHttpContent) for us.
        lastContentFuture = sendFileFuture;
    }

    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.");
        }
    });

    // Decide whether to close the connection or not.
    if (!HttpHeaderUtil.isKeepAlive(request)) {
        // Close the connection when the whole content is written out.
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.qq.servlet.demo.netty.sample.http.file.HttpStaticFileServerHandler.java

License:Apache License

@Override
public void messageReceived(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (!request.getDecoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);//from www.j a  v  a2  s  .  co  m
        return;
    }

    if (request.getMethod() != GET) {
        sendError(ctx, METHOD_NOT_ALLOWED);
        return;
    }

    final String uri = request.getUri();
    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);
        } else {
            sendRedirect(ctx, uri + '/');
        }
        return;
    }

    if (!file.isFile()) {
        sendError(ctx, FORBIDDEN);
        return;
    }

    // Cache Validation
    String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE);
    if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
        SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
        Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);

        // 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 fnfe) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    long fileLength = raf.length();

    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    setContentLength(response, fileLength);
    setContentTypeHeader(response, file);
    setDateAndCacheHeaders(response, file);
    if (isKeepAlive(request)) {
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }

    // Write the initial line and the header.
    ctx.write(response);

    // Write the content.
    ChannelFuture sendFileFuture;
    if (useSendFile) {
        sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength),
                ctx.newProgressivePromise());
    } else {
        sendFileFuture = ctx.write(new ChunkedFile(raf, 0, fileLength, 8192), ctx.newProgressivePromise());
    }

    sendFileFuture.addListener(new ChannelProgressiveFutureListener() {
        @Override
        public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) {
            if (total < 0) { // total unknown
                System.err.println("Transfer progress: " + progress);
            } else {
                System.err.println("Transfer progress: " + progress + " / " + total);
            }
        }

        @Override
        public void operationComplete(ChannelProgressiveFuture future) throws Exception {
            System.err.println("Transfer complete.");
        }
    });

    // Write the end marker
    ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);

    // Decide whether to close the connection or not.
    if (!isKeepAlive(request)) {
        // Close the connection when the whole content is written out.
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.sangupta.swift.netty.http.HttpStaticFileServerHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext context, FullHttpRequest request) throws Exception {
    if (!request.getDecoderResult().isSuccess()) {
        NettyUtils.sendError(context, HttpResponseStatus.BAD_REQUEST);
        return;// w w w.j av a2  s .  c  o m
    }

    if (request.getMethod() != HttpMethod.GET) {
        NettyUtils.sendError(context, HttpResponseStatus.METHOD_NOT_ALLOWED);
        return;
    }

    final String uri = request.getUri();
    final String path = NettyUtils.sanitizeUri(uri);
    if (path == null) {
        NettyUtils.sendError(context, HttpResponseStatus.FORBIDDEN);
        return;
    }

    File file = new File(documentRoot, path);
    if (file.isHidden() || !file.exists()) {
        NettyUtils.sendError(context, HttpResponseStatus.NOT_FOUND);
        return;
    }

    if (file.isDirectory()) {
        if (uri.endsWith("/")) {
            NettyUtils.sendListing(context, file);
        } else {
            NettyUtils.sendRedirect(context, uri + '/');
        }

        return;
    }

    if (!file.isFile()) {
        NettyUtils.sendError(context, HttpResponseStatus.FORBIDDEN);
        return;
    }

    // Cache Validation
    String ifModifiedSince = request.headers().get(HttpHeaders.Names.IF_MODIFIED_SINCE);
    if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
        Date ifModifiedSinceDate = NettyUtils.parseDateHeader(ifModifiedSince);

        if (ifModifiedSinceDate != null) {
            // 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) {
                NettyUtils.sendNotModified(context);
                return;
            }
        }
    }

    RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException ignore) {
        NettyUtils.sendError(context, HttpResponseStatus.NOT_FOUND);
        return;
    }

    final long fileLength = file.length();

    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    HttpHeaders.setContentLength(response, fileLength);
    NettyUtils.setContentTypeHeader(response, file);
    NettyUtils.setDateAndCacheHeaders(response, file, 3600); // cache for an hour

    // check for keep alive
    if (HttpHeaders.isKeepAlive(request)) {
        response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }

    // Write the initial line and the header.
    context.write(response);

    // Write the content.
    ChannelFuture sendFileFuture;
    if (context.pipeline().get(SslHandler.class) == null) {
        sendFileFuture = context.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength),
                context.newProgressivePromise());
    } else {
        sendFileFuture = context.write(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)),
                context.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.");
    //         }
    //         
    //      });

    // Write the end marker
    ChannelFuture lastContentFuture = context.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);

    // Decide whether to close the connection or not.
    if (!HttpHeaders.isKeepAlive(request)) {
        // Close the connection when the whole content is written out.
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.sangupta.swift.netty.spdy.SpdyStaticFileServerHandler.java

License:Apache License

@Override
protected void channelRead0(final ChannelHandlerContext context, final FullHttpRequest request)
        throws Exception {
    if (!request.getDecoderResult().isSuccess()) {
        NettyUtils.sendError(context, HttpResponseStatus.BAD_REQUEST);
        return;//from   ww  w.  j  a va  2  s.  com
    }

    // check for server name
    if (this.checkServerName) {
        String host = request.headers().get(HttpHeaders.Names.HOST);
        if (!host.startsWith(this.swiftServer.getServerName())) {
            NettyUtils.sendError(context, HttpResponseStatus.BAD_REQUEST);
            return;
        }
    }

    // check method
    if (request.getMethod() != HttpMethod.GET) {
        NettyUtils.sendError(context, HttpResponseStatus.METHOD_NOT_ALLOWED);
        return;
    }

    // check for SPDY support
    final boolean spdyRequest = request.headers().contains(NettyUtils.SPDY_STREAM_ID);

    // check for URI path to be proper
    final String uri = request.getUri();
    final String path = NettyUtils.sanitizeUri(uri);
    if (path == null) {
        NettyUtils.sendError(context, HttpResponseStatus.FORBIDDEN);
        return;
    }

    File file = new File(documentRoot, path);
    if (file.isHidden() || !file.exists()) {
        NettyUtils.sendError(context, HttpResponseStatus.NOT_FOUND);
        return;
    }

    if (file.isDirectory()) {
        if (uri.endsWith("/")) {
            NettyUtils.sendListing(context, file, request.headers().get(NettyUtils.SPDY_STREAM_ID));
            return;
        }

        // redirect to the listing page
        NettyUtils.sendRedirect(context, uri + '/');
        return;
    }

    if (!file.isFile()) {
        NettyUtils.sendError(context, HttpResponseStatus.FORBIDDEN);
        return;
    }

    // Cache Validation
    String ifModifiedSince = request.headers().get(HttpHeaders.Names.IF_MODIFIED_SINCE);
    if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
        Date ifModifiedSinceDate = NettyUtils.parseDateHeader(ifModifiedSince);

        if (ifModifiedSinceDate != null) {
            // 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) {
                NettyUtils.sendNotModified(context);
                return;
            }
        }
    }

    RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException ignore) {
        NettyUtils.sendError(context, HttpResponseStatus.NOT_FOUND);
        return;
    }

    final long fileLength = file.length();

    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    HttpHeaders.setContentLength(response, fileLength);
    NettyUtils.setContentTypeHeader(response, file);
    NettyUtils.setDateAndCacheHeaders(response, file, 3600); // cache for an hour

    // check for keep alive
    if (HttpHeaders.isKeepAlive(request)) {
        response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    } else {
        context.write(response).addListener(ChannelFutureListener.CLOSE);
    }

    // Write the initial line and the header.
    context.write(response);

    // Write the content.
    ChannelFuture sendFileFuture;
    if (context.pipeline().get(SslHandler.class) == null) {
        sendFileFuture = context.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength),
                context.newProgressivePromise());
    } else {
        sendFileFuture = context.write(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)),
                context.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.");
    //         }
    //         
    //      });

    // Write the end marker
    ChannelFuture lastContentFuture = context.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);

    // Decide whether to close the connection or not.
    if (!HttpHeaders.isKeepAlive(request)) {
        // Close the connection when the whole content is written out.
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.soho.framework.server.netty.http.HttpServletHandler.java

License:Apache License

protected void handleStaticResourceRequest(ChannelHandlerContext ctx, HttpRequest request) throws Exception {
    if (request.method() != GET) {
        sendError(ctx, METHOD_NOT_ALLOWED);
        return;// w  w w.j a  v  a2 s .c  o m
    }

    String uri = Utils.sanitizeUri(request.uri());
    final String path = (uri != null
            ? ServletWebApp.get().getStaticResourcesFolder().getAbsolutePath() + File.separator + uri
            : null);

    if (path == null) {
        sendError(ctx, FORBIDDEN);
        return;
    }

    File file = new File(path);
    if (file.isHidden() || !file.exists()) {
        sendError(ctx, NOT_FOUND);
        return;
    }
    if (!file.isFile()) {
        sendError(ctx, FORBIDDEN);
        return;
    }

    RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException fnfe) {
        sendError(ctx, NOT_FOUND);
        return;
    }

    long fileLength = raf.length();

    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
    setContentLength(response, fileLength);

    Channel ch = ctx.channel();

    // Write the initial line and the header.
    ch.write(response);

    // Write the content.
    ChannelFuture writeFuture;
    if (isSslChannel(ch)) {
        // Cannot use zero-copy with HTTPS.
        writeFuture = ch.write(new ChunkedFile(raf, 0, fileLength, 8192));
    } else {
        // No encryption - use zero-copy.
        final FileRegion region = new DefaultFileRegion(raf.getChannel(), 0, fileLength);
        writeFuture = ch.write(region);
        writeFuture.addListener(new ChannelProgressiveFutureListener() {

            @Override
            public void operationProgressed(ChannelProgressiveFuture channelProgressiveFuture, long current,
                    long total) throws Exception {
                System.out.printf("%s: %d / %d (+%d)%n", path, current, total, total);
            }

            @Override
            public void operationComplete(ChannelProgressiveFuture channelProgressiveFuture) throws Exception {
                region.release();
            }
        });
    }

}