001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.io.filefilter;
018
019import java.io.File;
020import java.io.Serializable;
021import java.nio.file.FileVisitResult;
022import java.nio.file.Path;
023import java.nio.file.attribute.BasicFileAttributes;
024import java.util.function.Function;
025import java.util.regex.Pattern;
026
027import org.apache.commons.io.IOCase;
028
029/**
030 * Filters files using supplied regular expression(s).
031 * <p>
032 * See java.util.regex.Pattern for regex matching rules.
033 * </p>
034 * <h2>Using Classic IO</h2>
035 * <p>
036 * e.g.
037 *
038 * <pre>
039 * File dir = new File(".");
040 * FileFilter fileFilter = new RegexFileFilter("^.*[tT]est(-\\d+)?\\.java$");
041 * File[] files = dir.listFiles(fileFilter);
042 * for (String file : files) {
043 *     System.out.println(file);
044 * }
045 * </pre>
046 *
047 * <h2>Using NIO</h2>
048 *
049 * <pre>
050 * final Path dir = Paths.get("");
051 * final AccumulatorPathVisitor visitor = AccumulatorPathVisitor.withLongCounters(new RegexFileFilter("^.*[tT]est(-\\d+)?\\.java$"));
052 * //
053 * // Walk one dir
054 * Files.<b>walkFileTree</b>(dir, Collections.emptySet(), 1, visitor);
055 * System.out.println(visitor.getPathCounters());
056 * System.out.println(visitor.getFileList());
057 * //
058 * visitor.getPathCounters().reset();
059 * //
060 * // Walk dir tree
061 * Files.<b>walkFileTree</b>(dir, visitor);
062 * System.out.println(visitor.getPathCounters());
063 * System.out.println(visitor.getDirList());
064 * System.out.println(visitor.getFileList());
065 * </pre>
066 *
067 * @since 1.4
068 */
069public class RegexFileFilter extends AbstractFileFilter implements Serializable {
070
071    private static final long serialVersionUID = 4269646126155225062L;
072
073    /**
074     * Compiles the given pattern source.
075     *
076     * @param pattern the source pattern.
077     * @param flags the compilation flags.
078     * @return a new Pattern.
079     */
080    private static Pattern compile(final String pattern, final int flags) {
081        if (pattern == null) {
082            throw new IllegalArgumentException("Pattern is missing");
083        }
084        return Pattern.compile(pattern, flags);
085    }
086
087    /**
088     * Converts IOCase to Pattern compilation flags.
089     *
090     * @param caseSensitivity case-sensitivity.
091     * @return Pattern compilation flags.
092     */
093    private static int toFlags(final IOCase caseSensitivity) {
094        return IOCase.isCaseSensitive(caseSensitivity) ? Pattern.CASE_INSENSITIVE : 0;
095    }
096
097    /** The regular expression pattern that will be used to match file names. */
098    private final Pattern pattern;
099    
100    /** How convert a path to a string. */
101    private final Function<Path, String> pathToString;
102
103    /**
104     * Constructs a new regular expression filter for a compiled regular expression
105     *
106     * @param pattern regular expression to match.
107     * @throws IllegalArgumentException if the pattern is null.
108     */
109    public RegexFileFilter(final Pattern pattern) {
110        this(pattern, p -> p.getFileName().toString());
111    }
112
113    /**
114     * Constructs a new regular expression filter for a compiled regular expression
115     *
116     * @param pattern regular expression to match.
117     * @param pathToString How convert a path to a string.
118     * @throws IllegalArgumentException if the pattern is null.
119     * @since 2.10.0
120     */
121    public RegexFileFilter(final Pattern pattern, final Function<Path, String> pathToString) {
122        if (pattern == null) {
123            throw new IllegalArgumentException("Pattern is missing");
124        }
125        this.pattern = pattern;
126        this.pathToString = pathToString;
127    }
128
129    /**
130     * Constructs a new regular expression filter.
131     *
132     * @param pattern regular string expression to match
133     * @throws IllegalArgumentException if the pattern is null
134     */
135    public RegexFileFilter(final String pattern) {
136        this(pattern, 0);
137    }
138
139    /**
140     * Constructs a new regular expression filter with the specified flags.
141     *
142     * @param pattern regular string expression to match
143     * @param flags pattern flags - e.g. {@link Pattern#CASE_INSENSITIVE}
144     * @throws IllegalArgumentException if the pattern is null
145     */
146    public RegexFileFilter(final String pattern, final int flags) {
147        this(compile(pattern, flags));
148    }
149
150    /**
151     * Constructs a new regular expression filter with the specified flags case sensitivity.
152     *
153     * @param pattern regular string expression to match
154     * @param caseSensitivity how to handle case sensitivity, null means case-sensitive
155     * @throws IllegalArgumentException if the pattern is null
156     */
157    public RegexFileFilter(final String pattern, final IOCase caseSensitivity) {
158        this(compile(pattern, toFlags(caseSensitivity)));
159    }
160
161    /**
162     * Checks to see if the file name matches one of the regular expressions.
163     *
164     * @param dir the file directory (ignored)
165     * @param name the file name
166     * @return true if the file name matches one of the regular expressions
167     */
168    @Override
169    public boolean accept(final File dir, final String name) {
170        return pattern.matcher(name).matches();
171    }
172
173    /**
174     * Checks to see if the file name matches one of the regular expressions.
175     *
176     * @param path the path
177     * @param attributes the path attributes
178     * @return true if the file name matches one of the regular expressions
179     */
180    @Override
181    public FileVisitResult accept(final Path path, final BasicFileAttributes attributes) {
182        return toFileVisitResult(pattern.matcher(pathToString.apply(path)).matches(), path);
183    }
184
185    /**
186     * Returns a debug string.
187     *
188     * @since 2.10.0
189     */
190    @Override
191    public String toString() {
192        return "RegexFileFilter [pattern=" + pattern + "]";
193    }
194
195}