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<ActionBean> resolver = new ResolverUtil<ActionBean>();
069 * esolver.findImplementation(ActionBean.class, pkg1, pkg2);
070 * esolver.find(new CustomTest(), pkg1);
071 * esolver.find(new CustomTest(), pkg2);
072 * ollection<ActionBean> 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 /**
130 * Constructs an AnnotatedWith test for the specified annotation type.
131 */
132 public AnnotatedWith(Class<? extends Annotation> annotation) {
133 this.annotation = annotation;
134 }
135
136 /**
137 * Returns true if the type is annotated with the class provided to the
138 * constructor.
139 */
140 public boolean matches(Class type) {
141 return type != null && type.isAnnotationPresent(annotation);
142 }
143
144 @Override
145 public String toString() {
146 return "annotated with @" + annotation.getSimpleName();
147 }
148 }
149
150 /** The set of matches being accumulated. */
151 private Set<Class<? extends T>> matches = new HashSet<Class<? extends T>>();
152
153 /**
154 * The ClassLoader to use when looking for classes. If null then the
155 * ClassLoader returned by Thread.currentThread().getContextClassLoader()
156 * will be used.
157 */
158 private Set<ClassLoader> classLoaders;
159
160 /**
161 * Provides access to the classes discovered so far. If no calls have been
162 * made to any of the {@code find()} methods, this set will be empty.
163 *
164 * @return the set of classes that have been discovered.
165 */
166 public Set<Class<? extends T>> getClasses() {
167 return matches;
168 }
169
170
171 /**
172 * Returns the classloaders that will be used for scanning for classes. If no
173 * explicit ClassLoader has been set by the calling, the context class
174 * loader will be used.
175 *
176 * @return the ClassLoader instances that will be used to scan for classes
177 */
178 public Set<ClassLoader> getClassLoaders() {
179 if (classLoaders == null) {
180 classLoaders = new HashSet<ClassLoader>();
181 classLoaders.add(Thread.currentThread().getContextClassLoader());
182 }
183 return classLoaders;
184 }
185
186 /**
187 * Sets the ClassLoader instances that should be used when scanning for
188 * classes. If none is set then the context classloader will be used.
189 *
190 * @param classLoaders a ClassLoader to use when scanning for classes
191 */
192 public void setClassLoaders(Set<ClassLoader> classLoaders) {
193 this.classLoaders = classLoaders;
194 }
195
196 /**
197 * Attempts to discover classes that are assignable to the type provided. In
198 * the case that an interface is provided this method will collect
199 * implementations. In the case of a non-interface class, subclasses will be
200 * collected. Accumulated classes can be accessed by calling
201 * {@link #getClasses()}.
202 *
203 * @param parent the class of interface to find subclasses or
204 * implementations of
205 * @param packageNames one or more package names to scan (including
206 * subpackages) for classes
207 */
208 public void findImplementations(Class parent, String... packageNames) {
209 if (packageNames == null) {
210 return;
211 }
212
213 LOG.debug("Searching for implementations of " + parent.getName() + " in packages: " + Arrays.asList(packageNames));
214
215 Test test = new IsA(parent);
216 for (String pkg : packageNames) {
217 find(test, pkg);
218 }
219
220 LOG.debug("Found: " + getClasses());
221 }
222
223 /**
224 * Attempts to discover classes that are annotated with to the annotation.
225 * Accumulated classes can be accessed by calling {@link #getClasses()}.
226 *
227 * @param annotation the annotation that should be present on matching
228 * classes
229 * @param packageNames one or more package names to scan (including
230 * subpackages) for classes
231 */
232 public void findAnnotated(Class<? extends Annotation> annotation, String... packageNames) {
233 if (packageNames == null) {
234 return;
235 }
236
237 Test test = new AnnotatedWith(annotation);
238 for (String pkg : packageNames) {
239 find(test, pkg);
240 }
241 }
242
243 /**
244 * Scans for classes starting at the package provided and descending into
245 * subpackages. Each class is offered up to the Test as it is discovered,
246 * and if the Test returns true the class is retained. Accumulated classes
247 * can be fetched by calling {@link #getClasses()}.
248 *
249 * @param test an instance of {@link Test} that will be used to filter
250 * classes
251 * @param packageName the name of the package from which to start scanning
252 * for classes, e.g. {@code net.sourceforge.stripes}
253 */
254 public void find(Test test, String packageName) {
255 packageName = packageName.replace('.', '/');
256
257 Set<ClassLoader> set = getClassLoaders();
258 for (ClassLoader classLoader : set) {
259 LOG.trace("Searching: " + classLoader);
260
261 find(test, packageName, classLoader);
262 }
263 }
264
265 protected void find(Test test, String packageName, ClassLoader loader) {
266 Enumeration<URL> urls;
267
268 try {
269 urls = loader.getResources(packageName);
270 } catch (IOException ioe) {
271 LOG.warn("Could not read package: " + packageName, ioe);
272 return;
273 }
274
275 while (urls.hasMoreElements()) {
276 try {
277 URL url = urls.nextElement();
278
279 String urlPath = url.getFile();
280 urlPath = URLDecoder.decode(urlPath, "UTF-8");
281
282 // If it's a file in a directory, trim the stupid file: spec
283 if (urlPath.startsWith("file:")) {
284 urlPath = urlPath.substring(5);
285 }
286
287 // Else it's in a JAR, grab the path to the jar
288 if (urlPath.indexOf('!') > 0) {
289 urlPath = urlPath.substring(0, urlPath.indexOf('!'));
290 }
291
292 LOG.debug("Scanning for classes in [" + urlPath + "] matching criteria: " + test);
293 File file = new File(urlPath);
294 if (file.isDirectory()) {
295 loadImplementationsInDirectory(test, packageName, file);
296 } else {
297 loadImplementationsInJar(test, packageName, file);
298 }
299 } catch (IOException ioe) {
300 LOG.warn("could not read entries", ioe);
301 }
302 }
303 }
304
305 /**
306 * Finds matches in a physical directory on a filesystem. Examines all files
307 * within a directory - if the File object is not a directory, and ends with
308 * <i>.class</i> the file is loaded and tested to see if it is acceptable
309 * according to the Test. Operates recursively to find classes within a
310 * folder structure matching the package structure.
311 *
312 * @param test a Test used to filter the classes that are discovered
313 * @param parent the package name up to this directory in the package
314 * hierarchy. E.g. if /classes is in the classpath and we
315 * wish to examine files in /classes/org/apache then the
316 * values of <i>parent</i> would be <i>org/apache</i>
317 * @param location a File object representing a directory
318 */
319 private void loadImplementationsInDirectory(Test test, String parent, File location) {
320 File[] files = location.listFiles();
321 StringBuilder builder = null;
322
323 for (File file : files) {
324 builder = new StringBuilder(100);
325 String name = file.getName();
326 if (name != null) {
327 name = name.trim();
328
329 builder.append(parent).append("/").append(name);
330 String packageOrClass = parent == null ? name : builder.toString();
331
332 if (file.isDirectory()) {
333 loadImplementationsInDirectory(test, packageOrClass, file);
334 } else if (name.endsWith(".class")) {
335 addIfMatching(test, packageOrClass);
336 }
337 }
338 }
339 }
340
341 /**
342 * Finds matching classes within a jar files that contains a folder
343 * structure matching the package structure. If the File is not a JarFile or
344 * does not exist a warning will be logged, but no error will be raised.
345 *
346 * @param test a Test used to filter the classes that are discovered
347 * @param parent the parent package under which classes must be in order to
348 * be considered
349 * @param jarfile the jar file to be examined for classes
350 */
351 private void loadImplementationsInJar(Test test, String parent, File jarfile) {
352
353 try {
354 JarEntry entry;
355 JarInputStream jarStream = new JarInputStream(new FileInputStream(jarfile));
356
357 while ((entry = jarStream.getNextJarEntry()) != null) {
358 String name = entry.getName();
359 if (name != null) {
360 name = name.trim();
361 if (!entry.isDirectory() && name.startsWith(parent) && name.endsWith(".class")) {
362 addIfMatching(test, name);
363 }
364 }
365 }
366 } catch (IOException ioe) {
367 LOG.error("Could not search jar file '" + jarfile + "' for classes matching criteria: " + test
368 + "due to an IOException: " + ioe.getMessage());
369 }
370 }
371
372 /**
373 * Add the class designated by the fully qualified class name provided to
374 * the set of resolved classes if and only if it is approved by the Test
375 * supplied.
376 *
377 * @param test the test used to determine if the class matches
378 * @param fqn the fully qualified name of a class
379 */
380 protected void addIfMatching(Test test, String fqn) {
381 try {
382 String externalName = fqn.substring(0, fqn.indexOf('.')).replace('/', '.');
383 Set<ClassLoader> set = getClassLoaders();
384 boolean found = false;
385 for (ClassLoader classLoader : set) {
386 LOG.trace("Checking to see if class " + externalName + " matches criteria [" + test + "]");
387
388 try {
389 Class type = classLoader.loadClass(externalName);
390 if (test.matches(type)) {
391 matches.add((Class<T>)type);
392 }
393 found = true;
394 break;
395 } catch (ClassNotFoundException e) {
396 LOG.debug("Could not find class '" + fqn + "' in class loader: " + classLoader
397 + ". Reason: " + e, e);
398 }
399 }
400 if (!found) {
401 LOG.warn("Could not find class '" + fqn + "' in any class loaders: " + set);
402 }
403 } catch (Throwable t) {
404 LOG.warn("Could not examine class '" + fqn + "' due to a " + t.getClass().getName()
405 + " with message: " + t.getMessage());
406 }
407 }
408 }