/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2007-2008 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
 * --------------------------------------------------------------------------
 * $Id: ExclusionFilenameFilter.java 22065 2012-01-31 13:14:39Z joaninh $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.deployablemonitor;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * Exclude monitored filenames based on patterns.
 * By default, system files are excluded too (starting with '.')
 * @author Guillaume Sauthier
 */
public class ExclusionFilenameFilter implements FilenameFilter {

    /**
     * Exclusion patterns.
     */
    private List<String> patterns = new ArrayList<String>();

    /**
     * Tests if a specified file should be included in a file list.
     * @param   dir    the directory in which the file was found.
     * @param   name   the name of the file.
     * @return  <code>true</code> if and only if the name should be
     * included in the file list; <code>false</code> otherwise.
     */
    public boolean accept(final File dir, final String name) {
        // Exclude system files, backup files or file matching the patterns.
        if(name.startsWith(".") || name.endsWith("~") || match(name)) {
            return false;
        }
        return true;
    }

    /**
     * @param name filename to be matched.
     * @return true if the file name matches one the patterns.
     */
    private boolean match(final String name) {
        for (String pattern : patterns) {
            if (Pattern.matches(pattern, name)) {
                return true;
            }
        }
        return false;
    }

    /**
     * @param patterns list of filename patterns to be excluded.
     */
    public void setExclusionList(final List<String> patterns) {
        this.patterns = patterns;
    }

}
