1   /**
2    * Copyright (c) 2000-2007 Liferay, Inc. All rights reserved.
3    *
4    * Permission is hereby granted, free of charge, to any person obtaining a copy
5    * of this software and associated documentation files (the "Software"), to deal
6    * in the Software without restriction, including without limitation the rights
7    * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8    * copies of the Software, and to permit persons to whom the Software is
9    * furnished to do so, subject to the following conditions:
10   *
11   * The above copyright notice and this permission notice shall be included in
12   * all copies or substantial portions of the Software.
13   *
14   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20   * SOFTWARE.
21   */
22  
23  package com.liferay.util.servlet;
24  
25  import com.liferay.portal.kernel.servlet.HttpHeaders;
26  import com.liferay.portal.kernel.util.GetterUtil;
27  import com.liferay.portal.kernel.util.ServerDetector;
28  import com.liferay.portal.kernel.util.StringUtil;
29  import com.liferay.portal.kernel.util.Validator;
30  import com.liferay.util.FileUtil;
31  
32  import java.io.BufferedOutputStream;
33  import java.io.IOException;
34  import java.io.InputStream;
35  import java.io.OutputStream;
36  
37  import javax.servlet.http.HttpServletResponse;
38  
39  import org.apache.commons.codec.net.URLCodec;
40  import org.apache.commons.lang.CharUtils;
41  import org.apache.commons.logging.Log;
42  import org.apache.commons.logging.LogFactory;
43  
44  /**
45   * <a href="ServletResponseUtil.java.html"><b><i>View Source</i></b></a>
46   *
47   * @author Brian Wing Shun Chan
48   *
49   */
50  public class ServletResponseUtil {
51  
52      public static final String DEFAULT_CONTENT_TYPE =
53          "application/octet-stream";
54  
55      public static void cleanUp(InputStream is) {
56          try {
57              if (is != null) {
58                  is.close();
59              }
60          }
61          catch (Exception e) {
62              if (_log.isWarnEnabled()) {
63                  _log.warn(e);
64              }
65          }
66      }
67  
68      public static void cleanUp(OutputStream os) {
69          try {
70              if (os != null) {
71                  os.flush();
72              }
73          }
74          catch (Exception e) {
75              if (_log.isWarnEnabled()) {
76                  _log.warn(e);
77              }
78          }
79  
80          try {
81              if (os != null) {
82                  os.close();
83              }
84          }
85          catch (Exception e) {
86              if (_log.isWarnEnabled()) {
87                  _log.warn(e);
88              }
89          }
90      }
91  
92      public static void cleanUp(OutputStream os, InputStream is) {
93          cleanUp(os);
94          cleanUp(is);
95      }
96  
97      public static void sendFile(
98              HttpServletResponse res, String fileName, byte[] byteArray)
99          throws IOException {
100 
101         sendFile(res, fileName, byteArray, null);
102     }
103 
104     public static void sendFile(
105             HttpServletResponse res, String fileName, byte[] byteArray,
106             String contentType)
107         throws IOException {
108 
109         setHeaders(res, fileName, contentType);
110 
111         write(res, byteArray);
112     }
113 
114     public static void sendFile(
115             HttpServletResponse res, String fileName, InputStream is)
116         throws IOException {
117 
118         sendFile(res, fileName, is, null);
119     }
120 
121     public static void sendFile(
122             HttpServletResponse res, String fileName, InputStream is,
123             String contentType)
124         throws IOException {
125 
126         setHeaders(res, fileName, contentType);
127 
128         write(res, is);
129     }
130 
131     public static void write(HttpServletResponse res, String s)
132         throws IOException {
133 
134         write(res, s.getBytes("UTF-8"));
135     }
136 
137     public static void write(HttpServletResponse res, byte[] byteArray)
138         throws IOException {
139 
140         write(res, byteArray, 0);
141     }
142 
143     public static void write(
144             HttpServletResponse res, byte[] byteArray, int contentLength)
145         throws IOException {
146 
147         OutputStream os = null;
148 
149         try {
150 
151             // LEP-3122
152 
153             if (!res.isCommitted() || ServerDetector.isPramati()) {
154 
155                 // LEP-536
156 
157                 if (contentLength == 0) {
158                     contentLength = byteArray.length;
159                 }
160 
161                 res.setContentLength(contentLength);
162 
163                 os = new BufferedOutputStream(res.getOutputStream());
164 
165                 os.write(byteArray, 0, contentLength);
166             }
167         }
168         finally {
169             cleanUp(os);
170         }
171     }
172 
173     public static void write(HttpServletResponse res, InputStream is)
174         throws IOException {
175 
176         OutputStream os = null;
177 
178         try {
179             if (!res.isCommitted()) {
180                 os = new BufferedOutputStream(res.getOutputStream());
181 
182                 int c = is.read();
183 
184                 while (c != -1) {
185                     os.write(c);
186 
187                     c = is.read();
188                 }
189             }
190         }
191         finally {
192             cleanUp(os, is);
193         }
194     }
195 
196     protected static void setHeaders(
197             HttpServletResponse res, String fileName, String contentType)
198         throws IOException {
199 
200         if (_log.isDebugEnabled()) {
201             _log.debug("Sending file of type " + contentType);
202         }
203 
204         // LEP-2201
205 
206         if (Validator.isNotNull(contentType)) {
207             res.setContentType(contentType);
208         }
209 
210         res.setHeader(HttpHeaders.CACHE_CONTROL, HttpHeaders.PUBLIC);
211         res.setHeader(HttpHeaders.PRAGMA, HttpHeaders.PUBLIC);
212 
213         if (Validator.isNotNull(fileName)) {
214             String contentDisposition =
215                 "attachment; filename=\"" + fileName + "\"";
216 
217             // If necessary for non-ASCII characters, encode based on RFC 2184.
218             // However, not all browsers support RFC 2184. See LEP-3127.
219 
220             boolean ascii = true;
221 
222             for (int i = 0; i < fileName.length(); i++) {
223                 if (!CharUtils.isAscii(fileName.charAt(i))) {
224                     ascii = false;
225 
226                     break;
227                 }
228             }
229 
230             try {
231                 if (!ascii) {
232                     URLCodec codec = new URLCodec("UTF-8");
233 
234                     String encodedFileName =
235                         StringUtil.replace(codec.encode(fileName), "+", "%20");
236 
237                     contentDisposition =
238                         "attachment; filename*=UTF-8''" + encodedFileName;
239                 }
240             }
241             catch (Exception e) {
242                 if (_log.isWarnEnabled()) {
243                     _log.warn(e);
244                 }
245             }
246 
247             String extension = GetterUtil.getString(
248                 FileUtil.getExtension(fileName));
249 
250             if (extension.equals("pdf")) {
251                 contentDisposition = StringUtil.replace(
252                     contentDisposition, "attachment; ", "inline; ");
253             }
254 
255             res.setHeader(HttpHeaders.CONTENT_DISPOSITION, contentDisposition);
256         }
257     }
258 
259     private static Log _log = LogFactory.getLog(ServletResponseUtil.class);
260 
261 }