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:com.digitalpetri.opcua.stack.server.tcp.SocketServer.java

License:Apache License

public synchronized void bind() throws ExecutionException, InterruptedException {
    if (channel != null)
        return; // Already bound

    CompletableFuture<Void> bindFuture = new CompletableFuture<>();

    bootstrap.bind(address).addListener(new ChannelFutureListener() {
        @Override/*from  w  ww  .  j  a v  a  2 s . co  m*/
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                channel = future.channel();
                bindFuture.complete(null);
            } else {
                bindFuture.completeExceptionally(future.cause());
            }
        }
    });

    bindFuture.get();
}

From source file:com.dinstone.jrpc.transport.netty4.NettyConnection.java

License:Apache License

@Override
public ResultFuture call(Call call) {
    final int id = ID_GENERATOR.incrementAndGet();
    Map<Integer, ResultFuture> futureMap = SessionUtil.getResultFutureMap(ioSession);
    final ResultFuture resultFuture = new ResultFuture();
    futureMap.put(id, resultFuture);//from  ww w  .jav  a 2s .  co m

    ChannelFuture wf = ioSession.writeAndFlush(new Request(id, serializeType, call));
    wf.addListener(new GenericFutureListener<ChannelFuture>() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                resultFuture.setResult(new Result(500, "can't write request"));
            }
        }

    });

    return resultFuture;
}

From source file:com.dinstone.jrpc.transport.netty5.NettyConnection.java

License:Apache License

@Override
public ResultFuture call(Call call) {
    final int id = ID_GENERATOR.incrementAndGet();
    Map<Integer, ResultFuture> futureMap = SessionUtil.getResultFutureMap(ioSession);
    final ResultFuture resultFuture = new ResultFuture();
    futureMap.put(id, resultFuture);/*from  w w w . j  av  a 2 s . c  o m*/

    ChannelFuture wf = ioSession.writeAndFlush(new Request(id, serializeType, call));
    wf.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                resultFuture.setResult(new Result(500, "can't write request"));
            }
        }

    });

    return resultFuture;
}

From source file:com.dinstone.netty.Client.java

License:Apache License

public static void main(String[] args) throws IOException, InterruptedException {
    Bootstrap b = new Bootstrap();
    b.group(new NioEventLoopGroup()).channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<NioSocketChannel>() {

                @Override//from ww  w  . j ava2s.co  m
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ch.pipeline().addLast("dd", new ChannelHandlerAdapter() {

                        /**
                         * {@inheritDoc}
                         * 
                         * @see io.netty.channel.ChannelHandlerAdapter#exceptionCaught(io.netty.channel.ChannelHandlerContext,
                         *      java.lang.Throwable)
                         */
                        @Override
                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
                                throws Exception {
                            System.out.println("error: ");
                            cause.printStackTrace();
                        }
                    });
                }
            });
    b.connect("localhost", 8090).addListener(new ChannelFutureListener() {

        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                future.channel().write(Unpooled.buffer().writeBytes("123".getBytes()));
                future.channel().flush();
            }
        }
    });
}

From source file:com.diwayou.hybrid.remoting.netty.NettyRemotingAbstract.java

License:Apache License

public RemotingCommand invokeSyncImpl(final Channel channel, final RemotingCommand request,
        final long timeoutMillis)
        throws InterruptedException, RemotingSendRequestException, RemotingTimeoutException {
    try {/*from  w  w  w .ja  v  a 2 s.c o  m*/
        final ResponseFuture responseFuture = new ResponseFuture(request.getOpaque(), timeoutMillis, null,
                null);
        this.responseTable.put(request.getOpaque(), responseFuture);
        channel.writeAndFlush(request).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture f) throws Exception {
                if (f.isSuccess()) {
                    responseFuture.setSendRequestOK(true);
                    return;
                } else {
                    responseFuture.setSendRequestOK(false);
                }

                responseTable.remove(request.getOpaque());
                responseFuture.setCause(f.cause());
                responseFuture.putResponse(null);
                plog.warn("send a request command to channel <" + channel.remoteAddress() + "> failed.");
                plog.warn(request.toString());
            }
        });

        RemotingCommand responseCommand = responseFuture.waitResponse(timeoutMillis);
        if (null == responseCommand) {
            // ????
            if (responseFuture.isSendRequestOK()) {
                throw new RemotingTimeoutException(RemotingHelper.parseChannelRemoteAddr(channel),
                        timeoutMillis, responseFuture.getCause());
            }
            // ??
            else {
                throw new RemotingSendRequestException(RemotingHelper.parseChannelRemoteAddr(channel),
                        responseFuture.getCause());
            }
        }

        return responseCommand;
    } finally {
        this.responseTable.remove(request.getOpaque());
    }
}

From source file:com.ebay.jetstream.messaging.transport.netty.autoflush.handler.AutoFlushWriterChannelListener.java

License:MIT License

