- public static Set<File> findOnCP(String namePattern) {
- ClassLoader loader = TestUtility.class.getClassLoader();
- File f;
- Pattern p = Pattern.compile(namePattern);
- Set<File> selected = new HashSet<File>();
- Set<String> stuffOnClassPath = new HashSet<String>();
- //take all URLs on the CP
- if (loader instanceof URLClassLoader) {
- URLClassLoader uLoader = (URLClassLoader) loader;
- for (URL url : uLoader.getURLs()) {
- if ("file".equals(url.getProtocol())) {
- //this is a file somewhere on the CP
- try {
- stuffOnClassPath.add(new File(url.toURI()).getCanonicalPath());
- } catch (Exception e) {
- throw new IllegalStateException("something went horribly wrong",e);
- }
- }
- }
- }
- //another approach
- String[] elements = System.getProperty("java.class.path").split(File.pathSeparator);
- stuffOnClassPath.addAll(Arrays.asList(elements));
- if (elements.length==1) {
- //on windows this is a workaround for long paths
- File jarFile = new File(elements[0]);
- if (jarFile.exists() && jarFile.canRead()) {
- try {
- JarInputStream is = new JarInputStream(new FileInputStream(jarFile));
- stuffOnClassPath.addAll(Arrays.asList(is.getManifest().getMainAttributes().getValue("Class-Path").split("[\\s]+")));
- } catch (Exception e) {
- throw new IllegalStateException(e);
- }
- }
- }
- for (String fileName : stuffOnClassPath) {
- try {
- f = new File(fileName);
- if (!f.exists()) {
- try {
- f = new File(new URI(fileName));
- } catch (URISyntaxException e) {
- continue;
- }
- }
- if (!f.exists()) {
- continue;
- }
- if (p.matcher(f.getName()).matches()) {
- selected.add(f);
- }
- } catch (Exception e) {
- throw new IllegalStateException(e);
- }
- }
- System.out.println("search for "+namePattern+" produced "+selected.size()+" results");
- if (selected.isEmpty()) {
- return Collections.emptySet();
- }
- return selected;
- }