public static boolean validateFileType ( final FileItemWrap newFile , final List < String > fileTypes ) { // The newFile is null, then return false if ( newFile == null ) { return false ; } // If fileTypes to validate is null or empty, then assume newFile is valid if ( fileTypes == null || fileTypes . isEmpty ( ) ) { return true ; } final List < String > fileExts = fileTypes . stream ( ) . filter ( fileType -> fileType . startsWith ( "." ) ) . collect ( Collectors . toList ( ) ) ; // filter mime types from fileTypes. final List < String > fileMimes = fileTypes . stream ( ) . filter ( fileType -> ! fileExts . contains ( fileType ) ) . collect ( Collectors . toList ( ) ) ; // First validate newFile against fileExts list // If extensions are supplied, then check if newFile has a name if ( fileExts . size ( ) > 0 && newFile . getName ( ) != null ) { // Then see if newFile has an extension String [ ] split = newFile . getName ( ) . split ( ( "\\.(?=[^\\.]+$)" ) ) ; // If it exists, then check if it matches supplied extension(s) if ( split . length == 2 && fileExts . stream ( ) . anyMatch ( fileExt -> fileExt . equals ( "." + split [ 1 ] ) ) ) { return true ; } } // If extension match is unsucessful, then move to fileMimes list if ( fileMimes . size ( ) > 0 ) { final String mimeType = getFileMimeType ( newFile ) ; LOG . debug ( "File mime-type is: " + mimeType ) ; for ( String fileMime : fileMimes ) { if ( StringUtils . equals ( mimeType , fileMime ) ) { return true ; } if ( fileMime . indexOf ( "*" ) == fileMime . length ( ) - 1 ) { fileMime = fileMime . substring ( 0 , fileMime . length ( ) - 1 ) ; if ( mimeType . indexOf ( fileMime ) == 0 ) { return true ; } } } } return false ; }
Checks if the file item is one among the supplied file types . This first checks against file extensions then against file mime types