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:org.gamejam.gc.fartroulette.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 ww.j  a  v  a2 s  .co  m
        return;
    }

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

    final String uri = request.getUri();

    if (filter.run(uri)) { //pass to the next handler
        ctx.fireChannelRead(request);
        return;
    }

    final String path = sanitizeUri(uri);
    if (path == null) {
        sendError(ctx, FORBIDDEN);
        return;
    }

    s_logger.info(path);

    /*if (path.contains("wow")) {
       FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT));
    response.headers().set(CONTENT_TYPE, "text/plain");
    response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
    ctx.writeAndFlush(response);
    return;
               
    } else {
    ctx.fireChannelRead(request);
    }*/

    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:org.jooby.internal.netty.NettyResponse.java

License:Apache License

@Override
public void send(final FileChannel channel, final long offset, final long count) throws Exception {
    DefaultHttpResponse rsp = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status);
    if (!headers.contains(HttpHeaderNames.CONTENT_LENGTH)) {
        headers.remove(HttpHeaderNames.TRANSFER_ENCODING);
        headers.set(HttpHeaderNames.CONTENT_LENGTH, count);
    }/* w w  w .  ja  va 2 s. c  o m*/

    if (keepAlive) {
        headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }

    // dump headers
    rsp.headers().set(headers);
    ChannelHandlerContext ctx = this.ctx;
    ctx.channel().attr(NettyRequest.NEED_FLUSH).set(false);

    ChannelPipeline pipeline = ctx.pipeline();
    boolean ssl = pipeline.get(SslHandler.class) != null;

    if (ssl) {
        // add chunker
        chunkHandler(pipeline);

        // Create the chunked input here already, to properly handle the IOException
        HttpChunkedInput chunkedInput = new HttpChunkedInput(
                new ChunkedNioFile(channel, offset, count, bufferSize));

        ctx.channel().eventLoop().execute(() -> {
            // send headers
            ctx.write(rsp);
            // chunked file
            keepAlive(ctx.writeAndFlush(chunkedInput));
        });
    } else {
        ctx.channel().eventLoop().execute(() -> {
            // send headers
            ctx.write(rsp);
            // file region
            ctx.write(new DefaultFileRegion(channel, offset, count));
            keepAlive(ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT));
        });
    }

    committed = true;

}

From source file:org.mp4parser.rtp2dash.DashServerHandler.java

