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:net.tomp2p.connection2.TestChannelCreator.java

License:Apache License

/**
 * This test only works if the server calls "nc -lku 4000", that is done in @Before.
 * //from  w w  w.  j av a2s .  c o  m
 * @throws InterruptedException .
 */
@Test
@Ignore
public void testCreatorUDP() throws InterruptedException {
    long start = System.currentTimeMillis();
    final int rounds = 10000;
    final int connections = 20;
    final int printOut = 100;
    EventLoopGroup ev = new NioEventLoopGroup();

    for (int j = 0; j < rounds; j++) {

        ChannelClientConfiguration c = new ChannelClientConfiguration();
        c.pipelineFilter(new MyPipeLine());
        final ChannelCreator channelCreator2 = new ChannelCreator(ev, new FutureDone<Void>(), connections, 0,
                c);

        if (j % printOut == 0) {
            System.out.print(j + " ");
        }

        final CountDownLatch countDownLatch = new CountDownLatch(connections);
        final Map<String, ChannelHandler> tmp = new HashMap<String, ChannelHandler>();

        GenericFutureListener<ChannelFuture> handler = new GenericFutureListener<ChannelFuture>() {
            @Override
            public void operationComplete(final ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    future.channel().writeAndFlush(Unpooled.wrappedBuffer(new byte[1]));
                    future.channel().close();
                    countDownLatch.countDown();
                } else {
                    future.cause().printStackTrace();
                }
            }
        };

        for (int i = 0; i < connections; i++) {
            final ChannelFuture channelFuture = channelCreator2.createUDP(SOCKET_ADDRESS, false, tmp);
            channelFuture.addListener(handler);
        }
        countDownLatch.await();
        channelCreator2.shutdown().awaitUninterruptibly();
    }
    ev.shutdownGracefully().awaitUninterruptibly();
    long time = System.currentTimeMillis() - start;
    long mil = TimeUnit.SECONDS.toMillis(1);
    System.err.println("\nBENCHMARK: opened and closed " + connections + " x " + rounds
            + " UDP connections to localhost in " + time + " ms. STAT: UDP open/close per sec:"
            + ((connections * rounds * mil) / time));
}

From source file:net.tomp2p.connection2.TestReservation.java

License:Apache License

/**
 * Test the TCP connection reservation./*  ww w .j  av  a 2  s  .  c  o  m*/
 * 
 * @throws InterruptedException .
 */
@Test
public void testReservationTCP() throws InterruptedException {
    EventLoopGroup ev = new NioEventLoopGroup();
    long start = System.currentTimeMillis();
    final int round = 10;
    final int inner = 200;
    final int conn = 50;
    final int tcpMax = 1000;
    for (int i = 0; i < round; i++) {
        ChannelClientConfiguration c = new ChannelClientConfiguration();
        c.maxPermitsTCP(tcpMax);
        c.pipelineFilter(new MyPipeLine());
        Reservation r = new Reservation(ev, c);
        List<FutureChannelCreator> fcc = new ArrayList<FutureChannelCreator>();
        for (int j = 0; j < inner; j++) {
            FutureChannelCreator fc = r.create(0, conn);
            fc.addListener(new BaseFutureAdapter<FutureChannelCreator>() {
                @Override
                public void operationComplete(final FutureChannelCreator future) throws Exception {
                    final ChannelCreator cc = future.getChannelCreator();
                    final int timeout = 2000;
                    final CountDownLatch countDownLatch = new CountDownLatch(conn);
                    for (int k = 0; k < conn; k++) {
                        ChannelFuture channelFuture = cc.createTCP(SOCKET_ADDRESS, timeout,
                                new HashMap<String, ChannelHandler>());
                        channelFuture.addListener(new GenericFutureListener<ChannelFuture>() {
                            @Override
                            public void operationComplete(final ChannelFuture future) throws Exception {
                                future.channel().close();
                                countDownLatch.countDown();
                            }
                        });
                    }
                    countDownLatch.await();
                    cc.shutdown().awaitUninterruptibly();
                }
            });
            fcc.add(fc);
        }
        for (FutureChannelCreator fcc1 : fcc) {
            fcc1.awaitListeners();
        }
        r.shutdown().awaitUninterruptibly();
    }
    ev.shutdownGracefully().awaitUninterruptibly();
    long time = System.currentTimeMillis() - start;
    long mil = TimeUnit.SECONDS.toMillis(1);
    System.err.println("BENCHMARK: opened and closed " + round + " x " + inner + " x " + conn
            + " TCP connections to localhost in " + time + " ms. STAT: TCP res open/close per sec:"
            + ((round * inner * conn * mil) / time));
}

From source file:net.tomp2p.connection2.TestReservation.java

License:Apache License

/**
 * Test the TCP connection reservation.//  w ww. j a va 2s.c  o m
 * 
 * @throws InterruptedException .
 */
