List of usage examples for io.netty.channel FileRegion release
boolean release();
From source file:com.soho.framework.server.netty.http.HttpServletHandler.java
License:Apache License
protected void handleStaticResourceRequest(ChannelHandlerContext ctx, HttpRequest request) throws Exception { if (request.method() != GET) { sendError(ctx, METHOD_NOT_ALLOWED); return;/*w w w . j a va 2s .co m*/ } String uri = Utils.sanitizeUri(request.uri()); final String path = (uri != null ? ServletWebApp.get().getStaticResourcesFolder().getAbsolutePath() + File.separator + uri : null); if (path == null) { sendError(ctx, FORBIDDEN); return; } File file = new File(path); if (file.isHidden() || !file.exists()) { sendError(ctx, NOT_FOUND); return; } if (!file.isFile()) { sendError(ctx, FORBIDDEN); 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); Channel ch = ctx.channel(); // Write the initial line and the header. ch.write(response); // Write the content. ChannelFuture writeFuture; if (isSslChannel(ch)) { // 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 ChannelProgressiveFutureListener() { @Override public void operationProgressed(ChannelProgressiveFuture channelProgressiveFuture, long current, long total) throws Exception { System.out.printf("%s: %d / %d (+%d)%n", path, current, total, total); } @Override public void operationComplete(ChannelProgressiveFuture channelProgressiveFuture) throws Exception { region.release(); } }); } }
From source file:net.javaforge.netty.servlet.bridge.ServletBridgeHandler.java
License:Apache License
protected void handleStaticResourceRequest(ChannelHandlerContext ctx, HttpRequest request) throws Exception { if (request.method() != GET) { sendError(ctx, METHOD_NOT_ALLOWED); return;// ww w. jav a 2 s. c o m } String uri = Utils.sanitizeUri(request.uri()); final String path = (uri != null ? ServletBridgeWebapp.get().getStaticResourcesFolder().getAbsolutePath() + File.separator + uri : null); if (path == null) { sendError(ctx, FORBIDDEN); return; } File file = new File(path); if (file.isHidden() || !file.exists()) { sendError(ctx, NOT_FOUND); return; } if (!file.isFile()) { sendError(ctx, FORBIDDEN); 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); Channel ch = ctx.channel(); // Write the initial line and the header. ch.write(response); // Write the content. ChannelFuture writeFuture; if (isSslChannel(ch)) { // 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 ChannelProgressiveFutureListener() { @Override public void operationProgressed(ChannelProgressiveFuture channelProgressiveFuture, long current, long total) throws Exception { System.out.printf("%s: %d / %d (+%d)%n", path, current, total, total); } @Override public void operationComplete(ChannelProgressiveFuture channelProgressiveFuture) throws Exception { region.release(); } }); } }
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;/* ww w . java2 s. c o 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 .j a v a 2 s .com*/ 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.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.j ava 2 s . c o m // 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:whitespell.net.websockets.socketio.handler.ResourceHandler.java
License:Apache License
private void writeContent(RandomAccessFile raf, long fileLength, Channel ch) throws IOException { ChannelFuture writeFuture;// ww w . j a va 2 s . c o m 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); }