Example usage for io.netty.channel ChannelProgressiveFutureListener ChannelProgressiveFutureListener

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

Introduction

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

Prototype

ChannelProgressiveFutureListener

Source Link

Usage

From source file:storage.netty.HttpUploadClient.java

License:Apache License

/**
 * Standard post without multipart but already support on Factory (memory management)
 *
 * @return the list of HttpData object (attribute and file) to be reused on next post
 *//*from   www .  ja  va2s .c  o  m*/
private void formpost(Bootstrap bootstrap, String host, int port, URI uriSimple, String resourceUrl, File file,
        HttpDataFactory factory) throws Exception {
    // Start the connection attempt.
    Channel channel = bootstrap.connect(host, port).sync().channel();
    // Wait until the connection attempt succeeds or fails.
    //Channel channel = future.sync().channel();

    // Prepare the HTTP request.        
    HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT,
            uriSimple.toASCIIString());
    request.headers().set(HttpHeaderNames.HOST, host);
    request.headers().add("x-ms-version", "2016-05-31");

    final DateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
    formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
    String dateTime = formatter.format(new Date());

    request.headers().set("x-ms-date", dateTime);
    request.headers().set("x-ms-blob-type", "BlockBlob");
    request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);

    RandomAccessFile raf = new RandomAccessFile(file, "r");
    long fileLength = raf.length();
    HttpUtil.setContentLength(request, fileLength);
    setContentTypeHeader(request, file);

    // Use the PostBody encoder
    //HttpPostRequestEncoder bodyRequestEncoder =
    //        new HttpPostRequestEncoder(factory, request, false);  // false => not multipart

    // add Form attribute
    //bodyRequestEncoder.addBodyFileUpload("myfile", file, "application/x-zip-compressed", false);
    request.headers().set("Authorization", "SharedKey " + account_name + ":"
            + AuthorizationHeader(account_name, account_key, "PUT", dateTime, request, resourceUrl, "", ""));

    channel.write(request);
    // ByteBuf buffer = Unpooled.copiedBuffer(Files.readAllBytes(file.toPath()));                //ByteBuf buffer = Unpooled.buffer(new FileInputStream(file), (int) file.length());

    ChannelFuture sendFileFuture = channel.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength),
            channel.newProgressivePromise());

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

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

}

From source file:uk.tanton.streaming.live.http.HttpStaticFileServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
    if (!request.decoderResult().isSuccess()) {
        sendError(ctx, BAD_REQUEST);/*from  w  ww.  j av a 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);

    final String path = "/tmp/dash" + uri;

    LOG.info("Path {}", path);

    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
    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 = 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);
    HttpUtil.setContentLength(response, fileLength);
    setContentTypeHeader(response, file);
    setDateAndCacheHeaders(response, file);
    if (HttpUtil.isKeepAlive(request)) {
        response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }

    response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, "*");

    // 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.writeAndFlush(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 (!HttpUtil.isKeepAlive(request)) {
        // Close the connection when the whole content is written out.
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}