Example usage for io.netty.util.concurrent Future addListener

List of usage examples for io.netty.util.concurrent Future addListener

Introduction

In this page you can find the example usage for io.netty.util.concurrent Future addListener.

Prototype

Future<V> addListener(GenericFutureListener<? extends Future<? super V>> listener);

Source Link

Document

Adds the specified listener to this future.

Usage

From source file:org.opendaylight.controller.netconf.util.AbstractNetconfSessionNegotiator.java

License:Open Source License

@Override
protected void startNegotiation() throws Exception {
    final Optional<SslHandler> sslHandler = getSslHandler(channel);
    if (sslHandler.isPresent()) {
        Future<Channel> future = sslHandler.get().handshakeFuture();
        future.addListener(new GenericFutureListener<Future<? super Channel>>() {
            @Override//ww w .ja v a  2 s.  co m
            public void operationComplete(Future<? super Channel> future) throws Exception {
                Preconditions.checkState(future.isSuccess(), "Ssl handshake was not successful");
                logger.debug("Ssl handshake complete");
                start();
            }
        });
    } else
        start();
}

From source file:org.opendaylight.netconf.client.TcpClientChannelInitializer.java

License:Open Source License

@Override
public void initialize(final Channel ch, final Promise<NetconfClientSession> promise) {
    final Future<NetconfClientSession> negotiationFuture = promise;

    //We have to add this channel outbound handler to channel pipeline, in order
    //to get notifications from netconf negotiatior. Set connection promise to
    //success only after successful negotiation.
    ch.pipeline().addFirst(new ChannelOutboundHandlerAdapter() {
        ChannelPromise connectPromise;/*from   w  w w.j ava 2  s . c  o  m*/
        GenericFutureListener<Future<NetconfClientSession>> negotiationFutureListener;

        @Override
        public void connect(final ChannelHandlerContext ctx, final SocketAddress remoteAddress,
                final SocketAddress localAddress, final ChannelPromise channelPromise) throws Exception {
            connectPromise = channelPromise;
            ChannelPromise tcpConnectFuture = new DefaultChannelPromise(ch);

            negotiationFutureListener = new GenericFutureListener<Future<NetconfClientSession>>() {
                @Override
                public void operationComplete(final Future<NetconfClientSession> future) throws Exception {
                    if (future.isSuccess()) {
                        connectPromise.setSuccess();
                    }
                }
            };

            tcpConnectFuture.addListener(new GenericFutureListener<Future<? super Void>>() {
                @Override
                public void operationComplete(final Future<? super Void> future) throws Exception {
                    if (future.isSuccess()) {
                        //complete connection promise with netconf negotiation future
                        negotiationFuture.addListener(negotiationFutureListener);
                    } else {
                        connectPromise.setFailure(future.cause());
                    }
                }
            });
            ctx.connect(remoteAddress, localAddress, tcpConnectFuture);
        }

        @Override
        public void disconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) throws Exception {
            // If we have already succeeded and the session was dropped after, we need to fire inactive to notify reconnect logic
            if (connectPromise.isSuccess()) {
                ctx.fireChannelInactive();
            }

            //If connection promise is not already set, it means negotiation failed
            //we must set connection promise to failure
            if (!connectPromise.isDone()) {
                connectPromise.setFailure(new IllegalStateException("Negotiation failed"));
            }

            //Remove listener from negotiation future, we don't want notifications
            //from negotiation anymore
            negotiationFuture.removeListener(negotiationFutureListener);

            super.disconnect(ctx, promise);
            promise.setSuccess();
        }
    });

    super.initialize(ch, promise);
}

From source file:org.opendaylight.openflowjava.protocol.impl.core.TcpChannelInitializer.java

License:Open Source License

