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.chenyang.proxy.http.HttpUserAgentForwardHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext uaChannelCtx, final Object msg) throws Exception {

    final Channel uaChannel = uaChannelCtx.channel();

    final HttpRemote apnProxyRemote = uaChannel.attr(HttpConnectionAttribute.ATTRIBUTE_KEY).get().getRemote();

    if (msg instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) msg;

        Channel remoteChannel = remoteChannelMap.get(apnProxyRemote.getRemoteAddr());

        if (remoteChannel != null && remoteChannel.isActive()) {
            HttpRequest request = constructRequestForProxy(httpRequest, apnProxyRemote);
            remoteChannel.writeAndFlush(request);
        } else {/*from   w  w w.  j a  v a2 s .com*/

            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(uaChannel.eventLoop()).channel(NioSocketChannel.class)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                    .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .option(ChannelOption.AUTO_READ, false)
                    .handler(new HttpRemoteForwardChannelInitializer(uaChannel, this));

            ChannelFuture remoteConnectFuture = bootstrap.connect(apnProxyRemote.getInetSocketAddress(),
                    new InetSocketAddress(NetworkUtils.getCyclicLocalIp().getHostAddress(), 0));
            remoteChannel = remoteConnectFuture.channel();
            remoteChannelMap.put(apnProxyRemote.getRemoteAddr(), remoteChannel);

            remoteConnectFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        future.channel().write(constructRequestForProxy((HttpRequest) msg, apnProxyRemote));

                        for (HttpContent hc : httpContentBuffer) {
                            future.channel().writeAndFlush(hc);

                            if (hc instanceof LastHttpContent) {
                                future.channel().writeAndFlush(Unpooled.EMPTY_BUFFER)
                                        .addListener(new ChannelFutureListener() {
                                            @Override
                                            public void operationComplete(ChannelFuture future)
                                                    throws Exception {
                                                if (future.isSuccess()) {
                                                    future.channel().read();
                                                }

                                            }
                                        });
                            }
                        }
                        httpContentBuffer.clear();
                    } else {
                        HttpErrorUtil.writeAndFlush(uaChannel, HttpResponseStatus.INTERNAL_SERVER_ERROR);
                        httpContentBuffer.clear();
                        future.channel().close();
                    }
                }
            });

        }
        ReferenceCountUtil.release(msg);
    } else {
        Channel remoteChannel = remoteChannelMap.get(apnProxyRemote.getRemoteAddr());
        HttpContent hc = ((HttpContent) msg);
        if (remoteChannel != null && remoteChannel.isActive()) {
            remoteChannel.writeAndFlush(hc);

            if (hc instanceof LastHttpContent) {
                remoteChannel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        if (future.isSuccess()) {
                            future.channel().read();
                        }

                    }
                });
            }
        } else {
            httpContentBuffer.add(hc);
        }
    }

}

From source file:com.chenyang.proxy.http.HttpUserAgentTunnelHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext uaChannelCtx, Object msg) throws Exception {

    if (msg instanceof HttpRequest) {
        // Channel uaChannel = uaChannelCtx.channel();

        // connect remote
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(uaChannelCtx.channel().eventLoop()).channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
                .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                .option(ChannelOption.AUTO_READ, false)
                .handler(new HttpTunnelChannelInitializer(uaChannelCtx.channel()));

        final HttpRemote apnProxyRemote = uaChannelCtx.channel().attr(HttpConnectionAttribute.ATTRIBUTE_KEY)
                .get().getRemote();/* w  w w  .jav a  2s . co  m*/

        bootstrap
                .connect(apnProxyRemote.getInetSocketAddress(),
                        new InetSocketAddress(NetworkUtils.getCyclicLocalIp().getHostAddress(), 0))
                .addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(final ChannelFuture future1) throws Exception {
                        if (future1.isSuccess()) {
                            HttpResponse proxyConnectSuccessResponse = new DefaultFullHttpResponse(
                                    HttpVersion.HTTP_1_1,
                                    new HttpResponseStatus(200, "Connection established"));
                            uaChannelCtx.writeAndFlush(proxyConnectSuccessResponse)
                                    .addListener(new ChannelFutureListener() {
                                        @Override
                                        public void operationComplete(ChannelFuture future2) throws Exception {
                                            // remove handlers
                                            uaChannelCtx.pipeline().remove("codec");
                                            uaChannelCtx.pipeline().remove(HttpPreHandler.HANDLER_NAME);
                                            uaChannelCtx.pipeline()
                                                    .remove(HttpUserAgentTunnelHandler.HANDLER_NAME);

                                            uaChannelCtx.pipeline()
                                                    .addLast(new HttpRelayHandler(
                                                            "UA --> " + apnProxyRemote.getRemoteAddr(),
                                                            future1.channel()));
                                        }

                                    });

                        } else {
                            if (uaChannelCtx.channel().isActive()) {
                                uaChannelCtx.channel().writeAndFlush(Unpooled.EMPTY_BUFFER)
                                        .addListener(ChannelFutureListener.CLOSE);
                            }
                        }
                    }
                });

    }
    ReferenceCountUtil.release(msg);
}

