Java Code Examples for com.google.common.util.concurrent.Futures#transform()

The following examples show how to use com.google.common.util.concurrent.Futures#transform() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BaseRelationService.java    From iotplatform with Apache License 2.0 6 votes vote down vote up
@Override
public ListenableFuture<List<EntityRelationInfo>> findInfoByFrom(EntityId from, RelationTypeGroup typeGroup) {
    log.trace("Executing findInfoByFrom [{}][{}]", from, typeGroup);
    validate(from);
    validateTypeGroup(typeGroup);
    ListenableFuture<List<EntityRelation>> relations = relationDao.findAllByFrom(from, typeGroup);
    ListenableFuture<List<EntityRelationInfo>> relationsInfo = Futures.transform(relations,
            (AsyncFunction<List<EntityRelation>, List<EntityRelationInfo>>) relations1 -> {
        List<ListenableFuture<EntityRelationInfo>> futures = new ArrayList<>();
                relations1.stream().forEach(relation ->
                        futures.add(fetchRelationInfoAsync(relation,
                                relation2 -> relation2.getTo(),
                                (EntityRelationInfo relationInfo, String entityName) -> relationInfo.setToName(entityName)))
                );
                return Futures.successfulAsList(futures);
    });
    return relationsInfo;
}
 
Example 2
Source File: AddSourceToProjectHelper.java    From intellij with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the list of targets building the given source file, which aren't already in the
 * project. Returns null if this can't be calculated.
 */
@Nullable
static ListenableFuture<List<TargetInfo>> getTargetsBuildingSource(LocationContext context) {
  if (!SourceToTargetProvider.hasProvider()) {
    return null;
  }
  // early-out if source is trivially covered by project targets (e.g. because there's a wildcard
  // target pattern for the parent package)
  if (context.getImportRoots().packageInProjectTargets(context.blazePackage)) {
    return null;
  }
  // Finally, query the exact targets building this source file.
  // This is required to handle project targets which failed to build
  return Futures.transform(
      SourceToTargetHelper.findTargetsBuildingSourceFile(
          context.project, context.workspacePath.relativePath()),
      (Function<List<TargetInfo>, List<TargetInfo>>)
          (List<TargetInfo> result) ->
              result == null || sourceInProjectTargets(context, fromTargetInfo(result))
                  ? ImmutableList.of()
                  : result,
      MoreExecutors.directExecutor());
}
 
Example 3
Source File: OvsdbClientImpl.java    From ovsdb with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public ListenableFuture<TypedDatabaseSchema> getSchema(final String database) {
    final TypedDatabaseSchema existing = schemas.get(database);
    if (existing != null) {
        return Futures.immediateFuture(existing);
    }

    return Futures.transform(getSchemaFromDevice(Collections.singletonList(database)), result -> {
        final DatabaseSchema dbSchema = result.get(database);
        if (dbSchema == null) {
            return null;
        }

        final TypedDatabaseSchema typedSchema = TypedDatabaseSchema.of(dbSchema.withInternallyGeneratedColumns());
        final TypedDatabaseSchema raced = schemas.putIfAbsent(database, typedSchema);
        return raced != null ? raced : typedSchema;
    }, executorService);
}
 
Example 4
Source File: Publisher.java    From curiostack with MIT License 6 votes vote down vote up
public ListenableFuture<String> publish(PubsubMessage message) {
  Span span = tracer.currentSpan();
  if (span != null) {
    PubsubMessage.Builder messageBuilder = message.toBuilder();
    traceInjector.inject(span.context(), messageBuilder);
    message = messageBuilder.build();
  }

  PublishRequest request =
      PublishRequest.newBuilder().setTopic(options.getTopic()).addMessages(message).build();

  return Futures.transform(
      stub.publish(request),
      (response) -> {
        if (response.getMessageIdsCount() != 1) {
          throw new IllegalStateException(
              String.format(
                  "The publish result count %s does not match "
                      + "the expected 1 result. Please contact Cloud Pub/Sub support "
                      + "if this frequently occurs",
                  response.getMessageIdsCount()));
        }
        return response.getMessageIds(0);
      },
      MoreExecutors.directExecutor());
}
 
