001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018
019package org.apache.hadoop.fs;
020
021import java.util.regex.PatternSyntaxException;
022import java.io.IOException;
023
024import org.apache.hadoop.classification.InterfaceAudience;
025import org.apache.hadoop.classification.InterfaceStability;
026
027/**
028 * A filter for POSIX glob pattern with brace expansions.
029 */
030@InterfaceAudience.Public
031@InterfaceStability.Evolving
032public class GlobFilter implements PathFilter {
033  private final static PathFilter DEFAULT_FILTER = new PathFilter() {
034      public boolean accept(Path file) {
035        return true;
036      }
037    };
038
039  private PathFilter userFilter = DEFAULT_FILTER;
040  private GlobPattern pattern;
041
042  /**
043   * Creates a glob filter with the specified file pattern.
044   *
045   * @param filePattern the file pattern.
046   * @throws IOException thrown if the file pattern is incorrect.
047   */
048  public GlobFilter(String filePattern) throws IOException {
049    init(filePattern, DEFAULT_FILTER);
050  }
051
052  /**
053   * Creates a glob filter with the specified file pattern and an user filter.
054   *
055   * @param filePattern the file pattern.
056   * @param filter user filter in addition to the glob pattern.
057   * @throws IOException thrown if the file pattern is incorrect.
058   */
059  public GlobFilter(String filePattern, PathFilter filter) throws IOException {
060    init(filePattern, filter);
061  }
062
063  void init(String filePattern, PathFilter filter) throws IOException {
064    try {
065      userFilter = filter;
066      pattern = new GlobPattern(filePattern);
067    }
068    catch (PatternSyntaxException e) {
069      // Existing code expects IOException startWith("Illegal file pattern")
070      throw new IOException("Illegal file pattern: "+ e.getMessage(), e);
071    }
072  }
073
074  boolean hasPattern() {
075    return pattern.hasWildcard();
076  }
077
078  public boolean accept(Path path) {
079    return pattern.matches(path.getName()) && userFilter.accept(path);
080  }
081}