1 /* 2 * Copyright (C) 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.car.testapi; 18 19 import android.annotation.NonNull; 20 import android.car.util.concurrent.AsyncFuture; 21 22 import java.util.concurrent.ExecutionException; 23 import java.util.concurrent.TimeUnit; 24 import java.util.concurrent.TimeoutException; 25 26 /** 27 * Provides common helpers for generic car-related classes. 28 */ 29 public final class CarTestingHelper { 30 31 private static final long ASYNC_TIMEOUT_MS = 500; 32 33 /** 34 * Gets the result of a future, or throw a {@link IllegalStateException} if it times out after 35 * {@value #ASYNC_TIMEOUT_MS} ms. 36 */ 37 @NonNull getResult(@onNull AsyncFuture<T> future)38 public static <T> T getResult(@NonNull AsyncFuture<T> future) 39 throws InterruptedException, ExecutionException { 40 return getResult(future, ASYNC_TIMEOUT_MS); 41 } 42 43 /** 44 * Gets the result of a future, or throw a {@link IllegalStateException} if it times out. 45 */ 46 @NonNull getResult(@onNull AsyncFuture<T> future, long timeoutMs)47 public static <T> T getResult(@NonNull AsyncFuture<T> future, long timeoutMs) { 48 try { 49 return future.get(timeoutMs, TimeUnit.MILLISECONDS); 50 } catch (InterruptedException e) { 51 Thread.currentThread().interrupt(); 52 throw new IllegalStateException("future interrupted", e); 53 } catch (TimeoutException e) { 54 throw new IllegalStateException("future not called in " + ASYNC_TIMEOUT_MS + "ms", e); 55 } catch (ExecutionException e) { 56 throw new IllegalStateException("failed to get future", e); 57 } 58 } 59 CarTestingHelper()60 private CarTestingHelper() { 61 throw new UnsupportedOperationException("contains only static methods"); 62 } 63 64 } 65