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:c5db.control.SimpleControlClient.java

License:Apache License

public ListenableFuture<CommandReply> sendRequest(CommandRpcRequest<?> request,
        InetSocketAddress remoteAddress) {
    SettableFuture<CommandReply> replyMessageFuture = SettableFuture.create();
    ChannelFuture connectFuture = client.connect(remoteAddress);
    connectFuture.addListener(new ChannelFutureListener() {
        @Override//from   w  w  w  .j  av a2s. c o  m
        public void operationComplete(ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                future.channel().pipeline().addLast(new SimpleChannelInboundHandler<CommandReply>() {
                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, CommandReply msg) throws Exception {
                        replyMessageFuture.set(msg);
                        ctx.channel().close();
                    }
                });

                // connected is fine, flush message:
                future.channel().writeAndFlush(request);
            } else {
                replyMessageFuture.setException(future.cause());
                future.channel().close();
            }
        }
    });

    return replyMessageFuture;
}

From source file:c5db.regionserver.RegionServerService.java

License:Apache License

@Override
protected void doStart() {
    fiber.start();//from  w ww .  j a  v  a2  s  .c  om

    fiber.execute(() -> {
        // we need the tablet module:
        ListenableFuture<C5Module> f = server.getModule(ModuleType.Tablet);
        Futures.addCallback(f, new FutureCallback<C5Module>() {
            @Override
            public void onSuccess(final C5Module result) {
                tabletModule = (TabletModule) result;
                bootstrap.group(acceptGroup, workerGroup).option(ChannelOption.SO_REUSEADDR, true)
                        .childOption(ChannelOption.TCP_NODELAY, true).channel(NioServerSocketChannel.class)
                        .childHandler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            protected void initChannel(SocketChannel ch) throws Exception {
                                ChannelPipeline p = ch.pipeline();
                                p.addLast("http-server-codec", new HttpServerCodec());
                                p.addLast("http-agg",
                                        new HttpObjectAggregator(C5ServerConstants.MAX_CALL_SIZE));
                                p.addLast("websocket-agg",
                                        new WebSocketFrameAggregator(C5ServerConstants.MAX_CALL_SIZE));
                                p.addLast("decoder", new WebsocketProtostuffDecoder("/websocket"));
                                p.addLast("encoder", new WebsocketProtostuffEncoder());
                                p.addLast("handler", new RegionServerHandler(RegionServerService.this));
                            }
                        });

                bootstrap.bind(port).addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (future.isSuccess()) {
                            listenChannel = future.channel();
                            notifyStarted();
                        } else {
                            LOG.error("Unable to find Region Server to {} {}", port, future.cause());
                            notifyFailed(future.cause());
                        }
                    }
                });
            }

            @Override
            public void onFailure(Throwable t) {
                notifyFailed(t);
            }
        }, fiber);
    });
}

From source file:ccwihr.client.t2.HttpResponseHandler.java

License:Apache License

/**
 * Wait (sequentially) for a time duration for each anticipated response
 *
 * @param timeout Value of time to wait for each response
 * @param unit Units associated with {@code timeout}
 * @see HttpResponseHandler#put(int, io.netty.channel.ChannelFuture, io.netty.channel.ChannelPromise)
 *///from   ww  w  .ja v  a2  s . co m
public void awaitResponses(long timeout, TimeUnit unit) {
    Iterator<Entry<Integer, Entry<ChannelFuture, ChannelPromise>>> itr = streamidPromiseMap.entrySet()
            .iterator();
    while (itr.hasNext()) {
        Entry<Integer, Entry<ChannelFuture, ChannelPromise>> entry = itr.next();
        ChannelFuture writeFuture = entry.getValue().getKey();
        if (!writeFuture.awaitUninterruptibly(timeout, unit)) {
            throw new IllegalStateException("Timed out waiting to write for stream id " + entry.getKey());
        }
        if (!writeFuture.isSuccess()) {
            throw new RuntimeException(writeFuture.cause());
        }
        ChannelPromise promise = entry.getValue().getValue();
        if (!promise.awaitUninterruptibly(timeout, unit)) {
            throw new IllegalStateException("Timed out waiting for response on stream id " + entry.getKey());
        }
        if (!promise.isSuccess()) {
            throw new RuntimeException(promise.cause());
        }
        System.out.println("---Stream id: " + entry.getKey() + " received---");
        itr.remove();
    }
}

