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.camel.util;
018    
019    import java.io.File;
020    import java.io.FileInputStream;
021    import java.io.IOException;
022    import java.lang.annotation.Annotation;
023    import java.net.URL;
024    import java.net.URLDecoder;
025    import java.util.Arrays;
026    import java.util.Enumeration;
027    import java.util.HashSet;
028    import java.util.Set;
029    import java.util.jar.JarEntry;
030    import java.util.jar.JarInputStream;
031    
032    import org.apache.commons.logging.Log;
033    import org.apache.commons.logging.LogFactory;
034    
035    /**
036     * <p>
037     * ResolverUtil is used to locate classes that are available in the/a class path
038     * and meet arbitrary conditions. The two most common conditions are that a
039     * class implements/extends another class, or that is it annotated with a
040     * specific annotation. However, through the use of the {@link Test} class it is
041     * possible to search using arbitrary conditions.
042     * </p>
043     *
044     * <p>
045     * A ClassLoader is used to locate all locations (directories and jar files) in
046     * the class path that contain classes within certain packages, and then to load
047     * those classes and check them. By default the ClassLoader returned by
048     * {@code Thread.currentThread().getContextClassLoader()} is used, but this can
049     * be overridden by calling {@link #setClassLoaders(Set)} prior to
050     * invoking any of the {@code find()} methods.
051     * </p>
052     *
053     * <p>
054     * General searches are initiated by calling the
055     * {@link #find(ResolverUtil.Test, String)} ()} method and supplying a package
056     * name and a Test instance. This will cause the named package <b>and all
057     * sub-packages</b> to be scanned for classes that meet the test. There are
058     * also utility methods for the common use cases of scanning multiple packages
059     * for extensions of particular classes, or classes annotated with a specific
060     * annotation.
061     * </p>
062     *
063     * <p>
064     * The standard usage pattern for the ResolverUtil class is as follows:
065     * </p>
066     *
067     * <pre>
068     * esolverUtil&lt;ActionBean&gt; resolver = new ResolverUtil&lt;ActionBean&gt;();
069     * esolver.findImplementation(ActionBean.class, pkg1, pkg2);
070     * esolver.find(new CustomTest(), pkg1);
071     * esolver.find(new CustomTest(), pkg2);
072     * ollection&lt;ActionBean&gt; beans = resolver.getClasses();
073     * </pre>
074     *
075     * @author Tim Fennell
076     */
077    public class ResolverUtil<T> {
078        private static final transient Log LOG = LogFactory.getLog(ResolverUtil.class);
079    
080        /**
081         * A simple interface that specifies how to test classes to determine if
082         * they are to be included in the results produced by the ResolverUtil.
083         */
084        public static interface Test {
085            /**
086             * Will be called repeatedly with candidate classes. Must return True if
087             * a class is to be included in the results, false otherwise.
088             */
089            boolean matches(Class type);
090        }
091    
092        /**
093         * A Test that checks to see if each class is assignable to the provided
094         * class. Note that this test will match the parent type itself if it is
095         * presented for matching.
096         */
097        public static class IsA implements Test {
098            private Class parent;
099    
100            /**
101             * Constructs an IsA test using the supplied Class as the parent
102             * class/interface.
103             */
104            public IsA(Class parentType) {
105                this.parent = parentType;
106            }
107    
108            /**
109             * Returns true if type is assignable to the parent type supplied in the
110             * constructor.
111             */
112            public boolean matches(Class type) {
113                return type != null && parent.isAssignableFrom(type);
114            }
115    
116            @Override
117            public String toString() {
118                return "is assignable to " + parent.getSimpleName();
119            }
120        }
121    
122        /**
123         * A Test that checks to see if each class is annotated with a specific
124         * annotation. If it is, then the test returns true, otherwise false.
125         */
126        public static class AnnotatedWith implements Test {
127            private Class<? extends Annotation> annotation;
128    
129            /** Construts an AnnotatedWith test for the specified annotation type. */
130            public AnnotatedWith(Class<? extends Annotation> annotation) {
131                this.annotation = annotation;
132            }
133    
134            /**
135             * Returns true if the type is annotated with the class provided to the
136             * constructor.
137             */
138            public boolean matches(Class type) {
139                return type != null && type.isAnnotationPresent(annotation);
140            }
141    
142            @Override
143            public String toString() {
144                return "annotated with @" + annotation.getSimpleName();
145            }
146        }
147    
148        /** The set of matches being accumulated. */
149        private Set<Class<? extends T>> matches = new HashSet<Class<? extends T>>();
150    
151        /**
152         * The ClassLoader to use when looking for classes. If null then the
153         * ClassLoader returned by Thread.currentThread().getContextClassLoader()
154         * will be used.
155         */
156        private Set<ClassLoader> classLoaders;
157    
158        /**
159         * Provides access to the classes discovered so far. If no calls have been
160         * made to any of the {@code find()} methods, this set will be empty.
161         *
162         * @return the set of classes that have been discovered.
163         */
164        public Set<Class<? extends T>> getClasses() {
165            return matches;
166        }
167    
168    
169        /**
170         * Returns the classloaders that will be used for scanning for classes. If no
171         * explicit ClassLoader has been set by the calling, the context class
172         * loader will be used.
173         *
174         * @return the ClassLoader instances that will be used to scan for classes
175         */
176        public Set<ClassLoader> getClassLoaders() {
177            if (classLoaders == null) {
178                classLoaders = new HashSet<ClassLoader>();
179                classLoaders.add(Thread.currentThread().getContextClassLoader());
180            }
181            return classLoaders;
182        }
183    
184        /**
185         * Sets the ClassLoader instances that should be used when scanning for
186         * classes. If none is set then the context classloader will be used.
187         *
188         * @param classLoaders a ClassLoader to use when scanning for classes
189         */
190        public void setClassLoaders(Set<ClassLoader> classLoaders) {
191            this.classLoaders = classLoaders;
192        }
193    
194        /**
195         * Attempts to discover classes that are assignable to the type provided. In
196         * the case that an interface is provided this method will collect
197         * implementations. In the case of a non-interface class, subclasses will be
198         * collected. Accumulated classes can be accessed by calling
199         * {@link #getClasses()}.
200         *
201         * @param parent the class of interface to find subclasses or
202         *                implementations of
203         * @param packageNames one or more package names to scan (including
204         *                subpackages) for classes
205         */
206        public void findImplementations(Class parent, String... packageNames) {
207            if (packageNames == null) {
208                return;
209            }
210    
211            LOG.debug("Searching for implementations of " + parent.getName() + " in packages: " + Arrays.asList(packageNames));
212    
213            Test test = new IsA(parent);
214            for (String pkg : packageNames) {
215                find(test, pkg);
216            }
217    
218            LOG.debug("Found: " + getClasses());
219        }
220    
221        /**
222         * Attempts to discover classes that are annotated with to the annotation.
223         * Accumulated classes can be accessed by calling {@link #getClasses()}.
224         *
225         * @param annotation the annotation that should be present on matching
226         *                classes
227         * @param packageNames one or more package names to scan (including
228         *                subpackages) for classes
229         */
230        public void findAnnotated(Class<? extends Annotation> annotation, String... packageNames) {
231            if (packageNames == null) {
232                return;
233            }
234    
235            Test test = new AnnotatedWith(annotation);
236            for (String pkg : packageNames) {
237                find(test, pkg);
238            }
239        }
240    
241        /**
242         * Scans for classes starting at the package provided and descending into
243         * subpackages. Each class is offered up to the Test as it is discovered,
244         * and if the Test returns true the class is retained. Accumulated classes
245         * can be fetched by calling {@link #getClasses()}.
246         *
247         * @param test an instance of {@link Test} that will be used to filter
248         *                classes
249         * @param packageName the name of the package from which to start scanning
250         *                for classes, e.g. {@code net.sourceforge.stripes}
251         */
252        public void find(Test test, String packageName) {
253            packageName = packageName.replace('.', '/');
254    
255            Set<ClassLoader> set = getClassLoaders();
256            for (ClassLoader classLoader : set) {
257                LOG.trace("Searching: " + classLoader);
258    
259                find(test, packageName, classLoader);
260            }
261        }
262    
263        protected void find(Test test, String packageName, ClassLoader loader) {
264            Enumeration<URL> urls;
265    
266            try {
267                urls = loader.getResources(packageName);
268            } catch (IOException ioe) {
269                LOG.warn("Could not read package: " + packageName, ioe);
270                return;
271            }
272    
273            while (urls.hasMoreElements()) {
274                try {
275                    URL url = urls.nextElement();
276    
277                    String urlPath = url.getFile();
278                    urlPath = URLDecoder.decode(urlPath, "UTF-8");
279    
280                    // If it's a file in a directory, trim the stupid file: spec
281                    if (urlPath.startsWith("file:")) {
282                        urlPath = urlPath.substring(5);
283                    }
284    
285                    // Else it's in a JAR, grab the path to the jar
286                    if (urlPath.indexOf('!') > 0) {
287                        urlPath = urlPath.substring(0, urlPath.indexOf('!'));
288                    }
289    
290                    LOG.debug("Scanning for classes in [" + urlPath + "] matching criteria: " + test);
291                    File file = new File(urlPath);
292                    if (file.isDirectory()) {
293                        loadImplementationsInDirectory(test, packageName, file);
294                    } else {
295                        loadImplementationsInJar(test, packageName, file);
296                    }
297                } catch (IOException ioe) {
298                    LOG.warn("could not read entries", ioe);
299                }
300            }
301        }
302    
303        /**
304         * Finds matches in a physical directory on a filesystem. Examines all files
305         * within a directory - if the File object is not a directory, and ends with
306         * <i>.class</i> the file is loaded and tested to see if it is acceptable
307         * according to the Test. Operates recursively to find classes within a
308         * folder structure matching the package structure.
309         *
310         * @param test a Test used to filter the classes that are discovered
311         * @param parent the package name up to this directory in the package
312         *                hierarchy. E.g. if /classes is in the classpath and we
313         *                wish to examine files in /classes/org/apache then the
314         *                values of <i>parent</i> would be <i>org/apache</i>
315         * @param location a File object representing a directory
316         */
317        private void loadImplementationsInDirectory(Test test, String parent, File location) {
318            File[] files = location.listFiles();
319            StringBuilder builder = null;
320    
321            for (File file : files) {
322                builder = new StringBuilder(100);
323                String name = file.getName();
324                if (name != null) {
325                    name = name.trim();
326                }
327                builder.append(parent).append("/").append(name);
328                String packageOrClass = parent == null ? name : builder.toString();
329    
330                if (file.isDirectory()) {
331                    loadImplementationsInDirectory(test, packageOrClass, file);
332                } else if (name.endsWith(".class")) {
333                    addIfMatching(test, packageOrClass);
334                }
335            }
336        }
337    
338        /**
339         * Finds matching classes within a jar files that contains a folder
340         * structure matching the package structure. If the File is not a JarFile or
341         * does not exist a warning will be logged, but no error will be raised.
342         *
343         * @param test a Test used to filter the classes that are discovered
344         * @param parent the parent package under which classes must be in order to
345         *                be considered
346         * @param jarfile the jar file to be examined for classes
347         */
348        private void loadImplementationsInJar(Test test, String parent, File jarfile) {
349    
350            try {
351                JarEntry entry;
352                JarInputStream jarStream = new JarInputStream(new FileInputStream(jarfile));
353    
354                while ((entry = jarStream.getNextJarEntry()) != null) {
355                    String name = entry.getName();
356                    if (name != null) {
357                        name = name.trim();
358                    }
359                    if (!entry.isDirectory() && name.startsWith(parent) && name.endsWith(".class")) {
360                        addIfMatching(test, name);
361                    }
362                }
363            } catch (IOException ioe) {
364                LOG.error("Could not search jar file '" + jarfile + "' for classes matching criteria: " + test
365                          + "due to an IOException: " + ioe.getMessage());
366            }
367        }
368    
369        /**
370         * Add the class designated by the fully qualified class name provided to
371         * the set of resolved classes if and only if it is approved by the Test
372         * supplied.
373         *
374         * @param test the test used to determine if the class matches
375         * @param fqn the fully qualified name of a class
376         */
377        protected void addIfMatching(Test test, String fqn) {
378            try {
379                String externalName = fqn.substring(0, fqn.indexOf('.')).replace('/', '.');
380                Set<ClassLoader> set = getClassLoaders();
381                boolean found = false;
382                for (ClassLoader classLoader : set) {
383                    LOG.trace("Checking to see if class " + externalName + " matches criteria [" + test + "]");
384    
385                    try {
386                        Class type = classLoader.loadClass(externalName);
387                        if (test.matches(type)) {
388                            matches.add((Class<T>)type);
389                        }
390                        found = true;
391                        break;
392                    } catch (ClassNotFoundException e) {
393                        LOG.debug("Could not find class '" + fqn + "' in class loader: " + classLoader
394                                  + ". Reason: " + e, e);
395                    }
396                }
397                if (!found) {
398                    LOG.warn("Could not find class '" + fqn + "' in any class loaders: " + set);
399                }
400            } catch (Throwable t) {
401                LOG.warn("Could not examine class '" + fqn + "' due to a " + t.getClass().getName()
402                         + " with message: " + t.getMessage());
403            }
404        }
405    }