Example usage for io.netty.channel ChannelFuture isSuccess

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

Introduction

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

Prototype

boolean isSuccess();

Source Link

Document

Returns true if and only if the I/O operation was completed successfully.

Usage

From source file:NettyInboundHttpTargetHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
    //   System.out.println("Receving data");
    inboundChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
        @Override/*w w w  . j  av a 2 s  .  c o m*/
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                ctx.channel().read();
            } else {
                future.channel().close();
            }
        }
    });
}

From source file:NettyHttpTransportSourceHandler.java

License:Apache License

/**
 * activating registered handler to accept events.
 *
 * @param ctx//from w w w .j  a va  2  s .  c o m
 * @throws Exception
 */
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {

    final Channel inboundChannel = ctx.channel();

    Bootstrap b = new Bootstrap();
    b.group(inboundChannel.eventLoop()).channel(ctx.channel().getClass());
    b.handler(new NettyTargetHandlerInitilizer(inboundChannel)).option(ChannelOption.AUTO_READ, false);

    b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    b.option(ChannelOption.TCP_NODELAY, true);
    b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 15000);

    b.option(ChannelOption.SO_SNDBUF, 1048576);
    b.option(ChannelOption.SO_RCVBUF, 1048576);

    ChannelFuture f = b.connect(NettyHttpListner.HOST, NettyHttpListner.HOST_PORT);

    outboundChannel = f.channel();
    f.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                // connection complete start to read first data
                inboundChannel.read();
            } else {
                // Close the connection if the connection attempt has failed.
                inboundChannel.close();
            }
        }
    });

}

From source file:NettyHttpTransportSourceHandler.java

License:Apache License

/**
 * receiving events through netty./*from w  w w.jav a  2s  .co  m*/
 *
 * @param ctx
 * @param msg
 * @throws Exception
 */
@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {

    if (outboundChannel.isActive()) {
        outboundChannel.writeAndFlush(msg).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    // was able to flush out data, start to read the next chunk
                    ctx.channel().read();
                } else {
                    future.channel().close();
                }
            }
        });
    } else {
        // System.out.println("Outbound Channel Not Active");
    }
}

From source file:alluxio.client.netty.NettyUnderFileSystemBlockReader.java

License:Apache License

@Override
public ByteBuffer read(InetSocketAddress address, long blockId, long offset, long length, long sessionId,
        boolean noCache) throws IOException {
    Channel channel = null;//  ww  w. j  av  a 2  s.com
    ClientHandler clientHandler = null;
    Metrics.NETTY_UFS_BLOCK_READ_OPS.inc();
    try {
        channel = mContext.acquireNettyChannel(address);
        if (!(channel.pipeline().last() instanceof ClientHandler)) {
            channel.pipeline().addLast(new ClientHandler());
        }
        clientHandler = (ClientHandler) channel.pipeline().last();
        SingleResponseListener listener = new SingleResponseListener();
        clientHandler.addListener(listener);

        ChannelFuture channelFuture = channel.writeAndFlush(
                new RPCUnderFileSystemBlockReadRequest(blockId, offset, length, sessionId, noCache));
        channelFuture = channelFuture.sync();
        if (channelFuture.isDone() && !channelFuture.isSuccess()) {
            LOG.error("Failed to read from %s for block %d with error %s.", address.toString(), blockId,
                    channelFuture.cause());
            throw new IOException(channelFuture.cause());
        }

        RPCResponse response = listener.get(NettyClient.TIMEOUT_MS, TimeUnit.MILLISECONDS);

        switch (response.getType()) {
        case RPC_BLOCK_READ_RESPONSE:
            RPCBlockReadResponse blockResponse = (RPCBlockReadResponse) response;
            LOG.debug("Data {} from machine {} received", blockId, address);

            RPCResponse.Status status = blockResponse.getStatus();
            if (status == RPCResponse.Status.SUCCESS) {
                // always clear the previous response before reading another one
                close();
                mReadResponse = blockResponse;
                return blockResponse.getPayloadDataBuffer().getReadOnlyByteBuffer();
            }
            throw new IOException(status.getMessage() + " response: " + blockResponse);
        case RPC_ERROR_RESPONSE:
            RPCErrorResponse error = (RPCErrorResponse) response;
            throw new IOException(error.getStatus().getMessage());
        default:
            throw new IOException(ExceptionMessage.UNEXPECTED_RPC_RESPONSE.getMessage(response.getType(),
                    RPCMessage.Type.RPC_BLOCK_READ_RESPONSE));
        }
    } catch (Exception e) {
        Metrics.NETTY_UFS_BLOCK_READ_FAILURES.inc();
        try {
            if (channel != null) {
                channel.close().sync();
            }
        } catch (InterruptedException ee) {
            throw new RuntimeException(ee);
        }
        throw new IOException(e);
    } finally {
        if (clientHandler != null) {
            clientHandler.removeListeners();
        }
        if (channel != null) {
            mContext.releaseNettyChannel(address, channel);
        }
    }
}