From source file:com.cloudera.livy.client.local.rpc.Rpc.java

License:Apache License

/**
 * Creates an RPC client for a server running on the given remote host and port.
 *
 * @param config RPC configuration data.
 * @param eloop Event loop for managing the connection.
 * @param host Host name or IP address to connect to.
 * @param port Port where server is listening.
 * @param clientId The client ID that identifies the connection.
 * @param secret Secret for authenticating the client with the server.
 * @param dispatcher Dispatcher used to handle RPC calls.
 * @return A future that can be used to monitor the creation of the RPC object.
 *//*  w ww .  j a v a 2s .  c  o  m*/
public static Promise<Rpc> createClient(final LocalConf config, final EventLoopGroup eloop, String host,
        int port, final String clientId, final String secret, final RpcDispatcher dispatcher) throws Exception {
    int connectTimeoutMs = (int) config.getTimeAsMs(RPC_CLIENT_CONNECT_TIMEOUT);

    final ChannelFuture cf = new Bootstrap().group(eloop).handler(new ChannelInboundHandlerAdapter() {
    }).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMs).connect(host, port);

    final Promise<Rpc> promise = eloop.next().newPromise();
    final AtomicReference<Rpc> rpc = new AtomicReference<Rpc>();

    // Set up a timeout to undo everything.
    final Runnable timeoutTask = new Runnable() {
        @Override
        public void run() {
            promise.setFailure(new TimeoutException("Timed out waiting for RPC server connection."));
        }
    };
    final ScheduledFuture<?> timeoutFuture = eloop.schedule(timeoutTask,
            config.getTimeAsMs(RPC_CLIENT_HANDSHAKE_TIMEOUT), TimeUnit.MILLISECONDS);

    // The channel listener instantiates the Rpc instance when the connection is established,
    // and initiates the SASL handshake.
    cf.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture cf) throws Exception {
            if (cf.isSuccess()) {
                SaslClientHandler saslHandler = new SaslClientHandler(config, clientId, promise, timeoutFuture,
                        secret, dispatcher);
                Rpc rpc = createRpc(config, saslHandler, (SocketChannel) cf.channel(), eloop);
                saslHandler.rpc = rpc;
                saslHandler.sendHello(cf.channel());
            } else {
                promise.setFailure(cf.cause());
            }
        }
    });

    // Handle cancellation of the promise.
    promise.addListener(new GenericFutureListener<Promise<Rpc>>() {
        @Override
        public void operationComplete(Promise<Rpc> p) {
            if (p.isCancelled()) {
                cf.cancel(true);
            }
        }
    });

    return promise;
}

From source file:com.cloudera.livy.client.local.rpc.Rpc.java

License:Apache License

/**
 * Send an RPC call to the remote endpoint and returns a future that can be used to monitor the
 * operation.//from www. j  a  v a  2s  . c  o  m
 *
 * @param msg RPC call to send.
 * @param retType Type of expected reply.
 * @return A future used to monitor the operation.
 */
public <T> Future<T> call(Object msg, Class<T> retType) {
    Preconditions.checkArgument(msg != null);
    Preconditions.checkState(channel.isOpen(), "RPC channel is closed.");
    try {
        final long id = rpcId.getAndIncrement();
        final Promise<T> promise = createPromise();
        ChannelFutureListener listener = new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture cf) {
                if (!cf.isSuccess() && !promise.isDone()) {
                    LOG.warn("Failed to send RPC, closing connection.", cf.cause());
                    promise.setFailure(cf.cause());
                    dispatcher.discardRpc(id);
                    close();
                }
            }
        };

        dispatcher.registerRpc(id, promise, msg.getClass().getName());
        synchronized (channelLock) {
            channel.write(new MessageHeader(id, Rpc.MessageType.CALL)).addListener(listener);
            channel.writeAndFlush(msg).addListener(listener);
        }
        return promise;
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:com.cloudera.livy.rsc.rpc.Rpc.java

License:Apache License

/**
 * Creates an RPC client for a server running on the given remote host and port.
 *
 * @param config RPC configuration data.
 * @param eloop Event loop for managing the connection.
 * @param host Host name or IP address to connect to.
 * @param port Port where server is listening.
 * @param clientId The client ID that identifies the connection.
 * @param secret Secret for authenticating the client with the server.
 * @param dispatcher Dispatcher used to handle RPC calls.
 * @return A future that can be used to monitor the creation of the RPC object.
 *//* w  w w. j a  v a2  s  .co m*/
