BlockingFind.java

/*
 * Copyright (C) 2017 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package androidx.test.services.shellexecutor;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import androidx.test.services.speakeasy.SpeakEasyProtocol.FindResult;
import androidx.test.services.speakeasy.client.AppAtslConnection;
import androidx.test.services.speakeasy.client.AppConnection;
import androidx.test.services.speakeasy.client.FindResultReceiver;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * Synchronously gets a {@link FindResult} from SpeakEasy
 *
 * @throws InterruptedException if find not successful in 5 seconds.
 */
final class BlockingFind extends FindResultReceiver {

  private static final String TAG = "FindResultReceiver";
  private static final int WAIT_TIME = 30;
  private static final int WAIT_INTERVAL = 5;

  private final CountDownLatch latch;
  private List<FindResult> findResults = new CopyOnWriteArrayList<>();

  private BlockingFind(Handler h) {
    super(h);
    latch = new CountDownLatch(1);
  }

  @Override
  protected void handleFindResult(FindResult findResult) {
    this.findResults.add(findResult);
    if (findResult.found || findResults.size() == 2) {
      // notify as soon as we have found one result, or we have all the results back
      latch.countDown();
    }
  }

  private List<FindResult> waitOnResults() throws InterruptedException {
    int awaitTime = 0;
    while (true) {
      if (latch.await(WAIT_INTERVAL, TimeUnit.SECONDS)) {
        return findResults;
      } else {
        awaitTime += WAIT_INTERVAL;
        if (awaitTime < WAIT_TIME) {
          Log.i(TAG, "Waiting " + awaitTime + " for SpeakEasy find");
        } else {
          throw new InterruptedException(
              "Timed out after " + WAIT_TIME + " seconds while waiting for SpeakEasy find");
        }
      }
    }
  }

  public static FindResult getResult(Looper looper, Context context, String key)
      throws InterruptedException {

    // connect to both android.support.test and androidx.test speakeasy in parallel
    BlockingFind receiver = new BlockingFind(new Handler(looper));
    new AppConnection(context).find(key, receiver);
    new AppAtslConnection(context).find(key, receiver);
    List<FindResult> results = receiver.waitOnResults();
    return getBestResult(results);
  }

  private static FindResult getBestResult(List<FindResult> results) {
    FindResult bestResult = null;
    for (FindResult result : results) {
      if (result.found) {
        bestResult = result;
      } else if (bestResult == null) {
        bestResult = result;
      }
    }
    return bestResult;
  }
}