Example usage for io.netty.channel ChannelFuture await

List of usage examples for io.netty.channel ChannelFuture await

Introduction

In this page you can find the example usage for io.netty.channel ChannelFuture await.

Prototype

boolean await(long timeout, TimeUnit unit) throws InterruptedException;

Source Link

Document

Waits for this future to be completed within the specified time limit.

Usage

From source file:com.avanza.astrix.netty.client.NettyRemotingClient.java

License:Apache License

public void connect(String host, int port) {
    Bootstrap b = new Bootstrap();
    b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
        @Override//w  w w  .  j a  v a2s .  c  o m
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            p.addLast(new ObjectEncoder(), new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                    nettyRemotingClientHandler);
        }
    });

    // Start the connection attempt.
    ChannelFuture channel = b.connect(host, port);
    try {
        if (channel.await(1, TimeUnit.SECONDS)) {
            if (channel.isSuccess()) {
                return;
            }
        }
    } catch (InterruptedException e) {
    }
    destroy();
    throw new IllegalArgumentException(
            String.format("Failed to connect to remoting server: %s:%d", host, port));
}

From source file:com.avanza.astrix.netty.server.NettyRemotingServer.java

License:Apache License

public void start() {
    bossGroup = new NioEventLoopGroup(1);
    workerGroup = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_REUSEADDR, false).handler(new LoggingHandler(LogLevel.INFO))
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override/*from   w w w .j  av  a 2  s  .com*/
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(new ObjectEncoder(), new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                            new NettyRemotingServerHandler(serviceActivator));
                }
            });

    // Bind and start to accept incoming connections. Binds to all interfaces
    // TODO: Allow specifying a bind port range. Attempt to bind to each port in range and use first successfully bound port
    ChannelFuture channel = b.bind(port);
    try {
        if (channel.await(2, TimeUnit.SECONDS)) {
            if (channel.isSuccess()) {
                port = InetSocketAddress.class.cast(channel.channel().localAddress()).getPort();
                log.info("NettyRemotingServer started listening on port={}", port);
                return;
            }
        }
    } catch (InterruptedException e) {
    }
    throw new IllegalStateException("Failed to start netty remoting server. Can't bind to port: " + port);
}

From source file:com.github.mrstampy.gameboot.otp.netty.OtpNettyTest.java

License:Open Source License

private void createEncryptedChannel() throws InterruptedException {
    ChannelFuture cf = encClient.connect(HOST, ENC_SERVER_PORT);
    cf.await(1, TimeUnit.SECONDS);

    assertTrue(cf.isSuccess());// w w  w .j av a2 s.  c  o  m
    encChannel = cf.channel();
}

From source file:com.github.sinsinpub.pero.backend.ConnectBackendHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception {
    final Channel inboundChannel = ctx.channel();
    final Promise<Channel> outboundPromise = newOutboundPromise(ctx, request);
    final int maxProxies = AppProps.PROPS.getInteger("upstream.socks5.count", 1);
    final AtomicBoolean isFinalSuccess = new AtomicBoolean(false);
    final AtomicBoolean isRetryOccured = new AtomicBoolean(false);
    for (int i = 1; i <= maxProxies; i++) {
        final boolean isFirstOne = (i == 1);
        final boolean isFinalOne = (i == maxProxies);
        if (!isFirstOne) {
            isRetryOccured.set(true);/*from   ww w . j a va2  s  .c  o m*/
        }
        try {
            final ProxyHandler upstreamProxyHandler = newUpstreamProxyHandler(i);
            final Bootstrap b = newConnectionBootstrap(inboundChannel, outboundPromise, upstreamProxyHandler);
            logger.info(String.format("Connecting backend %s:%s via %s", request.host(), request.port(),
                    upstreamProxyHandler != null ? upstreamProxyHandler.proxyAddress() : "direct"));
            ChannelFuture connFuture = b.connect(request.host(), request.port());
            connFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        // Connection established use handler provided results
                        if (upstreamProxyHandler == null) {
                            logger.info("Backend connected directly");
                        } else {
                            logger.info("Backend connected via: " + upstreamProxyHandler.proxyAddress());
                        }
                    } else {
                        // Close the connection if the connection attempt has failed.
                        if (isFinalOne) {
                            logger.error("Backend connection failed: " + future.cause(), future.cause());
                            ctx.channel().writeAndFlush(
                                    new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                            NettyChannelUtils.closeOnFlush(ctx.channel());
                        } else {
                            logger.warn("Backend connection failed: {}", future.cause().toString());
                        }
                    }
                }
            });
            connFuture.await(getConnectTimeoutMillis(), TimeUnit.MILLISECONDS);
            if (connFuture.isSuccess()) {
                isFinalSuccess.set(true);
                break;
            }
        } catch (Exception e) {
            logger.error("Connecting exception {} caught:", e);
        }
    }
    if (isFinalSuccess.get() && isRetryOccured.get()) {
        logger.warn("Protected from Error-Neko: {} times", nekoKilled.incrementAndGet());
    }
}

From source file:com.lambdaworks.redis.protocol.ReconnectionHandler.java

