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.ChannelCreator.java

License:Apache License

/**
 * Shutdown this channel creator. This means that no TCP or UDP connection can be established.
 * // w w  w  .ja  v a2  s .co m
 * @return The shutdown future.
 */
public FutureDone<Void> shutdown() {
    // set shutdown flag for UDP and TCP, if we acquire a write lock, all read locks are blocked as well
    writeUDP.lock();
    writeTCP.lock();
    try {
        if (shutdownTCP || shutdownUDP) {
            shutdownFuture().setFailed("already shutting down");
            return shutdownFuture();
        }
        shutdownUDP = true;
        shutdownTCP = true;
    } finally {
        writeTCP.unlock();
        writeUDP.unlock();
    }

    recipients.close().addListener(new GenericFutureListener<ChannelGroupFuture>() {
        @Override
        public void operationComplete(final ChannelGroupFuture future) throws Exception {
            if (!semaphoreUPD.tryAcquire(maxPermitsUDP)) {
                LOG.error("Cannot shutdown, as connections (UDP) are still alive");
                shutdownFuture().setFailed("Cannot shutdown, as connections (UDP) are still alive");
                throw new RuntimeException("Cannot shutdown, as connections (UDP) are still alive");
            }
            if (!semaphoreTCP.tryAcquire(maxPermitsTCP)) {
                LOG.error("Cannot shutdown, as connections (TCP) are still alive");
                shutdownFuture().setFailed("Cannot shutdown, as connections (TCP) are still alive");
                throw new RuntimeException("Cannot shutdown, as connections (TCP) are still alive");
            }
            shutdownFuture().setDone();
        }
    });
    return shutdownFuture();
}

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

License:Apache License

/**
 * Shuts down the server./*from   w  w  w  . j  a v  a2  s . co  m*/
 * 
 * @return The future when the shutdown is complete. This includes the worker and boss event loop
 */
public FutureDone<Void> shutdown() {
    LOG.debug("shutdown UPD server");
    channelUDP.close().addListener(new GenericFutureListener<ChannelFuture>() {
        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {
            LOG.debug("shutdown TCP server");
            channelTCP.close().addListener(new GenericFutureListener<ChannelFuture>() {
                @SuppressWarnings({ "unchecked", "rawtypes" })
                @Override
                public void operationComplete(final ChannelFuture future) throws Exception {
                    LOG.debug("shutdown TCP workergroup");
                    workerGroup.shutdownGracefully(0, 0, TimeUnit.SECONDS)
                            .addListener(new GenericFutureListener() {
                                @Override
                                public void operationComplete(final Future future) throws Exception {
                                    LOG.debug("shutdown TCP workergroup done!");
                                    bossGroup.shutdownGracefully(0, 0, TimeUnit.SECONDS)
                                            .addListener(new GenericFutureListener() {
                                                @Override
                                                public void operationComplete(final Future future)
                                                        throws Exception {
                                                    futureServerDone.setDone();
                                                }
                                            });
                                }
                            });
                }
            });
        }
    });
    return shutdownFuture();
}

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

License:Apache License

/**
 * Shutdown the peer. If the peer is a master, then also the connections and the server will be closed, otherwise
 * its just de-registering.//  ww  w  . j a va 2  s  . com
 * 
 * @return The future when the shutdown is complete
 */
public FutureDone<Void> shutdown() {
    if (master) {
        LOG.debug("shutdown in progress...");
    }
    // de-register in dispatcher
    connectionBean.dispatcher().removeIoHandler(peerBean().serverPeerAddress().getPeerId());
    // shutdown running tasks for this peer
    if (peerBean.maintenanceTask() != null) {
        peerBean.maintenanceTask().cancel();
    }
    if (peerBean.replicationExecutor() != null) {
        peerBean.replicationExecutor().cancel();
    }
    // shutdown all children
    if (!master) {
        for (PeerCreator peerCreator : childConnections) {
            peerCreator.shutdown();
        }
        return shutdownFuture().setDone();
    }
    //shutdown the timer
    connectionBean.timer().cancel();
    // we have two things to shut down: the server that listens for incoming connections and the connection creator
    // that establishes connections
    final int maxListeners = 2;
    final AtomicInteger listenerCounter = new AtomicInteger(0);
    LOG.debug("starting shutdown done in client...");
    connectionBean.reservation().shutdown().addListener(new BaseFutureAdapter<FutureDone<Void>>() {
        @SuppressWarnings({ "unchecked", "rawtypes" })
        @Override
        public void operationComplete(final FutureDone<Void> future) throws Exception {
            workerGroup.shutdownGracefully(0, 0, TimeUnit.SECONDS).addListener(new GenericFutureListener() {
                @Override
                public void operationComplete(final Future future) throws Exception {
                    LOG.debug("shutdown done in client...");
                    if (listenerCounter.incrementAndGet() == maxListeners) {
                        shutdownFuture().setDone();
                    }
                }
            });
        }
    });
    LOG.debug("starting shutdown done in server...");
    connectionBean.channelServer().shutdown().addListener(new BaseFutureAdapter<FutureDone<Void>>() {
        @Override
        public void operationComplete(final FutureDone<Void> future) throws Exception {
            LOG.debug("shutdown done in server...");
            if (listenerCounter.incrementAndGet() == maxListeners) {
                shutdownFuture().setDone();
            }
        }
    });
    connectionBean.natUtils().shutdown();
    return shutdownFuture();
}

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

License:Apache License

/**
 * Report a successful response after the channel was closed.
 * /* w  w w.  j  a v a  2s .  c o  m*/
 * @param close
 *            The close future
 * @param responseMessage
 *            The response message
 */
