1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 package org.apache.commons.vfs2; 18 19 import java.util.Arrays; 20 import java.util.Collection; 21 import java.util.HashSet; 22 import java.util.Set; 23 24 /** 25 * A {@link FileSelector} that selects based on file extensions. 26 * <p> 27 * The extension comparison is case insensitive. 28 * </p> 29 * <p> 30 * The selector makes a copy of a given Collection or array. Changing the object passed in the constructors will not 31 * affect the selector. 32 * </p> 33 * 34 * @since 2.1 35 */ 36 public class FileExtensionSelector implements FileSelector { 37 38 /** 39 * The extensions to select. 40 */ 41 private final Set<String> extensions = new HashSet<>(); 42 43 /** 44 * Creates a new selector for the given extensions. 45 * 46 * @param extensions The extensions to be included by this selector. 47 */ 48 public FileExtensionSelector(final Collection<String> extensions) { 49 if (extensions != null) { 50 this.extensions.addAll(extensions); 51 } 52 } 53 54 /** 55 * Creates a new selector for the given extensions. 56 * 57 * @param extensions The extensions to be included by this selector. 58 */ 59 public FileExtensionSelector(final String... extensions) { 60 if (extensions != null) { 61 this.extensions.addAll(Arrays.asList(extensions)); 62 } 63 } 64 65 /** 66 * Determines if a file or folder should be selected. 67 * 68 * @param fileInfo The file selection information. 69 * @return true if the file should be selected, false otherwise. 70 */ 71 @Override 72 public boolean includeFile(final FileSelectInfo fileInfo) throws Exception { 73 for (final String extension : this.extensions) { 74 if (fileInfo.getFile().getName().getExtension().equalsIgnoreCase(extension)) { 75 return true; 76 } 77 } 78 return false; 79 } 80 81 /** 82 * Determines whether a folder should be traversed. 83 * 84 * @param fileInfo The file selection information. 85 * @return true if descendants should be traversed, fase otherwise. 86 */ 87 @Override 88 public boolean traverseDescendents(final FileSelectInfo fileInfo) throws Exception { 89 return true; 90 } 91 }