1   /**
2    * Copyright (c) 2000-2008 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.FileUtil;
27  import com.liferay.portal.kernel.util.GetterUtil;
28  import com.liferay.portal.kernel.util.ServerDetector;
29  import com.liferay.portal.kernel.util.StringPool;
30  import com.liferay.portal.kernel.util.StringUtil;
31  import com.liferay.portal.kernel.util.Validator;
32  
33  import java.io.BufferedOutputStream;
34  import java.io.IOException;
35  import java.io.InputStream;
36  import java.io.OutputStream;
37  
38  import javax.servlet.http.HttpServletResponse;
39  
40  import org.apache.commons.codec.net.URLCodec;
41  import org.apache.commons.lang.CharUtils;
42  import org.apache.commons.logging.Log;
43  import org.apache.commons.logging.LogFactory;
44  
45  /**
46   * <a href="ServletResponseUtil.java.html"><b><i>View Source</i></b></a>
47   *
48   * @author Brian Wing Shun Chan
49   *
50   */
51  public class ServletResponseUtil {
52  
53      public static void cleanUp(InputStream is) {
54          try {
55              if (is != null) {
56                  is.close();
57              }
58          }
59          catch (Exception e) {
60              if (_log.isWarnEnabled()) {
61                  _log.warn(e);
62              }
63          }
64      }
65  
66      public static void cleanUp(OutputStream os) {
67          try {
68              if (os != null) {
69                  os.flush();
70              }
71          }
72          catch (Exception e) {
73              if (_log.isWarnEnabled()) {
74                  _log.warn(e);
75              }
76          }
77  
78          try {
79              if (os != null) {
80                  os.close();
81              }
82          }
83          catch (Exception e) {
84              if (_log.isWarnEnabled()) {
85                  _log.warn(e);
86              }
87          }
88      }
89  
90      public static void cleanUp(OutputStream os, InputStream is) {
91          cleanUp(os);
92          cleanUp(is);
93      }
94  
95      public static void sendFile(
96              HttpServletResponse response, String fileName, byte[] bytes)
97          throws IOException {
98  
99          sendFile(response, fileName, bytes, null);
100     }
101 
102     public static void sendFile(
103             HttpServletResponse response, String fileName, byte[] bytes,
104             String contentType)
105         throws IOException {
106 
107         setHeaders(response, fileName, contentType);
108 
109         write(response, bytes);
110     }
111 
112     public static void sendFile(
113             HttpServletResponse response, String fileName, InputStream is)
114         throws IOException {
115 
116         sendFile(response, fileName, is, null);
117     }
118 
119     public static void sendFile(
120             HttpServletResponse response, String fileName, InputStream is,
121             String contentType)
122         throws IOException {
123 
124         setHeaders(response, fileName, contentType);
125 
126         write(response, is);
127     }
128 
129     public static void write(HttpServletResponse response, String s)
130         throws IOException {
131 
132         write(response, s.getBytes(StringPool.UTF8));
133     }
134 
135     public static void write(HttpServletResponse response, byte[] bytes)
136         throws IOException {
137 
138         write(response, bytes, 0);
139     }
140 
141     public static void write(
142             HttpServletResponse response, byte[] bytes, int contentLength)
143         throws IOException {
144 
145         OutputStream os = null;
146 
147         try {
148 
149             // LEP-3122
150 
151             if (!response.isCommitted() || ServerDetector.isPramati()) {
152 
153                 // LEP-536
154 
155                 if (contentLength == 0) {
156                     contentLength = bytes.length;
157                 }
158 
159                 response.setContentLength(contentLength);
160 
161                 os = new BufferedOutputStream(response.getOutputStream());
162 
163                 os.write(bytes, 0, contentLength);
164             }
165         }
166         finally {
167             cleanUp(os);
168         }
169     }
170 
171     public static void write(HttpServletResponse response, InputStream is)
172         throws IOException {
173 
174         OutputStream os = null;
175 
176         try {
177             if (!response.isCommitted()) {
178                 os = new BufferedOutputStream(response.getOutputStream());
179 
180                 int c = is.read();
181 
182                 while (c != -1) {
183                     os.write(c);
184 
185                     c = is.read();
186                 }
187             }
188         }
189         finally {
190             cleanUp(os, is);
191         }
192     }
193 
194     protected static void setHeaders(
195         HttpServletResponse response, String fileName, String contentType) {
196 
197         if (_log.isDebugEnabled()) {
198             _log.debug("Sending file of type " + contentType);
199         }
200 
201         // LEP-2201
202 
203         if (Validator.isNotNull(contentType)) {
204             response.setContentType(contentType);
205         }
206 
207         response.setHeader(HttpHeaders.CACHE_CONTROL, HttpHeaders.PUBLIC);
208         response.setHeader(HttpHeaders.PRAGMA, HttpHeaders.PUBLIC);
209 
210         if (Validator.isNotNull(fileName)) {
211             String contentDisposition =
212                 "attachment; filename=\"" + fileName + "\"";
213 
214             // If necessary for non-ASCII characters, encode based on RFC 2184.
215             // However, not all browsers support RFC 2184. See LEP-3127.
216 
217             boolean ascii = true;
218 
219             for (int i = 0; i < fileName.length(); i++) {
220                 if (!CharUtils.isAscii(fileName.charAt(i))) {
221                     ascii = false;
222 
223                     break;
224                 }
225             }
226 
227             try {
228                 if (!ascii) {
229                     URLCodec codec = new URLCodec(StringPool.UTF8);
230 
231                     String encodedFileName =
232                         StringUtil.replace(codec.encode(fileName), "+", "%20");
233 
234                     contentDisposition =
235                         "attachment; filename*=UTF-8''" + encodedFileName;
236                 }
237             }
238             catch (Exception e) {
239                 if (_log.isWarnEnabled()) {
240                     _log.warn(e);
241                 }
242             }
243 
244             String extension = GetterUtil.getString(
245                 FileUtil.getExtension(fileName));
246 
247             if (extension.equals("pdf")) {
248                 contentDisposition = StringUtil.replace(
249                     contentDisposition, "attachment; ", "inline; ");
250             }
251 
252             response.setHeader(
253                 HttpHeaders.CONTENT_DISPOSITION, contentDisposition);
254         }
255     }
256 
257     private static Log _log = LogFactory.getLog(ServletResponseUtil.class);
258 
259 }