List of usage examples for io.netty.channel ChannelFuture channel
Channel channel();
From source file:com.couchbase.client.core.endpoint.AbstractEndpoint.java
License:Apache License
/** * Helper method to perform the actual connect and reconnect. * * @param observable the {@link Subject} which is eventually notified if the connect process * succeeded or failed. * @param bootstrapping true if connection attempt is for bootstrapping phase and therefore be less forgiving of * some errors (like socket connect timeout). *///from w ww . j a v a2 s . c o m protected void doConnect(final Subject<LifecycleState, LifecycleState> observable, final boolean bootstrapping) { bootstrap.connect().addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (state() == LifecycleState.DISCONNECTING || state() == LifecycleState.DISCONNECTED) { LOGGER.debug(logIdent(channel, AbstractEndpoint.this) + "Endpoint connect completed, " + "but got instructed to disconnect in the meantime."); transitionState(LifecycleState.DISCONNECTED); channel = null; } else { if (future.isSuccess()) { channel = future.channel(); LOGGER.debug(logIdent(channel, AbstractEndpoint.this) + "Connected Endpoint."); transitionState(LifecycleState.CONNECTED); } else { if (future.cause() instanceof AuthenticationException) { LOGGER.warn(logIdent(channel, AbstractEndpoint.this) + "Authentication Failure."); transitionState(LifecycleState.DISCONNECTED); observable.onError(future.cause()); } else if (future.cause() instanceof SSLHandshakeException) { LOGGER.warn(logIdent(channel, AbstractEndpoint.this) + "SSL Handshake Failure during connect."); transitionState(LifecycleState.DISCONNECTED); observable.onError(future.cause()); } else if (future.cause() instanceof ClosedChannelException) { LOGGER.warn(logIdent(channel, AbstractEndpoint.this) + "Generic Failure."); transitionState(LifecycleState.DISCONNECTED); LOGGER.warn(future.cause().getMessage()); observable.onError(future.cause()); } else if (future.cause() instanceof ConnectTimeoutException) { LOGGER.warn(logIdent(channel, AbstractEndpoint.this) + "Socket connect took longer than specified timeout."); transitionState(LifecycleState.DISCONNECTED); observable.onError(future.cause()); } else if (isTransient) { transitionState(LifecycleState.DISCONNECTED); LOGGER.warn(future.cause().getMessage()); observable.onError(future.cause()); } if (!disconnected && !bootstrapping && !isTransient) { long delay = env.reconnectDelay().calculate(reconnectAttempt++); TimeUnit delayUnit = env.reconnectDelay().unit(); LOGGER.warn(logIdent(channel, AbstractEndpoint.this) + "Could not connect to endpoint, retrying with delay " + delay + " " + delayUnit + ": ", future.cause()); if (responseBuffer != null) { responseBuffer.publishEvent(ResponseHandler.RESPONSE_TRANSLATOR, SignalConfigReload.INSTANCE, null); } transitionState(LifecycleState.CONNECTING); future.channel().eventLoop().schedule(new Runnable() { @Override public void run() { // Make sure to avoid a race condition where the reconnect could override // the disconnect phase. If this happens, explicitly break the retry loop // and re-run the disconnect phase to make sure all is properly freed. if (!disconnected) { doConnect(observable, bootstrapping); } else { LOGGER.debug( "{}Explicitly breaking retry loop because already disconnected.", logIdent(channel, AbstractEndpoint.this)); disconnect(); } } }, delay, delayUnit); } else { LOGGER.debug("{}Not retrying because already disconnected.", logIdent(channel, AbstractEndpoint.this)); } } } observable.onNext(state()); observable.onCompleted(); } }); }
From source file:com.couchbase.client.core.io.endpoint.AbstractEndpoint.java
License:Open Source License
@Override public Promise<EndpointState> connect() { if (state == EndpointState.CONNECTED || state == EndpointState.CONNECTING) { return Promises.success(state).get(); }//from ww w.java2 s. c o m if (state != EndpointState.RECONNECTING) { transitionState(EndpointState.CONNECTING); } final Deferred<EndpointState, Promise<EndpointState>> deferred = Promises.defer(env, defaultPromiseEnv); connectionBootstrap.connect().addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (future.isSuccess()) { channel = future.channel(); transitionState(EndpointState.CONNECTED); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Successfully connected Endpoint to: " + channel.remoteAddress()); } } else { channel = null; transitionState(EndpointState.RECONNECTING); long nextReconnectDelay = nextReconnectDelay(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Could not connect to Endpoint, retrying with delay: " + nextReconnectDelay, future.cause()); } future.channel().eventLoop().schedule(new Runnable() { @Override public void run() { if (shouldRetry) { connect(); } } }, nextReconnectDelay, TimeUnit.MILLISECONDS); } deferred.accept(state); } }); addRetryListener(); return deferred.compose(); }
From source file:com.couchbase.client.QueryConnection.java
License:Open Source License
public QueryConnection(List<String> nodes, CouchbaseConnectionFactory cf) { connectionFactory = cf;// w ww . j a v a 2 s . c om Class<? extends SocketChannel> channel = NioSocketChannel.class; Bootstrap bootstrap = new Bootstrap().group(group).channel(channel).handler(new QueryInitializer()); List<ChannelFuture> connectFutures = new ArrayList<ChannelFuture>(); for (String node : nodes) { connectFutures.add(bootstrap.connect(node, QUERY_PORT)); } long startTime = System.nanoTime(); long connectTimeout = TimeUnit.MILLISECONDS.toNanos(CONNECT_TIMEOUT); while (connectFutures.size() > 0 && System.nanoTime() - startTime <= connectTimeout) { Iterator<ChannelFuture> iterator = connectFutures.iterator(); while (iterator.hasNext()) { ChannelFuture connectFuture = iterator.next(); if (!connectFuture.isDone()) { continue; } if (connectFuture.isSuccess()) { connectedChannels.add(connectFuture.channel()); } else { getLogger().error("Could not connect to Query node, skipping: " + connectFuture.cause()); } iterator.remove(); } } if (connectedChannels.size() == 0) { throw new BootstrapException("Could not connect to at least one io node, stopping bootstrap."); } }
From source file:com.ctrip.xpipe.redis.console.health.netty.EchoClient.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL.git final SslContext sslCtx; if (SSL) {/*from w w w . ja v a2s .c om*/ sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build(); } else { sslCtx = null; } // Configure the client. EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); if (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT)); } // p.addLast(new LoggingHandler(LogLevel.INFO)); p.addLast(new EchoClientHandler()); } }); // Start the client. ChannelFuture f = b.connect(HOST, PORT); Channel c = f.channel(); while (true) { ByteBuf buf = Unpooled.buffer(8); buf.writeLong(System.nanoTime()); c.writeAndFlush(buf); Thread.sleep(1000); } } finally { // Shut down the event loop to terminate all threads. group.shutdownGracefully(); } }
From source file:com.ctrip.xpipe.redis.console.health.netty.EchoServer.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) {//from w w w. j av a 2s.c om SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); } else { sslCtx = null; } // Configure the server. EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 100).option(ChannelOption.TCP_NODELAY, true) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); if (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc())); } //p.addLast(new LoggingHandler(LogLevel.INFO)); p.addLast(new EchoServerHandler()); } }); // Start the server. ChannelFuture f = b.bind(PORT).sync(); // Wait until the server socket is closed. f.channel().closeFuture().sync(); } finally { // Shut down all event loops to terminate all threads. bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:com.datastax.driver.core.Connection.java
License:Apache License
public ListenableFuture<Void> initAsync() { if (factory.isShutdown) return Futures .immediateFailedFuture(new ConnectionException(address, "Connection factory is shut down")); ProtocolVersion protocolVersion = factory.protocolVersion == null ? ProtocolVersion.NEWEST_SUPPORTED : factory.protocolVersion;//from w ww. ja va 2s.co m final SettableFuture<Void> channelReadyFuture = SettableFuture.create(); try { Bootstrap bootstrap = factory.newBootstrap(); ProtocolOptions protocolOptions = factory.configuration.getProtocolOptions(); bootstrap.handler(new Initializer(this, protocolVersion, protocolOptions.getCompression().compressor(), protocolOptions.getSSLOptions(), factory.configuration.getPoolingOptions().getHeartbeatIntervalSeconds(), factory.configuration.getNettyOptions())); ChannelFuture future = bootstrap.connect(address); writer.incrementAndGet(); future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { writer.decrementAndGet(); channel = future.channel(); if (isClosed()) { channel.close().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { channelReadyFuture.setException(new TransportException(Connection.this.address, "Connection closed during initialization.")); } }); } else { Connection.this.factory.allChannels.add(channel); if (!future.isSuccess()) { if (logger.isDebugEnabled()) logger.debug(String.format("%s Error connecting to %s%s", Connection.this, Connection.this.address, extractMessage(future.cause()))); channelReadyFuture.setException(new TransportException(Connection.this.address, "Cannot connect", future.cause())); } else { logger.debug("{} Connection established, initializing transport", Connection.this); channel.closeFuture().addListener(new ChannelCloseListener()); channelReadyFuture.set(null); } } } }); } catch (RuntimeException e) { closeAsync().force(); throw e; } Executor initExecutor = factory.manager.configuration.getPoolingOptions().getInitializationExecutor(); ListenableFuture<Void> initializeTransportFuture = Futures.transformAsync(channelReadyFuture, onChannelReady(protocolVersion, initExecutor), initExecutor); // Fallback on initializeTransportFuture so we can properly propagate specific exceptions. ListenableFuture<Void> initFuture = Futures.catchingAsync(initializeTransportFuture, Throwable.class, new AsyncFunction<Throwable, Void>() { @Override public ListenableFuture<Void> apply(@Nullable Throwable t) throws Exception { SettableFuture<Void> future = SettableFuture.create(); // Make sure the connection gets properly closed. if (t instanceof ClusterNameMismatchException || t instanceof UnsupportedProtocolVersionException) { // Just propagate closeAsync().force(); future.setException(t); } else { // Defunct to ensure that the error will be signaled (marking the host down) Exception e = (t instanceof ConnectionException || t instanceof DriverException || t instanceof InterruptedException) ? (Exception) t : new ConnectionException(Connection.this.address, String.format( "Unexpected error during transport initialization (%s)", t), t); future.setException(defunct(e)); } return future; } }, initExecutor); // Ensure the connection gets closed if the caller cancels the returned future. Futures.addCallback(initFuture, new MoreFutures.FailureCallback<Void>() { @Override public void onFailure(Throwable t) { if (!isClosed()) { closeAsync().force(); } } }, initExecutor); return initFuture; }
From source file:com.demo.netty.echo.EchoServer.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) {/*from w ww . ja va 2 s . com*/ SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); } else { sslCtx = null; } //EventLoopGroup is abstraction of Notification and Thread loop EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) // .channel(NioServerSocketChannel.class) // .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); if (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc())); } //p.addLast(new LoggingHandler(LogLevel.INFO)); p.addLast(new EchoServerHandler()); } }); // Start the server. ChannelFuture f = b.bind(PORT).sync(); // Wait until the server socket is closed. f.channel().closeFuture().sync(); } finally { // Shut down all event loops to terminate all threads. bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:com.dianping.cat.status.StatusUpdateTask.java
License:Open Source License
private void buildExtenstion(StatusInfo status) { StatusExtensionRegister res = StatusExtensionRegister.getInstance(); List<StatusExtension> extensions = res.getStatusExtension(); for (StatusExtension extension : extensions) { Transaction t = Cat.newTransaction("System", "StatusExtension-" + extension.getId()); try {//w w w . jav a 2 s . c o m Map<String, String> properties = extension.getProperties(); if (properties.size() > 0) { String id = extension.getId(); String des = extension.getDescription(); Extension item = status.findOrCreateExtension(id).setDescription(des); for (Entry<String, String> entry : properties.entrySet()) { final String key = entry.getKey(); final String value = entry.getValue(); try { double doubleValue = Double.parseDouble(value); if (value.equalsIgnoreCase("NaN")) { doubleValue = 0; } item.findOrCreateExtensionDetail(key).setValue(doubleValue); } catch (Exception e) { status.getCustomInfos().put(key, new CustomInfo().setKey(key).setValue(value)); } } } t.setSuccessStatus(); } catch (Exception e) { LOGGER.error(e.getMessage(), e); t.setStatus(e); } finally { t.complete(); } } ChannelFuture future; if (null != (future = channelManager.channel())) { String localAddress = future.channel().localAddress().toString(); status.getCustomInfos().put("localAddress", new CustomInfo().setKey("localAddress").setValue(localAddress)); status.getCustomInfos().put("env", new CustomInfo().setKey("env").setValue(ApplicationEnvironment.ENVIRONMENT)); } }
From source file:com.digitalpetri.modbus.master.ModbusTcpMaster.java
License:Apache License
public static CompletableFuture<Channel> bootstrap(ModbusTcpMaster master, ModbusTcpMasterConfig config) { CompletableFuture<Channel> future = new CompletableFuture<>(); Bootstrap bootstrap = new Bootstrap(); config.getBootstrapConsumer().accept(bootstrap); bootstrap.group(config.getEventLoop()).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) config.getTimeout().toMillis()) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .handler(new ChannelInitializer<SocketChannel>() { @Override/*from w ww . ja v a2 s . com*/ protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast( new ModbusTcpCodec(new ModbusRequestEncoder(), new ModbusResponseDecoder())); ch.pipeline().addLast(new ModbusTcpMasterHandler(master)); } }).connect(config.getAddress(), config.getPort()).addListener((ChannelFuture f) -> { if (f.isSuccess()) { future.complete(f.channel()); } else { future.completeExceptionally(f.cause()); } }); return future; }
From source file:com.digitalpetri.modbus.slave.ModbusTcpSlave.java
License:Apache License
public CompletableFuture<ModbusTcpSlave> bind(String host, int port) { CompletableFuture<ModbusTcpSlave> bindFuture = new CompletableFuture<>(); ServerBootstrap bootstrap = new ServerBootstrap(); ChannelInitializer<SocketChannel> initializer = new ChannelInitializer<SocketChannel>() { @Override//from w ww . java 2 s . c o m protected void initChannel(SocketChannel channel) throws Exception { channelCounter.inc(); logger.info("channel initialized: {}", channel); channel.pipeline().addLast(new LoggingHandler(LogLevel.TRACE)); channel.pipeline() .addLast(new ModbusTcpCodec(new ModbusResponseEncoder(), new ModbusRequestDecoder())); channel.pipeline().addLast(new ModbusTcpSlaveHandler(ModbusTcpSlave.this)); channel.closeFuture().addListener(future -> channelCounter.dec()); } }; config.getBootstrapConsumer().accept(bootstrap); bootstrap.group(config.getEventLoop()).channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.DEBUG)).childHandler(initializer) .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); bootstrap.bind(host, port).addListener((ChannelFuture future) -> { if (future.isSuccess()) { Channel channel = future.channel(); serverChannels.put(channel.localAddress(), channel); bindFuture.complete(ModbusTcpSlave.this); } else { bindFuture.completeExceptionally(future.cause()); } }); return bindFuture; }