1/*
2 * Copyright (C) 2015 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
17package tests.util;
18
19/**
20 * Runner which executes the provided code under test (via a callback) for each provided input
21 * value.
22 */
23public final class ForEachRunner {
24
25  /**
26   * Callback parameterized with a value.
27   */
28  public interface Callback<T> {
29    /**
30     * Invokes the callback for the provided value.
31     */
32    void run(T value) throws Exception;
33  }
34
35  private ForEachRunner() {}
36
37  /**
38   * Invokes the provided callback for each of the provided named values.
39   *
40   * @param namesAndValues named values represented as name-value pairs.
41   *
42   * @param <T> type of value.
43   */
44  public static <T> void runNamed(Callback<T> callback, Iterable<Pair<String, T>> namesAndValues)
45      throws Exception {
46    for (Pair<String, T> nameAndValue : namesAndValues) {
47      try {
48        callback.run(nameAndValue.getSecond());
49      } catch (Throwable e) {
50        throw new Exception("Failed for " + nameAndValue.getFirst() + ": " + e.getMessage(), e);
51      }
52    }
53  }
54}
55