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:org.opendaylight.controller.cluster.datastore.SingleCommitCohortProxy.java

@Override
public ListenableFuture<Boolean> canCommit() {
    LOG.debug("Tx {} canCommit", transactionId);

    final SettableFuture<Boolean> returnFuture = SettableFuture.create();

    cohortFuture.onComplete(new OnComplete<Object>() {
        @Override/*  ww w. j a v  a  2 s. co  m*/
        public void onComplete(Throwable failure, Object cohortResponse) {
            if (failure != null) {
                operationCallbackRef.get().failure();
                returnFuture.setException(failure);
                return;
            }

            operationCallbackRef.get().success();

            LOG.debug("Tx {} successfully completed direct commit", transactionId);

            // The Future was the result of a direct commit to the shard, essentially eliding the
            // front-end 3PC coordination. We don't really care about the specific Future
            // response object, only that it completed successfully. At this point the Tx is complete
            // so return true. The subsequent preCommit and commit phases will be no-ops, ie return
            // immediate success, to complete the 3PC for the front-end.
            returnFuture.set(Boolean.TRUE);
        }
    }, actorContext.getClientDispatcher());

    return returnFuture;
}

From source file:co.cask.cdap.internal.app.runtime.workflow.WorkflowMapReduceRunnerFactory.java

/**
 * Executes given MapReduce Program and block until it completed. On completion, return the MapReduceContext.
 *
 * @throws Exception if execution failed.
 *//* w  ww. ja v  a2 s. co  m*/
private MapReduceContext runAndWait(Program program, ProgramOptions options) throws Exception {
    ProgramController controller = programRunner.run(program, options);
    final MapReduceContext context = (controller instanceof MapReduceProgramController)
            ? ((MapReduceProgramController) controller).getContext()
            : null;
    // Execute the program.
    final SettableFuture<MapReduceContext> completion = SettableFuture.create();
    controller.addListener(new AbstractListener() {
        @Override
        public void stopped() {
            completion.set(context);
        }

        @Override
        public void error(Throwable cause) {
            completion.setException(cause);
        }
    }, Threads.SAME_THREAD_EXECUTOR);

    // Block for completion.
    try {
        return completion.get();
    } catch (ExecutionException e) {
        Throwable cause = e.getCause();
        if (cause instanceof Exception) {
            throw (Exception) cause;
        }
        throw Throwables.propagate(cause);
    }
}

From source file:com.android.build.gradle.internal.process.GradleProcessExecutor.java

@NonNull
@Override/*from ww w.  j  a v a  2 s  .  c  o m*/
public ListenableFuture<ProcessResult> submit(@NonNull final ProcessInfo processInfo,
        @NonNull final ProcessOutputHandler processOutputHandler) {
    final SettableFuture<ProcessResult> res = SettableFuture.create();
    new Thread() {
        @Override
        public void run() {
            try {
                ProcessResult result = execute(processInfo, processOutputHandler);
                res.set(result);
            } catch (Exception e) {
                res.setException(e);
            }
        }
    }.start();

    return res;
}

From source file:com.facebook.buck.parser.PipelineNodeCache.java

/**
 * Helper for de-duping jobs against the cache.
 *
 * @param jobSupplier a supplier to use to create the actual job.
 * @return future describing the job. It can either be an immediate future (result cache hit),
 *         ongoing job (job cache hit) or a new job (miss).
 *///from   w w w  .  j av  a2 s . c om
protected final ListenableFuture<T> getJobWithCacheLookup(final Cell cell, final K key,
        JobSupplier<T> jobSupplier) throws BuildTargetException {
    Optional<T> cacheLookupResult = cache.lookupComputedNode(cell, key);
    if (cacheLookupResult.isPresent()) {
        return Futures.immediateFuture(cacheLookupResult.get());
    }

    ListenableFuture<T> speculativeCacheLookupResult = jobsCache.get(key);
    if (speculativeCacheLookupResult != null) {
        return speculativeCacheLookupResult;
    }

    // We use a SettableFuture to resolve any races between threads that are trying to create the
    // job for the given key. The SettableFuture is cheap to throw away in case we didn't "win" and
    // can be easily "connected" to a future that actually does work in case we did.
    SettableFuture<T> resultFutureCandidate = SettableFuture.create();
    ListenableFuture<T> resultFutureInCache = jobsCache.putIfAbsent(key, resultFutureCandidate);
    if (resultFutureInCache != null) {
        // Another thread succeeded in putting the new value into the cache.
        return resultFutureInCache;
    }
    // Ok, "our" candidate future went into the jobsCache, schedule the job and 'chain' the result
    // to the SettableFuture, so that anyone else waiting on it will get the same result.
    final SettableFuture<T> resultFuture = resultFutureCandidate;
    try {
        ListenableFuture<T> nodeJob = Futures.transformAsync(jobSupplier.get(),
                input -> Futures.immediateFuture(cache.putComputedNodeIfNotPresent(cell, key, input)));
        resultFuture.setFuture(nodeJob);
    } catch (Throwable t) {
        resultFuture.setException(t);
        throw t;
    }
    return resultFuture;
}