From source file:alluxio.network.connection.NettyChannelPool.java

License:Apache License

/**
 * Creates a netty channel instance./*  ww w.j a v  a2 s  .co  m*/
 *
 * @return the channel created
 * @throws IOException if it fails to create a channel
 */
@Override
protected Channel createNewResource() throws IOException {
    Bootstrap bs;
    try {
        bs = mBootstrap.clone();
    } catch (Exception e) {
        // No exception should happen here.
        throw Throwables.propagate(e);
    }
    try {
        ChannelFuture channelFuture = bs.connect().sync();
        if (channelFuture.isSuccess()) {
            LOG.info("Created netty channel with netty bootstrap {}.", mBootstrap);
            return channelFuture.channel();
        } else {
            LOG.error("Failed to create netty channel with netty bootstrap {} and error {}.", mBootstrap,
                    channelFuture.cause().getMessage());
            throw new IOException(channelFuture.cause());
        }
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

From source file:alluxio.network.netty.NettyChannelPool.java

License:Apache License

/**
 * Creates a netty channel instance./*from   w  w w  .j  a v  a2  s .co m*/
 *
 * @return the channel created
 */
@Override
protected Channel createNewResource() throws IOException {
    Bootstrap bs;
    bs = mBootstrap.clone();
    try {
        ChannelFuture channelFuture = bs.connect().sync();
        if (channelFuture.isSuccess()) {
            LOG.info("Created netty channel with netty bootstrap {}.", mBootstrap);
            return channelFuture.channel();
        } else {
            LOG.error("Failed to create netty channel with netty bootstrap {} and error {}.", mBootstrap,
                    channelFuture.cause().getMessage());
            throw new UnavailableException(channelFuture.cause());
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new CanceledException(e);
    }
}

From source file:be.yildizgames.module.network.netty.server.ServerNetty.java

License:MIT License

/**
 * Start the server to listen to clients.
 *///from   ww w .  j av  a 2s .co m
//@ensures To start the server and having the port listening to clients.
@Override
public void startServer(String address, int port, SessionManager sessionManager, DecoderEncoder codec) {
    try {
        ChannelInitializer<SocketChannel> initializer = new NettyChannelInitializer(
                new SessionServerHandlerFactory(sessionManager, codec));

        this.bootstrap.childHandler(initializer);
        InetSocketAddress socketAddress;
        if (address == null) {
            socketAddress = new InetSocketAddress(port);
        } else {
            socketAddress = new InetSocketAddress(address, port);
        }
        ChannelFuture acceptor = this.bootstrap.bind(socketAddress).sync();
        if (acceptor.isSuccess()) {
            LOGGER.debug("server bound to :" + port);
            LOGGER.info("Server started.");
        } else {
            LOGGER.warn("server not bound to :" + port);
            LOGGER.info("Server not started.");
        }
    } catch (ChannelException e) {
        this.throwError("Port " + port + " already in use.", e);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        this.throwError("Error starting network engine.", e);
    }
}

From source file:bftsmart.communication.client.netty.NettyClientServerCommunicationSystemClientSide.java

License:Apache License

public NettyClientServerCommunicationSystemClientSide(int clientId, ClientViewController controller) {
    super();//from www .  j a v  a  2s  .com

    this.clientId = clientId;
    this.workerGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors());
    try {

        this.secretKeyFactory = TOMUtil.getSecretFactory();

        this.controller = controller;

        /* Tulio Ribeiro */
        privKey = controller.getStaticConf().getPrivateKey();

        this.listener = new SyncListener();
        this.rl = new ReentrantReadWriteLock();

        int[] currV = controller.getCurrentViewProcesses();

        for (int i = 0; i < currV.length; i++) {
            int replicaId = currV[i];
            try {

                ChannelFuture future = connectToReplica(replicaId, secretKeyFactory);

                logger.debug("ClientID {}, connecting to replica {}, at address: {}", clientId, replicaId,
                        controller.getRemoteAddress(replicaId));

                future.awaitUninterruptibly();

                if (!future.isSuccess()) {
                    logger.error("Impossible to connect to " + replicaId);
                }

            } catch (java.lang.NullPointerException ex) {
                // What is this??? This is not possible!!!
                logger.debug("Should fix the problem, and I think it has no other implications :-), "
                        + "but we must make the servers store the view in a different place.");
            } catch (Exception ex) {
                logger.error("Failed to initialize MAC engine", ex);
            }
        }
    } catch (NoSuchAlgorithmException ex) {
        logger.error("Failed to initialize secret key factory", ex);
    }
}

From source file:bftsmart.communication.client.netty.NettyClientServerCommunicationSystemClientSide.java

License:Apache License

@Override
public void updateConnections() {
    int[] currV = controller.getCurrentViewProcesses();
    try {/*from   www.jav a2 s. c  o  m*/
        // open connections with new servers
        for (int i = 0; i < currV.length; i++) {

            int replicaId = currV[i];

            rl.readLock().lock();
            if (sessionClientToReplica.get(replicaId) == null) {
                rl.readLock().unlock();
                rl.writeLock().lock();
                try {
                    ChannelFuture future = connectToReplica(replicaId, secretKeyFactory);
                    logger.debug("ClientID {}, updating connection to replica {}, at address: {}", clientId,
                            replicaId, controller.getRemoteAddress(replicaId));

                    future.awaitUninterruptibly();

                    if (!future.isSuccess()) {
                        logger.error("Impossible to connect to " + replicaId);
                    }

                } catch (InvalidKeyException | InvalidKeySpecException ex) {
                    logger.error("Failed to initialize MAC engine", ex);
                }
                rl.writeLock().unlock();
            } else {
                rl.readLock().unlock();
            }
        }
    } catch (NoSuchAlgorithmException ex) {
        logger.error("Failed to initialzie secret key factory", ex);
    }
}

From source file:c5db.control.ControlService.java

License:Apache License

private void startHttpRpc() {
    try {//from  www . jav a2 s. co  m
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        ServerBootstrap serverBootstrap1 = serverBootstrap.group(acceptConnectionGroup, ioWorkerGroup)
                .channel(NioServerSocketChannel.class).option(ChannelOption.SO_REUSEADDR, true)
                .option(ChannelOption.SO_BACKLOG, 100).childOption(ChannelOption.TCP_NODELAY, true)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();

                        //              pipeline.addLast("logger", new LoggingHandler(LogLevel.DEBUG));
                        pipeline.addLast("http-server", new HttpServerCodec());
                        pipeline.addLast("aggregator",
                                new HttpObjectAggregator(C5ServerConstants.MAX_CALL_SIZE));

                        pipeline.addLast("encode", new ServerHttpProtostuffEncoder());
                        pipeline.addLast("decode", new ServerHttpProtostuffDecoder());

                        pipeline.addLast("translate", new ServerDecodeCommandRequest());

                        pipeline.addLast("inc-messages", new MessageHandler());
                    }
                });

        serverBootstrap.bind(modulePort).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    // yay
                    listenChannel = future.channel();
                    notifyStarted();
                } else {
                    LOG.error("Unable to bind to port {}", modulePort);
                    notifyFailed(future.cause());
                }
            }
        });
    } catch (Exception e) {
        notifyFailed(e);
    }
}