From source file:cloudeventbus.client.EventBusImpl.java

License:Open Source License

private void connect() {
    synchronized (lock) {
        if (closed) {
            return;
        }//w  ww .  j a  v a2s  .c  o m
        serverReady = false;
    }
    final ServerList.Server server = servers.nextServer();
    LOGGER.debug("Attempting connecting to {}", server.getAddress());
    new Bootstrap().group(eventLoopGroup).remoteAddress(server.getAddress()).channel(NioSocketChannel.class)
            .handler(new ClientChannelInitializer()).connect().addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        LOGGER.debug("Connection to {} successful", server.getAddress());
                        server.connectionSuccess();
                        synchronized (lock) {
                            channel = future.channel();
                            if (closed) {
                                channel.close();
                            }
                        }
                    } else {
                        LOGGER.warn("Connection to {} failed", server.getAddress());
                        server.connectionFailure();
                        scheduleReconnect();
                        fireStateChange(ConnectionState.CONNECTION_FAILED, null);
                    }
                }
            });
}

From source file:cn.jpush.api.common.connection.HttpResponseHandler.java

License:Apache License

/**
 * Wait (sequentially) for a time duration for each anticipated response
 *
 * @param timeout Value of time to wait for each response
 * @param unit Units associated with {@code timeout}
 * @see HttpResponseHandler#put(int, ChannelFuture, ChannelPromise)
 *//*w  w w. java2 s .  co  m*/
public void awaitResponses(long timeout, TimeUnit unit) {
    Iterator<Entry<Integer, Entry<ChannelFuture, ChannelPromise>>> itr = streamidPromiseMap.entrySet()
            .iterator();
    while (itr.hasNext()) {
        Entry<Integer, Entry<ChannelFuture, ChannelPromise>> entry = itr.next();
        ChannelFuture writeFuture = entry.getValue().getKey();
        if (!writeFuture.awaitUninterruptibly(timeout, unit)) {
            throw new IllegalStateException("Timed out waiting to write for stream id " + entry.getKey());
        }
        if (!writeFuture.isSuccess()) {
            throw new RuntimeException(writeFuture.cause());
        }
        ChannelPromise promise = entry.getValue().getValue();
        if (!promise.awaitUninterruptibly(timeout, unit)) {
            throw new IllegalStateException("Timed out waiting for response on stream id " + entry.getKey());
        }
        if (!promise.isSuccess()) {
            throw new RuntimeException(promise.cause());
        }
        System.out.println("---Stream id: " + entry.getKey() + " received---");
        System.out.println("---Stream id: " + promise.toString());
        itr.remove();
    }
}

From source file:cn.savor.small.netty.MiniProNettyClientHandler.java

License:Open Source License

@Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
        String channelId = ctx.channel().id().toString();
        if (evt instanceof IdleStateEvent) {

            IdleStateEvent event = (IdleStateEvent) evt;

            if (event.state().equals(IdleState.READER_IDLE)) {
                //?
                LogUtils.i("READER_IDLE");
                LogFileUtil.write("MiniNettyClientHandler READER_IDLE");

            } else if (event.state().equals(IdleState.WRITER_IDLE)) {

                LogUtils.i("WRITER_IDLE");
                LogFileUtil.write("MiniNettyClientHandler WRITER_IDLE");
                try {
                    // ???
                    MessageBean message = new MessageBean();
                    message.setCmd(MessageBean.Action.HEART_CLENT_TO_SERVER);
                    String number = channelId + System.currentTimeMillis();
                    message.setSerialnumber(number);
                    message.setIp(AppUtils.getLocalIPAddress());
                    message.setMac(session.getEthernetMac());
                    InnerBean bean = new InnerBean();
                    bean.setHotelId(session.getBoiteId());
                    bean.setRoomId(session.getRoomId());
                    bean.setSsid(AppUtils.getShowingSSID(mContext));
                    bean.setBoxId(session.getBoxId());
                    ArrayList<String> contList = new ArrayList<>();
                    contList.add("I am a mini Heart Pakage...");
                    contList.add(new Gson().toJson(bean));
                    message.setContent(contList);
                    ChannelFuture future = ctx.writeAndFlush(message);
                    if (!future.isSuccess()) {
                        close(ctx);//w  ww. ja  v  a2  s .  c  o  m
                    }
                    LogUtils.v("miniProgram--WRITER_IDLE====" + channelId + "====>>>>...??:"
                            + message.getSerialnumber());
                    LogUtils.v("miniProgram--future.isSuccess()====" + future.isSuccess());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (event.state().equals(IdleState.ALL_IDLE)) {
                //
                //?REQ==========
                LogUtils.i("ALL_IDLE");
                close(ctx);
            }

        }
    }

From source file:cn.savor.small.netty.MiniProNettyClientHandler.java

License:Open Source License

public void close(ChannelHandlerContext ctx) {
        try {/*from w ww . j av  a 2s  .com*/
            Channel cid = ctx.pipeline().channel();
            LogUtils.v("close a client id: " + cid.toString());
            ChannelFuture future = ctx.close();
            boolean is = future.isSuccess();
            LogUtils.v("close be invoke.is success?" + is);

        } catch (Exception ex) {
            ex.toString();
        }

    }

From source file:cn.savor.small.netty.NettyClient.java

License:Open Source License

public void connect() {
    System.out.println("client connection.................");
    if (channel != null && channel.isActive()) {
        return;/*from w ww  .ja v a 2 s.c  o m*/
    }

    ChannelFuture future = bootstrap.connect(host, port);
    System.out.println("client connection.................host=" + host + ",port=" + port + ",future="
            + future.isSuccess());

    future.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture futureListener) throws Exception {
            if (futureListener.isSuccess()) {
                channel = futureListener.channel();
                System.out.println("Connect to server successfully!");
            } else {
                System.out.println("Failed to connect to server, try connect after 10s");

                futureListener.channel().eventLoop().schedule(new Runnable() {
                    @Override
                    public void run() {
                        connect();
                    }
                }, 1, TimeUnit.SECONDS);
            }
        }
    });
}

From source file:cn.savor.small.netty.NettyClientHandler.java

License:Open Source License

public void close(ChannelHandlerContext ctx) {
    try {/*from w  w  w .j a v a 2 s.co  m*/
        Channel cid = ctx.pipeline().channel();
        LogUtils.v("close a client id: " + cid.toString());
        ChannelFuture future = ctx.close();
        boolean is = future.isSuccess();
        LogUtils.v("close be invoke.is success?" + is);

    } catch (Exception ex) {
        ex.toString();
    }

}

From source file:cn.wantedonline.puppy.httpserver.component.HttpObjectAggregator.java

License:Apache License

