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.rzo.netty.ahessian.application.jmx.remote.client.RPCClientSessionPipelineFactory.java

License:Apache License

public HandlerList getPipeline() throws Exception {
    HandlerList pipeline = new HandlerList();
    pipeline.addLast("logger", new OutLogger("1"));
    pipeline.addLast("reconnector", new ChannelInboundHandlerAdapter() {

        @Override// w  w w.j  ava2s .  c  o  m
        public void channelInactive(ChannelHandlerContext ctx) {
            ctx.fireChannelInactive();
            System.out.println("channel closed wait to reconnect ...");
            timer.schedule(new TimerTask() {
                public void run() {
                    System.out.println("reconnecting...");
                    ChannelFuture f = _bootstrap.connect();
                    try {
                        System.out.println("future wait");
                        f.awaitUninterruptibly();
                        System.out.println("future wait terminated");
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    if (f.isSuccess())
                        System.out.println("connected");
                    else {
                        System.out.println("not connected");
                        // f.getChannel().close();
                    }

                }
            }, RECONNECT_DELAY);
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) {
            Throwable cause = e;
            if (cause instanceof ConnectException) {
                System.out.println("conection lost");
            }
            ctx.channel().close();
        }
    });
    pipeline.addLast("sessionFilter", _sessionFilter);

    return pipeline;
}

From source file:org.spongepowered.lantern.LanternServer.java

License:MIT License

public void bind() throws BindException {
    SocketAddress address = getBindAddress();

    SpongeImpl.getLogger().info("Binding to address: " + address + "...");
    ChannelFuture future = networkServer.bind(address);
    Channel channel = future.awaitUninterruptibly().channel();
    if (!channel.isActive()) {
        Throwable cause = future.cause();
        if (cause instanceof BindException) {
            throw (BindException) cause;
        }//from  www . j ava2 s.  c om
        throw new RuntimeException("Failed to bind to address", cause);
    }

    SpongeImpl.getLogger().info("Successfully bound to: " + channel.localAddress());
}

From source file:org.stem.client.Connection.java

License:Apache License

public Connection(String name, InetSocketAddress address, Factory factory) throws ConnectionException {
    this.name = name;
    this.address = address;
    this.factory = factory;
    dispatcher = new Dispatcher();

    Bootstrap bootstrap = factory.createNewBootstrap();
    bootstrap.handler(new ChannelHandler(this));

    ChannelFuture future = bootstrap.connect(address);
    writeCounter.incrementAndGet();//  w w  w .j a v a  2 s.  c  om
    try {
        this.channel = future.awaitUninterruptibly().channel();
        if (!future.isSuccess()) {
            if (logger.isDebugEnabled())
                logger.debug(String.format("%s Error connecting to %s%s", this, address,
                        extractMessage(future.cause())));
            throw defunct(new ClientTransportException(address, "Can't connect", future.cause()));
        }
    } finally {
        writeCounter.decrementAndGet();
    }

    logger.trace("{} Connection opened successfully", this);
    isInitialized = true;
}

From source file:org.stem.client.old.StorageNodeClient.java

License:Apache License

public void start() throws IOException {
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
    channel = future.awaitUninterruptibly().channel();

    if (!future.isSuccess()) {
        throw new IOException("Connection failed", future.cause());
    }/* www .  j  a v a 2 s . c  o m*/
    this.connected = true;
}

From source file:org.waarp.gateway.ftp.config.FileBasedConfiguration.java

License:Open Source License

/**
 * Configure HTTPS/*from  w w w. jav  a  2 s .  c  o m*/
 */
public void configureHttps() {
    // Now start the HTTPS support
    // Configure the server.
    httpsBootstrap = new ServerBootstrap();
    httpExecutor = new NioEventLoopGroup(SERVER_THREAD * 10, new WaarpThreadFactory("HttpExecutor"));
    bossGroup = new NioEventLoopGroup(SERVER_THREAD, new WaarpThreadFactory("HTTP_Boss"));
    workerGroup = new NioEventLoopGroup(SERVER_THREAD * 10, new WaarpThreadFactory("HTTP_Worker"));
    WaarpNettyUtil.setServerBootstrap(httpsBootstrap, bossGroup, workerGroup, (int) TIMEOUTCON);

    // Configure the pipeline factory.
    httpsBootstrap.childHandler(new HttpSslInitializer(useHttpCompression, false));

    // Bind and start to accept incoming connections.
    logger.warn("Start Https Support on port: " + SERVER_HTTPSPORT);
    ChannelFuture future = httpsBootstrap.bind(new InetSocketAddress(SERVER_HTTPSPORT));
    if (future.awaitUninterruptibly().isSuccess()) {
        httpChannelGroup.add(future.channel());
    }
}

From source file:org.wenxueliu.netty.client.ClientTest.java

License:Apache License

private void connectRetry(String ip, int port, ChannelFutureListener clientConnectionListener) {
    try {//from  w  w  w .j a  va  2  s  . com
        bootstrap = new Bootstrap().group(workerGroup).channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_REUSEADDR, true)
                .option(ChannelOption.SO_KEEPALIVE, true).option(ChannelOption.SO_SNDBUF, SEND_BUFFER_SIZE)
                .option(ChannelOption.SO_RCVBUF, SEND_BUFFER_SIZE)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, CONNECT_TIMEOUT);

        pipelineFactory = new DefaultChannelInitializer(timer, this);
        bootstrap.handler(pipelineFactory);
        //.handler(new ChannelInitializer<SocketChannel>() {

        //    @Override
        //    protected void initChannel(SocketChannel channel) throws Exception {
        //        ChannelPipeline p = channel.pipeline();
        //        p.addLast(new MessageDecoder(),
        //                  new StringEncoder(CharsetUtil.UTF_8),
        //                  new IdleStateHandler(IDLE_TIMEOUT_SEC, 0, 0),
        //                  new BootstrapTimeoutHandler(timer, 10),
        //                  new ConnectionHandler());
        //    }
        //});
        bootstrap.remoteAddress(ip, port);
        ChannelFuture future = bootstrap.connect();
        future.awaitUninterruptibly();
        future.addListener(clientConnectionListener);
    } catch (Exception e) {
        log.warn("Connection to the server {}:{} failed", ip, port);
    }
}