private void reportMessage(final ChannelFuture close, final Message2 responseMessage) {
    close.addListener(new GenericFutureListener<ChannelFuture>() {
        @Override
        public void operationComplete(final ChannelFuture arg0) throws Exception {
            LOG.debug("report success {}", responseMessage);
            //trigger the notify when we closed the channel.
            futureResponse.setResponseNow();
        }
    });
}

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

License:Apache License

/**
 * Report a failure after the channel was closed.
 * //from www.  j a va2 s. c  om
 * @param close
 *            The close future
 */
private void reportFailed(final ChannelFuture close) {
    close.addListener(new GenericFutureListener<ChannelFuture>() {
        @Override
        public void operationComplete(final ChannelFuture arg0) throws Exception {
            futureResponse.setResponseNow();
        }
    });
}

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

License:Apache License

/**
 * After connecting, we check if the connect was successful.
 * //from w  ww. j a  v a  2 s  .c om
 * @param futureResponse
 *            The future to set the response
 * @param message
 *            The message to send
 * @param channelFuture
 *            the future of the connect
 * @param fireAndForget
 *            True, if we don't expect a message
 */
private void afterConnect(final FutureResponse futureResponse, final Message2 message,
        final ChannelFuture channelFuture, final boolean fireAndForget) {
    final Cancel connectCancel = createCancel(channelFuture);
    futureResponse.addCancel(connectCancel);
    channelFuture.addListener(new GenericFutureListener<ChannelFuture>() {
        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {
            futureResponse.removeCancel(connectCancel);
            if (future.isSuccess()) {
                futureResponse.setProgressHandler(new ProgresHandler() {
                    @Override
                    public void progres() {
                        final ChannelFuture writeFuture = future.channel().writeAndFlush(message);
                        afterSend(writeFuture, futureResponse, fireAndForget);
                    }
                });
                // this needs to be called first before all other progress
                futureResponse.progressFirst();
            } else {
                futureResponse.setFailed("Channel creation failed " + future.cause());
                LOG.warn("Channel creation failed ", future.cause());
            }
        }
    });
}

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

License:Apache License

/**
 * After sending, we check if the write was successful or if it was a fire and forget.
 * /*  w  ww .j a va  2 s.c om*/
 * @param writeFuture
 *            The future of the write operation. Can be UDP or TCP
 * @param futureResponse
 *            The future to set the response
 * @param fireAndForget
 *            True, if we don't expect a message
 */
private void afterSend(final ChannelFuture writeFuture, final FutureResponse futureResponse,
        final boolean fireAndForget) {
    final Cancel writeCancel = createCancel(writeFuture);
    writeFuture.addListener(new GenericFutureListener<ChannelFuture>() {

        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {
            futureResponse.removeCancel(writeCancel);
            if (!future.isSuccess()) {
                futureResponse.setFailedLater(future.cause());
                reportFailed(futureResponse, future.channel().close());
                LOG.warn("Failed to write channel the request {}", futureResponse.getRequest(), future.cause());

            }
            if (fireAndForget) {
                futureResponse.setResponseLater(null);
                LOG.debug("fire and forget, close channel now");
                reportMessage(futureResponse, future.channel().close());
            }
        }
    });

}

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

License:Apache License

/**
 * Report a failure after the channel was closed.
 * /*  w w w .ja  v a2 s .  c o m*/
 * @param futureResponse
 *            The future to set the response
 * @param close
 *            The close future
 * @param cause
 *            The response message
 */
private void reportFailed(final FutureResponse futureResponse, final ChannelFuture close) {
    close.addListener(new GenericFutureListener<ChannelFuture>() {
        @Override
        public void operationComplete(final ChannelFuture arg0) throws Exception {
            futureResponse.setResponseNow();
        }
    });
}

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

License:Apache License

/**
 * Report a successful response after the channel was closed.
 * /*from   w w w. j ava2s. c  o  m*/
 * @param futureResponse
 *            The future to set the response
 * @param close
 *            The close future
 * @param responseMessage
 *            The response message
 */
private void reportMessage(final FutureResponse futureResponse, final ChannelFuture close) {
    close.addListener(new GenericFutureListener<ChannelFuture>() {
        @Override
        public void operationComplete(final ChannelFuture arg0) throws Exception {
            futureResponse.setResponseNow();
        }
    });
}

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

License:Apache License

/**
 * This test only works if the server calls "nc -lk 4000", that is done in @Before. It will open and close 1000 *
 * 1000 connections to localhost./*from w  ww.  j a  v  a2 s.co  m*/
 * 
 * @throws InterruptedException .
 */
@Test
@Ignore
public void testCreatorTCP() throws InterruptedException {
    long start = System.currentTimeMillis();
    final int rounds = 10000;
    final int connections = 20;
    final int printOut = 100;
    EventLoopGroup ev = new NioEventLoopGroup();

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

        ChannelClientConfiguration c = new ChannelClientConfiguration();
        c.pipelineFilter(new MyPipeLine());

        final ChannelCreator channelCreator2 = new ChannelCreator(ev, new FutureDone<Void>(), 0, connections,
                c);
        if (j % printOut == 0) {
            System.out.print(j + " ");
        }

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

        final GenericFutureListener<ChannelFuture> handler = new GenericFutureListener<ChannelFuture>() {
            @Override
            public void operationComplete(final ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    future.channel().close();
                    countDownLatch.countDown();

                } else {
                    future.cause().printStackTrace();
                }
            }
        };

        for (int i = 0; i < connections; i++) {
            final ChannelFuture channelFuture = channelCreator2.createTCP(SOCKET_ADDRESS, timeout, 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
            + " TCP connections to localhost in " + time + " ms. STAT: TCP open/close per sec:"
            + ((connections * rounds * mil) / time));
}