Example usage for com.google.common.util.concurrent Futures immediateFuture

List of usage examples for com.google.common.util.concurrent Futures immediateFuture

Introduction

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

Prototype

@CheckReturnValue
public static <V> ListenableFuture<V> immediateFuture(@Nullable V value) 

Source Link

Document

Creates a ListenableFuture which has its value set immediately upon construction.

Usage

From source file:io.v.android.security.BlessingsManager.java

/**
 * Returns a new {@link ListenableFuture} whose result are the {@link Blessings} found in
 * {@link SharedPreferences} under the given key.
 * <p>/*ww w . j a  v  a  2s .co m*/
 * If no {@link Blessings} are found, mints a new set of {@link Blessings} and stores them
 * in {@link SharedPreferences} under the provided key.
 * <p>
 * This method may start an activity to handle the creation of new blessings, if needed.
 * Hence, you should be prepared that your activity may be stopped and re-started.
 * <p>
 * This method is re-entrant: if blessings need to be minted, multiple concurrent invocations
 * of this method will result in only the last invocation's future ever being invoked.  This
 * means that it's safe to call this method from any of the android's lifecycle methods
 * (e.g., onCreate(), onStart(), onResume()).
 * <p>
 * This method must be invoked on the UI thread.
 *
 * @param context      Vanadium context
 * @param activity     android {@link Activity} requesting blessings
 * @param key          a key under which the blessings are stored
 * @param setAsDefault if true, the returned {@link Blessings} will be set as default
 *                     blessings for the app
 * @return             a new {@link ListenableFuture} whose result are the blessings
 *                     persisted under the given key
 */
public static ListenableFuture<Blessings> getBlessings(VContext context, final Activity activity, String key,
        boolean setAsDefault) {
    if (Looper.myLooper() != Looper.getMainLooper()) {
        return Futures
                .immediateFailedFuture(new VException("getBlessings() must be invoked " + "on the UI thread"));
    }
    try {
        Blessings blessings = readBlessings(context, activity, key, setAsDefault);
        if (blessings != null) {
            return Futures.immediateFuture(blessings);
        }
    } catch (VException e) {
        Log.e(TAG, "Malformed blessings in SharedPreferences. Minting new blessings: " + e.getMessage());
    }
    return mintBlessings(context, activity, key, setAsDefault);
}

From source file:org.opendaylight.coretutorials.impl.DscrudProvider.java

/**
 * clean data store//www  .j av a 2 s.  c o m
 *
 */
@Override
public Future<RpcResult<Void>> cleanupStore() {
    cleanupTestStore();
    LOG.info("Data Store cleaned up");
    return Futures.immediateFuture(RpcResultBuilder.<Void>success().build());
}

From source file:com.proofpoint.event.collector.LocalEventClient.java

@Override
public <T> ListenableFuture<Void> post(EventGenerator<T> eventGenerator) {
    checkNotNull(eventGenerator, "eventGenerator");
    try {/*w ww  .  j av  a  2s  . c om*/
        eventGenerator.generate(new EventPoster<T>() {
            @Override
            public void post(T event) throws IOException {
                checkNotNull(event, "event");
                for (EventWriter eventWriter : eventWriters) {
                    eventWriter.write(serializeEvent(event));
                }
            }
        });
    } catch (IOException e) {
        return Futures.immediateFailedFuture(new RuntimeException(e));
    }
    return Futures.immediateFuture(null);
}

From source file:com.google.api.server.spi.config.datastore.testing.FakeAsyncMemcacheService.java

@Override
public <T> Future<Set<T>> deleteAll(Collection<T> keys) {
    return Futures.immediateFuture(memcacheService.deleteAll(keys));
}

From source file:com.facebook.buck.artifact_cache.RetryingCacheDecorator.java

