View Javadoc
1   /**
2    * This file Copyright (c) 2015-2017 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
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.regex.Pattern;
45  
46  import org.apache.commons.io.FilenameUtils;
47  
48  import com.google.common.base.Predicate;
49  
50  /**
51   * Predicate and DirectoryStream.Filter which checks a given Path is under the root and is able to exclude.
52   * <ul><li>directories</li>
53   * <li>file extensions</li>
54   * <li>any other pattern</li></ul>
55   * @see java.nio.file.DirectoryStream.Filter
56   */
57  public class ExclusionsFilter implements Predicate<Path>, DirectoryStream.Filter<Path> {
58  
59      private final Path rootPath;
60      private final List<String> excludePatterns;
61  
62      /**
63       * @param rootPath an absolute root path to evaluate paths against
64       * @param excludedDirectories directory names that will be excluded regardless of their location.
65       * @param excludedExtensions file extensions that will be excluded.
66       * @param otherPatterns regex or glob path patterns, relative to given <code>rootPath</code>. Defaults to regex: if no prefix is given.
67       * @see java.nio.file.FileSystem#getPathMatcher(java.lang.String)
68       */
69      public ExclusionsFilter(Path rootPath, List<String> excludedDirectories, List<String> excludedExtensions, List<String> otherPatterns) {
70          this.rootPath = validateRootPath(rootPath);
71          this.excludePatterns = new ArrayList<>();
72          addDirectoryExcludes(excludePatterns, excludedDirectories);
73          addExtensionExcludes(excludePatterns, excludedExtensions);
74          addPatternList(excludePatterns, otherPatterns);
75      }
76  
77      @Override
78      public boolean accept(Path entry) throws IOException {
79          return apply(entry);
80      }
81  
82      @Override
83      public boolean apply(Path dir) {
84          // is starting visiting from root directory
85          Path normalizedDir = Paths.get(FilenameUtils.normalize(dir.toString()));
86          if (!normalizedDir.isAbsolute() || !normalizedDir.startsWith(rootPath)) {
87              return false;
88          }
89  
90          Path rel = rootPath.relativize(normalizedDir);
91  
92          // is an excluded directory
93          for (String excludePattern : excludePatterns) {
94              final PathMatcher matcher = normalizedDir.getFileSystem().getPathMatcher(excludePattern);
95              if (matcher.matches(rel)) {
96                  return false;
97              }
98          }
99  
100         return true;
101     }
102 
103     private Path validateRootPath(Path rootPath) {
104         Path normalizedPath = Paths.get(FilenameUtils.normalize(rootPath.toString()));
105         if (!normalizedPath.isAbsolute()) {
106             throw new IllegalStateException(rootPath + " is not an absolute Path.");
107         }
108         return normalizedPath;
109     }
110 
111     private void addDirectoryExcludes(List<String> excludePatterns, List<String> excludedDirectories) {
112         for (String directory : excludedDirectories) {
113             excludePatterns.add("regex:(^|.*" + (File.separator.replace("\\", "\\\\")) + ")" + Pattern.quote(directory) + "($|" + (File.separator.replace("\\", "\\\\")) + ".*)");
114         }
115     }
116 
117     private void addExtensionExcludes(List<String> excludePatterns, List<String> excludedExtensions) {
118         for (String ext : excludedExtensions) {
119             excludePatterns.add("regex:.*\\." + Pattern.quote(ext) + "$");
120         }
121     }
122 
123     private void addPatternList(List<String> excludePatterns, List<String> stringPatterns) {
124         for (String pattern : stringPatterns) {
125             if (pattern.startsWith("glob:") || pattern.startsWith("regex:")) {
126                 excludePatterns.add(pattern);
127             } else {
128                 excludePatterns.add("regex:" + pattern);
129             }
130         }
131     }
132 
133 }