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 package info.magnolia.resourceloader.file;
35
36 import java.io.File;
37 import java.io.IOException;
38 import java.nio.file.DirectoryStream;
39 import java.nio.file.Path;
40 import java.nio.file.PathMatcher;
41 import java.nio.file.Paths;
42 import java.util.ArrayList;
43 import java.util.List;
44 import java.util.function.Predicate;
45 import java.util.regex.Pattern;
46
47 import org.apache.commons.io.FilenameUtils;
48
49
50
51
52
53
54
55
56 public class ExclusionsFilter implements Predicate<Path>, DirectoryStream.Filter<Path> {
57
58 private final Path rootPath;
59 private final List<String> excludePatterns;
60
61
62
63
64
65
66
67
68 public ExclusionsFilter(Path rootPath, List<String> excludedDirectories, List<String> excludedExtensions, List<String> otherPatterns) {
69 this.rootPath = validateRootPath(rootPath);
70 this.excludePatterns = new ArrayList<>();
71 addDirectoryExcludes(excludePatterns, excludedDirectories);
72 addExtensionExcludes(excludePatterns, excludedExtensions);
73 addPatternList(excludePatterns, otherPatterns);
74 }
75
76 @Override
77 public boolean accept(Path entry) throws IOException {
78 return test(entry);
79 }
80
81 @Override
82 public boolean test(Path dir) {
83
84 Path normalizedDir = Paths.get(FilenameUtils.normalize(dir.toString()));
85 if (!normalizedDir.isAbsolute() || !normalizedDir.startsWith(rootPath)) {
86 return false;
87 }
88
89 Path rel = rootPath.relativize(normalizedDir);
90
91
92 for (String excludePattern : excludePatterns) {
93 final PathMatcher matcher = normalizedDir.getFileSystem().getPathMatcher(excludePattern);
94 if (matcher.matches(rel)) {
95 return false;
96 }
97 }
98
99 return true;
100 }
101
102 private Path validateRootPath(Path rootPath) {
103 Path normalizedPath = Paths.get(FilenameUtils.normalize(rootPath.toString()));
104 if (!normalizedPath.isAbsolute()) {
105 throw new IllegalStateException(rootPath + " is not an absolute Path.");
106 }
107 return normalizedPath;
108 }
109
110 private void addDirectoryExcludes(List<String> excludePatterns, List<String> excludedDirectories) {
111 for (String directory : excludedDirectories) {
112 excludePatterns.add("regex:(^|.*" + (File.separator.replace("\\", "\\\\")) + ")" + Pattern.quote(directory) + "($|" + (File.separator.replace("\\", "\\\\")) + ".*)");
113 }
114 }
115
116 private void addExtensionExcludes(List<String> excludePatterns, List<String> excludedExtensions) {
117 for (String ext : excludedExtensions) {
118 excludePatterns.add("regex:.*\\." + Pattern.quote(ext) + "$");
119 }
120 }
121
122 private void addPatternList(List<String> excludePatterns, List<String> stringPatterns) {
123 for (String pattern : stringPatterns) {
124 if (pattern.startsWith("glob:") || pattern.startsWith("regex:")) {
125 excludePatterns.add(pattern);
126 } else {
127 excludePatterns.add("regex:" + pattern);
128 }
129 }
130 }
131
132 }