1 package fr.ifremer.quadrige3.synchro.server.resource;
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 import fr.ifremer.quadrige3.core.dao.technical.Files;
28 import fr.ifremer.quadrige3.synchro.server.config.SynchroServerConfiguration;
29 import fr.ifremer.quadrige3.synchro.server.security.SecurityContextHelper;
30 import org.apache.commons.io.FileUtils;
31 import org.apache.commons.io.FilenameUtils;
32 import org.apache.commons.lang3.StringUtils;
33 import org.apache.wicket.WicketRuntimeException;
34 import org.apache.wicket.request.resource.AbstractResource;
35 import org.springframework.util.MimeTypeUtils;
36
37 import java.io.*;
38
39 public class DownloadFileResource extends AbstractResource {
40
41 private static final long serialVersionUID = 1L;
42
43 private static final String PARAM_TYPE = "type";
44 private static final String PARAM_FILE = "file";
45
46 @Override
47 protected ResourceResponse newResourceResponse(Attributes attributes) {
48
49 String type = attributes.getParameters().get(PARAM_TYPE).toString();
50 String fileName = attributes.getParameters().get(PARAM_FILE).toString();
51 ResourceResponse resourceResponse = new ResourceResponse();
52
53
54 if (StringUtils.isBlank(type) || StringUtils.isBlank(fileName)) {
55 resourceResponse.setError(404);
56 return resourceResponse;
57 }
58
59 final File file = getFile(type, fileName);
60 if (file == null || !file.exists()) {
61 resourceResponse.setError(404);
62 return resourceResponse;
63 }
64
65
66 String contentType = "application/download";
67 if (FilenameUtils.isExtension(file.getName(), "properties")) {
68 contentType = MimeTypeUtils.TEXT_PLAIN.getType();
69 }
70 resourceResponse.setContentType(contentType);
71
72
73 resourceResponse.setFileName(fileName);
74
75 long fileLength = FileUtils.sizeOf(file);
76 resourceResponse.setContentLength(fileLength);
77
78 resourceResponse.setWriteCallback(new WriteCallback() {
79 @Override
80 public void writeData(Attributes attributes) {
81
82 try (OutputStream os = attributes.getResponse().getOutputStream();
83 InputStream is = new BufferedInputStream(new FileInputStream(file))) {
84
85 Files.copyStream(is, os);
86
87 } catch (IOException e) {
88 throw new WicketRuntimeException("Error while writing file content to response", e);
89 }
90 }
91 });
92
93 return resourceResponse;
94 }
95
96 private File getFile(String type, String filename) {
97 SynchroServerConfiguration config = SynchroServerConfiguration.getInstance();
98
99 int userId = SecurityContextHelper.getPrincipalUserId();
100 if ("import".equalsIgnoreCase(type)) {
101 return new File(config.getSynchroImportDirectoryByUser(userId), filename);
102 }
103 if ("export".equalsIgnoreCase(type)) {
104 return new File(config.getSynchroExportDirectoryByUser(userId), filename);
105 }
106 if ("install".equalsIgnoreCase(type)) {
107 return new File(config.getSynchroDirectory(), filename);
108 }
109
110 return null;
111 }
112 }