Debian Codegraph @

tools/protologtool/src/com/android/protolog/tool/ProtoLogGroupReader.kt

raw
1 /*
2 * Copyright (C) 2019 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.protolog.tool
18
19 import com.android.protolog.tool.Constants.ENUM_VALUES_METHOD
20 import com.android.internal.protolog.common.IProtoLogGroup
21 import java.io.File
22 import java.net.URLClassLoader
23
24 class ProtoLogGroupReader {
25 private fun getClassloaderForJar(jarPath: String): ClassLoader {
26 val jarFile = File(jarPath)
27 val url = jarFile.toURI().toURL()
28 return URLClassLoader(arrayOf(url), ProtoLogGroupReader::class.java.classLoader)
29 }
30
31 private fun getEnumValues(clazz: Class<*>): List<IProtoLogGroup> {
32 val valuesMethod = clazz.getMethod(ENUM_VALUES_METHOD)
33 @Suppress("UNCHECKED_CAST")
34 return (valuesMethod.invoke(null) as Array<IProtoLogGroup>).toList()
35 }
36
37 fun loadFromJar(jarPath: String, className: String): Map<String, LogGroup> {
38 try {
39 val classLoader = getClassloaderForJar(jarPath)
40 val clazz = classLoader.loadClass(className)
41 val values = getEnumValues(clazz)
42 return values.map { group ->
43 group.name() to
44 LogGroup(group.name(), group.isEnabled, group.isLogToLogcat, group.tag)
45 }.toMap()
46 } catch (ex: ReflectiveOperationException) {
47 throw RuntimeException("Unable to load ProtoLogGroup enum class", ex)
48 }
49 }
50 }