Example usage for io.netty.channel ChannelFuture cause

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

Introduction

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

Prototype

Throwable cause();

Source Link

Document

Returns the cause of the failed I/O operation if the I/O operation has failed.

Usage

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

License:Apache License

/**
 * After connecting, we check if the connect was successful.
 * //from w  w  w  .j a va  2  s  .  c o  m
 * @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
 */
public void afterConnect(final FutureResponse futureResponse, final Message message,
        final ChannelFuture channelFuture, final boolean fireAndForget) {
    if (channelFuture == null) {
        futureResponse.failed("could not create a " + (message.isUdp() ? "UDP" : "TCP") + " channel");
        return;
    }
    LOG.debug("about to connect to {} with channel {}, ff={}", message.recipient(), channelFuture.channel(),
            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()) {
                final ChannelFuture writeFuture = future.channel().writeAndFlush(message);
                afterSend(writeFuture, futureResponse, fireAndForget);
            } else {
                LOG.debug("Channel creation failed", future.cause());
                futureResponse.failed("Channel creation failed " + future.channel() + "/" + future.cause());
                // may have been closed by the other side,
                // or it may have been canceled from this side
                if (!(future.cause() instanceof CancellationException)
                        && !(future.cause() instanceof ClosedChannelException)
                        && !(future.cause() instanceof ConnectException)) {
                    LOG.warn("Channel creation failed to {} for {}", future.channel(), message);
                }
            }
        }
    });
}

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

License:Apache License

/**
 * After sending, we check if the write was successful or if it was a fire
 * and forget./*from   w  ww  . j  a  va 2s  . co m*/
 * 
 * @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.failedLater(future.cause());
                reportFailed(futureResponse, future.channel().close());
                LOG.warn("Failed to write channel the request {} {}", futureResponse.request(), future.cause());
            }
            if (fireAndForget) {
                futureResponse.responseLater(null);
                LOG.debug("fire and forget, close channel now {}, {}", futureResponse.request(),
                        future.channel());
                reportMessage(futureResponse, future.channel().close());
            }
        }
    });

}

From source file:net.tomp2p.connection.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  ww w . j  a v a  2 s.  c  o  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 = PeerBuilder.createDefaultChannelClientConfiguration();
        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, Pair<EventExecutorGroup, ChannelHandler>> tmp = new HashMap<String, Pair<EventExecutorGroup, 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,
                    new FutureResponse(null));
            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));
}

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

License:Apache License

/**
 * This test only works if the server calls "nc -lku 4000", that is done in @Before.
 * //from  w  ww  .j ava 2 s.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 = PeerBuilder.createDefaultChannelClientConfiguration();
        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, Pair<EventExecutorGroup, ChannelHandler>> tmp = new HashMap<String, Pair<EventExecutorGroup, 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(false, tmp, new FutureResponse(null));
            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.ChannelServer.java

License:Apache License

/**
 * Handles the waiting and returning the channel.
 * //from   ww w  . ja v  a  2s.  c o  m
 * @param future
 *            The future to wait for
 * @return The channel or null if we failed to bind.
 */
private boolean handleFuture(final ChannelFuture future) {
    try {
        future.await();
    } catch (InterruptedException e) {
        if (LOG.isWarnEnabled()) {
            LOG.warn("could not start UPD server", e);
        }
        return false;
    }
    boolean success = future.isSuccess();
    if (success) {
        return true;
    } else {
        future.cause().printStackTrace();
        return false;
    }

}

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  va  2  s.  c o m*/
 * @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.
 * //from w  w  w  . j  av a  2  s. c o m
 * @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.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 a 2 s .  c  o  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));
}

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  www  .  j a  v  a  2s.  com*/
 * @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:org.acmsl.katas.antlr4netty.InterpreterServer.java

License:Open Source License

/**
 * Wraps given {@link ChannelFuture} to ensure the event loops
 * shut down gracefully./*from  w  w  w.  j av  a 2s. c o  m*/
 * @param target the original channel future.
 * @param bossGroup the boss group.
 * @param workerGroup the worker group.
 * @return the wrapped future.
 */
@NotNull
protected ChannelFuture wrap(@NotNull final ChannelFuture target, @NotNull final NioEventLoopGroup bossGroup,
        @NotNull final NioEventLoopGroup workerGroup) {
    return new ChannelFuture() {
        @Override
        public Channel channel() {
            return target.channel();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ChannelFuture addListener(
                @NotNull final GenericFutureListener<? extends Future<? super Void>> listener) {
            return target.addListener(listener);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ChannelFuture addListeners(
                @NotNull final GenericFutureListener<? extends Future<? super Void>>... listeners) {
            return target.addListeners(listeners);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ChannelFuture removeListener(
                @NotNull final GenericFutureListener<? extends Future<? super Void>> listener) {
            return target.removeListener(listener);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ChannelFuture removeListeners(
                @NotNull final GenericFutureListener<? extends Future<? super Void>>... listeners) {
            return target.removeListeners(listeners);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ChannelFuture sync() throws InterruptedException {
            ChannelFuture result = null;

            try {
                result = target.sync();
            } finally {
                workerGroup.shutdownGracefully();
                bossGroup.shutdownGracefully();
            }

            return result;
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ChannelFuture syncUninterruptibly() {
            return target.syncUninterruptibly();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ChannelFuture await() throws InterruptedException {
            return target.await();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public ChannelFuture awaitUninterruptibly() {
            return target.awaitUninterruptibly();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean isSuccess() {
            return target.isSuccess();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean isCancellable() {
            return target.isCancellable();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public Throwable cause() {
            return target.cause();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean await(final long timeout, @NotNull final TimeUnit unit) throws InterruptedException {
            return target.await(timeout, unit);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean await(final long timeoutMillis) throws InterruptedException {
            return target.await(timeoutMillis);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean awaitUninterruptibly(final long timeout, @NotNull final TimeUnit unit) {
            return target.awaitUninterruptibly(timeout, unit);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean awaitUninterruptibly(final long timeoutMillis) {
            return target.awaitUninterruptibly(timeoutMillis);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public Void getNow() {
            return target.getNow();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean cancel(final boolean mayInterruptIfRunning) {
            return target.cancel(mayInterruptIfRunning);
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean isCancelled() {
            return target.isCancelled();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public boolean isDone() {
            return target.isDone();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public Void get() throws InterruptedException, ExecutionException {
            return target.get();
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public Void get(final long timeout, @NotNull final TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            return target.get(timeout, unit);
        }
    };
}