From source file:org.apache.bookkeeper.stream.io.Entry.java

/**
 * Cancel record futures when encountering exception <i>throwable</i>.
 *
 * @param throwable exception to cancel record futures
 *//* ww w  .j  ava  2  s  .c  o m*/
public void cancelRecordFutures(Throwable throwable) {
    if (!recordFutureList.isPresent()) {
        return;
    }
    for (SettableFuture<SSN> future : recordFutureList.get()) {
        future.setException(throwable);
    }
}

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

@Override
public <T> void executeRead(AbstractRead<T> readCmd, SettableFuture<T> proxyFuture) {
    LOG.debug("Tx {} executeRead {} called path = {}", getIdentifier(), readCmd.getClass().getSimpleName(),
            readCmd.getPath());/*from w w  w .j  ava  2 s.c  o m*/

    final Throwable t;
    if (failure instanceof NoShardLeaderException) {
        t = new DataStoreUnavailableException(failure.getMessage(), failure);
    } else {
        t = failure;
    }
    proxyFuture.setException(new ReadFailedException(
            "Error executeRead " + readCmd.getClass().getSimpleName() + " for path " + readCmd.getPath(), t));
}

From source file:com.google.pubsub.clients.vtk.CPSPublisherTask.java

@Override
public ListenableFuture<RunResult> doRun() {
    List<PubsubMessage> messages = new ArrayList<>(batchSize);
    String sendTime = String.valueOf(System.currentTimeMillis());
    for (int i = 0; i < batchSize; i++) {
        messages.add(PubsubMessage.newBuilder().setData(payload).putAttributes("sendTime", sendTime)
                .putAttributes("clientId", id.toString())
                .putAttributes("sequenceNumber", Integer.toString(sequenceNumber.getAndIncrement())).build());
    }//from  w  w  w.j  av a 2 s.  co  m
    PublishRequest request = PublishRequest.newBuilder().setTopic(topic).addAllMessages(messages).build();
    SettableFuture<RunResult> result = SettableFuture.create();
    publisherApi.publishCallable().futureCall(request).addCallback(new RpcFutureCallback<PublishResponse>() {
        @Override
        public void onSuccess(PublishResponse s) {
            result.set(RunResult.fromBatchSize(batchSize));
        }

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

From source file:org.fcrepo.kernel.modeshape.utils.iterators.PersistingRdfStreamConsumer.java

@Override
public ListenableFuture<Boolean> consumeAsync() {
    // TODO make this actually asynch
    final SettableFuture<Boolean> result = SettableFuture.create();
    try {//from w  w w.jav a2  s . c  o  m
        consume();
        result.set(true);
    } catch (final MalformedRdfException e) {
        LOGGER.warn("Got exception consuming RDF stream", e);
        result.setException(e);
        result.set(false);
    }
    return result;
}

From source file:org.pentaho.osgi.bridge.KarafCapability.java

@Override
public Future<Boolean> uninstall() {
    SettableFuture<Boolean> uninstallFuture = SettableFuture.<Boolean>create();
    try {//from  w  w w . jav  a  2s.  com
        manager.watchForUnInstall(feature, uninstallFuture);
        featuresService.uninstallFeature(feature.getName());
    } catch (Exception e) {
        logger.error("Unknown error uninstalling feature", e);
        uninstallFuture.set(false);
        uninstallFuture.setException(e);
    }
    return uninstallFuture;
}

From source file:org.usrz.libs.utils.concurrent.SimpleExecutor.java

public <T> NotifyingFuture<T> call(Callable<T> callable) {
    final SettableFuture<T> settableFuture = SettableFuture.create();

    final Future<T> executingFuture = executor.submit(() -> {
        try {// ww  w .  j a va2s.c o  m
            final T result = callable.call();
            settableFuture.set(result);
            return result;
        } catch (Throwable throwable) {
            settableFuture.setException(throwable);
            throw new Exception(throwable);
        }
    });

    return new NotifyingFuture<T>() {

        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            if (executingFuture.cancel(mayInterruptIfRunning)) {
                settableFuture.cancel(mayInterruptIfRunning);
                return true;
            } else {
                return false;
            }
        }

        @Override
        public boolean isCancelled() {
            return settableFuture.isCancelled();
        }

        @Override
        public boolean isDone() {
            return settableFuture.isCancelled();
        }

        @Override
        public T get() throws InterruptedException, ExecutionException {
            return settableFuture.get();
        }

        @Override
        public T get(long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            return settableFuture.get(timeout, unit);
        }

        @Override
        public NotifyingFuture<T> withConsumer(Consumer<Future<T>> consumer) {
            settableFuture.addListener(() -> consumer.accept(settableFuture), notifier);
            return this;
        }

    };
}