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.rackspacecloud.blueflood.outputs.handlers.HttpMetricDataQueryServer.java
License:Apache License
private void setupPipeline(SocketChannel channel, RouteMatcher router) { final ChannelPipeline pipeline = channel.pipeline(); pipeline.addLast("encoder", new HttpResponseEncoder()); pipeline.addLast("decoder", new HttpRequestDecoder() { @Override/*w w w.ja va 2 s. c o m*/ public void exceptionCaught(ChannelHandlerContext ctx, Throwable thr) throws Exception { try { if (ctx.channel().isWritable()) { log.debug("request decoder error " + thr.getCause().toString() + " on channel " + ctx.channel().toString()); ctx.channel().write( new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST)) .addListener(ChannelFutureListener.CLOSE); } else { log.debug("channel " + ctx.channel().toString() + " is no longer writeable, not sending 400 response back to client"); } } catch (Exception ex) { // If we are getting exception trying to write, // don't propagate to caller. It may cause this // method to be called again and will produce // stack overflow. So just log it here. log.debug("Can't write to channel " + ctx.channel().toString(), ex); } } }); pipeline.addLast("chunkaggregator", new HttpObjectAggregator(httpMaxContentLength)); pipeline.addLast("handler", new QueryStringDecoderAndRouter(router)); }
From source file:com.rs3e.network.session.impl.UpdateSession.java
License:Open Source License
@Override public void message(Object obj) { if (handshakeComplete) { if (obj instanceof FileRequest) { FileRequest request = (FileRequest) obj; synchronized (fileQueue) { if (request.isPriority()) { fileQueue.addFirst(request); } else { fileQueue.addLast(request); }/* w ww . j a v a 2s . c o m*/ if (idle) { service.addPendingSession(this); idle = false; } } } else if (obj instanceof UpdateEncryptionMessage) { UpdateEncryptionMessage encryption = (UpdateEncryptionMessage) obj; XorEncoder encoder = channel.pipeline().get(XorEncoder.class); encoder.setKey(encryption.getKey()); } } else { UpdateVersionMessage version = (UpdateVersionMessage) obj; int status; if (version.getVersion() == Constants.ServerRevision) { status = UpdateStatusMessage.STATUS_OK; } else { status = UpdateStatusMessage.STATUS_OUT_OF_DATE; } ChannelFuture future = channel.write(new UpdateStatusMessage(status)); if (status == UpdateStatusMessage.STATUS_OK) { /* * the client won't re-connect so an ondemand session cannot * time out */ channel.pipeline().remove(ReadTimeoutHandler.class); handshakeComplete = true; } else { future.addListener(ChannelFutureListener.CLOSE); } } }
From source file:com.rs3e.network.session.impl.WorldListSession.java
License:Open Source License
@Override public void message(Object obj) { World[] worlds = { new World(1, World.FLAG_MEMBERS | World.FLAG_QUICK_CHAT, 0, "RS3Emu", "127.0.0.1"), new World(2, World.FLAG_MEMBERS | World.FLAG_QUICK_CHAT, 0, "Ieldor BETA", "127.0.0.1") }; int[] players = { 0 }; channel.write(new WorldListMessage(0xDEADBEEF, COUNTRIES, worlds, players)) .addListener(ChannelFutureListener.CLOSE); }
From source file:com.sangupta.swift.netty.http.HttpStaticFileServerHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext context, FullHttpRequest request) throws Exception { if (!request.getDecoderResult().isSuccess()) { NettyUtils.sendError(context, HttpResponseStatus.BAD_REQUEST); return;// w w w. java 2 s.com } if (request.getMethod() != HttpMethod.GET) { NettyUtils.sendError(context, HttpResponseStatus.METHOD_NOT_ALLOWED); return; } 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); } else { 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); } // 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.sangupta.swift.netty.NettyUtils.java
License:Apache License
public static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) { FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, Unpooled.copiedBuffer("Failure: " + status + "\r\n", CharsetUtil.UTF_8)); response.headers().set(HttpHeaders.Names.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:com.sangupta.swift.netty.NettyUtils.java
License:Apache License
public static void sendRedirect(ChannelHandlerContext ctx, String newUri) { FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FOUND); response.headers().set(HttpHeaders.Names.LOCATION, newUri); // Close the connection as soon as the error message is sent. ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }
From source file:com.sangupta.swift.netty.NettyUtils.java
License:Apache License
/** * When file timestamp is the same as what the browser is sending up, send a * "304 Not Modified"// w ww. j av a 2 s. c o m * * @param ctx * Context */ public static void sendNotModified(ChannelHandlerContext ctx) { FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_MODIFIED); setDateHeader(response); // Close the connection as soon as the error message is sent. ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }
From source file:com.sangupta.swift.netty.NettyUtils.java
License:Apache License
public static void sendListing(ChannelHandlerContext ctx, File dir) { FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); response.headers().set(HttpHeaders.Names.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("Listing of: "); buf.append(dirPath);//from ww w. j av a2 s .co m buf.append("</title></head><body>\r\n"); buf.append("<h3>Listing of: "); buf.append(dirPath); 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(); // Close the connection as soon as the error message is sent. ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }
From source file:com.sangupta.swift.netty.NettyUtils.java
License:Apache License
public static void sendListing(final ChannelHandlerContext ctx, final File dir, final String spdyRequest) { FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/html; charset=UTF-8"); if (AssertUtils.isNotEmpty(spdyRequest)) { response.headers().set(SPDY_STREAM_ID, spdyRequest); response.headers().set(SPDY_STREAM_PRIO, 0); }//from w ww . j av a 2 s . c om StringBuilder buf = new StringBuilder(); String dirPath = dir.getPath(); buf.append("<!DOCTYPE html>\r\n"); buf.append("<html><head><title>"); buf.append("Listing of: "); buf.append(dirPath); buf.append("</title></head><body>\r\n"); buf.append("<h3>Listing of: "); buf.append(dirPath); 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(); // Close the connection as soon as the error message is sent. ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }
From source file:com.sangupta.swift.netty.proxy.ProxyFrontendHandler.java
License:Apache License
/** * Closes the specified channel after all queued write requests are flushed. *//*w w w .j av a2 s. c om*/ static void closeOnFlush(Channel channel) { if (channel.isActive()) { channel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } }