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      @Override
035      public boolean accept(Path file) {
036        return true;
037      }
038    };
039
040  private PathFilter userFilter = DEFAULT_FILTER;
041  private GlobPattern pattern;
042
043  /**
044   * Creates a glob filter with the specified file pattern.
045   *
046   * @param filePattern the file pattern.
047   * @throws IOException thrown if the file pattern is incorrect.
048   */
049  public GlobFilter(String filePattern) throws IOException {
050    init(filePattern, DEFAULT_FILTER);
051  }
052
053  /**
054   * Creates a glob filter with the specified file pattern and an user filter.
055   *
056   * @param filePattern the file pattern.
057   * @param filter user filter in addition to the glob pattern.
058   * @throws IOException thrown if the file pattern is incorrect.
059   */
060  public GlobFilter(String filePattern, PathFilter filter) throws IOException {
061    init(filePattern, filter);
062  }
063
064  void init(String filePattern, PathFilter filter) throws IOException {
065    try {
066      userFilter = filter;
067      pattern = new GlobPattern(filePattern);
068    }
069    catch (PatternSyntaxException e) {
070      // Existing code expects IOException startWith("Illegal file pattern")
071      throw new IOException("Illegal file pattern: "+ e.getMessage(), e);
072    }
073  }
074
075  boolean hasPattern() {
076    return pattern.hasWildcard();
077  }
078
079  @Override
080  public boolean accept(Path path) {
081    return pattern.matches(path.getName()) && userFilter.accept(path);
082  }
083}