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:com.flowpowered.networking.NetworkClient.java

License:MIT License

public ChannelFuture connect(final SocketAddress remoteAdress) {
    return bootstrap.connect(remoteAdress).addListener(new GenericFutureListener<Future<? super Void>>() {
        @Override/*from w w  w.  j  a va2 s . c  o  m*/
        public void operationComplete(Future<? super Void> f) throws Exception {
            Throwable cause = f.cause();
            if (cause != null || f.isCancelled()) {
                onConnectFailure();
            }
        }
    });
}

From source file:com.flowpowered.networking.session.BasicSession.java

License:MIT License

public ChannelFuture sendWithFuture(Message message) {
    if (!channel.isActive()) {
        throw new IllegalStateException("Trying to send a message when a session is inactive!");
    }/*from   ww  w .j a v  a 2  s  . c om*/
    return channel.writeAndFlush(message).addListener(new GenericFutureListener<Future<? super Void>>() {
        @Override
        public void operationComplete(Future<? super Void> future) throws Exception {
            if (future.cause() != null) {
                onOutboundThrowable(future.cause());
            }
        }
    });
}

From source file:com.flysoloing.learning.network.netty.redis.RedisClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    try {//from  www  . j a va2  s  .com
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                p.addLast(new RedisDecoder());
                p.addLast(new RedisBulkStringAggregator());
                p.addLast(new RedisArrayAggregator());
                p.addLast(new RedisEncoder());
                p.addLast(new RedisClientHandler());
            }
        });

        // Start the connection attempt.
        Channel ch = b.connect(HOST, PORT).sync().channel();

        // Read commands from the stdin.
        System.out.println("Enter Redis commands (quit to end)");
        ChannelFuture lastWriteFuture = null;
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        for (;;) {
            final String input = in.readLine();
            final String line = input != null ? input.trim() : null;
            if (line == null || "quit".equalsIgnoreCase(line)) { // EOF or "quit"
                ch.close().sync();
                break;
            } else if (line.isEmpty()) { // skip `enter` or `enter` with spaces.
                continue;
            }
            // Sends the received line to the server.
            lastWriteFuture = ch.writeAndFlush(line);
            lastWriteFuture.addListener(new GenericFutureListener<ChannelFuture>() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        System.err.print("write failed: ");
                        future.cause().printStackTrace(System.err);
                    }
                }
            });
        }

        // Wait until all messages are flushed before closing the channel.
        if (lastWriteFuture != null) {
            lastWriteFuture.sync();
        }
    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.flysoloing.learning.network.netty.securechat.SecureChatServerHandler.java

License:Apache License

@Override
public void channelActive(final ChannelHandlerContext ctx) {
    // Once session is secured, send a greeting and register the channel to the global channel
    // list so the channel received the messages from others.
    ctx.pipeline().get(SslHandler.class).handshakeFuture()
            .addListener(new GenericFutureListener<Future<Channel>>() {
                public void operationComplete(Future<Channel> future) throws Exception {
                    ctx.writeAndFlush("Welcome to " + InetAddress.getLocalHost().getHostName()
                            + " secure chat service!\n");
                    ctx.writeAndFlush("Your session is protected by "
                            + ctx.pipeline().get(SslHandler.class).engine().getSession().getCipherSuite()
                            + " cipher suite.\n");

                    channels.add(ctx.channel());
                }//from  w  w  w.  j a  v  a  2 s.  c om
            });
}

From source file:com.gdut.Netty_testing.time_server.server.TimeServer.java

License:Apache License

/**
 * /*  w  w w.  j  av  a  2 s .  c  o m*/
 * @Title: main
 * @Description: TODO
 * @param @param args
 * @param @throws Exception
 * @return void
 * @throws
 */
public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        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).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), new TimeEncoder(),
                                new TimeServerHandler());
                        // new TimeEncoder(),
                    }
                });

        // Start the server.
        ChannelFuture f = b.bind(PORT).sync();
        f.addListener(new GenericFutureListener<Future<? super Void>>() {

            public void operationComplete(Future<? super Void> future) throws Exception {
                // TODO Auto-generated method stub
                System.out.println("success " + future.isSuccess());
            }
        });

        // 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.github.milenkovicm.kafka.handler.MetadataHandler.java

