Example usage for io.netty.channel ChannelFuture awaitUninterruptibly

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

Introduction

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

Prototype

@Override
    ChannelFuture awaitUninterruptibly();

Source Link

Usage

From source file:org.lanternpowered.pingy.Pingy.java

License:MIT License

/**
 * Starts the pingy server.// w  w w  .java  2 s.  c  o m
 *
 * @throws IOException
 */
public void start() throws IOException {
    boolean epoll = false;

    if (this.properties.isUseEpollWhenAvailable()) {
        if (Epoll.isAvailable()) {
            debugInfo("Epoll is available");
            epoll = true;
        } else {
            debugWarn(
                    "Epoll is unavailable (The following exception is only used to print the cause why it's unavailable, "
                            + "it won't affect the functionality.)");
            //noinspection ThrowableResultOfMethodCallIgnored
            debug(() -> Epoll.unavailabilityCause().printStackTrace());
        }
    }

    final ServerBootstrap bootstrap = new ServerBootstrap();
    final EventLoopGroup group = epoll ? new EpollEventLoopGroup() : new NioEventLoopGroup();

    final ChannelFuture future = bootstrap.group(group)
            .channel(epoll ? EpollServerSocketChannel.class : NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new ReadTimeoutHandler(20))
                            .addLast(new PingyLegacyHandler(properties)).addLast(new PingyFramingHandler())
                            .addLast(new PingyHandler(properties));
                }
            }).childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true)
            .bind(getBindAddress(this.properties.getIp(), this.properties.getPort()));
    final Channel channel = future.awaitUninterruptibly().channel();
    if (!channel.isActive()) {
        final Throwable cause = future.cause();
        if (cause instanceof BindException) {
            throw (BindException) cause;
        }
        throw new RuntimeException("Failed to bind to address", cause);
    }
    info("Successfully bound to: " + channel.localAddress());
}

From source file:org.lanternpowered.server.LanternServer.java

License:MIT License

private void bind() throws BindException {
    final InetSocketAddress address = this.getBindAddress(this.game.getGlobalConfig().getServerPort());
    final boolean useEpollWhenAvailable = this.game.getGlobalConfig().useServerEpollWhenAvailable();

    ProtocolState.init();/*w  w  w .j  ava 2s.c  o m*/
    final ChannelFuture future = this.networkManager.init(address, useEpollWhenAvailable);
    final Channel channel = future.awaitUninterruptibly().channel();
    if (!channel.isActive()) {
        final Throwable cause = future.cause();
        if (cause instanceof BindException) {
            throw (BindException) cause;
        }
        throw new RuntimeException("Failed to bind to address", cause);
    }

    this.logger.info("Successfully bound to: " + channel.localAddress());
}

From source file:org.lanternpowered.server.LanternServer.java

License:MIT License

private void bindQuery() {
    if (this.queryServer == null) {
        return;//from  w w w  . j  a va2s  .  c  om
    }

    final InetSocketAddress address = getBindAddress(this.game.getGlobalConfig().getQueryPort());
    final boolean useEpollWhenAvailable = this.game.getGlobalConfig().useQueryEpollWhenAvailable();
    this.game.getLogger().info("Binding query to address: " + address + "...");

    final ChannelFuture future = this.queryServer.init(address, useEpollWhenAvailable);
    final Channel channel = future.awaitUninterruptibly().channel();
    if (!channel.isActive()) {
        this.game.getLogger().warn("Failed to bind query. Address already in use?");
    }
}

From source file:org.lanternpowered.server.LanternServer.java

License:MIT License

private void bindRcon() {
    if (this.rconServer == null) {
        return;/*from ww w. j ava2s  .  c  o m*/
    }

    final InetSocketAddress address = this.getBindAddress(this.game.getGlobalConfig().getRconPort());
    final boolean useEpollWhenAvailable = this.game.getGlobalConfig().useRconEpollWhenAvailable();
    this.game.getLogger().info("Binding rcon to address: " + address + "...");

    final ChannelFuture future = this.rconServer.init(address, useEpollWhenAvailable);
    final Channel channel = future.awaitUninterruptibly().channel();
    if (!channel.isActive()) {
        this.game.getLogger().warn("Failed to bind rcon. Address already in use?");
    }
}

