View Javadoc
1   package fr.ifremer.quadrige3.synchro.server.technical;
2   
3   /*-
4    * #%L
5    * Quadrige3 Core :: Quadrige3 Synchro server
6    * $Id:$
7    * $HeadURL:$
8    * %%
9    * Copyright (C) 2017 Ifremer
10   * %%
11   * This program is free software: you can redistribute it and/or modify
12   * it under the terms of the GNU Affero General Public License as published by
13   * the Free Software Foundation, either version 3 of the License, or
14   * (at your option) any later version.
15   * 
16   * This program is distributed in the hope that it will be useful,
17   * but WITHOUT ANY WARRANTY; without even the implied warranty of
18   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19   * GNU General Public License for more details.
20   * 
21   * You should have received a copy of the GNU Affero General Public License
22   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
23   * #L%
24   */
25  
26  
27  import com.google.gson.Gson;
28  import fr.ifremer.quadrige3.core.dao.technical.Files;
29  import fr.ifremer.quadrige3.core.exception.QuadrigeTechnicalException;
30  import org.apache.commons.io.FilenameUtils;
31  import org.apache.commons.lang3.builder.ToStringBuilder;
32  import org.apache.commons.lang3.builder.ToStringStyle;
33  import org.apache.commons.logging.Log;
34  import org.apache.commons.logging.LogFactory;
35  import org.apache.http.HttpResponse;
36  import org.springframework.util.MimeTypeUtils;
37  import org.springframework.web.multipart.MultipartFile;
38  
39  import javax.servlet.http.HttpServletResponse;
40  import java.io.*;
41  import java.lang.reflect.Type;
42  import java.nio.charset.StandardCharsets;
43  
44  public class ServletUtils {
45  
46      private static final Log log = LogFactory.getLog(ServletUtils.class);
47  
48      public static void copyFile(MultipartFile source, File target) throws IOException {
49          try (OutputStream os = new BufferedOutputStream(new FileOutputStream(target, false));
50               InputStream is = new BufferedInputStream(source.getInputStream())) {
51  
52              Files.copyStream(is, os);
53          }
54      }
55  
56      public static void copyFileToResponse(File file, HttpServletResponse response) {
57          // Set mime type
58          String contentType = MimeTypeUtils.APPLICATION_OCTET_STREAM.getType();
59          if (FilenameUtils.isExtension(file.getName(), "properties")) {
60              contentType = MimeTypeUtils.TEXT_PLAIN.getType();
61          }
62          response.setContentType(contentType);
63  
64          // Set length
65          response.setContentLengthLong(file.length());
66  
67          // set headers for the response
68          String headerKey = "Content-Disposition";
69          String headerValue = String.format("attachment; filename=\"%s\"", file.getName());
70          response.setHeader(headerKey, headerValue);
71  
72          try (OutputStream os = response.getOutputStream();
73               InputStream is = new BufferedInputStream(new FileInputStream(file))) {
74              Files.copyStream(is, os);
75          } catch (IOException e) {
76              throw new QuadrigeTechnicalException("Error while writing file content to response", e);
77          }
78      }
79      
80      /* -- Internal methods -- */
81  
82      protected static Object parseResponse(HttpResponse response, Gson gson, Class<?> ResultClass) throws IOException {
83          Object result;
84          
85          boolean stringOutput = ResultClass.equals(String.class);
86          
87          // If trace enable, log the response before parsing
88          if (stringOutput) {
89              try (InputStream content = response.getEntity().getContent()) {
90                  String stringContent = getContentAsString(content);
91                  if (log.isDebugEnabled()) {
92                      log.debug("Parsing response:\n" + stringContent);
93                  }
94                  return stringContent;
95              }
96          }
97          
98          // trace not enable
99          else {
100             try (InputStream content = response.getEntity().getContent()) {
101                 Reader reader = new InputStreamReader(content, StandardCharsets.UTF_8);
102                 result = gson.fromJson(reader, ResultClass);
103             }
104         }
105         
106 
107         if (result == null) {
108             throw new QuadrigeTechnicalException("emptyResponse");
109         }
110 
111         if (log.isTraceEnabled()) {
112             log.trace("response: " + ToStringBuilder.reflectionToString(result, ToStringStyle.SHORT_PREFIX_STYLE));
113         }
114 
115         return result;
116     }
117 
118     protected static <T> T parseResponse(HttpResponse response, Gson gson, Type typeOfT) throws IOException {
119         T result;
120 
121         try (InputStream content = response.getEntity().getContent()) {
122             Reader reader = new InputStreamReader(content, StandardCharsets.UTF_8);
123             result = gson.fromJson(reader, typeOfT);
124         }
125 
126         if (result == null) {
127             throw new QuadrigeTechnicalException("emptyResponse");
128         }
129 
130         if (log.isTraceEnabled()) {
131             log.trace("response: " + ToStringBuilder.reflectionToString(result, ToStringStyle.SHORT_PREFIX_STYLE));
132         }
133 
134         return result;
135     }
136 
137     private static String getContentAsString(InputStream content) throws IOException {
138         Reader reader = new InputStreamReader(content, StandardCharsets.UTF_8);
139         StringBuilder result = new StringBuilder();
140         char[] buf = new char[64];
141         int len;
142         while((len = reader.read(buf)) != -1) {
143             result.append(buf, 0, len);
144         }
145         return result.toString();
146     }
147     
148 
149 
150 }