License:Apache License

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {

    final ControlTuple tuple = (ControlTuple) msg;
    final int currentCorrelation = correlation++;
    ByteBuf kafkaMessage = createMetadataRequest(ctx.alloc(), tuple.topicName, currentCorrelation);

    // not sure if it is possible that tread may read response message before it
    // puts future in the map. that's why I have it here .
    acks.put(currentCorrelation, tuple.promise);
    promise.addListener(new GenericFutureListener<ChannelPromise>() {
        @Override//from  ww w  .j  a  va 2s  .  c  o m
        public void operationComplete(ChannelPromise future) throws Exception {
            // shouldn't be possible to cancel this operation
            //                if (future.isCancelled()) {
            //                    tuple.promise.cancel(true);
            //                    return;
            //                }
            if (future.isDone() && !future.isSuccess()) {
                acks.remove(currentCorrelation);
                tuple.promise.setFailure(future.cause());
            }
        }
    });
    super.write(ctx, kafkaMessage, promise);
}

From source file:com.github.milenkovicm.kafka.NoTopicTest.java

License:Apache License

@Test
public void test_producer_no_topic_async() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    String topic = "test_producer_no_topic__async";
    ProducerProperties properties = new ProducerProperties();
    properties.override(ProducerProperties.NETTY_DEBUG_PIPELINE, true);
    //createTopic(topic);

    KafkaProducer producer = new KafkaProducer("localhost", START_PORT, topic, properties);
    final Future<Void> connect = producer.connect();

    connect.addListener(new GenericFutureListener<Future<? super Void>>() {
        @Override/*  ww  w . j  a  v a2 s  .c om*/
        public void operationComplete(Future<? super Void> future) throws Exception {
            latch.countDown();
        }
    });

    latch.await(5, TimeUnit.SECONDS);

    Assert.assertThat(connect.isDone(), is(true));
    Assert.assertThat(connect.isSuccess(), is(false));
    Assert.assertThat(connect.cause(), notNullValue());
    Assert.assertThat(((KafkaException) connect.cause()).error, is(Error.LEADER_NOT_AVAILABLE));

    producer.disconnect();
}

From source file:com.github.mrstampy.kitchensync.netty.Bootstrapper.java

License:Open Source License

private GenericFutureListener<ChannelFuture> getBindListener(final int port, final CountDownLatch latch) {
    return new GenericFutureListener<ChannelFuture>() {

        @Override//from   www . j a va 2  s. com
        public void operationComplete(ChannelFuture future) throws Exception {
            try {
                if (future.isSuccess()) {
                    log.debug("Channel creation successful for {}", future.channel());
                } else {
                    Throwable cause = future.cause();
                    if (cause == null) {
                        log.error("Could not create channel for {}", port);
                    } else {
                        log.error("Could not create channel for {}", port, cause);
                    }
                }
            } finally {
                latch.countDown();
            }
        }
    };
}

From source file:com.github.mrstampy.kitchensync.netty.Bootstrapper.java

License:Open Source License

private GenericFutureListener<ChannelFuture> getMulticastBindListener(final InetSocketAddress multicast,
        final CountDownLatch latch) {
    return new GenericFutureListener<ChannelFuture>() {

        @Override//from  w  ww  .  j a va 2 s .c o m
        public void operationComplete(ChannelFuture future) throws Exception {
            try {
                if (future.isSuccess()) {
                    log.debug("Multicast channel creation successful for {}", multicast);
                } else {
                    Throwable cause = future.cause();
                    if (cause == null) {
                        log.error("Could not create multicast channel for {}", multicast);
                    } else {
                        log.error("Could not create multicast channel for {}", multicast, cause);
                    }
                }
            } finally {
                latch.countDown();
            }
        }
    };
}

From source file:com.github.mrstampy.kitchensync.netty.channel.AbstractKiSyChannel.java

License:Open Source License

/**
 * Sets the channel.//from  w w w.  j ava  2 s .c o m
 *
 * @param channel
 *          the channel
 */
protected void setChannel(DC channel) {
    this.channel = channel;

    channel.closeFuture().addListener(new GenericFutureListener<ChannelFuture>() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            registry.removeChannel(AbstractKiSyChannel.this);
            active.set(false);
        }
    });

    active.set(true);
}