From source file:org.mobicents.media.server.ctrl.rtsp.stack.RtspClientStackImpl.java

License:Open Source License

public void stop() {
    if (null != channel) {
        RtspResponseHandler handler = (RtspResponseHandler) channel.pipeline().get("handler");
        handler.sendTeardown();/* w w w  .  jav  a  2 s.  c o m*/

        ChannelFuture cf = channel.closeFuture();
        cf.addListener(new ClientChannelFutureListener());
        channel.close();
        cf.awaitUninterruptibly();

        channel = null;
    }
}

From source file:org.mobicents.media.server.ctrl.rtsp.stack.RtspClientStackImpl.java

License:Open Source License

public void sendRequest(HttpRequest rtspRequest, String remoteHost, int remotePort) {

    ChannelFuture future = null;
    if (channel == null || (channel != null && !channel.isOpen())) {
        // Start the connection attempt.
        future = bootstrap.connect(new InetSocketAddress(remoteHost, remotePort));

        // Wait until the connection attempt succeeds or fails.
        channel = future.awaitUninterruptibly().channel();
        if (!future.isSuccess()) {
            future.cause().printStackTrace();
            // bootstrap.releaseExternalResources();
            return;
        }/*  w  w w .j  a  va  2s  . co  m*/
    }

    channel.writeAndFlush(rtspRequest);
}

From source file:org.mobicents.media.server.rtsp.stack.RtspClientStackImpl.java

License:Open Source License

public void disconnect() {
    if (null != channel) {
        RtspResponseHandler handler = (RtspResponseHandler) channel.pipeline().get("handler");
        handler.sendTeardown();/*from   www  .  j  a v  a 2 s. c o m*/

        ChannelFuture cf = channel.closeFuture();
        cf.addListener(new ClientChannelFutureListener());
        channel.close();
        cf.awaitUninterruptibly();

        channel = null;
    }
}

From source file:org.opendaylight.controller.netconf.ssh.threads.Handshaker.java

License:Open Source License

@Override
public ServerSessionCallback acceptSession(final ServerSession serverSession) {
    String currentUser = currentUserSupplier.get();
    final String additionalHeader = new NetconfHelloMessageAdditionalHeader(currentUser, remoteAddress,
            remotePort, "ssh", "client").toFormattedString();

    return new SimpleServerSessionCallback() {
        @Override//ww  w. j a  v a2  s. co  m
        public Runnable requestSubsystem(final ServerSession ss, final String subsystem) throws IOException {
            return new Runnable() {
                @Override
                public void run() {
                    if (NETCONF_SUBSYSTEM.equals(subsystem)) {
                        // connect
                        final SSHClientHandler sshClientHandler = new SSHClientHandler(ganymedConnection,
                                ss.getStdin(), session);
                        ChannelFuture clientChannelFuture = initializeNettyConnection(localAddress, bossGroup,
                                sshClientHandler);
                        // get channel
                        final Channel channel = clientChannelFuture.awaitUninterruptibly().channel();

                        // write additional header before polling thread is started
                        // polling thread could process and forward data before additional header is written
                        // This will result into unexpected state:  hello message without additional header and the next message with additional header
                        channel.writeAndFlush(Unpooled.copiedBuffer(additionalHeader.getBytes()));

                        new ClientInputStreamPoolingThread(session, ss.getStdout(), channel,
                                new AutoCloseable() {
                                    @Override
                                    public void close() throws Exception {
                                        logger.trace("Closing both ganymed and local connection");
                                        try {
                                            ganymedConnection.close();
                                        } catch (Exception e) {
                                            logger.warn("Ignoring exception while closing ganymed", e);
                                        }
                                        try {
                                            channel.close();
                                        } catch (Exception e) {
                                            logger.warn("Ignoring exception while closing channel", e);
                                        }
                                    }
                                }, sshClientHandler.getChannelHandlerContext()).start();
                    } else {
                        logger.debug("{} Wrong subsystem requested:'{}', closing ssh session", serverSession,
                                subsystem);
                        String reason = "Only netconf subsystem is supported, requested:" + subsystem;
                        closeSession(ss, reason);
                    }
                }
            };
        }

        public void closeSession(ServerSession ss, String reason) {
            logger.trace("{} Closing session - {}", serverSession, reason);
            try {
                ss.getStdin().write(reason.getBytes());
            } catch (IOException e) {
                logger.warn("{} Exception while closing session", serverSession, e);
            }
            ss.close();
        }

        @Override
        public Runnable requestPtyReq(final ServerSession ss, final PtySettings pty) throws IOException {
            return new Runnable() {
                @Override
                public void run() {
                    closeSession(ss, "PTY request not supported");
                }
            };
        }

        @Override
        public Runnable requestShell(final ServerSession ss) throws IOException {
            return new Runnable() {
                @Override
                public void run() {
                    closeSession(ss, "Shell not supported");
                }
            };
        }
    };
}

