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