List of usage examples for io.netty.channel ChannelFuture addListener
@Override ChannelFuture addListener(GenericFutureListener<? extends Future<? super Void>> listener);
From source file:io.aos.netty5.telnet.TelnetServerHandler.java
License:Apache License
@Override public void messageReceived(ChannelHandlerContext ctx, String request) { // Generate and write a response. String response;//w w w . j a v a 2 s .co m boolean close = false; if (request.isEmpty()) { response = "Please type something.\r\n"; } else if ("bye".equals(request.toLowerCase())) { response = "Have a good day!\r\n"; close = true; } else { response = "Did you say '" + request + "'?\r\n"; } // We do not need to write a ChannelBuffer here. // We know the encoder inserted at TelnetPipelineFactory will do the conversion. ChannelFuture future = ctx.write(response); // Close the connection after sending 'Have a good day!' // if the client has sent 'bye'. if (close) { future.addListener(ChannelFutureListener.CLOSE); } }
From source file:io.apigee.trireme.container.netty.UpgradedSocketHandler.java
License:Open Source License
@Override public void shutdownOutput(final IOCompletionHandler<Integer> handler) { log.debug("Shutting down output"); ChannelFuture future = channel.shutdownOutput(); future.addListener(new GenericFutureListener<Future<Void>>() { @Override//w w w. j a v a 2 s .c o m public void operationComplete(Future<Void> voidFuture) { log.debug("Shutdown complete"); handler.ioComplete(0, 0); } }); }
From source file:io.apigee.trireme.container.netty.UpgradedSocketHandler.java
License:Open Source License
public int write(ByteBuffer buf, final IOCompletionHandler<Integer> handler) { final int len = buf.remaining(); ByteBuf nettyBuf = Unpooled.wrappedBuffer(buf); ChannelFuture future = channel.writeAndFlush(nettyBuf); if (log.isDebugEnabled()) { log.debug("Writing {} bytes to the upgraded socket", len); }/* www .j a v a 2 s . com*/ future.addListener(new GenericFutureListener<Future<Void>>() { @Override public void operationComplete(Future<Void> voidFuture) { if (log.isDebugEnabled()) { log.debug("Upgraded socket write complete"); } handler.ioComplete(0, len); } }); return len; }
From source file:io.atomix.catalyst.transport.netty.NettyServer.java
License:Apache License
/** * Starts listening for the given member. *//*w w w . j a v a 2 s .c o m*/ private void listen(Address address, Consumer<Connection> listener, ThreadContext context) { channelGroup = new DefaultChannelGroup("catalyst-acceptor-channels", GlobalEventExecutor.INSTANCE); handler = new ServerHandler(connections, listener, context, transport.properties()); final ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(transport.eventLoopGroup()).channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel channel) throws Exception { ChannelPipeline pipeline = channel.pipeline(); if (transport.properties().sslEnabled()) { pipeline.addFirst( new SslHandler(new NettyTls(transport.properties()).initSslEngine(false))); } pipeline.addLast(FIELD_PREPENDER); pipeline.addLast(new LengthFieldBasedFrameDecoder(transport.properties().maxFrameSize(), 0, 4, 0, 4)); pipeline.addLast(handler); } }).option(ChannelOption.SO_BACKLOG, transport.properties().acceptBacklog()) .option(ChannelOption.TCP_NODELAY, transport.properties().tcpNoDelay()) .option(ChannelOption.SO_REUSEADDR, transport.properties().reuseAddress()) .childOption(ChannelOption.ALLOCATOR, ALLOCATOR) .childOption(ChannelOption.SO_KEEPALIVE, transport.properties().tcpKeepAlive()); if (transport.properties().sendBufferSize() != -1) { bootstrap.childOption(ChannelOption.SO_SNDBUF, transport.properties().sendBufferSize()); } if (transport.properties().receiveBufferSize() != -1) { bootstrap.childOption(ChannelOption.SO_RCVBUF, transport.properties().receiveBufferSize()); } LOGGER.info("Binding to {}", address); ChannelFuture bindFuture = bootstrap.bind(address.socketAddress()); bindFuture.addListener((ChannelFutureListener) channelFuture -> { if (channelFuture.isSuccess()) { listening = true; context.executor().execute(() -> { LOGGER.info("Listening at {}", bindFuture.channel().localAddress()); listenFuture.complete(null); }); } else { context.execute(() -> listenFuture.completeExceptionally(channelFuture.cause())); } }); channelGroup.add(bindFuture.channel()); }
From source file:io.atomix.catalyst.transport.NettyServer.java
License:Apache License
/** * Starts listening for the given member. *///w w w .j ava 2s . com private void listen(Address address, Consumer<Connection> listener, ThreadContext context) { channelGroup = new DefaultChannelGroup("catalyst-acceptor-channels", GlobalEventExecutor.INSTANCE); handler = new ServerHandler(connections, listener, context); final ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(eventLoopGroup) .channel(eventLoopGroup instanceof EpollEventLoopGroup ? EpollServerSocketChannel.class : NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel channel) throws Exception { ChannelPipeline pipeline = channel.pipeline(); pipeline.addLast(FIELD_PREPENDER); pipeline.addLast(new LengthFieldBasedFrameDecoder(1024 * 32, 0, 2, 0, 2)); pipeline.addLast(handler); } }).option(ChannelOption.SO_BACKLOG, 128).option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.SO_REUSEADDR, true).childOption(ChannelOption.ALLOCATOR, ALLOCATOR) .childOption(ChannelOption.SO_KEEPALIVE, true); LOGGER.info("Binding to {}", address); ChannelFuture bindFuture = bootstrap.bind(address.socketAddress()); bindFuture.addListener((ChannelFutureListener) channelFuture -> { if (channelFuture.isSuccess()) { listening = true; context.executor().execute(() -> { LOGGER.info("Listening at {}", bindFuture.channel().localAddress()); listenFuture.complete(null); }); } else { context.execute(() -> listenFuture.completeExceptionally(channelFuture.cause())); } }); channelGroup.add(bindFuture.channel()); }
From source file:io.atomix.cluster.messaging.impl.NettyMessagingService.java
License:Apache License
private CompletableFuture<Channel> openChannel(Address address) { Bootstrap bootstrap = bootstrapClient(address); CompletableFuture<Channel> retFuture = new CompletableFuture<>(); ChannelFuture f = bootstrap.connect(); f.addListener(future -> { if (future.isSuccess()) { retFuture.complete(f.channel()); } else {//ww w. j a v a 2 s .co m retFuture.completeExceptionally(future.cause()); } }); log.debug("Established a new connection to {}", address); return retFuture; }
From source file:io.blobkeeper.server.handler.BaseFileHandler.java
License:Apache License
protected void writeResponse(Channel channel, String result, HttpRequest request) { // Convert the response content to a ChannelBuffer. ByteBuf buf = copiedBuffer(result, CharsetUtil.UTF_8); // Decide whether to close the connection or not. boolean close = HttpHeaders.Values.CLOSE.equalsIgnoreCase(request.headers().get(CONNECTION)) || request.getProtocolVersion().equals(HTTP_1_0) && !KEEP_ALIVE.equalsIgnoreCase(request.headers().get(CONNECTION)); // Build the response object. FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, buf); response.headers().set(CONTENT_TYPE, "application/json; charset=UTF-8"); if (!close) { // There's no need to add 'Content-Length' header // if this is the last response. response.headers().set(CONTENT_LENGTH, buf.readableBytes()); }/* w ww .ja v a 2 s . c o m*/ // Write the response. ChannelFuture future = channel.writeAndFlush(response); // Close the connection after the write operation is done if necessary. if (close) { future.addListener(ChannelFutureListener.CLOSE); } }
From source file:io.blobkeeper.server.handler.FileReaderHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext context, FullHttpRequest request) throws Exception { setContext();/*from www . ja v a 2 s . c om*/ if (request.getMethod() == POST) { context.fireChannelRead(request.copy()); return; } if (request.getMethod() == DELETE) { context.fireChannelRead(request.copy()); return; } addWriterBack(context); if (log.isTraceEnabled()) { log.trace("Request is: {}", request); } if (request.getUri().equals("/favicon.ico")) { sendError(context, HttpResponseStatus.NOT_FOUND, createError(INVALID_REQUEST, "No favorite icon here")); return; } if (!request.getDecoderResult().isSuccess()) { sendError(context, BAD_REQUEST, createError(INVALID_REQUEST, "Strange request given")); return; } if (request.getMethod() != GET) { sendError(context, METHOD_NOT_ALLOWED, createError(INVALID_REQUEST, "Only GET requests are acceptable")); return; } String uri = request.getUri(); final long fileId = getId(uri); final int typeId = getType(uri); if (NOT_FOUND == fileId) { if (tryHandleApiRequest(context, request)) { return; } else { log.error("No id"); sendError(context, BAD_REQUEST, createError(INVALID_REQUEST, "No id")); return; } } if (NOT_FOUND == typeId) { log.error("No type id"); sendError(context, BAD_REQUEST, createError(INVALID_REQUEST, "No type id")); return; } File readerFile = null; IndexElt indexElt; boolean modified; try { log.debug("Id {}", fileId); indexElt = indexService.getById(fileId, typeId); log.debug("Index elt is {}", indexElt); if (null != indexElt) { if (indexElt.isDeleted()) { sendError(context, GONE, createError(DELETED, "File was deleted")); return; } if (indexElt.isAuthRequired()) { String authToken = MetadataParser.getAuthToken(request); if (authToken == null || !indexElt.isAllowed(authToken)) { log.error("You have no permission to see this file {} : token {}", indexElt.getId(), authToken); sendError(context, HttpResponseStatus.FORBIDDEN, createError(ErrorCode.FORBIDDEN, "You have no permission to see this file")); return; } } modified = isModified(indexElt, request); if (modified) { readerFile = fileStorage.getFile(indexElt); } } else { log.error("Index elt not found"); sendError(context, HttpResponseStatus.NOT_FOUND, createError(INVALID_REQUEST, "Index elt not found")); return; } } catch (Exception e) { log.error("Unknown error", e); sendError(context, BAD_GATEWAY, createError(SERVICE_ERROR, "Unknown error")); return; } if (!modified) { sendNotModified(context, indexElt, request); return; } if (null == readerFile) { log.error("Can't find reader file"); sendError(context, BAD_GATEWAY, createError(SERVICE_ERROR, "No reader file")); return; } if (readerFile.getLength() - indexElt.getOffset() < indexElt.getLength()) { String errorMessage = String.format("Reader file length less than index elt %s < %s", readerFile.getLength() - indexElt.getOffset(), indexElt.getLength()); log.error(errorMessage); sendError(context, BAD_GATEWAY, createError(SERVICE_ERROR, errorMessage)); return; } if (FileUtils.isFileEmpty(readerFile, indexElt)) { String errorMessage = String.format("File %s is empty", indexElt); log.error(errorMessage); sendError(context, BAD_GATEWAY, createError(SERVICE_ERROR, errorMessage)); return; } HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); MetadataParser.copyMetadata(indexElt.getHeaders(), response); addCacheHeaders(response, indexElt); setContentLength(response, indexElt.getLength()); if (isKeepAlive(request)) { response.headers().set(CONNECTION, KEEP_ALIVE); } context.write(response); // Write the content. context.write( new UnClosableFileRegion(readerFile.getFileChannel(), indexElt.getOffset(), indexElt.getLength()), context.voidPromise()); // Write the end marker ChannelFuture lastContentFuture = context.writeAndFlush(EMPTY_LAST_CONTENT); if (!isKeepAlive(request)) { lastContentFuture.addListener(CLOSE); } }
From source file:io.blobkeeper.server.handler.FileReaderHandler.java
License:Apache License
private void sendNotModified(ChannelHandlerContext ctx, IndexElt indexElt, HttpRequest request) { HttpResponse response = new DefaultHttpResponse(HTTP_1_1, NOT_MODIFIED); MetadataParser.copyMetadata(indexElt.getHeaders(), response); response.headers().add("Last-Modified", ofInstant(ofEpochMilli(indexElt.getCreated()), ZoneId.of("UTC")).format(RFC1123_FORMATTER)); if (isKeepAlive(request)) { response.headers().set(CONNECTION, KEEP_ALIVE); }//from ww w. j ava2 s .c o m ctx.write(response); // Write the end marker ChannelFuture lastContentFuture = ctx.writeAndFlush(EMPTY_LAST_CONTENT); if (!isKeepAlive(request)) { lastContentFuture.addListener(CLOSE); } }
From source file:io.codis.nedis.NedisClientBuilder.java
License:Apache License
public Future<NedisClientImpl> connect(SocketAddress remoteAddress) { validateGroupConfig();// w ww . j a va2 s . c o m Bootstrap b = new Bootstrap().group(group).channel(channelClass).handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(new RedisResponseDecoder(), new RedisDuplexHandler(TimeUnit.MILLISECONDS.toNanos(timeoutMs))); } }); if (timeoutMs > 0) { b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) Math.min(Integer.MAX_VALUE, timeoutMs)); } ChannelFuture f = b.connect(remoteAddress); final Promise<NedisClientImpl> promise = f.channel().eventLoop().newPromise(); f.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { promise.trySuccess(new NedisClientImpl(future.channel(), pool)); } else { promise.tryFailure(future.cause()); } } }); return promise; }