@Override
protected void initChannel(final SocketChannel ch) {
    if (ch.remoteAddress() != null) {
        final InetAddress switchAddress = ch.remoteAddress().getAddress();
        final int port = ch.localAddress().getPort();
        final int remotePort = ch.remoteAddress().getPort();
        LOG.debug("Incoming connection from (remote address): {}:{} --> :{}", switchAddress.toString(),
                remotePort, port);//  w  ww  .ja v a2 s .c o m

        if (!getSwitchConnectionHandler().accept(switchAddress)) {
            ch.disconnect();
            LOG.debug("Incoming connection rejected");
            return;
        }
    }
    LOG.debug("Incoming connection accepted - building pipeline");
    allChannels.add(ch);
    ConnectionFacade connectionFacade = null;
    connectionFacade = connectionAdapterFactory.createConnectionFacade(ch, null, useBarrier());
    try {
        LOG.debug("Calling OF plugin: {}", getSwitchConnectionHandler());
        getSwitchConnectionHandler().onSwitchConnected(connectionFacade);
        connectionFacade.checkListeners();
        ch.pipeline().addLast(PipelineHandlers.IDLE_HANDLER.name(),
                new IdleHandler(getSwitchIdleTimeout(), TimeUnit.MILLISECONDS));
        boolean tlsPresent = false;

        // If this channel is configured to support SSL it will only support SSL
        if (getTlsConfiguration() != null) {
            tlsPresent = true;
            final SslContextFactory sslFactory = new SslContextFactory(getTlsConfiguration());
            final SSLEngine engine = sslFactory.getServerContext().createSSLEngine();
            engine.setNeedClientAuth(true);
            engine.setUseClientMode(false);
            List<String> suitesList = getTlsConfiguration().getCipherSuites();
            if (suitesList != null && !suitesList.isEmpty()) {
                LOG.debug("Requested Cipher Suites are: {}", suitesList);
                String[] suites = suitesList.toArray(new String[suitesList.size()]);
                engine.setEnabledCipherSuites(suites);
                LOG.debug("Cipher suites enabled in SSLEngine are: {}",
                        engine.getEnabledCipherSuites().toString());
            }
            final SslHandler ssl = new SslHandler(engine);
            final Future<Channel> handshakeFuture = ssl.handshakeFuture();
            final ConnectionFacade finalConnectionFacade = connectionFacade;
            handshakeFuture.addListener(new GenericFutureListener<Future<? super Channel>>() {
                @Override
                public void operationComplete(final Future<? super Channel> future) throws Exception {
                    finalConnectionFacade.fireConnectionReadyNotification();
                }
            });
            ch.pipeline().addLast(PipelineHandlers.SSL_HANDLER.name(), ssl);
        }
        ch.pipeline().addLast(PipelineHandlers.OF_FRAME_DECODER.name(),
                new OFFrameDecoder(connectionFacade, tlsPresent));
        ch.pipeline().addLast(PipelineHandlers.OF_VERSION_DETECTOR.name(), new OFVersionDetector());
        final OFDecoder ofDecoder = new OFDecoder();
        ofDecoder.setDeserializationFactory(getDeserializationFactory());
        ch.pipeline().addLast(PipelineHandlers.OF_DECODER.name(), ofDecoder);
        final OFEncoder ofEncoder = new OFEncoder();
        ofEncoder.setSerializationFactory(getSerializationFactory());
        ch.pipeline().addLast(PipelineHandlers.OF_ENCODER.name(), ofEncoder);
        ch.pipeline().addLast(PipelineHandlers.DELEGATING_INBOUND_HANDLER.name(),
                new DelegatingInboundHandler(connectionFacade));
        if (!tlsPresent) {
            connectionFacade.fireConnectionReadyNotification();
        }
    } catch (final Exception e) {
        LOG.warn("Failed to initialize channel", e);
        ch.close();
    }
}

From source file:org.opendaylight.protocol.bgp.testtool.BGPPeerBuilder.java

License:Open Source License

private static <T> void addFutureListener(final InetSocketAddress localAddress, final Future<T> future) {
    future.addListener(future1 -> Preconditions.checkArgument(future1.isSuccess(),
            "Unable to start bgp session on %s", localAddress, future1.cause()));
}

From source file:org.redisson.async.ResultOperation.java

License:Apache License

@Override
public void execute(Promise<R> promise, RedisAsyncConnection<Object, V> async) {
    Future<R> future = execute(async);
    future.addListener(new ResultListener<V, R>(promise, async, this));
}

From source file:org.redisson.async.VoidOperation.java

License:Apache License

@Override
public void execute(Promise<Void> promise, RedisAsyncConnection<Object, V> async) {
    Future<R> future = execute(async);
    future.addListener(new VoidListener<V, R>(promise, async, this));
}

From source file:org.redisson.connection.balancer.LoadBalancerManagerImpl.java

License:Apache License

