Search in sources :

Example 11 with DefaultFileRegion

use of org.apache.flink.shaded.netty4.io.netty.channel.DefaultFileRegion in project cassandra by apache.

the class AsyncStreamingOutputPlus method writeFileToChannelZeroCopyUnthrottled.

private long writeFileToChannelZeroCopyUnthrottled(FileChannel file) throws IOException {
    final long length = file.size();
    if (logger.isTraceEnabled())
        logger.trace("Writing {} bytes", length);
    ChannelPromise promise = beginFlush(length, 0, length);
    final DefaultFileRegion defaultFileRegion = new DefaultFileRegion(file, 0, length);
    channel.writeAndFlush(defaultFileRegion, promise);
    return length;
}
Also used : ChannelPromise(io.netty.channel.ChannelPromise) DefaultFileRegion(io.netty.channel.DefaultFileRegion)

Example 12 with DefaultFileRegion

use of org.apache.flink.shaded.netty4.io.netty.channel.DefaultFileRegion in project netty by netty.

the class StompWebSocketClientPageHandler method sendResource.

private static boolean sendResource(FullHttpRequest request, ChannelHandlerContext ctx) {
    if (request.uri().isEmpty() || !request.uri().startsWith("/")) {
        return false;
    }
    String requestResource = request.uri().substring(1);
    if (requestResource.isEmpty()) {
        requestResource = "index.html";
    }
    URL resourceUrl = INSTANCE.getClass().getResource(requestResource);
    if (resourceUrl == null) {
        return false;
    }
    RandomAccessFile raf = null;
    long fileLength = -1L;
    try {
        raf = new RandomAccessFile(resourceUrl.getFile(), "r");
        fileLength = raf.length();
    } catch (FileNotFoundException fne) {
        System.out.println("File not found " + fne.getMessage());
        return false;
    } catch (IOException io) {
        System.out.println("Cannot read file length " + io.getMessage());
        return false;
    } finally {
        if (fileLength < 0 && raf != null) {
            try {
                raf.close();
            } catch (IOException io) {
            // Nothing to do
            }
        }
    }
    HttpResponse response = new DefaultHttpResponse(request.protocolVersion(), OK);
    HttpUtil.setContentLength(response, fileLength);
    String contentType = "application/octet-stream";
    if (requestResource.endsWith("html")) {
        contentType = "text/html; charset=UTF-8";
    } else if (requestResource.endsWith("css")) {
        contentType = "text/css; charset=UTF-8";
    } else if (requestResource.endsWith("js")) {
        contentType = "application/javascript";
    }
    response.headers().set(CONTENT_TYPE, contentType);
    sendResponse(response, ctx, false);
    ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength));
    ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
    return true;
}
Also used : RandomAccessFile(java.io.RandomAccessFile) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) FileNotFoundException(java.io.FileNotFoundException) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultHttpResponse(io.netty.handler.codec.http.DefaultHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) HttpResponse(io.netty.handler.codec.http.HttpResponse) IOException(java.io.IOException) DefaultFileRegion(io.netty.channel.DefaultFileRegion) URL(java.net.URL)

Example 13 with DefaultFileRegion

use of org.apache.flink.shaded.netty4.io.netty.channel.DefaultFileRegion in project netty by netty.

the class SocketFileRegionTest method testFileRegionCountLargerThenFile.