public static Promise<Rpc> createClient(final RSCConf config, final EventLoopGroup eloop, String host, int port,
        final String clientId, final String secret, final RpcDispatcher dispatcher) throws Exception {
    int connectTimeoutMs = (int) config.getTimeAsMs(RPC_CLIENT_CONNECT_TIMEOUT);

    final ChannelFuture cf = new Bootstrap().group(eloop).handler(new ChannelInboundHandlerAdapter() {
    }).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMs).connect(host, port);

    final Promise<Rpc> promise = eloop.next().newPromise();
    final AtomicReference<Rpc> rpc = new AtomicReference<Rpc>();

    // Set up a timeout to undo everything.
    final Runnable timeoutTask = new Runnable() {
        @Override
        public void run() {
            promise.setFailure(new TimeoutException("Timed out waiting for RPC server connection."));
        }
    };
    final ScheduledFuture<?> timeoutFuture = eloop.schedule(timeoutTask,
            config.getTimeAsMs(RPC_CLIENT_HANDSHAKE_TIMEOUT), TimeUnit.MILLISECONDS);

    // The channel listener instantiates the Rpc instance when the connection is established,
    // and initiates the SASL handshake.
    cf.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture cf) throws Exception {
            if (cf.isSuccess()) {
                SaslClientHandler saslHandler = new SaslClientHandler(config, clientId, promise, timeoutFuture,
                        secret, dispatcher);
                Rpc rpc = createRpc(config, saslHandler, (SocketChannel) cf.channel(), eloop);
                saslHandler.rpc = rpc;
                saslHandler.sendHello(cf.channel());
            } else {
                promise.setFailure(cf.cause());
            }
        }
    });

    // Handle cancellation of the promise.
    promise.addListener(new GenericFutureListener<Promise<Rpc>>() {
        @Override
        public void operationComplete(Promise<Rpc> p) {
            if (p.isCancelled()) {
                cf.cancel(true);
            }
        }
    });

    return promise;
}

From source file:com.cloudera.livy.rsc.rpc.Rpc.java

License:Apache License

/**
 * Send an RPC call to the remote endpoint and returns a future that can be used to monitor the
 * operation.//  w ww  . jav a2  s. com
 *
 * @param msg RPC call to send.
 * @param retType Type of expected reply.
 * @return A future used to monitor the operation.
 */
public <T> Future<T> call(Object msg, Class<T> retType) {
    Utils.checkArgument(msg != null);
    Utils.checkState(channel.isOpen(), "RPC channel is closed.");
    try {
        final long id = rpcId.getAndIncrement();
        final Promise<T> promise = egroup.next().newPromise();
        ChannelFutureListener listener = new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture cf) {
                if (!cf.isSuccess() && !promise.isDone()) {
                    LOG.warn("Failed to send RPC, closing connection.", cf.cause());
                    promise.setFailure(cf.cause());
                    dispatcher.discardRpc(id);
                    close();
                }
            }
        };

        dispatcher.registerRpc(id, promise, msg.getClass().getName());
        synchronized (channelLock) {
            channel.write(new MessageHeader(id, Rpc.MessageType.CALL)).addListener(listener);
            channel.writeAndFlush(msg).addListener(listener);
        }
        return promise;
    } catch (Exception e) {
        throw Utils.propagate(e);
    }
}

From source file:com.cloudhopper.smpp.impl.DefaultSmppClient.java

License:Apache License

protected Channel createConnectedChannel(String host, int port, long connectTimeoutMillis)
        throws SmppTimeoutException, SmppChannelException, InterruptedException {
    // a socket address used to "bind" to the remote system
    InetSocketAddress socketAddr = new InetSocketAddress(host, port);

    // attempt to connect to the remote system
    ChannelFuture connectFuture = this.clientBootstrap.connect(socketAddr);

    // wait until the connection is made successfully
    boolean timeout = !connectFuture.await(connectTimeoutMillis);

    if (timeout) {
        throw new SmppChannelConnectTimeoutException("Unable to connect to host [" + host + "] and port ["
                + port + "] within " + connectTimeoutMillis + " ms");
    }//from   ww w  .  java  2s.  c o  m

    if (!connectFuture.isSuccess()) {
        throw new SmppChannelConnectException("Unable to connect to host [" + host + "] and port [" + port
                + "]: " + connectFuture.cause().getMessage(), connectFuture.cause());
    }

    // if we get here, then we were able to connect and get a channel
    return connectFuture.channel();
}

From source file:com.cloudhopper.smpp.impl.DefaultSmppServer.java

License:Apache License

