Example usage for io.netty.channel ChannelFuture await

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

Introduction

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

Prototype

@Override
    ChannelFuture await() throws InterruptedException;

Source Link

Usage

From source file:net.mms_projects.copy_it.server.Main.java

License:Open Source License

public static void main(String[] args) throws Exception {
    if (args.length > 0) {
        if ("generate-pages".equals(args[0])) {
            new Config(new File((args.length > 1 ? args[1] : "copyit.config")));
            System.exit(PageGenerator.generate() ? 0 : 1);
        } else/*  w w  w. j  av a 2  s . c om*/
            new Config(new File(args[0]));
    } else
        new Config(new File("copyit.config"));
    if (PageGenerator.checkPages()) {
        Messages.printWarning("Outdated pages detected! Updating them now!");
        PageGenerator.generate();
    }
    printPid();
    new DatabasePool(MySQL.class, Config.getMaxConnectionsDatabasePool());
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        Signal.handle(new Signal("USR2"), new SignalHandler() {
            public void handle(Signal signal) {
                FileCache.clear();
                Messages.printOK("Cleared file cache.");
            }
        });
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new Initializer());
        ChannelFuture channelFuture = b.bind(Config.getHTTPAPIPort());
        if (channelFuture.await().isSuccess()) {
            Messages.printOK("Bound to port " + Config.getHTTPAPIPort());
            Page.initPages();
            Channel channel = channelFuture.sync().channel();
            channel.closeFuture().sync();
        } else
            Messages.printError("Failed to listen on " + Config.getHTTPAPIPort());
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

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

License:Apache License

/**
 * Handles the waiting and returning the channel.
 * // www.  j  av a  2  s. 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 {
        LOG.debug("binding not successful", future.cause());
        return false;
    }

}

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

License:Apache License

/**
 * Handles the waiting and returning the channel.
 * /*from w w  w .ja v a2  s.  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: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  a  v a2  s . 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);
        }
    };
}

From source file:org.apache.flink.runtime.io.network.netty.ClientTransportErrorHandlingTest.java

License:Apache License

/**
 * Verifies that failed client requests via {@link PartitionRequestClient} are correctly
 * attributed to the respective {@link RemoteInputChannel}.
 *//*from w  w  w.  j  a  v  a 2  s. c om*/
@Test
public void testExceptionOnWrite() throws Exception {

    NettyProtocol protocol = new NettyProtocol() {
        @Override
        public ChannelHandler[] getServerChannelHandlers() {
            return new ChannelHandler[0];
        }

        @Override
        public ChannelHandler[] getClientChannelHandlers() {
            return new PartitionRequestProtocol(mock(ResultPartitionProvider.class),
                    mock(TaskEventDispatcher.class), mock(NetworkBufferPool.class)).getClientChannelHandlers();
        }
    };

    // We need a real server and client in this test, because Netty's EmbeddedChannel is
    // not failing the ChannelPromise of failed writes.
    NettyServerAndClient serverAndClient = initServerAndClient(protocol, createConfig());

    Channel ch = connect(serverAndClient);

    PartitionRequestClientHandler handler = getClientHandler(ch);

    // Last outbound handler throws Exception after 1st write
    ch.pipeline().addFirst(new ChannelOutboundHandlerAdapter() {
        int writeNum = 0;

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

            if (writeNum >= 1) {
                throw new RuntimeException("Expected test exception.");
            }

            writeNum++;
            ctx.write(msg, promise);
        }
    });

    PartitionRequestClient requestClient = new PartitionRequestClient(ch, handler, mock(ConnectionID.class),
            mock(PartitionRequestClientFactory.class));

    // Create input channels
    RemoteInputChannel[] rich = new RemoteInputChannel[] { createRemoteInputChannel(),
            createRemoteInputChannel() };

    final CountDownLatch sync = new CountDownLatch(1);

    // Do this with explicit synchronization. Otherwise this is not robust against slow timings
    // of the callback (e.g. we cannot just verify that it was called once, because there is
    // a chance that we do this too early).
    doAnswer(new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            sync.countDown();
            return null;
        }
    }).when(rich[1]).onError(isA(LocalTransportException.class));

    // First request is successful
    ChannelFuture f = requestClient.requestSubpartition(new ResultPartitionID(), 0, rich[0], 0);
    assertTrue(f.await().isSuccess());

    // Second request is *not* successful
    f = requestClient.requestSubpartition(new ResultPartitionID(), 0, rich[1], 0);
    assertFalse(f.await().isSuccess());

    // Only the second channel should be notified about the error
    verify(rich[0], times(0)).onError(any(LocalTransportException.class));

    // Wait for the notification
    if (!sync.await(TestingUtils.TESTING_DURATION().toMillis(), TimeUnit.MILLISECONDS)) {
        fail("Timed out after waiting for " + TestingUtils.TESTING_DURATION().toMillis()
                + " ms to be notified about the channel error.");
    }

    shutdown(serverAndClient);
}

