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-2016 ForgeRock AS.
015 */
016package org.forgerock.audit.rotation;
017
018import java.util.List;
019import java.util.concurrent.TimeUnit;
020
021import org.forgerock.util.time.Duration;
022import org.joda.time.DateMidnight;
023import org.joda.time.DateTime;
024import org.slf4j.Logger;
025import org.slf4j.LoggerFactory;
026
027/**
028 * Rotates audit files at fixed times throughout the day.
029 */
030public class FixedTimeRotationPolicy implements RotationPolicy {
031    private static final Logger logger = LoggerFactory.getLogger(FixedTimeRotationPolicy.class);
032    private final List<Duration> dailyRotationTimes;
033
034    /**
035     * Constructs a {@link FixedTimeRotationPolicy} given a list of milliseconds after midnight to rotateIfNeeded the
036     * files.
037     *
038     * @param rotationTimes List of {@link Duration} objects specifying the time after midnight to rotate the log file.
039     */
040    public FixedTimeRotationPolicy(final List<Duration> rotationTimes) {
041        dailyRotationTimes = rotationTimes;
042    }
043
044    /**
045     * {@inheritDoc}
046     */
047    @Override
048    public boolean shouldRotateFile(RotatableObject rotatable) {
049        final DateTime currentTime = new DateTime();
050        final DateTime midnight = new DateMidnight().toDateTime();
051        for (final Duration dailyRotationTime : dailyRotationTimes) {
052            final DateTime nextRotationTime = midnight.plus(dailyRotationTime.to(TimeUnit.MILLISECONDS));
053            if (currentTime.isAfter(nextRotationTime) && rotatable.getLastRotationTime().isBefore(nextRotationTime)) {
054                return true;
055            }
056        }
057        return false;
058    }
059
060    /**
061     * Get the list of times since midnight that rotation will occur at.
062     * @return The list of times as {@code Duration} instances.
063     */
064    public List<Duration> getDailyRotationTimes() {
065        return dailyRotationTimes;
066    }
067}