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:com.microsoft.azure.keyvault.extensions.KeyVaultKeyResolver.java

@Override
public ListenableFuture<IKey> resolveKeyAsync(String kid) {

    if (KeyIdentifier.isKeyIdentifier(kid)) {
        return resolveKeyFromKeyAsync(kid);
    } else if (SecretIdentifier.isSecretIdentifier(kid)) {
        return resolveKeyFromSecretAsync(kid);
    }/*ww  w  .  j a  va 2 s . c  o  m*/

    return Futures.immediateFuture(null);
}

From source file:com.proofpoint.testing.SerialScheduledExecutorService.java

@Override
public <T> Future<T> submit(Runnable runnable, T t) {
    Preconditions.checkNotNull(runnable, "Task object is null");
    try {//from   ww w.  jav a2  s . c  om
        runnable.run();
        return Futures.immediateFuture(t);
    } catch (Exception e) {
        return Futures.immediateFailedFuture(e);
    }
}

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

@Override
public Future<Long> increment(Object key, long delta) {
    return Futures.immediateFuture(memcacheService.increment(key, delta));
}

From source file:dagger.producers.internal.Producers.java

/** Returns a producer that succeeds with the given value. */
public static <T> Producer<T> immediateProducer(final T value) {
    return new Producer<T>() {
        @Override/*from w  w w .j  a  v a  2s  .  c  o  m*/
        public ListenableFuture<T> get() {
            return Futures.immediateFuture(value);
        }
    };
}

From source file:org.apache.qpid.server.security.access.plugins.AclFileAccessControlProviderImpl.java

@StateTransition(currentState = { State.UNINITIALIZED, State.QUIESCED,
        State.ERRORED }, desiredState = State.ACTIVE)
@SuppressWarnings("unused")
private ListenableFuture<Void> activate() {

    try {//  w  ww  .ja  va 2s. com
        recreateAccessController();
        setState(_broker.isManagementMode() ? State.QUIESCED : State.ACTIVE);
    } catch (RuntimeException e) {
        setState(State.ERRORED);
        if (_broker.isManagementMode()) {
            LOGGER.warn("Failed to activate ACL provider: " + getName(), e);
        } else {
            throw e;
        }
    }
    return Futures.immediateFuture(null);
}

From source file:org.apache.usergrid.persistence.graph.serialization.impl.shard.impl.ShardGroupDeletionImpl.java

@Override
public ListenableFuture<DeleteResult> maybeDeleteShard(final ApplicationScope applicationScope,
        final DirectedEdgeMeta directedEdgeMeta, final ShardEntryGroup shardEntryGroup,
        final Iterator<MarkedEdge> edgeIterator) {

    /**//from   www .j a  va  2  s  .  co  m
     * Try and submit.  During back pressure, we may not be able to submit, that's ok.  Better to drop than to
     * hose the system
     */
    final ListenableFuture<DeleteResult> future;

    try {
        future = asyncTaskExecutor
                .submit(new ShardDeleteTask(applicationScope, directedEdgeMeta, shardEntryGroup, edgeIterator));
    } catch (RejectedExecutionException ree) {

        //ignore, if this happens we don't care, we're saturated, we can check later
        logger.info("Rejected shard delete check for group {}", edgeIterator);

        return Futures.immediateFuture(DeleteResult.NOT_CHECKED);
    }

    /**
     * Log our success or failures for debugging purposes
     */
    Futures.addCallback(future, new FutureCallback<DeleteResult>() {
        @Override
        public void onSuccess(@Nullable final ShardGroupDeletion.DeleteResult result) {
            if (logger.isTraceEnabled())
                logger.trace("Successfully completed delete of task {}", result);
        }

        @Override
        public void onFailure(final Throwable t) {
            logger.error("Unable to perform shard delete audit.  Exception is ", t);
        }
    });

    return future;
}

From source file:com.microsoft.azure.keyvault.cryptography.RsaKey.java

