VirusScanAspect.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.File;
import java.io.IOException;
import java.nio.file.Path;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.genesys.filerepository.service.VirusFoundException;
import org.genesys.filerepository.service.VirusScanner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

/**
 * Scans files with VirusScanner before storing to the byteService.
 *
 * @author Matija Obreza
 */
@Aspect
@Component
@Slf4j
public class VirusScanAspect {

	/** The VirusScanner. */
	@Autowired(required = false)
	private VirusScanner virusScanner;

	/**
	 * Before bytes upsert.
	 *
	 * @param bytesFile the path
	 * @param data the data
	 * @throws Throwable the throwable
	 */
	@Before(value = "execution(void org.genesys.filerepository.service.BytesStorageService.upsert(..)) && args(bytesFile,data)")
	public void beforeBytesUpsert(final Path bytesFile, final byte[] data) throws Throwable {

		if (virusScanner != null) {
			log.info("Scaning data for viruses before storing path={}", bytesFile);
			try {
				virusScanner.scan(data);
			} catch (final VirusFoundException e) {
				log.warn("**VIRUS** in {}: {}", bytesFile, e.getMessage());
				throw new IOException(e);
			}
		} else {
			log.info("Virus scanner is not available, storing bytes without scanning.");
		}
	}


	/**
	 * Before bytes upsert.
	 *
	 * @param bytesFile the path
	 * @param fileWithData the file with data
	 * @throws Throwable the throwable
	 */
	@Before(value = "execution(void org.genesys.filerepository.service.BytesStorageService.upsert(..)) && args(bytesFile,fileWithData)")
	public void beforeBytesUpsert(final Path bytesFile, final File fileWithData) throws Throwable {

		if (virusScanner != null) {
			log.info("Scaning data for viruses before storing path={}", bytesFile);
			try {
				virusScanner.scan(fileWithData);
			} catch (final VirusFoundException e) {
				log.warn("**VIRUS** in {}: {}", bytesFile, e.getMessage());
				throw new IOException(e);
			}
		} else {
			log.info("Virus scanner is not available, storing bytes without scanning.");
		}
	}
}