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.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 files.
036     *
037     * @param rotationTimes List of {@link Duration} objects specifying the time after midnight to rotate the log file.
038     */
039    public FixedTimeRotationPolicy(final List<Duration> rotationTimes) {
040        dailyRotationTimes = rotationTimes;
041    }
042
043    /**
044     * {@inheritDoc}
045     */
046    @Override
047    public boolean shouldRotateFile(RotatableObject rotatable) {
048        final DateTime currentTime = new DateTime();
049        final DateTime midnight = new DateMidnight().toDateTime();
050        for (final Duration dailyRotationTime : dailyRotationTimes) {
051            final DateTime nextRotationTime = midnight.plus(dailyRotationTime.to(TimeUnit.MILLISECONDS));
052            if (currentTime.isAfter(nextRotationTime) && rotatable.getLastRotationTime().isBefore(nextRotationTime)) {
053                return true;
054            }
055        }
056        return false;
057    }
058
059    public List<Duration> getDailyRotationTimes() {
060        return dailyRotationTimes;
061    }
062}