From source file:org.proton.plug.test.minimalclient.SimpleAMQPConnector.java

License:Apache License

public AMQPClientConnectionContext connect(String host, int port) throws Exception {
    SocketAddress remoteDestination = new InetSocketAddress(host, port);

    ChannelFuture future = bootstrap.connect(remoteDestination);

    future.awaitUninterruptibly();

    AMQPClientSPI clientConnectionSPI = new AMQPClientSPI(future.channel());

    final AMQPClientConnectionContext connection = (AMQPClientConnectionContext) ProtonClientConnectionContextFactory
            .getFactory().createConnection(clientConnectionSPI);

    future.channel().pipeline().addLast(new ChannelDuplexHandler() {

        @Override/*from  w  w w .j a  v  a  2  s.  c o  m*/
        public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
            ByteBuf buffer = (ByteBuf) msg;
            connection.inputBuffer(buffer);
        }
    });

    return connection;
}

From source file:org.rzo.netty.ahessian.application.jmx.remote.client.Client.java

License:Apache License

public static void main(String[] args) throws Exception {

    // InternalLoggerFactory.setDefaultFactory(new SimpleLoggerFactory());
    final ExecutorService executor = Executors.newCachedThreadPool();

    Bootstrap bootstrap = new Bootstrap();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    // workerGroup.setIoRatio(99);
    bootstrap.group(workerGroup);// w w  w  .ja v a  2 s.  com
    bootstrap.channel(NioSocketChannel.class);

    bootstrap.remoteAddress(new InetSocketAddress("localhost", 15009));
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);

    final HessianProxyFactory factory = new HessianProxyFactory(executor, "localhost:15009");
    bootstrap.handler(new RPCClientSessionPipelineFactory(
            new RPCClientMixinPipelineFactory(executor, factory, workerGroup), bootstrap));

    factory.setDisconnectedListener(new Runnable() {
        public void run() {
            // stop = true;
        }
    });

    factory.setNewSessionListener(new Runnable() {
        public void run() {
            stop = false;
            executor.execute(new Runnable() {
                public void run() {
                    System.out.println("started work thread");
                    Map options = new HashMap();
                    options.put("sync", true);
                    options.put("timeout", (long) 10000);
                    AsyncMBeanServerConnection service = (AsyncMBeanServerConnection) factory
                            .create(AsyncMBeanServerConnection.class, Client.class.getClassLoader(), options);
                    server = new MBeanServerConnectionAsyncAdapter(service);

                    while (!stop) {
                        try {
                            ObjectName on = new ObjectName("java.lang:type=ClassLoading");
                            Object x = server.getAttribute(on, "LoadedClassCount");
                            System.out.println(x);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                            System.out.println(ex);
                        }
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println("stopped work thread");
                }
            });
        }
    });

    // Start the connection attempt.
    ChannelFuture future = bootstrap.connect(new InetSocketAddress("localhost", 15009));
    // Wait until the connection attempt succeeds or fails.
    Channel channel = future.awaitUninterruptibly().channel();
    if (future.isSuccess())
        System.out.println("connected");

    // get a proxy

}