1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.logging.log4j.core.config.plugins.util;
18
19 import java.io.File;
20 import java.io.FileInputStream;
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.io.UnsupportedEncodingException;
24 import java.net.JarURLConnection;
25 import java.net.URI;
26 import java.net.URISyntaxException;
27 import java.net.URL;
28 import java.net.URLDecoder;
29 import java.nio.charset.StandardCharsets;
30 import java.util.Arrays;
31 import java.util.Collection;
32 import java.util.Enumeration;
33 import java.util.HashSet;
34 import java.util.List;
35 import java.util.Set;
36 import java.util.jar.JarEntry;
37 import java.util.jar.JarFile;
38 import java.util.jar.JarInputStream;
39
40 import org.apache.logging.log4j.Logger;
41 import org.apache.logging.log4j.core.util.Loader;
42 import org.apache.logging.log4j.status.StatusLogger;
43 import org.osgi.framework.FrameworkUtil;
44 import org.osgi.framework.wiring.BundleWiring;
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 public class ResolverUtil {
84
85 private static final Logger LOGGER = StatusLogger.getLogger();
86
87 private static final String VFSZIP = "vfszip";
88
89 private static final String VFS = "vfs";
90
91 private static final String JAR = "jar";
92
93 private static final String BUNDLE_RESOURCE = "bundleresource";
94
95
96 private final Set<Class<?>> classMatches = new HashSet<>();
97
98
99 private final Set<URI> resourceMatches = new HashSet<>();
100
101
102
103
104
105 private ClassLoader classloader;
106
107
108
109
110
111
112
113 public Set<Class<?>> getClasses() {
114 return classMatches;
115 }
116
117
118
119
120
121
122 public Set<URI> getResources() {
123 return resourceMatches;
124 }
125
126
127
128
129
130
131
132 public ClassLoader getClassLoader() {
133 return classloader != null ? classloader : (classloader = Loader.getClassLoader(ResolverUtil.class, null));
134 }
135
136
137
138
139
140
141
142
143 public void setClassLoader(final ClassLoader aClassloader) {
144 this.classloader = aClassloader;
145 }
146
147
148
149
150
151
152
153
154
155
156 public void find(final Test test, final String... packageNames) {
157 if (packageNames == null) {
158 return;
159 }
160
161 for (final String pkg : packageNames) {
162 findInPackage(test, pkg);
163 }
164 }
165
166
167
168
169
170
171
172
173
174
175
176 public void findInPackage(final Test test, String packageName) {
177 packageName = packageName.replace('.', '/');
178 final ClassLoader loader = getClassLoader();
179 Enumeration<URL> urls;
180
181 try {
182 urls = loader.getResources(packageName);
183 } catch (final IOException ioe) {
184 LOGGER.warn("Could not read package: {}", packageName, ioe);
185 return;
186 }
187
188 while (urls.hasMoreElements()) {
189 try {
190 final URL url = urls.nextElement();
191 final String urlPath = extractPath(url);
192
193 LOGGER.info("Scanning for classes in '{}' matching criteria {}", urlPath , test);
194
195 if (VFSZIP.equals(url.getProtocol())) {
196 final String path = urlPath.substring(0, urlPath.length() - packageName.length() - 2);
197 final URL newURL = new URL(url.getProtocol(), url.getHost(), path);
198 @SuppressWarnings("resource")
199 final JarInputStream stream = new JarInputStream(newURL.openStream());
200 try {
201 loadImplementationsInJar(test, packageName, path, stream);
202 } finally {
203 close(stream, newURL);
204 }
205 } else if (VFS.equals(url.getProtocol())) {
206 final String containerPath = urlPath.substring(1, urlPath.length() - packageName.length() - 2);
207 final File containerFile = new File(containerPath);
208 if (containerFile.exists()) {
209 if (containerFile.isDirectory()) {
210 loadImplementationsInDirectory(test, packageName, new File(containerFile, packageName));
211 } else {
212 loadImplementationsInJar(test, packageName, containerFile);
213 }
214 } else {
215
216
217 final String path = urlPath.substring(0, urlPath.length() - packageName.length() - 2);
218 final URL newURL = new URL(url.getProtocol(), url.getHost(), path);
219
220 try (final InputStream is = newURL.openStream()) {
221 final JarInputStream jarStream;
222 if (is instanceof JarInputStream) {
223 jarStream = (JarInputStream) is;
224 } else {
225 jarStream = new JarInputStream(is);
226 }
227 loadImplementationsInJar(test, packageName, path, jarStream);
228 }
229 }
230 } else if (BUNDLE_RESOURCE.equals(url.getProtocol())) {
231 loadImplementationsInBundle(test, packageName);
232 } else if (JAR.equals(url.getProtocol())) {
233 loadImplementationsInJar(test, packageName, url);
234 } else {
235 final File file = new File(urlPath);
236 if (file.isDirectory()) {
237 loadImplementationsInDirectory(test, packageName, file);
238 } else {
239 loadImplementationsInJar(test, packageName, file);
240 }
241 }
242 } catch (final IOException | URISyntaxException ioe) {
243 LOGGER.warn("Could not read entries", ioe);
244 }
245 }
246 }
247
248 String extractPath(final URL url) throws UnsupportedEncodingException, URISyntaxException {
249 String urlPath = url.getPath();
250
251
252
253 if (urlPath.startsWith("jar:")) {
254 urlPath = urlPath.substring(4);
255 }
256
257 if (urlPath.startsWith("file:")) {
258 urlPath = urlPath.substring(5);
259 }
260
261 final int bangIndex = urlPath.indexOf('!');
262 if (bangIndex > 0) {
263 urlPath = urlPath.substring(0, bangIndex);
264 }
265
266
267
268 final String protocol = url.getProtocol();
269 final List<String> neverDecode = Arrays.asList(VFS, VFSZIP, BUNDLE_RESOURCE);
270 if (neverDecode.contains(protocol)) {
271 return urlPath;
272 }
273 final String cleanPath = new URI(urlPath).getPath();
274 if (new File(cleanPath).exists()) {
275
276 return cleanPath;
277 }
278 return URLDecoder.decode(urlPath, StandardCharsets.UTF_8.name());
279 }
280
281 private void loadImplementationsInBundle(final Test test, final String packageName) {
282 final BundleWiring wiring = FrameworkUtil.getBundle(ResolverUtil.class).adapt(BundleWiring.class);
283 final Collection<String> list = wiring.listResources(packageName, "*.class",
284 BundleWiring.LISTRESOURCES_RECURSE);
285 for (final String name : list) {
286 addIfMatching(test, name);
287 }
288 }
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305 private void loadImplementationsInDirectory(final Test test, final String parent, final File location) {
306 final File[] files = location.listFiles();
307 if (files == null) {
308 return;
309 }
310
311 StringBuilder builder;
312 for (final File file : files) {
313 builder = new StringBuilder();
314 builder.append(parent).append('/').append(file.getName());
315 final String packageOrClass = parent == null ? file.getName() : builder.toString();
316
317 if (file.isDirectory()) {
318 loadImplementationsInDirectory(test, packageOrClass, file);
319 } else if (isTestApplicable(test, file.getName())) {
320 addIfMatching(test, packageOrClass);
321 }
322 }
323 }
324
325 private boolean isTestApplicable(final Test test, final String path) {
326 return test.doesMatchResource() || path.endsWith(".class") && test.doesMatchClass();
327 }
328
329
330
331
332
333
334
335
336
337
338
339
340 private void loadImplementationsInJar(final Test test, final String parent, final URL url) {
341 JarURLConnection connection = null;
342 try {
343 connection = (JarURLConnection) url.openConnection();
344 if (connection != null) {
345 try (JarFile jarFile = connection.getJarFile()) {
346 Enumeration<JarEntry> entries = jarFile.entries();
347 while (entries.hasMoreElements()) {
348 JarEntry entry = entries.nextElement();
349 final String name = entry.getName();
350 if (!entry.isDirectory() && name.startsWith(parent) && isTestApplicable(test, name)) {
351 addIfMatching(test, name);
352 }
353 }
354 }
355 } else {
356 LOGGER.error("Could not establish connection to {}", url.toString());
357 }
358 } catch (final IOException ex) {
359 LOGGER.error("Could not search JAR file '{}' for classes matching criteria {}, file not found",
360 url.toString(), test, ex);
361 }
362 }
363
364
365
366
367
368
369
370
371
372
373
374
375 private void loadImplementationsInJar(final Test test, final String parent, final File jarFile) {
376 JarInputStream jarStream = null;
377 try {
378 jarStream = new JarInputStream(new FileInputStream(jarFile));
379 loadImplementationsInJar(test, parent, jarFile.getPath(), jarStream);
380 } catch (final IOException ex) {
381 LOGGER.error("Could not search JAR file '{}' for classes matching criteria {}, file not found", jarFile,
382 test, ex);
383 } finally {
384 close(jarStream, jarFile);
385 }
386 }
387
388
389
390
391
392 private void close(final JarInputStream jarStream, final Object source) {
393 if (jarStream != null) {
394 try {
395 jarStream.close();
396 } catch (final IOException e) {
397 LOGGER.error("Error closing JAR file stream for {}", source, e);
398 }
399 }
400 }
401
402
403
404
405
406
407
408
409
410
411
412
413 private void loadImplementationsInJar(final Test test, final String parent, final String path,
414 final JarInputStream stream) {
415
416 try {
417 JarEntry entry;
418
419 while ((entry = stream.getNextJarEntry()) != null) {
420 final String name = entry.getName();
421 if (!entry.isDirectory() && name.startsWith(parent) && isTestApplicable(test, name)) {
422 addIfMatching(test, name);
423 }
424 }
425 } catch (final IOException ioe) {
426 LOGGER.error("Could not search JAR file '{}' for classes matching criteria {} due to an IOException", path,
427 test, ioe);
428 }
429 }
430
431
432
433
434
435
436
437
438
439
440 protected void addIfMatching(final Test test, final String fqn) {
441 try {
442 final ClassLoader loader = getClassLoader();
443 if (test.doesMatchClass()) {
444 final String externalName = fqn.substring(0, fqn.indexOf('.')).replace('/', '.');
445 if (LOGGER.isDebugEnabled()) {
446 LOGGER.debug("Checking to see if class {} matches criteria {}", externalName, test);
447 }
448
449 final Class<?> type = loader.loadClass(externalName);
450 if (test.matches(type)) {
451 classMatches.add(type);
452 }
453 }
454 if (test.doesMatchResource()) {
455 URL url = loader.getResource(fqn);
456 if (url == null) {
457 url = loader.getResource(fqn.substring(1));
458 }
459 if (url != null && test.matches(url.toURI())) {
460 resourceMatches.add(url.toURI());
461 }
462 }
463 } catch (final Throwable t) {
464 LOGGER.warn("Could not examine class {}", fqn, t);
465 }
466 }
467
468
469
470
471
472 public interface Test {
473
474
475
476
477
478
479
480
481 boolean matches(Class<?> type);
482
483
484
485
486
487
488
489
490 boolean matches(URI resource);
491
492 boolean doesMatchClass();
493
494 boolean doesMatchResource();
495 }
496
497 }