Leonardo Vannucci
2018-09-17 13c46f877d0540f22b16f80facd7e60de74490fa
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
package it.digione.dg1cloud.service;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDate;
import java.time.ZoneId;
 
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
 
import it.digione.dg1cloud.config.AppConfig;
import it.digione.dg1cloud.model.RegDocument;
import it.digione.dg1cloud.pojo.UploadedFileDescriptor;
import it.digione.dg1cloud.pojo.UploadedFileDescriptorOk;
import it.digione.dg1cloud.repository.RegDocumentRepository;
 
@Service("cloudService")
public class CloudService {
 
   private static final Logger logger = LoggerFactory.getLogger(CloudService.class);
   
   @Autowired private AppConfig appConfig;
   @Autowired private Utils utils;
   @Autowired private RegDocumentRepository regDocumentRepository;
   
   public void scannAccountHomeDirs() throws JsonParseException, JsonMappingException, NoSuchAlgorithmException, IOException {
       
       String repositoryPath = appConfig.getRepositoryBaseUploadPath();
       File basePath = new File(repositoryPath);
       
       if ( basePath.exists() == false || basePath.isDirectory() == false )
           throw new RuntimeException("La directory '" + basePath.getAbsolutePath() + "' non esiste oppure non e' una directory");
       
       for ( File folder : basePath.listFiles(File::isDirectory)) {
           for ( File descriptor : folder.listFiles(
               (dir, name) -> {
                   return name.toLowerCase().endsWith(".dg1cloud");
               }))
           {
               boolean checkFile = false;
               try {
                   checkFile = checkFile(descriptor.getAbsolutePath());
               } catch (Exception e ) {
                   logger.error("Errore durante la fase di verifica del file", e);
                   writeKoFile(descriptor.getAbsolutePath(), "Errore durante la fase di verifica del file\n" + e.getMessage());
                   continue;
               }
               
               if ( checkFile == true ) {
                   logger.debug("Controllo file descrittore completato con successo");
                   try {
                       storeFile(descriptor.getAbsolutePath());
                   } catch (Exception e) {
                       writeKoFile(descriptor.getAbsolutePath(), "Errore duranto la memorizzazione del file nello store\n" + e.getMessage());
                   }
               } else {
                   logger.debug("Il file non ha passato le verifiche");
               }
           }
       }
   }
   
   public boolean checkFile(String cloudFileDescriptorPath) throws IOException, NoSuchAlgorithmException {
       logger.debug("Controllo il file {}", cloudFileDescriptorPath);
       
       TypeReference<UploadedFileDescriptor> typeReference = new TypeReference<UploadedFileDescriptor>() {};
       File cloudFileDescriptor = new File(cloudFileDescriptorPath);
       
       String koMessage = null;
       
       if ( cloudFileDescriptor.exists() == false ) {
           koMessage = "Il file descrittore inviato '" + cloudFileDescriptor + "' non esiste";
           writeKoFile(cloudFileDescriptorPath, koMessage);
           return false;
       }
       
       if ( cloudFileDescriptor.isFile() == false ) {
           koMessage = "Il file descrittore inviato '" + cloudFileDescriptor + "' non e' di tipo file";
           writeKoFile(cloudFileDescriptorPath, koMessage);
           return false;
       }
       
       InputStream is = new FileInputStream(cloudFileDescriptor);
       
       ObjectMapper mapper = new ObjectMapper();
       
       UploadedFileDescriptor uploadedFileDescriptor;
       try {
           uploadedFileDescriptor = mapper.readValue(is, typeReference);
       } catch (IOException e) {
           koMessage = "Il file descrittore non conforme:\n" + e.getMessage();
           writeKoFile(cloudFileDescriptorPath, koMessage);
           return false;
       }
       
       is.close();
       
       File uploadedFile = new File(cloudFileDescriptor.getParentFile(), uploadedFileDescriptor.getFileName());
       if ( uploadedFile.exists() == false ) {
           koMessage = "Il file inviato '" + uploadedFile + "' non esiste";
           writeKoFile(cloudFileDescriptorPath, koMessage);
           return false;
       }
       
       if ( uploadedFile.isFile() == false ) {
           koMessage = "Il file inviato '" + uploadedFile + "' non e' di tipo file";
           writeKoFile(cloudFileDescriptorPath, koMessage);
           return false;
       }
       
       FileInputStream fis = new FileInputStream(uploadedFile);
       String hash = DigestUtils.sha256Hex(fis);
       fis.close();
       
       if ( hash.equalsIgnoreCase(uploadedFileDescriptor.getSha256()) == false ) {
           koMessage = "L'hash del file inviato non corrisponde con l'hash dichiarato nel descrittore del file:\n\t" +
                   "hash file inviato: " + hash + "\n\t" +
                   "hash dichiarato nel descrittore: " + uploadedFileDescriptor.getSha256();
           writeKoFile(cloudFileDescriptorPath, koMessage);
           return false;
       }
       
       return true;
   }
   
