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)
From source file:dk.ilios.spanner.internal.ExperimentingSpannerRun.java
/** * Schedule all the trials.//from www . j a v a2 s. com * <p> * <p>This method arranges all the {@link ScheduledTrial trials} to run according to their * scheduling criteria. The executor instance is responsible for enforcing max parallelism. */ private List<ListenableFuture<Trial.Result>> scheduleTrials(List<ScheduledTrial> trials, final ListeningExecutorService executor) { List<ListenableFuture<Trial.Result>> pendingTrials = Lists.newArrayList(); List<ScheduledTrial> serialTrials = Lists.newArrayList(); for (final ScheduledTrial scheduledTrial : trials) { if (scheduledTrial.policy() == TrialSchedulingPolicy.PARALLEL) { pendingTrials.add(executor.submit(scheduledTrial.trialTask())); } else { serialTrials.add(scheduledTrial); } } // A future representing the completion of all prior tasks. Futures.successfulAsList allows us // to ignore failure. ListenableFuture<?> previous = Futures.successfulAsList(pendingTrials); for (final ScheduledTrial scheduledTrial : serialTrials) { // each of these trials can only start after all prior trials have finished, so we use // Futures.transform to force the sequencing. ListenableFuture<Trial.Result> current = Futures.transform(previous, new AsyncFunction<Object, Trial.Result>() { @Override public ListenableFuture<Trial.Result> apply(Object ignored) { return executor.submit(scheduledTrial.trialTask()); } }); pendingTrials.add(current); // ignore failure of the prior task. previous = Futures.withFallback(current, FALLBACK_TO_NULL); } return pendingTrials; }
From source file:org.opendaylight.openflowplugin.impl.util.FlatBatchUtil.java
/** * Merge list of Futures with partial results into one ListenableFuture with single result. * @param firedJobs list of ListenableFutures with RPC results {@link ProcessFlatBatchOutput} * @return ListenableFuture of RPC result with combined status and all errors + batch failures *//*from ww w . j a va2s .com*/ public static ListenableFuture<RpcResult<ProcessFlatBatchOutput>> mergeJobsResultsFutures( final List<ListenableFuture<RpcResult<ProcessFlatBatchOutput>>> firedJobs) { return Futures.transform(Futures.successfulAsList(firedJobs), mergeRpcResults()); }
From source file:org.glassfish.jersey.examples.rx.agent.ListenableFutureAgentResource.java
private ListenableFuture<List<Recommendation>> calculations( final ListenableFuture<List<Recommendation>> recommendations) { return Futures.transform(recommendations, new AsyncFunction<List<Recommendation>, List<Recommendation>>() { @Override//w ww.j av a 2 s. c o m public ListenableFuture<List<Recommendation>> apply(final List<Recommendation> input) throws Exception { final RxWebTarget<RxListenableFutureInvoker> rxCalculations = RxListenableFuture.from(calculation); return Futures.successfulAsList( Lists.transform(input, new Function<Recommendation, ListenableFuture<Recommendation>>() { @Override public ListenableFuture<Recommendation> apply(final Recommendation r) { return Futures.transform( rxCalculations.resolveTemplate("from", "Moon") .resolveTemplate("to", r.getDestination()).request().rx() .get(Calculation.class), new AsyncFunction<Calculation, Recommendation>() { @Override public ListenableFuture<Recommendation> apply(final Calculation c) throws Exception { r.setPrice(c.getPrice()); return Futures.immediateFuture(r); } }); } })); } }); }
From source file:me.j360.trace.storage.elasticsearch.ElasticsearchSpanStore.java
ListenableFuture<List<List<Span>>> getTracesByIds(Collection<Long> traceIds, String[] indices) { List<String> traceIdsStr = new ArrayList<>(traceIds.size()); for (long traceId : traceIds) { traceIdsStr.add(Util.toLowerHex(traceId)); }//from w ww .j av a 2s . c o m SearchRequestBuilder elasticRequest = client.prepareSearch(indices) .setIndicesOptions(IndicesOptions.lenientExpandOpen()).setTypes(ElasticsearchConstants.SPAN) .setSize(MAX_RAW_SPANS).setQuery(termsQuery("traceId", traceIdsStr)); return Futures.transform(ElasticFutures.toGuava(elasticRequest.execute()), ConvertTracesResponse.INSTANCE); }
From source file:com.spotify.asyncdatastoreclient.Datastore.java
/** * Rollback a given transaction.//from www .j a v a 2 s .c o m * * You normally rollback a transaction in the event of d Datastore failure. * * @param txn the transaction. * @return the result of the rollback request. */ public ListenableFuture<RollbackResult> rollbackAsync(final ListenableFuture<TransactionResult> txn) { final ListenableFuture<Response> httpResponse = Futures.transform(txn, (TransactionResult result) -> { final ByteString transaction = result.getTransaction(); if (transaction == null) { throw new DatastoreException("Invalid transaction."); } final DatastoreV1.RollbackRequest.Builder request = DatastoreV1.RollbackRequest.newBuilder(); final ProtoHttpContent payload = new ProtoHttpContent(request.build()); return ListenableFutureAdapter.asGuavaFuture(prepareRequest("rollback", payload).execute()); }); return Futures.transform(httpResponse, (Response response) -> { if (!isSuccessful(response.getStatusCode())) { throw new DatastoreException(response.getStatusCode(), response.getResponseBody()); } final DatastoreV1.RollbackResponse rollback = DatastoreV1.RollbackResponse .parseFrom(streamResponse(response)); return Futures.immediateFuture(RollbackResult.build(rollback)); }); }
From source file:org.fixtrading.silverflash.fixp.store.CassandraMessageStore.java
public void retrieveMessagesAsync(final MessageStoreResult result, Consumer<MessageStoreResult> consumer) { final long fromSeqNo = result.getFromSeqNo(); boundSelectStatement.bind(result.getSessionId(), fromSeqNo, fromSeqNo + result.getCountRequested()); final ResultSetFuture resultSetFuture = session.executeAsync(boundSelectStatement); Function<ResultSet, MessageStoreResult> rowFunction = resultSet -> { final RowConsumer action = new RowConsumer(result); resultSet.forEach(action);/*from w ww .j a v a 2 s. com*/ return result; }; ListenableFuture<MessageStoreResult> queryFuture = Futures.transform(resultSetFuture, rowFunction); FutureCallback<MessageStoreResult> retrievalCallback = new FutureCallback<MessageStoreResult>() { public void onFailure(Throwable ex) { ex.printStackTrace(); } public void onSuccess(MessageStoreResult result) { consumer.accept(result); } }; Futures.addCallback(queryFuture, retrievalCallback, executor); }
From source file:org.thingsboard.server.dao.dashboard.DashboardServiceImpl.java
@Override public ListenableFuture<TimePageData<DashboardInfo>> findDashboardsByTenantIdAndCustomerId(TenantId tenantId, CustomerId customerId, TimePageLink pageLink) { log.trace("Executing findDashboardsByTenantIdAndCustomerId, tenantId [{}], customerId [{}], pageLink [{}]", tenantId, customerId, pageLink); Validator.validateId(tenantId, INCORRECT_TENANT_ID + tenantId); Validator.validateId(customerId, "Incorrect customerId " + customerId); Validator.validatePageLink(pageLink, "Incorrect page link " + pageLink); ListenableFuture<List<DashboardInfo>> dashboards = dashboardInfoDao .findDashboardsByTenantIdAndCustomerId(tenantId.getId(), customerId.getId(), pageLink); return Futures.transform(dashboards, new Function<List<DashboardInfo>, TimePageData<DashboardInfo>>() { @Nullable/*from w w w. ja va2 s . c o m*/ @Override public TimePageData<DashboardInfo> apply(@Nullable List<DashboardInfo> dashboards) { return new TimePageData<>(dashboards, pageLink); } }); }
From source file:com.facebook.buck.rules.modern.builders.grpc.GrpcRemoteExecution.java
private ContentAddressedStorage createStorage(ContentAddressableStorageFutureStub storageStub, ByteStreamStub byteStreamStub, String instanceName, Protocol protocol) { MultiThreadedBlobUploader uploader = new MultiThreadedBlobUploader(1000, 10 * 1024 * 1024, MostExecutors.newMultiThreadExecutor("blob-uploader", 4), new CasBlobUploader() { @Override//from w ww . ja v a2 s . c om public ImmutableSet<String> getMissingHashes(List<Protocol.Digest> requiredDigests) throws IOException { try { FindMissingBlobsRequest.Builder requestBuilder = FindMissingBlobsRequest.newBuilder(); requiredDigests .forEach(digest -> requestBuilder.addBlobDigests((GrpcProtocol.get(digest)))); return storageStub.findMissingBlobs(requestBuilder.build()).get() .getMissingBlobDigestsList().stream().map(Digest::getHash) .collect(ImmutableSet.toImmutableSet()); } catch (InterruptedException | ExecutionException e) { Throwables.throwIfInstanceOf(e.getCause(), IOException.class); e.printStackTrace(); throw new BuckUncheckedExecutionException(e); } catch (RuntimeException e) { throw e; } } @Override public ImmutableList<UploadResult> batchUpdateBlobs(ImmutableList<UploadData> blobs) throws IOException { try { BatchUpdateBlobsRequest.Builder requestBuilder = BatchUpdateBlobsRequest.newBuilder(); for (UploadData blob : blobs) { try (InputStream dataStream = blob.data.get()) { requestBuilder.addRequests(UpdateBlobRequest.newBuilder() .setContentDigest(GrpcProtocol.get(blob.digest)) .setData(ByteString.readFrom(dataStream))); } } BatchUpdateBlobsResponse batchUpdateBlobsResponse = storageStub .batchUpdateBlobs(requestBuilder.build()).get(); ImmutableList.Builder<UploadResult> resultBuilder = ImmutableList.builder(); for (Response response : batchUpdateBlobsResponse.getResponsesList()) { resultBuilder.add(new UploadResult(new GrpcDigest(response.getBlobDigest()), response.getStatus().getCode(), response.getStatus().getMessage())); } return resultBuilder.build(); } catch (InterruptedException | ExecutionException e) { MoreThrowables.throwIfInitialCauseInstanceOf(e, IOException.class); e.printStackTrace(); throw new BuckUncheckedExecutionException(e); } } }); OutputsMaterializer outputsMaterializer = new OutputsMaterializer(new AsyncBlobFetcher() { @Override public ListenableFuture<ByteBuffer> fetch(Protocol.Digest digest) { return Futures.transform(readByteStream(instanceName, digest, byteStreamStub), string -> string.asReadOnlyByteBuffer()); } @Override public void fetchToStream(Protocol.Digest digest, OutputStream outputStream) { throw new UnsupportedOperationException(); } }, protocol); return new ContentAddressedStorage() { @Override public void addMissing(ImmutableMap<Protocol.Digest, ThrowingSupplier<InputStream, IOException>> data) throws IOException { uploader.addMissing(data); } @Override public void materializeOutputs(List<OutputDirectory> outputDirectories, List<OutputFile> outputFiles, Path root) throws IOException { outputsMaterializer.materialize(outputDirectories, outputFiles, root); } }; }
From source file:com.sk89q.worldguard.bukkit.commands.region.MemberCommands.java
@Command(aliases = { "removeowner", "remowner", "ro" }, usage = "<id> <owners...>", flags = "naw:", desc = "Remove an owner to a region", min = 1) public void removeOwner(CommandContext args, CommandSender sender) throws CommandException { warnAboutSaveFailures(sender);//from ww w . j av a2s.c o m World world = checkWorld(args, sender, 'w'); // Get the world String id = args.getString(0); RegionManager manager = checkRegionManager(plugin, world); ProtectedRegion region = checkExistingRegion(manager, id, true); // Check permissions if (!getPermissionModel(sender).mayRemoveOwners(region)) { throw new CommandPermissionsException(); } ListenableFuture<?> future; if (args.hasFlag('a')) { region.getOwners().removeAll(); future = Futures.immediateFuture(null); } else { if (args.argsLength() < 2) { throw new CommandException("List some names to remove, or use -a to remove all."); } // Resolve owners asynchronously DomainInputResolver resolver = new DomainInputResolver(plugin.getProfileService(), args.getParsedPaddedSlice(1, 0)); resolver.setLocatorPolicy( args.hasFlag('n') ? UserLocatorPolicy.NAME_ONLY : UserLocatorPolicy.UUID_AND_NAME); // Then remove it from the owners future = Futures.transform(plugin.getExecutorService().submit(resolver), resolver.createRemoveAllFunction(region.getOwners())); } AsyncCommandHelper.wrap(future, plugin, sender).formatUsing(region.getId(), world.getName()) .registerWithSupervisor("Removing owners from the region '%s' on '%s'") .sendMessageAfterDelay("(Please wait... querying player names...)") .thenRespondWith("Region '%s' updated with owners removed.", "Failed to remove owners"); }
From source file:org.opendaylight.groupbasedpolicy.ui.backend.UiBackendServiceImpl.java
@Override public Future<RpcResult<GetSubjectsBetweenEndpointGroupsOutput>> getSubjectsBetweenEndpointGroups( GetSubjectsBetweenEndpointGroupsInput input) { LOG.trace("getSubjectsBetweenEndpointGroups: {}", input); final TenantId tenantId = input.getTenantId(); if (tenantId == null) { throw new IllegalArgumentException("Missing tenant-Id in RPC input."); }//w ww.ja v a2s .c om final FromOperData fromOperData = input.getFromOperData(); InstanceIdentifier<Tenant> tenantIid = InstanceIdentifier.builder(Tenants.class) .child(Tenant.class, new TenantKey(tenantId)).build(); CheckedFuture<Optional<Tenant>, ReadFailedException> futureTenant; try (ReadOnlyTransaction rTx = dataProvider.newReadOnlyTransaction()) { if (fromOperData == null) { futureTenant = rTx.read(LogicalDatastoreType.CONFIGURATION, tenantIid); } else { futureTenant = rTx.read(LogicalDatastoreType.OPERATIONAL, tenantIid); } } return Futures.transform(futureTenant, new Function<Optional<Tenant>, RpcResult<GetSubjectsBetweenEndpointGroupsOutput>>() { @Override public RpcResult<GetSubjectsBetweenEndpointGroupsOutput> apply( Optional<Tenant> potentialTenant) { GetSubjectsBetweenEndpointGroupsOutputBuilder outputBuilder = new GetSubjectsBetweenEndpointGroupsOutputBuilder(); if (!potentialTenant.isPresent()) { LOG.trace("No tenant with id {} in {} datastore", tenantId.getValue(), fromOperData == null ? LogicalDatastoreType.CONFIGURATION : LogicalDatastoreType.OPERATIONAL); return RpcResultBuilder.success(outputBuilder.build()).build(); } Tenant tenant = potentialTenant.get(); Table<EgKey, EgKey, Policy> resolvedPolicy = PolicyResolverUtils .resolvePolicy(ImmutableSet.of(new IndexedTenant(tenant))); List<EndpointGroupPairWithSubject> epgPairsWithSubjects = new ArrayList<>(); for (Cell<EgKey, EgKey, Policy> policyByConsProvEpg : resolvedPolicy.cellSet()) { Policy policy = policyByConsProvEpg.getValue(); List<RuleGroup> subjects = getUniqueSortedSubjects(policy); List<UiSubject> uiSubjects = new ArrayList<>(); for (RuleGroup subject : subjects) { UiSubject uiSubject = new UiSubjectBuilder().setName(subject.getRelatedSubject()) .setOrder(subject.getOrder()).setUiRule(getUiRules(subject.getRules())) .build(); uiSubjects.add(uiSubject); } EgKey consEgKey = policyByConsProvEpg.getRowKey(); EgKey provEgKey = policyByConsProvEpg.getColumnKey(); LOG.trace( "Resolved policies from {} datastore: \nConsumer EPG: {}\nProvider EPG: {}\nPolicy: {}", fromOperData == null ? LogicalDatastoreType.CONFIGURATION : LogicalDatastoreType.OPERATIONAL, consEgKey, provEgKey, policy); EndpointGroupPairWithSubject epgPairWithSubject = new EndpointGroupPairWithSubjectBuilder() .setConsumerEndpointGroupId(consEgKey.getEgId()) .setConsumerTenantId(consEgKey.getTenantId()) .setProviderEndpointGroupId(provEgKey.getEgId()) .setProviderTenantId(provEgKey.getTenantId()).setUiSubject(uiSubjects).build(); epgPairsWithSubjects.add(epgPairWithSubject); } GetSubjectsBetweenEndpointGroupsOutput result = outputBuilder .setEndpointGroupPairWithSubject(epgPairsWithSubjects).build(); return RpcResultBuilder.success(result).build(); } }); }