1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.shared.jar.classes;
20
21 import java.util.ArrayList;
22 import java.util.List;
23 import java.util.regex.Matcher;
24 import java.util.regex.Pattern;
25
26 import org.apache.bcel.classfile.ConstantClass;
27 import org.apache.bcel.classfile.ConstantUtf8;
28 import org.apache.bcel.classfile.EmptyVisitor;
29 import org.apache.bcel.classfile.JavaClass;
30 import org.apache.commons.collections4.list.SetUniqueList;
31
32
33
34
35 public class ImportVisitor extends EmptyVisitor {
36
37
38
39 private final List<String> imports;
40
41
42
43
44 private final JavaClass javaClass;
45
46
47
48
49
50 private static final Pattern QUALIFIED_IMPORT_PATTERN = Pattern.compile("L([a-zA-Z][a-zA-Z0-9\\.]+);");
51
52
53
54
55 private static final Pattern VALID_UTF8_PATTERN = Pattern.compile("^[\\(\\)\\[A-Za-z0-9;/]+$");
56
57
58
59
60
61
62 public ImportVisitor(JavaClass javaClass) {
63 this.javaClass = javaClass;
64
65
66
67 this.imports = SetUniqueList.setUniqueList(new ArrayList<>());
68 }
69
70
71
72
73
74
75 public List<String> getImports() {
76 return imports;
77 }
78
79
80
81
82
83
84 @Override
85 public void visitConstantClass(ConstantClass constantClass) {
86 String name = constantClass.getBytes(javaClass.getConstantPool());
87
88
89 if (name.indexOf('/') == -1) {
90 return;
91 }
92
93 name = name.replace('/', '.');
94
95 if (name.endsWith(".class")) {
96 name = name.substring(0, name.length() - 6);
97 }
98
99 Matcher mat = QUALIFIED_IMPORT_PATTERN.matcher(name);
100 if (mat.find()) {
101 this.imports.add(mat.group(1));
102 } else {
103 this.imports.add(name);
104 }
105 }
106
107
108
109
110
111
112 @Override
113 public void visitConstantUtf8(ConstantUtf8 constantUtf8) {
114 String ret = constantUtf8.getBytes().trim();
115
116
117 if (ret.length() <= 0) {
118 return;
119 }
120
121
122 if (!VALID_UTF8_PATTERN.matcher(ret).matches()) {
123 return;
124 }
125
126
127 if (ret.indexOf('/') == -1) {
128 return;
129 }
130
131
132
133 if (ret.charAt(0) == '/') {
134 return;
135 }
136
137
138 ret = ret.replace('/', '.');
139
140
141
142 if (ret.contains("..")) {
143 return;
144 }
145
146 Matcher mat = QUALIFIED_IMPORT_PATTERN.matcher(ret);
147 char prefix = ret.charAt(0);
148
149 if (prefix == '(') {
150
151
152
153 while (mat.find()) {
154 this.imports.add(mat.group(1));
155 }
156 } else {
157
158 if (mat.find()) {
159
160 this.imports.add(mat.group(1));
161 } else {
162
163 this.imports.add(ret);
164 }
165 }
166 }
167 }