License:Apache License

protected boolean reconnect(InternalLogLevel infoLevel) throws Exception {

    SocketAddress remoteAddress = socketAddressSupplier.get();

    try {/*from  ww w. ja  va  2s  . c o  m*/
        long timeLeft = timeoutUnit.toNanos(timeout);
        long start = System.nanoTime();

        logger.debug("Reconnecting to Redis at {}", remoteAddress);
        ChannelFuture currentFuture = this.currentFuture = bootstrap.connect(remoteAddress);
        if (!currentFuture.await(timeLeft, TimeUnit.NANOSECONDS)) {
            if (currentFuture.isCancellable()) {
                currentFuture.cancel(true);
            }

            throw new TimeoutException(
                    "Reconnection attempt exceeded timeout of " + timeout + " " + timeoutUnit);
        }

        currentFuture.sync();

        Channel channel = currentFuture.channel();

        RedisChannelInitializer channelInitializer = channel.pipeline().get(RedisChannelInitializer.class);
        CommandHandler<?, ?> commandHandler = channel.pipeline().get(CommandHandler.class);

        if (channelInitializer == null) {
            logger.warn("Reconnection attempt without a RedisChannelInitializer in the channel pipeline");
            close(channel);
            return false;
        }

        if (commandHandler == null) {
            logger.warn("Reconnection attempt without a CommandHandler in the channel pipeline");
            close(channel);
            return false;
        }

        try {
            timeLeft -= System.nanoTime() - start;
            channelInitializer.channelInitialized().get(Math.max(0, timeLeft), TimeUnit.NANOSECONDS);
            if (logger.isDebugEnabled()) {
                logger.log(infoLevel, "Reconnected to {}, Channel {}", remoteAddress,
                        ChannelLogDescriptor.logDescriptor(channel));
            } else {
                logger.log(infoLevel, "Reconnected to {}", remoteAddress);
            }
            return true;
        } catch (TimeoutException e) {
            channelInitializer.channelInitialized().cancel(true);
        } catch (Exception e) {
            if (clientOptions.isCancelCommandsOnReconnectFailure()) {
                commandHandler.reset();
            }

            if (clientOptions.isSuspendReconnectOnProtocolFailure()) {
                logger.error("Cannot initialize channel. Disabling autoReconnect", e);
                setReconnectSuspended(true);
            } else {
                logger.error("Cannot initialize channel.", e);
                throw e;
            }
        }
    } finally {
        this.currentFuture = null;
    }

    return false;
}

From source file:io.grpc.netty.ProtocolNegotiatorsTest.java

License:Apache License

@Test
public void clientTlsHandler_firesNegotiation() throws Exception {
    SelfSignedCertificate cert = new SelfSignedCertificate("authority");
    SslContext clientSslContext = GrpcSslContexts
            .configure(SslContextBuilder.forClient().trustManager(cert.cert())).build();
    SslContext serverSslContext = GrpcSslContexts
            .configure(SslContextBuilder.forServer(cert.key(), cert.cert())).build();
    FakeGrpcHttp2ConnectionHandler gh = FakeGrpcHttp2ConnectionHandler.newHandler();

    ClientTlsProtocolNegotiator pn = new ClientTlsProtocolNegotiator(clientSslContext);
    WriteBufferingAndExceptionHandler clientWbaeh = new WriteBufferingAndExceptionHandler(pn.newHandler(gh));

    SocketAddress addr = new LocalAddress("addr");

    ChannelHandler sh = ProtocolNegotiators.serverTls(serverSslContext)
            .newHandler(FakeGrpcHttp2ConnectionHandler.noopHandler());
    WriteBufferingAndExceptionHandler serverWbaeh = new WriteBufferingAndExceptionHandler(sh);
    Channel s = new ServerBootstrap().childHandler(serverWbaeh).group(group).channel(LocalServerChannel.class)
            .bind(addr).sync().channel();
    Channel c = new Bootstrap().handler(clientWbaeh).channel(LocalChannel.class).group(group).register().sync()
            .channel();//from ww w.  ja  va 2  s. c  om
    ChannelFuture write = c.writeAndFlush(NettyClientHandler.NOOP_MESSAGE);
    c.connect(addr).sync();
    write.sync();

    boolean completed = gh.negotiated.await(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    if (!completed) {
        assertTrue("failed to negotiated", write.await(TIMEOUT_SECONDS, TimeUnit.SECONDS));
        // sync should fail if we are in this block.
        write.sync();
        throw new AssertionError("neither wrote nor negotiated");
    }
    c.close();
    s.close();

    assertThat(gh.securityInfo).isNotNull();
    assertThat(gh.securityInfo.tls).isNotNull();
    assertThat(gh.attrs.get(GrpcAttributes.ATTR_SECURITY_LEVEL)).isEqualTo(SecurityLevel.PRIVACY_AND_INTEGRITY);
    assertThat(gh.attrs.get(Grpc.TRANSPORT_ATTR_SSL_SESSION)).isInstanceOf(SSLSession.class);
    // This is not part of the ClientTls negotiation, but shows that the negotiation event happens
    // in the right order.
    assertThat(gh.attrs.get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR)).isEqualTo(addr);
}

