1 package org.jadira.scanner.file.projector;
2
3 import java.io.File;
4 import java.util.ArrayList;
5 import java.util.List;
6
7 import org.jadira.scanner.core.api.Projector;
8 import org.jadira.scanner.core.exception.FileAccessException;
9 import org.jadira.scanner.core.helper.FileUtils;
10 import org.jadira.scanner.core.helper.filenamefilter.AntPathFilter;
11
12 public class AntPathProjector implements Projector<File> {
13
14 private String path;
15
16 public AntPathProjector(String path) {
17 this.path = path;
18 }
19
20 @Override
21 public List<File> project(File segment) {
22
23 final List<File> files;
24
25 AntPathFilter antPathMatcher = new AntPathFilter(path);
26 if (antPathMatcher.isPatterned()) {
27 files = findFilesForPatternPath(segment, path);
28 } else {
29 files = findFilesForActualPath(segment, path);
30 }
31 return files;
32 }
33
34 private List<File> findFilesForPatternPath(File parentFile, String pattern) throws FileAccessException {
35
36 final List<File> files = new ArrayList<File>();
37
38 AntPathFilter antPathMatcher = new AntPathFilter(pattern);
39 if (antPathMatcher.match(AntPathFilter.PATH_SEPARATOR) || antPathMatcher.match("")) {
40 files.add(parentFile);
41 } else {
42 findFilesForPatternRecursively(pattern, files, parentFile, parentFile);
43 }
44 return files;
45 }
46
47 private List<File> findFilesForActualPath(File parentFile, String path) {
48
49 final List<File> files = new ArrayList<File>();
50 File nextFile = FileUtils.getFileForPathName(path, parentFile);
51 if ((nextFile != null) && nextFile.isFile()) {
52 files.add(nextFile);
53 }
54 return files;
55 }
56
57 private void findFilesForPatternRecursively(String pattern, final List<File> resultsHolder, File root, File currentParent) {
58
59 if (currentParent.isDirectory()) {
60 File[] childFiles = currentParent.listFiles();
61 for (File next : childFiles) {
62 String currentPath = next.getPath().substring(root.getPath().length());
63 if (next.isDirectory() && (!currentPath.endsWith(AntPathFilter.PATH_SEPARATOR))) {
64 currentPath = currentPath + AntPathFilter.PATH_SEPARATOR;
65 }
66 AntPathFilter antPathMatcher = new AntPathFilter(pattern);
67 if (antPathMatcher.match(currentPath)) {
68 resultsHolder.add(next);
69 } else if (antPathMatcher.matchStart(currentPath)) {
70 findFilesForPatternRecursively(pattern, resultsHolder, root, currentParent);
71 }
72 }
73 }
74 }
75 }