Example 5
Source File: PendingAsyncTestContext.java    From intellij with Apache License 2.0 5 votes vote down vote up
static PendingAsyncTestContext fromTargetFuture(
    ImmutableSet<ExecutorType> supportedExecutors,
    ListenableFuture<TargetInfo> target,
    PsiElement sourceElement,
    ImmutableList<BlazeFlagsModification> blazeFlags,
    @Nullable String description) {
  Project project = sourceElement.getProject();
  String buildSystem = Blaze.buildSystemName(project);
  String progressMessage = String.format("Searching for %s target", buildSystem);
  ListenableFuture<RunConfigurationContext> future =
      Futures.transform(
          target,
          t -> {
            if (t == null) {
              return new FailedPendingRunConfiguration(
                  sourceElement, String.format("No %s target found.", buildSystem));
            }
            RunConfigurationContext context =
                PendingWebTestContext.findWebTestContext(
                    project, supportedExecutors, t, sourceElement, blazeFlags, description);
            return context != null
                ? context
                : new KnownTargetTestContext(t, sourceElement, blazeFlags, description);
          },
          MoreExecutors.directExecutor());
  return new PendingAsyncTestContext(
      supportedExecutors, future, progressMessage, sourceElement, blazeFlags, description);
}
 
Example 6
Source File: IdentityGroup.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
ListenableFuture<Boolean> removeMember(EntityKey memberKey, IdentityService identityService)
    throws IOException {
  Membership existing = members.get(memberKey);
  if (existing == null) {
    return Futures.immediateFuture(true);
  }
  String groupId = groupResourceName.get();
  String memberId = existing.getName();
  ListenableFuture<Operation> created = identityService.deleteMembership(memberId);
  return Futures.transform(
      created,
      new Function<Operation, Boolean>() {
        @Override
        @Nullable
        public Boolean apply(@Nullable Operation input) {
          try {
            validateOperation(input);
            removeMember(memberKey);
            return true;
          } catch (IOException e) {
            logger.log(
                Level.WARNING,
                String.format("Failed to delete membership %s under group %s", existing, groupId),
                e);
            return false;
          }
        }
      },
      getExecutor());
}
 
Example 7
Source File: JavascriptTestContextProvider.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public RunConfigurationContext getTestContext(ConfigurationContext context) {
  JSFile file =
      Optional.of(context)
          .map(ConfigurationContext::getPsiLocation)
          .map(PsiElement::getContainingFile)
          .filter(JSFile.class::isInstance)
          .map(JSFile.class::cast)
          .orElse(null);
  if (file == null) {
    return null;
  }
  ListenableFuture<TargetInfo> targetFuture =
      TestTargetHeuristic.targetFutureForPsiElement(file, null);
  if (targetFuture == null) {
    return null;
  }
  targetFuture =
      Futures.transform(
          targetFuture,
          (target) ->
              target != null && ReadAction.compute(() -> isTestFile(file)) ? target : null,
          ApplicationManager.getApplication().isUnitTestMode()
              ? MoreExecutors.directExecutor()
              : PooledThreadExecutor.INSTANCE);
  return TestContext.builder(file, ExecutorType.DEBUG_UNSUPPORTED_TYPES)
      .setTarget(targetFuture)
      .setTestFilter(getTestFilter(file))
      .setDescription(file.getName())
      .build();
}
 
Example 8
Source File: CatalogTraversal.java    From metacat with Apache License 2.0 5 votes vote down vote up
/**
 * Apply all tables to all registered actions.
 *
 * @param name database Name
 * @param dtos        table dtos
 * @return future
 */
private ListenableFuture<Void> applyTables(final QualifiedName name, final List<Optional<TableDto>> dtos) {
    log.info("Traversal: Apply tables for database: {}", name);
    final List<ListenableFuture<Void>> actionFutures = actions.stream()
        .map(a -> actionService.submit((Callable<Void>) () -> {
            a.applyTables(context, dtos);
            return null;
        })).collect(Collectors.toList());
    return Futures.transform(Futures.successfulAsList(actionFutures),
        Functions.constant(null), defaultService);
}
 
Example 9
Source File: OutputsMaterializerTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Override
public ListenableFuture<Unit> fetchToStream(Digest digest, WritableByteChannel channel) {
  return Futures.transform(
      fetch(digest),
      buf -> {
        try {
          channel.write(buf);
          /* Close just as in batchFetchBlobs try() to fix isClosed test in testMaterializeFiles */
          channel.close();
          return null;
        } catch (IOException e) {
          throw new RuntimeException(e);
        }
      });
}
 
Example 10
Source File: AbstractExecutionServiceController.java    From twill with Apache License 2.0 5 votes vote down vote up
@Override
public Future<? extends ServiceController> terminate() {
  stop();

  return Futures.transform(terminationFuture, new Function<State, ServiceController>() {
    @Override
    public ServiceController apply(State input) {
      return AbstractExecutionServiceController.this;
    }
  });
}
 
Example 11
Source File: AbstractTwillController.java    From twill with Apache License 2.0 5 votes vote down vote up
@Override
public ListenableFuture<String> restartInstances(final String runnable, Set<Integer> instanceIds) {
  return Futures.transform(restartInstances(ImmutableMap.of(runnable, instanceIds)),
                           new Function<Set<String>, String>() {
                             public String apply(Set<String> input) {
                               return runnable;
                             }
                           });
}
 
