/
SimpleFileResolver.java
64 lines (57 loc) · 1.98 KB
/
SimpleFileResolver.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package dk.netarkivet.common.utils;
import java.io.File;
import java.io.FilenameFilter;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A simple file resolver for resolving local files against a parent directory to get
* Path objects representing these files
*/
public class SimpleFileResolver implements FileResolver {
private static final Logger log = LoggerFactory.getLogger(SimpleFileResolver.class);
Path directory;
public void setDirectory(Path directory) {
this.directory = directory;
}
public SimpleFileResolver(Path directory) {
this.directory = directory;
}
@Override public List<Path> getPaths(Pattern filepattern) {
PathMatcher globPattern = FileSystems.getDefault().getPathMatcher("regex:" + filepattern);
File[] dirContents = new File(directory.toString()).listFiles(
new FilenameFilter() {
@Override public boolean accept(File dir, String name) {
return globPattern.matches(Paths.get(name));
}
}
);
if (dirContents == null) {
log.debug("No files found in directory '{}'. Returning empty list.", directory);
return Collections.emptyList();
}
List<Path> result = new ArrayList<>();
for (File file : dirContents) {
if (file.isFile()) {
Path filePath = getPath(file.getName());
log.debug("Adding path '{}'", filePath);
result.add(filePath);
}
}
return result;
}
@Override public Path getPath(String filename) {
Path path = directory.resolve(filename);
if (!path.toFile().exists()) {
return null;
}
return path;
}
}