List of usage examples for io.netty.channel ChannelFutureListener ChannelFutureListener
ChannelFutureListener
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 w w.j a va 2 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.endpoint.AbstractEndpoint.java
License:Apache License
@Override public Observable<LifecycleState> disconnect() { disconnected = true;// www . j a va2 s . c o m if (state() == LifecycleState.DISCONNECTED || state() == LifecycleState.DISCONNECTING) { return Observable.just(state()); } if (state() == LifecycleState.CONNECTING) { transitionState(LifecycleState.DISCONNECTED); return Observable.just(state()); } transitionState(LifecycleState.DISCONNECTING); final AsyncSubject<LifecycleState> observable = AsyncSubject.create(); channel.disconnect().addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (future.isSuccess()) { LOGGER.debug(logIdent(channel, AbstractEndpoint.this) + "Disconnected Endpoint."); } else { LOGGER.warn( logIdent(channel, AbstractEndpoint.this) + "Received an error " + "during disconnect.", future.cause()); } transitionState(LifecycleState.DISCONNECTED); observable.onNext(state()); observable.onCompleted(); channel = null; } }); return observable; }
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(); }/*w w w . j a v a2 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.core.io.endpoint.AbstractEndpoint.java
License:Open Source License
@Override public Promise<EndpointState> disconnect() { shouldRetry = false;//from www .java 2 s . c o m if (state != EndpointState.CONNECTED) { if (state == EndpointState.CONNECTING || state == EndpointState.RECONNECTING) { transitionState(EndpointState.DISCONNECTED); } return Promises.success(state).get(); } transitionState(EndpointState.DISCONNECTING); final Deferred<EndpointState, Promise<EndpointState>> deferred = Promises.defer(env, defaultPromiseEnv); channel.disconnect().addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future) throws Exception { transitionState(EndpointState.DISCONNECTED); deferred.accept(state); if (future.isSuccess()) { LOGGER.debug("Successfully disconnected Endpoint from: " + channel.remoteAddress()); } else { LOGGER.error("Detected error during Endpoint disconnect phase from: " + channel.remoteAddress(), future.cause()); } channel = null; } }); return deferred.compose(); }
From source file:com.couchbase.client.QueryConnection.java
License:Open Source License
public HttpFuture<QueryResult> execute(String query) { Channel chan = connectedChannels.get(0); // always use first channel for now CountDownLatch futureLatch = new CountDownLatch(1); HttpFuture<QueryResult> future = new HttpFuture<QueryResult>(futureLatch, 10000, connectionFactory.getListenerExecutorService()); ChannelFuture channelFuture = chan.writeAndFlush(new QueryEvent<QueryResult>(query, future, futureLatch)); final CountDownLatch latch = new CountDownLatch(1); channelFuture.addListener(new ChannelFutureListener() { @Override/* www . java 2 s .c o m*/ public void operationComplete(ChannelFuture channelFuture) throws Exception { latch.countDown(); } }); try { latch.await(); } catch (InterruptedException e) { getLogger().warn("Got interrupted while writing Query, cancelling operation."); future.cancel(true); } return future; }
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;/*ww w . ja v a 2 s . c om*/ 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.datastax.driver.core.Connection.java
License:Apache License
private ChannelFutureListener writeHandler(final Message.Request request, final ResponseHandler handler) { return new ChannelFutureListener() { @Override/*from w w w . j ava 2s . c o m*/ public void operationComplete(ChannelFuture writeFuture) { writer.decrementAndGet(); if (!writeFuture.isSuccess()) { logger.debug("{}, stream {}, Error writing request {}", Connection.this, request.getStreamId(), request); // Remove this handler from the dispatcher so it don't get notified of the error // twice (we will fail that method already) dispatcher.removeHandler(handler, true); final ConnectionException ce; if (writeFuture.cause() instanceof java.nio.channels.ClosedChannelException) { ce = new TransportException(address, "Error writing: Closed channel"); } else { ce = new TransportException(address, "Error writing", writeFuture.cause()); } final long latency = System.nanoTime() - handler.startTime; // This handler is executed while holding the writeLock of the channel. // defunct might close the pool, which will close all of its connections; closing a connection also // requires its writeLock. // Therefore if multiple connections in the same pool get a write error, they could deadlock; // we run defunct on a separate thread to avoid that. ListeningExecutorService executor = factory.manager.executor; if (!executor.isShutdown()) executor.execute(new Runnable() { @Override public void run() { handler.callback.onException(Connection.this, defunct(ce), latency, handler.retryCount); } }); } else { logger.trace("{}, stream {}, request sent successfully", Connection.this, request.getStreamId()); } } }; }
From source file:com.digisky.stresstest.HttpSnoopClient.java
License:Apache License
public static void main(String[] args) throws Exception { uri = new URI(URL); String scheme = uri.getScheme() == null ? "http" : uri.getScheme(); String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost(); int port = uri.getPort(); if (port == -1) { if ("http".equalsIgnoreCase(scheme)) { port = 80;// ww w .j a v a 2s . c o m } else if ("https".equalsIgnoreCase(scheme)) { port = 443; } } if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) { System.err.println("Only HTTP(S) is supported."); return; } // Configure SSL context if necessary. final boolean ssl = "https".equalsIgnoreCase(scheme); final SslContext sslCtx; if (ssl) { sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE); } else { sslCtx = null; } // Configure the client. EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new HttpSnoopClientInitializer(sslCtx)); // Make the connection attempt. System.out.println("try to connect!"); ChannelFuture f = b.connect(host, port); f.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) { // Perform post-closure operation // ... System.out.println("complete!"); if (!future.isSuccess()) { // You might get a NullPointerException here because the future // might not be completed yet. future.cause().printStackTrace(); } else { System.out.println("ok!!!!"); } } }); } finally { group.shutdownGracefully(); } }
From source file:com.digitalpetri.opcua.stack.server.tcp.SocketServer.java
License:Apache License
public synchronized void bind() throws ExecutionException, InterruptedException { if (channel != null) return; // Already bound CompletableFuture<Void> bindFuture = new CompletableFuture<>(); bootstrap.bind(address).addListener(new ChannelFutureListener() { @Override/* www . j a va 2 s .c o m*/ public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { channel = future.channel(); bindFuture.complete(null); } else { bindFuture.completeExceptionally(future.cause()); } } }); bindFuture.get(); }
From source file:com.dinstone.jrpc.transport.netty5.NettyConnection.java
License:Apache License
@Override public ResultFuture call(Call call) { final int id = ID_GENERATOR.incrementAndGet(); Map<Integer, ResultFuture> futureMap = SessionUtil.getResultFutureMap(ioSession); final ResultFuture resultFuture = new ResultFuture(); futureMap.put(id, resultFuture);//from w w w. j av a 2 s .c o m ChannelFuture wf = ioSession.writeAndFlush(new Request(id, serializeType, call)); wf.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { resultFuture.setResult(new Result(500, "can't write request")); } } }); return resultFuture; }