1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.shared.dependency.analyzer;
20
21 import java.io.File;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.net.URI;
25 import java.net.URISyntaxException;
26 import java.net.URL;
27 import java.nio.file.Files;
28 import java.nio.file.Path;
29 import java.util.List;
30 import java.util.jar.JarEntry;
31 import java.util.jar.JarInputStream;
32 import java.util.stream.Collectors;
33 import java.util.stream.Stream;
34
35
36
37
38
39
40 public final class ClassFileVisitorUtils {
41
42 private ClassFileVisitorUtils() {
43
44 }
45
46
47
48
49
50
51 public static void accept(URL url, ClassFileVisitor visitor) throws IOException {
52 if (url.getPath().endsWith(".jar")) {
53 acceptJar(url, visitor);
54 } else if (url.getProtocol().equalsIgnoreCase("file")) {
55 try {
56 File file = new File(new URI(url.toString()));
57
58 if (file.isDirectory()) {
59 acceptDirectory(file, visitor);
60 } else if (file.exists()) {
61 throw new IllegalArgumentException("Cannot accept visitor on URL: " + url);
62 }
63 } catch (URISyntaxException exception) {
64 throw new IllegalArgumentException("Cannot accept visitor on URL: " + url, exception);
65 }
66 } else {
67 throw new IllegalArgumentException("Cannot accept visitor on URL: " + url);
68 }
69 }
70
71
72
73 private static void acceptJar(URL url, ClassFileVisitor visitor) throws IOException {
74 try (JarInputStream in = new JarInputStream(url.openStream())) {
75 JarEntry entry;
76 while ((entry = in.getNextJarEntry()) != null) {
77 String name = entry.getName();
78
79 if (name.endsWith(".class") && name.indexOf('-') == -1) {
80
81 visitClass(name, in, visitor, '/');
82 }
83 }
84 }
85 }
86
87 private static void acceptDirectory(File directory, ClassFileVisitor visitor) throws IOException {
88
89 List<Path> classFiles;
90 try (Stream<Path> walk = Files.walk(directory.toPath())) {
91 classFiles = walk.filter(path -> path.getFileName().toString().endsWith(".class"))
92 .collect(Collectors.toList());
93 }
94
95 for (Path path : classFiles) {
96 try (InputStream in = Files.newInputStream(path)) {
97 try {
98 visitClass(directory, path, in, visitor);
99 } catch (RuntimeException e) {
100
101 throw new RuntimeException(
102 String.format("%s from directory = %s, path = %s", e.getMessage(), directory, path), e);
103 }
104 }
105 }
106 }
107
108 private static void visitClass(File baseDirectory, Path path, InputStream in, ClassFileVisitor visitor) {
109
110 String stringPath =
111 path.toFile().getPath().substring(baseDirectory.getPath().length() + 1);
112 visitClass(stringPath, in, visitor, File.separatorChar);
113 }
114
115 private static void visitClass(String stringPath, InputStream in, ClassFileVisitor visitor, char separator) {
116 String className = stringPath.substring(0, stringPath.length() - 6);
117
118 className = className.replace(separator, '.');
119
120 visitor.visitClass(className, in);
121 }
122 }