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