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:snow.http.server.StaticHttpHandler.java

License:Open Source License

private void sendFile(final ChannelHandlerContext ctx, final FullHttpRequest request, final File file)
        throws Throwable {
    final RandomAccessFile raf = new RandomAccessFile(file, "r");
    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK);
    long modified = file.lastModified();
    Date since = HttpHelper.parseDate(getHeader(request, IF_MODIFIED_SINCE));
    if (since != null && since.getTime() >= modified) {
        HttpHelper.sendStatus(ctx, NOT_MODIFIED);
    } else {//from w  w w .j  a  v a2  s.com
        final long length = raf.length();
        HttpHelper.setDate(response);
        HttpHelper.setLastModified(response, modified);
        HttpHeaders.setContentLength(response, length);
        HttpHeaders.setHeader(response, CONTENT_TYPE, mimeType(file.toPath()));
        setHeader(response, CACHE_CONTROL, cache);

        //            boolean isKeep = isKeepAlive(request);
        //            if (isKeep) {
        //                setHeader(response, CONNECTION, KEEP_ALIVE);
        //            }
        ctx.write(response);

        //            ChannelFuture writeFuture = ctx.writeAndFlush(new ChunkedFile(raf, 0, length, 8192));

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

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

        //            if (!isKeep) {
        sendFileFuture.addListener(CLOSE);
        //            }
    }
}

From source file:spark.network.netty.FileServerHandler.java

License:Apache License

@Override
public void messageReceived(ChannelHandlerContext ctx, String blockId) {
    String path = pResolver.getAbsolutePath(blockId);
    // if getFilePath returns null, close the channel
    if (path == null) {
        //ctx.close();
        return;//  www. j  a  v a 2  s.  c om
    }
    File file = new File(path);
    if (file.exists()) {
        if (!file.isFile()) {
            //logger.info("Not a file : " + file.getAbsolutePath());
            ctx.write(new FileHeader(0, blockId).buffer());
            ctx.flush();
            return;
        }
        long length = file.length();
        if (length > Integer.MAX_VALUE || length <= 0) {
            //logger.info("too large file : " + file.getAbsolutePath() + " of size "+ length);
            ctx.write(new FileHeader(0, blockId).buffer());
            ctx.flush();
            return;
        }
        int len = new Long(length).intValue();
        //logger.info("Sending block "+blockId+" filelen = "+len);
        //logger.info("header = "+ (new FileHeader(len, blockId)).buffer());
        ctx.write((new FileHeader(len, blockId)).buffer());
        try {
            ctx.sendFile(new DefaultFileRegion(new FileInputStream(file).getChannel(), 0, file.length()));
        } catch (Exception e) {
            //logger.warning("Exception when sending file : " + file.getAbsolutePath());
            e.printStackTrace();
        }
    } else {
        //logger.warning("File not found: " + file.getAbsolutePath());
        ctx.write(new FileHeader(0, blockId).buffer());
    }
    ctx.flush();
}

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  w w w  . j  a v a 2  s .  co 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:storage.netty.HttpUploadClientHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx)
        throws InvalidKeyException, IOException, InterruptedException {
    System.out.println("Sending: " + ctx.channel().localAddress());
    RandomAccessFile raf = new RandomAccessFile(ctx.channel().attr(HTTPUploadClientAsync.FILETOUPLOAD).get(),
            "r");
    long fileLength = raf.length();

    HttpRequest request = ctx.channel().attr(HTTPUploadClientAsync.HTTPREQUEST).get();
    ChannelFuture cf = ctx.channel().writeAndFlush(request);
    if (!cf.isSuccess()) {
        System.out.println("Send failed: " + cf.cause());
    }//from w  w  w  .j av  a  2 s.  c om
    ctx.channel().write(new DefaultFileRegion(raf.getChannel(), 0, fileLength));

    // Write the end marker.
    ctx.channel().writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
}

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  w w  . j av  a2 s. 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);
    }
}

From source file:whitespell.net.websockets.socketio.handler.ResourceHandler.java

License:Apache License

private void writeContent(RandomAccessFile raf, long fileLength, Channel ch) throws IOException {
    ChannelFuture writeFuture;// w w  w .j  ava2 s  .  c  om
    if (ch.pipeline().get(SslHandler.class) != null) {
        // 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 ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                region.release();
            }
        });
    }

    writeFuture.addListener(ChannelFutureListener.CLOSE);
}