public void testFileRegionCountLargerThenFile(ServerBootstrap sb, Bootstrap cb) throws Throwable {
    File file = PlatformDependent.createTempFile("netty-", ".tmp", null);
    file.deleteOnExit();
    final FileOutputStream out = new FileOutputStream(file);
    out.write(data);
    out.close();
    sb.childHandler(new SimpleChannelInboundHandler<ByteBuf>() {

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) {
        // Just drop the message.
        }
    });
    cb.handler(new ChannelInboundHandlerAdapter());
    Channel sc = sb.bind().sync().channel();
    Channel cc = cb.connect(sc.localAddress()).sync().channel();
    // Request file region which is bigger then the underlying file.
    FileRegion region = new DefaultFileRegion(new RandomAccessFile(file, "r").getChannel(), 0, data.length + 1024);
    assertThat(cc.writeAndFlush(region).await().cause(), CoreMatchers.<Throwable>instanceOf(IOException.class));
    cc.close().sync();
    sc.close().sync();
}
Also used : RandomAccessFile(java.io.RandomAccessFile) FileOutputStream(java.io.FileOutputStream) Channel(io.netty.channel.Channel) WritableByteChannel(java.nio.channels.WritableByteChannel) FileRegion(io.netty.channel.FileRegion) DefaultFileRegion(io.netty.channel.DefaultFileRegion) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) IOException(java.io.IOException) ByteBuf(io.netty.buffer.ByteBuf) DefaultFileRegion(io.netty.channel.DefaultFileRegion) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 14 with DefaultFileRegion

use of org.apache.flink.shaded.netty4.io.netty.channel.DefaultFileRegion in project flink by apache.

the class StaticFileServerHandler method respondToRequest.

/**
 * Response when running with leading JobManager.
 */
private void respondToRequest(ChannelHandlerContext ctx, HttpRequest request, String requestPath) throws IOException, ParseException, URISyntaxException, RestHandlerException {
    // convert to absolute path
    final File file = new File(rootPath, requestPath);
    if (!file.exists()) {
        // file does not exist. Try to load it with the classloader
        ClassLoader cl = StaticFileServerHandler.class.getClassLoader();
        try (InputStream resourceStream = cl.getResourceAsStream("web" + requestPath)) {
            boolean success = false;
            try {
                if (resourceStream != null) {
                    URL root = cl.getResource("web");
                    URL requested = cl.getResource("web" + requestPath);
                    if (root != null && requested != null) {
                        URI rootURI = new URI(root.getPath()).normalize();
                        URI requestedURI = new URI(requested.getPath()).normalize();
                        // expected scope.
                        if (!rootURI.relativize(requestedURI).equals(requestedURI)) {
                            logger.debug("Loading missing file from classloader: {}", requestPath);
                            // ensure that directory to file exists.
                            file.getParentFile().mkdirs();
                            Files.copy(resourceStream, file.toPath());
                            success = true;
                        }
                    }
                }
            } catch (Throwable t) {
                logger.error("error while responding", t);
            } finally {
                if (!success) {
                    logger.debug("Unable to load requested file {} from classloader", requestPath);
                    throw new NotFoundException(String.format("Unable to load requested file %s.", requestPath));
                }
            }
        }
    }
    checkFileValidity(file, rootPath, logger);
    // cache validation
    final 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) {
            if (logger.isDebugEnabled()) {
                logger.debug("Responding 'NOT MODIFIED' for file '" + file.getAbsolutePath() + '\'');
            }
            sendNotModified(ctx);
            return;
        }
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Responding with file '" + file.getAbsolutePath() + '\'');
    }
    // Don't need to close this manually. Netty's DefaultFileRegion will take care of it.
    final RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("Could not find file {}.", file.getAbsolutePath());
        }
        throw new NotFoundException("File not found.");
    }
    try {
        long fileLength = raf.length();
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
        setContentTypeHeader(response, file);
        setDateAndCacheHeaders(response, file);
        if (HttpHeaders.isKeepAlive(request)) {
            response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
        }
        HttpHeaders.setContentLength(response, fileLength);
        // write the initial line and the header.
        ctx.write(response);
        // write the content.
        ChannelFuture lastContentFuture;
        if (ctx.pipeline().get(SslHandler.class) == null) {
            ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise());
            lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
        } else {
            lastContentFuture = ctx.writeAndFlush(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)), ctx.newProgressivePromise());
        // HttpChunkedInput will write the end marker (LastHttpContent) for us.
        }
        // close the connection, if no keep-alive is needed
        if (!HttpHeaders.isKeepAlive(request)) {
            lastContentFuture.addListener(ChannelFutureListener.CLOSE);
        }
    } catch (Exception e) {
        raf.close();
        logger.error("Failed to serve file.", e);
        throw new RestHandlerException("Internal server error.", INTERNAL_SERVER_ERROR);
    }
}
Also used : ChannelFuture(org.apache.flink.shaded.netty4.io.netty.channel.ChannelFuture) InputStream(java.io.InputStream) ChunkedFile(org.apache.flink.shaded.netty4.io.netty.handler.stream.ChunkedFile) FileNotFoundException(java.io.FileNotFoundException) NotFoundException(org.apache.flink.runtime.rest.NotFoundException) FileNotFoundException(java.io.FileNotFoundException) FullHttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.FullHttpResponse) HttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpResponse) DefaultHttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultHttpResponse) DefaultFullHttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultFullHttpResponse) DefaultFileRegion(org.apache.flink.shaded.netty4.io.netty.channel.DefaultFileRegion) URI(java.net.URI) URL(java.net.URL) Date(java.util.Date) SslHandler(org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslHandler) URISyntaxException(java.net.URISyntaxException) NotFoundException(org.apache.flink.runtime.rest.NotFoundException) ParseException(java.text.ParseException) FileNotFoundException(java.io.FileNotFoundException) RestHandlerException(org.apache.flink.runtime.rest.handler.RestHandlerException) IOException(java.io.IOException) RestHandlerException(org.apache.flink.runtime.rest.handler.RestHandlerException) HttpChunkedInput(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpChunkedInput) RandomAccessFile(java.io.RandomAccessFile) DefaultHttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultHttpResponse) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) ChunkedFile(org.apache.flink.shaded.netty4.io.netty.handler.stream.ChunkedFile) SimpleDateFormat(java.text.SimpleDateFormat)

