1 /*
2 * Copyright 2009-2021 the original author or authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.apache.ibatis.io;
17
18 import java.io.IOException;
19 import java.lang.annotation.Annotation;
20 import java.util.HashSet;
21 import java.util.List;
22 import java.util.Set;
23
24 import org.apache.ibatis.logging.Log;
25 import org.apache.ibatis.logging.LogFactory;
26
27 /**
28 * <p>ResolverUtil is used to locate classes that are available in the/a class path and meet
29 * arbitrary conditions. The two most common conditions are that a class implements/extends
30 * another class, or that is it annotated with a specific annotation. However, through the use
31 * of the {@link Test} class it is possible to search using arbitrary conditions.</p>
32 *
33 * <p>A ClassLoader is used to locate all locations (directories and jar files) in the class
34 * path that contain classes within certain packages, and then to load those classes and
35 * check them. By default the ClassLoader returned by
36 * {@code Thread.currentThread().getContextClassLoader()} is used, but this can be overridden
37 * by calling {@link #setClassLoader(ClassLoader)} prior to invoking any of the {@code find()}
38 * methods.</p>
39 *
40 * <p>General searches are initiated by calling the {@link #find(Test, String)} and supplying
41 * a package name and a Test instance. This will cause the named package <b>and all sub-packages</b>
42 * to be scanned for classes that meet the test. There are also utility methods for the common
43 * use cases of scanning multiple packages for extensions of particular classes, or classes
44 * annotated with a specific annotation.</p>
45 *
46 * <p>The standard usage pattern for the ResolverUtil class is as follows:</p>
47 *
48 * <pre>
49 * ResolverUtil<ActionBean> resolver = new ResolverUtil<ActionBean>();
50 * resolver.findImplementation(ActionBean.class, pkg1, pkg2);
51 * resolver.find(new CustomTest(), pkg1);
52 * resolver.find(new CustomTest(), pkg2);
53 * Collection<ActionBean> beans = resolver.getClasses();
54 * </pre>
55 *
56 * @author Tim Fennell
57 * @param <T>
58 * the generic type
59 */
60 public class ResolverUtil<T> {
61
62 /**
63 * An instance of Log to use for logging in this class.
64 */
65 private static final Log log = LogFactory.getLog(ResolverUtil.class);
66
67 /**
68 * A simple interface that specifies how to test classes to determine if they
69 * are to be included in the results produced by the ResolverUtil.
70 */
71 public interface Test {
72
73 /**
74 * Will be called repeatedly with candidate classes. Must return True if a class
75 * is to be included in the results, false otherwise.
76 *
77 * @param type
78 * the type
79 * @return true, if successful
80 */
81 boolean matches(Class<?> type);
82 }
83
84 /**
85 * A Test that checks to see if each class is assignable to the provided class. Note
86 * that this test will match the parent type itself if it is presented for matching.
87 */
88 public static class IsA implements Test {
89
90 /** The parent. */
91 private Class<?> parent;
92
93 /**
94 * Constructs an IsA test using the supplied Class as the parent class/interface.
95 *
96 * @param parentType
97 * the parent type
98 */
99 public IsA(Class<?> parentType) {
100 this.parent = parentType;
101 }
102
103 /** Returns true if type is assignable to the parent type supplied in the constructor. */
104 @Override
105 public boolean matches(Class<?> type) {
106 return type != null && parent.isAssignableFrom(type);
107 }
108
109 @Override
110 public String toString() {
111 return "is assignable to " + parent.getSimpleName();
112 }
113 }
114
115 /**
116 * A Test that checks to see if each class is annotated with a specific annotation. If it
117 * is, then the test returns true, otherwise false.
118 */
119 public static class AnnotatedWith implements Test {
120
121 /** The annotation. */
122 private Class<? extends Annotation> annotation;
123
124 /**
125 * Constructs an AnnotatedWith test for the specified annotation type.
126 *
127 * @param annotation
128 * the annotation
129 */
130 public AnnotatedWith(Class<? extends Annotation> annotation) {
131 this.annotation = annotation;
132 }
133
134 /** Returns true if the type is annotated with the class provided to the constructor. */
135 @Override
136 public boolean matches(Class<?> type) {
137 return type != null && type.isAnnotationPresent(annotation);
138 }
139
140 @Override
141 public String toString() {
142 return "annotated with @" + annotation.getSimpleName();
143 }
144 }
145
146 /** The set of matches being accumulated. */
147 private Set<Class<? extends T>> matches = new HashSet<>();
148
149 /**
150 * The ClassLoader to use when looking for classes. If null then the ClassLoader returned
151 * by Thread.currentThread().getContextClassLoader() will be used.
152 */
153 private ClassLoader classloader;
154
155 /**
156 * Provides access to the classes discovered so far. If no calls have been made to
157 * any of the {@code find()} methods, this set will be empty.
158 *
159 * @return the set of classes that have been discovered.
160 */
161 public Set<Class<? extends T>> getClasses() {
162 return matches;
163 }
164
165 /**
166 * Returns the classloader that will be used for scanning for classes. If no explicit
167 * ClassLoader has been set by the calling, the context class loader will be used.
168 *
169 * @return the ClassLoader that will be used to scan for classes
170 */
171 public ClassLoader getClassLoader() {
172 return classloader == null ? Thread.currentThread().getContextClassLoader() : classloader;
173 }
174
175 /**
176 * Sets an explicit ClassLoader that should be used when scanning for classes. If none
177 * is set then the context classloader will be used.
178 *
179 * @param classloader a ClassLoader to use when scanning for classes
180 */
181 public void setClassLoader(ClassLoader classloader) {
182 this.classloader = classloader;
183 }
184
185 /**
186 * Attempts to discover classes that are assignable to the type provided. In the case
187 * that an interface is provided this method will collect implementations. In the case
188 * of a non-interface class, subclasses will be collected. Accumulated classes can be
189 * accessed by calling {@link #getClasses()}.
190 *
191 * @param parent
192 * the class of interface to find subclasses or implementations of
193 * @param packageNames
194 * one or more package names to scan (including subpackages) for classes
195 * @return the resolver util
196 */
197 public ResolverUtil<T> findImplementations(Class<?> parent, String... packageNames) {
198 if (packageNames == null) {
199 return this;
200 }
201
202 Test test = new IsA(parent);
203 for (String pkg : packageNames) {
204 find(test, pkg);
205 }
206
207 return this;
208 }
209
210 /**
211 * Attempts to discover classes that are annotated with the annotation. Accumulated
212 * classes can be accessed by calling {@link #getClasses()}.
213 *
214 * @param annotation
215 * the annotation that should be present on matching classes
216 * @param packageNames
217 * one or more package names to scan (including subpackages) for classes
218 * @return the resolver util
219 */
220 public ResolverUtil<T> findAnnotated(Class<? extends Annotation> annotation, String... packageNames) {
221 if (packageNames == null) {
222 return this;
223 }
224
225 Test test = new AnnotatedWith(annotation);
226 for (String pkg : packageNames) {
227 find(test, pkg);
228 }
229
230 return this;
231 }
232
233 /**
234 * Scans for classes starting at the package provided and descending into subpackages.
235 * Each class is offered up to the Test as it is discovered, and if the Test returns
236 * true the class is retained. Accumulated classes can be fetched by calling
237 * {@link #getClasses()}.
238 *
239 * @param test
240 * an instance of {@link Test} that will be used to filter classes
241 * @param packageName
242 * the name of the package from which to start scanning for classes, e.g. {@code net.sourceforge.stripes}
243 * @return the resolver util
244 */
245 public ResolverUtil<T> find(Test test, String packageName) {
246 String path = getPackagePath(packageName);
247
248 try {
249 List<String> children = VFS.getInstance().list(path);
250 for (String child : children) {
251 if (child.endsWith(".class")) {
252 addIfMatching(test, child);
253 }
254 }
255 } catch (IOException ioe) {
256 log.error("Could not read package: " + packageName, ioe);
257 }
258
259 return this;
260 }
261
262 /**
263 * Converts a Java package name to a path that can be looked up with a call to
264 * {@link ClassLoader#getResources(String)}.
265 *
266 * @param packageName
267 * The Java package name to convert to a path
268 * @return the package path
269 */
270 protected String getPackagePath(String packageName) {
271 return packageName == null ? null : packageName.replace('.', '/');
272 }
273
274 /**
275 * Add the class designated by the fully qualified class name provided to the set of
276 * resolved classes if and only if it is approved by the Test supplied.
277 *
278 * @param test the test used to determine if the class matches
279 * @param fqn the fully qualified name of a class
280 */
281 @SuppressWarnings("unchecked")
282 protected void addIfMatching(Test test, String fqn) {
283 try {
284 String externalName = fqn.substring(0, fqn.indexOf('.')).replace('/', '.');
285 ClassLoader loader = getClassLoader();
286 if (log.isDebugEnabled()) {
287 log.debug("Checking to see if class " + externalName + " matches criteria [" + test + "]");
288 }
289
290 Class<?> type = loader.loadClass(externalName);
291 if (test.matches(type)) {
292 matches.add((Class<T>) type);
293 }
294 } catch (Throwable t) {
295 log.warn("Could not examine class '" + fqn + "'" + " due to a "
296 + t.getClass().getName() + " with message: " + t.getMessage());
297 }
298 }
299 }