DatasetAndSubsetCountAspect.java

/*
 * Copyright 2020 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.aspect;

import java.util.List;
import java.util.concurrent.BlockingQueue;

import javax.annotation.Resource;

import org.apache.commons.collections4.CollectionUtils;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.genesys.server.component.elastic.ElasticReindex;
import org.genesys.server.model.PublishState;
import org.genesys.server.model.dataset.Dataset;
import org.genesys.server.model.genesys.Accession;
import org.genesys.server.model.genesys.AccessionId;
import org.genesys.server.model.impl.Subset;
import org.genesys.server.persistence.AccessionIdRepository;
import org.genesys.server.persistence.SubsetAccessionRefRepository;
import org.genesys.server.persistence.dataset.DatasetAccessionRefRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;

/**
 * This aspect updates {@link AccessionId#datasetCount} and {@link AccessionId#subsetCount}.
 * - when associated subset/dataset is published, the count is increased by 1;
 * - when associated subset/dataset is unpublished, the count is decreased by 1.
 *
 * @author Maxym Borodenko
 */
@Aspect
@Component
public class DatasetAndSubsetCountAspect {

	/** The Constant LOG. */
	private final static Logger LOG = LoggerFactory.getLogger(DatasetAndSubsetCountAspect.class);

	@Autowired
	private AccessionIdRepository accessionIdRepository;

	@Autowired
	private DatasetAccessionRefRepository datasetAccessionRefRepository;

	@Autowired
	private SubsetAccessionRefRepository subsetAccessionRefRepository;

	@Autowired
	private TaskExecutor taskExecutor;

	@Resource
	private BlockingQueue<ElasticReindex> elasticReindexQueue;


	@AfterReturning(value = "execution(* org.genesys.server.service.*.approveDataset(..)) || execution(* org.genesys.server.service.*.rejectDataset(..))", returning = "result")
	public void afterDatasetPersist(final Dataset result) {
		if (result == null || result.getAccessionCount() == 0) {
			return;
		}

		List<AccessionId> accessionIds = datasetAccessionRefRepository.findAccessionIdsByList(result);
		Lists.partition(accessionIds, 1000).parallelStream().forEach(batch ->  {
			try {
				if (result.getState().equals(PublishState.PUBLISHED)) {
					accessionIdRepository.increaseDatasetCount(batch);
				} else {
					accessionIdRepository.decreaseDatasetCount(batch);
				}

				scheduleReindexing(batch);
			} catch (Throwable ex) {
				LOG.warn("Error updating datasetCount of accessions, error is {}", ex.getMessage());
			}
		});
	}

	@AfterReturning(value = "execution(* org.genesys.server.service.*.approveSubset(..)) || execution(* org.genesys.server.service.*.rejectSubset(..))", returning = "result")
	public void afterSubsetPersist(final Subset result) {
		if (result == null || result.getAccessionCount() == 0) {
			return;
		}

		List<AccessionId> accessionIds = subsetAccessionRefRepository.findAccessionIdsByList(result);
		Lists.partition(accessionIds, 1000).parallelStream().forEach(batch ->  {
			try {
				if (result.getState().equals(PublishState.PUBLISHED)) {
					accessionIdRepository.increaseSubsetCount(batch);
				} else {
					accessionIdRepository.decreaseSubsetCount(batch);
				}

				scheduleReindexing(batch);
			} catch (Throwable ex) {
				LOG.warn("Error updating datasetCount of accessions, error is {}", ex.getMessage());
			}
		});
	}

	private void scheduleReindexing(List<AccessionId> toReindex) {
		if (CollectionUtils.isEmpty(toReindex)) {
			return;
		}

		taskExecutor.execute(() -> toReindex.forEach(accessionId -> {
			LOG.trace("Scheduling reindexing of {} {}", Accession.class.getName(), accessionId.getId());
			elasticReindexQueue.add(new ElasticReindex(Accession.class, accessionId.getId()));
		}));
	}

}