Example usage for io.netty.util.concurrent Promise setFailure

List of usage examples for io.netty.util.concurrent Promise setFailure

Introduction

In this page you can find the example usage for io.netty.util.concurrent Promise setFailure.

Prototype

Promise<V> setFailure(Throwable cause);

Source Link

Document

Marks this future as a failure and notifies all listeners.

Usage

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.
 *//*from ww w  . j  av  a2 s .  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  w  ww.  ja v a  2s .  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) {
    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.
 *///from  w  ww. j a va 2s  .  c o  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./*from   w w  w. j a v  a 2 s. 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) {
    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.cloudera.livy.rsc.RSCClient.java

License:Apache License

private <T> io.netty.util.concurrent.Future<T> deferredCall(final Object msg, final Class<T> retType) {
    if (driverRpc.isSuccess()) {
        try {//from  w  ww  .j av  a2  s.  co m
            return driverRpc.get().call(msg, retType);
        } catch (Exception ie) {
            throw Utils.propagate(ie);
        }
    }

    // No driver RPC yet, so install a listener and return a promise that will be ready when
    // the driver is up and the message is actually delivered.
    final Promise<T> promise = eventLoopGroup.next().newPromise();
    final FutureListener<T> callListener = new FutureListener<T>() {
        @Override
        public void onSuccess(T value) throws Exception {
            promise.setSuccess(value);
        }

        @Override
        public void onFailure(Throwable error) throws Exception {
            promise.setFailure(error);
        }
    };

    Utils.addListener(driverRpc, new FutureListener<Rpc>() {
        @Override
        public void onSuccess(Rpc rpc) throws Exception {
            Utils.addListener(rpc.call(msg, retType), callListener);
        }

        @Override
        public void onFailure(Throwable error) throws Exception {
            promise.setFailure(error);
        }
    });
    return promise;
}

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

License:MIT License

@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {

    AutoFlushWriterChannelQueue queue = m_channelQueue.remove(ctx.channel());

    if (queue == null) {
        ctx.fireChannelInactive();//from www.  j  av a 2  s. c  o  m
        return;
    }

    MessageEvent[] events = queue.get();

    if (events == null) {
        ctx.fireChannelInactive();
        return;
    }

    Throwable cause = new ClosedChannelException();

    for (int i = 0; i < events.length; i++) {

        MessageEvent ev = events[i];

        Promise promise = ev.getPromise();

        if (promise != null)
            promise.setFailure(cause);

        ((ByteBuf) ev.getMsg()).release();

    }

    if (queue != null) {
        queue.clear();

    }

    ctx.fireChannelInactive();
}

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

License:MIT License

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

    LOGGER.error(cause.getLocalizedMessage(), cause);

    AutoFlushWriterChannelQueue queue = m_channelQueue.remove(ctx.channel());

    if (queue == null)
        return;/*from  www .  j  a  v a2 s .c  om*/

    MessageEvent[] events = queue.get();

    if (events == null)
        return;

    for (int i = 0; i < events.length; i++) {

        MessageEvent ev = events[i];

        Promise promise = ev.getPromise();

        if (promise != null)
            promise.setFailure(cause);

        ((ByteBuf) ev.getMsg()).release();

    }

    if (queue != null) {
        queue.clear();

    }

    super.exceptionCaught(ctx, cause);
}

From source file:com.linecorp.armeria.client.circuitbreaker.CircuitBreakerRemoteInvoker.java

License:Apache License

@Override
public <T> Future<T> invoke(EventLoop eventLoop, URI uri, ClientOptions options, ClientCodec codec,
        Method method, Object[] args) throws Exception {

    final CircuitBreaker circuitBreaker;
    try {// ww w. j a v  a  2  s .  c  o  m
        circuitBreaker = mapping.get(eventLoop, uri, options, codec, method, args);
    } catch (Throwable t) {
        logger.warn("Failed to get a circuit breaker from mapping", t);
        return delegate().invoke(eventLoop, uri, options, codec, method, args);
    }

    if (circuitBreaker.canRequest()) {
        final Future<T> resultFut = delegate().invoke(eventLoop, uri, options, codec, method, args);
        resultFut.addListener(future -> {
            if (future.isSuccess()) {
                // reports success event
                circuitBreaker.onSuccess();
            } else {
                circuitBreaker.onFailure(future.cause());
            }
        });
        return resultFut;
    } else {
        // the circuit is tripped

        // prepares a failed resultPromise
        final Promise<T> resultPromise = eventLoop.newPromise();
        resultPromise.setFailure(new FailFastException(circuitBreaker));
        codec.prepareRequest(method, args, resultPromise);

        // returns immediately without calling succeeding remote invokers
        return resultPromise;
    }
}

