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.netty.grpc.proxy.demo.handler.GrpcProxyFrontendHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) {
    final Channel inboundChannel = ctx.channel();

    // ??/*  w  ww.  j  a va2 s  . c o m*/
    Bootstrap b = new Bootstrap();
    b.group(inboundChannel.eventLoop()).channel(ctx.channel().getClass())
            .handler(new GrpcProxyBackendHandler(inboundChannel)).option(ChannelOption.AUTO_READ, false);

    for (int i = 0; i < remoteHosts.length; i++) {
        final ChannelFuture f = b.connect(remoteHosts[i], remotePorts[i]);
        outboundChannels[i] = f.channel();
        f.addListener(new ChannelFutureListener() {
            public void operationComplete(ChannelFuture future) {
                if (future.isSuccess()) {
                    // connection complete start to read first data
                    inboundChannel.read();
                    //                        System.out.println(f.channel().remoteAddress() + ", " + f.channel().localAddress());
                } else {
                    // Close the connection if the connection attempt has failed.
                    //                        System.out.println("channelActive close" + inboundChannel.remoteAddress() + ", " + inboundChannel.localAddress());
                    inboundChannel.close();
                }
            }
        });
    }
}

From source file:com.netty.grpc.proxy.demo.handler.GrpcProxyFrontendHandler.java

License:Apache License

private void handleSettingFrame(final ChannelHandlerContext ctx, Http2Flags flags) {
    ByteBufAllocator alloc = ctx.alloc();
    ByteBuf byteBuf = alloc.buffer();/* w ww  . j av a 2s .  com*/
    if (!flags.ack()) {
        //            System.out.println("********************* setting received ...");

        //00 00 0c 04 00 00 00 00 00 00 03 7f ff ff ff 00
        byteBuf.writeByte(0x00);
        byteBuf.writeByte(0x00);
        byteBuf.writeByte(0x0c);
        byteBuf.writeByte(0x04);
        byteBuf.writeByte(0x00);
        byteBuf.writeByte(0x00);
        byteBuf.writeByte(0x00);
        byteBuf.writeByte(0x00);
        byteBuf.writeByte(0x00);
        byteBuf.writeByte(0x00);
        byteBuf.writeByte(0x03);
        byteBuf.writeByte(0x7f);
        byteBuf.writeByte(0xff);
        byteBuf.writeByte(0xff);
        byteBuf.writeByte(0xff);
        byteBuf.writeByte(0x00);
        //04 00 10 00 00
        byteBuf.writeByte(0x04);
        byteBuf.writeByte(0x00);
        byteBuf.writeByte(0x10);
        byteBuf.writeByte(0x00);
        byteBuf.writeByte(0x00);
    } else {
        //            System.out.println("********************* setting ack received ...");
        //00 00 00 04 01 00 00 00 00
        byteBuf.writeByte(0x00);
        byteBuf.writeByte(0x00);
        byteBuf.writeByte(0x00);
        byteBuf.writeByte(0x04);
        byteBuf.writeByte(0x01);
        byteBuf.writeByte(0x00);
        byteBuf.writeByte(0x00);
        byteBuf.writeByte(0x00);
        byteBuf.writeByte(0x00);
    }
    ctx.writeAndFlush(byteBuf).addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                //                    System.out.println(" ...operationComplete isSuccess");
                ctx.channel().read();
            } else {
                //                    System.out.println("...operationComplete failure");
                future.channel().close();
            }
        }
    });

}

From source file:com.netty.grpc.proxy.demo.handler.GrpcProxyFrontendHandler.java

License:Apache License

private void forwardThisFrame(final ChannelHandlerContext ctx, final ByteBuf copy, int streamId,
        final int type) {
    if (selectedChannel == null) {
        int select = (counter.getAndIncrement()) % remoteHosts.length;
        selectedChannel = outboundChannels[select];
    }/*from w w w.  ja v  a 2s .c  om*/

    //int select = 0;
    //        System.out.println("---------------------------------select:" + select + "," + ByteBufUtil.hexDump(copy));
    final Channel inboundChannel = ctx.channel();
    selectedChannel.writeAndFlush(copy).addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) {
            if (future.isSuccess()) {
                //                    System.out.println("forward success ------------------------------------------type=" + type);
                inboundChannel.read();
            } else {
                //                    System.out.println("forward failure------------------------------------------");
                inboundChannel.close();
            }
        }
    });
}

From source file:com.newlandframework.avatarmq.broker.LauncherListener.java

License:Apache License

public void operationComplete(ChannelFuture future) throws Exception {
    if (!future.isSuccess()) {
        invoke.setReason(future.cause());
    }//  www .  ja v a  2  s. c  o  m
}

From source file:com.newlandframework.avatarmq.netty.MessageProcessor.java

License:Apache License

public void sendAsynMessage(RequestMessage request, final NotifyCallback listener) {
    Channel channel = factory.getMessageChannel();
    if (channel == null) {
        return;/*from   w  ww.j  ava 2 s  . c  om*/
    }

    Map<String, CallBackInvoker<Object>> callBackMap = factory.getCallBackMap();

    CallBackInvoker<Object> invoker = new CallBackInvoker<Object>();
    callBackMap.put(request.getMsgId(), invoker);

    invoker.setRequestId(request.getMsgId());

    invoker.join(new CallBackListener<Object>() {
        public void onCallBack(Object t) {
            ResponseMessage response = (ResponseMessage) t;
            listener.onEvent((ProducerAckMessage) response.getMsgParams());

        }
    });

    ChannelFuture channelFuture = channel.writeAndFlush(request);
    channelFuture.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                invoker.setReason(future.cause());
            }
        }
    });

}

