68 lines
2.4 KiB
Java
68 lines
2.4 KiB
Java
package eu.openaire.urls_worker.services;
|
|
|
|
import eu.openaire.urls_worker.exceptions.FileStorageException;
|
|
import org.slf4j.Logger;
|
|
import org.slf4j.LoggerFactory;
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
import org.springframework.core.io.Resource;
|
|
import org.springframework.core.io.UrlResource;
|
|
import org.springframework.stereotype.Service;
|
|
|
|
import java.io.File;
|
|
import java.io.FileReader;
|
|
import java.io.IOException;
|
|
import java.nio.file.Files;
|
|
import java.nio.file.Path;
|
|
import java.nio.file.Paths;
|
|
import java.util.Properties;
|
|
|
|
|
|
@Service
|
|
public class FileStorageService {
|
|
|
|
private static final Logger logger = LoggerFactory.getLogger(FileStorageService.class);
|
|
|
|
public static Path assignmentsLocation = null;
|
|
|
|
static {
|
|
String springPropertiesFile = System.getProperty("user.dir") + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator + "application.properties";
|
|
FileReader fReader = null;
|
|
try {
|
|
fReader = new FileReader(springPropertiesFile);
|
|
Properties props = new Properties();
|
|
props.load(fReader); // Load jdbc related properties.
|
|
String assignmentsDir = props.getProperty("file.assignments-dir");
|
|
assignmentsLocation = Paths.get(assignmentsDir).toAbsolutePath().normalize();
|
|
} catch (java.io.FileNotFoundException fnfe) {
|
|
logger.error("The properties file was not found!", fnfe);
|
|
System.exit(-10);
|
|
} catch (IOException ioe) {
|
|
logger.error("I/O error when reading the properties file!", ioe);
|
|
System.exit(-11);
|
|
}
|
|
}
|
|
|
|
|
|
@Autowired
|
|
public FileStorageService() throws FileStorageException {
|
|
try {
|
|
Files.createDirectories(assignmentsLocation);
|
|
} catch (Exception ex) {
|
|
throw new FileStorageException("Could not create the directory where the uploaded files will be stored.", ex);
|
|
}
|
|
}
|
|
|
|
|
|
public Resource loadFileAsResource(String fullFileName) {
|
|
try {
|
|
Path filePath = assignmentsLocation.resolve(fullFileName).normalize();
|
|
Resource resource = new UrlResource(filePath.toUri());
|
|
return resource.exists() ? resource : null;
|
|
} catch (Exception e) {
|
|
logger.error("Error when loading file: " + fullFileName, e);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
}
|