@Override
public void start() throws SmppChannelException {
    if (isDestroyed()) {
        throw new SmppChannelException("Unable to start: server is destroyed");
    }// w  w  w . j av a  2  s  .com
    try {
        ChannelFuture f = this.serverBootstrap.bind(new InetSocketAddress(configuration.getPort()));

        // wait until the connection is made successfully
        boolean timeout = !f.await(configuration.getBindTimeout());

        if (timeout || !f.isSuccess())
            throw new SmppChannelException("Can't bind to port " + configuration.getPort() + " after "
                    + configuration.getBindTimeout() + " milliseconds");

        logger.info("{} started on SMPP port [{}]", configuration.getName(), configuration.getPort());
        serverChannel = f.channel();
    } catch (ChannelException e) {
        throw new SmppChannelException(e.getMessage(), e);
    } catch (InterruptedException e) {
        throw new SmppChannelException(e.getMessage(), e);
    }
}

From source file:com.cloudhopper.smpp.impl.DefaultSmppSession.java

License:Apache License

@SuppressWarnings("unchecked")
@Override/*from  w  ww .  j  ava  2s . c o m*/
public WindowFuture<Integer, PduRequest, PduResponse> sendRequestPdu(PduRequest pdu, long timeoutMillis,
        boolean synchronous) throws RecoverablePduException, UnrecoverablePduException, SmppTimeoutException,
        SmppChannelException, InterruptedException {
    // assign the next PDU sequence # if its not yet assigned
    if (!pdu.hasSequenceNumberAssigned()) {
        pdu.setSequenceNumber(this.sequenceNumber.next());
    }

    // encode the pdu into a buffer
    ByteBuf buffer = transcoder.encode(pdu);

    WindowFuture<Integer, PduRequest, PduResponse> future = null;
    try {
        future = sendWindow.offer(pdu.getSequenceNumber(), pdu, timeoutMillis,
                configuration.getRequestExpiryTimeout(), synchronous);
    } catch (DuplicateKeyException e) {
        throw new UnrecoverablePduException(e.getMessage(), e);
    } catch (OfferTimeoutException e) {
        throw new SmppTimeoutException(e.getMessage(), e);
    }

    // we need to log the PDU after encoding since some things only happen
    // during the encoding process such as looking up the result message
    if (configuration.getLoggingOptions().isLogPduEnabled()) {
        if (synchronous) {
            logger.info("sync send PDU: {}", pdu);
        } else {
            logger.info("async send PDU: {}", pdu);
        }
    }

    // write the pdu out & wait timeout amount of time
    ChannelFuture channelFuture = this.channel.writeAndFlush(buffer);
    if (configuration.getWriteTimeout() > 0) {
        channelFuture.await(configuration.getWriteTimeout());
    } else {
        channelFuture.await();
    }

    // check if the write was a success
    if (!channelFuture.isSuccess()) {
        // the write failed, make sure to throw an exception
        throw new SmppChannelException(channelFuture.cause().getMessage(), channelFuture.cause());
    }

    this.countSendRequestPdu(pdu);

    return future;
}

From source file:com.cloudhopper.smpp.impl.DefaultSmppSession.java

License:Apache License

/**
 * Asynchronously sends a PDU and does not wait for a response PDU.
 * This method will wait for the PDU to be written to the underlying channel.
 * @param pdu The PDU to send (can be either a response or request)
 * @throws RecoverablePduException/*w w w .j  a v a  2s .c  om*/
 * @throws UnrecoverablePduException
 * @throws SmppChannelException
 * @throws InterruptedException
 */
@Override
public void sendResponsePdu(PduResponse pdu)
        throws RecoverablePduException, UnrecoverablePduException, SmppChannelException, InterruptedException {
    // assign the next PDU sequence # if its not yet assigned
    if (!pdu.hasSequenceNumberAssigned()) {
        pdu.setSequenceNumber(this.sequenceNumber.next());
    }

    // encode the pdu into a buffer
    ByteBuf buffer = transcoder.encode(pdu);

    // we need to log the PDU after encoding since some things only happen
    // during the encoding process such as looking up the result message
    if (configuration.getLoggingOptions().isLogPduEnabled()) {
        logger.info("send PDU: {}", pdu);
    }

    // write the pdu out & wait timeout amount of time
    ChannelFuture channelFuture = this.channel.writeAndFlush(buffer);
    if (configuration.getWriteTimeout() > 0) {
        channelFuture.await(configuration.getWriteTimeout());
    } else {
        channelFuture.await();
    }

    // check if the write was a success
    if (!channelFuture.isSuccess()) {
        // the write failed, make sure to throw an exception
        throw new SmppChannelException(channelFuture.cause().getMessage(), channelFuture.cause());
    }
}