diff --git a/src/main/java/de/dhbwstuttgart/environment/DirectoryClassLoader.java b/src/main/java/de/dhbwstuttgart/environment/DirectoryClassLoader.java index 0b69dead..8fba019a 100644 --- a/src/main/java/de/dhbwstuttgart/environment/DirectoryClassLoader.java +++ b/src/main/java/de/dhbwstuttgart/environment/DirectoryClassLoader.java @@ -5,31 +5,61 @@ import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; -import java.nio.file.Files; -import java.nio.file.Path; +import java.nio.file.*; +import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class DirectoryClassLoader extends URLClassLoader implements IByteArrayClassLoader { - public DirectoryClassLoader(File directory, java.lang.ClassLoader parent) { - super(generateURLArray(dirToURL(directory)), parent); - } +// public DirectoryClassLoader(File directory, java.lang.ClassLoader parent) { +// super(generateURLArray(dirToURL(directory)), parent); +// } public DirectoryClassLoader(List directory, java.lang.ClassLoader parent) { - super(directory.stream().map(DirectoryClassLoader::dirToURL).collect(Collectors.toList()).toArray(new URL[0]), parent); + super(directory.stream().map(DirectoryClassLoader::dirToURL).flatMap(List::stream).collect(Collectors.toList()).toArray(new URL[0]), parent.getParent()); } private static URL[] generateURLArray(URL url) { return new URL[]{url}; } - private static URL dirToURL(File url){ + private static List dirToURL(File file) { //if(!url.isDirectory())throw new RuntimeException(url.toString() + " is not a directory"); - try { - return url.toURI().toURL(); - } catch (MalformedURLException e) { - throw new RuntimeException(e); + + Path dir; + if (file.isDirectory()) { + try { + return List.of(file.toURI().toURL()); // if file is a directory, use it as is + } catch (MalformedURLException e) { + e.printStackTrace(); + return List.of(); + } } + + dir = file.toPath().getParent(); // if file is not a directory, get its parent directory + String pattern = file.toPath().getFileName().toString(); // use the file name as a glob pattern + + List urls = new ArrayList<>(); + + try { + urls = Files.walk(dir) + .filter(Files::isRegularFile) // only consider files (not directories) + .filter(path -> { + PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern); + return matcher.matches(path.getFileName()); // match the file name against the pattern + }) + .map(path -> { + try { + return path.toUri().toURL(); + } catch (MalformedURLException e) { + throw new RuntimeException(e); + } + }) // convert the path to a URL + .toList(); // print the path of each matching file + } catch (IOException | RuntimeException e) { + e.printStackTrace(); + } + return urls; } @Override