• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2025 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.dependencymapper;
17 
18 import org.objectweb.asm.ClassReader;
19 
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.nio.file.Path;
23 import java.util.ArrayList;
24 import java.util.Enumeration;
25 import java.util.List;
26 import java.util.jar.JarEntry;
27 import java.util.jar.JarFile;
28 
29 /**
30  * An utility class that reads each class file present in the classes jar, then analyzes the same,
31  * collecting the dependencies in {@link List<ClassDependencyData>}
32  */
33 public class ClassDependencyAnalyzer {
34 
analyze(Path classJar, ClassRelevancyFilter classFilter)35     public static List<ClassDependencyData> analyze(Path classJar, ClassRelevancyFilter classFilter) {
36         List<ClassDependencyData> classAnalysisList = new ArrayList<>();
37         try (JarFile jarFile = new JarFile(classJar.toFile())) {
38             Enumeration<JarEntry> entries = jarFile.entries();
39             while (entries.hasMoreElements()) {
40                 JarEntry entry = entries.nextElement();
41                 if (entry.getName().endsWith(".class")) {
42                     try (InputStream inputStream = jarFile.getInputStream(entry)) {
43                         String name = Utils.trimAndConvertToPackageBasedPath(entry.getName());
44                         ClassDependencyData classAnalysis = ClassDependenciesVisitor.analyze(name,
45                                 new ClassReader(inputStream), classFilter);
46                         classAnalysisList.add(classAnalysis);
47                     }
48                 }
49             }
50         } catch (IOException e) {
51             System.err.println("Error reading the jar file at: " + classJar);
52             throw new RuntimeException(e);
53         }
54         return classAnalysisList;
55     }
56 }
57