1 package media;
2
3
4 import java.io.*;
5 import java.nio.file.Files;
6 import java.nio.file.Path;
7 import java.util.UUID;
8
9 /**
10 * Classe che incapsula la logica per il ritrovo di media (immagini) dal filesystem
11 */
12 public class MediaRepository implements Serializable{
13
14 private Path uploadRoot = Path.of(System.getProperty("openejb.home"), "uploads");
15 private final long sizeLimit = 5*1024*1024; //todo: parametrizza nel metodo insert
16
17 /**
18 * Costruttore vuoto
19 * @return nuova istanza di MediaRepository
20 */
21 public MediaRepository(){}
22
23 /**
24 * Costruttore con parametro per settare uploadRoot
25 * @param uploadRoot oggetto Path per settare uploadRoot
26 * @return nuova istanza di MediaRepository
27 */
28 public MediaRepository(Path uploadRoot){
29 this.uploadRoot = uploadRoot;
30 }
31
32 /**
33 * Salva un file nel filesystem e ne restituisce il nome
34 * @param stream stream di dati
35 * @param filename nome del file da salvare
36 * @throws ReadLimitExceededException se il file supera i 5MB
37 * @throws IOException
38 * @return nuova istanza di MediaRepository
39 */
40 public String insert(InputStream stream, String filename) throws IOException {
41 Files.createDirectories(uploadRoot);
42 File file = new File(uploadRoot.toFile(), filename);
43 Files.copy(new LimitedInputStream(stream,sizeLimit), file.toPath());
44 return filename;
45 }
46
47 /**
48 * Salva un file nel filesystem e ne restituisce un nome univoco generato in maniera casuale
49 * @param stream stream di dati
50 * @throws IOException
51 * @return nuova istanza di MediaRepository
52 */
53 public String insert(InputStream stream) throws IOException {
54 return insert(stream, UUID.randomUUID().toString());
55 }
56
57 /**
58 * Rimuove un file dal filesystem dato un nome se esiste
59 * @param filename nome del file
60 * @throws IOException
61 */
62 public void remove(String filename) throws IOException {
63 boolean successful = Files.deleteIfExists(uploadRoot.resolve(filename));
64 // if (!successful) { ???? }
65 }
66
67 /**
68 * Restituisce un file dal filesystem dato un nome se esiste altrimenti restituisce null
69 * @param filename nome del file
70 * @return stream di dati del file o null
71 */
72 public InputStream get(String filename){
73 File file = new File(uploadRoot.toFile(), filename);
74 if (!file.exists() || !file.isFile())
75 return null;
76 try {
77 return new FileInputStream(file);
78 } catch (FileNotFoundException e) {
79 return null;
80 }
81 }
82
83 }