@Test
public void testReservationUDP() throws InterruptedException {
    EventLoopGroup ev = new NioEventLoopGroup();
    long start = System.currentTimeMillis();
    final int round = 10;
    final int inner = 200;
    final int conn = 50;
    final int udpMax = 1000;
    for (int i = 0; i < round; i++) {
        ChannelClientConfiguration c = new ChannelClientConfiguration();
        c.pipelineFilter(new MyPipeLine());
        c.maxPermitsUDP(udpMax);
        Reservation r = new Reservation(ev, c);
        List<FutureChannelCreator> fcc = new ArrayList<FutureChannelCreator>();
        for (int j = 0; j < inner; j++) {
            FutureChannelCreator fc = r.create(conn, 0);
            fc.addListener(new BaseFutureAdapter<FutureChannelCreator>() {
                @Override
                public void operationComplete(final FutureChannelCreator future) throws Exception {
                    final ChannelCreator cc = future.getChannelCreator();
                    final CountDownLatch countDownLatch = new CountDownLatch(conn);
                    for (int k = 0; k < conn; k++) {
                        ChannelFuture channelFuture = cc.createUDP(SOCKET_ADDRESS, false,
                                new HashMap<String, ChannelHandler>() {
                                });
                        channelFuture.addListener(new GenericFutureListener<ChannelFuture>() {
                            @Override
                            public void operationComplete(final ChannelFuture future) throws Exception {
                                future.channel().writeAndFlush(Unpooled.wrappedBuffer(new byte[1]));
                                future.channel().close();
                                countDownLatch.countDown();
                            }
                        });
                    }
                    countDownLatch.await();
                    cc.shutdown().awaitUninterruptibly();
                }
            });
            fcc.add(fc);
        }
        for (FutureChannelCreator fcc1 : fcc) {
            fcc1.awaitListeners();
        }
        r.shutdown().awaitUninterruptibly();
    }
    ev.shutdownGracefully().awaitUninterruptibly();
    long time = System.currentTimeMillis() - start;
    long mil = TimeUnit.SECONDS.toMillis(1);
    System.err.println("BENCHMARK: opened and closed " + round + " x " + inner + " x " + conn
            + " UDP connections to localhost in " + time + " ms. STAT: UDP res open/close per sec:"
            + ((round * inner * conn * mil) / time));
}

From source file:net.tomp2p.connection2.TestReservation.java

License:Apache License

/**
 * Test an unclean shutdown, that means the reservation is shutdown, but the connectioncreation is not.
 * // www  .j av a 2 s . c  o m
 * @throws InterruptedException .
 */
@Test
public void testReservationTCPNonCleanShutdown() throws InterruptedException {
    EventLoopGroup ev = new NioEventLoopGroup();
    long start = System.currentTimeMillis();
    final int round = 50;
    final int inner = 100;
    final int conn = 10;
    final int tcpMax = 1000;
    for (int i = 0; i < round; i++) {
        ChannelClientConfiguration c = new ChannelClientConfiguration();
        c.pipelineFilter(new MyPipeLine());
        c.maxPermitsTCP(tcpMax);
        Reservation r = new Reservation(ev, c);
        List<FutureChannelCreator> fcc = new ArrayList<FutureChannelCreator>();
        for (int j = 0; j < inner; j++) {
            FutureChannelCreator fc = r.create(0, conn);
            fc.addListener(new BaseFutureAdapter<FutureChannelCreator>() {
                @Override
                public void operationComplete(final FutureChannelCreator future) throws Exception {
                    if (future.isFailed()) {
                        return;
                    }
                    final ChannelCreator cc = future.getChannelCreator();
                    final int timeout = 2000;
                    for (int k = 0; k < conn; k++) {
                        ChannelFuture channelFuture = cc.createTCP(SOCKET_ADDRESS, timeout,
                                new HashMap<String, ChannelHandler>() {
                                });
                        if (channelFuture == null) {
                            return;
                        }
                        channelFuture.addListener(new GenericFutureListener<ChannelFuture>() {
                            @Override
                            public void operationComplete(final ChannelFuture future) throws Exception {
                                future.channel().close();
                            }
                        });
                    }
                }
            });
            fcc.add(fc);
        }
        for (FutureChannelCreator fcc1 : fcc) {
            fcc1.awaitListeners();
        }
        r.shutdown().awaitUninterruptibly();
    }
    ev.shutdownGracefully().awaitUninterruptibly();
    long time = System.currentTimeMillis() - start;
    long mil = TimeUnit.SECONDS.toMillis(1);
    System.err.println("BENCHMARK: opened and closed " + round + " x " + inner + " x " + conn
            + " TCP connections to localhost in " + time + " ms. STAT: TCP unclean open/close per sec:"
            + ((round * inner * conn * mil) / time));
}

