View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache license, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License. You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the license for the specific language governing permissions and
15   * limitations under the license.
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.nio.charset.StandardCharsets;
29  import java.util.Arrays;
30  import java.util.Collection;
31  import java.util.Enumeration;
32  import java.util.HashSet;
33  import java.util.List;
34  import java.util.Set;
35  import java.util.jar.JarEntry;
36  import java.util.jar.JarInputStream;
37  
38  import org.apache.logging.log4j.Logger;
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   * <p>
46   * ResolverUtil is used to locate classes that are available in the/a class path and meet arbitrary conditions. The two
47   * most common conditions are that a class implements/extends another class, or that is it annotated with a specific
48   * annotation. However, through the use of the {@link Test} class it is possible to search using arbitrary conditions.
49   * </p>
50   *
51   * <p>
52   * A ClassLoader is used to locate all locations (directories and jar files) in the class path that contain classes
53   * within certain packages, and then to load those classes and check them. By default the ClassLoader returned by
54   * {@code Thread.currentThread().getContextClassLoader()} is used, but this can be overridden by calling
55   * {@link #setClassLoader(ClassLoader)} prior to invoking any of the {@code find()} methods.
56   * </p>
57   *
58   * <p>
59   * General searches are initiated by calling the {@link #find(ResolverUtil.Test, String...)} method and supplying a
60   * package name and a Test instance. This will cause the named package <b>and all sub-packages</b> to be scanned for
61   * classes that meet the test. There are also utility methods for the common use cases of scanning multiple packages for
62   * extensions of particular classes, or classes annotated with a specific annotation.
63   * </p>
64   *
65   * <p>
66   * The standard usage pattern for the ResolverUtil class is as follows:
67   * </p>
68   *
69   * <pre>
70   * ResolverUtil resolver = new ResolverUtil();
71   * resolver.findInPackage(new CustomTest(), pkg1);
72   * resolver.find(new CustomTest(), pkg1);
73   * resolver.find(new CustomTest(), pkg1, pkg2);
74   * Set&lt;Class&lt;?&gt;&gt; beans = resolver.getClasses();
75   * </pre>
76   *
77   * <p>
78   * This class was copied and modified from Stripes - http://stripes.mc4j.org/confluence/display/stripes/Home
79   * </p>
80   */
81  public class ResolverUtil {
82      /** An instance of Log to use for logging in this class. */
83      private static final Logger LOGGER = StatusLogger.getLogger();
84  
85      private static final String VFSZIP = "vfszip";
86  
87      private static final String VFS = "vfs";
88  
89      private static final String BUNDLE_RESOURCE = "bundleresource";
90  
91      /** The set of matches being accumulated. */
92      private final Set<Class<?>> classMatches = new HashSet<>();
93  
94      /** The set of matches being accumulated. */
95      private final Set<URI> resourceMatches = new HashSet<>();
96  
97      /**
98       * The ClassLoader to use when looking for classes. If null then the ClassLoader returned by
99       * Thread.currentThread().getContextClassLoader() will be used.
100      */
101     private ClassLoader classloader;
102 
103     /**
104      * Provides access to the classes discovered so far. If no calls have been made to any of the {@code find()}
105      * methods, this set will be empty.
106      *
107      * @return the set of classes that have been discovered.
108      */
109     public Set<Class<?>> getClasses() {
110         return classMatches;
111     }
112 
113     /**
114      * Returns the matching resources.
115      * 
116      * @return A Set of URIs that match the criteria.
117      */
118     public Set<URI> getResources() {
119         return resourceMatches;
120     }
121 
122     /**
123      * Returns the ClassLoader that will be used for scanning for classes. If no explicit ClassLoader has been set by
124      * the calling, the context class loader will be used.
125      *
126      * @return the ClassLoader that will be used to scan for classes
127      */
128     public ClassLoader getClassLoader() {
129         return classloader != null ? classloader : (classloader = Loader.getClassLoader(ResolverUtil.class, null));
130     }
131 
132     /**
133      * Sets an explicit ClassLoader that should be used when scanning for classes. If none is set then the context
134      * ClassLoader will be used.
135      *
136      * @param aClassloader
137      *        a ClassLoader to use when scanning for classes
138      */
139     public void setClassLoader(final ClassLoader aClassloader) {
140         this.classloader = aClassloader;
141     }
142 
143     /**
144      * Attempts to discover classes that pass the test. Accumulated classes can be accessed by calling
145      * {@link #getClasses()}.
146      *
147      * @param test
148      *        the test to determine matching classes
149      * @param packageNames
150      *        one or more package names to scan (including subpackages) for classes
151      */
152     public void find(final Test test, final String... packageNames) {
153         if (packageNames == null) {
154             return;
155         }
156 
157         for (final String pkg : packageNames) {
158             findInPackage(test, pkg);
159         }
160     }
161 
162     /**
163      * Scans for classes starting at the package provided and descending into subpackages. Each class is offered up to
164      * the Test as it is discovered, and if the Test returns true the class is retained. Accumulated classes can be
165      * fetched by calling {@link #getClasses()}.
166      *
167      * @param test
168      *        an instance of {@link Test} that will be used to filter classes
169      * @param packageName
170      *        the name of the package from which to start scanning for classes, e.g. {@code net.sourceforge.stripes}
171      */
172     public void findInPackage(final Test test, String packageName) {
173         packageName = packageName.replace('.', '/');
174         final ClassLoader loader = getClassLoader();
175         Enumeration<URL> urls;
176 
177         try {
178             urls = loader.getResources(packageName);
179         } catch (final IOException ioe) {
180             LOGGER.warn("Could not read package: {}", packageName, ioe);
181             return;
182         }
183 
184         while (urls.hasMoreElements()) {
185             try {
186                 final URL url = urls.nextElement();
187                 final String urlPath = extractPath(url);
188 
189                 LOGGER.info("Scanning for classes in '{}' matching criteria {}", urlPath , test);
190                 // Check for a jar in a war in JBoss
191                 if (VFSZIP.equals(url.getProtocol())) {
192                     final String path = urlPath.substring(0, urlPath.length() - packageName.length() - 2);
193                     final URL newURL = new URL(url.getProtocol(), url.getHost(), path);
194                     @SuppressWarnings("resource")
195                     final JarInputStream stream = new JarInputStream(newURL.openStream());
196                     try {
197                         loadImplementationsInJar(test, packageName, path, stream);
198                     } finally {
199                         close(stream, newURL);
200                     }
201                 } else if (VFS.equals(url.getProtocol())) {
202                     final String containerPath = urlPath.substring(1,
203                                                   urlPath.length() - packageName.length() - 2);
204                     final File containerFile = new File(containerPath);
205                     if (containerFile.isDirectory()) {
206                         loadImplementationsInDirectory(test, packageName, new File(containerFile, packageName));
207                     } else {
208                         loadImplementationsInJar(test, packageName, containerFile);
209                     }
210                 } else if (BUNDLE_RESOURCE.equals(url.getProtocol())) {
211                     loadImplementationsInBundle(test, packageName);
212                 } else {
213                     final File file = new File(urlPath);
214                     if (file.isDirectory()) {
215                         loadImplementationsInDirectory(test, packageName, file);
216                     } else {
217                         loadImplementationsInJar(test, packageName, file);
218                     }
219                 }
220             } catch (final IOException | URISyntaxException ioe) {
221                 LOGGER.warn("Could not read entries", ioe);
222             }
223         }
224     }
225 
226     String extractPath(final URL url) throws UnsupportedEncodingException, URISyntaxException {
227         String urlPath = url.getPath(); // same as getFile but without the Query portion
228         // System.out.println(url.getProtocol() + "->" + urlPath);
229 
230         // I would be surprised if URL.getPath() ever starts with "jar:" but no harm in checking
231         if (urlPath.startsWith("jar:")) {
232             urlPath = urlPath.substring(4);
233         }
234         // For jar: URLs, the path part starts with "file:"
235         if (urlPath.startsWith("file:")) {
236             urlPath = urlPath.substring(5);
237         }
238         // If it was in a JAR, grab the path to the jar
239         final int bangIndex = urlPath.indexOf('!');
240         if (bangIndex > 0) {
241             urlPath = urlPath.substring(0, bangIndex);
242         }
243 
244         // LOG4J2-445
245         // Finally, decide whether to URL-decode the file name or not...
246         final String protocol = url.getProtocol();
247         final List<String> neverDecode = Arrays.asList(VFS, VFSZIP, BUNDLE_RESOURCE);
248         if (neverDecode.contains(protocol)) {
249             return urlPath;
250         }
251         final String cleanPath = new URI(urlPath).getPath();
252         if (new File(cleanPath).exists()) {
253             // if URL-encoded file exists, don't decode it
254             return cleanPath;
255         }
256         return URLDecoder.decode(urlPath, StandardCharsets.UTF_8.name());
257     }
258 
259     private void loadImplementationsInBundle(final Test test, final String packageName) {
260         final BundleWiring wiring = FrameworkUtil.getBundle(ResolverUtil.class).adapt(BundleWiring.class);
261         final Collection<String> list = wiring.listResources(packageName, "*.class",
262                 BundleWiring.LISTRESOURCES_RECURSE);
263         for (final String name : list) {
264             addIfMatching(test, name);
265         }
266     }
267 
268     /**
269      * Finds matches in a physical directory on a file system. Examines all files within a directory - if the File object
270      * is not a directory, and ends with <i>.class</i> the file is loaded and tested to see if it is acceptable
271      * according to the Test. Operates recursively to find classes within a folder structure matching the package
272      * structure.
273      *
274      * @param test
275      *        a Test used to filter the classes that are discovered
276      * @param parent
277      *        the package name up to this directory in the package hierarchy. E.g. if /classes is in the classpath and
278      *        we wish to examine files in /classes/org/apache then the values of <i>parent</i> would be
279      *        <i>org/apache</i>
280      * @param location
281      *        a File object representing a directory
282      */
283     private void loadImplementationsInDirectory(final Test test, final String parent, final File location) {
284         final File[] files = location.listFiles();
285         if (files == null) {
286             return;
287         }
288 
289         StringBuilder builder;
290         for (final File file : files) {
291             builder = new StringBuilder();
292             builder.append(parent).append('/').append(file.getName());
293             final String packageOrClass = parent == null ? file.getName() : builder.toString();
294 
295             if (file.isDirectory()) {
296                 loadImplementationsInDirectory(test, packageOrClass, file);
297             } else if (isTestApplicable(test, file.getName())) {
298                 addIfMatching(test, packageOrClass);
299             }
300         }
301     }
302 
303     private boolean isTestApplicable(final Test test, final String path) {
304         return test.doesMatchResource() || path.endsWith(".class") && test.doesMatchClass();
305     }
306 
307     /**
308      * Finds matching classes within a jar files that contains a folder structure matching the package structure. If the
309      * File is not a JarFile or does not exist a warning will be logged, but no error will be raised.
310      *
311      * @param test
312      *        a Test used to filter the classes that are discovered
313      * @param parent
314      *        the parent package under which classes must be in order to be considered
315      * @param jarFile
316      *        the jar file to be examined for classes
317      */
318     private void loadImplementationsInJar(final Test test, final String parent, final File jarFile) {
319         JarInputStream jarStream = null;
320         try {
321             jarStream = new JarInputStream(new FileInputStream(jarFile));
322             loadImplementationsInJar(test, parent, jarFile.getPath(), jarStream);
323         } catch (final IOException ex) {
324             LOGGER.error("Could not search JAR file '{}' for classes matching criteria {}, file not found", jarFile,
325                     test, ex);
326         } finally {
327             close(jarStream, jarFile);
328         }
329     }
330 
331     /**
332      * @param jarStream
333      * @param source
334      */
335     private void close(final JarInputStream jarStream, final Object source) {
336         if (jarStream != null) {
337             try {
338                 jarStream.close();
339             } catch (final IOException e) {
340                 LOGGER.error("Error closing JAR file stream for {}", source, e);
341             }
342         }
343     }
344 
345     /**
346      * Finds matching classes within a jar files that contains a folder structure matching the package structure. If the
347      * File is not a JarFile or does not exist a warning will be logged, but no error will be raised.
348      *
349      * @param test
350      *        a Test used to filter the classes that are discovered
351      * @param parent
352      *        the parent package under which classes must be in order to be considered
353      * @param stream
354      *        The jar InputStream
355      */
356     private void loadImplementationsInJar(final Test test, final String parent, final String path,
357             final JarInputStream stream) {
358 
359         try {
360             JarEntry entry;
361 
362             while ((entry = stream.getNextJarEntry()) != null) {
363                 final String name = entry.getName();
364                 if (!entry.isDirectory() && name.startsWith(parent) && isTestApplicable(test, name)) {
365                     addIfMatching(test, name);
366                 }
367             }
368         } catch (final IOException ioe) {
369             LOGGER.error("Could not search JAR file '{}' for classes matching criteria {} due to an IOException", path,
370                     test, ioe);
371         }
372     }
373 
374     /**
375      * Add the class designated by the fully qualified class name provided to the set of resolved classes if and only if
376      * it is approved by the Test supplied.
377      *
378      * @param test
379      *        the test used to determine if the class matches
380      * @param fqn
381      *        the fully qualified name of a class
382      */
383     protected void addIfMatching(final Test test, final String fqn) {
384         try {
385             final ClassLoader loader = getClassLoader();
386             if (test.doesMatchClass()) {
387                 final String externalName = fqn.substring(0, fqn.indexOf('.')).replace('/', '.');
388                 if (LOGGER.isDebugEnabled()) {
389                     LOGGER.debug("Checking to see if class {} matches criteria {}", externalName, test);
390                 }
391 
392                 final Class<?> type = loader.loadClass(externalName);
393                 if (test.matches(type)) {
394                     classMatches.add(type);
395                 }
396             }
397             if (test.doesMatchResource()) {
398                 URL url = loader.getResource(fqn);
399                 if (url == null) {
400                     url = loader.getResource(fqn.substring(1));
401                 }
402                 if (url != null && test.matches(url.toURI())) {
403                     resourceMatches.add(url.toURI());
404                 }
405             }
406         } catch (final Throwable t) {
407             LOGGER.warn("Could not examine class {}", fqn, t);
408         }
409     }
410 
411     /**
412      * A simple interface that specifies how to test classes to determine if they are to be included in the results
413      * produced by the ResolverUtil.
414      */
415     public interface Test {
416         /**
417          * Will be called repeatedly with candidate classes. Must return True if a class is to be included in the
418          * results, false otherwise.
419          * 
420          * @param type
421          *        The Class to match against.
422          * @return true if the Class matches.
423          */
424         boolean matches(Class<?> type);
425 
426         /**
427          * Test for a resource.
428          * 
429          * @param resource
430          *        The URI to the resource.
431          * @return true if the resource matches.
432          */
433         boolean matches(URI resource);
434 
435         boolean doesMatchClass();
436 
437         boolean doesMatchResource();
438     }
439 
440 }