License:Apache License

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

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

    final String uri = request.getUri();

    if ("/Manifest.mpd".equals(uri)) {
        try {
            sendManifest(ctx);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return;
    }

    final String path = sanitizeUri(uri);
    if (path == null) {
        sendError(ctx, FORBIDDEN);
        return;
    }

    File file = new File(path);
    if (file.isHidden() || file.isDirectory() || !file.exists()) {
        sendError(ctx, NOT_FOUND);
        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;
        }
    }

    final 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);
    response.headers().set("Access-Control-Allow-Origin", "*");
    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() {

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

        public void operationComplete(ChannelProgressiveFuture future) {
            try {
                raf.close();
            } catch (IOException e) {
                LOG.severe("Cannot close " + raf.toString());
            }
            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:org.ratpackframework.file.internal.DefaultFileHttpTransmitter.java

License:Apache License

private void transmit(BasicFileAttributes basicFileAttributes, final FileChannel fileChannel) {
    long length = basicFileAttributes.size();

    response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, length);

    if (isKeepAlive(request)) {
        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    }//from ww w  .ja  v a  2s  . co  m

    if (!channel.isOpen()) {
        closeQuietly(fileChannel);
        return;
    }

    HttpResponse minimalResponse = new DefaultHttpResponse(response.getProtocolVersion(), response.getStatus());
    minimalResponse.headers().set(response.headers());
    ChannelFuture writeFuture = channel.writeAndFlush(minimalResponse);

    writeFuture.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                closeQuietly(fileChannel);
                channel.close();
            }
        }
    });

    FileRegion message = new DefaultFileRegion(fileChannel, 0, length);
    writeFuture = channel.write(message);

    writeFuture.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) {
            closeQuietly(fileChannel);
            if (!future.isSuccess()) {
                channel.close();
            }
        }
    });

    ChannelFuture lastContentFuture = channel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    if (!isKeepAlive(response)) {
        lastContentFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:org.robotbrains.support.web.server.netty.NettyStaticContentHandler.java

License:Apache License

@Override
public void handleWebRequest(ChannelHandlerContext ctx, HttpRequest request, Set<HttpCookie> cookiesToAdd)
        throws IOException {
    String url = request.getUri();
    String originalUrl = url;//from   w w w  .jav a  2 s  .  c  om

    // Strip off query parameters, if any, as we don't care.
    int pos = url.indexOf('?');
    if (pos != -1) {
        url = url.substring(0, pos);
    }

    int luriPrefixLength = uriPrefix.length();
    String filepath = URLDecoder.decode(url.substring(url.indexOf(uriPrefix) + luriPrefixLength),
            StandardCharsets.UTF_8.name());

    File file = new File(baseDir, filepath);

    // Refuse to process if the path wanders outside of the base directory.
    if (!allowLinks && !fileSupport.isParent(baseDir, file)) {
        HttpResponseStatus status = HttpResponseStatus.FORBIDDEN;
        parentHandler.getWebServer().getLog().warn(String.format(
                "HTTP [%s] %s --> (Path attempts to leave base directory)", status.code(), originalUrl));
        parentHandler.sendError(ctx, status);
        return;
    }

    RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException fnfe) {
        if (fallbackHandler != null) {
            fallbackHandler.handleWebRequest(ctx, request, cookiesToAdd);
        } else {
            HttpResponseStatus status = HttpResponseStatus.NOT_FOUND;
            parentHandler.getWebServer().getLog()
                    .warn(String.format("HTTP [%s] %s --> (File Not Found)", status.code(), originalUrl));
            parentHandler.sendError(ctx, status);
        }
        return;
    }
    long fileLength = raf.length();

    // Start with an initial OK response which will be modified as needed.
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.OK);

    setMimeType(filepath, response);

    parentHandler.addHttpResponseHeaders(response, extraHttpContentHeaders);
    parentHandler.addHeaderIfNotExists(response, HttpHeaders.Names.ACCEPT_RANGES, HttpHeaders.Values.BYTES);

    if (cookiesToAdd != null) {

        addHeader(response, HttpHeaders.Names.SET_COOKIE, ServerCookieEncoder.STRICT
                .encode(Collections2.transform(cookiesToAdd, new Function<HttpCookie, Cookie>() {
                    @Override
                    public Cookie apply(HttpCookie cookie) {
                        return NettyHttpResponse.createNettyCookie(cookie);
                    }
                })));
    }

    RangeRequest rangeRequest = null;
    try {
        rangeRequest = parseRangeRequest(request, fileLength);
    } catch (Exception e) {
        try {
            HttpResponseStatus status = HttpResponseStatus.REQUESTED_RANGE_NOT_SATISFIABLE;
            parentHandler.getWebServer().getLog()
                    .error(String.format("[%s] HTTP %s --> %s", status.code(), originalUrl, e.getMessage()));
            response.setStatus(status);
            parentHandler.sendError(ctx, status);
        } finally {
            try {
                raf.close();
            } catch (Exception e1) {
                parentHandler.getWebServer().getLog().warn("Unable to close static content file", e1);
            }
        }
        return;
    }

    HttpResponseStatus status = HttpResponseStatus.OK;
    if (rangeRequest == null) {
        setContentLength(response, fileLength);
    } else {
        setContentLength(response, rangeRequest.getRangeLength());
        addHeader(response, HttpHeaders.Names.CONTENT_RANGE,
                CONTENT_RANGE_PREFIX + rangeRequest.begin + CONTENT_RANGE_RANGE_SEPARATOR + rangeRequest.end
                        + CONTENT_RANGE_RANGE_SIZE_SEPARATOR + fileLength);
        status = HttpResponseStatus.PARTIAL_CONTENT;
        response.setStatus(status);
    }

    Channel ch = ctx.channel();

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

    // Write the content if there have been no errors and we are a GET request.
    if (HttpMethod.GET == request.getMethod()) {
        if (ch.pipeline().get(SslHandler.class) != null) {
            // Cannot use zero-copy with HTTPS.
            writeFuture = ch.write(new ChunkedFile(raf, 0, fileLength, COPY_CHUNK_SIZE));
        } else {
            // No encryption - use zero-copy.
            final FileRegion region = new DefaultFileRegion(raf.getChannel(),
                    rangeRequest != null ? rangeRequest.begin : 0,
                    rangeRequest != null ? rangeRequest.getRangeLength() : fileLength);
            writeFuture = ch.write(region);
            writeFuture.addListener(new ChannelProgressiveFutureListener() {
                @Override
                public void operationComplete(ChannelProgressiveFuture future) throws Exception {
                    region.release();
                }

                @Override
                public void operationProgressed(ChannelProgressiveFuture future, long progress, long total)
                        throws Exception {
                    // Do nothng
                }
            });
        }
    }

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

    parentHandler.getWebServer().getLog()
            .trace(String.format("[%s] HTTP %s --> %s", status.code(), originalUrl, file.getPath()));
}

