1 /* 2 * Copyright 2020 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package android.app.appsearch.testutil; 18 19 import android.annotation.NonNull; 20 import android.app.appsearch.AppSearchResult; 21 import android.app.appsearch.SearchResult; 22 import android.app.appsearch.SearchResults; 23 import android.app.appsearch.SearchResultsShim; 24 import android.app.appsearch.exceptions.AppSearchException; 25 26 import com.google.common.util.concurrent.Futures; 27 import com.google.common.util.concurrent.ListenableFuture; 28 import com.google.common.util.concurrent.SettableFuture; 29 30 import java.util.List; 31 import java.util.Objects; 32 import java.util.concurrent.Executor; 33 34 /** 35 * This test class adapts the AppSearch Framework API to ListenableFuture, so it can be tested via 36 * a consistent interface. 37 * @hide 38 */ 39 public class SearchResultsShimImpl implements SearchResultsShim { 40 private final Executor mExecutor; 41 private final SearchResults mSearchResults; 42 SearchResultsShimImpl(@onNull SearchResults searchResults, @NonNull Executor executor)43 SearchResultsShimImpl(@NonNull SearchResults searchResults, @NonNull Executor executor) { 44 mExecutor = Objects.requireNonNull(executor); 45 mSearchResults = Objects.requireNonNull(searchResults); 46 } 47 48 /** 49 * Retrieves the next page of {@link SearchResult} objects. 50 */ 51 @NonNull getNextPageAsync()52 public ListenableFuture<List<SearchResult>> getNextPageAsync() { 53 SettableFuture<AppSearchResult<List<SearchResult>>> future = SettableFuture.create(); 54 mSearchResults.getNextPage(mExecutor, future::set); 55 return Futures.transformAsync(future, this::transformResult, mExecutor); 56 } 57 58 @Override close()59 public void close() { 60 mSearchResults.close(); 61 } 62 transformResult( @onNull AppSearchResult<T> result)63 private <T> ListenableFuture<T> transformResult( 64 @NonNull AppSearchResult<T> result) throws AppSearchException { 65 if (!result.isSuccess()) { 66 throw new AppSearchException(result.getResultCode(), result.getErrorMessage()); 67 } 68 return Futures.immediateFuture(result.getResultValue()); 69 } 70 } 71