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