@Override
public ListenableFuture<CacheResult> fetchAsync(@Nullable BuildTarget target, RuleKey ruleKey,
        LazyPath output) {//from  ww w. j av  a  2  s .  co  m
    List<String> allCacheErrors = new ArrayList<>();
    ListenableFuture<CacheResult> resultFuture = delegate.fetchAsync(target, ruleKey, output);
    for (int retryCount = 1; retryCount < maxFetchRetries; retryCount++) {
        int retryCountForLambda = retryCount;
        resultFuture = Futures.transformAsync(resultFuture, result -> {
            if (result.getType() != CacheResultType.ERROR) {
                return Futures.immediateFuture(result);
            }
            result.cacheError().ifPresent(allCacheErrors::add);
            LOG.info("Failed to fetch %s after %d/%d attempts, exception: %s", ruleKey, retryCountForLambda + 1,
                    maxFetchRetries, result.cacheError());
            return delegate.fetchAsync(target, ruleKey, output);
        });
    }
    return Futures.transform(resultFuture, result -> {
        if (result.getType() != CacheResultType.ERROR) {
            return result;
        }
        String msg = String.join("\n", allCacheErrors);
        if (!msg.contains(NoHealthyServersException.class.getName())) {
            buckEventBus.post(ConsoleEvent.warning("Failed to fetch %s over %s after %d attempts.", ruleKey,
                    cacheMode.name(), maxFetchRetries));
        }
        return CacheResult.builder().from(result).setCacheError(msg).build();
    }, MoreExecutors.directExecutor());
}

From source file:com.facebook.buck.util.concurrent.WeightedListeningExecutorService.java

private <T> ListenableFuture<T> submitWithSemaphore(final Callable<T> callable, final ResourceAmounts amounts) {
    ListenableFuture<T> future = Futures.transformAsync(semaphore.acquire(amounts), input -> {
        try {/*from   w w  w .  j a v  a  2s. c o m*/
            return Futures.immediateFuture(callable.call());
        } catch (Throwable thrown) {
            return Futures.immediateFailedFuture(thrown);
        }
    }, delegate);
    future.addListener(() -> semaphore.release(amounts),
            com.google.common.util.concurrent.MoreExecutors.directExecutor());
    return future;
}

From source file:com.facebook.buck.parser.cache.impl.FakeManifestService.java

private ListenableFuture<Void> addToManifestBackingCollection(Manifest manifest) {
    String key = manifest.key;//from  w w  w. java2  s . co  m
    ArrayList<ByteBuffer> fingerprintsForKey = fingerprints.get(key);
    if (fingerprintsForKey == null) {
        fingerprintsForKey = new ArrayList<>();
        fingerprints.put(key, fingerprintsForKey);
    }

    for (ByteBuffer bytes : manifest.values) {
        fingerprintsForKey.add(bytes);
    }

    return Futures.immediateFuture(null);
}

From source file:com.facebook.buck.distributed.build_slave.RuleKeyDivergenceRunnerFactory.java

/** Creates DistBuildModeRunner to be used for rule key divergence checks */
public static DistBuildModeRunner createRunner(StampedeId stampedeId, BuildSlaveRunId buildSlaveRunId,
        Clock clock, DistBuildService distBuildService, DelegateAndGraphsInitializer initializer,
        RuleKeyConfiguration ruleKeyConfiguration, RuleKeyCacheScope<RuleKey> ruleKeyCacheScope,
        WeightedListeningExecutorService executorService, BuckEventBus eventBus, DistBuildState state,
        Cell rootCell, UnconfiguredBuildTargetFactory unconfiguredBuildTargetFactory) {
    return new AbstractDistBuildModeRunner() {
        @Override/* ww w. j  av a  2s.  c  o  m*/
        public ListenableFuture<?> getAsyncPrepFuture() {
            return Futures.immediateFuture(null);
        }

        @Override
        public ExitCode runAndReturnExitCode(HeartbeatService heartbeatService)
                throws IOException, InterruptedException {

            try (Closer closer = Closer.create()) {
                closer.register(heartbeatService.addCallback("ReportCoordinatorAlive",
                        createHeartbeatCallback(stampedeId, distBuildService)));

                try {
                    List<Pair<BuildRule, RuleKey>> rulesAndKeys = calculateDefaultRuleKeys(
                            getTopLevelTargetsToBuild(state, rootCell, unconfiguredBuildTargetFactory),
                            initializer, ruleKeyConfiguration, ruleKeyCacheScope, executorService, eventBus);

                    List<BuildSlaveEvent> ruleKeyCalculatedEvents = rulesAndKeys.stream().map(rk -> {
                        RuleKeyCalculatedEvent event = new RuleKeyCalculatedEvent();
                        event.setBuildTarget(rk.getFirst().getFullyQualifiedName());
                        event.setDefaultRuleKey(rk.getSecond().getHashCode().toString());

                        BuildSlaveEvent buildSlaveEvent = new BuildSlaveEvent();
                        buildSlaveEvent.setEventType(BuildSlaveEventType.RULE_KEY_CALCULATED_EVENT);
                        buildSlaveEvent.setRuleKeyCalculatedEvent(event);

                        return buildSlaveEvent;
                    }).collect(Collectors.toList());

                    List<List<BuildSlaveEvent>> ruleKeyCalculationBatches = Lists
                            .partition(ruleKeyCalculatedEvents, RULE_CALCULATION_EVENTS_PER_FRONTEND_REQUEST);

                    for (List<BuildSlaveEvent> ruleKeyCalculateBatch : ruleKeyCalculationBatches) {
                        distBuildService.uploadBuildSlaveEvents(stampedeId, buildSlaveRunId,
                                ruleKeyCalculateBatch);
                    }

                    // Ensure client doesn't wait for timeout before completing
                    distBuildService.sendAllBuildRulesPublishedEvent(stampedeId, buildSlaveRunId,
                            clock.currentTimeMillis());
                    distBuildService.setFinalBuildStatus(stampedeId, BuildStatus.FINISHED_SUCCESSFULLY,
                            "Rule key divergence check complete");
                    return ExitCode.SUCCESS;

                } catch (ExecutionException | IOException e) {
                    LOG.error(e, "Failed to calculate rule keys");
                    distBuildService.setFinalBuildStatus(stampedeId, BuildStatus.FAILED,
                            "Could not compute or publish rule keys");
                    return ExitCode.FATAL_GENERIC;
                }
            }
        }
    };
}