From source file:poke.server.cluster.OutboundClusterWorker.java

License:Apache License

@Override
public void run() {
    while (true) {
        if (!forever && ClusterQueue.outbound.size() == 0)
            break;

        try {// www . j  a  v a  2s.  co m
            // block until a message is enqueued
            ClusterQueueEntry msg = ClusterQueue.outbound.take();

            if (logger.isDebugEnabled())
                logger.debug("Outbound cluster message routing to cluster " + msg.req.getHeader().getClusterId()
                        + " and node" + msg.req.getHeader().getClientId());

            if (msg.channel.isWritable()) {
                boolean rtn = false;
                if (msg.channel != null && msg.channel.isOpen() && msg.channel.isWritable()) {
                    ChannelFuture cf = msg.channel.write(msg);

                    // blocks on write - use listener to be async
                    cf.awaitUninterruptibly();
                    rtn = cf.isSuccess();
                    if (!rtn)
                        ClusterQueue.outbound.putFirst(msg);
                }

            } else {
                logger.info("channel to cluster " + msg.req.getHeader().getClusterId() + " & node "
                        + msg.req.getHeader().getClientId() + " is not writable");
                ClusterQueue.outbound.putFirst(msg);
            }
        } catch (InterruptedException ie) {
            break;
        } catch (Exception e) {
            logger.error("Unexpected cluster communcation failure", e);
            break;
        }
    }

    if (!forever) {
        logger.info("cluster outbound queue closing");
    }
}

From source file:poke.server.management.OutboundMgmtWorker.java

License:Apache License

@Override
public void run() {
    while (true) {
        if (!forever && ManagementQueue.outbound.size() == 0)
            break;

        try {//from w  w  w . ja va 2s.c  o  m
            // block until a message is enqueued
            ManagementQueueEntry msg = ManagementQueue.outbound.take();

            if (logger.isDebugEnabled())
                logger.debug("Outbound management message routing to node " + msg.req.getHeader().getToNode());

            if (msg.channel.isWritable()) {
                boolean rtn = false;
                if (msg.channel != null && msg.channel.isOpen() && msg.channel.isWritable()) {
                    ChannelFuture cf = msg.channel.write(msg);

                    // blocks on write - use listener to be async
                    cf.awaitUninterruptibly();
                    rtn = cf.isSuccess();
                    if (!rtn)
                        ManagementQueue.outbound.putFirst(msg);
                }

            } else {
                logger.info("channel to node " + msg.req.getHeader().getToNode() + " is not writable");
                ManagementQueue.outbound.putFirst(msg);
            }
        } catch (InterruptedException ie) {
            break;
        } catch (Exception e) {
            logger.error("Unexpected management communcation failure", e);
            break;
        }
    }

    if (!forever) {
        logger.info("management outbound queue closing");
    }
}

From source file:poke.server.queue.OutboundAppWorker.java

License:Apache License

@Override
public void run() {
    Channel conn = sq.channel;/* ww w .  j  ava  2s. co  m*/
    if (conn == null || !conn.isOpen()) {
        PerChannelQueue.logger.error("connection missing, no outbound communication");
        return;
    }

    while (true) {
        if (!forever && sq.outbound.size() == 0)
            break;

        try {
            // block until a message is enqueued
            PerChannelQueueEntry msg = sq.outbound.take();
            if (conn.isWritable()) {
                boolean rtn = false;
                if (sq.channel != null && sq.channel.isOpen() && sq.channel.isWritable()) {
                    ChannelFuture cf = sq.channel.writeAndFlush(msg.req);

                    // blocks on write - use listener to be async
                    cf.awaitUninterruptibly();
                    rtn = cf.isSuccess();
                    if (!rtn)
                        sq.outbound.putFirst(msg);
                }

            } else
                sq.outbound.putFirst(msg);
        } catch (InterruptedException ie) {
            break;
        } catch (Exception e) {
            logger.error("Unexpected communcation failure", e);
            break;
        }
    }

    if (!forever) {
        logger.info("connection queue closing");
    }
}

From source file:poke.server.worker.comm.CommHandler.java

License:Apache License

/**
 * messages pass through this method. We use a blackbox design as much as
        /* www .  ja v a  2s.  co m*/
 * possible to ensure we can replace the underlining communication without
 * affecting behavior.
 * 
 * @param msg
 * @return
 * @throws InterruptedException 
 */
public boolean send(GeneratedMessage msg, Channel ch) throws InterruptedException {
    // TODO a queue is needed to prevent overloading of the socket
    // connection. For the demonstration, we don't need it 

    ChannelFuture cf = ch.writeAndFlush((Request) msg);

    cf.awaitUninterruptibly();
    logger.info(" " + cf.cause());
    if (cf.isDone() && !cf.isSuccess()) {
        logger.error("failed to poke!");
        return false;
    }
    return true;
}