it.micegroup.voila2runtime.attachment.serviceImpl.StorageServiceImpl Maven / Gradle / Ivy
package it.micegroup.voila2runtime.attachment.serviceImpl;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.stream.Stream;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.FileSystemUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import it.micegroup.voila2runtime.attachment.service.StorageException;
import it.micegroup.voila2runtime.attachment.service.StorageFileNotFoundException;
import it.micegroup.voila2runtime.attachment.service.StorageService;
@Service
public class StorageServiceImpl implements StorageService {
private Path uploadedFilePath;
public Path getUploadedFilePath() {
return uploadedFilePath;
}
@Override
public void setUploadedFilePath(Path uploadedFilePath) {
this.uploadedFilePath = uploadedFilePath;
}
@Override
public void store(MultipartFile file) {
String filename = StringUtils.cleanPath(file.getOriginalFilename());
try {
if (file.isEmpty()) {
throw new StorageException("Failed to store empty file " + filename);
}
if (filename.contains("..")) {
// This is a security check
throw new StorageException(
"Cannot store file with relative path outside current directory " + filename);
}
try (InputStream inputStream = file.getInputStream()) {
Files.copy(inputStream, this.uploadedFilePath.resolve(filename), StandardCopyOption.REPLACE_EXISTING);
}
} catch (IOException e) {
throw new StorageException("Failed to store file " + filename, e);
}
}
@Override
public Stream loadAll() {
try {
return Files.walk(this.uploadedFilePath, 1).filter(path -> !path.equals(this.uploadedFilePath))
.map(this.uploadedFilePath::relativize);
} catch (IOException e) {
throw new StorageException("Failed to read stored files", e);
}
}
@Override
public Path load(String filename) {
return uploadedFilePath.resolve(filename);
}
@Override
public Resource loadAsResource(String filename) {
try {
Path file = load(filename);
Resource resource = new UrlResource(file.toUri());
if (resource.exists() || resource.isReadable()) {
return resource;
} else {
throw new StorageFileNotFoundException("Could not read file: " + filename);
}
} catch (MalformedURLException e) {
throw new StorageFileNotFoundException("Could not read file: " + filename, e);
}
}
@Override
public void deleteAll() {
FileSystemUtils.deleteRecursively(uploadedFilePath.toFile());
}
@Override
public void init() {
try {
Files.createDirectories(uploadedFilePath);
} catch (IOException e) {
throw new StorageException("Could not initialize storage", e);
}
}
}