List of usage examples for io.netty.channel DefaultFileRegion DefaultFileRegion
public DefaultFileRegion(File f, long position, long count)
From source file:org.apache.spark.network.netty.FileServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, String blockIdString) { BlockId blockId = BlockId.apply(blockIdString); FileSegment fileSegment = pResolver.getBlockLocation(blockId); // if getBlockLocation returns null, close the channel if (fileSegment == null) { //ctx.close(); return;//w ww . j av a 2 s . c om } File file = fileSegment.file(); if (file.exists()) { if (!file.isFile()) { ctx.write(new FileHeader(0, blockId).buffer()); ctx.flush(); return; } long length = fileSegment.length(); if (length > Integer.MAX_VALUE || length <= 0) { ctx.write(new FileHeader(0, blockId).buffer()); ctx.flush(); return; } int len = (int) length; ctx.write((new FileHeader(len, blockId)).buffer()); try { ctx.write(new DefaultFileRegion(new FileInputStream(file).getChannel(), fileSegment.offset(), fileSegment.length())); } catch (Exception e) { LOG.error("Exception: ", e); } } else { ctx.write(new FileHeader(0, blockId).buffer()); } ctx.flush(); }
From source file:org.apache.tajo.HttpFileServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (request.getMethod() != HttpMethod.GET) { sendError(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED); return;/*from w ww .java 2s . co m*/ } final String path = sanitizeUri(request.getUri()); if (path == null) { sendError(ctx, HttpResponseStatus.FORBIDDEN); return; } File file = new File(path); if (file.isHidden() || !file.exists()) { sendError(ctx, HttpResponseStatus.NOT_FOUND); return; } if (!file.isFile()) { sendError(ctx, HttpResponseStatus.FORBIDDEN); return; } RandomAccessFile raf; try { raf = new RandomAccessFile(file, "r"); } catch (FileNotFoundException fnfe) { sendError(ctx, HttpResponseStatus.NOT_FOUND); return; } long fileLength = raf.length(); HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); HttpHeaders.setContentLength(response, fileLength); setContentTypeHeader(response); // Write the initial line and the header. ctx.write(response); // Write the content. ChannelFuture writeFuture; ChannelFuture lastContentFuture; if (ctx.pipeline().get(SslHandler.class) != null) { // Cannot use zero-copy with HTTPS. lastContentFuture = ctx.writeAndFlush(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192))); } else { // No encryption - use zero-copy. final FileRegion region = new DefaultFileRegion(raf.getChannel(), 0, fileLength); writeFuture = ctx.write(region); lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); writeFuture.addListener(new ChannelProgressiveFutureListener() { @Override public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) throws Exception { LOG.trace(String.format("%s: %d / %d", path, progress, total)); } @Override public void operationComplete(ChannelProgressiveFuture future) throws Exception { region.release(); } }); } // 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.apache.tajo.pullserver.HttpDataServerHandler.java
License:Apache License
private ChannelFuture sendFile(ChannelHandlerContext ctx, FileChunk file) throws IOException { RandomAccessFile raf;// ww w.ja v a2s .c o m try { raf = new RandomAccessFile(file.getFile(), "r"); } catch (FileNotFoundException fnfe) { return null; } ChannelFuture writeFuture; ChannelFuture lastContentFuture; if (ctx.pipeline().get(SslHandler.class) != null) { // Cannot use zero-copy with HTTPS. lastContentFuture = ctx .write(new HttpChunkedInput(new ChunkedFile(raf, file.startOffset(), file.length(), 8192))); } else { // No encryption - use zero-copy. final FileRegion region = new DefaultFileRegion(raf.getChannel(), file.startOffset(), file.length()); writeFuture = ctx.write(region); lastContentFuture = ctx.write(LastHttpContent.EMPTY_LAST_CONTENT); writeFuture.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) { if (region.refCnt() > 0) { region.release(); } } }); } return lastContentFuture; }
From source file:org.apache.tajo.storage.http.ExampleHttpServerHandler.java
License:Apache License
private void processGet(ChannelHandlerContext context, FullHttpRequest request) { try {// w w w. ja va 2 s .c om File file = getRequestedFile(request.getUri()); RandomAccessFile raf = new RandomAccessFile(file, "r"); long fileLength = raf.length(); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); HttpHeaders.setContentLength(response, fileLength); setContentTypeHeader(response, file); context.write(response); context.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength)); // Write the end marker. ChannelFuture future = context.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); future.addListener(ChannelFutureListener.CLOSE); } catch (IOException | URISyntaxException e) { context.writeAndFlush(getBadRequest(e.getMessage())); } }
From source file:org.asynchttpclient.netty.request.body.NettyFileBody.java
License:Open Source License
@Override public void write(Channel channel, NettyResponseFuture<?> future) throws IOException { @SuppressWarnings("resource") // Netty will close the ChunkedNioFile or the DefaultFileRegion final FileChannel fileChannel = new RandomAccessFile(file, "r").getChannel(); Object message = (ChannelManager.isSslHandlerConfigured(channel.pipeline()) || config.isDisableZeroCopy()) ? // new ChunkedNioFile(fileChannel, offset, length, config.getChunkedFileChunkSize()) : new DefaultFileRegion(fileChannel, offset, length); channel.write(message, channel.newProgressivePromise())// .addListener(new WriteProgressListener(future, false, getContentLength())); channel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT, channel.voidPromise()); }
From source file:org.asynchttpclient.providers.netty.request.body.NettyFileBody.java
License:Apache License
@Override public void write(Channel channel, NettyResponseFuture<?> future, AsyncHttpClientConfig config) throws IOException { final RandomAccessFile raf = new RandomAccessFile(file, "r"); try {//from www. j av a2s . c om ChannelFuture writeFuture; if (Channels.getSslHandler(channel) != null || disableZeroCopy) { writeFuture = channel.write(new ChunkedFile(raf, offset, length, MAX_BUFFERED_BYTES), channel.newProgressivePromise()); } else { FileRegion region = new DefaultFileRegion(raf.getChannel(), offset, length); writeFuture = channel.write(region, channel.newProgressivePromise()); } writeFuture.addListener( new ProgressListener(config, future.getAsyncHandler(), future, false, getContentLength()) { public void operationComplete(ChannelProgressiveFuture cf) { try { // FIXME probably useless in Netty 4 raf.close(); } catch (IOException e) { LOGGER.warn("Failed to close request body: {}", e.getMessage(), e); } super.operationComplete(cf); } }); channel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); } catch (IOException ex) { if (raf != null) { try { raf.close(); } catch (IOException e) { } } throw ex; } }
From source file:org.asynchttpclient.providers.netty4.request.body.NettyFileBody.java
License:Open Source License
@Override public void write(Channel channel, NettyResponseFuture<?> future, AsyncHttpClientConfig config) throws IOException { final RandomAccessFile raf = new RandomAccessFile(file, "r"); try {//w ww . ja va2 s . c o m ChannelFuture writeFuture; if (ChannelManager.isSslHandlerConfigured(channel.pipeline()) || nettyConfig.isDisableZeroCopy()) { writeFuture = channel.write( new ChunkedFile(raf, offset, length, nettyConfig.getChunkedFileChunkSize()), channel.newProgressivePromise()); } else { FileRegion region = new DefaultFileRegion(raf.getChannel(), offset, length); writeFuture = channel.write(region, channel.newProgressivePromise()); } writeFuture.addListener( new ProgressListener(config, future.getAsyncHandler(), future, false, getContentLength()) { public void operationComplete(ChannelProgressiveFuture cf) { closeSilently(raf); super.operationComplete(cf); } }); channel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); } catch (IOException ex) { closeSilently(raf); throw ex; } }
From source file:org.atmosphere.nettosphere.HttpStaticFileServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (!request.getDecoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST, request); return;//from ww w. ja v a 2 s .c om } if (request.getMethod() != GET) { sendError(ctx, METHOD_NOT_ALLOWED, request); return; } File file = null; RandomAccessFile raf = null; boolean found = true; for (String p : paths) { String path = p + sanitizeUri(request.getUri()); if (path.endsWith("/") || path.endsWith(File.separator)) { path += "index.html"; } if (path.endsWith("/favicon.ico") || path.endsWith(File.separator)) { request.headers().add(SERVICED, "true"); found = false; continue; } file = new File(path); if (file.isHidden() || !file.exists() || !file.isFile()) { found = false; continue; } // if (file.isDirectory()) { // if (uri.endsWith("/")) { // sendListing(ctx, file); // } else { // sendRedirect(ctx, uri + '/'); // } // return; // } try { raf = new RandomAccessFile(file, "r"); found = true; break; } catch (FileNotFoundException ignore) { sendError(ctx, NOT_FOUND, request); return; } } if (!found) { sendError(ctx, NOT_FOUND, request); return; } request.headers().add(SERVICED, "true"); // 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; } } long fileLength = raf.length(); ctx.pipeline().addBefore(BridgeRuntime.class.getName(), "encoder", new HttpResponseEncoder()); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); HttpHeaders.setContentLength(response, fileLength); contentType(request, 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.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 logger.trace(future.channel() + " Transfer progress: " + progress); } else { logger.trace(future.channel() + " Transfer progress: " + progress + " / " + total); } } @Override public void operationComplete(ChannelProgressiveFuture future) { logger.trace(future.channel() + " Transfer complete."); } }); // Close the connection when the whole content is written out. lastContentFuture.addListener(ChannelFutureListener.CLOSE); }
From source file:org.base.netty.http.buffer.FileSegmentManagedBuffer.java
License:Apache License
@Override public Object convertToNetty() throws IOException { if (lazyFileDescriptor) { return new DefaultFileRegion(file, offset, length); } else {/*w w w .j a va 2 s . c om*/ FileChannel fileChannel = new FileInputStream(file).getChannel(); return new DefaultFileRegion(fileChannel, offset, length); } }
From source file:org.dcache.xrootd.protocol.messages.ZeroCopyReadResponse.java
License:Open Source License
@Override public void writeTo(ChannelHandlerContext ctx, final ChannelPromise promise) { ByteBuf header = ctx.alloc().buffer(8); header.writeShort(request.getStreamId()); header.writeShort(kXR_ok);/*from w w w. j ava 2 s. co m*/ header.writeInt(count); ctx.write(header).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { promise.tryFailure(future.cause()); } } }); ctx.write(new DefaultFileRegion(file, request.getReadOffset(), count)) .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { promise.trySuccess(); } else { promise.tryFailure(future.cause()); } } }); }