List of usage examples for com.google.common.util.concurrent Futures transform
public static <I, O> ListenableFuture<O> transform(ListenableFuture<I> input, Function<? super I, ? extends O> function, Executor executor)
From source file:io.v.v23.VFutures.java
/** * Returns a new {@link ListenableFuture} whose result is the same as the result of the * given {@code future} and is executed on an {@link Executor} specified in the given * {@code context}./*from w ww.j av a 2 s. com*/ * <p> * If no executor is specified in the context, the future may be executed on an arbitrary * thread. */ public static <T> ListenableFuture<T> onExecutor(final VContext context, final ListenableFuture<T> future) { Executor executor = V.getExecutor(context); if (executor == null) { return future; } return Futures.transform(future, new AsyncFunction<T, T>() { @Override public ListenableFuture<T> apply(T input) throws Exception { return Futures.immediateFuture(input); } }, executor); }
From source file:org.thingsboard.server.dao.sql.timeseries.JpaTimeseriesDao.java
@Override public ListenableFuture<List<TsKvEntry>> findAllAsync(TenantId tenantId, EntityId entityId, List<ReadTsKvQuery> queries) { List<ListenableFuture<List<TsKvEntry>>> futures = queries.stream() .map(query -> findAllAsync(tenantId, entityId, query)).collect(Collectors.toList()); return Futures.transform(Futures.allAsList(futures), new Function<List<List<TsKvEntry>>, List<TsKvEntry>>() { @Nullable/*from www.ja v a 2s . co m*/ @Override public List<TsKvEntry> apply(@Nullable List<List<TsKvEntry>> results) { if (results == null || results.isEmpty()) { return null; } return results.stream().flatMap(List::stream).collect(Collectors.toList()); } }, service); }
From source file:org.jclouds.atmos.internal.StubAtmosAsyncClient.java
@Override public ListenableFuture<URI> createDirectory(String directoryName, PutOptions... options) { final String container; final String path; if (directoryName.indexOf('/') != -1) { container = directoryName.substring(0, directoryName.indexOf('/')); path = directoryName.substring(directoryName.indexOf('/') + 1); } else {/*w ww. j a v a2s . c o m*/ container = directoryName; path = null; } return Futures.transform(blobStore.createContainerInLocation(null, container), new Function<Boolean, URI>() { public URI apply(Boolean from) { if (path != null) { Blob blob = blobStore.blobBuilder(path + "/").payload("") .contentType("application/directory").build(); blobStore.putBlob(container, blob); } return URI.create("http://stub/containers/" + container); } }, userExecutor); }
From source file:com.facebook.buck.remoteexecution.grpc.GrpcRemoteExecutionServiceClient.java
@Override public ListenableFuture<ExecutionResult> execute(Protocol.Digest actionDigest, String ruleName) throws IOException, InterruptedException { SettableFuture<Operation> future = SettableFuture.create(); StubAndResponseMetadata<ExecutionStub> stubAndMetadata = GrpcHeaderHandler .wrapStubToSendAndReceiveMetadata(executionStub, metadataProvider .getForAction(RemoteExecutionActionEvent.actionDigestToString(actionDigest), ruleName)); stubAndMetadata.getStub().execute(/*from w ww . jav a2s . com*/ ExecuteRequest.newBuilder().setInstanceName(instanceName) .setActionDigest(GrpcProtocol.get(actionDigest)).setSkipCacheLookup(false).build(), new StreamObserver<Operation>() { @Nullable Operation op = null; @Override public void onNext(Operation value) { op = value; } @Override public void onError(Throwable t) { String msg = String.format( "Failed execution request with metadata=[%s] and exception=[%s].", stubAndMetadata.getMetadata(), t.toString()); LOG.error(msg); future.setException(new IOException(msg, t)); } @Override public void onCompleted() { future.set(op); } }); return Futures.transform(future, operation -> { Objects.requireNonNull(operation); if (operation.hasError()) { throw new RuntimeException( String.format("Execution failed due to an infra error with Status=[%s] Metadata=[%s].", operation.getError().toString(), stubAndMetadata.getMetadata())); } if (!operation.hasResponse()) { throw new RuntimeException(String.format( "Invalid operation response: missing ExecutionResponse object. " + "Response=[%s] Metadata=[%s].", operation.toString(), stubAndMetadata.getMetadata())); } try { return getExecutionResult(operation.getResponse().unpack(ExecuteResponse.class).getResult(), stubAndMetadata.getMetadata()); } catch (InvalidProtocolBufferException e) { throw new BuckUncheckedExecutionException(e, "Exception getting execution result with Metadata=[%s].", stubAndMetadata.getMetadata()); } }, MoreExecutors.directExecutor()); }
From source file:org.thingsboard.server.dao.attributes.CassandraBaseAttributesDao.java
@Override public ListenableFuture<List<AttributeKvEntry>> findAll(TenantId tenantId, EntityId entityId, String attributeType) {//from w w w .j a v a 2 s . c o m Select.Where select = select().from(ATTRIBUTES_KV_CF) .where(eq(ENTITY_TYPE_COLUMN, entityId.getEntityType())).and(eq(ENTITY_ID_COLUMN, entityId.getId())) .and(eq(ATTRIBUTE_TYPE_COLUMN, attributeType)); log.trace("Generated query [{}] for entityId {} and attributeType {}", select, entityId, attributeType); return Futures.transform(executeAsyncRead(tenantId, select), (Function<? super ResultSet, ? extends List<AttributeKvEntry>>) input -> convertResultToAttributesKvEntryList( input), readResultsProcessingExecutor); }
From source file:com.facebook.buck.distributed.DistributedBuildFileHashes.java
private static ListenableFuture<ImmutableMap<BuildRule, RuleKey>> ruleKeyComputation(ActionGraph actionGraph, final LoadingCache<ProjectFilesystem, DefaultRuleKeyBuilderFactory> ruleKeyFactories, ListeningExecutorService executorService) { List<ListenableFuture<Map.Entry<BuildRule, RuleKey>>> ruleKeyEntries = new ArrayList<>(); for (final BuildRule rule : actionGraph.getNodes()) { ruleKeyEntries.add(executorService.submit(new Callable<Map.Entry<BuildRule, RuleKey>>() { @Override//from w ww . j a v a 2 s. c om public Map.Entry<BuildRule, RuleKey> call() throws Exception { return Maps.immutableEntry(rule, ruleKeyFactories.get(rule.getProjectFilesystem()).build(rule)); } })); } ListenableFuture<List<Map.Entry<BuildRule, RuleKey>>> ruleKeyComputation = Futures .allAsList(ruleKeyEntries); return Futures.transform(ruleKeyComputation, new Function<List<Map.Entry<BuildRule, RuleKey>>, ImmutableMap<BuildRule, RuleKey>>() { @Override public ImmutableMap<BuildRule, RuleKey> apply(List<Map.Entry<BuildRule, RuleKey>> input) { return ImmutableMap.copyOf(input); } }, executorService); }
From source file:org.thingsboard.server.dao.audit.CassandraAuditLogDao.java
private <T> ListenableFuture<T> getFuture(ResultSetFuture future, java.util.function.Function<ResultSet, T> transformer) { return Futures.transform(future, new Function<ResultSet, T>() { @Nullable/*from w w w.j a va 2 s .com*/ @Override public T apply(@Nullable ResultSet input) { return transformer.apply(input); } }, readResultsProcessingExecutor); }
From source file:com.facebook.buck.distributed.DistBuildFileHashes.java
private static ListenableFuture<ImmutableMap<BuildRule, RuleKey>> ruleKeyComputation(ActionGraph actionGraph, final LoadingCache<ProjectFilesystem, DefaultRuleKeyFactory> ruleKeyFactories, ListeningExecutorService executorService) { List<ListenableFuture<Map.Entry<BuildRule, RuleKey>>> ruleKeyEntries = new ArrayList<>(); for (final BuildRule rule : actionGraph.getNodes()) { ruleKeyEntries.add(executorService.submit(() -> Maps.immutableEntry(rule, ruleKeyFactories.get(rule.getProjectFilesystem()).build(rule)))); }// ww w .j a v a 2 s . com ListenableFuture<List<Map.Entry<BuildRule, RuleKey>>> ruleKeyComputation = Futures .allAsList(ruleKeyEntries); return Futures.transform(ruleKeyComputation, new Function<List<Map.Entry<BuildRule, RuleKey>>, ImmutableMap<BuildRule, RuleKey>>() { @Override public ImmutableMap<BuildRule, RuleKey> apply(List<Map.Entry<BuildRule, RuleKey>> input) { return ImmutableMap.copyOf(input); } }, executorService); }
From source file:org.apache.helix.provisioning.yarn.YarnProvisioner.java
@Override public ListenableFuture<Boolean> deallocateContainer(final ContainerId containerId) { ListenableFuture<ContainerReleaseResponse> releaseContainer = applicationMaster .releaseContainer(allocatedContainersMap.get(containerId)); return Futures.transform(releaseContainer, new Function<ContainerReleaseResponse, Boolean>() { @Override// w w w .j a v a 2s .c om public Boolean apply(ContainerReleaseResponse response) { return response != null; } }, service); }
From source file:org.smartdeveloperhub.harvesters.it.frontend.publisher.DynamicPublisher.java
@Override public void start() { LOGGER.info("Starting publisher..."); try {/* w w w. j av a 2 s.c o m*/ LOGGER.info("Starting notification manager..."); this.manager.start(); LOGGER.info("Started notification manager. Starting initial publication..."); // Queue the publisher tasks... @SuppressWarnings("unchecked") final ListenableFuture<List<Boolean>> terminations = Futures.<Boolean>allAsList( submitTask(new ProjectContentPublisherTask(this.controller)), submitTask(new ContributorPublisherTask(this.controller)), submitTask(new CommitPublisherTask(this.controller))); // Combine their result final ListenableFuture<Boolean> aggregatedTermination = Futures.transform(terminations, new PublicationTerminationAggregator(), this.pool); // ... and take an action Futures.addCallback(aggregatedTermination, new PublicationTerminationHandler(), this.pool); } catch (final IOException e) { LOGGER.error("Could not start notification manager. Full stacktrace follows:", e); } finally { LOGGER.info("Publisher started."); } }