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

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

Introduction

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

Prototype

FutureListener

Source Link

Usage

From source file:cc.agentx.client.net.nio.XConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksCmdRequest request) throws Exception {
    boolean proxyMode = isAgentXNeeded(request.host());
    log.info("\tClient -> Proxy           \tTarget {}:{} [{}]", request.host(), request.port(),
            proxyMode ? "AGENTX" : "DIRECT");
    Promise<Channel> promise = ctx.executor().newPromise();
    promise.addListener(new FutureListener<Channel>() {
        @Override/*from  www  .  ja  va 2  s  . co  m*/
        public void operationComplete(final Future<Channel> future) throws Exception {
            final Channel outboundChannel = future.getNow();
            if (future.isSuccess()) {
                ctx.channel().writeAndFlush(new SocksCmdResponse(SocksCmdStatus.SUCCESS, request.addressType()))
                        .addListener(channelFuture -> {
                            ByteBuf byteBuf = Unpooled.buffer();
                            request.encodeAsByteBuf(byteBuf);
                            if (byteBuf.hasArray()) {
                                byte[] xRequestBytes = new byte[byteBuf.readableBytes()];
                                byteBuf.getBytes(0, xRequestBytes);

                                if (proxyMode) {
                                    // handshaking to remote proxy
                                    xRequestBytes = requestWrapper.wrap(xRequestBytes);
                                    outboundChannel.writeAndFlush(Unpooled.wrappedBuffer(
                                            exposeRequest ? xRequestBytes : wrapper.wrap(xRequestBytes)));
                                }

                                // task handover
                                ReferenceCountUtil.retain(request); // auto-release? a trap?
                                ctx.pipeline().remove(XConnectHandler.this);
                                outboundChannel.pipeline().addLast(new XRelayHandler(ctx.channel(),
                                        proxyMode ? wrapper : rawWrapper, false));
                                ctx.pipeline().addLast(new XRelayHandler(outboundChannel,
                                        proxyMode ? wrapper : rawWrapper, true));
                            }
                        });
            } else {
                ctx.channel()
                        .writeAndFlush(new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));

                if (ctx.channel().isActive()) {
                    ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
                }
            }
        }
    });

    String host = request.host();
    int port = request.port();
    if (host.equals(config.getConsoleDomain())) {
        host = "localhost";
        port = config.getConsolePort();
    } else if (proxyMode) {
        host = config.getServerHost();
        port = config.getServerPort();
    }

    // ping target
    bootstrap.group(ctx.channel().eventLoop()).channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
            .handler(new XPingHandler(promise, System.currentTimeMillis())).connect(host, port)
            .addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        ctx.channel().writeAndFlush(
                                new SocksCmdResponse(SocksCmdStatus.FAILURE, request.addressType()));
                        if (ctx.channel().isActive()) {
                            ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
                        }
                    }
                }
            });
}

