de.terrestris.shoguncore.service.FileService Maven / Gradle / Ivy
package de.terrestris.shoguncore.service;
import de.terrestris.shoguncore.dao.FileDao;
import de.terrestris.shoguncore.model.File;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
/**
* Service class for the {@link File} model.
*
* @author Daniel Koch
* @author Johannes Weskamm
*/
@Service("fileService")
public class FileService>
extends PermissionAwareCrudService {
/**
* Default constructor, which calls the type-constructor
*/
@SuppressWarnings("unchecked")
public FileService() {
this((Class) File.class);
}
/**
* Constructor that sets the concrete entity class for the service.
* Subclasses MUST call this constructor.
*/
protected FileService(Class entityClass) {
super(entityClass);
}
/**
* We have to use {@link Qualifier} to define the correct dao here.
* Otherwise, spring can not decide which dao has to be autowired here
* as there are multiple candidates.
*/
@Override
@Autowired
@Qualifier("fileDao")
public void setDao(D dao) {
this.dao = dao;
}
/**
* Method persists a given MultipartFile as a bytearray in the database
*
* @param file
* @throws Exception
*/
@PreAuthorize("isAuthenticated()")
public E uploadFile(MultipartFile file) throws Exception {
if (file == null) {
final String errMsg = "Upload failed. File is null.";
logger.error(errMsg);
throw new Exception(errMsg);
} else if (file.isEmpty()) {
final String errMsg = "Upload failed. File is empty.";
logger.error(errMsg);
throw new Exception(errMsg);
}
InputStream is = null;
byte[] fileByteArray = null;
E fileToPersist = getEntityClass().newInstance();
try {
is = file.getInputStream();
fileByteArray = IOUtils.toByteArray(is);
} catch (Exception e) {
throw new Exception("Could not create the bytearray: " + e.getMessage());
} finally {
IOUtils.closeQuietly(is);
}
fileToPersist.setFile(fileByteArray);
fileToPersist.setFileType(file.getContentType());
fileToPersist.setFileName(file.getOriginalFilename());
dao.saveOrUpdate(fileToPersist);
return fileToPersist;
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy