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
53 private static final Pattern QUALIFIED_IMPORT_PATTERN = Pattern.compile( "L([a-zA-Z][a-zA-Z0-9\\.]+);" );
54
55
56
57
58 private static final Pattern VALID_UTF8_PATTERN = Pattern.compile( "^[\\(\\)\\[A-Za-z0-9;/]+$" );
59
60
61
62
63
64
65 public ImportVisitor( JavaClass javaClass )
66 {
67 this.javaClass = javaClass;
68
69
70
71 this.imports = SetUniqueList.decorate( new ArrayList() );
72 }
73
74
75
76
77
78
79 public List getImports()
80 {
81 return imports;
82 }
83
84
85
86
87
88
89 public void visitConstantClass( ConstantClass constantClass )
90 {
91 String name = constantClass.getBytes( javaClass.getConstantPool() );
92
93
94 if ( name.indexOf( '/' ) == -1 )
95 {
96 return;
97 }
98
99 name = name.replace( '/', '.' );
100
101 if ( name.endsWith( ".class" ) )
102 {
103 name = name.substring( 0, name.length() - 6 );
104 }
105
106 Matcher mat = QUALIFIED_IMPORT_PATTERN.matcher( name );
107 if ( mat.find() )
108 {
109 this.imports.add( mat.group( 1 ) );
110 }
111 else
112 {
113 this.imports.add( name );
114 }
115 }
116
117
118
119
120
121
122 public void visitConstantUtf8( ConstantUtf8 constantUtf8 )
123 {
124 String ret = constantUtf8.getBytes().trim();
125
126
127 if ( ret.length() <= 0 )
128 {
129 return;
130 }
131
132
133 if ( !VALID_UTF8_PATTERN.matcher( ret ).matches() )
134 {
135 return;
136 }
137
138
139 if ( ret.indexOf( '/' ) == -1 )
140 {
141 return;
142 }
143
144
145
146 if ( ret.charAt( 0 ) == '/' )
147 {
148 return;
149 }
150
151
152 ret = ret.replace( '/', '.' );
153
154
155
156 if ( ret.indexOf( ".." ) != -1 )
157 {
158 return;
159 }
160
161 Matcher mat = QUALIFIED_IMPORT_PATTERN.matcher( ret );
162 char prefix = ret.charAt( 0 );
163
164 if ( prefix == '(' )
165 {
166
167
168
169 while ( mat.find() )
170 {
171 this.imports.add( mat.group( 1 ) );
172 }
173 }
174 else
175 {
176
177 if ( mat.find() )
178 {
179
180 this.imports.add( mat.group( 1 ) );
181 }
182 else
183 {
184
185 this.imports.add( ret );
186 }
187 }
188 }
189 }