1 /*
2  * Copyright (C) 2024 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.adservices.utils;
18 
19 import org.json.JSONException;
20 
21 import java.io.IOException;
22 import java.net.URL;
23 import java.util.Random;
24 
25 /** Used to construct {@link ScenarioDispatcher} instances by loading required data. */
26 public class ScenarioDispatcherFactory {
27 
28     private final String mFilePath;
29     private final String mPrefix;
30 
ScenarioDispatcherFactory(String filePath, String prefix)31     private ScenarioDispatcherFactory(String filePath, String prefix) {
32         this.mFilePath = filePath;
33         this.mPrefix = prefix;
34     }
35 
36     /**
37      * Construct a factory for a given scenario file path.
38      *
39      * @param filePath Path to scenario JSON.
40      * @return Factory for constructing {@link ScenarioDispatcher} instances.
41      */
createFromScenarioFile(String filePath)42     public static ScenarioDispatcherFactory createFromScenarioFile(String filePath) {
43         return new ScenarioDispatcherFactory(filePath, "");
44     }
45 
46     /**
47      * Construct a factory for a given scenario file path (and add a random prefix).
48      *
49      * @param filePath Path to scenario JSON.
50      * @return Factory for constructing {@link ScenarioDispatcher} instances.
51      */
createFromScenarioFileWithRandomPrefix( String filePath)52     public static ScenarioDispatcherFactory createFromScenarioFileWithRandomPrefix(
53             String filePath) {
54         Random random = new Random();
55         String prefix = "/" + random.nextInt();
56         return new ScenarioDispatcherFactory(filePath, prefix);
57     }
58 
59     /**
60      * Construct a valid dispatcher.
61      *
62      * @param serverBaseAddress Base URL of the MockWebServer being used
63      * @return A valid interface implementing {@link com.squareup.okhttp.Dispatcher}
64      * @throws JSONException if the scenario JSON was not able to parse correctly.
65      * @throws IOException if the scenario file was not able to load correctly.
66      */
getDispatcher(URL serverBaseAddress)67     public ScenarioDispatcher getDispatcher(URL serverBaseAddress)
68             throws JSONException, IOException {
69         return new ScenarioDispatcher(mFilePath, mPrefix, serverBaseAddress);
70     }
71 }
72