From source file:org.scache.network.buffer.FileSegmentManagedBuffer.java

License:Apache License

@Override
public Object convertToNetty() throws IOException {
    if (conf.lazyFileDescriptor()) {
        return new DefaultFileRegion(file, offset, length);
    } else {//from   w  ww  . j a  va2s . com
        FileChannel fileChannel = new FileInputStream(file).getChannel();
        return new DefaultFileRegion(fileChannel, offset, length);
    }
}

From source file:org.thingsplode.synapse.endpoint.handlers.FileRequestHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, FileRequest req) throws Exception {

    Optional<String> uri = getSanitizedPath(req.getHeader().getUri().getPath());
    if (!uri.isPresent()) {
        HttpResponseHandler.sendError(ctx, HttpResponseStatus.FORBIDDEN, "Path is not available.");
        return;//from   w ww .  j a  v  a 2 s.  c om
    }

    if (!this.redirects.isEmpty()) {
        for (Entry<Pattern, String> e : this.redirects.entrySet()) {
            if (e.getKey().matcher(uri.get()).matches()) {
                HttpResponseHandler.sendRedirect(ctx, createRedirectUrl(req.getHeader(), e.getValue()),
                        req.getHeader());
                break;
            }
        }
    }

    if (uri.get().endsWith("/")) {
        HttpResponseHandler.sendRedirect(ctx, uri.get() + "index.html", req.getHeader());
        return;
    }

    File file = null;
    if (webroot != null) {
        file = new File(webroot, uri.get());
    }
    //if ((!file.exists()) && "/index.html".equals(msg.getHeader().getUri().getPath())) {
    //    file = new File(sanitizeUri("/index.html"));
    //}

    RandomAccessFile raf = null;
    if (file == null || !file.exists() || file.isHidden() || file.isDirectory()) {
        raf = Loader.extractResource(uri.get());
        if (raf == null) {
            HttpResponseHandler.sendError(ctx, HttpResponseStatus.NOT_FOUND, "File not found.");
            return;
        }
    }

    if (file == null && raf == null) {
        HttpResponseHandler.sendError(ctx, HttpResponseStatus.NOT_FOUND, "File not found.");
        return;
    }

    if (raf == null && !file.isFile()) {
        HttpResponseHandler.sendError(ctx, HttpResponseStatus.FORBIDDEN, "Is not a file.");
        return;
    }

    String contentType = MIME_TYPES_MAP.getContentType(file.getPath());
    try {
        if (raf == null) {
            raf = new RandomAccessFile(file, "r");
        }
    } catch (FileNotFoundException ex) {
        HttpResponseHandler.sendError(ctx, HttpResponseStatus.NOT_FOUND, ex.getMessage());
        return;
    }
    //don't send apps
    //if ("application/octet-stream".equals(contentType)) {
    //    file = new File(sanitizeUri("/index.html"));
    //}

    // Cache Validation
    if (file.exists()) {
        Optional<String> ifModifiedSinceOpt = req.getHeader()
                .getProperty(HttpHeaderNames.IF_MODIFIED_SINCE.toString());
        if (ifModifiedSinceOpt.isPresent() && !Util.isEmpty(ifModifiedSinceOpt.get())) {
            SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
            Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSinceOpt.get());

            // 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;
            }
        }
    }

    long fileLength = raf.length();

    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
    HttpUtil.setContentLength(response, fileLength);
    setContentTypeHeader(response, file);
    setDateAndCacheHeaders(response, file);
    if (isKeepAlive(req.getHeader())) {
        response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderNames.CONNECTION);
    }
    // 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;
    }

}

From source file:ratpack.file.internal.DefaultFileHttpTransmitter.java

License:Apache License