From source file:cc.agentx.server.net.nio.XConnectHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    try {//from  w  ww.j  a v a  2s.c o m
        ByteBuf byteBuf = (ByteBuf) msg;
        if (!byteBuf.hasArray()) {
            byte[] bytes = new byte[byteBuf.readableBytes()];
            byteBuf.getBytes(0, bytes);

            if (!requestParsed) {
                if (!exposedRequest) {
                    bytes = wrapper.unwrap(bytes);
                    if (bytes == null) {
                        log.info("\tClient -> Proxy           \tHalf Request");
                        return;
                    }
                }
                XRequest xRequest = requestWrapper.parse(bytes);
                String host = xRequest.getHost();
                int port = xRequest.getPort();
                int dataLength = xRequest.getSubsequentDataLength();
                if (dataLength > 0) {
                    byte[] tailData = Arrays.copyOfRange(bytes, bytes.length - dataLength, bytes.length);
                    if (exposedRequest) {
                        tailData = wrapper.unwrap(tailData);
                        if (tailData != null) {
                            tailDataBuffer.write(tailData, 0, tailData.length);
                        }
                    } else {
                        tailDataBuffer.write(tailData, 0, tailData.length);
                    }
                }
                log.info("\tClient -> Proxy           \tTarget {}:{}{}", host, port,
                        DnsCache.isCached(host) ? " [Cached]" : "");
                if (xRequest.getAtyp() == XRequest.Type.DOMAIN) {
                    try {
                        host = DnsCache.get(host);
                        if (host == null) {
                            host = xRequest.getHost();
                        }
                    } catch (UnknownHostException e) {
                        log.warn("\tClient <- Proxy           \tBad DNS! ({})", e.getMessage());
                        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
                        return;
                    }
                }

                Promise<Channel> promise = ctx.executor().newPromise();
                promise.addListener(new FutureListener<Channel>() {
                    @Override
                    public void operationComplete(final Future<Channel> future) throws Exception {
                        final Channel outboundChannel = future.getNow();
                        if (future.isSuccess()) {
                            // handle tail
                            byte[] tailData = tailDataBuffer.toByteArray();
                            tailDataBuffer.close();
                            if (tailData.length > 0) {
                                log.info("\tClient ==========> Target \tSend Tail [{} bytes]", tailData.length);
                            }
                            outboundChannel
                                    .writeAndFlush((tailData.length > 0) ? Unpooled.wrappedBuffer(tailData)
                                            : Unpooled.EMPTY_BUFFER)
                                    .addListener(channelFuture -> {
                                        // task handover
                                        outboundChannel.pipeline()
                                                .addLast(new XRelayHandler(ctx.channel(), wrapper, false));
                                        ctx.pipeline()
                                                .addLast(new XRelayHandler(outboundChannel, wrapper, true));
                                        ctx.pipeline().remove(XConnectHandler.this);
                                    });

                        } else {
                            if (ctx.channel().isActive()) {
                                ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
                                        .addListener(ChannelFutureListener.CLOSE);
                            }
                        }
                    }
                });

                final String finalHost = host;
                bootstrap.group(ctx.channel().eventLoop()).channel(NioSocketChannel.class)
                        .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                        .option(ChannelOption.SO_KEEPALIVE, true)
                        .handler(new XPingHandler(promise, System.currentTimeMillis())).connect(host, port)
                        .addListener(new ChannelFutureListener() {
                            @Override
                            public void operationComplete(ChannelFuture future) throws Exception {
                                if (!future.isSuccess()) {
                                    if (ctx.channel().isActive()) {
                                        log.warn("\tClient <- Proxy           \tBad Ping! ({}:{})", finalHost,
                                                port);
                                        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
                                                .addListener(ChannelFutureListener.CLOSE);
                                    }
                                }
                            }
                        });

                requestParsed = true;
            } else {
                bytes = wrapper.unwrap(bytes);
                if (bytes != null)
                    tailDataBuffer.write(bytes, 0, bytes.length);
            }
        }
    } finally {
        ReferenceCountUtil.release(msg);
    }
}

From source file:com.corundumstudio.socketio.SocketIOServer.java

License:Apache License

/**
 * Start server asynchronously/*from w w  w .j av  a 2 s . c om*/
 */
public Future<Void> startAsync() {
    log.info("Session store / pubsub factory used: {}", configCopy.getStoreFactory());
    initGroups();

    pipelineFactory.start(configCopy, namespacesHub);

    Class channelClass = NioServerSocketChannel.class;
    if (configCopy.isUseLinuxNativeEpoll()) {
        channelClass = EpollServerSocketChannel.class;
    }

    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(channelClass).childHandler(pipelineFactory);
    applyConnectionOptions(b);

    InetSocketAddress addr = new InetSocketAddress(configCopy.getPort());
    if (configCopy.getHostname() != null) {
        addr = new InetSocketAddress(configCopy.getHostname(), configCopy.getPort());
    }

    return b.bind(addr).addListener(new FutureListener<Void>() {
        @Override
        public void operationComplete(Future<Void> future) throws Exception {
            if (future.isSuccess()) {
                log.info("SocketIO server started at port: {}", configCopy.getPort());
            } else {
                log.error("SocketIO server start failed at port: {}!", configCopy.getPort());
            }
        }
    });
}

