/
ClassFileVisitor.java
251 lines (228 loc) · 8.01 KB
/
ClassFileVisitor.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
package org.codehaus.mojo.animal_sniffer;
/*
* The MIT License
*
* Copyright (c) 2008 Kohsuke Kawaguchi and codehaus.org.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.FileVisitOption;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.codehaus.mojo.animal_sniffer.logging.Logger;
import org.codehaus.mojo.animal_sniffer.logging.PrintWriterLogger;
/**
* @author Kohsuke Kawaguchi
*/
public abstract class ClassFileVisitor
{
protected final Logger logger;
protected ClassFileVisitor()
{
this( new PrintWriterLogger( System.err ) );
}
protected ClassFileVisitor( Logger logger )
{
this.logger = logger;
}
/**
* Whether to check inside <code>.jar</code> files
*/
private boolean checkJars = true;
public boolean isCheckJars()
{
return checkJars;
}
public void setCheckJars( boolean checkJars )
{
this.checkJars = checkJars;
}
/**
* Multi-arg version of {@link #process(File)}.
*/
public void process( File[] files )
throws IOException
{
Arrays.sort( files, new Comparator<File>()
{
public int compare( File f1, File f2 )
{
String n1 = f1.getName();
String n2 = f2.getName();
// Ensure that outer classes are visited before inner classes:
int diff = n1.length() - n2.length();
return diff != 0 ? diff : n1.compareTo( n2 );
}
} );
for ( int i = 0; i < files.length; i++ )
{
process( files[i] );
}
}
/**
* Recursively finds class files and invokes {@link #process(String, InputStream)}
*
* @param file Directory full of class files or jar files (in which case all of them are processed recursively),
* or a class file (in which case that single class is processed),
* or a jar file (in which case all the classes in this jar file are processed.)
*/
public void process( File file )
throws IOException
{
if ( file.isDirectory() )
{
processDirectory( file );
}
else if ( file.getName().endsWith( ".class" ) )
{
processClassFile( file );
}
else if ( ( file.getName().endsWith( ".jar" ) || file.getName().endsWith( ".jmod" ) ) && checkJars )
{
processJarFile( file );
}
// ignore other files
}
/**
* Recursively finds class files and invokes {@link #process(String, InputStream)}
*
* @param path Directory (or other Path like {@code Paths.get(URI.create("jrt:/modules"))}) full of class files,
* or a class file (in which case that single class is processed).
*/
public void process( Path path )
throws IOException {
Files.walkFileTree(path, Collections.<FileVisitOption>emptySet(), 10000, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (file.getFileName().toString().endsWith(".class")) {
process(file.toString(), Files.newInputStream(file));
}
// XXX we could add processing of jars here as well
// but it's not necessary for processing: Paths.get(URI.create("jrt:/modules"))
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
});
}
protected void processDirectory( File dir )
throws IOException
{
File[] files = dir.listFiles();
if ( files == null )
{
return;
}
process( files );
}
protected void processJarFile( File file )
throws IOException
{
try ( JarFile jar = new JarFile( file ) )
{
SortedSet<JarEntry> entries = new TreeSet<JarEntry>( new Comparator<JarEntry>() {
public int compare( JarEntry e1, JarEntry e2 )
{
String n1 = e1.getName();
String n2 = e2.getName();
int diff = n1.length() - n2.length();
return diff != 0 ? diff : n1.compareTo( n2 );
}
} );
Enumeration<JarEntry> e = jar.entries();
while ( e.hasMoreElements() )
{
JarEntry x = e.nextElement();
String name = x.getName();
if ( !name.endsWith( ".class" ) )
{
continue; // uninteresting to log even at debug
}
if ( name.startsWith( "META-INF/" ) || name.equals( "module-info.class" ) )
{
logger.debug( "Ignoring " + name );
continue;
}
entries.add( x );
}
Iterator<JarEntry> it = entries.iterator();
while ( it.hasNext() ) {
JarEntry x = it.next();
// Even debug level seems too verbose for: logger.debug( "Processing " + x.getName() + " in " + file );
InputStream is = jar.getInputStream( x );
try
{
process( file.getPath() + ':' + x.getName(), is );
}
finally
{
is.close();
}
}
}
catch ( IOException cause )
{
IOException e = new IOException( " failed to process jar " + file.getPath() + " : " + cause.getMessage() );
e.initCause( cause );
throw e;
}
}
protected void processClassFile( File file )
throws IOException
{
InputStream in = new FileInputStream( file );
try
{
process( file.getPath(), in );
}
finally
{
in.close();
}
}
/**
* @param name Displayable name to identify what class file we are processing
* @param image Class file image.
*/
protected abstract void process( String name, InputStream image )
throws IOException;
}