Leonardo Vannucci
2018-08-10 09740e77ea352852ff90b738787f7f6aa657b604
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package it.digione.dg1cloud.service;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
 
import javax.servlet.ServletContext;
 
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.util.UriBuilder;
import org.springframework.web.util.UriComponentsBuilder;
 
import it.digione.dg1cloud.config.AppConfig;
import it.digione.dg1cloud.model.RegDocument;
import it.digione.dg1cloud.repository.RegDocumentRepository;
 
@Service("utils")
public class Utils {
   
   @Autowired private AppConfig appConfig;
   @Autowired private RegDocumentRepository regDocumentRepository;
   @Autowired private ServletContext servletContext;
   
   private static final Logger logger = LoggerFactory.getLogger(CloudService.class);
   
   public URL generateUrl(RegDocument regDocument) throws MalformedURLException {
       logger.debug("Genero l'url per il record file {} con id {}", regDocument.getFileName(), regDocument.getDocumentId());
       UriBuilder uriBuilder = UriComponentsBuilder.fromUriString(appConfig.getExternalBaseUrl());
       uriBuilder.path("/download");
       uriBuilder.queryParam("fileName", regDocument.getFileName());
       uriBuilder.queryParam("id", regDocument.getDocumentId());
       if ( Strings.isEmpty(regDocument.getSecretKey()) == false ) {
           uriBuilder.queryParam("secretKey", regDocument.getSecretKey());
       }
       return uriBuilder.build().toURL();
   }
   
   public void deleteDir( File directory ) throws IOException {
       logger.debug("Rimozione directory {}", directory.getAbsolutePath());
       FileUtils.deleteDirectory(directory);
   }
   
   public void deleteEmptyDirectoriesRecursive( File directory) throws IOException {
       for (File subDirectory : directory.listFiles(File::isDirectory) ) {
           logger.debug("Analizzo sottodirectory {}", subDirectory.getAbsolutePath());
           deleteEmptyDirectoriesRecursive(subDirectory);
       }
       if ( directory.listFiles().length == 0 ) {
           logger.debug("La directory {} e' vuota", directory.getAbsolutePath());
           deleteDir(directory);
       } else {
           logger.debug("La directory {} non e' vuota", directory.getAbsolutePath());
       }
   }
   
   public ResponseEntity<InputStreamResource> getDownloadResponseEntity(String fileName, long id, String secretKey)
           throws FileNotFoundException {
       logger.debug("Avvio download file {} con id {}", fileName, id);
       
       MediaType mediaType = MediaType.APPLICATION_OCTET_STREAM;
       try {
           mediaType = MediaType.parseMediaType(servletContext.getMimeType(fileName));
       } catch (Exception e) {
           logger.warn("Errore nello stabilire il mime type del file. VerrĂ  usato " + mediaType.toString(), e);
       }
       
       RegDocument regDocument = regDocumentRepository.getOne(id);
       
       if (regDocument.getFileName().equalsIgnoreCase(fileName) == false ) {
           logger.error("Il nome del file richiesto non corrisponde con quello referenziato dall'id");
           throw new RuntimeException("Il nome del file richiesto non corrisponde con quello referenziato dall'id");
       }
       
       if ( regDocument.getSecretKey() != null ) {
           logger.debug("E' stata specificata una secretKey. Avvio le verifiche.");
           if ( Strings.isEmpty(secretKey) == true ) {
               logger.error("Non e' stata inviata la secretKey");
               throw new RuntimeException("Per scaricare il file occorre specificare la secretKey");
           } else {
               logger.debug("Controllo corrispondenza della secretKey");
               if (secretKey.equals(regDocument.getSecretKey()) == false ) {
                   logger.error("La secretKey inviata non corrisponde a quella impostata in fase di richiesta salvataggio del file");
                   throw new RuntimeException("La secretKey inviata non corrisponde a quella impostata in fase di richiesta salvataggio del file");
               } else {
                   logger.debug("SecretKey verificata correttamente");
               }
           }
       }
       
       File file = new File(regDocument.getFilePath());
       FileInputStream fis = new FileInputStream(file);
       InputStreamResource isr = new InputStreamResource(fis);
       return ResponseEntity.ok()
               // Content-Disposition
               .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + file.getName())
               // Content-Type
               .contentType(mediaType)
               // Contet-Length
               .contentLength(file.length()) //
               .body(isr);
   }
}