From source file:com.emin.igwmp.skm.core.netty.handler.SocksServerConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksMessage message) throws Exception {
    if (message instanceof Socks4CommandRequest) {
        final Socks4CommandRequest request = (Socks4CommandRequest) message;
        Promise<Channel> promise = ctx.executor().newPromise();
        promise.addListener(new FutureListener<Channel>() {
            @Override/*from   www . java2  s  .  c  o  m*/
            public void operationComplete(final Future<Channel> future) throws Exception {
                final Channel outboundChannel = future.getNow();
                if (future.isSuccess()) {
                    ChannelFuture responseFuture = ctx.channel()
                            .writeAndFlush(new DefaultSocks4CommandResponse(Socks4CommandStatus.SUCCESS));

                    responseFuture.addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture channelFuture) {
                            ctx.pipeline().remove(SocksServerConnectHandler.this);
                            outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                            ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                        }
                    });
                } else {
                    ctx.channel().writeAndFlush(
                            new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });

        final Channel inboundChannel = ctx.channel();
        b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new DirectClientHandler(promise));

        b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    // Connection established use handler provided results
                } else {
                    // Close the connection if the connection attempt has failed.
                    ctx.channel().writeAndFlush(
                            new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
    } else if (message instanceof Socks5CommandRequest) {
        final Socks5CommandRequest request = (Socks5CommandRequest) message;
        Promise<Channel> promise = ctx.executor().newPromise();
        promise.addListener(new FutureListener<Channel>() {
            @Override
            public void operationComplete(final Future<Channel> future) throws Exception {
                final Channel outboundChannel = future.getNow();
                if (future.isSuccess()) {
                    ChannelFuture responseFuture = ctx.channel()
                            .writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.SUCCESS,
                                    request.dstAddrType(), request.dstAddr(), request.dstPort()));

                    responseFuture.addListener(new ChannelFutureListener() {
                        @Override
                        public void operationComplete(ChannelFuture channelFuture) {
                            ctx.pipeline().remove(SocksServerConnectHandler.this);
                            outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                            ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                        }
                    });
                } else {
                    ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE,
                            request.dstAddrType()));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });

        final Channel inboundChannel = ctx.channel();
        b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new DirectClientHandler(promise));

        b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    // Connection established use handler provided results
                } else {
                    // Close the connection if the connection attempt has failed.
                    ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE,
                            request.dstAddrType()));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
    } else {
        ctx.close();
    }
}

From source file:com.flysoloing.learning.network.netty.socksproxy.SocksServerConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksMessage message) throws Exception {
    if (message instanceof Socks4CommandRequest) {
        final Socks4CommandRequest request = (Socks4CommandRequest) message;
        Promise<Channel> promise = ctx.executor().newPromise();
        promise.addListener(new FutureListener<Channel>() {
            public void operationComplete(final Future<Channel> future) throws Exception {
                final Channel outboundChannel = future.getNow();
                if (future.isSuccess()) {
                    ChannelFuture responseFuture = ctx.channel()
                            .writeAndFlush(new DefaultSocks4CommandResponse(Socks4CommandStatus.SUCCESS));

                    responseFuture.addListener(new ChannelFutureListener() {
                        public void operationComplete(ChannelFuture channelFuture) {
                            ctx.pipeline().remove(SocksServerConnectHandler.this);
                            outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                            ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                        }//  w  ww. j  a v  a 2 s.  c  om
                    });
                } else {
                    ctx.channel().writeAndFlush(
                            new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });

        final Channel inboundChannel = ctx.channel();
        b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new DirectClientHandler(promise));

        b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() {
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    // Connection established use handler provided results
                } else {
                    // Close the connection if the connection attempt has failed.
                    ctx.channel().writeAndFlush(
                            new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
    } else if (message instanceof Socks5CommandRequest) {
        final Socks5CommandRequest request = (Socks5CommandRequest) message;
        Promise<Channel> promise = ctx.executor().newPromise();
        promise.addListener(new FutureListener<Channel>() {
            public void operationComplete(final Future<Channel> future) throws Exception {
                final Channel outboundChannel = future.getNow();
                if (future.isSuccess()) {
                    ChannelFuture responseFuture = ctx.channel()
                            .writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.SUCCESS,
                                    request.dstAddrType(), request.dstAddr(), request.dstPort()));

                    responseFuture.addListener(new ChannelFutureListener() {
                        public void operationComplete(ChannelFuture channelFuture) {
                            ctx.pipeline().remove(SocksServerConnectHandler.this);
                            outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                            ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                        }
                    });
                } else {
                    ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE,
                            request.dstAddrType()));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });

        final Channel inboundChannel = ctx.channel();
        b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new DirectClientHandler(promise));

        b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() {
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    // Connection established use handler provided results
                } else {
                    // Close the connection if the connection attempt has failed.
                    ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE,
                            request.dstAddrType()));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
    } else {
        ctx.close();
    }
}