From source file:net.tomp2p.connection2.TestReservation.java

License:Apache License

/**
 * Unclean shutdown of pending connections.
 * /*w w  w .  j  av a 2s.  c  o  m*/
 * @throws InterruptedException .
 */
@Test
public void testReservationTCPNonCleanShutdown2() throws InterruptedException {
    EventLoopGroup ev = new NioEventLoopGroup();
    final int round = 50;
    final int inner = 100;
    final int conn = 10;
    final int tcpMax = 1000;
    for (int i = 0; i < round; i++) {
        ChannelClientConfiguration c = new ChannelClientConfiguration();
        c.pipelineFilter(new MyPipeLine());
        c.maxPermitsTCP(tcpMax);
        Reservation r = new Reservation(ev, c);
        List<FutureChannelCreator> fcc = new ArrayList<FutureChannelCreator>();
        for (int j = 0; j < inner; j++) {
            FutureChannelCreator fc = r.create(0, conn);
            fc.addListener(new BaseFutureAdapter<FutureChannelCreator>() {
                @Override
                public void operationComplete(final FutureChannelCreator future) throws Exception {
                    if (future.isFailed()) {
                        return;
                    }
                    final ChannelCreator cc = future.getChannelCreator();
                    final int timeout = 2000;
                    for (int k = 0; k < conn; k++) {
                        ChannelFuture channelFuture = cc.createTCP(SOCKET_ADDRESS, timeout,
                                new HashMap<String, ChannelHandler>() {
                                });
                        if (channelFuture == null) {
                            return;
                        }
                        channelFuture.addListener(new GenericFutureListener<ChannelFuture>() {
                            @Override
                            public void operationComplete(final ChannelFuture future) throws Exception {
                                future.channel().close();
                            }
                        });
                    }
                }
            });
            fcc.add(fc);
        }
        r.shutdown().awaitUninterruptibly();
    }
    ev.shutdownGracefully().awaitUninterruptibly();
}

From source file:net.tomp2p.rpc.PingRPC.java

License:Apache License

/**
 * Ping a peer, and request the other peer to return the source port of our
 * socket used to send the message. This method needs to do the setup of a
 * ChannelFuture manually since we need to know the port number of the
 * assigned socket./*from  ww w  .  java  2 s.c  om*/
 * 
 * @param remotePeer
 *            The destination peer
 * @param channelCreator
 *            The channel creator where we create a UPD channel
 * @return The future that will be triggered when we receive an answer or
 *         something fails.
 */
public FutureDone<List<PeerSocketAddress>> pingNATType(final PeerAddress remotePeer,
        final ChannelCreator channelCreator, final ConnectionConfiguration configuration, final Peer peer) {
    final FutureDone<List<PeerSocketAddress>> fDone = new FutureDone<List<PeerSocketAddress>>();
    final List<PeerSocketAddress> peerSocketAddresses = new ArrayList<PeerSocketAddress>(2);
    final Message message = createMessage(remotePeer, RPC.Commands.PING.getNr(), Type.REQUEST_5);
    final FutureResponse futureResponse = new FutureResponse(message);
    final SimpleChannelInboundHandler<Message> inbound = new SimpleChannelInboundHandler<Message>() {

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, Message msg) throws Exception {
            if (!msg.peerSocketAddresses().isEmpty() && msg.type() == Type.OK) {
                peerSocketAddresses.add(msg.peerSocketAddresses().get(0));
                fDone.done(peerSocketAddresses);
                ctx.close();
            }
        }
    };
    Utils.addReleaseListener(channelCreator, futureResponse);
    final ChannelFuture cF = channelCreator.createUDP(false,
            peer.connectionBean().sender().configureHandlers(inbound, futureResponse, 30, false),
            futureResponse);
    cF.addListener(new GenericFutureListener<ChannelFuture>() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                InetSocketAddress srcAddress = (InetSocketAddress) future.channel().localAddress();
                peerSocketAddresses.add(new PeerSocketAddress(srcAddress.getAddress(), srcAddress.getPort(),
                        srcAddress.getPort()));
                peer.connectionBean().sender().afterConnect(futureResponse, message, future, false);
            }
        }
    });
    return fDone;
}

From source file:net.wessendorf.microprofile.service.PushSender.java

License:Apache License