From source file:com.linecorp.armeria.client.endpoint.dns.DnsEndpointGroup.java

License:Apache License

private void sendQueries() {
    if (stopped) {
        return;//from  w w w  . j av  a  2s  . c om
    }

    final Future<List<DnsRecord>> future;
    final int numQuestions = questions.size();
    if (numQuestions == 1) {
        // Simple case of single query
        final DnsQuestion question = questions.get(0);
        logger.debug("{} Sending a DNS query", logPrefix);
        future = resolver.resolveAll(question);
    } else {
        // Multiple queries
        logger.debug("{} Sending DNS queries", logPrefix);
        @SuppressWarnings("unchecked")
        final Promise<List<DnsRecord>> aggregatedPromise = eventLoop.newPromise();
        final FutureListener<List<DnsRecord>> listener = new FutureListener<List<DnsRecord>>() {
            private final List<DnsRecord> records = new ArrayList<>();
            private int remaining = numQuestions;
            @Nullable
            private List<Throwable> causes;

            @Override
            public void operationComplete(Future<List<DnsRecord>> future) throws Exception {
                if (future.isSuccess()) {
                    final List<DnsRecord> records = future.getNow();
                    this.records.addAll(records);
                } else {
                    if (causes == null) {
                        causes = new ArrayList<>(numQuestions);
                    }
                    causes.add(future.cause());
                }

                if (--remaining == 0) {
                    if (!records.isEmpty()) {
                        aggregatedPromise.setSuccess(records);
                    } else {
                        final Throwable aggregatedCause;
                        if (causes == null) {
                            aggregatedCause = new EndpointGroupException("empty result returned by DNS server");
                        } else {
                            aggregatedCause = new EndpointGroupException("failed to receive DNS records");
                            for (Throwable c : causes) {
                                aggregatedCause.addSuppressed(c);
                            }
                        }
                        aggregatedPromise.setFailure(aggregatedCause);
                    }
                }
            }
        };

        questions.forEach(q -> resolver.resolveAll(q).addListener(listener));
        future = aggregatedPromise;
    }

    attemptsSoFar++;
    future.addListener(this::onDnsRecords);
}

From source file:com.linecorp.armeria.client.http.DefaultSimpleHttpClient.java

License:Apache License

@Override
public Future<SimpleHttpResponse> execute(SimpleHttpRequest sReq) {
    final EventLoop eventLoop = client.eventLoop0();
    final Promise<SimpleHttpResponse> promise = eventLoop.newPromise();
    try {//from   w w w . j  a va2s.  com
        URI uri = sReq.uri();
        StringBuilder uriBuilder = new StringBuilder(uri.getPath());
        if (uri.getQuery() != null) {
            uriBuilder.append('?');
            uriBuilder.append(uri.getQuery());
        }
        if (uri.getFragment() != null) {
            uriBuilder.append('#');
            uriBuilder.append(uri.getFragment());
        }
        final AggregatedHttpMessage aReq = AggregatedHttpMessage.of(HttpMethod.valueOf(sReq.method().name()),
                uriBuilder.toString(), HttpData.of(sReq.content()));

        // Convert the headers.
        ArmeriaHttpUtil.toArmeria(sReq.headers(), aReq.headers());

        final HttpResponse res = client.execute(eventLoop, aReq);
        res.aggregate().handle(voidFunction((aRes, cause) -> {
            if (cause != null) {
                promise.setFailure(cause);
            } else {
                try {
                    final HttpData aContent = aRes.content();
                    final byte[] content;
                    if (aContent.offset() == 0 && aContent.length() == aContent.array().length) {
                        content = aContent.array();
                    } else {
                        content = Arrays.copyOfRange(aContent.array(), aContent.offset(), aContent.length());
                    }

                    final SimpleHttpResponse sRes = new SimpleHttpResponse(
                            HttpResponseStatus.valueOf(aRes.status().code()),
                            ArmeriaHttpUtil.toNettyHttp1(aRes.headers()), content);

                    promise.setSuccess(sRes);
                } catch (Throwable t) {
                    promise.setFailure(t);
                }
            }
        })).exceptionally(CompletionActions::log);
    } catch (Throwable t) {
        promise.setFailure(t);
    }

    return promise;
}