From source file:org.codice.alliance.distribution.sdk.video.stream.mpegts.MpegTsUdpClient.java

License:Open Source License

private static void transmit(Channel ch, byte[] buf, String ip, int port) throws InterruptedException {
    ChannelFuture cf = ch
            .writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(buf), new InetSocketAddress(ip, port)));
    cf.await();
}

From source file:org.conscrypt.testing.NettyServer.java

License:Apache License

public void start() {
    group = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    b.group(group);/*from  w  ww . j a v  a 2 s .c o m*/
    b.channel(NioServerSocketChannel.class);
    b.option(SO_BACKLOG, 128);
    b.childOption(SO_KEEPALIVE, true);
    b.childHandler(new ChannelInitializer<Channel>() {
        @Override
        public void initChannel(final Channel ch) throws Exception {
            SslContext context = TestUtil.newNettyServerContext(cipher);
            SSLEngine sslEngine = context.newEngine(ch.alloc());
            ch.pipeline().addFirst(new SslHandler(sslEngine));
            ch.pipeline().addLast(new MessageDecoder());
        }
    });
    // Bind and start to accept incoming connections.
    ChannelFuture future = b.bind(port);
    try {
        future.await();
    } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
        throw new RuntimeException("Interrupted waiting for bind");
    }
    if (!future.isSuccess()) {
        throw new RuntimeException("Failed to bind", future.cause());
    }
    channel = future.channel();
}

From source file:org.elasticsearch.http.nio.NettyAdaptor.java

License:Apache License

@Override
public void close() throws Exception {
    assert flushOperations.isEmpty() : "Should close outbound operations before calling close";

    ChannelFuture closeFuture = nettyChannel.close();
    // This should be safe as we are not a real network channel
    closeFuture.await();
    if (closeFuture.isSuccess() == false) {
        Throwable cause = closeFuture.cause();
        ExceptionsHelper.dieOnError(cause);
        throw (Exception) cause;
    }//from ww  w .  j  a  v a2 s .  co  m
}

From source file:org.ogcs.netty.impl.TcpProtocolClient.java

License:Apache License

@Override
public void start() {
    if (bootstrap == null) {
        createBootstrap();//from w  w w .  jav  a 2  s .  c o  m
    }
    try {
        ChannelFuture future = doConnect();
        future.await();
        client = future.channel();
        future.sync();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // add shutdown hook
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {
                stop();
            }
        }));
    }
}

From source file:org.onesec.raven.rtp.NettyRtpConnector.java

License:Apache License

private Channel getChannel(ChannelFuture future) throws IOException {
    if (future.isDone()) {
        if (future.isSuccess())
            return future.channel();
        else/*from   w ww . ja  v  a 2s  .c om*/
            throw new IOException(future.cause());
    } else
        try {
            return getChannel(future.await());
        } catch (InterruptedException e) {
            throw new IOException(e);
        }
}