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.Arrays; 020import java.util.Collection; 021import java.util.HashSet; 022import java.util.Set; 023 024/** 025 * A {@link FileSelector} that selects based on file extensions. 026 * <p> 027 * The extension comparison is case insensitive. 028 * </p> 029 * <p> 030 * The selector makes a copy of a given Collection or array. Changing the object passed in the constructors will not 031 * affect the selector. 032 * </p> 033 * 034 * @since 2.1 035 */ 036public class FileExtensionSelector implements FileSelector { 037 038 /** 039 * The extensions to select. 040 */ 041 private final Set<String> extensions = new HashSet<>(); 042 043 /** 044 * Creates a new selector for the given extensions. 045 * 046 * @param extensions The extensions to be included by this selector. 047 */ 048 public FileExtensionSelector(final Collection<String> extensions) { 049 if (extensions != null) { 050 this.extensions.addAll(extensions); 051 } 052 } 053 054 /** 055 * Creates a new selector for the given extensions. 056 * 057 * @param extensions The extensions to be included by this selector. 058 */ 059 public FileExtensionSelector(final String... extensions) { 060 if (extensions != null) { 061 this.extensions.addAll(Arrays.asList(extensions)); 062 } 063 } 064 065 /** 066 * Determines if a file or folder should be selected. 067 * 068 * @param fileInfo The file selection information. 069 * @return true if the file should be selected, false otherwise. 070 */ 071 @Override 072 public boolean includeFile(final FileSelectInfo fileInfo) throws Exception { 073 return extensions.stream().anyMatch(extension -> fileInfo.getFile().getName().getExtension().equalsIgnoreCase(extension)); 074 } 075 076 /** 077 * Determines whether a folder should be traversed. 078 * 079 * @param fileInfo The file selection information. 080 * @return true if descendants should be traversed, false otherwise. 081 */ 082 @Override 083 public boolean traverseDescendents(final FileSelectInfo fileInfo) throws Exception { 084 return true; 085 } 086}