001/** 002 * Logback: the reliable, generic, fast and flexible logging framework. 003 * Copyright (C) 1999-2024, 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.time.Instant; 018import java.util.Arrays; 019import java.util.Comparator; 020import java.util.Date; 021import java.util.regex.Matcher; 022import java.util.regex.Pattern; 023 024public class SizeAndTimeBasedArchiveRemover extends TimeBasedArchiveRemover { 025 026 protected static final int NO_INDEX = -1; 027 028 public SizeAndTimeBasedArchiveRemover(FileNamePattern fileNamePattern, RollingCalendar rc) { 029 super(fileNamePattern, rc); 030 } 031 032 @Override 033 protected File[] getFilesInPeriod(Instant instantOfPeriodToClean) { 034 File archive0 = new File(fileNamePattern.convertMultipleArguments(instantOfPeriodToClean, 0)); 035 File parentDir = getParentDir(archive0); 036 String stemRegex = createStemRegex(instantOfPeriodToClean); 037 File[] matchingFileArray = FileFilterUtil.filesInFolderMatchingStemRegex(parentDir, stemRegex); 038 return matchingFileArray; 039 } 040 041 @Override 042 protected void descendingSort(File[] matchingFileArray, Instant instant) { 043 044 String regexForIndexExtreaction = createStemRegex(instant); 045 final Pattern pattern = Pattern.compile(regexForIndexExtreaction); 046 047 Arrays.sort(matchingFileArray, new Comparator<File>() { 048 @Override 049 public int compare(final File f1, final File f2) { 050 051 int index1 = extractIndex(pattern, f1); 052 int index2 = extractIndex(pattern, f2); 053 054 if (index1 == index2) 055 return 0; 056 // descending sort, i.e. newest files first 057 if (index2 < index1) 058 return -1; 059 else 060 return 1; 061 } 062 063 private int extractIndex(Pattern pattern, File f1) { 064 Matcher matcher = pattern.matcher(f1.getName()); 065 if (matcher.find()) { 066 String indexAsStr = matcher.group(1); 067 068 if (indexAsStr == null || indexAsStr.isEmpty()) 069 return NO_INDEX; // unreachable code? 070 else 071 return Integer.parseInt(indexAsStr); 072 } else 073 return NO_INDEX; 074 } 075 }); 076 } 077 078 private String createStemRegex(final Instant instantOfPeriodToClean) { 079 String regex = fileNamePattern.toRegexForFixedDate(instantOfPeriodToClean); 080 return FileFilterUtil.afterLastSlash(regex); 081 } 082 083}