001    /*
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements. See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache license, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License. You may obtain a copy of the License at
008     *
009     *      http://www.apache.org/licenses/LICENSE-2.0
010     *
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the license for the specific language governing permissions and
015     * limitations under the license.
016     */
017    package org.apache.logging.log4j.core.config.plugins;
018    
019    import java.io.File;
020    import java.io.FileInputStream;
021    import java.io.FileNotFoundException;
022    import java.io.IOException;
023    import java.lang.annotation.Annotation;
024    import java.net.URI;
025    import java.net.URL;
026    import java.net.URLDecoder;
027    import java.util.Collection;
028    import java.util.Enumeration;
029    import java.util.HashSet;
030    import java.util.Set;
031    import java.util.jar.JarEntry;
032    import java.util.jar.JarInputStream;
033    
034    import org.apache.logging.log4j.Logger;
035    import org.apache.logging.log4j.core.helpers.Charsets;
036    import org.apache.logging.log4j.core.helpers.Loader;
037    import org.apache.logging.log4j.status.StatusLogger;
038    import org.osgi.framework.FrameworkUtil;
039    import org.osgi.framework.wiring.BundleWiring;
040    
041    /**
042     * <p>ResolverUtil is used to locate classes that are available in the/a class path and meet
043     * arbitrary conditions. The two most common conditions are that a class implements/extends
044     * another class, or that is it annotated with a specific annotation. However, through the use
045     * of the {@link Test} class it is possible to search using arbitrary conditions.</p>
046     *
047     * <p>A ClassLoader is used to locate all locations (directories and jar files) in the class
048     * path that contain classes within certain packages, and then to load those classes and
049     * check them. By default the ClassLoader returned by
050     *  {@code Thread.currentThread().getContextClassLoader()} is used, but this can be overridden
051     * by calling {@link #setClassLoader(ClassLoader)} prior to invoking any of the {@code find()}
052     * methods.</p>
053     *
054     * <p>General searches are initiated by calling the
055     * {@link #find(ResolverUtil.Test, String...)} method and supplying
056     * a package name and a Test instance. This will cause the named package <b>and all sub-packages</b>
057     * to be scanned for classes that meet the test. There are also utility methods for the common
058     * use cases of scanning multiple packages for extensions of particular classes, or classes
059     * annotated with a specific annotation.</p>
060     *
061     * <p>The standard usage pattern for the ResolverUtil class is as follows:</p>
062     *
063     *<pre>
064     *ResolverUtil&lt;ActionBean&gt; resolver = new ResolverUtil&lt;ActionBean&gt;();
065     *resolver.findImplementation(ActionBean.class, pkg1, pkg2);
066     *resolver.find(new CustomTest(), pkg1);
067     *resolver.find(new CustomTest(), pkg2);
068     *Collection&lt;ActionBean&gt; beans = resolver.getClasses();
069     *</pre>
070     *
071     * <p>This class was copied from Stripes - http://stripes.mc4j.org/confluence/display/stripes/Home
072     * </p>
073     *
074     * @author Tim Fennell
075     */
076    public class ResolverUtil {
077        /** An instance of Log to use for logging in this class. */
078        private static final Logger LOG = StatusLogger.getLogger();
079    
080        private static final String VFSZIP = "vfszip";
081    
082        private static final String BUNDLE_RESOURCE = "bundleresource";
083    
084        /** The set of matches being accumulated. */
085        private final Set<Class<?>> classMatches = new HashSet<Class<?>>();
086    
087        /** The set of matches being accumulated. */
088        private final Set<URI> resourceMatches = new HashSet<URI>();
089    
090        /**
091         * The ClassLoader to use when looking for classes. If null then the ClassLoader returned
092         * by Thread.currentThread().getContextClassLoader() will be used.
093         */
094        private ClassLoader classloader;
095    
096        /**
097         * Provides access to the classes discovered so far. If no calls have been made to
098         * any of the {@code find()} methods, this set will be empty.
099         *
100         * @return the set of classes that have been discovered.
101         */
102        public Set<Class<?>> 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(final 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(final Class<?> parent, final String... packageNames) {
143            if (packageNames == null) {
144                return;
145            }
146    
147            final Test test = new IsA(parent);
148            for (final 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(final String suffix, final String... packageNames) {
161            if (packageNames == null) {
162                return;
163            }
164    
165            final Test test = new NameEndsWith(suffix);
166            for (final 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(final Class<? extends Annotation> annotation, final String... packageNames) {
179            if (packageNames == null) {
180                return;
181            }
182    
183            final Test test = new AnnotatedWith(annotation);
184            for (final String pkg : packageNames) {
185                findInPackage(test, pkg);
186            }
187        }
188    
189        public void findNamedResource(final String name, final String... pathNames) {
190            if (pathNames == null) {
191                return;
192            }
193    
194            final Test test = new NameIs(name);
195            for (final 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(final Test test, final String... packageNames) {
208            if (packageNames == null) {
209                return;
210            }
211    
212            for (final 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(final Test test, String packageName) {
228            packageName = packageName.replace('.', '/');
229            final ClassLoader loader = getClassLoader();
230            Enumeration<URL> urls;
231    
232            try {
233                urls = loader.getResources(packageName);
234            } catch (final IOException ioe) {
235                LOG.warn("Could not read package: " + packageName, ioe);
236                return;
237            }
238    
239            while (urls.hasMoreElements()) {
240                try {
241                    final URL url = urls.nextElement();
242                    String urlPath = url.getFile();
243                    urlPath = URLDecoder.decode(urlPath, Charsets.UTF_8.name());
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                        final String path = urlPath.substring(0, urlPath.length() - packageName.length() - 2);
259                        final URL newURL = new URL(url.getProtocol(), url.getHost(), path);
260                        final 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                        final 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 (final IOException ioe) {
273                    LOG.warn("could not read entries", ioe);
274                }
275            }
276        }
277    
278        private void loadImplementationsInBundle(final Test test, final String packageName) {
279            //Do not remove the cast on the next line as removing it will cause a compile error on Java 7.
280            final BundleWiring wiring = (BundleWiring) FrameworkUtil.getBundle(
281                    ResolverUtil.class).adapt(BundleWiring.class);
282            final Collection<String> list = wiring.listResources(packageName, "*.class",
283                BundleWiring.LISTRESOURCES_RECURSE);
284            for (final String name : list) {
285                addIfMatching(test, name);
286            }
287        }
288    
289    
290        /**
291         * Finds matches in a physical directory on a filesystem.  Examines all
292         * files within a directory - if the File object is not a directory, and ends with <i>.class</i>
293         * the file is loaded and tested to see if it is acceptable according to the Test.  Operates
294         * recursively to find classes within a folder structure matching the package structure.
295         *
296         * @param test a Test used to filter the classes that are discovered
297         * @param parent the package name up to this directory in the package hierarchy.  E.g. if
298         *        /classes is in the classpath and we wish to examine files in /classes/org/apache then
299         *        the values of <i>parent</i> would be <i>org/apache</i>
300         * @param location a File object representing a directory
301         */
302        private void loadImplementationsInDirectory(final Test test, final String parent, final File location) {
303            final File[] files = location.listFiles();
304            if(files == null)
305                return;
306    
307            StringBuilder builder;
308            for (final File file : files) {
309                builder = new StringBuilder();
310                builder.append(parent).append("/").append(file.getName());
311                final String packageOrClass = parent == null ? file.getName() : builder.toString();
312    
313                if (file.isDirectory()) {
314                    loadImplementationsInDirectory(test, packageOrClass, file);
315                } else if (isTestApplicable(test, file.getName())) {
316                    addIfMatching(test, packageOrClass);
317                }
318            }
319        }
320    
321        private boolean isTestApplicable(final Test test, final String path) {
322            return test.doesMatchResource() || path.endsWith(".class") && test.doesMatchClass();
323        }
324    
325        /**
326         * Finds matching classes within a jar files that contains a folder structure
327         * matching the package structure.  If the File is not a JarFile or does not exist a warning
328         * will be logged, but no error will be raised.
329         *
330         * @param test a Test used to filter the classes that are discovered
331         * @param parent the parent package under which classes must be in order to be considered
332         * @param jarfile the jar file to be examined for classes
333         */
334        private void loadImplementationsInJar(final Test test, final String parent, final File jarfile) {
335            JarInputStream jarStream;
336            try {
337                jarStream = new JarInputStream(new FileInputStream(jarfile));
338                loadImplementationsInJar(test, parent, jarfile.getPath(), jarStream);
339            } catch (final FileNotFoundException ex) {
340                LOG.error("Could not search jar file '" + jarfile + "' for classes matching criteria: " +
341                    test + " file not found");
342            } catch (final IOException ioe) {
343                LOG.error("Could not search jar file '" + jarfile + "' for classes matching criteria: " +
344                    test + " due to an IOException", ioe);
345            }
346        }
347    
348        /**
349         * Finds matching classes within a jar files that contains a folder structure
350         * matching the package structure.  If the File is not a JarFile or does not exist a warning
351         * will be logged, but no error will be raised.
352         *
353         * @param test a Test used to filter the classes that are discovered
354         * @param parent the parent package under which classes must be in order to be considered
355         * @param stream The jar InputStream
356         */
357        private void loadImplementationsInJar(final Test test, final String parent, final String path,
358                                              final JarInputStream stream) {
359    
360            try {
361                JarEntry entry;
362    
363                while ((entry = stream.getNextJarEntry()) != null) {
364                    final String name = entry.getName();
365                    if (!entry.isDirectory() && name.startsWith(parent) && isTestApplicable(test, name)) {
366                        addIfMatching(test, name);
367                    }
368                }
369            } catch (final IOException ioe) {
370                LOG.error("Could not search jar file '" + path + "' for classes matching criteria: " +
371                    test + " due to an IOException", ioe);
372            }
373        }
374    
375        /**
376         * Add the class designated by the fully qualified class name provided to the set of
377         * resolved classes if and only if it is approved by the Test supplied.
378         *
379         * @param test the test used to determine if the class matches
380         * @param fqn the fully qualified name of a class
381         */
382        protected void addIfMatching(final Test test, final String fqn) {
383            try {
384                final ClassLoader loader = getClassLoader();
385                if (test.doesMatchClass()) {
386                    final String externalName = fqn.substring(0, fqn.indexOf('.')).replace('/', '.');
387                    if (LOG.isDebugEnabled()) {
388                        LOG.debug("Checking to see if class " + externalName + " matches criteria [" + test + "]");
389                    }
390    
391                    final Class<?> type = loader.loadClass(externalName);
392                    if (test.matches(type)) {
393                        classMatches.add(type);
394                    }
395                }
396                if (test.doesMatchResource()) {
397                    URL url = loader.getResource(fqn);
398                    if (url == null) {
399                        url = loader.getResource(fqn.substring(1));
400                    }
401                    if (url != null && test.matches(url.toURI())) {
402                        resourceMatches.add(url.toURI());
403                    }
404                }
405            } catch (final Throwable t) {
406                LOG.warn("Could not examine class '" + fqn + "' due to a " +
407                    t.getClass().getName() + " with message: " + t.getMessage());
408            }
409        }
410    
411        /**
412         * A simple interface that specifies how to test classes to determine if they
413         * are to be included in the results produced by the ResolverUtil.
414         */
415        public interface Test {
416            /**
417             * Will be called repeatedly with candidate classes. Must return True if a class
418             * is to be included in the results, false otherwise.
419             * @param type The Class to match against.
420             * @return true if the Class matches.
421             */
422            boolean matches(Class<?> type);
423    
424            /**
425             * Test for a resource.
426             * @param resource The URI to the resource.
427             * @return true if the resource matches.
428             */
429            boolean matches(URI resource);
430    
431            boolean doesMatchClass();
432    
433            boolean doesMatchResource();
434        }
435    
436        /**
437         * Test against a Class.
438         */
439        public abstract static class ClassTest implements Test {
440            @Override
441            public boolean matches(final URI resource) {
442                throw new UnsupportedOperationException();
443            }
444    
445            @Override
446            public boolean doesMatchClass() {
447                return true;
448            }
449    
450            @Override
451            public boolean doesMatchResource() {
452                return false;
453            }
454        }
455    
456        /**
457         * Test against a resource.
458         */
459        public abstract static class ResourceTest implements Test {
460            @Override
461            public boolean matches(final Class<?> cls) {
462                throw new UnsupportedOperationException();
463            }
464    
465            @Override
466            public boolean doesMatchClass() {
467                return false;
468            }
469    
470            @Override
471            public boolean doesMatchResource() {
472                return true;
473            }
474        }
475    
476        /**
477         * A Test that checks to see if each class is assignable to the provided class. Note
478         * that this test will match the parent type itself if it is presented for matching.
479         */
480        public static class IsA extends ClassTest {
481            private final Class<?> parent;
482    
483            /**
484             * Constructs an IsA test using the supplied Class as the parent class/interface.
485             * @param parentType The parent class to check for.
486             */
487            public IsA(final Class<?> parentType) { this.parent = parentType; }
488    
489            /**
490             * Returns true if type is assignable to the parent type supplied in the constructor.
491             * @param type The Class to check.
492             * @return true if the Class matches.
493             */
494            @Override
495            public boolean matches(final Class<?> type) {
496                return type != null && parent.isAssignableFrom(type);
497            }
498    
499            @Override
500            public String toString() {
501                return "is assignable to " + parent.getSimpleName();
502            }
503        }
504    
505        /**
506         * A Test that checks to see if each class name ends with the provided suffix.
507         */
508        public static class NameEndsWith extends ClassTest {
509            private final String suffix;
510    
511            /**
512             * Constructs a NameEndsWith test using the supplied suffix.
513             * @param suffix the String suffix to check for.
514             */
515            public NameEndsWith(final String suffix) { this.suffix = suffix; }
516    
517            /**
518             * Returns true if type name ends with the suffix supplied in the constructor.
519             * @param type The Class to check.
520             * @return true if the Class matches.
521             */
522            @Override
523            public boolean matches(final Class<?> type) {
524                return type != null && type.getName().endsWith(suffix);
525            }
526    
527            @Override
528            public String toString() {
529                return "ends with the suffix " + suffix;
530            }
531        }
532    
533        /**
534         * A Test that checks to see if each class is annotated with a specific annotation. If it
535         * is, then the test returns true, otherwise false.
536         */
537        public static class AnnotatedWith extends ClassTest {
538            private final Class<? extends Annotation> annotation;
539    
540            /**
541             * Constructs an AnnotatedWith test for the specified annotation type.
542             * @param annotation The annotation to check for.
543             */
544            public AnnotatedWith(final Class<? extends Annotation> annotation) {
545                this.annotation = annotation;
546            }
547    
548            /**
549             * Returns true if the type is annotated with the class provided to the constructor.
550             * @param type the Class to match against.
551             * @return true if the Classes match.
552             */
553            @Override
554            public boolean matches(final Class<?> type) {
555                return type != null && type.isAnnotationPresent(annotation);
556            }
557    
558            @Override
559            public String toString() {
560                return "annotated with @" + annotation.getSimpleName();
561            }
562        }
563    
564        /**
565         * A Test that checks to see if the class name matches.
566         */
567        public static class NameIs extends ResourceTest {
568            private final String name;
569    
570            public NameIs(final String name) { this.name = "/" + name; }
571    
572            @Override
573            public boolean matches(final URI resource) {
574                return resource.getPath().endsWith(name);
575            }
576    
577            @Override public String toString() {
578                return "named " + name;
579            }
580        }
581    }