From source file:io.grpc.netty.ProtocolNegotiatorsTest.java

License:Apache License

@Test
public void plaintextUpgradeNegotiator() throws Exception {
    LocalAddress addr = new LocalAddress("plaintextUpgradeNegotiator");
    UpgradeCodecFactory ucf = new UpgradeCodecFactory() {

        @Override/*from ww  w.  j  av a 2 s.c  o m*/
        public UpgradeCodec newUpgradeCodec(CharSequence protocol) {
            return new Http2ServerUpgradeCodec(FakeGrpcHttp2ConnectionHandler.newHandler());
        }
    };
    final HttpServerCodec serverCodec = new HttpServerCodec();
    final HttpServerUpgradeHandler serverUpgradeHandler = new HttpServerUpgradeHandler(serverCodec, ucf);
    Channel serverChannel = new ServerBootstrap().group(group).channel(LocalServerChannel.class)
            .childHandler(new ChannelInitializer<Channel>() {

                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ch.pipeline().addLast(serverCodec, serverUpgradeHandler);
                }
            }).bind(addr).sync().channel();

    FakeGrpcHttp2ConnectionHandler gh = FakeGrpcHttp2ConnectionHandler.newHandler();
    ProtocolNegotiator nego = ProtocolNegotiators.plaintextUpgrade();
    ChannelHandler ch = nego.newHandler(gh);
    WriteBufferingAndExceptionHandler wbaeh = new WriteBufferingAndExceptionHandler(ch);

    Channel channel = new Bootstrap().group(group).channel(LocalChannel.class).handler(wbaeh).register().sync()
            .channel();

    ChannelFuture write = channel.writeAndFlush(NettyClientHandler.NOOP_MESSAGE);
    channel.connect(serverChannel.localAddress());

    boolean completed = gh.negotiated.await(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    if (!completed) {
        assertTrue("failed to negotiated", write.await(TIMEOUT_SECONDS, TimeUnit.SECONDS));
        // sync should fail if we are in this block.
        write.sync();
        throw new AssertionError("neither wrote nor negotiated");
    }

    channel.close().sync();
    serverChannel.close();

    assertThat(gh.securityInfo).isNull();
    assertThat(gh.attrs.get(GrpcAttributes.ATTR_SECURITY_LEVEL)).isEqualTo(SecurityLevel.NONE);
    assertThat(gh.attrs.get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR)).isEqualTo(addr);
}

From source file:org.apache.flink.runtime.webmonitor.testutils.HttpTestClient.java

License:Apache License

/**
 * Sends a request to to the server./* ww  w. j  a v  a 2s .co  m*/
 *
 * <pre>
 * HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/overview");
 * request.headers().set(HttpHeaders.Names.HOST, host);
 * request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
 *
 * sendRequest(request);
 * </pre>
 *
 * @param request The {@link HttpRequest} to send to the server
 */
public void sendRequest(HttpRequest request, FiniteDuration timeout)
        throws InterruptedException, TimeoutException {
    LOG.debug("Writing {}.", request);

    // Make the connection attempt.
    ChannelFuture connect = bootstrap.connect(host, port);

    Channel channel;
    if (connect.await(timeout.toMillis(), TimeUnit.MILLISECONDS)) {
        channel = connect.channel();
    } else {
        throw new TimeoutException("Connection failed");
    }

    channel.writeAndFlush(request);
}

From source file:org.opendaylight.controller.netconf.it.AbstractNetconfConfigTest.java

License:Open Source License

private Channel startNetconfTcpServer(final AggregatedNetconfOperationServiceFactory listener,
        final NetconfMonitoringService monitoring) throws Exception {
    final NetconfServerDispatcherImpl dispatch = createDispatcher(listener, monitoring,
            getNotificationProducer());//from  ww  w.  j  a  v  a 2 s  . co m

    final ChannelFuture s;
    if (getTcpServerAddress() instanceof LocalAddress) {
        s = dispatch.createLocalServer(((LocalAddress) getTcpServerAddress()));
    } else {
        s = dispatch.createServer(((InetSocketAddress) getTcpServerAddress()));
    }
    s.await(RESOURCE_TIMEOUT_MINUTES, TimeUnit.MINUTES);
    return s.channel();
}

From source file:org.opendaylight.netconf.it.AbstractNetconfConfigTest.java

License:Open Source License

private Channel startNetconfTcpServer(final AggregatedNetconfOperationServiceFactory listener,
        final NetconfMonitoringService monitoring) throws Exception {
    final NetconfServerDispatcherImpl dispatch = createDispatcher(listener, monitoring);

    final ChannelFuture s;
    if (getTcpServerAddress() instanceof LocalAddress) {
        s = dispatch.createLocalServer(((LocalAddress) getTcpServerAddress()));
    } else {//from w w  w.  ja  v  a 2  s . c  om
        s = dispatch.createServer(((InetSocketAddress) getTcpServerAddress()));
    }
    s.await(RESOURCE_TIMEOUT_MINUTES, TimeUnit.MINUTES);
    return s.channel();
}