From source file:com.fsocks.SocksServerConnectHandler.java

License:Apache License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final SocksMessage message) throws Exception {
    if (message instanceof Socks4CommandRequest) {
        final Socks4CommandRequest request = (Socks4CommandRequest) message;
        Promise<Channel> promise = ctx.executor().newPromise();
        promise.addListener(new FutureListener<Channel>() {
            public void operationComplete(final Future<Channel> future) throws Exception {
                final Channel outboundChannel = future.getNow();
                if (future.isSuccess()) {
                    ChannelFuture responseFuture = ctx.channel()
                            .writeAndFlush(new DefaultSocks4CommandResponse(Socks4CommandStatus.SUCCESS));

                    responseFuture.addListener(new ChannelFutureListener() {
                        public void operationComplete(ChannelFuture channelFuture) {
                            ctx.pipeline().remove(SocksServerConnectHandler.this);
                            outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                            ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                        }//from ww w  .jav a 2s.  com
                    });
                } else {
                    ctx.channel().writeAndFlush(
                            new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });

        final Channel inboundChannel = ctx.channel();
        b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new DirectClientHandler(promise));

        b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() {
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    // Connection established use handler provided results
                } else {
                    // Close the connection if the connection attempt has failed.
                    ctx.channel().writeAndFlush(
                            new DefaultSocks4CommandResponse(Socks4CommandStatus.REJECTED_OR_FAILED));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
    } else if (message instanceof Socks5CommandRequest) {
        final Socks5CommandRequest request = (Socks5CommandRequest) message;
        Promise<Channel> promise = ctx.executor().newPromise();
        promise.addListener(new FutureListener<Channel>() {
            public void operationComplete(final Future<Channel> future) throws Exception {
                final Channel outboundChannel = future.getNow();
                if (future.isSuccess()) {
                    //??successclient
                    ChannelFuture responseFuture = ctx.channel()
                            .writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.SUCCESS,
                                    request.dstAddrType(), request.dstAddr(), request.dstPort()));

                    responseFuture.addListener(new ChannelFutureListener() {
                        public void operationComplete(ChannelFuture channelFuture) {
                            //clientremote???????local proxy
                            ctx.pipeline().remove(SocksServerConnectHandler.this);
                            outboundChannel.pipeline().addLast(new RelayHandler(ctx.channel()));
                            ctx.pipeline().addLast(new RelayHandler(outboundChannel));
                        }
                    });
                } else {
                    ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE,
                            request.dstAddrType()));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
        //?
        logger.info("? addressType : " + request.dstAddrType() + ", cmdType:" + request.type()
                + ", host:" + request.dstAddr() + ", port:" + request.dstPort());
        final Channel inboundChannel = ctx.channel();
        b.group(inboundChannel.eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000).option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new DirectClientHandler(promise));

        b.connect(request.dstAddr(), request.dstPort()).addListener(new ChannelFutureListener() {
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    // Connection established use handler provided results
                    logger.info("?? addressType : " + request.dstAddrType()
                            + ", cmdType:" + request.type() + ", host:" + request.dstAddr() + ", port:"
                            + request.dstPort());
                } else {
                    // Close the connection if the connection attempt has failed.
                    ctx.channel().writeAndFlush(new DefaultSocks5CommandResponse(Socks5CommandStatus.FAILURE,
                            request.dstAddrType()));
                    SocksServerUtils.closeOnFlush(ctx.channel());
                }
            }
        });
    } else {
        ctx.close();
    }
}

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

License:Apache License

@Test
public void test_fetchMetadata() throws Exception {
    createTopic(topic);//from   w  w  w.  j a v a 2 s . c om

    ProducerProperties properties = new ProducerProperties();
    properties.override(ProducerProperties.NETTY_DEBUG_PIPELINE, true);

    ControlKafkaBroker controlKafkaChannel = new ControlKafkaBroker("localhost", START_PORT, topic,
            new NioEventLoopGroup(), properties);
    controlKafkaChannel.connect().sync();

    final CountDownLatch latch = new CountDownLatch(1);
    final KafkaPromise future = controlKafkaChannel.fetchMetadata(topic);
    future.addListener(new FutureListener<MetadataResponse>() {

        @Override
        public void operationComplete(Future<MetadataResponse> future) throws Exception {
            Assert.assertNotNull(future.get());
            latch.countDown();
        }
    });

    Assert.assertTrue("latch not triggered", latch.await(2, TimeUnit.SECONDS));
    controlKafkaChannel.disconnect();
}

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