@Override
protected void decode(final ChannelHandlerContext ctx, HttpObject msg, List<Object> out) throws Exception {
    AggregatedFullHttpMessage currentMessage = this.currentMessage;

    if (msg instanceof HttpMessage) {
        tooLongFrameFound = false;/* w  ww.ja v a2s  . c  om*/
        assert currentMessage == null;

        HttpMessage m = (HttpMessage) msg;

        // Handle the 'Expect: 100-continue' header if necessary.
        if (is100ContinueExpected(m)) {
            if (HttpHeaders.getContentLength(m, 0) > maxContentLength) {
                tooLongFrameFound = true;
                final ChannelFuture future = ctx.writeAndFlush(EXPECTATION_FAILED.duplicate().retain());
                future.addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (!future.isSuccess()) {
                            ctx.fireExceptionCaught(future.cause());
                        }
                    }
                });
                if (closeOnExpectationFailed) {
                    future.addListener(ChannelFutureListener.CLOSE);
                }
                ctx.pipeline().fireUserEventTriggered(HttpExpectationFailedEvent.INSTANCE);
                return;
            }
            ctx.writeAndFlush(CONTINUE.duplicate().retain()).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        ctx.fireExceptionCaught(future.cause());
                    }
                }
            });
        }

        if (!m.getDecoderResult().isSuccess()) {
            removeTransferEncodingChunked(m);
            out.add(toFullMessage(m));
            this.currentMessage = null;
            return;
        }
        if (msg instanceof HttpRequest) {
            HttpRequest header = (HttpRequest) msg;
            this.currentMessage = currentMessage = new AggregatedFullHttpRequest(header,
                    ctx.alloc().compositeBuffer(maxCumulationBufferComponents), null);
        } else if (msg instanceof HttpResponse) {
            HttpResponse header = (HttpResponse) msg;
            this.currentMessage = currentMessage = new AggregatedFullHttpResponse(header,
                    Unpooled.compositeBuffer(maxCumulationBufferComponents), null);
        } else {
            throw new Error();
        }

        // A streamed message - initialize the cumulative buffer, and wait for incoming chunks.
        removeTransferEncodingChunked(currentMessage);
    } else if (msg instanceof HttpContent) {
        if (tooLongFrameFound) {
            if (msg instanceof LastHttpContent) {
                this.currentMessage = null;
            }
            // already detect the too long frame so just discard the content
            return;
        }
        assert currentMessage != null;

        // Merge the received chunk into the content of the current message.
        HttpContent chunk = (HttpContent) msg;
        CompositeByteBuf content = (CompositeByteBuf) currentMessage.content();

        if (content.readableBytes() > maxContentLength - chunk.content().readableBytes()) {
            tooLongFrameFound = true;

            // release current message to prevent leaks
            currentMessage.release();
            this.currentMessage = null;

            throw new TooLongFrameException("HTTP content length exceeded " + maxContentLength + " bytes.");
        }

        // Append the content of the chunk
        if (chunk.content().isReadable()) {
            chunk.retain();
            content.addComponent(chunk.content());
            content.writerIndex(content.writerIndex() + chunk.content().readableBytes());
        }

        final boolean last;
        if (!chunk.getDecoderResult().isSuccess()) {
            currentMessage.setDecoderResult(DecoderResult.failure(chunk.getDecoderResult().cause()));
            last = true;
        } else {
            last = chunk instanceof LastHttpContent;
        }

        if (last) {
            this.currentMessage = null;

            // Merge trailing headers into the message.
            if (chunk instanceof LastHttpContent) {
                LastHttpContent trailer = (LastHttpContent) chunk;
                currentMessage.setTrailingHeaders(trailer.trailingHeaders());
            } else {
                currentMessage.setTrailingHeaders(new DefaultHttpHeaders());
            }

            // Set the 'Content-Length' header. If one isn't already set.
            // This is important as HEAD responses will use a 'Content-Length' header which
            // does not match the actual body, but the number of bytes that would be
            // transmitted if a GET would have been used.
            //
            // See rfc2616 14.13 Content-Length
            if (!isContentLengthSet(currentMessage)) {
                currentMessage.headers().set(HttpHeaders.Names.CONTENT_LENGTH,
                        String.valueOf(content.readableBytes()));
            }
            // All done
            out.add(currentMessage);
        }
    } else {
        throw new Error();
    }
}