GenesysImageGalleryAspects.java

/*
 * Copyright 2019 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.regex.Matcher;

import org.aspectj.lang.annotation.Aspect;
import org.genesys.filerepository.InvalidRepositoryPathException;
import org.genesys.filerepository.model.ImageGallery;
import org.genesys.filerepository.model.RepositoryFolder;
import org.genesys.filerepository.model.RepositoryImage;
import org.genesys.filerepository.service.ImageGalleryService;
import org.genesys.filerepository.service.aspect.AbstractImageGalleryAspects;
import org.genesys.filerepository.service.aspect.ImageGalleryAspectsImpl;
import org.genesys.server.model.genesys.Accession;
import org.genesys.server.model.genesys.AccessionId;
import org.genesys.server.persistence.AccessionIdRepository;
import org.genesys.server.service.AccessionService;
import org.genesys.server.service.InstituteFilesService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;

/**
 * The Class GenesysImageGalleryAspects.
 */
@Aspect
public class GenesysImageGalleryAspects extends AbstractImageGalleryAspects implements InitializingBean {
	
	/** The Constant LOG. */
	public static final Logger LOG = LoggerFactory.getLogger(GenesysImageGalleryAspects.class);

	/** The image gallery aspect. */
	private ImageGalleryAspectsImpl imageGalleryAspect = new ImageGalleryAspectsImpl();

	/** The institute files service. */
	@Autowired
	private InstituteFilesService instituteFilesService;
	
	/** The image gallery service. */
	@Autowired
	private ImageGalleryService imageGalleryService;

	@Autowired
	private AccessionService accessionService;

	@Autowired
	private AccessionIdRepository accessionIdRepository;

	/**
	 * Instantiates a new genesys image gallery aspects.
	 */
	public GenesysImageGalleryAspects() {
		LOG.warn("Instantiating {}", getClass().getName());
	}

	/* (non-Javadoc)
	 * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
	 */
	@Override
	public void afterPropertiesSet() throws Exception {
		LOG.warn("Instantiating bean {}", getClass().getName());
		imageGalleryAspect.setImageGalleryService(imageGalleryService);
	}

	/* (non-Javadoc)
	 * @see org.genesys.filerepository.service.aspect.AbstractImageGalleryAspects#addImageToGallery(org.genesys.filerepository.model.RepositoryImage)
	 */
	@Override
	protected void addImageToGallery(RepositoryImage repositoryImage) throws InvalidRepositoryPathException {
		imageGalleryAspect.addImageToGallery(repositoryImage);
		
		RepositoryFolder folder = repositoryImage.getFolder();
		if (isAccessionFolder(folder)) {
			Accession accession = accessionService.findMatchingAccession(folder);
			if (accession != null) {
				ensureImageGallery(accession, repositoryImage);
				updateImageCountOfAcce(accession);
			} else {
				LOG.warn("No accession for repository folder {}", folder.getPath());
				throw new DataIntegrityViolationException("No unique accession in Genesys for " + folder.getPath());
			}
		}
	}

	/* (non-Javadoc)
	 * @see org.genesys.filerepository.service.aspect.AbstractImageGalleryAspects#removeImageFromGallery(org.genesys.filerepository.model.RepositoryImage)
	 */
	@Override
	protected void removeImageFromGallery(RepositoryImage repositoryImage) throws InvalidRepositoryPathException {
		imageGalleryAspect.removeImageFromGallery(repositoryImage);
		
		RepositoryFolder repositoryFolder = repositoryImage.getFolder();
		if (isAccessionFolder(repositoryFolder)) {
			Accession accession = accessionService.findMatchingAccession(repositoryFolder);
			if (accession != null) {
				updateImageCountOfAcce(accession);
			}
		}
	}


	/**
	 * Ensures that an {@link ImageGallery} exists for accession images.
	 *
	 * @param repositoryImage the repository image
	 */
	private void ensureImageGallery(Accession accession, RepositoryImage repositoryImage) {
		try {
			if (accession != null) {
				AccessionId accessionId = accession.getAccessionId();

				if (accessionId.getRepositoryFolder() == null // New gallery
						// or image gallery doesn't exist
						|| imageGalleryService.loadImageGallery(accessionId.getRepositoryFolder().getFolderPath()) == null) {

					ImageGallery imageGallery = instituteFilesService.createImageGallery(accession.getInstitute(), accession);
					
					if (accessionId.getRepositoryFolder() == null) {
						accessionIdRepository.updateRepositoryFolder(accessionId, imageGallery.getFolder());
					}
				}
			}
		} catch (InvalidRepositoryPathException e) {
			LOG.warn("Error creating accession image gallery at {}, error is {}", repositoryImage.getFolder().getPath(), e.getMessage());
		}
	}

	public final static boolean isAccessionFolder(RepositoryFolder folder) {
		Matcher matcher = AccessionService.ACCESSION_IMAGE_PATTERN.matcher(folder.getPath());
		if (matcher.matches()) {
			LOG.debug("Path {} is within institute accession files prefix instCode={} acceNumb={}", folder.getPath(), matcher.group(1), matcher.group(2));
			return true;
		} else {
			return false;
		}
	}

	public final static boolean isInstituteFolder(RepositoryFolder folder) {
		Matcher matcher = AccessionService.INSTITUTE_FOLDER_PATTERN.matcher(folder.getPath());
		if (matcher.matches()) {
			LOG.debug("Path {} is an institute folder instCode={}", folder.getPath(), matcher.group(1));
			return true;
		} else {
			return false;
		}
	}

	private void updateImageCountOfAcce(Accession accession) {
		AccessionId accessionId = accession.getAccessionId();
		try {
			ImageGallery imageGallery = instituteFilesService.loadImageGallery(accession.getInstitute(), accession);
			if (imageGallery != null) {
				accessionIdRepository.updateImageCount(accessionId, imageGallery.getImages().size());
			} else {
				accessionIdRepository.updateImageCount(accessionId, 0);
			}
		} catch (InvalidRepositoryPathException e) {
			LOG.warn("Error updating imageCount of accession, error is {}", e.getMessage());
		}
	}
}