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