Java Code Examples for com.google.common.util.concurrent.Futures#transformAsync()
The following examples show how to use
com.google.common.util.concurrent.Futures#transformAsync() .
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: Stateful07TopologySessionListener.java From bgpcep with Eclipse Public License 1.0 | 6 votes |
@Override @SuppressFBWarnings(value = "NP_NULL_ON_SOME_PATH", justification = "SB does not grok TYPE_USE") public synchronized ListenableFuture<OperationResult> removeLsp(final RemoveLspArgs input) { checkArgument(input != null && input.getName() != null && input.getNode() != null, MISSING_XML_TAG); LOG.trace("RemoveLspArgs {}", input); // Make sure the LSP exists, we need it for PLSP-ID final InstanceIdentifier<ReportedLsp> lsp = lspIdentifier(input.getName()); final ListenableFuture<Optional<ReportedLsp>> f = readOperationalData(lsp); return f == null ? OperationResults.createUnsent(PCEPErrors.LSP_INTERNAL_ERROR).future() : Futures.transformAsync(f, rep -> { final Lsp reportedLsp = validateReportedLsp(rep, input); if (reportedLsp == null) { return OperationResults.createUnsent(PCEPErrors.UNKNOWN_PLSP_ID).future(); } final PcinitiateMessageBuilder ib = new PcinitiateMessageBuilder(MESSAGE_HEADER); final Requests rb = buildRequest(rep, reportedLsp); ib.setRequests(Collections.singletonList(rb)); return sendMessage(new PcinitiateBuilder().setPcinitiateMessage(ib.build()).build(), rb.getSrp().getOperationId(), null); }, MoreExecutors.directExecutor()); }
Example 2
Source File: DiskCacheClient.java From bazel with Apache License 2.0 | 6 votes |
@Override public ListenableFuture<Void> downloadBlob(Digest digest, OutputStream out) { @Nullable HashingOutputStream hashOut = verifyDownloads ? digestUtil.newHashingOutputStream(out) : null; return Futures.transformAsync( download(digest, hashOut != null ? hashOut : out, /* isActionCache= */ false), (v) -> { try { if (hashOut != null) { Utils.verifyBlobContents( digest.getHash(), DigestUtil.hashCodeToString(hashOut.hash())); } out.flush(); return Futures.immediateFuture(null); } catch (IOException e) { return Futures.immediateFailedFuture(e); } }, MoreExecutors.directExecutor()); }
Example 3
Source File: WebRTCWrapper.java From Conversations with GNU General Public License v3.0 | 6 votes |
ListenableFuture<Void> setLocalDescription(final SessionDescription sessionDescription) { Log.d(EXTENDED_LOGGING_TAG, "setting local description:"); for (final String line : sessionDescription.description.split(eu.siacs.conversations.xmpp.jingle.SessionDescription.LINE_DIVIDER)) { Log.d(EXTENDED_LOGGING_TAG, line); } return Futures.transformAsync(getPeerConnectionFuture(), peerConnection -> { final SettableFuture<Void> future = SettableFuture.create(); peerConnection.setLocalDescription(new SetSdpObserver() { @Override public void onSetSuccess() { future.set(null); } @Override public void onSetFailure(final String s) { future.setException(new IllegalArgumentException("unable to set local session description: " + s)); } }, sessionDescription); return future; }, MoreExecutors.directExecutor()); }
Example 4
Source File: WebRTCWrapper.java From Conversations with GNU General Public License v3.0 | 6 votes |
ListenableFuture<Void> setRemoteDescription(final SessionDescription sessionDescription) { Log.d(EXTENDED_LOGGING_TAG, "setting remote description:"); for (final String line : sessionDescription.description.split(eu.siacs.conversations.xmpp.jingle.SessionDescription.LINE_DIVIDER)) { Log.d(EXTENDED_LOGGING_TAG, line); } return Futures.transformAsync(getPeerConnectionFuture(), peerConnection -> { final SettableFuture<Void> future = SettableFuture.create(); peerConnection.setRemoteDescription(new SetSdpObserver() { @Override public void onSetSuccess() { future.set(null); } @Override public void onSetFailure(String s) { future.setException(new IllegalArgumentException("unable to set remote session description: " + s)); } }, sessionDescription); return future; }, MoreExecutors.directExecutor()); }
Example 5
Source File: DeviceServiceImpl.java From Groza with Apache License 2.0 | 6 votes |
@Override public ListenableFuture<List<Device>> findDevicesByQuery(DeviceSearchQuery query) { ListenableFuture<List<EntityRelation>> relations = relationService.findByQuery(query.toEntitySearchQuery()); ListenableFuture<List<Device>> devices = Futures.transformAsync(relations, r -> { EntitySearchDirection direction = query.toEntitySearchQuery().getParameters().getDirection(); List<ListenableFuture<Device>> futures = new ArrayList<>(); for (EntityRelation relation : r) { EntityId entityId = direction == EntitySearchDirection.FROM ? relation.getTo() : relation.getFrom(); if (entityId.getEntityType() == EntityType.DEVICE) { futures.add(findDeviceByIdAsync(new DeviceId(entityId.getId()))); } } return Futures.successfulAsList(futures); }); devices = Futures.transform(devices, new Function<List<Device>, List<Device>>() { @Nullable @Override public List<Device> apply(@Nullable List<Device> deviceList) { return deviceList == null ? Collections.emptyList() : deviceList.stream().filter(device -> query.getDeviceTypes().contains(device.getType())).collect(Collectors.toList()); } }); return devices; }
Example 6
Source File: BuildCacheArtifactFetcher.java From buck with Apache License 2.0 | 6 votes |
/** * Converts a failed {@code ListenableFuture<CacheResult>} to a {@code CacheResult} error. Then * logs all {@code CacheResult} of type {@code CacheResultType.ERROR}. Returns a {@code * ListenableFuture<CacheResult>} without an Exception. * * @param cacheResultListenableFuture ListenableFuture input * @param ruleKey rule key associated with that cache result * @return a ListenableFuture that holds a CacheResult without Exception */ protected ListenableFuture<CacheResult> convertErrorToSoftError( ListenableFuture<CacheResult> cacheResultListenableFuture, RuleKey ruleKey) { return Futures.transformAsync( Futures.catchingAsync( cacheResultListenableFuture, Exception.class, e -> Futures.immediateFuture( CacheResult.softError( "fetch_cache_artifact_exception", ArtifactCacheMode.unknown, Throwables.getStackTraceAsString(e))), executorService), cacheResult -> { if (cacheResult.getType() == CacheResultType.ERROR || cacheResult.getType() == CacheResultType.SOFT_ERROR) { LOG.warn( "Cache error from fetching artifact with rule key [%s]: %s", ruleKey, cacheResult.cacheError().get()); } return Futures.immediateFuture(cacheResult); }, executorService); }
Example 7
Source File: WebRTCWrapper.java From Conversations with GNU General Public License v3.0 | 6 votes |
ListenableFuture<SessionDescription> createOffer() { return Futures.transformAsync(getPeerConnectionFuture(), peerConnection -> { final SettableFuture<SessionDescription> future = SettableFuture.create(); peerConnection.createOffer(new CreateSdpObserver() { @Override public void onCreateSuccess(SessionDescription sessionDescription) { future.set(sessionDescription); } @Override public void onCreateFailure(String s) { future.setException(new IllegalStateException("Unable to create offer: " + s)); } }, new MediaConstraints()); return future; }, MoreExecutors.directExecutor()); }
Example 8
Source File: DatastoreImpl.java From async-datastore-client with Apache License 2.0 | 6 votes |
@Override public ListenableFuture<QueryResult> executeAsync(final List<KeyQuery> statements, final ListenableFuture<TransactionResult> txn) { final ListenableFuture<Response> httpResponse = Futures.transformAsync(txn, result -> { final List<com.google.datastore.v1.Key> keys = statements .stream().map(s -> s.getKey().getPb(config.getNamespace())).collect(Collectors.toList()); final LookupRequest.Builder request = LookupRequest.newBuilder().addAllKeys(keys); final ByteString transaction = result.getTransaction(); if (transaction != null) { request.setReadOptions(ReadOptions.newBuilder().setTransaction(transaction)); } final ProtoHttpContent payload = new ProtoHttpContent(request.build()); return ListenableFutureAdapter.asGuavaFuture(prepareRequest("lookup", payload).execute()); }, MoreExecutors.directExecutor()); return Futures.transformAsync(httpResponse, response -> { if (!isSuccessful(response.getStatusCode())) { throw new DatastoreException(response.getStatusCode(), response.getResponseBody()); } final LookupResponse query = LookupResponse.parseFrom(streamResponse(response)); return Futures.immediateFuture(QueryResult.build(query)); }, MoreExecutors.directExecutor()); }
Example 9
Source File: MultipleJavaClassesTestContextProvider.java From intellij with Apache License 2.0 | 6 votes |
/** * Returns a {@link RunConfigurationContext} future setting up the relevant test target pattern, * if one can be found. */ @Nullable private static ListenableFuture<TargetInfo> getTargetContext(PsiDirectory dir) { Project project = dir.getProject(); ProjectFileIndex index = ProjectFileIndex.SERVICE.getInstance(project); if (!index.isInTestSourceContent(dir.getVirtualFile())) { return null; } if (BlazePackage.isBlazePackage(dir)) { // this case is handled by a separate run config producer return null; } ListenableFuture<Set<PsiClass>> classes = findAllTestClassesBeneathDirectory(dir); if (classes == null) { return null; } return Futures.transformAsync( classes, set -> set == null ? null : ReadAction.compute(() -> getTestTargetIfUnique(project, set)), EXECUTOR); }
Example 10
Source File: FindRecipeGraph.java From curiostack with MIT License | 5 votes |
@Produces static ListenableFuture<Recipe> recipe( List<String> ingredients, SearchResponse searchResponse, Supplier<Random> randomSupplier, YummlyApi yummly) { int totalCount = searchResponse.totalMatchCount(); ListenableFuture<SearchResponse> future = Futures.immediateFuture(null); // Get a random recipe to return. Search request fails randomly so try a few times. Executor executor = RequestContext.current().contextAwareEventLoop(); Random random = randomSupplier.get(); for (int i = 0; i < 5; i++) { int resultIndex = random.nextInt(totalCount); future = Futures.transformAsync( future, result -> { if (result != null && !result.matches().isEmpty()) { return Futures.immediateFuture(result); } return yummly.search( EggworldConstants.EGG_QUERY, ingredients, resultIndex, 1, true, ImmutableList.of()); }, executor); } return Futures.transform(future, r -> r.matches().get(0), MoreExecutors.directExecutor()); }
Example 11
Source File: BaseAlarmService.java From Groza with Apache License 2.0 | 5 votes |
@Override public ListenableFuture<AlarmInfo> findAlarmInfoByIdAsync(AlarmId alarmId) { log.trace("Executing findAlarmInfoByIdAsync [{}]", alarmId); validateId(alarmId, "Incorrect alarmId " + alarmId); return Futures.transformAsync(alarmDao.findAlarmByIdAsync(alarmId.getId()), a -> { AlarmInfo alarmInfo = new AlarmInfo(a); return Futures.transform( entityService.fetchEntityNameAsync(alarmInfo.getOriginator()), originatorName -> { alarmInfo.setOriginatorName(originatorName); return alarmInfo; } ); }); }
Example 12
Source File: Stateful07TopologySessionListener.java From bgpcep with Eclipse Public License 1.0 | 5 votes |
private ListenableFuture<OperationResult> triggerLspSyncronization(final TriggerSyncArgs input) { LOG.trace("Trigger Lsp Resynchronization {}", input); // Make sure the LSP exists final InstanceIdentifier<ReportedLsp> lsp = lspIdentifier(input.getName()); final FluentFuture<Optional<ReportedLsp>> f = readOperationalData(lsp); if (f == null) { return OperationResults.createUnsent(PCEPErrors.LSP_INTERNAL_ERROR).future(); } return Futures.transformAsync(f, new ResyncLspFunction(input), MoreExecutors.directExecutor()); }
Example 13
Source File: MoreFutures.java From more-lambdas-java with Artistic License 2.0 | 5 votes |
public static <I, O> ListenableFuture<O> transformAsync(ListenableFuture<I> input, AsyncFunction<? super I, ? extends O> function, Executor executor) { ListenableFuture<O> result = Futures.transformAsync(input, function, executor); if (input instanceof TimeoutListenableFuture) { TimeoutListenableFuture<O> newResult = new TimeoutListenableFuture<>(result); for (ThrowableConsumer<TimeoutException, Exception> timeoutListener : ((TimeoutListenableFuture<I>) input) .getTimeoutListeners()) { newResult.addTimeoutListener(timeoutListener); } return newResult; } else { return result; } }
Example 14
Source File: QueryRepository.java From lttrs-android with Apache License 2.0 | 5 votes |
public void refresh(final EmailQuery emailQuery) { final String queryString = emailQuery.toQueryString(); synchronized (this) { if (!runningQueries.add(queryString)) { Log.d("lttrs", "skipping refresh since already running"); return; } if (runningPagingRequests.contains(queryString)) { //even though this refresh call is only implicit through the pageRequest we want to display something nice for the user runningQueries.add(queryString); runningQueriesLiveData.postValue(runningQueries); Log.d("lttrs", "skipping refresh since we are running a page request"); return; } } final ListenableFuture<Status> statusFuture = Futures.transformAsync(mua, mua -> mua.query(emailQuery), MoreExecutors.directExecutor()); statusFuture.addListener(() -> { synchronized (runningQueries) { runningQueries.remove(queryString); } runningQueriesLiveData.postValue(runningQueries); try { Status status = statusFuture.get(); } catch (Exception e) { Log.d("lttrs", "unable to refresh", e); } }, MoreExecutors.directExecutor()); }
Example 15
Source File: ByteStreamUploader.java From bazel with Apache License 2.0 | 5 votes |
private ListenableFuture<Void> query( AtomicLong committedOffset, ProgressiveBackoff progressiveBackoff) { ListenableFuture<Long> committedSizeFuture = Futures.transform( bsFutureStub() .queryWriteStatus( QueryWriteStatusRequest.newBuilder().setResourceName(resourceName).build()), (response) -> response.getCommittedSize(), MoreExecutors.directExecutor()); ListenableFuture<Long> guardedCommittedSizeFuture = Futures.catchingAsync( committedSizeFuture, Exception.class, (e) -> { Status status = Status.fromThrowable(e); if (status.getCode() == Code.UNIMPLEMENTED) { // if the bytestream server does not implement the query, insist // that we should reset the upload return Futures.immediateFuture(0L); } return Futures.immediateFailedFuture(e); }, MoreExecutors.directExecutor()); return Futures.transformAsync( guardedCommittedSizeFuture, (committedSize) -> { if (committedSize > committedOffset.get()) { // we have made progress on this upload in the last request, // reset the backoff so that this request has a full deck of retries progressiveBackoff.reset(); } committedOffset.set(committedSize); return Futures.immediateFuture(null); }, MoreExecutors.directExecutor()); }
Example 16
Source File: Session.java From glowroot with Apache License 2.0 | 5 votes |
public ListenableFuture<ResultSet> readAsyncFailIfNoRows(Statement statement, String errorMessage) throws Exception { return Futures.transformAsync(readAsync(statement), new AsyncFunction<ResultSet, ResultSet>() { @Override public ListenableFuture<ResultSet> apply(ResultSet results) { if (results.isExhausted()) { return Futures.immediateFailedFuture(new Exception(errorMessage)); } else { return Futures.immediateFuture(results); } } }, MoreExecutors.directExecutor()); }
Example 17
Source File: ElasticSearchRefresh.java From metacat with Apache License 2.0 | 4 votes |
/** * Process the list of databases. * * @param catalogName catalog name * @param databaseNames database names * @return future */ @SuppressWarnings("checkstyle:methodname") private ListenableFuture<Void> _processDatabases(final QualifiedName catalogName, final List<QualifiedName> databaseNames) { ListenableFuture<Void> resultFuture = null; log.info("Full refresh of catalog {} for databases({}): {}", catalogName, databaseNames.size(), databaseNames); final List<ListenableFuture<DatabaseDto>> getDatabaseFutures = databaseNames.stream() .map(databaseName -> service.submit(() -> { DatabaseDto result = null; try { result = getDatabase(databaseName); } catch (Exception e) { log.error("Failed to retrieve database: {}", databaseName); elasticSearchUtil.log("ElasticSearchRefresh.getDatabase", ElasticSearchDoc.Type.database.name(), databaseName.toString(), null, e.getMessage(), e, true); } return result; })) .collect(Collectors.toList()); if (getDatabaseFutures != null && !getDatabaseFutures.isEmpty()) { resultFuture = Futures.transformAsync(Futures.successfulAsList(getDatabaseFutures), input -> { final ListenableFuture<Void> processDatabaseFuture = indexDatabaseDtos(catalogName, input); final List<ListenableFuture<Void>> processDatabaseFutures = input.stream().filter(NOT_NULL) .map(databaseDto -> { final List<QualifiedName> tableNames = databaseDto.getTables().stream() .map(s -> QualifiedName.ofTable(databaseDto.getName().getCatalogName(), databaseDto.getName().getDatabaseName(), s)) .collect(Collectors.toList()); log.info("Full refresh of database {} for tables({}): {}", databaseDto.getName(), databaseDto.getTables().size(), databaseDto.getTables()); return processTables(databaseDto.getName(), tableNames); }).filter(NOT_NULL).collect(Collectors.toList()); processDatabaseFutures.add(processDatabaseFuture); return Futures.transform(Futures.successfulAsList(processDatabaseFutures), Functions.constant(null), defaultService); }, defaultService); } return resultFuture; }
Example 18
Source File: PinActivity.java From GreenBits with GNU General Public License v3.0 | 4 votes |
private void setUpLogin(final String pin, final Runnable onFailureFn) { final AsyncFunction<Void, LoginData> connectToLogin = new AsyncFunction<Void, LoginData>() { @Override public ListenableFuture<LoginData> apply(final Void input) throws Exception { return mService.pinLogin(pin); } }; final ListenableFuture<LoginData> loginFuture; loginFuture = Futures.transformAsync(mService.onConnected, connectToLogin, mService.getExecutor()); Futures.addCallback(loginFuture, new FutureCallback<LoginData>() { @Override public void onSuccess(final LoginData result) { mService.cfgEdit("pin").putInt("counter", 0).apply(); if (getCallingActivity() == null) { onLoginSuccess(); return; } setResult(RESULT_OK); finishOnUiThread(); } @Override public void onFailure(final Throwable t) { final String message; final SharedPreferences prefs = mService.cfg("pin"); final int counter = prefs.getInt("counter", 0) + 1; final Throwable error; if (t instanceof GAException || Throwables.getRootCause(t) instanceof LoginFailed) { final SharedPreferences.Editor editor = prefs.edit(); if (counter < 3) { editor.putInt("counter", counter); message = getString(R.string.attemptsLeftLong, 3 - counter); } else { message = getString(R.string.attemptsFinished); editor.clear(); } editor.apply(); error = null; } else { error = t; message = null; } PinActivity.this.runOnUiThread(new Runnable() { public void run() { if (error != null) PinActivity.this.toast(error); else PinActivity.this.toast(message); if (counter >= 3) { startActivity(new Intent(PinActivity.this, FirstScreenActivity.class)); finish(); return; } if (onFailureFn != null) onFailureFn.run(); } }); } }, mService.getExecutor()); }
Example 19
Source File: MnemonicActivity.java From GreenBits with GNU General Public License v3.0 | 4 votes |
private void doLogin() { final String mnemonic = getMnemonic(); setMnemonic(mnemonic); // Trim mnemonic when OK pressed if (mOkButton.isLoading()) return; if (mService.isLoggedIn()) { toast(R.string.err_mnemonic_activity_logout_required); return; } if (!mService.isConnected()) { toast(R.string.err_send_not_connected_will_resume); return; } final String words[] = mnemonic.split(" "); if (words.length != 24 && words.length != 27) { toast(R.string.err_mnemonic_activity_invalid_mnemonic); return; } int start = 0; for (final String word : words) { final int end = start + word.length(); if (!MnemonicHelper.mWords.contains(word)) { promptToFixInvalidWord(word, start, end); return; } start = end + 1; } try { Wally.bip39_mnemonic_validate(Wally.bip39_get_wordlist("en"), mnemonic); } catch (final IllegalArgumentException e) { toast(R.string.err_mnemonic_activity_invalid_mnemonic); // FIXME: Use different error message return; } mOkButton.startLoading();; mMnemonicText.setEnabled(false); hideKeyboardFrom(mMnemonicText); final AsyncFunction<Void, LoginData> connectToLogin = new AsyncFunction<Void, LoginData>() { @Override public ListenableFuture<LoginData> apply(final Void input) { if (words.length != 27) return mService.login(mnemonic); // Encrypted mnemonic return Futures.transformAsync(askForPassphrase(), new AsyncFunction<String, LoginData>() { @Override public ListenableFuture<LoginData> apply(final String passphrase) { return mService.login(CryptoHelper.decrypt_mnemonic(mnemonic, passphrase)); } }); } }; final ListenableFuture<LoginData> loginFuture; loginFuture = Futures.transformAsync(mService.onConnected, connectToLogin, mService.getExecutor()); Futures.addCallback(loginFuture, new FutureCallback<LoginData>() { @Override public void onSuccess(final LoginData result) { if (getCallingActivity() == null) { final Intent savePin = PinSaveActivity.createIntent(MnemonicActivity.this, mService.getMnemonic()); startActivityForResult(savePin, PINSAVE); } else { setResult(RESULT_OK); finishOnUiThread(); } } @Override public void onFailure(final Throwable t) { final boolean accountDoesntExist = t instanceof ClassCastException; final String message = accountDoesntExist ? "Account doesn't exist" : "Login failed"; t.printStackTrace(); MnemonicActivity.this.runOnUiThread(new Runnable() { public void run() { MnemonicActivity.this.toast(message); enableLogin(); } }); } }, mService.getExecutor()); }
Example 20
Source File: AbstractQueue.java From qpid-broker-j with Apache License 2.0 | 4 votes |
@Override public ListenableFuture<Integer> deleteAndReturnCountAsync() { return Futures.transformAsync(deleteAsync(), v -> _deleteQueueDepthFuture, getTaskExecutor()); }