public static File copyResources( ClassLoader classLoader, String rootPath, File toDir, Function<String, String> relocationFunction) { Collection<String> relativePaths = listFiles(classLoader, rootPath); for (String relativePath : relativePaths) { URL resource = classLoader.getResource(relativePath); String filename = relocationFunction.apply(relativePath); File toFile = new File(toDir, filename); try { FileUtils.copyURLToFile(resource, toFile); } catch (IOException e) { throw new IllegalStateException( "Fail to extract " + relativePath + " to " + toFile.getAbsolutePath()); } } return toDir; }
/** * Finds directories and files within a given directory and its subdirectories. * * @param classLoader * @param rootPath the root directory, for example org/sonar/sqale, or a file in this root * directory, for example org/sonar/sqale/index.txt * @param * @return a list of relative paths, for example {"org/sonar/sqale", "org/sonar/sqale/foo", * "org/sonar/sqale/foo/bar.txt}. Never null. */ public static Collection<String> listResources( ClassLoader classLoader, String rootPath, Predicate<String> predicate) { String jarPath = null; JarFile jar = null; try { Collection<String> paths = Lists.newArrayList(); rootPath = StringUtils.removeStart(rootPath, "/"); URL root = classLoader.getResource(rootPath); if (root != null) { checkJarFile(root); // Path of the root directory // Examples : // org/sonar/sqale/index.txt -> rootDirectory is org/sonar/sqale // org/sonar/sqale/ -> rootDirectory is org/sonar/sqale // org/sonar/sqale -> rootDirectory is org/sonar/sqale String rootDirectory = rootPath; if (StringUtils.substringAfterLast(rootPath, "/").indexOf('.') >= 0) { rootDirectory = StringUtils.substringBeforeLast(rootPath, "/"); } jarPath = root.getPath().substring(5, root.getPath().indexOf("!")); // strip out only the JAR file jar = new JarFile(URLDecoder.decode(jarPath, CharEncoding.UTF_8)); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { String name = entries.nextElement().getName(); if (name.startsWith(rootDirectory) && predicate.apply(name)) { paths.add(name); } } } return paths; } catch (Exception e) { throw Throwables.propagate(e); } finally { closeJar(jar, jarPath); } }