Example usage for io.netty.util.concurrent GenericFutureListener GenericFutureListener

List of usage examples for io.netty.util.concurrent GenericFutureListener GenericFutureListener

Introduction

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

Prototype

GenericFutureListener

Source Link

Usage

From source file:org.opendaylight.openflowjava.protocol.impl.connection.ConnectionAdapterImpl.java

License:Open Source License

/**
 * @param resultFuture//  ww w  .j  a v  a 2 s .c  om
 * @param failureInfo
 * @param errorSeverity
 * @param errorMessage
 * @param input
 * @param responseClazz
 * @param key of rpcResponse
 * @return
 */
private <IN extends OfHeader, OUT extends OfHeader> SettableFuture<RpcResult<OUT>> handleRpcChannelFutureWithResponse(
        ChannelFuture resultFuture, final String failureInfo, final ErrorSeverity errorSeverity,
        final String errorMessage, final IN input, Class<OUT> responseClazz,
        final SettableFuture<RpcResult<OUT>> rpcResult, final RpcResponseKey key) {
    LOG.debug("handleRpcchanfuture with response");

    resultFuture.addListener(new GenericFutureListener<io.netty.util.concurrent.Future<? super Void>>() {

        @Override
        public void operationComplete(io.netty.util.concurrent.Future<? super Void> future) throws Exception {

            LOG.debug("operation complete");
            Collection<RpcError> errors = Collections.emptyList();
            if (future.cause() != null) {
                LOG.debug("ChannelFuture.cause != null");
                RpcError rpcError = buildRpcError(failureInfo, errorSeverity, errorMessage, future.cause());
                errors = Lists.newArrayList(rpcError);
                rpcResult.set(Rpcs.getRpcResult(future.isSuccess(), (OUT) null, errors));
                responseCache.invalidate(key);
            } else {
                LOG.debug("ChannelFuture.cause == null");
                if (responseCache.getIfPresent(key) == null) {
                    LOG.debug("responcache: key wasn't present");
                }
            }
        }
    });
    return rpcResult;
}

From source file:org.opendaylight.openflowjava.protocol.impl.connection.ConnectionAdapterImpl.java

License:Open Source License

/**
 * @param resultFuture/*from w ww .j  a va 2 s  .  c  om*/
 * @param failureInfo
 * @param errorSeverity
 * @param message
 * @return
 */
private static SettableFuture<Boolean> handleTransportChannelFuture(ChannelFuture resultFuture,
        final String failureInfo, final ErrorSeverity errorSeverity, final String message) {

    final SettableFuture<Boolean> transportResult = SettableFuture.create();

    resultFuture.addListener(new GenericFutureListener<io.netty.util.concurrent.Future<? super Void>>() {

        @Override
        public void operationComplete(io.netty.util.concurrent.Future<? super Void> future) throws Exception {
            transportResult.set(future.isSuccess());
            if (!future.isSuccess()) {
                transportResult.setException(future.cause());
            }
        }
    });
    return transportResult;
}

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);/*from w ww.ja  va2 s .co  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.openflowjava.protocol.impl.core.TcpHandler.java

License:Open Source License

/**
 * Shuts down {@link TcpHandler}}/*from w  w w  .  j  a  v a2 s .  co m*/
 */
@Override
public ListenableFuture<Boolean> shutdown() {
    final SettableFuture<Boolean> result = SettableFuture.create();
    workerGroup.shutdownGracefully();
    // boss will shutdown as soon, as worker is down
    bossGroup.shutdownGracefully()
            .addListener(new GenericFutureListener<io.netty.util.concurrent.Future<Object>>() {

                @Override
                public void operationComplete(io.netty.util.concurrent.Future<Object> downResult)
                        throws Exception {
                    result.set(downResult.isSuccess());
                    if (downResult.cause() != null) {
                        result.setException(downResult.cause());
                    }
                }

            });
    return result;
}

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

License:Open Source License

@Override
public ListenableFuture<Boolean> shutdown() {
    final SettableFuture<Boolean> result = SettableFuture.create();
    group.shutdownGracefully()/* w ww .  j  a va2s  . co m*/
            .addListener(new GenericFutureListener<io.netty.util.concurrent.Future<Object>>() {

                @Override
                public void operationComplete(final io.netty.util.concurrent.Future<Object> downResult)
                        throws Exception {
                    result.set(downResult.isSuccess());
                    if (downResult.cause() != null) {
                        result.setException(downResult.cause());
                    }
                }

            });
    return result;
}

From source file:org.opendaylight.protocol.bgp.rib.impl.BGPDispatcherImplTest.java

License:Open Source License

private Channel createServer(final InetSocketAddress serverAddress) throws InterruptedException {
    this.serverListener = new SimpleSessionListener();
    this.registry.addPeer(new IpAddress(new Ipv4Address(serverAddress.getAddress().getHostAddress())),
            this.serverListener, createPreferences(serverAddress));
    LoggerFactory.getLogger(BGPDispatcherImplTest.class).info("createServer");
    final ChannelFuture future = this.serverDispatcher.createServer(this.registry, serverAddress);
    future.addListener(new GenericFutureListener<Future<Void>>() {
        @Override//from  w ww. j av a 2  s.  c  o  m
        public void operationComplete(final Future<Void> future) {
            Preconditions.checkArgument(future.isSuccess(), "Unable to start bgp server on %s", future.cause());
        }
    });
    waitFutureSuccess(future);
    return future.channel();
}

