View Javadoc

1   /* Copyright 2005-2006 Tim Fennell
2    *
3    * Licensed under the Apache License, Version 2.0 (the "License");
4    * you may not use this file except in compliance with the License.
5    * You may obtain a copy of the License at
6    *
7    *     http://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */
15  package org.apache.logging.log4j.core.config.plugins;
16  
17  import org.apache.logging.log4j.Logger;
18  import org.apache.logging.log4j.status.StatusLogger;
19  
20  import java.io.File;
21  import java.io.FileInputStream;
22  import java.io.IOException;
23  import java.lang.annotation.Annotation;
24  import java.net.URI;
25  import java.net.URL;
26  import java.net.URLDecoder;
27  import java.util.Enumeration;
28  import java.util.HashSet;
29  import java.util.Set;
30  import java.util.jar.JarEntry;
31  import java.util.jar.JarInputStream;
32  
33  /**
34   * <p>ResolverUtil is used to locate classes that are available in the/a class path and meet
35   * arbitrary conditions. The two most common conditions are that a class implements/extends
36   * another class, or that is it annotated with a specific annotation. However, through the use
37   * of the {@link Test} class it is possible to search using arbitrary conditions.</p>
38   *
39   * <p>A ClassLoader is used to locate all locations (directories and jar files) in the class
40   * path that contain classes within certain packages, and then to load those classes and
41   * check them. By default the ClassLoader returned by
42   *  {@code Thread.currentThread().getContextClassLoader()} is used, but this can be overridden
43   * by calling {@link #setClassLoader(ClassLoader)} prior to invoking any of the {@code find()}
44   * methods.</p>
45   *
46   * <p>General searches are initiated by calling the
47   * {@link #find(org.apache.logging.log4j.core..util.ResolverUtil.Test, String...)} ()} method and supplying
48   * a package name and a Test instance. This will cause the named package <b>and all sub-packages</b>
49   * to be scanned for classes that meet the test. There are also utility methods for the common
50   * use cases of scanning multiple packages for extensions of particular classes, or classes
51   * annotated with a specific annotation.</p>
52   *
53   * <p>The standard usage pattern for the ResolverUtil class is as follows:</p>
54   *
55   *<pre>
56   *ResolverUtil&lt;ActionBean&gt; resolver = new ResolverUtil&lt;ActionBean&gt;();
57   *resolver.findImplementation(ActionBean.class, pkg1, pkg2);
58   *resolver.find(new CustomTest(), pkg1);
59   *resolver.find(new CustomTest(), pkg2);
60   *Collection&lt;ActionBean&gt; beans = resolver.getClasses();
61   *</pre>
62   *
63   * <p>This class was copied from Stripes - http://stripes.mc4j.org/confluence/display/stripes/Home
64   * </p>
65   *
66   * @author Tim Fennell
67   * @param <T> The type of the Class that can be returned.
68   */
69  public class ResolverUtil<T> {
70      /** An instance of Log to use for logging in this class. */
71      private static final Logger LOG = StatusLogger.getLogger();
72  
73      /** The set of matches being accumulated. */
74      private Set<Class<? extends T>> classMatches = new HashSet<Class<?extends T>>();
75  
76      /** The set of matches being accumulated. */
77      private Set<URI> resourceMatches = new HashSet<URI>();
78  
79      /**
80       * The ClassLoader to use when looking for classes. If null then the ClassLoader returned
81       * by Thread.currentThread().getContextClassLoader() will be used.
82       */
83      private ClassLoader classloader;
84  
85      /**
86       * Provides access to the classes discovered so far. If no calls have been made to
87       * any of the {@code find()} methods, this set will be empty.
88       *
89       * @return the set of classes that have been discovered.
90       */
91      public Set<Class<? extends T>> getClasses() {
92          return classMatches;
93      }
94  
95      /**
96       * Return the matching resources.
97       * @return A Set of URIs that match the criteria.
98       */
99      public Set<URI> getResources() {
100         return resourceMatches;
101     }
102 
103 
104     /**
105      * Returns the classloader that will be used for scanning for classes. If no explicit
106      * ClassLoader has been set by the calling, the context class loader will be used.
107      *
108      * @return the ClassLoader that will be used to scan for classes
109      */
110     public ClassLoader getClassLoader() {
111         return classloader == null ? Thread.currentThread().getContextClassLoader() : classloader;
112     }
113 
114     /**
115      * Sets an explicit ClassLoader that should be used when scanning for classes. If none
116      * is set then the context classloader will be used.
117      *
118      * @param classloader a ClassLoader to use when scanning for classes
119      */
120     public void setClassLoader(ClassLoader classloader) { this.classloader = classloader; }
121 
122     /**
123      * Attempts to discover classes that are assignable to the type provided. In the case
124      * that an interface is provided this method will collect implementations. In the case
125      * of a non-interface class, subclasses will be collected.  Accumulated classes can be
126      * accessed by calling {@link #getClasses()}.
127      *
128      * @param parent the class of interface to find subclasses or implementations of
129      * @param packageNames one or more package names to scan (including subpackages) for classes
130      */
131     public void findImplementations(Class parent, String... packageNames) {
132         if (packageNames == null) {
133             return;
134         }
135 
136         Test test = new IsA(parent);
137         for (String pkg : packageNames) {
138             findInPackage(test, pkg);
139         }
140     }
141 
142     /**
143      * Attempts to discover classes who's name ends with the provided suffix. Accumulated classes can be
144      * accessed by calling {@link #getClasses()}.
145      *
146      * @param suffix The class name suffix to match
147      * @param packageNames one or more package names to scan (including subpackages) for classes
148      */
149     public void findSuffix(String suffix, String... packageNames) {
150         if (packageNames == null) {
151             return;
152         }
153 
154         Test test = new NameEndsWith(suffix);
155         for (String pkg : packageNames) {
156             findInPackage(test, pkg);
157         }
158     }
159 
160     /**
161      * Attempts to discover classes that are annotated with to the annotation. Accumulated
162      * classes can be accessed by calling {@link #getClasses()}.
163      *
164      * @param annotation the annotation that should be present on matching classes
165      * @param packageNames one or more package names to scan (including subpackages) for classes
166      */
167     public void findAnnotated(Class<? extends Annotation> annotation, String... packageNames) {
168         if (packageNames == null) {
169             return;
170         }
171 
172         Test test = new AnnotatedWith(annotation);
173         for (String pkg : packageNames) {
174             findInPackage(test, pkg);
175         }
176     }
177 
178     public void findNamedResource(String name, String... pathNames) {
179         if (pathNames == null) {
180             return;
181         }
182 
183         Test test = new NameIs(name);
184         for (String pkg : pathNames) {
185             findInPackage(test, pkg);
186         }
187     }
188 
189     /**
190      * Attempts to discover classes that pass the test. Accumulated
191      * classes can be accessed by calling {@link #getClasses()}.
192      *
193      * @param test the test to determine matching classes
194      * @param packageNames one or more package names to scan (including subpackages) for classes
195      */
196     public void find(Test test, String... packageNames) {
197         if (packageNames == null) {
198             return;
199         }
200 
201         for (String pkg : packageNames) {
202             findInPackage(test, pkg);
203         }
204     }
205 
206     /**
207      * Scans for classes starting at the package provided and descending into subpackages.
208      * Each class is offered up to the Test as it is discovered, and if the Test returns
209      * true the class is retained.  Accumulated classes can be fetched by calling
210      * {@link #getClasses()}.
211      *
212      * @param test an instance of {@link Test} that will be used to filter classes
213      * @param packageName the name of the package from which to start scanning for
214      *        classes, e.g. {@code net.sourceforge.stripes}
215      */
216     public void findInPackage(Test test, String packageName) {
217         packageName = packageName.replace('.', '/');
218         ClassLoader loader = getClassLoader();
219         Enumeration<URL> urls;
220 
221         try {
222             urls = loader.getResources(packageName);
223         } catch (IOException ioe) {
224             LOG.warn("Could not read package: " + packageName, ioe);
225             return;
226         }
227 
228         while (urls.hasMoreElements()) {
229             try {
230                 String urlPath = urls.nextElement().getFile();
231                 urlPath = URLDecoder.decode(urlPath, "UTF-8");
232 
233                 // If it's a file in a directory, trim the stupid file: spec
234                 if (urlPath.startsWith("file:")) {
235                     urlPath = urlPath.substring(5);
236                 }
237 
238                 // Else it's in a JAR, grab the path to the jar
239                 if (urlPath.indexOf('!') > 0) {
240                     urlPath = urlPath.substring(0, urlPath.indexOf('!'));
241                 }
242 
243                 LOG.info("Scanning for classes in [" + urlPath + "] matching criteria: " + test);
244                 File file = new File(urlPath);
245                 if (file.isDirectory()) {
246                     loadImplementationsInDirectory(test, packageName, file);
247                 } else {
248                     loadImplementationsInJar(test, packageName, file);
249                 }
250             } catch (IOException ioe) {
251                 LOG.warn("could not read entries", ioe);
252             }
253         }
254     }
255 
256 
257     /**
258      * Finds matches in a physical directory on a filesystem.  Examines all
259      * files within a directory - if the File object is not a directory, and ends with <i>.class</i>
260      * the file is loaded and tested to see if it is acceptable according to the Test.  Operates
261      * recursively to find classes within a folder structure matching the package structure.
262      *
263      * @param test a Test used to filter the classes that are discovered
264      * @param parent the package name up to this directory in the package hierarchy.  E.g. if
265      *        /classes is in the classpath and we wish to examine files in /classes/org/apache then
266      *        the values of <i>parent</i> would be <i>org/apache</i>
267      * @param location a File object representing a directory
268      */
269     private void loadImplementationsInDirectory(Test test, String parent, File location) {
270         File[] files = location.listFiles();
271         StringBuilder builder;
272 
273         for (File file : files) {
274             builder = new StringBuilder();
275             builder.append(parent).append("/").append(file.getName());
276             String packageOrClass = parent == null ? file.getName() : builder.toString();
277 
278             if (file.isDirectory()) {
279                 loadImplementationsInDirectory(test, packageOrClass, file);
280             } else if (isTestApplicable(test, file.getName())) {
281                 addIfMatching(test, packageOrClass);
282             }
283         }
284     }
285 
286     private boolean isTestApplicable(Test test, String path) {
287         return test.doesMatchResource() || path.endsWith(".class") && test.doesMatchClass();
288     }
289 
290     /**
291      * Finds matching classes within a jar files that contains a folder structure
292      * matching the package structure.  If the File is not a JarFile or does not exist a warning
293      * will be logged, but no error will be raised.
294      *
295      * @param test a Test used to filter the classes that are discovered
296      * @param parent the parent package under which classes must be in order to be considered
297      * @param jarfile the jar file to be examined for classes
298      */
299     private void loadImplementationsInJar(Test test, String parent, File jarfile) {
300 
301         try {
302             JarEntry entry;
303             JarInputStream jarStream = new JarInputStream(new FileInputStream(jarfile));
304 
305             while ((entry = jarStream.getNextJarEntry()) != null) {
306                 String name = entry.getName();
307                 if (!entry.isDirectory() && name.startsWith(parent) && isTestApplicable(test, name)) {
308                     addIfMatching(test, name);
309                 }
310             }
311         } catch (IOException ioe) {
312             LOG.error("Could not search jar file '" + jarfile + "' for classes matching criteria: " +
313                       test + " due to an IOException", ioe);
314         }
315     }
316 
317     /**
318      * Add the class designated by the fully qualified class name provided to the set of
319      * resolved classes if and only if it is approved by the Test supplied.
320      *
321      * @param test the test used to determine if the class matches
322      * @param fqn the fully qualified name of a class
323      */
324     protected void addIfMatching(Test test, String fqn) {
325         try {
326             ClassLoader loader = getClassLoader();
327             if (test.doesMatchClass()) {
328                 String externalName = fqn.substring(0, fqn.indexOf('.')).replace('/', '.');
329                 if (LOG.isDebugEnabled()) {
330                     LOG.debug("Checking to see if class " + externalName + " matches criteria [" + test + "]");
331                 }
332 
333                 Class type = loader.loadClass(externalName);
334                 if (test.matches(type)) {
335                     classMatches.add((Class<T>) type);
336                 }
337             }
338             if (test.doesMatchResource()) {
339                 URL url = loader.getResource(fqn);
340                 if (url == null) {
341                     url = loader.getResource(fqn.substring(1));
342                 }
343                 if (url != null && test.matches(url.toURI())) {
344                     resourceMatches.add(url.toURI());
345                 }
346             }
347         } catch (Throwable t) {
348             LOG.warn("Could not examine class '" + fqn + "' due to a " +
349                      t.getClass().getName() + " with message: " + t.getMessage());
350         }
351     }
352 
353     /**
354      * A simple interface that specifies how to test classes to determine if they
355      * are to be included in the results produced by the ResolverUtil.
356      */
357     public interface Test {
358         /**
359          * Will be called repeatedly with candidate classes. Must return True if a class
360          * is to be included in the results, false otherwise.
361          * @param type The Class to match against.
362          * @return true if the Class matches.
363          */
364         boolean matches(Class type);
365 
366         /**
367          * Test for a resource.
368          * @param resource The URI to the resource.
369          * @return true if the resource matches.
370          */
371         boolean matches(URI resource);
372 
373         boolean doesMatchClass();
374         boolean doesMatchResource();
375     }
376 
377     /**
378      * Test against a Class.
379      */
380     public abstract static class ClassTest implements Test {
381         public boolean matches(URI resource) {
382             throw new UnsupportedOperationException();
383         }
384 
385         public boolean doesMatchClass() {
386             return true;
387         }
388         public boolean doesMatchResource() {
389             return false;
390         }
391     }
392 
393     /**
394      * Test against a resource.
395      */
396     public abstract static class ResourceTest implements Test {
397         public boolean matches(Class cls) {
398             throw new UnsupportedOperationException();
399         }
400 
401         public boolean doesMatchClass() {
402             return false;
403         }
404         public boolean doesMatchResource() {
405             return true;
406         }
407     }
408 
409     /**
410      * A Test that checks to see if each class is assignable to the provided class. Note
411      * that this test will match the parent type itself if it is presented for matching.
412      */
413     public static class IsA extends ClassTest {
414         private Class parent;
415 
416         /**
417          * Constructs an IsA test using the supplied Class as the parent class/interface.
418          * @param parentType The parent class to check for.
419          */
420         public IsA(Class parentType) { this.parent = parentType; }
421 
422         /**
423          * Returns true if type is assignable to the parent type supplied in the constructor.
424          * @param type The Class to check.
425          * @return true if the Class matches.
426          */
427         public boolean matches(Class type) {
428             return type != null && parent.isAssignableFrom(type);
429         }
430 
431         @Override
432         public String toString() {
433             return "is assignable to " + parent.getSimpleName();
434         }
435     }
436 
437     /**
438      * A Test that checks to see if each class name ends with the provided suffix.
439      */
440     public static class NameEndsWith extends ClassTest {
441         private String suffix;
442 
443         /**
444          * Constructs a NameEndsWith test using the supplied suffix.
445          * @param suffix the String suffix to check for.
446          */
447         public NameEndsWith(String suffix) { this.suffix = suffix; }
448 
449         /**
450          * Returns true if type name ends with the suffix supplied in the constructor.
451          * @param type The Class to check.
452          * @return true if the Class matches.
453          */
454         public boolean matches(Class type) {
455             return type != null && type.getName().endsWith(suffix);
456         }
457 
458         @Override
459         public String toString() {
460             return "ends with the suffix " + suffix;
461         }
462     }
463 
464     /**
465      * A Test that checks to see if each class is annotated with a specific annotation. If it
466      * is, then the test returns true, otherwise false.
467      */
468     public static class AnnotatedWith extends ClassTest {
469         private Class<? extends Annotation> annotation;
470 
471         /**
472          * Constructs an AnnotatedWith test for the specified annotation type.
473          * @param annotation The annotation to check for.
474          */
475         public AnnotatedWith(Class<? extends Annotation> annotation) {
476             this.annotation = annotation;
477         }
478 
479         /**
480          * Returns true if the type is annotated with the class provided to the constructor.
481          * @param type the Class to match against.
482          * @return true if the Classes match.
483          */
484         public boolean matches(Class type) {
485             return type != null && type.isAnnotationPresent(annotation);
486         }
487 
488         @Override
489         public String toString() {
490             return "annotated with @" + annotation.getSimpleName();
491         }
492     }
493 
494     /**
495      * A Test that checks to see if the class name matches.
496      */
497     public static class NameIs extends ResourceTest {
498         private String name;
499 
500         public NameIs(String name) { this.name = "/" + name; }
501 
502         public boolean matches(URI resource) {
503             return (resource.getPath().endsWith(name));
504         }
505 
506         @Override public String toString() {
507             return "named " + name;
508         }
509     }
510 }