Example 12
Source File: Office365ManagerImpl.java    From Microsoft-Cloud-Services-for-Android with MIT License 5 votes vote down vote up
private <T> ListenableFuture<T> getFirstItem(ListenableFuture<List<T>> future) {
    return Futures.transform(future, new AsyncFunction<List<T>, T>() {
        @Override
        public ListenableFuture<T> apply(List<T> items) throws Exception {
            return Futures.immediateFuture((items != null && items.size() > 0) ? items.get(0) : null);
        }
    });
}
 
Example 13
Source File: DDLStatementDispatcher.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private ListenableFuture<Long> wrapRowCountFuture(ListenableFuture<?> wrappedFuture, final Long rowCount) {
    return Futures.transform(wrappedFuture, new Function<Object, Long>() {
        @Nullable
        @Override
        public Long apply(@Nullable Object input) {
            return rowCount;
        }
    });
}
 
Example 14
Source File: CreateTunnelInstructionExecutor.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected ListenableFuture<OperationResult> invokeOperation() {
    try (ReadTransaction transaction = this.dataProvider.newReadOnlyTransaction()) {
        AddLspInput addLspInput = createAddLspInput(transaction);

        return Futures.transform(
                this.topologyService.addLsp(addLspInput),
                RpcResult::getResult, MoreExecutors.directExecutor());
    }
}
 