@Override
public void operationComplete(ChannelFuture future) throws Exception {

    if (future.isSuccess()) {
        ExtendedChannelPromise bPromise = (ExtendedChannelPromise) future;
        ExtendedChannelPromise firstEvent = (ExtendedChannelPromise) (m_events[0].getPromise());
        firstEvent.setWrittenSize(bPromise.getWrittenSize());
        firstEvent.setRawBytes(bPromise.getRawBytes());
        firstEvent.setCompressedBytes(bPromise.getCompressedBytes());
        for (int i = 0; i < m_events.length; i++) {
            m_events[i].getPromise().setSuccess(null);

        }//from  w  w w.j  a  va  2s.  c  om
    } else {
        Throwable cause = future.cause();
        for (int i = 0; i < m_events.length; i++) {
            m_events[i].getPromise().setFailure(cause);
        }
    }

}

From source file:com.ebay.jetstream.messaging.transport.netty.eventproducer.EventConsumerActivationRequest.java

License:MIT License

@Override
public void operationComplete(ChannelFuture future) throws Exception {

    if (!future.isDone())
        return;//w  ww. j a v a2s. co m

    if (future.isSuccess()) {
        ConsumerChannelContext ccc = new ConsumerChannelContext();
        ccc.setChannel(m_channel);
        m_ecInfo.getVirtualQueueMonitor().setMaxQueueBackLog(m_maxNettybackLog);
        ccc.setVirtualQueueMonitor(m_ecInfo.getVirtualQueueMonitor()); // one virtual queue monitor shared between all connections to one consumer
        m_ecInfo.setChannelContext(m_channel, ccc);
        m_producer.handleNewActiveConsumer(this);
    } else {
        m_producer.markConsumerDead(m_ecInfo);
    }

}

From source file:com.ebay.jetstream.messaging.transport.netty.eventproducer.EventProducer.java

License:MIT License

/**
 * @param ecinfo//from  w w w  . j av a  2s  .com
 * @throws Exception
 */
Channel activateEventConsumerSession(EventConsumerInfo ecinfo, boolean asyncConnect, int numConnections)
        throws Exception {

    if (asyncConnect) {

        createAsyncMultipleConnections(ecinfo, numConnections);

    } else {

        // now we create the configd number of connections

        // Start the client.
        ChannelFuture cf = m_bootstrap.connect(InetAddress.getByName(ecinfo.getAdvertisement().getHostName()),
                ecinfo.getAdvertisement().getListenTcpPort()); // (5)

        cf.awaitUninterruptibly((m_transportConfig.getConnectionTimeoutInSecs() + 1) * 1000);

        if (cf.isSuccess()) {
            ConsumerChannelContext ccc = new ConsumerChannelContext();
            ccc.setChannel(cf.channel());

            ecinfo.setChannelContext(cf.channel(), ccc);
            activateEventConsumer(ecinfo);
        }
    }

    return null;
}

From source file:com.ebay.jetstream.messaging.transport.netty.eventproducer.EventProducer.java

License:MIT License

@Override
public void operationComplete(ChannelFuture future) throws Exception {

    if (future instanceof EventConsumerChannelFuture) {

        EventConsumerChannelFuture eccf = (EventConsumerChannelFuture) future;

        eccf.getVirtualQueueMonitor().decrement();

        if (!future.isSuccess()) {
            // we submit the message back if TTL has not expired.

            JetstreamMessage msg = eccf.getMessage();

            if (msg.broadcast()) {
                msg = null;/*from   w ww . jav  a2  s.  c  o m*/
                return;
            }

            tryResendMessage(msg);

            Channel channel = ((EventConsumerChannelFuture) future).getConsumerChannelContext().channel();
            if (channel != null && !channel.isActive()) {
                removeSession(((EventConsumerChannelFuture) future).getConsumerChannelContext());
            }

        } else {
            m_avgMsgsSentPerSec.increment();

            m_totalMsgsSent.increment();
            if (eccf.getWrittenSize() > 0) {
                m_totalBytesSent.addAndGet(eccf.getWrittenSize());
                m_totalRequestsSent.increment();

                m_totalRawBytes.addAndGet(eccf.getRawBytes());
                m_totalCompressedBytes.addAndGet(eccf.getCompressedBytes());
            }
        }
    }

}

From source file:com.eightkdata.mongowp.server.wp.NettyMongoServer.java

License:Open Source License

@Override
protected void startUp() throws Exception {
    LOGGER.info("Listening MongoDB requests on port " + port);

    connectionGroup = new NioEventLoopGroup(0,
            new ThreadFactoryBuilder().setNameFormat("netty-connection-%d").build());
    workerGroup = new NioEventLoopGroup(0, new ThreadFactoryBuilder().setNameFormat("netty-worker-%d").build());

    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(connectionGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override/*from w w w .ja  v  a 2s . c  om*/
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    buildChildHandlerPipeline(socketChannel.pipeline());
                }
            }) // TODO: set TCP channel options?
    ;

    ChannelFuture channelFuture = bootstrap.bind(port).awaitUninterruptibly();
    if (!channelFuture.isSuccess()) {
        workerGroup.shutdownGracefully();
        connectionGroup.shutdownGracefully();
    }
}