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:org.apache.hive.spark.client.rpc.RpcServer.java

License:Apache License

@VisibleForTesting
Future<Rpc> registerClient(final String clientId, String secret, RpcDispatcher serverDispatcher,
        long clientTimeoutMs) {
    final Promise<Rpc> promise = group.next().newPromise();

    Runnable timeout = new Runnable() {
        @Override/*  w ww.  j  a va2s .com*/
        public void run() {
            promise.setFailure(new TimeoutException("Timed out waiting for client connection."));
        }
    };
    ScheduledFuture<?> timeoutFuture = group.schedule(timeout, clientTimeoutMs, TimeUnit.MILLISECONDS);
    final ClientInfo client = new ClientInfo(clientId, promise, secret, serverDispatcher, timeoutFuture);
    if (pendingClients.putIfAbsent(clientId, client) != null) {
        throw new IllegalStateException(String.format("Client '%s' already registered.", clientId));
    }

    promise.addListener(new GenericFutureListener<Promise<Rpc>>() {
        @Override
        public void operationComplete(Promise<Rpc> p) {
            if (!p.isSuccess()) {
                pendingClients.remove(clientId);
            }
        }
    });

    return promise;
}

From source file:org.apache.spark.sql.hive.thriftserver.rsc.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 a 2  s.  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(RSCConf.Entry.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(RSCConf.Entry.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:org.apache.spark.sql.hive.thriftserver.rsc.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. ja va2  s  . co  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) {

    LOG.info("tlitest retType: " + 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:org.asynchttpclient.resolver.JdkNameResolver.java

License:Open Source License

@Override
public Future<List<InetSocketAddress>> resolve(String name, int port) {

    Promise<List<InetSocketAddress>> promise = ImmediateEventExecutor.INSTANCE.newPromise();
    try {//from  www . ja v  a2  s  . c  o  m
        InetAddress[] resolved = InetAddress.getAllByName(name);
        List<InetSocketAddress> socketResolved = new ArrayList<InetSocketAddress>(resolved.length);
        for (InetAddress res : resolved) {
            socketResolved.add(new InetSocketAddress(res, port));
        }
        return promise.setSuccess(socketResolved);
    } catch (UnknownHostException e) {
        return promise.setFailure(e);
    }
}

From source file:org.asynchttpclient.resolver.RequestNameResolver.java

License:Open Source License

public Future<List<InetSocketAddress>> resolve(Request request, ProxyServer proxy,
        AsyncHandler<?> asyncHandler) {

    Uri uri = request.getUri();/*from w w  w .  ja va 2 s .  c  o  m*/

    if (request.getAddress() != null) {
        List<InetSocketAddress> resolved = Collections
                .singletonList(new InetSocketAddress(request.getAddress(), uri.getExplicitPort()));
        Promise<List<InetSocketAddress>> promise = ImmediateEventExecutor.INSTANCE.newPromise();
        return promise.setSuccess(resolved);

    }

    // don't notify on explicit address
    final AsyncHandlerExtensions asyncHandlerExtensions = request.getAddress() == null
            ? toAsyncHandlerExtensions(asyncHandler)
            : null;
    final String name;
    final int port;

    if (proxy != null && !proxy.isIgnoredForHost(uri.getHost())) {
        name = proxy.getHost();
        port = uri.isSecured() ? proxy.getSecuredPort() : proxy.getPort();
    } else {
        name = uri.getHost();
        port = uri.getExplicitPort();
    }

    if (asyncHandlerExtensions != null)
        asyncHandlerExtensions.onDnsResolution(name);

    final Future<List<InetSocketAddress>> whenResolved = request.getNameResolver().resolve(name, port);

    if (asyncHandlerExtensions == null)
        return whenResolved;

    Promise<List<InetSocketAddress>> promise = ImmediateEventExecutor.INSTANCE.newPromise();

    whenResolved.addListener(new SimpleGenericFutureListener<List<InetSocketAddress>>() {

        @Override
        protected void onSuccess(List<InetSocketAddress> addresses) throws Exception {
            asyncHandlerExtensions.onDnsResolutionSuccess(name, addresses);
            promise.setSuccess(addresses);
        }

        @Override
        protected void onFailure(Throwable t) throws Exception {
            asyncHandlerExtensions.onDnsResolutionFailure(name, t);
            promise.setFailure(t);
        }
    });

    return promise;
}

From source file:org.redisson.async.OperationListener.java

License:Apache License

protected boolean isBreak(RedisAsyncConnection<Object, V> async, Promise<P> promise, Future<F> future) {
    if (!future.isSuccess()) {
        if (future.cause() instanceof RedisTimeoutException) {
            timeoutCallback.execute(promise, async);
            return false;
        } else {/*from   w  w w  .java2s .co m*/
            promise.setFailure(future.cause());
            return true;
        }
    }

    if (promise.isCancelled()) {
        if (async.isMultiMode()) {
            async.discard();
        }
        return true;
    }

    return false;
}

From source file:org.redisson.CommandBatchExecutorService.java

License:Apache License

public Future<List<?>> executeAsync() {
    if (executed) {
        throw new IllegalStateException("Batch already executed!");
    }/* ww  w .  j a va 2s . com*/

    if (commands.isEmpty()) {
        return connectionManager.getGroup().next().newSucceededFuture(null);
    }
    executed = true;

    Promise<Void> voidPromise = connectionManager.newPromise();
    final Promise<List<?>> promise = connectionManager.newPromise();
    voidPromise.addListener(new FutureListener<Void>() {
        @Override
        public void operationComplete(Future<Void> future) throws Exception {
            if (!future.isSuccess()) {
                promise.setFailure(future.cause());
                return;
            }

            List<CommandEntry> entries = new ArrayList<CommandEntry>();
            for (Entry e : commands.values()) {
                entries.addAll(e.getCommands());
            }
            Collections.sort(entries);
            List<Object> result = new ArrayList<Object>();
            for (CommandEntry commandEntry : entries) {
                result.add(commandEntry.getCommand().getPromise().getNow());
            }
            promise.setSuccess(result);
            commands = null;
        }
    });
    for (java.util.Map.Entry<Integer, Entry> e : commands.entrySet()) {
        execute(e.getValue(), e.getKey(), voidPromise, new AtomicInteger(commands.size()), 0);
    }
    return promise;
}

From source file:org.redisson.CommandBatchExecutorService.java

License:Apache License

public void execute(final Entry entry, final int slot, final Promise<Void> mainPromise,
        final AtomicInteger slots, final int attempt) {
    if (!connectionManager.getShutdownLatch().acquire()) {
        mainPromise.setFailure(new IllegalStateException("Redisson is shutdown"));
        return;/*from  w ww .  j a v a2s  .  c om*/
    }

    final Promise<Void> attemptPromise = connectionManager.newPromise();
    final AtomicReference<RedisException> ex = new AtomicReference<RedisException>();

    final TimerTask retryTimerTask = new TimerTask() {
        @Override
        public void run(Timeout timeout) throws Exception {
            if (attemptPromise.isDone()) {
                return;
            }
            if (attempt == connectionManager.getConfig().getRetryAttempts()) {
                attemptPromise.setFailure(ex.get());
                return;
            }
            attemptPromise.cancel(true);

            int count = attempt + 1;
            execute(entry, slot, mainPromise, slots, count);
        }
    };

    try {
        org.redisson.client.RedisConnection connection;
        if (entry.isReadOnlyMode()) {
            connection = connectionManager.connectionReadOp(slot);
        } else {
            connection = connectionManager.connectionWriteOp(slot);
        }

        ArrayList<CommandData<?, ?>> list = new ArrayList<CommandData<?, ?>>(entry.getCommands().size());
        for (CommandEntry c : entry.getCommands()) {
            list.add(c.getCommand());
        }
        ChannelFuture future = connection.send(new CommandsData(attemptPromise, list));

        ex.set(new RedisTimeoutException());
        final Timeout timeout = connectionManager.getTimer().newTimeout(retryTimerTask,
                connectionManager.getConfig().getTimeout(), TimeUnit.MILLISECONDS);

        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    timeout.cancel();
                    ex.set(new WriteRedisConnectionException("channel: " + future.channel() + " closed"));
                    connectionManager.getTimer().newTimeout(retryTimerTask,
                            connectionManager.getConfig().getRetryInterval(), TimeUnit.MILLISECONDS);
                }
            }
        });

        if (entry.isReadOnlyMode()) {
            attemptPromise.addListener(connectionManager.createReleaseReadListener(slot, connection, timeout));
        } else {
            attemptPromise.addListener(connectionManager.createReleaseWriteListener(slot, connection, timeout));
        }
    } catch (RedisException e) {
        ex.set(e);
        connectionManager.getTimer().newTimeout(retryTimerTask,
                connectionManager.getConfig().getRetryInterval(), TimeUnit.MILLISECONDS);
    }
    attemptPromise.addListener(new FutureListener<Void>() {
        @Override
        public void operationComplete(Future<Void> future) throws Exception {
            if (future.isCancelled()) {
                return;
            }

            if (future.cause() instanceof RedisMovedException) {
                RedisMovedException ex = (RedisMovedException) future.cause();
                execute(entry, ex.getSlot(), mainPromise, slots, attempt);
                return;
            }

            if (future.isSuccess()) {
                if (slots.decrementAndGet() == 0) {
                    mainPromise.setSuccess(future.getNow());
                }
            } else {
                mainPromise.setFailure(future.cause());
            }
        }
    });
}

From source file:org.redisson.CommandExecutorService.java

License:Apache License

public <T, R> Future<Collection<R>> readAllAsync(RedisCommand<T> command, Object... params) {
    final Promise<Collection<R>> mainPromise = connectionManager.newPromise();
    Promise<R> promise = new DefaultPromise<R>() {
        Queue<R> results = new ConcurrentLinkedQueue<R>();
        AtomicInteger counter = new AtomicInteger(connectionManager.getEntries().keySet().size());

        @Override/*from  ww w. ja v a2s.  c om*/
        public Promise<R> setSuccess(R result) {
            if (result instanceof Collection) {
                results.addAll((Collection) result);
            } else {
                results.add(result);
            }

            if (counter.decrementAndGet() == 0 && !mainPromise.isDone()) {
                mainPromise.setSuccess(results);
            }
            return this;
        }

        @Override
        public Promise<R> setFailure(Throwable cause) {
            mainPromise.setFailure(cause);
            return this;
        }

    };

    for (Integer slot : connectionManager.getEntries().keySet()) {
        async(true, slot, null, connectionManager.getCodec(), command, params, promise, 0);
    }
    return mainPromise;
}

From source file:org.redisson.CommandExecutorService.java

License:Apache License

private <R, T> void retryReadRandomAsync(final RedisCommand<T> command, final Promise<R> mainPromise,
        final List<Integer> slots, final Object... params) {
    final Promise<R> attemptPromise = connectionManager.newPromise();
    attemptPromise.addListener(new FutureListener<R>() {
        @Override//from  w w w .j  a  v a 2  s  .c o  m
        public void operationComplete(Future<R> future) throws Exception {
            if (future.isSuccess()) {
                if (future.getNow() == null) {
                    if (slots.isEmpty()) {
                        mainPromise.setSuccess(null);
                    } else {
                        retryReadRandomAsync(command, mainPromise, slots, params);
                    }
                } else {
                    mainPromise.setSuccess(future.getNow());
                }
            } else {
                mainPromise.setFailure(future.cause());
            }
        }
    });

    Integer slot = slots.remove(0);
    async(true, slot, null, connectionManager.getCodec(), command, params, attemptPromise, 0);
}