From source file:com.newlandframework.avatarmq.netty.MessageProcessor.java

License:Apache License

public Object sendAsynMessage(RequestMessage request) {
    Channel channel = factory.getMessageChannel();

    if (channel == null) {
        return null;
    }/*from   w  ww  .  j  av a  2s  . c  o m*/

    Map<String, CallBackInvoker<Object>> callBackMap = factory.getCallBackMap();

    CallBackInvoker<Object> invoker = new CallBackInvoker<Object>();
    callBackMap.put(request.getMsgId(), invoker);
    invoker.setRequestId(request.getMsgId());

    ChannelFuture channelFuture = channel.writeAndFlush(request);
    channelFuture.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                invoker.setReason(future.cause());
            }
        }
    });

    try {
        Object result = invoker.getMessageResult(factory.getTimeOut(), TimeUnit.MILLISECONDS);
        callBackMap.remove(request.getMsgId());
        return result;
    } catch (RuntimeException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.newlandframework.avatarmq.netty.MessageProcessor.java

License:Apache License

public void sendSyncMessage(RequestMessage request) {
    Channel channel = factory.getMessageChannel();

    if (channel == null) {
        return;//w  w  w.  j a  v a  2s. co m
    }

    Map<String, CallBackInvoker<Object>> callBackMap = factory.getCallBackMap();

    CallBackInvoker<Object> invoker = new CallBackInvoker<Object>();
    callBackMap.put(request.getMsgId(), invoker);

    invoker.setRequestId(request.getMsgId());

    ChannelFuture channelFuture;
    try {
        channelFuture = channel.writeAndFlush(request).sync();
        channelFuture.addListener(new ChannelFutureListener() {

            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    invoker.setReason(future.cause());
                }
            }
        });
    } catch (InterruptedException ex) {
        Logger.getLogger(MessageProcessor.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.newlandframework.rpc.netty.MessageSendInitializeTask.java

License:Apache License

public Boolean call() {
    Bootstrap b = new Bootstrap();
    b.group(eventLoopGroup).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true);
    b.handler(new MessageSendChannelInitializer().buildRpcSerializeProtocol(protocol));

    ChannelFuture channelFuture = b.connect(serverAddress);
    channelFuture.addListener(new ChannelFutureListener() {
        public void operationComplete(final ChannelFuture channelFuture) throws Exception {
            if (channelFuture.isSuccess()) {
                MessageSendHandler handler = channelFuture.channel().pipeline().get(MessageSendHandler.class);
                RpcServerLoader.getInstance().setMessageSendHandler(handler);
            }/*w w w  . j  a  va  2  s  .  c  o  m*/
        }
    });
    return Boolean.TRUE;
}

From source file:com.ning.http.client.providers.netty_4.NettyConnectListener.java

License:Apache License

public final void operationComplete(ChannelFuture f) throws Exception {
    if (f.isSuccess()) {
        Channel channel = f.channel();
        channel.pipeline().context(NettyAsyncHttpProvider.class).attr(NettyAsyncHttpProvider.DEFAULT_ATTRIBUTE)
                .set(future);/*from   ww  w.  ja  v a 2  s  .c  om*/
        SslHandler sslHandler = (SslHandler) channel.pipeline().get(NettyAsyncHttpProvider.SSL_HANDLER);
        if (!handshakeDone.getAndSet(true) && (sslHandler != null)) {
            ((SslHandler) channel.pipeline().get(NettyAsyncHttpProvider.SSL_HANDLER)).handshake()
                    .addListener(this);
            return;
        }

        HostnameVerifier v = config.getHostnameVerifier();
        if (sslHandler != null) {
            if (!v.verify(future.getURI().getHost(), sslHandler.engine().getSession())) {
                ConnectException exception = new ConnectException("HostnameVerifier exception.");
                future.abort(exception);
                throw exception;
            }
        }

        future.provider().writeRequest(f.channel(), config, future, nettyRequest);
    } else {
        Throwable cause = f.cause();

        logger.debug("Trying to recover a dead cached channel {} with a retry value of {} ", f.channel(),
                future.canRetry());
        if (future.canRetry() && cause != null
                && (NettyAsyncHttpProvider.abortOnDisconnectException(cause)
                        || ClosedChannelException.class.isAssignableFrom(cause.getClass())
                        || future.getState() != NettyResponseFuture.STATE.NEW)) {

            logger.debug("Retrying {} ", nettyRequest);
            if (future.provider().remotelyClosed(f.channel(), future)) {
                return;
            }
        }

        logger.debug("Failed to recover from exception: {} with channel {}", cause, f.channel());

        boolean printCause = f.cause() != null && cause.getMessage() != null;
        ConnectException e = new ConnectException(
                printCause ? cause.getMessage() + " to " + future.getURI().toString()
                        : future.getURI().toString());
        if (cause != null) {
            e.initCause(cause);
        }
        future.abort(e);
    }
}

From source file:com.nitesh.netty.snoop.client.HttpSnoopClient.java

License:Apache License

private void sendRequest() {
    // Prepare the HTTP request.
    FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
            uri.getRawPath());/* ww w.java 2s  . c  o  m*/
    //HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath());
    request.headers().set(HttpHeaders.Names.HOST, host);
    request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);
    request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, 0);

    // Set some example cookies.
    request.headers().set(HttpHeaders.Names.COOKIE, ClientCookieEncoder
            .encode(new DefaultCookie("my-cookie", "foo"), new DefaultCookie("another-cookie", "bar")));

    // Send the HTTP request.
    ch.writeAndFlush(request).addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            System.out.println("Request sent. Success? " + future.isSuccess());
            if (!future.isSuccess()) {
                future.cause().printStackTrace(System.out);
            }
        }
    });
}