List of usage examples for io.netty.channel DefaultFileRegion DefaultFileRegion
public DefaultFileRegion(File f, long position, long count)
From source file:io.advantageous.conekt.net.impl.ConnectionBase.java
License:Open Source License
protected ChannelFuture sendFile(RandomAccessFile raf, long offset, long length) throws IOException { // Write the content. ChannelFuture writeFuture;//from w w w. j av a 2 s . c om if (!supportsFileRegion()) { // Cannot use zero-copy writeFuture = writeToChannel(new ChunkedFile(raf, offset, length, 8192)); } else { // No encryption - use zero-copy. FileRegion region = new DefaultFileRegion(raf.getChannel(), offset, length); writeFuture = writeToChannel(region); } if (writeFuture != null) { writeFuture.addListener(fut -> raf.close()); } else { raf.close(); } return writeFuture; }
From source file:io.aos.netty5.file.FileServerHandler.java
License:Apache License
@Override public void messageReceived(ChannelHandlerContext ctx, String msg) throws Exception { RandomAccessFile raf = null;//from ww w.ja v a2s .c om long length = -1; try { raf = new RandomAccessFile(msg, "r"); length = raf.length(); } catch (Exception e) { ctx.writeAndFlush("ERR: " + e.getClass().getSimpleName() + ": " + e.getMessage() + '\n'); return; } finally { if (length < 0 && raf != null) { raf.close(); } } ctx.write("OK: " + raf.length() + '\n'); if (ctx.pipeline().get(SslHandler.class) == null) { // SSL not enabled - can use zero-copy file transfer. ctx.write(new DefaultFileRegion(raf.getChannel(), 0, length)); } else { // SSL enabled - cannot use zero-copy file transfer. ctx.write(new ChunkedFile(raf)); } ctx.writeAndFlush("\n"); }
From source file:io.aos.netty5.http.file.HttpStaticFileServerHandler.java
License:Apache License
@Override public void messageReceived(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (!request.decoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST);// ww w. jav a 2 s . com return; } if (request.method() != GET) { sendError(ctx, METHOD_NOT_ALLOWED); return; } final String uri = request.uri(); final String path = sanitizeUri(uri); 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); } 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 ignore) { sendError(ctx, NOT_FOUND); return; } long fileLength = raf.length(); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); HttpHeaderUtil.setContentLength(response, fileLength); setContentTypeHeader(response, file); setDateAndCacheHeaders(response, file); if (HttpHeaderUtil.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 (ctx.pipeline().get(SslHandler.class) == null) { sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise()); } else { sendFileFuture = ctx.write(new HttpChunkedInput(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(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."); } }); // Write the end marker ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); // Decide whether to close the connection or not. if (!HttpHeaderUtil.isKeepAlive(request)) { // Close the connection when the whole content is written out. lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }
From source file:io.crate.protocols.http.HttpBlobHandler.java
License:Apache License
private ChannelFuture transferFile(final String digest, RandomAccessFile raf, long position, long count) throws IOException { Channel channel = ctx.channel(); final ChannelFuture fileFuture; final ChannelFuture endMarkerFuture; if (sslEnabled) { HttpChunkedInput httpChunkedInput = new HttpChunkedInput( new ChunkedFile(raf, 0, count, HTTPS_CHUNK_SIZE)); fileFuture = channel.writeAndFlush(httpChunkedInput, ctx.newProgressivePromise()); // HttpChunkedInput also writes the end marker (LastHttpContent) for us. endMarkerFuture = fileFuture;/*from www.jav a 2 s. co m*/ } else { FileRegion region = new DefaultFileRegion(raf.getChannel(), position, count); fileFuture = channel.write(region, ctx.newProgressivePromise()); // Flushes and sets the ending marker endMarkerFuture = channel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); } fileFuture.addListener(new ChannelProgressiveFutureListener() { @Override public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) throws Exception { LOGGER.debug("transferFile digest={} progress={} total={}", digest, progress, total); } @Override public void operationComplete(ChannelProgressiveFuture future) throws Exception { LOGGER.trace("transferFile operationComplete"); } }); return endMarkerFuture; }
From source file:io.gatling.http.client.body.file.FileRequestBody.java
License:Apache License
@Override public WritableContent build(boolean zeroCopy, ByteBufAllocator alloc) throws IOException { long contentLength = content.length(); Object file = zeroCopy ? new DefaultFileRegion(content, 0, contentLength) : new ChunkedFile(content); return new WritableContent(file, contentLength); }
From source file:io.jsync.net.impl.ConnectionBase.java
License:Open Source License
protected ChannelFuture sendFile(File file) { final RandomAccessFile raf; try {/*from w ww. ja v a2 s. c o m*/ raf = new RandomAccessFile(file, "r"); long fileLength = file.length(); // Write the content. ChannelFuture writeFuture; if (!supportsFileRegion()) { // Cannot use zero-copy writeFuture = write(new ChunkedFile(raf, 0, fileLength, 8192)); } else { // No encryption - use zero-copy. final FileRegion region = new DefaultFileRegion(raf.getChannel(), 0, fileLength); writeFuture = write(region); } writeFuture.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { raf.close(); } }); return writeFuture; } catch (IOException e) { handleException(e); return null; } }
From source file:io.netty.example.http.file.HttpStaticFileServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { this.request = request; if (!request.decoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST);/*from w w w . j ava 2s . c om*/ return; } if (!GET.equals(request.method())) { this.sendError(ctx, METHOD_NOT_ALLOWED); return; } final boolean keepAlive = HttpUtil.isKeepAlive(request); final String uri = request.uri(); final String path = sanitizeUri(uri); if (path == null) { this.sendError(ctx, FORBIDDEN); return; } File file = new File(path); if (file.isHidden() || !file.exists()) { this.sendError(ctx, NOT_FOUND); return; } if (file.isDirectory()) { if (uri.endsWith("/")) { this.sendListing(ctx, file, uri); } else { this.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) { this.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 (!keepAlive) { response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE); } else if (request.protocolVersion().equals(HTTP_1_0)) { response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.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 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 (!keepAlive) { // Close the connection when the whole content is written out. lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }
From source file:io.reactivex.netty.protocol.http.server.file.FileRequestHandler.java
License:Apache License
@Override public Observable<Void> handle(HttpServerRequest<ByteBuf> request, HttpServerResponse<ByteBuf> response) { // We don't support GET. if (!request.getHttpMethod().equals(GET)) { return Observable.error(new HttpError(METHOD_NOT_ALLOWED)); }/*from w w w. j a v a2s . co m*/ RandomAccessFile raf = null; String sanitizedUri = sanitizeUri(request.getUri()); if (sanitizedUri == null) { return Observable.error(new HttpError(FORBIDDEN)); } URI uri = resolveUri(sanitizedUri); if (uri == null) { return Observable.error(new HttpError(NOT_FOUND)); } File file = new File(uri); if (file.isHidden() || !file.exists()) { return Observable.error(new HttpError(NOT_FOUND)); } if (file.isDirectory()) { return Observable.error(new HttpError(FORBIDDEN)); } if (!file.isFile()) { return Observable.error(new HttpError(FORBIDDEN)); } long fileLength; try { raf = new RandomAccessFile(file, "r"); fileLength = raf.length(); } catch (Exception e) { logger.warn("Error accessing file {}", uri, e); if (raf != null) { try { raf.close(); } catch (IOException e1) { logger.warn("Error closing file {}", uri, e1); } } return Observable.error(e); } // Cache Validation String ifModifiedSince = request.getHeaders().get(IF_MODIFIED_SINCE); if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) { SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US); Date ifModifiedSinceDate = null; try { ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince); } catch (ParseException e) { logger.warn("Failed to parse {} header", IF_MODIFIED_SINCE); } if (ifModifiedSinceDate != null) { // 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) { response.setStatus(NOT_MODIFIED); setDateHeader(response, dateFormatter); return response.close(); } } } response.setStatus(OK); response.getHeaders().setContentLength(fileLength); setContentTypeHeader(response, file); setDateAndCacheHeaders(response, file); if (request.getHeaders().isKeepAlive()) { response.getHeaders().set(CONNECTION, KEEP_ALIVE); } if (response.getChannel().pipeline().get(SslHandler.class) == null) { response.writeFileRegion(new DefaultFileRegion(raf.getChannel(), 0, fileLength)); } else { try { response.writeChunkedInput(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, CHUNK_SIZE))); } catch (IOException e) { logger.warn("Failed to write chunked file {}", e); return Observable.error(e); } } return response.close(); }
From source file:io.syncframework.netty.RequestHandler.java
License:Apache License
private boolean sendFile(ChannelHandlerContext ctx, Response response) throws Exception { Application application = response.getApplication(); if (application == null) { log.error("no response.application has been set"); sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR); return true; }//from w ww. jav a2 s . c o m File file = response.getFile(); if (file == null) { log.error("no response.file has been set"); sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR); return true; } if (!file.exists()) { // file not found try request dynamically if (log.isDebugEnabled()) log.debug("{}: file not found: {}", application, file); return false; } if (file.isHidden()) { if (log.isDebugEnabled()) { log.debug("{}: file {} is hidden; returning File Not Found", application, file.getAbsolutePath()); } sendFileNotFound(ctx); return true; } if (file.isDirectory()) { // once is a directory a dynamic handler can take it ... // even if a index.html, the @Action Controller.main() shall handle it return false; } // // Check if the file resides under the PUBLIC or PRIVATE folders. // More important point for this verification is with PUBLIC requests where multiples ../../../.. // may lead to security breach - exposing unwanted system files. // String path = file.getAbsolutePath(); if (!path.startsWith(application.getConfig().getPublicDirectory().getAbsolutePath()) && !path.startsWith(application.getConfig().getPrivateDirectory().getAbsolutePath())) { log.error("{}: file {} returned, is not located under Public or Private folders", application, file.getAbsolutePath()); sendError(ctx, HttpResponseStatus.FORBIDDEN); return true; } if (!file.isFile()) { sendError(ctx, HttpResponseStatus.FORBIDDEN); return true; } RandomAccessFile raf; try { raf = new RandomAccessFile(file, "r"); } catch (FileNotFoundException ignore) { sendError(ctx, NOT_FOUND); return true; } long fileLength = raf.length(); if (log.isTraceEnabled()) log.trace("{}: returning file: {}", application, file); HttpResponse httpResponse = new DefaultHttpResponse(HTTP_1_1, OK); HttpUtil.setContentLength(httpResponse, fileLength); httpResponse.headers().set(CONTENT_TYPE, MimeUtils.getContentType(file)); setDateAndCacheHeaders(httpResponse, file); httpResponse.headers().set(CONNECTION, HttpHeaderValues.CLOSE); // // if response has declared specific Headers, then this may or may not override the default headers // declared above. // if (response.getHeaders() != null) { if (log.isTraceEnabled()) log.trace("custom response headers identified... passing to the response"); for (String header : response.getHeaders().keySet()) { if (log.isTraceEnabled()) log.trace("setting response header: {}: {}", header, response.getHeaders().get(header)); httpResponse.headers().set(header, response.getHeaders().get(header)); } } // Write the initial line and the header. ctx.write(httpResponse); // Write the content. ChannelFuture sendFileFuture; ChannelFuture lastContentFuture; sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise()); lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); sendFileFuture.addListener(new ChannelProgressiveFutureListener() { @Override public void operationProgressed(ChannelProgressiveFuture future, long progress, long total) { if (total < 0) { // total unknown if (log.isTraceEnabled()) log.trace("{}: " + future.channel() + " transfer progress: " + progress, application); } else { if (log.isTraceEnabled()) log.trace("{}: " + future.channel() + " Transfer progress: " + progress + " / " + total, application); } } @Override public void operationComplete(ChannelProgressiveFuture future) { if (log.isTraceEnabled()) log.trace("{}: " + future.channel() + " transfer complete.", application); if (raf != null) { try { raf.close(); } catch (Exception ignore) { if (log.isTraceEnabled()) log.trace("exception caught: {}", ignore); } } } }); // Close the connection when the whole content is written out. ctx.flush(); lastContentFuture.addListener(ChannelFutureListener.CLOSE); return true; }
From source file:io.urmia.st.StorageServerHandler.java
License:Open Source License
private void downloadFile(ChannelHandlerContext ctx, File file) throws IOException { final RandomAccessFile raf; try {/*from w w w. j a v a 2s. c o m*/ raf = new RandomAccessFile(file, "r"); } catch (FileNotFoundException fnfe) { log.warn("no file at: {}", file.getPath()); access.fail(ctx, "GET", file.getAbsolutePath(), requestStartMS); sendError(ctx, NOT_FOUND); return; } final long fileLength = raf.length(); log.info("downloading file: {} of len: {}", file, fileLength); 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); final ChannelFuture sendFileFuture; sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), 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); access.success(ctx, "GET", file.getAbsolutePath(), requestStartMS); // 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); } }