Remi NGUYEN VAN | 9671ec4 | 2021-02-04 16:57:19 +0900 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2021 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 com.android.testutils |
| 18 | |
| 19 | import android.net.NetworkSpecifier |
| 20 | import android.os.Build |
| 21 | |
| 22 | /** |
| 23 | * Test utility to create [NetworkSpecifier]s on different SDK versions. |
| 24 | */ |
| 25 | object CompatUtil { |
| 26 | @JvmStatic |
| 27 | fun makeTestNetworkSpecifier(ifName: String): NetworkSpecifier { |
| 28 | // Until R, there was no TestNetworkSpecifier, StringNetworkSpecifier was used instead |
| 29 | if (isDevSdkInRange(minExclusive = null, maxInclusive = Build.VERSION_CODES.R)) { |
| 30 | makeNetworkSpecifierInternal("android.net.StringNetworkSpecifier", ifName) |
| 31 | } |
| 32 | // TestNetworkSpecifier is not part of the SDK in some branches using this utility |
| 33 | // TODO: replace with a direct call to the constructor |
| 34 | return makeNetworkSpecifierInternal("android.net.TestNetworkSpecifier", ifName) |
| 35 | } |
| 36 | |
| 37 | @JvmStatic |
| 38 | fun makeEthernetNetworkSpecifier(ifName: String): NetworkSpecifier { |
| 39 | // Until R, there was no EthernetNetworkSpecifier, StringNetworkSpecifier was used instead |
| 40 | if (isDevSdkInRange(minExclusive = null, maxInclusive = Build.VERSION_CODES.R)) { |
| 41 | makeNetworkSpecifierInternal("android.net.StringNetworkSpecifier", ifName) |
| 42 | } |
| 43 | // EthernetNetworkSpecifier is not part of the SDK in some branches using this utility |
| 44 | // TODO: replace with a direct call to the constructor |
| 45 | return makeNetworkSpecifierInternal("android.net.EthernetNetworkSpecifier", ifName) |
| 46 | } |
| 47 | |
| 48 | private fun makeNetworkSpecifierInternal(clazz: String, specifier: String): NetworkSpecifier { |
| 49 | // StringNetworkSpecifier was removed after R (and was hidden API before that) |
| 50 | return Class.forName(clazz) |
| 51 | .getConstructor(String::class.java).newInstance(specifier) as NetworkSpecifier |
| 52 | } |
| 53 | } |