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