private static List<String> getClassesUnder(File directory, String packageName) { List<String> classes = new ArrayList<>(); if (!directory.exists()) { return classes; } File[] files = directory.listFiles(); if (files != null) { for (File file : files) { if (file.isDirectory()) { classes.addAll(getClassesUnder(file, in(packageName, file.getName()))); } else if (isClass(file.getName())) { classes.add(in(packageName, trimClass(file.getName()))); } } } return classes; }
private static void walkJars(List<String> classNames, String packageName, List<JarInputStream> jars) throws IOException { for (JarInputStream jarFile : jars) { try { JarEntry entry; while ((entry = jarFile.getNextJarEntry()) != null) { String name = toPackage(entry.getName()); if (name.startsWith(packageName) && isClass(name)) { classNames.add(trimClass(name)); } } } finally { if (jarFile != null) { jarFile.close(); } } } }
List<String> classNames = new ArrayList<>(); try { Enumeration<URL> resources = classLoader.getResources(toPath(packageName)); List<File> dirs = new ArrayList<>(); List<JarInputStream> jars = new ArrayList<>(); while (resources.hasMoreElements()) { URL resource = resources.nextElement(); if (isJar(resource)) { jars.add(new JarInputStream(new FileInputStream(URLDecoder.decode(getJarName(resource), "UTF-8")))); } else if (containsJar(resource)) { jars.add(getContainingResource(classLoader, resource)); } else { dirs.add(new File(URLDecoder.decode(resource.getFile(), "UTF-8"))); walkJars(classNames, packageName, jars); walkDirs(classNames, packageName, dirs); } catch (IOException exception) { log.error(
private static void walkDirs(List<String> classNames, String packageName, List<File> dirs) throws IOException { for (File directory : dirs) { if (directory.exists()) { classNames.addAll(getClassesUnder(directory, packageName)); } } }
/** * Discover mappers and populate internal registry. The classloading * environment is scanned for classes contained under the * org.ovirt.engine.api.restapi.types package and exposing methods decorated * with the @Mapping annotation. */ public void populate() { String packageName = discoverPackageName != null? discoverPackageName: this.getClass().getPackage().getName(); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); List<String> classNames = PackageExplorer.discoverClasses(packageName); for (String className : classNames) { try { Class<?> mapperClass = classLoader.loadClass(className); for (Method method : mapperClass.getMethods()) { Mapping mapping = method.getAnnotation(Mapping.class); if (mapping != null) { mappers.put(new ClassPairKey(mapping.from(), mapping.to()), new MethodInvokerMapper(method, mapping.to())); } } } catch (ClassNotFoundException exception) { log.error( "Error while trying to load mapper class \"{}\".", className, exception ); } } }