From source file:org.opendaylight.protocol.bgp.rib.impl.protocol.BGPReconnectPromise.java

License:Open Source License

public synchronized void connect() {
    // Set up a client with pre-configured bootstrap, but add a closed channel handler into the pipeline to support reconnect attempts
    this.pending = connectSessionPromise(this.address, this.retryTimer, this.bootstrap,
            new ChannelPipelineInitializer<S>() {
                @Override// w  w  w . ja va  2  s  .c  o m
                public void initializeChannel(final SocketChannel channel, final Promise<S> promise) {
                    BGPReconnectPromise.this.initializer.initializeChannel(channel, promise);
                    // add closed channel handler
                    // This handler has to be added as last channel handler and the channel inactive event has to be caught by it
                    // Handlers in front of it can react to channelInactive event, but have to forward the event or the reconnect will not work
                    // This handler is last so all handlers in front of it can handle channel inactive (to e.g. resource cleanup) before a new connection is started
                    channel.pipeline().addLast(new ClosedChannelHandler(BGPReconnectPromise.this));
                }
            });

    this.pending.addListener(new GenericFutureListener<Future<Object>>() {
        @Override
        public void operationComplete(final Future<Object> future) throws Exception {
            if (!future.isSuccess()) {
                BGPReconnectPromise.this.setFailure(future.cause());
            }
        }
    });
}

From source file:org.opendaylight.protocol.framework.ReconnectPromise.java

License:Open Source License

synchronized void connect() {
    final ReconnectStrategy cs = this.strategyFactory.createReconnectStrategy();

    // Set up a client with pre-configured bootstrap, but add a closed channel handler into the pipeline to support reconnect attempts
    pending = this.dispatcher.createClient(this.address, cs, b,
            new AbstractDispatcher.PipelineInitializer<S>() {
                @Override/*from w w w.j a va  2 s. co  m*/
                public void initializeChannel(final SocketChannel channel, final Promise<S> promise) {
                    initializer.initializeChannel(channel, promise);
                    // add closed channel handler
                    // This handler has to be added as last channel handler and the channel inactive event has to be caught by it
                    // Handlers in front of it can react to channelInactive event, but have to forward the event or the reconnect will not work
                    // This handler is last so all handlers in front of it can handle channel inactive (to e.g. resource cleanup) before a new connection is started
                    channel.pipeline().addLast(new ClosedChannelHandler(ReconnectPromise.this));
                }
            });

    pending.addListener(new GenericFutureListener<Future<Object>>() {
        @Override
        public void operationComplete(Future<Object> future) throws Exception {
            if (!future.isSuccess()) {
                ReconnectPromise.this.setFailure(future.cause());
            }
        }
    });
}

From source file:org.opendaylight.usc.client.netconf.ReconnectPromise.java

License:Open Source License

synchronized void connect() {
    final ReconnectStrategy cs = this.strategyFactory.createReconnectStrategy();

    // Set up a client with pre-configured bootstrap, but add a closed channel handler into the pipeline to
    // support reconnect attempts
    pending = dispatcher.createClient(this.address, cs, b, new PipelineInitializer<NetconfClientSession>() {
        @Override//  www  . j  a  va  2  s  .  com
        public void initializeChannel(final Channel channel, final Promise<NetconfClientSession> promise) {
            initializer.initializeChannel(channel, promise);
            // add closed channel handler
            // This handler has to be added as last channel handler and the channel inactive event has
            // to be caught by it
            // Handlers in front of it can react to channelInactive event, but have to forward the event
            // or the reconnect will not work
            // This handler is last so all handlers in front of it can handle channel inactive (to e.g.
            // resource cleanup) before a new connection is started
            channel.pipeline().addLast(new ClosedChannelHandler(ReconnectPromise.this));
        }
    });

    pending.addListener(new GenericFutureListener<Future<Object>>() {
        @Override
        public void operationComplete(Future<Object> future) throws Exception {
            if (!future.isSuccess()) {
                ReconnectPromise.this.setFailure(future.cause());
            }
        }
    });
}

From source file:org.spongepowered.common.entity.player.PlayerKickHelper.java

License:MIT License

/**
 * A {@link IChatComponent}-friendly version of {@link NetHandlerPlayServer#kickPlayerFromServer(String)}.
 * This duplicates the code of that kick implementation pretty much exactly
 *
 * @param ply The player to kick/* w  w w . ja  va  2 s .  c  o  m*/
 * @param component The kick message
 */
public static void kickPlayer(final EntityPlayerMP ply, final IChatComponent component) {
    ply.playerNetServerHandler.getNetworkManager().sendPacket(new S40PacketDisconnect(component),
            new GenericFutureListener() {
                @Override
                public void operationComplete(Future future) throws Exception {
                    ply.playerNetServerHandler.getNetworkManager().closeChannel(component);
                }
            });
    ply.playerNetServerHandler.getNetworkManager().disableAutoRead();
    Futures.getUnchecked(MinecraftServer.getServer().addScheduledTask(new Runnable() {
        @Override
        public void run() {
            ply.playerNetServerHandler.getNetworkManager().checkDisconnected();
        }
    }));

}