From source file:com.facebook.buck.core.rulekey.calculator.ParallelRuleKeyCalculator.java

/**
 * @return a {@link ListenableFuture} wrapping the result of calculating the {@link RuleKey} of
 *     the given {@link BuildRule}.//  w ww.  j a  v a  2 s  .c  o  m
 */
public synchronized ListenableFuture<T> calculate(BuckEventBus buckEventBus, BuildRule rule) {
    ListenableFuture<T> fromOurCache = ruleKeys.get(rule.getBuildTarget());
    if (fromOurCache != null) {
        return fromOurCache;
    }

    T fromInternalCache = ruleKeyFactory.getFromCache(rule);
    if (fromInternalCache != null) {
        ListenableFuture<T> future = Futures.immediateFuture(fromInternalCache);
        // Record the rule key future.
        ruleKeys.put(rule.getBuildTarget(), future);
        // Because a rule key will be invalidated from the internal cache any time one of its
        // dependents is invalidated, we know that all of our transitive deps are also in cache.
        return future;
    }

    // Grab all the dependency rule key futures.  Since our rule key calculation depends on this
    // one, we need to wait for them to complete.
    ListenableFuture<List<T>> depKeys = Futures.transformAsync(Futures.immediateFuture(ruleDepsCache.get(rule)),
            (@Nonnull SortedSet<BuildRule> deps) -> {
                List<ListenableFuture<T>> depKeys1 = new ArrayList<>(
                        SortedSets.sizeEstimate(rule.getBuildDeps()));
                for (BuildRule dep : deps) {
                    depKeys1.add(calculate(buckEventBus, dep));
                }
                return Futures.allAsList(depKeys1);
            }, service);

    // Setup a future to calculate this rule key once the dependencies have been calculated.
    ListenableFuture<T> calculated = Futures.transform(depKeys, (List<T> input) -> {
        try (Scope scope = ruleKeyCalculationScope.apply(buckEventBus, rule)) {
            return ruleKeyFactory.build(rule);
        } catch (Exception e) {
            throw new BuckUncheckedExecutionException(e, String.format("When computing rulekey for %s.", rule));
        }
    }, service);

    // Record the rule key future.
    ruleKeys.put(rule.getBuildTarget(), calculated);
    return calculated;
}

From source file:ch.raffael.util.swing.SwingUtil.java

public static <T> ListenableFuture<T> invokeInEventQueue(Callable<T> callable) {
    if (SwingUtilities.isEventDispatchThread()) {
        T result;//from w w w  . ja  va 2 s  .com
        try {
            result = callable.call();
            return Futures.immediateFuture(result);
        } catch (Exception e) {
            return Futures.immediateFailedFuture(e);
        }
    } else {
        ListenableFutureTask<T> future = ListenableFutureTask.create(callable);
        SwingUtilities.invokeLater(future);
        return future;
    }
}