Example 15 with DefaultFileRegion

use of org.apache.flink.shaded.netty4.io.netty.channel.DefaultFileRegion in project flink by apache.

the class HandlerUtils method transferFile.

public static void transferFile(ChannelHandlerContext ctx, File file, HttpRequest httpRequest) throws FlinkException {
    final RandomAccessFile randomAccessFile;
    try {
        randomAccessFile = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException e) {
        throw new FlinkException("Can not find file " + file + ".", e);
    }
    try {
        final long fileLength = randomAccessFile.length();
        final FileChannel fileChannel = randomAccessFile.getChannel();
        try {
            HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
            response.headers().set(CONTENT_TYPE, "text/plain");
            if (HttpHeaders.isKeepAlive(httpRequest)) {
                response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
            }
            HttpHeaders.setContentLength(response, fileLength);
            // write the initial line and the header.
            ctx.write(response);
            // write the content.
            final ChannelFuture lastContentFuture;
            final GenericFutureListener<Future<? super Void>> completionListener = future -> {
                fileChannel.close();
                randomAccessFile.close();
            };
            if (ctx.pipeline().get(SslHandler.class) == null) {
                ctx.write(new DefaultFileRegion(fileChannel, 0, fileLength), ctx.newProgressivePromise()).addListener(completionListener);
                lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
            } else {
                lastContentFuture = ctx.writeAndFlush(new HttpChunkedInput(new ChunkedFile(randomAccessFile, 0, fileLength, 8192)), ctx.newProgressivePromise()).addListener(completionListener);
            // HttpChunkedInput will write the end marker (LastHttpContent) for us.
            }
            // close the connection, if no keep-alive is needed
            if (!HttpHeaders.isKeepAlive(httpRequest)) {
                lastContentFuture.addListener(ChannelFutureListener.CLOSE);
            }
        } catch (IOException ex) {
            fileChannel.close();
            throw ex;
        }
    } catch (IOException ioe) {
        try {
            randomAccessFile.close();
        } catch (IOException e) {
            throw new FlinkException("Close file or channel error.", e);
        }
        throw new FlinkException("Could not transfer file " + file + " to the client.", ioe);
    }
}
Also used : ChannelFuture(org.apache.flink.shaded.netty4.io.netty.channel.ChannelFuture) RestMapperUtils(org.apache.flink.runtime.rest.util.RestMapperUtils) FlinkException(org.apache.flink.util.FlinkException) RandomAccessFile(java.io.RandomAccessFile) ChannelFutureListener(org.apache.flink.shaded.netty4.io.netty.channel.ChannelFutureListener) OK(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpResponseStatus.OK) LastHttpContent(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.LastHttpContent) LoggerFactory(org.slf4j.LoggerFactory) CompletableFuture(java.util.concurrent.CompletableFuture) Future(org.apache.flink.shaded.netty4.io.netty.util.concurrent.Future) HTTP_1_1(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpVersion.HTTP_1_1) DefaultHttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultHttpResponse) HttpResponseStatus(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpResponseStatus) DefaultFileRegion(org.apache.flink.shaded.netty4.io.netty.channel.DefaultFileRegion) HttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpResponse) HttpHeaders(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpHeaders) ObjectMapper(org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper) Map(java.util.Map) ConfigConstants(org.apache.flink.configuration.ConfigConstants) HttpRequest(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpRequest) CONNECTION(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpHeaders.Names.CONNECTION) Nonnull(javax.annotation.Nonnull) ChannelFuture(org.apache.flink.shaded.netty4.io.netty.channel.ChannelFuture) ErrorResponseBody(org.apache.flink.runtime.rest.messages.ErrorResponseBody) ChannelHandlerContext(org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext) CONTENT_TYPE(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE) HttpChunkedInput(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpChunkedInput) Logger(org.slf4j.Logger) RestConstants(org.apache.flink.runtime.rest.util.RestConstants) GenericFutureListener(org.apache.flink.shaded.netty4.io.netty.util.concurrent.GenericFutureListener) StringWriter(java.io.StringWriter) Unpooled(org.apache.flink.shaded.netty4.io.netty.buffer.Unpooled) IOException(java.io.IOException) ByteBuf(org.apache.flink.shaded.netty4.io.netty.buffer.ByteBuf) SslHandler(org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslHandler) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) ResponseBody(org.apache.flink.runtime.rest.messages.ResponseBody) ChunkedFile(org.apache.flink.shaded.netty4.io.netty.handler.stream.ChunkedFile) FileChannel(java.nio.channels.FileChannel) FileChannel(java.nio.channels.FileChannel) ChunkedFile(org.apache.flink.shaded.netty4.io.netty.handler.stream.ChunkedFile) FileNotFoundException(java.io.FileNotFoundException) DefaultHttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpResponse) IOException(java.io.IOException) DefaultFileRegion(org.apache.flink.shaded.netty4.io.netty.channel.DefaultFileRegion) FlinkException(org.apache.flink.util.FlinkException) SslHandler(org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslHandler) HttpChunkedInput(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpChunkedInput) RandomAccessFile(java.io.RandomAccessFile) DefaultHttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultHttpResponse) CompletableFuture(java.util.concurrent.CompletableFuture) Future(org.apache.flink.shaded.netty4.io.netty.util.concurrent.Future) ChannelFuture(org.apache.flink.shaded.netty4.io.netty.channel.ChannelFuture)

Aggregations

DefaultFileRegion (io.netty.channel.DefaultFileRegion)14 RandomAccessFile (java.io.RandomAccessFile)11 File (java.io.File)9 IOException (java.io.IOException)8 FileNotFoundException (java.io.FileNotFoundException)7 ChunkedFile (io.netty.handler.stream.ChunkedFile)6 ChannelFuture (io.netty.channel.ChannelFuture)5 FileRegion (io.netty.channel.FileRegion)4 DefaultHttpResponse (io.netty.handler.codec.http.DefaultHttpResponse)4 HttpChunkedInput (io.netty.handler.codec.http.HttpChunkedInput)4 HttpResponse (io.netty.handler.codec.http.HttpResponse)4 URL (java.net.URL)4 FileChannel (java.nio.channels.FileChannel)4 SimpleDateFormat (java.text.SimpleDateFormat)4 Date (java.util.Date)4 Channel (io.netty.channel.Channel)3 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)3 DefaultFullHttpResponse (io.netty.handler.codec.http.DefaultFullHttpResponse)3 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)3 SslHandler (io.netty.handler.ssl.SslHandler)3