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.vfs2; 018 019import java.util.regex.Pattern; 020 021/** 022 * A {@link FileSelector} that selects based on regular expressions matched against base filename. 023 * 024 * @since 2.1 025 */ 026public class PatternFileSelector implements FileSelector { 027 028 /** 029 * The extensions to select. 030 */ 031 private final Pattern pattern; 032 033 /** 034 * Creates a new selector for the given pattern. 035 * 036 * @param pattern The regular expressed used by this selector. 037 */ 038 public PatternFileSelector(final Pattern pattern) { 039 this.pattern = pattern; 040 } 041 042 /** 043 * Creates a new selector for the given pattern. 044 * 045 * @param regex The regular expressed used by this selector. 046 */ 047 public PatternFileSelector(final String regex) { 048 this(Pattern.compile(regex)); 049 } 050 051 /** 052 * Creates a new selector for the given Pattern and flags. 053 * 054 * @param regex The expression to be compiled 055 * 056 * @param flags Match flags, a bit mask. 057 * 058 * @see Pattern#compile(String, int) 059 */ 060 public PatternFileSelector(final String regex, final int flags) { 061 this(Pattern.compile(regex, flags)); 062 } 063 064 /** 065 * Determines if a file or folder should be selected. 066 * 067 * @param fileInfo The file selection information. 068 * @return true if the file should be selected, false otherwise. 069 */ 070 @Override 071 public boolean includeFile(final FileSelectInfo fileInfo) { 072 return this.pattern.matcher(fileInfo.getFile().getName().getPath()).matches(); 073 } 074 075 @Override 076 public String toString() { 077 return this.pattern.toString(); 078 } 079 080 /** 081 * Determines whether a folder should be traversed. 082 * 083 * @param fileInfo The file selection information. 084 * @return true if descendants should be traversed, false otherwise. 085 */ 086 @Override 087 public boolean traverseDescendents(final FileSelectInfo fileInfo) { 088 return true; 089 } 090}