List of usage examples for io.netty.channel ChannelFuture addListener
@Override ChannelFuture addListener(GenericFutureListener<? extends Future<? super Void>> listener);
From source file:com.barchart.http.server.PooledServerResponse.java
License:BSD License
@Override public ChannelFuture finish() throws IOException { checkFinished();/*from w w w. ja v a 2s. co m*/ ChannelFuture writeFuture = null; // Handlers might call finish() on a cancelled/closed // channel, don't cause unnecessary pipeline exceptions if (context.channel().isOpen()) { if (isChunkedEncoding()) { if (!started) { log.debug("Warning, empty response"); startResponse(); } writeFuture = context.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); // MJS: TBD close the channel here // context.channel().close(); } else { writeFuture = startResponse(); } } close(); if (writeFuture != null && !HttpHeaders.isKeepAlive(request)) { writeFuture.addListener(ChannelFutureListener.CLOSE); } // Record to access log logger.access(request, this, System.currentTimeMillis() - requestTime); // Keep alive, need to tell channel handler it can return us to the pool if (HttpHeaders.isKeepAlive(request)) { channelHandler.freeHandlers(context); } return writeFuture; }
From source file:com.barchart.netty.client.base.ConnectableBase.java
License:BSD License
@Override public Observable<T> connect() { if (transport == null) { throw new IllegalArgumentException("Transport cannot be null"); }/* w w w.j ava 2 s .c om*/ if (channelInitializer == null) { throw new IllegalArgumentException("Channel initializer cannot be null"); } log.debug("Client connecting to " + transport.address().toString()); changeState(Connectable.State.CONNECTING); final ChannelFuture future = bootstrap() // .group(group) // .handler(new ClientPipelineInitializer()) // .connect(); channel = future.channel(); final ReplaySubject<T> connectObs = ReplaySubject.create(); future.addListener(new ChannelFutureListener() { @SuppressWarnings("unchecked") @Override public void operationComplete(final ChannelFuture future) throws Exception { if (!future.isSuccess()) { changeState(Connectable.State.CONNECT_FAIL); connectObs.onError(future.cause()); } else { connectObs.onNext((T) ConnectableBase.this); connectObs.onCompleted(); } } }); return connectObs; }
From source file:com.barchart.netty.server.http.pipeline.PooledHttpServerResponse.java
License:BSD License
@Override public ChannelFuture finish() throws IOException { checkFinished();/* w w w. j a va2s. co m*/ ChannelFuture writeFuture = null; // Handlers might call finish() on a cancelled/closed // channel, don't cause unnecessary pipeline exceptions if (context.channel().isOpen()) { if (chunkSize > 0) { if (!started) { log.debug("Warning, empty response"); startResponse(); } out.flush(); writeFuture = context.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); } else { writeFuture = startResponse(); } } close(); if (writeFuture != null && !HttpHeaders.isKeepAlive(request)) { writeFuture.addListener(ChannelFutureListener.CLOSE); } // Keep alive, need to tell channel handler it can return us to the pool if (HttpHeaders.isKeepAlive(request)) { keepaliveHelper.requestComplete(context); } return writeFuture; }
From source file:com.barchart.netty.server.stream.MulticastTransceiver.java
License:BSD License
/** * Join the multicast group address using the network interface associated * with the given address./*from ww w . j av a2s.c om*/ */ @Override public ChannelFuture listen(final SocketAddress address) { if (pipelineInit == null) { throw new IllegalStateException("No pipeline initializer has been provided, server would do nothing"); } // Kinda hacky, need to override bootstrap params based on passed // address final ChannelFuture future = bootstrap() // .option(ChannelOption.IP_MULTICAST_IF, bindInterface((InetSocketAddress) address)) // .localAddress(multicast.getPort()) // .remoteAddress(multicast) // .bind(); future.addListener(new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (future.isSuccess()) { final NioDatagramChannel channel = (NioDatagramChannel) future.channel(); channel.joinGroup(multicast, channel.config().getOption(ChannelOption.IP_MULTICAST_IF)); } } }); serverChannels.add(future.channel()); return future; }
From source file:com.base.research.socket.netty.ServerHandler.java
License:Apache License
@Override public void channelRead(final ChannelHandlerContext ctx, Object msg) { // (2) Date date = (Date) msg; System.out.println("handle:" + date); ctx.fireChannelRead(date);//from www. j a v a2 s. com // ? long timeMillis = System.currentTimeMillis(); final ChannelFuture f = ctx.write(timeMillis); ctx.flush(); System.out.println("flush"); // final ChannelFuture f = ctx.writeAndFlush(time); // (3) f.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { assert f == future; ctx.close(); System.out.println("close-----------------"); } }); }
From source file:com.basho.riak.client.core.RiakNode.java
License:Apache License
/** * Submits the operation to be executed on this node. * * @param operation The operation to perform * @return {@code true} if this operation was accepted, {@code false} if there * were no available connections. * @throws IllegalStateException if this node is not in the {@code RUNNING} or {@code HEALTH_CHECKING} state * @throws IllegalArgumentException if the protocol required for the operation is not supported by this node *///from ww w. j a v a 2 s . co m public boolean execute(FutureOperation operation) { stateCheck(State.RUNNING, State.HEALTH_CHECKING); operation.setLastNode(this); Channel channel = getConnection(); if (channel != null) { inProgressMap.put(channel, operation); ChannelFuture writeFuture = channel.writeAndFlush(operation); writeFuture.addListener(writeListener); logger.debug("Operation being executed on RiakNode {}:{}", remoteAddress, port); return true; } else { logger.debug("Operation not being executed Riaknode {}:{}; no connections available", remoteAddress, port); return false; } }
From source file:com.bloom.zerofs.rest.HealthCheckHandler.java
License:Open Source License
@Override public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception { logger.trace("Reading on channel {}", ctx.channel()); boolean forwardObj = false; if (obj instanceof HttpRequest) { if (request == null && ((HttpRequest) obj).getUri().equals(healthCheckUri)) { nettyMetrics.healthCheckRequestRate.mark(); startTimeInMs = System.currentTimeMillis(); logger.trace("Handling health check request while in state " + restServerState.isServiceUp()); request = (HttpRequest) obj; if (restServerState.isServiceUp()) { response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(GOOD)); HttpHeaders.setKeepAlive(response, HttpHeaders.isKeepAlive(request)); HttpHeaders.setContentLength(response, GOOD.length); } else { response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.SERVICE_UNAVAILABLE, Unpooled.wrappedBuffer(BAD)); HttpHeaders.setKeepAlive(response, false); HttpHeaders.setContentLength(response, BAD.length); }/*w w w.j av a2 s .c o m*/ nettyMetrics.healthCheckRequestProcessingTimeInMs .update(System.currentTimeMillis() - startTimeInMs); } else { // Rest server could be down even if not for health check request. We intentionally don't take any action in this // handler for such cases and leave it to the downstream handlers to handle it forwardObj = true; } } if (obj instanceof LastHttpContent) { if (response != null) { // response was created when we received the request with health check uri ChannelFuture future = ctx.writeAndFlush(response); if (!HttpHeaders.isKeepAlive(response)) { future.addListener(ChannelFutureListener.CLOSE); } request = null; response = null; nettyMetrics.healthCheckRequestRoundTripTimeInMs.update(System.currentTimeMillis() - startTimeInMs); } else { // request was not for health check uri forwardObj = true; } } else if (request == null) { // http Content which is not LastHttpContent is not intended for this handler forwardObj = true; } if (forwardObj) { super.channelRead(ctx, obj); } else { ReferenceCountUtil.release(obj); } }
From source file:com.bt.netty.TelnetServerHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, String request) throws Exception { // Generate and write a response. String response;/*from w w w .j av a2 s . c o 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:com.bunjlabs.fuga.network.netty.NettyHttpServerHandler.java
License:Apache License
private void writeResponse(ChannelHandlerContext ctx, Request request, Response response) { HttpResponse httpresponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(response.status())); httpresponse.headers().set(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED); httpresponse.headers().set(HttpHeaderNames.CONTENT_TYPE, response.contentType()); // Disable cache by default httpresponse.headers().set(HttpHeaderNames.CACHE_CONTROL, "no-cache, no-store, must-revalidate, max-age=0"); httpresponse.headers().set(HttpHeaderNames.PRAGMA, "no-cache"); httpresponse.headers().set(HttpHeaderNames.EXPIRES, "0"); response.headers().entrySet().stream().forEach((e) -> httpresponse.headers().set(e.getKey(), e.getValue())); httpresponse.headers().set(HttpHeaderNames.SERVER, "Fuga Netty Web Server/" + serverVersion); // Set cookies httpresponse.headers().set(HttpHeaderNames.SET_COOKIE, ServerCookieEncoder.STRICT.encode(NettyCookieConverter.convertListToNetty(response.cookies()))); if (response.length() >= 0) { httpresponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.length()); }/*from ww w . j a v a 2 s. c o m*/ if (HttpUtil.isKeepAlive(httprequest)) { httpresponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); } else { httpresponse.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE); } ctx.write(httpresponse); if (response.stream() != null) { ctx.write(new HttpChunkedInput(new ChunkedStream(response.stream()))); } LastHttpContent fs = new DefaultLastHttpContent(); ChannelFuture sendContentFuture = ctx.writeAndFlush(fs); if (!HttpUtil.isKeepAlive(httprequest)) { sendContentFuture.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.caricah.iotracah.server.netty.channelgroup.IotChannelGroupFuture.java
License:Apache License
/** * Creates a new instance./*from w w w. j a v a 2 s.c o m*/ */ IotChannelGroupFuture(ChannelGroup group, Collection<ChannelFuture> futures, EventExecutor executor) { super(executor); if (group == null) { throw new NullPointerException("group"); } if (futures == null) { throw new NullPointerException("futures"); } this.group = group; Map<Channel, ChannelFuture> futureMap = new LinkedHashMap<Channel, ChannelFuture>(); for (ChannelFuture f : futures) { futureMap.put(f.channel(), f); } this.futures = Collections.unmodifiableMap(futureMap); for (ChannelFuture f : this.futures.values()) { f.addListener(childListener); } // Done on arrival? if (this.futures.isEmpty()) { setSuccess0(); } }