@Override
public ListenableFuture<byte[]> decryptAsync(final byte[] ciphertext, final byte[] iv,
        final byte[] authenticationData, final byte[] authenticationTag, final String algorithm)
        throws NoSuchAlgorithmException {

    if (ciphertext == null) {
        throw new IllegalArgumentException("ciphertext");
    }//from  www .j a v  a 2s  .  c o  m

    // Interpret the requested algorithm
    if (Strings.isNullOrWhiteSpace(algorithm)) {
        throw new IllegalArgumentException("algorithm");
    }

    Algorithm baseAlgorithm = AlgorithmResolver.Default.get(algorithm);

    if (baseAlgorithm == null || !(baseAlgorithm instanceof AsymmetricEncryptionAlgorithm)) {
        throw new NoSuchAlgorithmException(algorithm);
    }

    AsymmetricEncryptionAlgorithm algo = (AsymmetricEncryptionAlgorithm) baseAlgorithm;

    ICryptoTransform transform;
    ListenableFuture<byte[]> result;

    try {
        transform = algo.CreateDecryptor(_keyPair, _provider);
        result = Futures.immediateFuture(transform.doFinal(ciphertext));
    } catch (Exception e) {
        result = Futures.immediateFailedFuture(e);
    }

    return result;
}

From source file:com.facebook.buck.core.build.engine.cache.manager.InputBasedRuleKeyManager.java

private ListenableFuture<Optional<Pair<BuildRuleSuccessType, CacheResult>>> performInputBasedCacheFetch(
        RuleKey inputRuleKey) {/* w  ww .j ava2  s . com*/
    Preconditions.checkArgument(SupportsInputBasedRuleKey.isSupported(rule));

    getBuildInfoRecorder().addBuildMetadata(BuildInfo.MetadataKey.INPUT_BASED_RULE_KEY,
            inputRuleKey.toString());

    // Check the input-based rule key says we're already built.
    if (checkMatchingInputBasedKey(inputRuleKey)) {
        return Futures
                .immediateFuture(Optional.of(new Pair<>(BuildRuleSuccessType.MATCHING_INPUT_BASED_RULE_KEY,
                        CacheResult.localKeyUnchangedHit())));
    }

    // Try to fetch the artifact using the input-based rule key.
    return Futures.transform(buildCacheArtifactFetcher
            .tryToFetchArtifactFromBuildCacheAndOverlayOnTopOfProjectFilesystem(inputRuleKey, artifactCache,
                    // TODO(simons): Share this between all tests, not one per cell.
                    rule.getProjectFilesystem()),
            cacheResult -> {
                if (cacheResult.getType().isSuccess()) {
                    try (Scope ignored = LeafEvents.scope(eventBus, "handling_cache_result")) {
                        return Optional.of(
                                new Pair<>(BuildRuleSuccessType.FETCHED_FROM_CACHE_INPUT_BASED, cacheResult));
                    }
                }
                return Optional.empty();
            }, MoreExecutors.directExecutor());
}

From source file:com.facebook.buck.remoteexecution.util.MultiThreadedBlobUploader.java

/** Uploads missing items to the CAS. */
public ListenableFuture<Void> addMissing(ImmutableMap<Digest, UploadDataSupplier> data) {
    data = ImmutableMap.copyOf(Maps.filterKeys(data, k -> !containedHashes.contains(k.getHash())));
    if (data.isEmpty()) {
        return Futures.immediateFuture(null);
    }/*w w  w . j  a  v a2 s .  co  m*/
    return enqueue(data);
}

From source file:org.apache.rave.opensocial.service.impl.DefaultActivityStreamsService.java

/**
 * Returns a list of activities that correspond to the passed in users and group.
 * <p/>/*w  ww  .j  ava 2 s  .  co  m*/
 * Specified by: getActivityEntries(...) in ActivityStreamService
 * <p/>
 * Parameters:
 * userIds The set of ids of the people to fetch activities for.
 * groupId Indicates whether to fetch activities for a group.
 * appId The app id.
 * fields The fields to return. Empty set implies all
 * options The sorting/filtering/pagination options
 * token A valid SecurityToken
 * Returns:
 * a response item with the list of activities.
 */
@Override
public Future<RestfulCollection<ActivityEntry>> getActivityEntries(Set<UserId> userIds, GroupId groupId,
        String appId, Set<String> fields, CollectionOptions options, SecurityToken token) {
    List<ActivityEntry> result = getFromRepository(userIds, groupId, appId, fields, options, token);
    return Futures.immediateFuture(new RestfulCollection<ActivityEntry>(result));

}