BaseAttachmentSupport.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.gringlobal.service.impl;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Set;

import com.querydsl.core.types.dsl.NumberPath;
import lombok.extern.slf4j.Slf4j;
import org.genesys.filerepository.InvalidRepositoryFileDataException;
import org.genesys.filerepository.InvalidRepositoryPathException;
import org.genesys.filerepository.NoSuchRepositoryFileException;
import org.genesys.filerepository.model.RepositoryFile;
import org.gringlobal.api.exception.NotFoundElement;
import org.gringlobal.model.CooperatorAttachment;
import org.gringlobal.model.CooperatorOwnedModel;
import org.gringlobal.spring.persistence.ExtendedJpaRepository;
import org.gringlobal.service.AttachmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author Maxym Borodenko
 */
@Validated
@Slf4j
public abstract class BaseAttachmentSupport<T extends CooperatorOwnedModel, A extends CooperatorAttachment, R extends AttachmentService.AttachmentRequest<A>> extends CRUDService2Impl<A, ExtendedJpaRepository<A,Long>> implements AttachmentService<T, A, R> {

	private NumberPath<Long> qActionOwningEntityId;
	private NumberPath<Long> qAttachId;

	@Autowired
	protected ExtendedJpaRepository<A, Long> attachRepository;

	@Autowired
	protected JpaRepository<T, Long> owningEntityRepository;

	@Autowired
	protected QuerydslPredicateExecutor<A> attachFinder;

	@Autowired
	private Validator validator;

	public BaseAttachmentSupport() {
	}

	protected BaseAttachmentSupport(NumberPath<Long> owningEntityId, NumberPath<Long> qAttachId) {
		this.qActionOwningEntityId = owningEntityId;
		this.qAttachId = qAttachId;
	}

	@Override
	public A createFast(A source) {
		// FIXME temporary measure
		return create(source);
	}

	@Override
	public A updateFast(A updated, A target) {
		// FIXME temporary measure
		return update(updated, target);
	}

	@Override
	@Transactional
	public A uploadFile(T entity, MultipartFile file, R metadata) throws IOException, InvalidRepositoryPathException, InvalidRepositoryFileDataException {
		T savedEntity = owningEntityRepository.getReferenceById(entity.getId());

		Path repositoryPath = createRepositoryPath(savedEntity);
		log.info("Upload file {} to path {}", file.getOriginalFilename(), repositoryPath);
		RepositoryFile uploadedFile = repositoryService.addFile(repositoryPath, file.getOriginalFilename(), file.getContentType(), file.getInputStream(), metadata.fileMetadata);

		// make virtualPath
		String virtualPath = Paths.get(uploadedFile.getFolder().getPath() + "/" + uploadedFile.getOriginalFilename()).toString();

		A attach = createAttach(savedEntity, metadata.attachMetadata);
		attach.setContentType(uploadedFile.getContentType());
		attach.setTitle(uploadedFile.getOriginalFilename());
		attach.setVirtualPath(virtualPath);
		attach.setRepositoryFile(uploadedFile);
		Set<ConstraintViolation<A>> violations = validator.validate(attach);
		if (violations != null && !violations.isEmpty()) {
			// remove file
			try {
				repositoryService.removeFile(uploadedFile);
				log.warn("Removed {} from repository", uploadedFile);
			} catch (NoSuchRepositoryFileException e) {
				log.warn(e.getMessage());
			}
			throw new ConstraintViolationException("Invalid attach", violations);
		}

		A savedAttach = attachRepository.save(attach);
		return _lazyLoad(savedAttach);
	}

	@Override
	@Transactional
	public A removeFile(T entity, Long attachmentId) {
		entity = owningEntityRepository.getReferenceById(entity.getId());

		A toDelete = attachFinder.findOne(qActionOwningEntityId.eq(entity.getId()).and(qAttachId.eq(attachmentId)))
				.orElseThrow(() -> new NotFoundElement("No such attach for provided entity"));

		// Note: repository file must be deleted in the AttachmentAspect
		attachRepository.delete(toDelete);
		return toDelete;
	}

	protected abstract Path createRepositoryPath(T entity);

	protected abstract A createAttach(T entity, A attachMetadata);
}