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.gringlobal.component;

import lombok.extern.slf4j.Slf4j;
import org.genesys.blocks.auditlog.model.QAuditLog;
import java.time.Period;
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 com.querydsl.jpa.impl.JPAQueryFactory;

import net.javacrumbs.shedlock.spring.annotation.SchedulerLock;

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

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

	@Value("${auditlog.retentionPeriod:3M}")
	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));
	}

	@Transactional
	@Scheduled(initialDelayString = "PT15M", fixedDelayString = "PT6H")
	@SchedulerLock(name = "org.gringlobal.component.ExpiredAuditLogCleaner")
	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);
	}
}