License:Apache License

@Test
public void test_success() throws Exception {

    String topic = "test_success";

    createTopic(topic, 1);//  w ww .j a v a  2s.co  m
    ProducerProperties properties = new ProducerProperties();
    properties.override(ProducerProperties.NETTY_DEBUG_PIPELINE, true);
    KafkaProducer producer = new KafkaProducer("localhost", START_PORT, topic, properties);
    producer.connect().sync();
    KafkaTopic kafkaTopic = producer.topic();

    final CountDownLatch latch = new CountDownLatch(1);

    final Future send = kafkaTopic.send(null, freeLaterBuffer(TEST_MESSAGE.getBytes()));

    send.addListener(new FutureListener() {
        @Override
        public void operationComplete(Future future) throws Exception {
            if (future.isSuccess()) {
                latch.countDown();
            }
        }
    });

    final List<KafkaStream<byte[], byte[]>> consume = consume(topic);

    final KafkaStream<byte[], byte[]> stream = consume.get(0);
    final ConsumerIterator<byte[], byte[]> messages = stream.iterator();

    Assert.assertThat(TEST_MESSAGE, is(new String(messages.next().message())));
    Assert.assertTrue(latch.await(2, TimeUnit.SECONDS));
    producer.disconnect().sync();
}

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

License:Apache License

@Test
public void test_producer_multi_message() throws Exception {

    String topic = "test_producer_multi_message";
    ProducerProperties properties = new ProducerProperties();
    properties.override(ProducerProperties.NETTY_DEBUG_PIPELINE, true);
    createTopic(topic);/*  w ww.j a  va  2  s .  c  o  m*/

    final CountDownLatch latch = new CountDownLatch(3);
    FutureListener listener = new FutureListener() {
        @Override
        public void operationComplete(Future future) throws Exception {
            if (future.isSuccess()) {
                latch.countDown();
            }
        }
    };

    KafkaProducer producer = new KafkaProducer("localhost", START_PORT, topic, properties);
    producer.connect().sync();
    KafkaTopic kafkaTopic = producer.topic();

    kafkaTopic.send(null, freeLaterBuffer((TEST_MESSAGE + "01").getBytes())).addListener(listener);
    kafkaTopic.send(null, freeLaterBuffer((TEST_MESSAGE + "02").getBytes())).addListener(listener);
    kafkaTopic.send(null, freeLaterBuffer((TEST_MESSAGE + "03").getBytes())).addListener(listener);

    final KafkaStream<byte[], byte[]> stream = consume(topic).get(0);
    final ConsumerIterator<byte[], byte[]> messages = stream.iterator();

    Assert.assertThat(new String(messages.next().message()), is(TEST_MESSAGE + "01"));
    Assert.assertThat(new String(messages.next().message()), is(TEST_MESSAGE + "02"));
    Assert.assertThat(new String(messages.next().message()), is(TEST_MESSAGE + "03"));
    Assert.assertTrue("latch failed", latch.await(2, TimeUnit.SECONDS));
    producer.disconnect().sync();
}

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

License:Apache License

@Test
@Ignore("not sure how to test this one")
public void test_fail() throws Exception {

    String topic = "doesnotexist";

    ProducerProperties properties = new ProducerProperties();
    properties.override(ProducerProperties.NETTY_DEBUG_PIPELINE, true);
    KafkaProducer producer = new KafkaProducer("localhost", START_PORT, topic, properties);
    producer.connect().sync();//from   w  w  w  .  j av a 2  s  . c om
    KafkaTopic kafkaTopic = producer.topic();

    final CountDownLatch latch = new CountDownLatch(1);

    final Future<Void> send = kafkaTopic.send(null, freeLaterBuffer(TEST_MESSAGE.getBytes()));

    send.addListener(new FutureListener<Void>() {
        @Override
        public void operationComplete(Future<Void> future) throws Exception {
            if (!future.isSuccess()) {
                latch.countDown();
            }
        }
    });

    Assert.assertTrue(latch.await(2, TimeUnit.SECONDS));
    producer.disconnect().sync();
}