public void sendPushs(final String payload) {

    final List<String> tokens = TokenDB.loadDeviceTokens();
    final String pushJobID = UUID.randomUUID().toString();

    ApnsClient apnsClient = null;/*  www  .  j a v a 2  s .co  m*/
    {
        try {
            apnsClient = receiveApnsConnection("net.wessendorf.something");
        } catch (IllegalArgumentException iae) {
            logger.error(iae.getMessage(), iae);
        }
    }

    if (apnsClient.isConnected()) {

        for (final String token : tokens) {

            final SimpleApnsPushNotification pushNotification = new SimpleApnsPushNotification(token,
                    "net.wessendorf.something", payload);
            final Future<PushNotificationResponse<SimpleApnsPushNotification>> notificationSendFuture = apnsClient
                    .sendNotification(pushNotification);

            notificationSendFuture.addListener(
                    new GenericFutureListener<Future<? super PushNotificationResponse<SimpleApnsPushNotification>>>() {
                        @Override
                        public void operationComplete(
                                Future<? super PushNotificationResponse<SimpleApnsPushNotification>> future)
                                throws Exception {

                            // we could submit "something" to APNs
                            if (future.isSuccess()) {
                                handlePushNotificationResponsePerToken(pushJobID, notificationSendFuture.get());
                            }
                        }
                    });
        }

    } else {
        logger.error("Unable to send notifications, client is not connected");
    }
}

From source file:net.wessendorf.microprofile.service.PushSender.java

License:Apache License

private ApnsClient receiveApnsConnection(final String topic) {
    return simpleApnsClientCache.getApnsClientForVariant(topic, new ServiceConstructor<ApnsClient>() {
        @Override/*w ww.j  a  v  a2s .c  o  m*/
        public ApnsClient construct() {

            final ApnsClient apnsClient = buildApnsClient();

            // connect and wait:
            connectToDestinations(apnsClient);

            // APNS client has auto-reconnect, but let's log when that happens
            apnsClient.getReconnectionFuture().addListener(new GenericFutureListener<Future<? super Void>>() {
                @Override
                public void operationComplete(Future<? super Void> future) throws Exception {
                    logger.trace("Reconnecting to APNs");
                }
            });
            return apnsClient;
        }
    });
}

From source file:netty.protocol.http.xml.server.HttpXmlServerHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpXmlRequest msg) throws Exception {
    HttpRequest request = msg.getRequest();
    Order order = (Order) msg.getBody();
    System.out.println("Http server receive request : " + order);
    dobusiness(order);//from w  ww .  j  a v  a 2 s. c  om
    ChannelFuture future = ctx.writeAndFlush(new HttpXmlResponse(null, order));
    if (!isKeepAlive(request)) {
        future.addListener(new GenericFutureListener<Future<? super Void>>() {
            public void operationComplete(Future future) throws Exception {
                ctx.close();
            }
        });
    }
}

From source file:org.apache.bookkeeper.proto.BookieRequestProcessor.java

License:Apache License

private void processStartTLSRequestV3(final BookkeeperProtocol.Request r, final Channel c) {
    BookkeeperProtocol.Response.Builder response = BookkeeperProtocol.Response.newBuilder();
    BookkeeperProtocol.BKPacketHeader.Builder header = BookkeeperProtocol.BKPacketHeader.newBuilder();
    header.setVersion(BookkeeperProtocol.ProtocolVersion.VERSION_THREE);
    header.setOperation(r.getHeader().getOperation());
    header.setTxnId(r.getHeader().getTxnId());
    response.setHeader(header.build());//from  w w w.j  a  v a2  s  .c o  m
    if (shFactory == null) {
        LOG.error("Got StartTLS request but TLS not configured");
        response.setStatus(BookkeeperProtocol.StatusCode.EBADREQ);
        c.writeAndFlush(response.build());
    } else {
        // there is no need to execute in a different thread as this operation is light
        SslHandler sslHandler = shFactory.newTLSHandler();
        c.pipeline().addFirst("tls", sslHandler);

        response.setStatus(BookkeeperProtocol.StatusCode.EOK);
        BookkeeperProtocol.StartTLSResponse.Builder builder = BookkeeperProtocol.StartTLSResponse.newBuilder();
        response.setStartTLSResponse(builder.build());
        sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() {
            @Override
            public void operationComplete(Future<Channel> future) throws Exception {
                // notify the AuthPlugin the completion of the handshake, even in case of failure
                AuthHandler.ServerSideHandler authHandler = c.pipeline()
                        .get(AuthHandler.ServerSideHandler.class);
                authHandler.authProvider.onProtocolUpgrade();
                if (future.isSuccess()) {
                    LOG.info("Session is protected by: {}", sslHandler.engine().getSession().getCipherSuite());
                } else {
                    LOG.error("TLS Handshake failure: {}", future.cause());
                    BookkeeperProtocol.Response.Builder errResponse = BookkeeperProtocol.Response.newBuilder()
                            .setHeader(r.getHeader()).setStatus(BookkeeperProtocol.StatusCode.EIO);
                    c.writeAndFlush(errResponse.build());
                    if (statsEnabled) {
                        bkStats.getOpStats(BKStats.STATS_UNKNOWN).incrementFailedOps();
                    }
                }
            }
        });
        c.writeAndFlush(response.build());
    }
}