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:com.sangupta.swift.netty.spdy.SpdyStaticFileServerHandler.java
License:Apache License
@Override protected void channelRead0(final ChannelHandlerContext context, final FullHttpRequest request) throws Exception { if (!request.getDecoderResult().isSuccess()) { NettyUtils.sendError(context, HttpResponseStatus.BAD_REQUEST); return;/*from w w w. j a va 2 s . c o m*/ } // check for server name if (this.checkServerName) { String host = request.headers().get(HttpHeaders.Names.HOST); if (!host.startsWith(this.swiftServer.getServerName())) { NettyUtils.sendError(context, HttpResponseStatus.BAD_REQUEST); return; } } // check method if (request.getMethod() != HttpMethod.GET) { NettyUtils.sendError(context, HttpResponseStatus.METHOD_NOT_ALLOWED); return; } // check for SPDY support final boolean spdyRequest = request.headers().contains(NettyUtils.SPDY_STREAM_ID); // check for URI path to be proper final String uri = request.getUri(); final String path = NettyUtils.sanitizeUri(uri); if (path == null) { NettyUtils.sendError(context, HttpResponseStatus.FORBIDDEN); return; } File file = new File(documentRoot, path); if (file.isHidden() || !file.exists()) { NettyUtils.sendError(context, HttpResponseStatus.NOT_FOUND); return; } if (file.isDirectory()) { if (uri.endsWith("/")) { NettyUtils.sendListing(context, file, request.headers().get(NettyUtils.SPDY_STREAM_ID)); return; } // redirect to the listing page NettyUtils.sendRedirect(context, uri + '/'); return; } if (!file.isFile()) { NettyUtils.sendError(context, HttpResponseStatus.FORBIDDEN); return; } // Cache Validation String ifModifiedSince = request.headers().get(HttpHeaders.Names.IF_MODIFIED_SINCE); if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) { Date ifModifiedSinceDate = NettyUtils.parseDateHeader(ifModifiedSince); 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) { NettyUtils.sendNotModified(context); return; } } } RandomAccessFile raf; try { raf = new RandomAccessFile(file, "r"); } catch (FileNotFoundException ignore) { NettyUtils.sendError(context, HttpResponseStatus.NOT_FOUND); return; } final long fileLength = file.length(); HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); HttpHeaders.setContentLength(response, fileLength); NettyUtils.setContentTypeHeader(response, file); NettyUtils.setDateAndCacheHeaders(response, file, 3600); // cache for an hour // check for keep alive if (HttpHeaders.isKeepAlive(request)) { response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } else { context.write(response).addListener(ChannelFutureListener.CLOSE); } // Write the initial line and the header. context.write(response); // Write the content. ChannelFuture sendFileFuture; if (context.pipeline().get(SslHandler.class) == null) { sendFileFuture = context.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), context.newProgressivePromise()); } else { sendFileFuture = context.write(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)), context.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 = context.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); // 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:com.shiyq.netty.http.helloworld.HttpHelloWorldServerHandler.java
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; boolean keepAlive = HttpUtil.isKeepAlive(req); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT)); response.headers().set(CONTENT_TYPE, "text/plain"); response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes()); if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else {//ww w . j a v a2s. c o m response.headers().set(CONNECTION, KEEP_ALIVE); ctx.write(response); } } }
From source file:com.slyak.services.proxy.handler.Socks5PasswordAuthRequestHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, DefaultSocks5PasswordAuthRequest msg) throws Exception { if (authProvider.authenticate(msg.username(), msg.password())) { Socks5PasswordAuthResponse passwordAuthResponse = new DefaultSocks5PasswordAuthResponse( Socks5PasswordAuthStatus.SUCCESS); ctx.writeAndFlush(passwordAuthResponse); } else {//from w w w. java2 s . co m Socks5PasswordAuthResponse passwordAuthResponse = new DefaultSocks5PasswordAuthResponse( Socks5PasswordAuthStatus.FAILURE); //??????channel ctx.writeAndFlush(passwordAuthResponse).addListener(ChannelFutureListener.CLOSE); } }
From source file:com.soho.framework.server.netty.http.AsyncHttpServletHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object e) throws Exception { if (e instanceof ServletResponse) { logger.info("Handler async task..."); HttpServletResponse response = (HttpServletResponse) e; Runnable task = ThreadLocalAsyncExecutor.pollTask(response); task.run();/*from w ww .j a va 2s .co m*/ // write response... ChannelFuture future = ctx.channel().writeAndFlush(response); String keepAlive = response.getHeader(CONNECTION); if (null != keepAlive && HttpHeaders.Values.KEEP_ALIVE.equalsIgnoreCase(keepAlive)) { future.addListener(ChannelFutureListener.CLOSE); } } else { ctx.fireChannelRead(e); } }
From source file:com.soho.framework.server.netty.http.HttpServletHandler.java
License:Apache License
protected void handleHttpServletRequest(ChannelHandlerContext ctx, HttpRequest request, FilterChainImpl chain) throws Exception { // ?/*ww w .j a v a2 s. c om*/ interceptOnRequestReceived(ctx, request); // Netty HTTP?Servlet HttpServletRequestImpl req = buildHttpServletRequest(request, chain); // Netty HTTP??Servlet? DefaultFullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK); HttpServletResponseImpl resp = buildHttpServletResponse(response); // chain.doFilter(req, resp); // ? interceptOnRequestSuccessed(ctx, request, response); resp.getWriter().flush(); boolean keepAlive = HttpHeaders.isKeepAlive(request); if (keepAlive) { // Add 'Content-Length' header only for a keep-alive connection. response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); // Add keep alive header as per: // - // http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } // ? if (req.isAsyncSupported() && req.isAsyncStarted()) { ctx.fireChannelRead(resp); } else { // write response... ChannelFuture future = ctx.channel().writeAndFlush(response); if (!keepAlive) { future.addListener(ChannelFutureListener.CLOSE); } } }
From source file:com.soho.framework.server.netty.http.HttpServletHandler.java
License:Apache License
private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) { String text = "Failure: " + status.toString() + "\r\n"; ByteBuf byteBuf = Unpooled.buffer(); byte[] bytes = null; try {//ww w . ja va2s. c o m bytes = text.getBytes("utf-8"); byteBuf.writeBytes(bytes); } catch (UnsupportedEncodingException e) { } FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, byteBuf); HttpHeaders headers = response.headers(); headers.add(CONTENT_TYPE, "text/plain;charset=utf-8"); headers.add(CACHE_CONTROL, "no-cache"); headers.add(PRAGMA, "No-cache"); headers.add(SERVER, ServerConfig.getServerName()); headers.add(CONTENT_LENGTH, byteBuf.readableBytes()); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }
From source file:com.sohu.jafka.http.HttpServerHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; if (HttpHeaders.is100ContinueExpected(request)) { send100Continue(ctx);/* w w w . ja v a 2 s. com*/ } body = new ByteArrayOutputStream(64); args = new HashMap<String, String>(4); // if (request.getMethod() != HttpMethod.POST) { sendStatusMessage(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED, "POST METHOD REQUIRED"); return; } HttpHeaders headers = request.headers(); String contentType = headers.get("Content-Type"); // ? text or octstream args.put("request_key", headers.get("request_key")); args.put("topic", headers.get("topic")); args.put("partition", headers.get("partition")); } if (msg instanceof HttpContent) { HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.content(); if (content.isReadable()) { //body.write(content.array()); content.readBytes(body, content.readableBytes()); //body.append(content.toString(CharsetUtil.UTF_8)); } if (msg instanceof LastHttpContent) { //process request if (server.handler != null) { server.handler.handle(args, body.toByteArray()); } if (!writeResponse(ctx)) { // If keep-alive is off, close the connection once the content is fully written. ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } body = null; args = null; } } }
From source file:com.springapp.mvc.netty.example.http.file.HttpStaticFileServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception { if (!request.getDecoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST);/*ww w .j a va2 s .c om*/ 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; } // 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); HttpHeaders.setContentLength(response, fileLength); setContentTypeHeader(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 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 (!HttpHeaders.isKeepAlive(request)) { // Close the connection when the whole content is written out. lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.springapp.mvc.netty.example.http.snoop.HttpSnoopServerHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; if (HttpHeaders.is100ContinueExpected(request)) { send100Continue(ctx);// w w w .j a va2 s. c o m } buf.setLength(0); buf.append("WELCOME TO THE WILD WILD WEB SERVER\r\n"); buf.append("===================================\r\n"); buf.append("VERSION: ").append(request.getProtocolVersion()).append("\r\n"); buf.append("HOSTNAME: ").append(HttpHeaders.getHost(request, "unknown")).append("\r\n"); buf.append("REQUEST_URI: ").append(request.getUri()).append("\r\n\r\n"); HttpHeaders headers = request.headers(); if (!headers.isEmpty()) { for (Entry<String, String> h : headers) { String key = h.getKey(); String value = h.getValue(); buf.append("HEADER: ").append(key).append(" = ").append(value).append("\r\n"); } buf.append("\r\n"); } QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri()); Map<String, List<String>> params = queryStringDecoder.parameters(); if (!params.isEmpty()) { for (Entry<String, List<String>> p : params.entrySet()) { String key = p.getKey(); List<String> vals = p.getValue(); for (String val : vals) { buf.append("PARAM: ").append(key).append(" = ").append(val).append("\r\n"); } } buf.append("\r\n"); } appendDecoderResult(buf, request); } if (msg instanceof HttpContent) { HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.content(); if (content.isReadable()) { buf.append("CONTENT: "); buf.append(content.toString(CharsetUtil.UTF_8)); buf.append("\r\n"); appendDecoderResult(buf, request); } if (msg instanceof LastHttpContent) { buf.append("END OF CONTENT\r\n"); LastHttpContent trailer = (LastHttpContent) msg; if (!trailer.trailingHeaders().isEmpty()) { buf.append("\r\n"); for (String name : trailer.trailingHeaders().names()) { for (String value : trailer.trailingHeaders().getAll(name)) { buf.append("TRAILING HEADER: "); buf.append(name).append(" = ").append(value).append("\r\n"); } } buf.append("\r\n"); } if (!writeResponse(trailer, ctx)) { // If keep-alive is off, close the connection once the content is fully written. ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } } } }
From source file:com.springapp.mvc.netty.example.spdy.server.SpdyServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; if (is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); }// w w w. j a v a 2 s. c om boolean keepAlive = isKeepAlive(req); ByteBuf content = Unpooled.copiedBuffer("Hello World " + new Date(), CharsetUtil.UTF_8); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, content); response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8"); response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(CONNECTION, Values.KEEP_ALIVE); ctx.write(response); } } }