Example 15
Source File: ByteStreamBuildEventArtifactUploader.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * For files where {@link PathMetadata#isRemote()} returns {@code false} this method checks if the
 * remote cache already contains the file. If so {@link PathMetadata#isRemote()} is set to {@code
 * true}.
 */
private ListenableFuture<ImmutableIterable<PathMetadata>> queryRemoteCache(
    ImmutableList<ListenableFuture<PathMetadata>> allPaths) throws Exception {
  List<PathMetadata> knownRemotePaths = new ArrayList<>(allPaths.size());
  List<PathMetadata> filesToQuery = new ArrayList<>();
  Set<Digest> digestsToQuery = new HashSet<>();
  for (ListenableFuture<PathMetadata> pathMetadataFuture : allPaths) {
    // This line is guaranteed to not block, as this code is only called after all futures in
    // allPaths have completed.
    PathMetadata pathMetadata = pathMetadataFuture.get();
    if (pathMetadata.isRemote() || pathMetadata.isDirectory()) {
      knownRemotePaths.add(pathMetadata);
    } else {
      filesToQuery.add(pathMetadata);
      digestsToQuery.add(pathMetadata.getDigest());
    }
  }
  if (digestsToQuery.isEmpty()) {
    return Futures.immediateFuture(ImmutableIterable.from(knownRemotePaths));
  }
  return Futures.transform(
      ctx.call(() -> missingDigestsFinder.findMissingDigests(digestsToQuery)),
      (missingDigests) -> {
        List<PathMetadata> filesToQueryUpdated = processQueryResult(missingDigests, filesToQuery);
        return ImmutableIterable.from(Iterables.concat(knownRemotePaths, filesToQueryUpdated));
      },
      MoreExecutors.directExecutor());
}
 
Example 16
Source File: C5GeneralizedReplicationService.java    From c5-replicator with Apache License 2.0 5 votes vote down vote up
@Override
public ListenableFuture<GeneralizedReplicator> createReplicator(String quorumId, Collection<Long> peerIds) {
  return Futures.transform(
      replicationModule.createReplicator(quorumId, peerIds),
      (Replicator replicator) -> {
        return new C5GeneralizedReplicator(replicator, createAndStartFiber(this::notifyFailed));
      });
}
 
Example 17
Source File: FutureTransformUtils.java    From ovsdb with Eclipse Public License 1.0 4 votes vote down vote up
public static ListenableFuture<List<OperationResult>> transformTransactResponse(
        final ListenableFuture<List<JsonNode>> transactResponseFuture, final List<Operation> operations) {
    return Futures.transform(transactResponseFuture, jsonNodes -> {
        final List<OperationResult> operationResults = new ArrayList<>();
        for (int index = 0; index < jsonNodes.size(); index++) {
            JsonNode jsonNode = jsonNodes.get(index);
            OperationResult or;
            if (jsonNode != null && jsonNode.size() > 0) {
                /*
                 * As per RFC 7047, section 4.1.3 :
                 * "In general, "result" contains some number of successful results,
                 * possibly followed by an error, in turn followed by enough JSON null
                 * values to match the number of elements in "params".  There is one
                 * exception: if all of the operations succeed, but the results cannot
                 * be committed, then "result" will have one more element than "params",
                 * with the additional element being an <error>."
                 *
                 * Hence, it is possible for a transaction response to contain more
                 * json elements than the transaction operation request.
                 * Also handle that case by checking for i < operations.size().
                 */
                if (index < operations.size()) {
                    Operation op = operations.get(index);
                    switch (op.getOp()) {
                        case "select":
                            or = new OperationResult();
                            or.setRows(op.getTableSchema().createRows(jsonNode));
                            break;

                        default:
                            or = OBJECT_MAPPER.convertValue(jsonNode, OperationResult.class);

                            break;
                    }
                } else {
                    or = OBJECT_MAPPER.convertValue(jsonNode, OperationResult.class);
                }
            } else {
                or = new OperationResult();
            }
            operationResults.add(or);
        }

        return operationResults;
    }, MoreExecutors.directExecutor());
}
 
Example 18
Source File: AbstractConfiguredObject.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
protected final ListenableFuture<Void> deleteChildren()
{
    // If this object manages its own child-storage then don't propagate the delete.  The rationale
    // is that deleting the object will delete the storage that contains the children.  Telling each
    // child and their children to delete themselves would generate unnecessary 'delete' work in the
    // child-storage (which also might fail).
    if (managesChildStorage())
    {
        return Futures.immediateFuture(null);
    }

    final List<ListenableFuture<Void>> childDeleteFutures = new ArrayList<>();

    applyToChildren(child -> {

        final ListenableFuture<Void> childDeleteFuture;
        if (child instanceof AbstractConfiguredObject<?>)
        {
             childDeleteFuture = ((AbstractConfiguredObject<?>) child).deleteNoChecks();
        }
        else if (child instanceof AbstractConfiguredObjectProxy)
        {
            childDeleteFuture = ((AbstractConfiguredObjectProxy) child).deleteNoChecks();
        }
        else
        {
            childDeleteFuture = Futures.immediateFuture(null);
        }

        addFutureCallback(childDeleteFuture, new FutureCallback<Void>()
        {
            @Override
            public void onSuccess(final Void result)
            {
            }

            @Override
            public void onFailure(final Throwable t)
            {
                LOGGER.error("Exception occurred while deleting {} : {}",
                             child.getClass().getSimpleName(), child.getName(), t);
            }
        }, getTaskExecutor());
        childDeleteFutures.add(childDeleteFuture);
    });

    ListenableFuture<List<Void>> combinedFuture = Futures.allAsList(childDeleteFutures);

    return Futures.transform(combinedFuture, input -> null, getTaskExecutor());
}
 
Example 19
Source File: TestBufferingSplitSource.java    From presto with Apache License 2.0 4 votes vote down vote up
private static ListenableFuture<NextBatchResult> getNextBatch(SplitSource splitSource, int maxSize)
{
    ListenableFuture<SplitBatch> future = splitSource.getNextBatch(NOT_PARTITIONED, Lifespan.taskWide(), maxSize);
    return Futures.transform(future, NextBatchResult::new, directExecutor());
}
 
Example 20
Source File: MultiArtifactCache.java    From buck with Apache License 2.0 4 votes vote down vote up
@Override
public ListenableFuture<ImmutableMap<RuleKey, CacheResult>> multiContainsAsync(
    ImmutableSet<RuleKey> ruleKeys) {
  Map<RuleKey, CacheResult> initialResults = new HashMap<>(ruleKeys.size());
  for (RuleKey ruleKey : ruleKeys) {
    initialResults.put(ruleKey, CacheResult.miss());
  }

  ListenableFuture<Map<RuleKey, CacheResult>> cacheResultFuture =
      Futures.immediateFuture(initialResults);

  for (ArtifactCache nextCache : artifactCaches) {
    cacheResultFuture =
        Futures.transformAsync(
            cacheResultFuture,
            mergedResults -> {
              ImmutableSet<RuleKey> missingKeys =
                  mergedResults.entrySet().stream()
                      .filter(e -> !e.getValue().getType().isSuccess())
                      .map(Map.Entry::getKey)
                      .collect(ImmutableSet.toImmutableSet());

              if (missingKeys.isEmpty()) {
                return Futures.immediateFuture(mergedResults);
              }

              ListenableFuture<ImmutableMap<RuleKey, CacheResult>> more =
                  nextCache.multiContainsAsync(missingKeys);
              return Futures.transform(
                  more,
                  results -> {
                    mergedResults.putAll(results);
                    return mergedResults;
                  },
                  MoreExecutors.directExecutor());
            },
            MoreExecutors.directExecutor());
  }

  return Futures.transform(
      cacheResultFuture, ImmutableMap::copyOf, MoreExecutors.directExecutor());
}