ExpiredAuditLogCleaner.java

/*
 * Copyright 2023 Global Crop Diversity Trust
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.genesys.server.component;

import com.querydsl.jpa.impl.JPAQueryFactory;
import org.genesys.blocks.auditlog.model.QAuditLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.Instant;
import java.time.Period;
import java.time.ZonedDateTime;

@Component("expiredAuditLogCleaner")
public class ExpiredAuditLogCleaner implements InitializingBean {

	public static final Logger LOG = LoggerFactory.getLogger(ExpiredAuditLogCleaner.class);

	@Value("${auditlog.retentionPeriod:1Y}")
	private String retentionPeriodProperty;

	private Period retentionPeriod;

	@Autowired
	private JPAQueryFactory jpaQueryFactory;

	@Override
	public void afterPropertiesSet() throws Exception {
		retentionPeriodProperty = retentionPeriodProperty.replaceAll(" ", "");
		retentionPeriod = Period.parse("P".concat(retentionPeriodProperty));
	}

	@Scheduled(initialDelayString = "PT15M", fixedDelayString = "PT6H")
	@Transactional
	public void processExpired() {
		Instant expiredInstant = ZonedDateTime.now().minus(retentionPeriod).toInstant();
		LOG.trace("Searching for the audit logs created before: {}", expiredInstant);

		var removed = jpaQueryFactory.delete(QAuditLog.auditLog).where(QAuditLog.auditLog.logDate.before(expiredInstant)).execute();
		LOG.warn("Removed {} auditlog entries older than {}. Retention period is {}.", removed, expiredInstant, retentionPeriodProperty);
	}
}