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.concurrent.TimeUnit;
019
020import org.forgerock.util.time.Duration;
021import org.joda.time.DateTime;
022import org.joda.time.DateTimeZone;
023
024/**
025 * Creates a rotation policy based on a time duration. Once the duration has passed the policy will indicate a
026 * file rotation is necessary.
027 */
028public class TimeLimitRotationPolicy implements RotationPolicy {
029    private final Duration rotationInterval;
030    private final long rotationIntervalInMillis;
031
032    /**
033     * Constructs a TimeLimitRotationPolicy with a given {@link Duration}.
034     * @param rotationInterval The interval to rotate at.
035     */
036    public TimeLimitRotationPolicy(final Duration rotationInterval) {
037        this.rotationInterval = rotationInterval;
038        this.rotationIntervalInMillis = rotationInterval.convertTo(TimeUnit.MILLISECONDS).getValue();
039    }
040
041    /**
042     * Checks whether or not a {@link RotatableObject} needs rotation.
043     * @param rotatable The rotatable to be checked.
044     * @return True - If the {@link RotatableObject} needs rotation.
045     *         False - If the {@link RotatableObject} doesn't need rotation.
046     */
047    @Override
048    public boolean shouldRotateFile(RotatableObject rotatable) {
049        if (rotationInterval.isZero() || rotationInterval.isUnlimited()) {
050            return false;
051        } else {
052            final DateTime now = DateTime.now(DateTimeZone.UTC);
053            final DateTime lastRotationTime = rotatable.getLastRotationTime();
054            final org.joda.time.Duration timeSinceLastRotation = new org.joda.time.Duration(lastRotationTime, now);
055            return timeSinceLastRotation.getMillis() >= rotationIntervalInMillis;
056        }
057    }
058
059    /**
060     * Gets the rotation duration interval.
061     * @return The interval as a {@link Duration}.
062     */
063    public Duration getRotationInterval() {
064        return rotationInterval;
065    }
066}