   public void storeFile(String cloudFileDescriptorPath) {
       logger.debug("Avvio processo di memorizzazione file nello store");
       TypeReference<UploadedFileDescriptor> typeReference = new TypeReference<UploadedFileDescriptor>() {};
       File cloudFileDescriptor = new File(cloudFileDescriptorPath);
       
       InputStream is;
       try {
           is = new FileInputStream(cloudFileDescriptor);
       } catch (FileNotFoundException e) {
           throw new RuntimeException("Errore apertura stream file descrittore", e);
       }
       
       ObjectMapper mapper = new ObjectMapper();
       
       UploadedFileDescriptor uploadedFileDescriptor;
       try {
           uploadedFileDescriptor = mapper.readValue(is, typeReference);
       } catch (IOException e) {
           throw new RuntimeException("Errore caricamento classe dal json del descrittore", e);
       }
       
       logger.debug("Controllo esistenza file sul db");
       RegDocument regDocument = regDocumentRepository.findOneByHashAndName(uploadedFileDescriptor.getSha256(), uploadedFileDescriptor.getFileName());
       
       String userName = cloudFileDescriptor.getParentFile().getName();
       
       File uploadedFile = new File(getUploadedFilePath(cloudFileDescriptorPath));
       
       if ( regDocument == null ) {
           
           logger.debug("Creazione nuovo record per il documento da conservare");
           regDocument = new RegDocument();
           regDocument.setCreatedBy(userName);
           regDocument.setModifiedBy(userName);
           regDocument.setFileHash(uploadedFileDescriptor.getSha256());
           regDocument.setFileName(uploadedFileDescriptor.getFileName());
           regDocument.setFileSize(uploadedFile.length());
           regDocument.setDueDate(uploadedFileDescriptor.getDueDate());
           regDocument.setFilePath("");
           regDocument.setSecretKey(uploadedFileDescriptor.getSecretKey());
           
           regDocumentRepository.save(regDocument);
           
       } else {
           logger.debug("Trovato 1 record per il documento da memorizzare");
       }
       
       try {
           moveUploadedFileToStorage(uploadedFile.getAbsolutePath(), regDocument);
       } catch (Exception e) {
           try {
               writeKoFile(cloudFileDescriptorPath, e.getMessage());
           } finally {
               logger.debug("Rimozione regDocument");
               regDocumentRepository.delete(regDocument);
           }
       }
       try {
           createOkFile(cloudFileDescriptorPath, regDocument);
       } catch (Exception e) {
           try {
               writeKoFile(cloudFileDescriptorPath, e.getMessage());
           } finally {
               logger.debug("Rimozione regDocument");
               regDocumentRepository.delete(regDocument);
           }
       }
   }
   
   private void moveUploadedFileToStorage( String source, RegDocument regDocument ) throws IOException {
       logger.debug("Spostamento file nello storage");
       
       String sha256Descriptor = regDocument.getFileHash();
       
       File sourceFile = new File(source);
       File destinationFile = new File(generateStoragePath(regDocument));
       
       if ( destinationFile.exists() == false ) {
           logger.debug("Creazione alberatura directory: " + destinationFile.getParent());
           FileUtils.forceMkdirParent(destinationFile);
           FileUtils.copyFile(sourceFile, destinationFile);
       } else {
           logger.debug("Il file risulta gia' presente nello storage. Verifico l'integrita'");
           FileInputStream fis = new FileInputStream(destinationFile);
           String hash = DigestUtils.sha256Hex(fis);
           fis.close();
           if ( sha256Descriptor.equalsIgnoreCase(hash) == false ) {
               throw new IllegalStateException("L'hash del file nello storage non corrisponde con l'hash dichiarato nel descrittore del file:\n\t" +
                   "hash file inviato: " + hash + "\n\t" +
                   "hash dichiarato nel descrittore: " + sha256Descriptor);
           }
       }
       
       regDocument.setFilePath(destinationFile.getAbsolutePath());
       logger.debug("Salvo il path nel regDocument: {}", regDocument.getFilePath());
       regDocumentRepository.save(regDocument);
   }
   