public Future<Void> add(final ClientConnectionsEntry entry) {
    Future<Void> f = entries.add(entry);
    f.addListener(new FutureListener<Void>() {
        @Override//from  w  ww  . j  a v  a 2s . c  o  m
        public void operationComplete(Future<Void> future) throws Exception {
            addr2Entry.put(entry.getClient().getAddr(), entry);
            pubSubEntries.add(entry);
        }
    });
    return f;
}

From source file:org.redisson.connection.ConnectionEntry.java

License:Apache License

public Future<RedisConnection> connect(final MasterSlaveServersConfig config) {
    final Promise<RedisConnection> connectionFuture = client.getBootstrap().group().next().newPromise();
    Future<RedisConnection> future = client.connectAsync();
    future.addListener(new FutureListener<RedisConnection>() {
        @Override/*from  w ww .j a va  2 s.  co  m*/
        public void operationComplete(Future<RedisConnection> future) throws Exception {
            if (!future.isSuccess()) {
                connectionFuture.tryFailure(future.cause());
                return;
            }
            RedisConnection conn = future.getNow();
            log.debug("new connection created: {}", conn);

            FutureConnectionListener<RedisConnection> listener = new FutureConnectionListener<RedisConnection>(
                    connectionFuture, conn);
            connectListener.onConnect(config, nodeType, listener);
            listener.executeCommands();

            addReconnectListener(config, conn);
        }

    });
    return connectionFuture;
}

From source file:org.redisson.connection.ConnectionEntry.java

License:Apache License

public Future<RedisPubSubConnection> connectPubSub(final MasterSlaveServersConfig config) {
    final Promise<RedisPubSubConnection> connectionFuture = client.getBootstrap().group().next().newPromise();
    Future<RedisPubSubConnection> future = client.connectPubSubAsync();
    future.addListener(new FutureListener<RedisPubSubConnection>() {
        @Override//  www.jav a  2 s  .com
        public void operationComplete(Future<RedisPubSubConnection> future) throws Exception {
            if (!future.isSuccess()) {
                connectionFuture.tryFailure(future.cause());
                return;
            }
            RedisPubSubConnection conn = future.getNow();
            log.debug("new pubsub connection created: {}", conn);

            FutureConnectionListener<RedisPubSubConnection> listener = new FutureConnectionListener<RedisPubSubConnection>(
                    connectionFuture, conn);
            connectListener.onConnect(config, nodeType, listener);
            listener.executeCommands();

            addReconnectListener(config, conn);
        }
    });
    return connectionFuture;
}

From source file:org.redisson.connection.DNSMonitor.java

License:Apache License

private void monitorMasters(AtomicInteger counter) {
    for (Entry<RedisURI, InetSocketAddress> entry : masters.entrySet()) {
        Future<InetSocketAddress> resolveFuture = resolver.resolve(
                InetSocketAddress.createUnresolved(entry.getKey().getHost(), entry.getKey().getPort()));
        resolveFuture.addListener(new FutureListener<InetSocketAddress>() {
            @Override/*ww w.  jav a2 s  .  com*/
            public void operationComplete(Future<InetSocketAddress> future) throws Exception {
                if (counter.decrementAndGet() == 0) {
                    monitorDnsChange();
                }

                if (!future.isSuccess()) {
                    log.error("Unable to resolve " + entry.getKey().getHost(), future.cause());
                    return;
                }

                InetSocketAddress currentMasterAddr = entry.getValue();
                InetSocketAddress newMasterAddr = future.getNow();
                if (!newMasterAddr.getAddress().equals(currentMasterAddr.getAddress())) {
                    log.info("Detected DNS change. Master {} has changed ip from {} to {}", entry.getKey(),
                            currentMasterAddr.getAddress().getHostAddress(),
                            newMasterAddr.getAddress().getHostAddress());
                    MasterSlaveEntry masterSlaveEntry = connectionManager.getEntry(currentMasterAddr);
                    if (masterSlaveEntry == null) {
                        if (connectionManager instanceof SingleConnectionManager) {
                            log.error(
                                    "Unable to find master entry for {}. Multiple IP bindings for single hostname supported only in Redisson PRO!",
                                    currentMasterAddr);
                        } else {
                            log.error("Unable to find master entry for {}", currentMasterAddr);
                        }
                        return;
                    }
                    masterSlaveEntry.changeMaster(newMasterAddr, entry.getKey());
                    masters.put(entry.getKey(), newMasterAddr);
                }
            }
        });
    }
}