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