   private void createOkFile( String cloudFileDescriptorPath, RegDocument regDocument ) throws IOException {
       logger.debug("Creazione file di OK");
       
       File fileDescriptor = new File(cloudFileDescriptorPath);
       File okFile = new File(fileDescriptor.getParentFile(), fileDescriptor.getName() + ".ok");
       
       ObjectMapper mapper = new ObjectMapper();
       mapper.enable(SerializationFeature.INDENT_OUTPUT);
       mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
       
       UploadedFileDescriptorOk uploadedFileDescriptorOk = new UploadedFileDescriptorOk();
       
       uploadedFileDescriptorOk.setFileName(regDocument.getFileName());
       
       URL url = utils.generateUrl(regDocument);
       
       uploadedFileDescriptorOk.setUrl(url.toExternalForm());
       
       try {
           String json = mapper.writeValueAsString(uploadedFileDescriptorOk);
           logger.debug("Scrittura json di ok:\n{}", json);
           FileUtils.writeStringToFile(okFile, json, StandardCharsets.UTF_8);
       } catch (IOException e) {
           throw new RuntimeException("Errore nella scrittura del file di OK", e);
       }
       
       File cloudFile = new File( getUploadedFilePath(cloudFileDescriptorPath) );
       if (cloudFile.exists() == true )
           FileUtils.deleteQuietly(cloudFile);
       
       try {
           FileUtils.forceDelete(fileDescriptor);
       } catch (IOException e) {
           throw new RuntimeException("Errore rimozione del file descrittore", e);
       }
   }
   
   public void writeKoFile( String cloudFileDescriptorPath, String errorMessage )  {
       logger.debug("Si e' verificato il seguente errore nella verifica tramite {}: {}", cloudFileDescriptorPath, errorMessage);
       
       File fileDescriptor = new File(cloudFileDescriptorPath);
       File koFile = new File(fileDescriptor.getParentFile(), fileDescriptor.getName() + ".ko");
       
       try {
           FileUtils.writeStringToFile(koFile, errorMessage, StandardCharsets.UTF_8);
       } catch (IOException e) {
           throw new RuntimeException("Errore nella scrittura del file di KO", e);
       }
       
       File cloudFile = new File( getUploadedFilePath(cloudFileDescriptorPath) );
       if (cloudFile.exists() == true )
           FileUtils.deleteQuietly(cloudFile);
       
       try {
           FileUtils.forceDelete(fileDescriptor);
       } catch (IOException e) {
           throw new RuntimeException("Errore rimozione del file descrittore", e);
       }
   }
   
   public String getUploadedFilePath( String cloudFileDescriptorPath ) {
       File fileDescriptor = new File(cloudFileDescriptorPath);
       return fileDescriptor.getParentFile().getAbsolutePath() + File.separator + FilenameUtils.getBaseName(fileDescriptor.getName());
   }
   
   private String generateStoragePath( RegDocument regDocument ) {
       
       if ( regDocument.getCreated() == null )
           throw new IllegalStateException("La data di creazione del RegDocument non e' valorizzata");
       
       LocalDate localDate = regDocument.getCreated().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
       int year = localDate.getYear();
       int month = localDate.getMonthValue();
       int day = localDate.getDayOfMonth();
       
       StringBuffer sb = new StringBuffer();
       sb.append(appConfig.getRepositoryBaseStoragePath());
       sb.append(File.separator);
       sb.append(regDocument.getCreatedBy());
       sb.append(File.separator);
       sb.append(year);
       sb.append(File.separator);
       sb.append(month);
       sb.append(File.separator);
       sb.append(day);
       sb.append(File.separator);
       sb.append(regDocument.getDocumentId());
       sb.append(File.separator);
       sb.append(regDocument.getFileName());
       
       return sb.toString();
   }
}