1 /*
2  * Copyright (C) 2020 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 com.android.tradefed.config.proxy;
17 
18 import com.android.tradefed.config.ConfigurationException;
19 import com.android.tradefed.config.Option;
20 import com.android.tradefed.log.LogUtil.CLog;
21 
22 import java.io.File;
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.List;
26 
27 /** Object that allows pointing to a remote configuration to execute. */
28 public final class ProxyConfiguration {
29 
30     public static final String PROXY_CONFIG_TYPE_KEY = "proxy-config";
31     private static final String PROXY_CONFIG_OPTION_NAME = "proxy-configuration";
32 
33     @Option(
34             name = PROXY_CONFIG_OPTION_NAME,
35             description = "Point to an external configuration to be run instead.")
36     private File mProxyConfig;
37 
38     /** Returns whether or not a proxy config value is set. */
isProxySet()39     public boolean isProxySet() {
40         return mProxyConfig != null;
41     }
42 
43     /** Returns the current proxy configuration to use. */
getProxyConfig()44     public File getProxyConfig() {
45         if (mProxyConfig == null || !mProxyConfig.exists()) {
46             CLog.e("No proxy configuration is configured: %s", mProxyConfig);
47             return null;
48         }
49         if (mProxyConfig.isDirectory()) {
50             CLog.e("Proxy configuration must be a file, found a directory: %s", mProxyConfig);
51             return null;
52         }
53         return mProxyConfig;
54     }
55 
clearCommandline(String[] originalCommand)56     public static String[] clearCommandline(String[] originalCommand)
57             throws ConfigurationException {
58         List<String> argsList = new ArrayList<>(Arrays.asList(originalCommand));
59         try {
60             while (argsList.contains("--" + PROXY_CONFIG_OPTION_NAME)) {
61                 int index = argsList.indexOf("--" + PROXY_CONFIG_OPTION_NAME);
62                 if (index != -1) {
63                     argsList.remove(index + 1);
64                     argsList.remove(index);
65                 }
66             }
67         } catch (RuntimeException e) {
68             throw new ConfigurationException(e.getMessage(), e);
69         }
70         return argsList.toArray(new String[0]);
71     }
72 }
73