View Javadoc
1   package fr.ifremer.quadrige2.synchro.server.technical;
2   
3   /*-
4    * #%L
5    * Quadrige2 Core :: Quadrige2 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.quadrige2.core.exception.Quadrige2TechnicalException;
29  import org.apache.commons.io.FileUtils;
30  import org.apache.commons.io.FilenameUtils;
31  import org.apache.commons.io.IOUtils;
32  import org.apache.commons.lang3.builder.ToStringBuilder;
33  import org.apache.commons.lang3.builder.ToStringStyle;
34  import org.apache.commons.logging.Log;
35  import org.apache.commons.logging.LogFactory;
36  import org.apache.http.HttpResponse;
37  import org.springframework.util.MimeTypeUtils;
38  import org.springframework.web.multipart.MultipartFile;
39  
40  import javax.servlet.http.HttpServletResponse;
41  import java.io.*;
42  import java.lang.reflect.Type;
43  import java.nio.charset.StandardCharsets;
44  
45  public class ServletUtils {
46  
47      private static final Log log = LogFactory.getLog(ServletUtils.class);
48  
49      public static void copyFile(MultipartFile source, File target) throws IOException {
50          OutputStream os = null;
51          InputStream is = null;
52          try {
53              os = new BufferedOutputStream(new FileOutputStream(target, false));
54              is = new BufferedInputStream(source.getInputStream());
55              IOUtils.copyLarge(is, os);
56              os.flush();
57          } finally {
58              IOUtils.closeQuietly(os);
59              IOUtils.closeQuietly(is);
60          }
61      }
62  
63      public static void copyFileToResponse(File file, HttpServletResponse response) {
64          // Set mime type
65          String contentType = MimeTypeUtils.APPLICATION_OCTET_STREAM.getType();
66          if (FilenameUtils.isExtension(file.getName(), "properties")) {
67              contentType = MimeTypeUtils.TEXT_PLAIN.getType();
68          }
69          response.setContentType(contentType);
70  
71          // Set length
72          long fileLength = FileUtils.sizeOf(file);
73          response.setContentLength((int) fileLength);
74  
75          // set headers for the response
76          String headerKey = "Content-Disposition";
77          String headerValue = String.format("attachment; filename=\"%s\"",
78                  file.getName());
79          response.setHeader(headerKey, headerValue);
80  
81          OutputStream os = null;
82          InputStream is = null;
83  
84          try {
85              os = response.getOutputStream();
86              is = new BufferedInputStream(new FileInputStream(file));
87  
88              IOUtils.copyLarge(is, os);
89  
90          } catch (IOException e) {
91              throw new Quadrige2TechnicalException("Error while writing file content to response", e);
92          }
93          finally {
94              IOUtils.closeQuietly(os);
95              IOUtils.closeQuietly(is);
96          }
97      }
98      
99      /* -- Internal methods -- */
100 
101     protected static Object parseResponse(HttpResponse response, Gson gson, Class<?> ResultClass) throws IOException {
102         Object result;
103         
104         boolean stringOutput = ResultClass.equals(String.class);
105         
106         // If trace enable, log the response before parsing
107         if (stringOutput) {
108             InputStream content = null;
109             try {
110                 content = response.getEntity().getContent();
111                 String stringContent = getContentAsString(content);
112                 if (log.isDebugEnabled()) {
113                     log.debug("Parsing response:\n" + stringContent);
114                 }
115 
116                 return stringContent;
117             }
118             finally {
119                 if (content!= null) {
120                     content.close();
121                 }
122             }
123         }
124         
125         // trace not enable
126         else {
127             InputStream content = null;
128             try {
129                 content = response.getEntity().getContent();
130                 Reader reader = new InputStreamReader(content, StandardCharsets.UTF_8);
131                 result = gson.fromJson(reader, ResultClass);                
132             }
133             finally {
134                 if (content!= null) {
135                     content.close();
136                 }
137             }
138         }
139         
140 
141         if (result == null) {
142             throw new Quadrige2TechnicalException("emptyResponse");
143         }
144 
145         if (log.isTraceEnabled()) {
146             log.trace("response: " + ToStringBuilder.reflectionToString(result, ToStringStyle.SHORT_PREFIX_STYLE));
147         }
148 
149         return result;
150     }
151 
152     protected static <T> T parseResponse(HttpResponse response, Gson gson, Type typeOfT) throws IOException {
153         T result;
154 
155         InputStream content = null;
156         try {
157             content = response.getEntity().getContent();
158             Reader reader = new InputStreamReader(content, StandardCharsets.UTF_8);
159             result = gson.fromJson(reader, typeOfT);
160         }
161         finally {
162             if (content!= null) {
163                 content.close();
164             }
165         }
166 
167         if (result == null) {
168             throw new Quadrige2TechnicalException("emptyResponse");
169         }
170 
171         if (log.isTraceEnabled()) {
172             log.trace("response: " + ToStringBuilder.reflectionToString(result, ToStringStyle.SHORT_PREFIX_STYLE));
173         }
174 
175         return result;
176     }
177 
178     protected static String getContentAsString(InputStream content) throws IOException {
179         Reader reader = new InputStreamReader(content, StandardCharsets.UTF_8);
180         StringBuilder result = new StringBuilder();
181         char[] buf = new char[64];
182         int len = 0;
183         while((len = reader.read(buf)) != -1) {
184             result.append(buf, 0, len);
185         }
186         return result.toString();
187     }
188     
189 
190 
191 }