@Override
public void transmit(ExecControl execContext, final BasicFileAttributes basicFileAttributes, final Path file)
        throws Exception {
    final boolean compressThis = compress && basicFileAttributes.size() > compressionMinSize
            && isContentTypeCompressible();

    if (compress && !compressThis) {
        // Signal to the compressor not to compress this
        httpHeaders.set(HttpHeaderConstants.CONTENT_ENCODING, HttpHeaders.Values.IDENTITY);
    }//from  ww  w  . j a  v a 2 s .c  o  m

    if (file.getFileSystem().equals(FileSystems.getDefault()) && !compressThis) {
        execContext.blocking(new Callable<FileChannel>() {
            public FileChannel call() throws Exception {
                return new FileInputStream(file.toFile()).getChannel();
            }
        }).then(new Action<FileChannel>() {
            public void execute(FileChannel fileChannel) throws Exception {
                FileRegion defaultFileRegion = new DefaultFileRegion(fileChannel, 0,
                        basicFileAttributes.size());
                transmit(basicFileAttributes, defaultFileRegion);
            }
        });
    } else {
        execContext.blocking(new Callable<ReadableByteChannel>() {
            public ReadableByteChannel call() throws Exception {
                return Files.newByteChannel(file);
            }
        }).then(new Action<ReadableByteChannel>() {
            public void execute(ReadableByteChannel fileChannel) throws Exception {
                transmit(basicFileAttributes, new ChunkedInputAdapter(new ChunkedNioStream(fileChannel)));
            }
        });
    }
}

From source file:ratpack.server.internal.DefaultResponseTransmitter.java

License:Apache License

@Override
public void transmit(final Context context, final HttpResponseStatus responseStatus,
        final BasicFileAttributes basicFileAttributes, final Path file) {
    String contentType = responseHeaders.get(HttpHeaderConstants.CONTENT_TYPE);
    final long size = basicFileAttributes.size();

    Pair<Long, String> fileDetails = Pair.of(size, contentType);

    CompressionConfig compressionConfig = context.get(CompressionConfig.class);
    final boolean compressionEnabled = compressionConfig.isCompressResponses();
    final Predicate<? super Pair<Long, String>> shouldCompress;
    if (compressionEnabled) {
        ImmutableSet<String> blacklist = compressionConfig.getMimeTypeBlackList();
        shouldCompress = new ShouldCompressPredicate(compressionConfig.getMinSize(),
                compressionConfig.getMimeTypeWhiteList(),
                blacklist.isEmpty() ? ActivationBackedMimeTypes.getDefaultExcludedMimeTypes() : blacklist);
    } else {/* w ww  . java 2s  .  c o m*/
        shouldCompress = Predicates.alwaysFalse();
    }
    final boolean compressThis = compressionEnabled
            && (contentType != null && shouldCompress.apply(fileDetails));
    if (!compressThis) {
        // Signal to the compressor not to compress this
        responseHeaders.set(HttpHeaderConstants.CONTENT_ENCODING, HttpHeaderConstants.IDENTITY);
    }

    responseHeaders.set(HttpHeaderConstants.CONTENT_LENGTH, size);

    if (!isSsl && !compressThis && file.getFileSystem().equals(FileSystems.getDefault())) {
        execControl.blocking(() -> new FileInputStream(file.toFile()).getChannel()).then(fileChannel -> {
            FileRegion defaultFileRegion = new DefaultFileRegion(fileChannel, 0, size);
            transmit(context, responseStatus, defaultFileRegion);
        });
    } else {
        execControl.blocking(() -> Files.newByteChannel(file)).then(fileChannel -> transmit(context,
                responseStatus, new HttpChunkedInput(new ChunkedNioStream(fileChannel))));
    }
}

From source file:reactor.ipc.netty.NettyOutbound.java

License:Open Source License

/**
 * Send content from given {@link Path} using
 * {@link java.nio.channels.FileChannel#transferTo(long, long, WritableByteChannel)}
 * support. If the system supports it and the path resolves to a local file
 * system {@link File} then transfer will use zero-byte copy
 * to the peer.//w  ww. j a  v a 2  s . c o  m
 * <p>It will
 * listen for any error on
 * write and close
 * on terminal signal (complete|error). If more than one publisher is attached
 * (multiple calls to send()) completion occurs after all publishers complete.
 * <p>
 * Note: this will emit {@link io.netty.channel.FileRegion} in the outbound
 * {@link io.netty.channel.ChannelPipeline}
 *
 * @param file the file Path
 * @param position where to start
 * @param count how much to transfer
 *
 * @return A Publisher to signal successful sequence write (e.g. after "flush") or any
 * error during write
 */
default NettyOutbound sendFile(Path file, long position, long count) {
    Objects.requireNonNull(file);
    return then(Mono.using(() -> FileChannel.open(file, StandardOpenOption.READ),
            fc -> FutureMono
                    .from(context().channel().writeAndFlush(new DefaultFileRegion(fc, position, count))),
            fc -> {
                try {
                    fc.close();
                } catch (IOException ioe) {
                    /*IGNORE*/}
            }));
}