1 /* 2 * Copyright (C) 2017 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.accessibilityservice.cts.utils; 18 19 import static android.accessibilityservice.cts.utils.CtsTestUtils.assertThrows; 20 21 import static java.util.concurrent.TimeUnit.MILLISECONDS; 22 23 import com.android.compatibility.common.util.TestUtils; 24 25 import java.util.concurrent.CancellationException; 26 import java.util.concurrent.Future; 27 import java.util.concurrent.TimeUnit; 28 import java.util.function.BooleanSupplier; 29 30 public class AsyncUtils { 31 public static final long DEFAULT_TIMEOUT_MS = 5000; 32 33 private AsyncUtils() {} 34 35 public static <T> T await(Future<T> f) { 36 return await(f, DEFAULT_TIMEOUT_MS, MILLISECONDS); 37 } 38 39 public static <T> T await(Future<T> f, long time, TimeUnit timeUnit) { 40 try { 41 return f.get(time, timeUnit); 42 } catch (Exception e) { 43 throw new RuntimeException(e); 44 } 45 } 46 47 public static Throwable awaitFailure(Future<?> f) { 48 return awaitFailure(f, DEFAULT_TIMEOUT_MS, MILLISECONDS); 49 } 50 51 public static Throwable awaitFailure(Future<?> f, long time, TimeUnit timeUnit) { 52 return assertThrows(() -> await(f, time, timeUnit)); 53 } 54 55 public static <T> CancellationException awaitCancellation(Future<T> f) { 56 return awaitCancellation(f, DEFAULT_TIMEOUT_MS, MILLISECONDS); 57 } 58 59 public static <T> CancellationException awaitCancellation( 60 Future<T> f, long time, TimeUnit timeUnit) { 61 Throwable ex = awaitFailure(f, time, timeUnit); 62 Throwable current = ex; 63 while (current != null) { 64 if (current instanceof CancellationException) { 65 return (CancellationException) current; 66 } 67 current = current.getCause(); 68 } 69 throw new AssertionError("Expected cancellation", ex); 70 } 71 72 public static void waitOn(Object notifyLock, BooleanSupplier condition) { 73 TestUtils.waitOn(notifyLock, condition, DEFAULT_TIMEOUT_MS, null); 74 } 75 } 76