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