001/**
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v1.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014package ch.qos.logback.core.rolling.helper;
015
016import java.io.File;
017import java.io.FilenameFilter;
018import java.util.Arrays;
019import java.util.Comparator;
020import java.util.regex.Matcher;
021import java.util.regex.Pattern;
022
023public class FileFilterUtil {
024
025    public static void sortFileArrayByName(File[] fileArray) {
026        Arrays.sort(fileArray, new Comparator<File>() {
027            public int compare(File o1, File o2) {
028                String o1Name = o1.getName();
029                String o2Name = o2.getName();
030                return (o1Name.compareTo(o2Name));
031            }
032        });
033    }
034
035    public static void reverseSortFileArrayByName(File[] fileArray) {
036        Arrays.sort(fileArray, new Comparator<File>() {
037            public int compare(File o1, File o2) {
038                String o1Name = o1.getName();
039                String o2Name = o2.getName();
040                return (o2Name.compareTo(o1Name));
041            }
042        });
043    }
044
045    public static String afterLastSlash(String sregex) {
046        int i = sregex.lastIndexOf('/');
047        if (i == -1) {
048            return sregex;
049        } else {
050            return sregex.substring(i + 1);
051        }
052    }
053
054    static public boolean isEmptyDirectory(File dir) {
055        if (!dir.isDirectory()) {
056            throw new IllegalArgumentException("[" + dir + "] must be a directory");
057        }
058        String[] filesInDir = dir.list();
059        if (filesInDir == null || filesInDir.length == 0) {
060            return true;
061        } else {
062            return false;
063        }
064    }
065
066    /**
067     * Return the set of files matching the stemRegex as found in 'directory'. A
068     * stemRegex does not contain any slash characters or any folder separators.
069     * 
070     * @param file
071     * @param stemRegex
072     * @return
073     */
074    public static File[] filesInFolderMatchingStemRegex(File file, final String stemRegex) {
075
076        if (file == null) {
077            return new File[0];
078        }
079        if (!file.exists() || !file.isDirectory()) {
080            return new File[0];
081        }
082
083        // better compile the regex. See also LOGBACK-1409
084        Pattern pattern = Pattern.compile(stemRegex);
085        return file.listFiles((dir, name) -> pattern.matcher(name).matches());
086    }
087
088    static public int findHighestCounter(File[] matchingFileArray, final String stemRegex) {
089        int max = Integer.MIN_VALUE;
090        for (File aFile : matchingFileArray) {
091            int aCounter = FileFilterUtil.extractCounter(aFile, stemRegex);
092            if (max < aCounter)
093                max = aCounter;
094        }
095        return max;
096    }
097
098    static public int extractCounter(File file, final String stemRegex) {
099        Pattern p = Pattern.compile(stemRegex);
100        String lastFileName = file.getName();
101
102        Matcher m = p.matcher(lastFileName);
103        if (!m.matches()) {
104            throw new IllegalStateException("The regex [" + stemRegex + "] should match [" + lastFileName + "]");
105        }
106        String counterAsStr = m.group(1);
107        return Integer.parseInt(counterAsStr);
108    }
109
110    public static String slashify(String in) {
111        return in.replace('\\', '/');
112    }
113
114    public static void removeEmptyParentDirectories(File file, int recursivityCount) {
115        // we should never go more than 3 levels higher
116        if (recursivityCount >= 3) {
117            return;
118        }
119        File parent = file.getParentFile();
120        if (parent.isDirectory() && FileFilterUtil.isEmptyDirectory(parent)) {
121            parent.delete();
122            removeEmptyParentDirectories(parent, recursivityCount + 1);
123        }
124    }
125}