001 /**
002 *
003 * Licensed to the Apache Software Foundation (ASF) under one or more
004 * contributor license agreements. See the NOTICE file distributed with
005 * this work for additional information regarding copyright ownership.
006 * The ASF licenses this file to You under the Apache License, Version 2.0
007 * (the "License"); you may not use this file except in compliance with
008 * the License. You may obtain a copy of the License at
009 *
010 * http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018 package org.apache.camel.util;
019
020 import org.apache.commons.logging.Log;
021 import org.apache.commons.logging.LogFactory;
022
023 import java.lang.annotation.Annotation;
024 import java.util.Set;
025 import java.util.HashSet;
026 import java.util.Enumeration;
027 import java.util.jar.JarEntry;
028 import java.util.jar.JarInputStream;
029 import java.net.URL;
030 import java.net.URLDecoder;
031 import java.io.IOException;
032 import java.io.File;
033 import java.io.FileInputStream;
034
035 /**
036 * <p>ResolverUtil is used to locate classes that are available in the/a class path and meet
037 * arbitrary conditions. The two most common conditions are that a class implements/extends
038 * another class, or that is it annotated with a specific annotation. However, through the use
039 * of the {@link Test} class it is possible to search using arbitrary conditions.</p>
040 *
041 * <p>A ClassLoader is used to locate all locations (directories and jar files) in the class
042 * path that contain classes within certain packages, and then to load those classes and
043 * check them. By default the ClassLoader returned by
044 * {@code Thread.currentThread().getContextClassLoader()} is used, but this can be overridden
045 * by calling {@link #setClassLoader(ClassLoader)} prior to invoking any of the {@code find()}
046 * methods.</p>
047 *
048 * <p>General searches are initiated by calling the
049 * {@link #find(ResolverUtil.Test, String)} ()} method and supplying
050 * a package name and a Test instance. This will cause the named package <b>and all sub-packages</b>
051 * to be scanned for classes that meet the test. There are also utility methods for the common
052 * use cases of scanning multiple packages for extensions of particular classes, or classes
053 * annotated with a specific annotation.</p>
054 *
055 * <p>The standard usage pattern for the ResolverUtil class is as follows:</p>
056 *
057 *<pre>
058 *ResolverUtil<ActionBean> resolver = new ResolverUtil<ActionBean>();
059 *resolver.findImplementation(ActionBean.class, pkg1, pkg2);
060 *resolver.find(new CustomTest(), pkg1);
061 *resolver.find(new CustomTest(), pkg2);
062 *Collection<ActionBean> beans = resolver.getClasses();
063 *</pre>
064 *
065 * @author Tim Fennell
066 */
067 public class ResolverUtil<T> {
068 private static final transient Log log = LogFactory.getLog(ResolverUtil.class);
069
070 /**
071 * A simple interface that specifies how to test classes to determine if they
072 * are to be included in the results produced by the ResolverUtil.
073 */
074 public static interface Test {
075 /**
076 * Will be called repeatedly with candidate classes. Must return True if a class
077 * is to be included in the results, false otherwise.
078 */
079 boolean matches(Class type);
080 }
081
082 /**
083 * A Test that checks to see if each class is assignable to the provided class. Note
084 * that this test will match the parent type itself if it is presented for matching.
085 */
086 public static class IsA implements Test {
087 private Class parent;
088
089 /** Constructs an IsA test using the supplied Class as the parent class/interface. */
090 public IsA(Class parentType) { this.parent = parentType; }
091
092 /** Returns true if type is assignable to the parent type supplied in the constructor. */
093 public boolean matches(Class type) {
094 return type != null && parent.isAssignableFrom(type);
095 }
096
097 @Override public String toString() {
098 return "is assignable to " + parent.getSimpleName();
099 }
100 }
101
102 /**
103 * A Test that checks to see if each class is annotated with a specific annotation. If it
104 * is, then the test returns true, otherwise false.
105 */
106 public static class AnnotatedWith implements Test {
107 private Class<? extends Annotation> annotation;
108
109 /** Construts an AnnotatedWith test for the specified annotation type. */
110 public AnnotatedWith(Class<? extends Annotation> annotation) { this.annotation = annotation; }
111
112 /** Returns true if the type is annotated with the class provided to the constructor. */
113 public boolean matches(Class type) {
114 return type != null && type.isAnnotationPresent(annotation);
115 }
116
117 @Override public String toString() {
118 return "annotated with @" + annotation.getSimpleName();
119 }
120 }
121
122 /** The set of matches being accumulated. */
123 private Set<Class<? extends T>> matches = new HashSet<Class<?extends T>>();
124
125 /**
126 * The ClassLoader to use when looking for classes. If null then the ClassLoader returned
127 * by Thread.currentThread().getContextClassLoader() will be used.
128 */
129 private ClassLoader classloader;
130
131 /**
132 * Provides access to the classes discovered so far. If no calls have been made to
133 * any of the {@code find()} methods, this set will be empty.
134 *
135 * @return the set of classes that have been discovered.
136 */
137 public Set<Class<? extends T>> getClasses() {
138 return matches;
139 }
140
141 /**
142 * Returns the classloader that will be used for scanning for classes. If no explicit
143 * ClassLoader has been set by the calling, the context class loader will be used.
144 *
145 * @return the ClassLoader that will be used to scan for classes
146 */
147 public ClassLoader getClassLoader() {
148 return classloader == null ? Thread.currentThread().getContextClassLoader() : classloader;
149 }
150
151 /**
152 * Sets an explicit ClassLoader that should be used when scanning for classes. If none
153 * is set then the context classloader will be used.
154 *
155 * @param classloader a ClassLoader to use when scanning for classes
156 */
157 public void setClassLoader(ClassLoader classloader) { this.classloader = classloader; }
158
159 /**
160 * Attempts to discover classes that are assignable to the type provided. In the case
161 * that an interface is provided this method will collect implementations. In the case
162 * of a non-interface class, subclasses will be collected. Accumulated classes can be
163 * accessed by calling {@link #getClasses()}.
164 *
165 * @param parent the class of interface to find subclasses or implementations of
166 * @param packageNames one or more package names to scan (including subpackages) for classes
167 */
168 public void findImplementations(Class parent, String... packageNames) {
169 if (packageNames == null) return;
170
171 Test test = new IsA(parent);
172 for (String pkg : packageNames) {
173 find(test, pkg);
174 }
175 }
176
177 /**
178 * Attempts to discover classes that are annotated with to the annotation. Accumulated
179 * classes can be accessed by calling {@link #getClasses()}.
180 *
181 * @param annotation the annotation that should be present on matching classes
182 * @param packageNames one or more package names to scan (including subpackages) for classes
183 */
184 public void findAnnotated(Class<? extends Annotation> annotation, String... packageNames) {
185 if (packageNames == null) return;
186
187 Test test = new AnnotatedWith(annotation);
188 for (String pkg : packageNames) {
189 find(test, pkg);
190 }
191 }
192
193 /**
194 * Scans for classes starting at the package provided and descending into subpackages.
195 * Each class is offered up to the Test as it is discovered, and if the Test returns
196 * true the class is retained. Accumulated classes can be fetched by calling
197 * {@link #getClasses()}.
198 *
199 * @param test an instance of {@link Test} that will be used to filter classes
200 * @param packageName the name of the package from which to start scanning for
201 * classes, e.g. {@code net.sourceforge.stripes}
202 */
203 public void find(Test test, String packageName) {
204 packageName = packageName.replace('.', '/');
205 ClassLoader loader = getClassLoader();
206 Enumeration<URL> urls;
207
208 try {
209 urls = loader.getResources(packageName);
210 }
211 catch (IOException ioe) {
212 log.warn("Could not read package: " + packageName, ioe);
213 return;
214 }
215
216 while (urls.hasMoreElements()) {
217 try {
218 String urlPath = urls.nextElement().getFile();
219 urlPath = URLDecoder.decode(urlPath, "UTF-8");
220
221 // If it's a file in a directory, trim the stupid file: spec
222 if ( urlPath.startsWith("file:") ) {
223 urlPath = urlPath.substring(5);
224 }
225
226 // Else it's in a JAR, grab the path to the jar
227 if (urlPath.indexOf('!') > 0) {
228 urlPath = urlPath.substring(0, urlPath.indexOf('!'));
229 }
230
231 log.debug("Scanning for classes in [" + urlPath + "] matching criteria: " + test);
232 File file = new File(urlPath);
233 if ( file.isDirectory() ) {
234 loadImplementationsInDirectory(test, packageName, file);
235 }
236 else {
237 loadImplementationsInJar(test, packageName, file);
238 }
239 }
240 catch (IOException ioe) {
241 log.warn("could not read entries", ioe);
242 }
243 }
244 }
245
246
247 /**
248 * Finds matches in a physical directory on a filesystem. Examines all
249 * files within a directory - if the File object is not a directory, and ends with <i>.class</i>
250 * the file is loaded and tested to see if it is acceptable according to the Test. Operates
251 * recursively to find classes within a folder structure matching the package structure.
252 *
253 * @param test a Test used to filter the classes that are discovered
254 * @param parent the package name up to this directory in the package hierarchy. E.g. if
255 * /classes is in the classpath and we wish to examine files in /classes/org/apache then
256 * the values of <i>parent</i> would be <i>org/apache</i>
257 * @param location a File object representing a directory
258 */
259 private void loadImplementationsInDirectory(Test test, String parent, File location) {
260 File[] files = location.listFiles();
261 StringBuilder builder = null;
262
263 for (File file : files) {
264 builder = new StringBuilder(100);
265 builder.append(parent).append("/").append(file.getName());
266 String packageOrClass = ( parent == null ? file.getName() : builder.toString() );
267
268 if (file.isDirectory()) {
269 loadImplementationsInDirectory(test, packageOrClass, file);
270 }
271 else if (file.getName().endsWith(".class")) {
272 addIfMatching(test, packageOrClass);
273 }
274 }
275 }
276
277 /**
278 * Finds matching classes within a jar files that contains a folder structure
279 * matching the package structure. If the File is not a JarFile or does not exist a warning
280 * will be logged, but no error will be raised.
281 *
282 * @param test a Test used to filter the classes that are discovered
283 * @param parent the parent package under which classes must be in order to be considered
284 * @param jarfile the jar file to be examined for classes
285 */
286 private void loadImplementationsInJar(Test test, String parent, File jarfile) {
287
288 try {
289 JarEntry entry;
290 JarInputStream jarStream = new JarInputStream(new FileInputStream(jarfile));
291
292 while ( (entry = jarStream.getNextJarEntry() ) != null) {
293 String name = entry.getName();
294 if (!entry.isDirectory() && name.startsWith(parent) && name.endsWith(".class")) {
295 addIfMatching(test, name);
296 }
297 }
298 }
299 catch (IOException ioe) {
300 log.error("Could not search jar file '" + jarfile + "' for classes matching criteria: " +
301 test + "due to an IOException: " + ioe.getMessage());
302 }
303 }
304
305 /**
306 * Add the class designated by the fully qualified class name provided to the set of
307 * resolved classes if and only if it is approved by the Test supplied.
308 *
309 * @param test the test used to determine if the class matches
310 * @param fqn the fully qualified name of a class
311 */
312 protected void addIfMatching(Test test, String fqn) {
313 try {
314 String externalName = fqn.substring(0, fqn.indexOf('.')).replace('/', '.');
315 ClassLoader loader = getClassLoader();
316 log.trace("Checking to see if class " + externalName + " matches criteria [" + test+ "]");
317
318 Class type = loader.loadClass(externalName);
319 if (test.matches(type) ) {
320 matches.add( (Class<T>) type);
321 }
322 }
323 catch (Throwable t) {
324 log.warn("Could not examine class '"+ fqn + "' due to a " +
325 t.getClass().getName()+ " with message: " + t.getMessage());
326 }
327 }
328 }