001/* 002 * The contents of this file are subject to the terms of the Common Development and 003 * Distribution License (the License). You may not use this file except in compliance with the 004 * License. 005 * 006 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the 007 * specific language governing permission and limitations under the License. 008 * 009 * When distributing Covered Software, include this CDDL Header Notice in each file and include 010 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL 011 * Header, with the fields enclosed by brackets [] replaced by your own identifying 012 * information: "Portions copyright [year] [name of copyright owner]". 013 * 014 * Copyright 2015 ForgeRock AS. 015 */ 016package org.forgerock.audit.retention; 017 018import java.io.File; 019import java.util.Collections; 020import java.util.Comparator; 021import java.util.LinkedList; 022import java.util.List; 023 024import org.forgerock.audit.util.LastModifiedTimeFileComparator; 025 026/** 027 * A {@link RetentionPolicy} that will retain/delete log files given a minimum amount of disk space the file system 028 * must contain. 029 */ 030public class FreeDiskSpaceRetentionPolicy implements RetentionPolicy { 031 032 private final long minFreeSpaceRequired; 033 private final Comparator<File> comparator = new LastModifiedTimeFileComparator(); 034 035 /** 036 * Constructs a {@link FreeDiskSpaceRetentionPolicy} given a minimum amount of disk space the file system must 037 * contain. 038 * @param minFreeSpaceRequired The minimum amount of free disk space the the file system must contain in bytes. 039 */ 040 public FreeDiskSpaceRetentionPolicy(final long minFreeSpaceRequired) { 041 this.minFreeSpaceRequired = minFreeSpaceRequired; 042 } 043 044 @Override 045 public List<File> deleteFiles(FileNamingPolicy fileNamingPolicy) { 046 final List<File> archivedFiles = fileNamingPolicy.listFiles(); 047 if (archivedFiles.isEmpty()) { 048 return Collections.emptyList(); 049 } 050 051 final long freeSpace = archivedFiles.get(0).getFreeSpace(); 052 if (freeSpace >= minFreeSpaceRequired) { 053 return Collections.emptyList(); 054 } 055 056 final long freeSpaceNeeded = minFreeSpaceRequired - freeSpace; 057 058 Collections.sort(archivedFiles, comparator); 059 060 long freedSpace = 0L; 061 List<File> filesToDelete = new LinkedList<>(); 062 for (File file : archivedFiles) { 063 filesToDelete.add(file); 064 freedSpace += file.length(); 065 if (freedSpace >= freeSpaceNeeded) { 066 break; 067 } 068 } 069 return filesToDelete; 070 } 071}