Home | History | Annotate | Download | only in util
      1 /*
      2  * Copyright (C) 2012 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.cts.util;
     18 
     19 import java.util.concurrent.Callable;
     20 
     21 import junit.framework.Assert;
     22 
     23 public abstract class PollingCheck {
     24     private static final long TIME_SLICE = 50;
     25     private long mTimeout = 3000;
     26 
     27     public static interface PollingCheckCondition {
     28         boolean canProceed();
     29     }
     30 
     31     public PollingCheck() {
     32     }
     33 
     34     public PollingCheck(long timeout) {
     35         mTimeout = timeout;
     36     }
     37 
     38     protected abstract boolean check();
     39 
     40     public void run() {
     41         if (check()) {
     42             return;
     43         }
     44 
     45         long timeout = mTimeout;
     46         while (timeout > 0) {
     47             try {
     48                 Thread.sleep(TIME_SLICE);
     49             } catch (InterruptedException e) {
     50                 Assert.fail("unexpected InterruptedException");
     51             }
     52 
     53             if (check()) {
     54                 return;
     55             }
     56 
     57             timeout -= TIME_SLICE;
     58         }
     59 
     60         Assert.fail("unexpected timeout");
     61     }
     62 
     63     public static void check(CharSequence message, long timeout, Callable<Boolean> condition)
     64             throws Exception {
     65         while (timeout > 0) {
     66             if (condition.call()) {
     67                 return;
     68             }
     69 
     70             Thread.sleep(TIME_SLICE);
     71             timeout -= TIME_SLICE;
     72         }
     73 
     74         Assert.fail(message.toString());
     75     }
     76 
     77     public static void waitFor(final PollingCheckCondition condition) {
     78         new PollingCheck() {
     79             @Override
     80             protected boolean check() {
     81                 return condition.canProceed();
     82             }
     83         }.run();
     84     }
     85 }
     86