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