MetadataInStorageAspect.java

/*
 * Copyright 2018 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.filerepository.service.aspect;

import java.io.IOException;
import java.nio.charset.Charset;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.genesys.filerepository.model.RepositoryFile;
import org.genesys.filerepository.service.BytesStorageService;
import org.springframework.beans.factory.annotation.Autowired;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

import lombok.extern.slf4j.Slf4j;

/**
 * Make sure that repository metadata is persisted as .json next to the data
 * bytes in {@link BytesStorageService}. Any change to the repository records
 * triggers a regeneration and rewrite of the .json file.
 *
 * On delete, the .json file is removed from {@link BytesStorageService}.
 *
 * @author Matija Obreza
 */
@Aspect
@Slf4j
public class MetadataInStorageAspect {

	/** The Constant UTF8. */
	private static final Charset UTF8 = Charset.forName("UTF8");

	/** The bytes storage service. */
	@Autowired
	private BytesStorageService bytesStorageService;

	/** The object writer. */
	private final ObjectWriter objectWriter;

	{
		log.warn("Instantiated {}", getClass().getName());
		var mapper = new ObjectMapper().disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
		mapper.registerModule(new JavaTimeModule());
		objectWriter = mapper.writerWithDefaultPrettyPrinter();
	}

	/**
	 * After repository image save iterable.
	 *
	 * @param joinPoint the join point
	 * @param repositoryFiles the repository files
	 * @return the object
	 */
	@AfterReturning(value = "execution(* org.genesys.filerepository.RepositoryPersistence.save(*))", returning = "repositoryFiles")
	public Object afterRepositoryImageSaveIterable(final JoinPoint joinPoint, final Iterable<RepositoryFile> repositoryFiles) {

		log.debug("Many files were saved: {}", repositoryFiles);

		if (repositoryFiles != null) {
			repositoryFiles.forEach(rf -> {
				try {
					updateMetadata(rf);
				} catch (final IOException e) {
					log.error(e.getMessage());
				}
			});
		}

		return repositoryFiles;
	}

	/**
	 * After repository image save.
	 *
	 * @param joinPoint the join point
	 * @param repositoryFile the repository file
	 * @return the object
	 */
	@AfterReturning(value = "execution(* org.genesys.filerepository.RepositoryPersistence.save(*))", returning = "repositoryFile")
	public Object afterRepositoryImageSave(final JoinPoint joinPoint, final RepositoryFile repositoryFile) {

		log.trace("1 file was saved: {}", repositoryFile);

		try {
			updateMetadata(repositoryFile);
		} catch (final IOException e) {
			log.error(e.getMessage());
		}

		return repositoryFile;
	}

	/**
	 * After repository files delete.
	 *
	 * @param joinPoint the join point
	 * @param repositoryFiles the repository files
	 * @return the object
	 */
	@AfterReturning(value = "execution(* org.genesys.filerepository.RepositoryPersistence.delete(*)) && args(repositoryFiles)")
	public Object afterRepositoryFilesDelete(final JoinPoint joinPoint, final Iterable<RepositoryFile> repositoryFiles) {

		if (repositoryFiles != null) {
			repositoryFiles.forEach(rf -> {
				try {
					removeMetadata(rf);
				} catch (final IOException e) {
					log.error(e.getMessage());
				}
			});
		}

		return repositoryFiles;
	}

	/**
	 * After repository image delete.
	 *
	 * @param joinPoint the join point
	 * @param repositoryFile the repository file
	 * @return the object
	 */
	@AfterReturning(value = "execution(* org.genesys.filerepository.RepositoryPersistence.delete(*)) && args(repositoryFile)")
	public Object afterRepositoryImageDelete(final JoinPoint joinPoint, final RepositoryFile repositoryFile) {

		try {
			removeMetadata(repositoryFile);
		} catch (final IOException e) {
			log.error(e.getMessage());
		}

		return repositoryFile;
	}

	/**
	 * Update metadata.
	 *
	 * @param repositoryFile the repository file
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	private void updateMetadata(final RepositoryFile repositoryFile) throws IOException {
		if (repositoryFile == null) {
			return;
		}
		log.trace("File was updated path={} originalFilename={}. Writing metadata.json", repositoryFile.getFolder(), repositoryFile.getOriginalFilename());

		try {
			final String metadataJson = objectWriter.writeValueAsString(repositoryFile);

			try {
				bytesStorageService.upsert(repositoryFile.storageFolder().resolve(repositoryFile.getMetadataFilename()), metadataJson.getBytes(UTF8));
			} catch (final IOException e) {
				log.debug("Failed to upload metadata bytes", e);
				throw e;
			}

		} catch (final JsonProcessingException e) {
			log.error("Could not serialize repositoryFile to JSON: {}", e.getMessage(), e);
		}
	}

	/**
	 * Removes the metadata.
	 *
	 * @param repositoryFile the repository file
	 * @throws IOException Signals that an I/O exception has occurred.
	 */
	private void removeMetadata(final RepositoryFile repositoryFile) throws IOException {
		if (repositoryFile == null) {
			return;
		}

		log.trace("File was deleted path={} originalFilename={}. Removing metadata.json", repositoryFile.getFolder(), repositoryFile.getOriginalFilename());

		try {
			bytesStorageService.remove(repositoryFile.storageFolder().resolve(repositoryFile.getMetadataFilename()));
		} catch (final IOException e) {
			log.debug("Failed to delete metadata bytes", e);
			throw e;
		}
	}

}