001: package com.sun.portal.util;
002:
003: import java.io.FilenameFilter;
004: import java.io.File;
005: import java.util.regex.Pattern;
006:
007: public class FileWildFilter implements FilenameFilter {
008:
009: public static final int ALL = 0;
010: public static final int ONLY_DIR = 1;
011: public static final int ONLY_FILE = 2;
012:
013: private Pattern m_includePattern = null;
014: private Pattern m_excludePattern = null;
015: private int m_iFileType = ALL;
016: private static FileWildFilter s_sDirectoryFilter;
017: private static FileWildFilter s_sFileFilter;
018: private static FileWildFilter s_sAllFilter;
019:
020: public FileWildFilter(final String regExIncl,
021: final String regExExcl, final int fileType) {
022:
023: // Select all if 'regExIncl' is null or empty.
024: String sRegExIncl = (regExIncl != null) ? regExIncl : null;
025: if ((sRegExIncl == null) || (sRegExIncl.length() == 0)) {
026: sRegExIncl = "[\\S|\\s]*";
027: }
028: m_includePattern = Pattern.compile(sRegExIncl);
029:
030: String sRegExExcl = (regExExcl != null) ? regExExcl : null;
031: if ((sRegExExcl != null) && (sRegExExcl.length() > 0)) {
032: m_excludePattern = Pattern.compile(sRegExExcl);
033: }
034:
035: m_iFileType = fileType;
036: if ((m_iFileType < ALL) || (m_iFileType > ONLY_FILE)) {
037: m_iFileType = ALL;
038: }
039: }
040:
041: public boolean accept(File dir, String name) {
042:
043: boolean bIsMatching = m_includePattern.matcher(name).matches();
044:
045: if (bIsMatching && (m_excludePattern != null)) {
046:
047: bIsMatching = !m_excludePattern.matcher(name).matches();
048: }
049:
050: if (bIsMatching) {
051:
052: File file = new File(dir, name);
053: bIsMatching = file.exists();
054:
055: if (bIsMatching) {
056:
057: switch (m_iFileType) {
058:
059: case ONLY_DIR:
060: bIsMatching = file.isDirectory();
061: break;
062: case ONLY_FILE:
063: bIsMatching = file.isFile();
064: break;
065: }
066: }
067: }
068:
069: return bIsMatching;
070: }
071:
072: public static FileWildFilter getExtensionFilter(final String ext,
073: final int type) {
074:
075: FileWildFilter filter = null;
076: if (ext == null) {
077:
078: filter = new FileWildFilter(null, null, type);
079: } else {
080:
081: filter = new FileWildFilter("[\\S|\\s]*\\." + ext, null,
082: type);
083: }
084:
085: return filter;
086: }
087:
088: public static FileWildFilter getDirectoryFilter() {
089:
090: if (s_sDirectoryFilter == null) {
091:
092: s_sDirectoryFilter = new FileWildFilter(null, null,
093: ONLY_DIR);
094: }
095:
096: return s_sDirectoryFilter;
097: }
098:
099: public static FileWildFilter getFileFilter() {
100:
101: if (s_sFileFilter == null) {
102:
103: s_sFileFilter = new FileWildFilter(null, null, ONLY_FILE);
104: }
105:
106: return s_sFileFilter;
107: }
108: }
|