List of usage examples for io.netty.channel ChannelFutureListener CLOSE
ChannelFutureListener CLOSE
To view the source code for io.netty.channel ChannelFutureListener CLOSE.
Click Source Link
From source file:fr.kissy.zergling_push.infrastructure.HttpStaticFileServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (!request.decoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST);// w w w .ja va 2 s . com return; } if (request.method() != GET) { sendError(ctx, METHOD_NOT_ALLOWED); return; } final String uri = request.uri(); final String path = sanitizeUri(uri); 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 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 (HttpUtil.isKeepAlive(request)) { response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); } // 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()); } // Decide whether to close the connection or not. if (!HttpUtil.isKeepAlive(request)) { // Close the connection when the whole content is written out. lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }
From source file:fr.meuret.web.HttpStaticFileServerHandler.java
License:Apache License
private static void sendListing(ChannelHandlerContext ctx, Path root, Path absolutePath) { logger.debug("Send listing for absolutePath={}", absolutePath); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK); response.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8"); final StringBuilder buf = new StringBuilder(); buf.append("<!DOCTYPE html>\r\n"); buf.append("<html><head><title>"); buf.append("Listing of: "); //Root filename (in case the root path corresponds to the root of the filesystem (i.e c:\\) String filename = "/"; Path relativePath = root.relativize(absolutePath); if (!relativePath.getFileName().toString().isEmpty()) filename = absolutePath.getFileName().toString(); buf.append(filename);/* ww w.j a v a 2 s . c o m*/ buf.append("</title></head><body>\r\n"); buf.append("<h3>Listing of: "); buf.append(filename); buf.append("</h3>\r\n"); buf.append("<ul>"); buf.append("<li><a href=\"../\">..</a></li>\r\n"); logger.debug("Browsing the path : {}", absolutePath); try (DirectoryStream<Path> stream = Files.newDirectoryStream(absolutePath, new DirectoryStream.Filter<Path>() { @Override public boolean accept(Path entry) throws IOException { return !Files.isHidden(entry) && Files.isReadable(entry) && ALLOWED_FILE_NAME.matcher(entry.getFileName().toString()).matches(); } })) { for (Path entry : stream) { logger.debug("Appending the path entry {} to the listing.", entry); buf.append("<li><a href=\""); buf.append(entry.getFileName().toString()); buf.append("\">"); buf.append(entry.getFileName()); buf.append("</a></li>\r\n"); } } catch (IOException | DirectoryIteratorException e) { logger.error("Error occuring when browsing " + absolutePath, e); } buf.append("</ul></body></html>\r\n"); ByteBuf buffer = Unpooled.copiedBuffer(buf, CharsetUtil.UTF_8); response.content().writeBytes(buffer); buffer.release(); // Close the connection as soon as the error message is sent. logger.debug("Writing the listing to the channel"); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }
From source file:fr.meuret.web.HttpStaticFileServerHandler.java
License:Apache License
private static void sendRedirect(ChannelHandlerContext ctx, String newUri) { logger.debug("Sending client redirect, location uri = {}", newUri); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, FOUND); response.headers().set(LOCATION, newUri); // Close the connection as soon as the error message is sent. ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }
From source file:fr.meuret.web.HttpStaticFileServerHandler.java
License:Apache License
private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) { logger.debug("Sending client error, status = {}", status); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status, Unpooled.copiedBuffer("Failure: " + status + "\r\n", CharsetUtil.UTF_8)); response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8"); // Close the connection as soon as the error message is sent. ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }
From source file:fr.meuret.web.HttpStaticFileServerHandler.java
License:Apache License
/** * When file timestamp is the same as what the browser is sending up, send a "304 Not Modified" * * @param ctx Context//from ww w . j a va 2s . co m */ private static void sendNotModified(ChannelHandlerContext ctx) { logger.debug("Sending not modified response"); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, NOT_MODIFIED); setDateHeader(response); // Close the connection as soon as the error message is sent. ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }
From source file:fr.meuret.web.HttpStaticFileServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (!request.getDecoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST);/* www. j av a 2s.com*/ return; } if (request.getMethod() != GET) { sendError(ctx, METHOD_NOT_ALLOWED); return; } final String uri = request.getUri(); final String relativePath = sanitizeUri(uri); if (relativePath == null) { sendError(ctx, FORBIDDEN); return; } Path fileAbsolutePath = rootPath.resolve(relativePath); if (Files.isHidden(fileAbsolutePath) || Files.notExists(fileAbsolutePath)) { sendError(ctx, NOT_FOUND); return; } if (Files.isDirectory(fileAbsolutePath)) { if (uri.endsWith("/")) { sendListing(ctx, rootPath, fileAbsolutePath); } else { sendRedirect(ctx, uri + '/'); } return; } if (!Files.isRegularFile(fileAbsolutePath)) { 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 = Files.getLastModifiedTime(fileAbsolutePath).to(TimeUnit.SECONDS); if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) { sendNotModified(ctx); return; } } RandomAccessFile raf; File file = fileAbsolutePath.toFile(); 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); 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; //Zero-copy transfer is SSL is not enabled 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 logger.info("{} Transfer progress: {}", future.channel(), progress); } else { logger.info("{} Transfer progress: {} / {}", future.channel(), progress, total); } } @Override public void operationComplete(ChannelProgressiveFuture future) { logger.info("{} Transfer complete.", future.channel()); } }); // 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:gribbit.http.request.decoder.HttpRequestDecoder.java
License:Open Source License
/** * Send non-OK response. Used by Netty pipeline for uncaught exceptions (e.g. connecion reset by peer, malformed * HTTP message, etc.), and also called manually for caught exceptions. *//*from w w w.java2s .com*/ @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) { try { if (e instanceof NotSslRecordException) { // Malformed SSL ctx.channel().flush(); ctx.channel().close(); } else if ("Connection reset by peer".equals(e.getMessage())) { // TODO: should connection be closed in this case? Does a response need to be sent? // Log.info(cause.getMessage()); } else { if (request != null) { ResponseException exception = e instanceof ResponseException ? (ResponseException) e : new InternalServerErrorException(e); // Override default error response page if there is a custom handler for this error type Response response = generateErrorResponse(exception); if (exception instanceof InternalServerErrorException) { // Log backtrace for Internal Server Errors Log.request(request, response, exception); } else { Log.request(request, response); } // Send response if (request != null && ctx.channel().isOpen()) { try { response.send(ctx); return; } catch (Exception e2) { } } } // If couldn't send response in normal way (either there is no request object generated yet, or // there was an exception calling response.send()), then send a plain text response as a fallback if (ctx.channel().isOpen()) { Log.exception("Unexpected un-sendable exception", e); FullHttpResponse res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR); res.content().writeBytes("Internal Server Error".getBytes("UTF-8")); HttpHeaders headers = res.headers(); headers.set(CONTENT_TYPE, "text/plain;charset=utf-8"); HttpUtil.setContentLength(res, res.content().readableBytes()); // Disable caching headers.add(CACHE_CONTROL, "no-cache, no-store, must-revalidate"); // HTTP 1.1 headers.add(PRAGMA, "no-cache"); // HTTP 1.0 headers.add(EXPIRES, "0"); // Proxies ChannelFuture f = ctx.writeAndFlush(res); f.addListener(ChannelFutureListener.CLOSE); } } } catch (Exception e2) { Log.exception("Exception thrown while calling toplevel exception handler", e2); try { ctx.channel().flush(); ctx.channel().close(); } catch (Exception e3) { } } finally { freeResources(); } }
From source file:gribbit.http.response.Response.java
License:Open Source License
/** Send the response. */ public void send(ChannelHandlerContext ctx) throws ResponseException { try {/*from w ww .j a v a 2s . c o m*/ writeResponse(ctx); } catch (Exception e) { if (e instanceof ResponseException) { throw (ResponseException) e; } else { throw new InternalServerErrorException(e); } } finally { if (!keepAlive) { ctx.newPromise().addListener(ChannelFutureListener.CLOSE); } } }
From source file:http.HttpFileServerHandler.java
License:Apache License
@Override public void messageReceived(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (!request.getDecoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST);/*from w w w. jav a 2 s . co m*/ return; } if (request.getMethod() != GET) { sendError(ctx, METHOD_NOT_ALLOWED); return; } final String uri = request.getUri(); 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; } RandomAccessFile randomAccessFile = null; try { randomAccessFile = new RandomAccessFile(file, "r");// ?? } catch (FileNotFoundException fnfe) { sendError(ctx, NOT_FOUND); return; } long fileLength = randomAccessFile.length(); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); setContentLength(response, fileLength); setContentTypeHeader(response, file); if (isKeepAlive(request)) { response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } ctx.write(response); ChannelFuture sendFileFuture; sendFileFuture = ctx.write(new ChunkedFile(randomAccessFile, 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.out.println("Transfer complete."); } }); //0?NIO ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); if (!isKeepAlive(request)) { lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }
From source file:http.HttpFileServerHandler.java
License:Apache License
private static void sendListing(ChannelHandlerContext ctx, File dir) { FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK); response.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8"); StringBuilder buf = new StringBuilder(); String dirPath = dir.getPath(); buf.append("<!DOCTYPE html>\r\n"); buf.append("<html><head><title>"); buf.append(dirPath);// ww w .jav a2 s.co m buf.append(" "); buf.append("</title></head><body>\r\n"); buf.append("<h3>"); buf.append(dirPath).append(" "); buf.append("</h3>\r\n"); buf.append("<ul>"); buf.append("<li><a href=\"../\">..</a></li>\r\n"); for (File f : dir.listFiles()) { if (f.isHidden() || !f.canRead()) { continue; } String name = f.getName(); if (!ALLOWED_FILE_NAME.matcher(name).matches()) { continue; } buf.append("<li><a href=\""); buf.append(name); buf.append("\">"); buf.append(name); buf.append("</a></li>\r\n"); } buf.append("</ul></body></html>\r\n"); // ByteBuf buffer = Unpooled.copiedBuffer(buf, CharsetUtil.UTF_8); response.content().writeBytes(buffer); buffer.release(); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }