Example usage for com.google.common.util.concurrent SettableFuture setException

List of usage examples for com.google.common.util.concurrent SettableFuture setException

Introduction

In this page you can find the example usage for com.google.common.util.concurrent SettableFuture setException.

Prototype

@Override
    public boolean setException(Throwable throwable) 

Source Link

Usage

From source file:com.yahoo.yqlplus.engine.java.ToyPersonSource.java

private <V> ListenableFuture<V> eventually(long delay, final Callable<V> todo) {
    final SettableFuture<V> result = SettableFuture.create();
    toyWorker.schedule(new Runnable() {
        @Override/*from  ww  w . j a  v  a  2 s.  com*/
        public void run() {
            try {
                result.set(todo.call());
            } catch (Exception e) {
                result.setException(e);
            }
        }
    }, delay, TimeUnit.MILLISECONDS);
    return result;
}

From source file:zipkin.collector.scribe.ScribeSpanConsumer.java

@Override
public ListenableFuture<ResultCode> log(List<LogEntry> messages) {
    metrics.incrementMessages();/*from   w  w  w .  j  av a  2 s. c  o  m*/
    List<byte[]> thrifts;
    try {
        thrifts = messages.stream().filter(m -> m.category.equals(category))
                .map(m -> m.message.getBytes(StandardCharsets.ISO_8859_1))
                .map(b -> Base64.getMimeDecoder().decode(b)) // finagle-zipkin uses mime encoding
                .collect(Collectors.toList());
    } catch (RuntimeException e) {
        metrics.incrementMessagesDropped();
        return Futures.immediateFailedFuture(e);
    }

    SettableFuture<ResultCode> result = SettableFuture.create();
    collector.acceptSpans(thrifts, Codec.THRIFT, new Callback<Void>() {
        @Override
        public void onSuccess(@Nullable Void value) {
            result.set(ResultCode.OK);
        }

        @Override
        public void onError(Throwable t) {
            result.setException(t);
        }
    });
    return result;
}

From source file:org.opendaylight.controller.cluster.datastore.LocalTransactionContext.java

@Override
public <T> void executeRead(AbstractRead<T> readCmd, final SettableFuture<T> proxyFuture) {
    Futures.addCallback(readCmd.apply(getReadDelegate()), new FutureCallback<T>() {
        @Override//w w w  .  j  a  v  a2  s . c  o  m
        public void onSuccess(final T result) {
            proxyFuture.set(result);
        }

        @Override
        public void onFailure(final Throwable t) {
            proxyFuture.setException(t);
        }
    });
}

From source file:com.facebook.presto.execution.ClusterSizeMonitor.java

public synchronized ListenableFuture<?> waitForMinimumWorkers() {
    if (currentCount >= executionMinCount) {
        return immediateFuture(null);
    }/*from  w  ww . j  av a  2s . c  om*/

    SettableFuture<?> future = SettableFuture.create();
    futures.add(future);

    // if future does not finish in wait period, complete with an exception
    ScheduledFuture<?> timeoutTask = executor.schedule(() -> {
        synchronized (this) {
            future.setException(new PrestoException(GENERIC_INSUFFICIENT_RESOURCES, format(
                    "Insufficient active worker nodes. Waited %s for at least %s workers, but only %s workers are active",
                    executionMaxWait, executionMinCount, currentCount)));
        }
    }, executionMaxWait.toMillis(), MILLISECONDS);

    // remove future if finished (e.g., canceled, timed out)
    future.addListener(() -> {
        timeoutTask.cancel(true);
        removeFuture(future);
    }, executor);

    return future;
}

From source file:com.microsoft.filediscovery.datasource.ListItemsDataSource.java

public ListenableFuture<byte[]> getFile(FileItem file) {
    FileClient fileClient = mApplication.getCurrentFileClient(file.getResourceId(), file.getEndpoint());
    final SettableFuture<byte[]> result = SettableFuture.create();
    ListenableFuture<byte[]> future = fileClient.getFile(file.getId(), null);

    Futures.addCallback(future, new FutureCallback<byte[]>() {
        @Override//w  ww  . j a  v a 2s  .  c o  m
        public void onFailure(Throwable t) {
            result.setException(t);
        }

        @Override
        public void onSuccess(byte[] payload) {
            result.set(payload);
        }
    });
    return result;
}

From source file:io.prestosql.execution.ClusterSizeMonitor.java

/**
 * Returns a listener that completes when the minimum number of workers for the cluster has been met.
 * Note: caller should not add a listener using the direct executor, as this can delay the
 * notifications for other listeners./*  www .j a  va  2 s  .c  o  m*/
 */
public synchronized ListenableFuture<?> waitForMinimumWorkers() {
    if (currentCount >= executionMinCount) {
        return immediateFuture(null);
    }

    SettableFuture<?> future = SettableFuture.create();
    futures.add(future);

    // if future does not finish in wait period, complete with an exception
    ScheduledFuture<?> timeoutTask = executor.schedule(() -> {
        synchronized (this) {
            future.setException(new PrestoException(GENERIC_INSUFFICIENT_RESOURCES, format(
                    "Insufficient active worker nodes. Waited %s for at least %s workers, but only %s workers are active",
                    executionMaxWait, executionMinCount, currentCount)));
        }
    }, executionMaxWait.toMillis(), MILLISECONDS);

    // remove future if finished (e.g., canceled, timed out)
    future.addListener(() -> {
        timeoutTask.cancel(true);
        removeFuture(future);
    }, executor);

    return future;
}

From source file:com.google.pubsub.flic.controllers.Controller.java

/**
 * Sends a LoadtestFramework.Start RPC to all clients to commence the load test. When this
 * function returns it is guaranteed that all clients have started.
 *//*  ww  w .  j a va2s  .com*/
public void startClients(MessageTracker messageTracker) {
    SettableFuture<Void> startFuture = SettableFuture.create();
    clients.forEach((client) -> executor.execute(() -> {
        try {
            client.start(messageTracker);
            startFuture.set(null);
        } catch (Throwable t) {
            startFuture.setException(t);
        }
    }));
    try {
        startFuture.get();
    } catch (ExecutionException e) {
        shutdown(e.getCause());
    } catch (InterruptedException e) {
        shutdown(e);
    }
}

From source file:com.spotify.folsom.client.DefaultRawMemcacheClient.java

public static ListenableFuture<RawMemcacheClient> connect(final HostAndPort address,
        final int outstandingRequestLimit, final boolean binary, final Executor executor,
        final long timeoutMillis, final Charset charset, final Metrics metrics, final int maxSetLength) {

    final ChannelInboundHandler decoder;
    if (binary) {
        decoder = new BinaryMemcacheDecoder();
    } else {//from   w ww  .  j  av  a  2s  .c  o m
        decoder = new AsciiMemcacheDecoder(charset);
    }

    final ChannelHandler initializer = new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(final Channel ch) throws Exception {
            ch.pipeline().addLast(new TcpTuningHandler(), decoder,

                    // Downstream
                    new MemcacheEncoder());
        }
    };

    final SettableFuture<RawMemcacheClient> clientFuture = SettableFuture.create();

    final Bootstrap bootstrap = new Bootstrap().group(EVENT_LOOP_GROUP).handler(initializer)
            .channel(NioSocketChannel.class)
            .option(ChannelOption.MESSAGE_SIZE_ESTIMATOR, SimpleSizeEstimator.INSTANCE);

    final ChannelFuture connectFuture = bootstrap
            .connect(new InetSocketAddress(address.getHostText(), address.getPort()));

    connectFuture.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                // Create client
                final RawMemcacheClient client = new DefaultRawMemcacheClient(address, future.channel(),
                        outstandingRequestLimit, executor, timeoutMillis, metrics, maxSetLength);
                clientFuture.set(client);
            } else {
                clientFuture.setException(future.cause());
            }
        }
    });

    return onExecutor(clientFuture, executor);
}

From source file:com.facebook.presto.hive.util.AsyncWalker.java

private void recursiveWalk(final Path path, final FileStatusCallback callback, final AtomicLong taskCount,
        final SettableFuture<Void> future) {
    taskCount.incrementAndGet();/*from   w  w w.j  a va2  s  .  c  om*/
    try {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                doWalk(path, callback, taskCount, future);
            }
        });
    } catch (Throwable t) {
        future.setException(t);
    }
}

From source file:com.spotify.futures.ConcurrencyLimiter.java

private void invoke(final SettableFuture<T> response, Callable<? extends ListenableFuture<T>> callable) {
    final ListenableFuture<T> future;
    try {// ww  w.  j a v  a2s. co  m
        future = callable.call();
        if (future == null) {
            limit.release();
            response.setException(new NullPointerException());
            return;
        }
    } catch (Throwable e) {
        limit.release();
        response.setException(e);
        return;
    }

    Futures.addCallback(future, new FutureCallback<T>() {
        @Override
        public void onSuccess(T result) {
            limit.release();
            response.set(result);
            pump();
        }

        @Override
        public void onFailure(Throwable t) {
            limit.release();
            response.setException(t);
            pump();
        }
    });
}