You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

DownloadStream.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. /*
  2. * Copyright 2000-2014 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.server;
  17. import java.io.IOException;
  18. import java.io.InputStream;
  19. import java.io.OutputStream;
  20. import java.io.Serializable;
  21. import java.io.UnsupportedEncodingException;
  22. import java.net.URLEncoder;
  23. import java.util.HashMap;
  24. import java.util.Iterator;
  25. import java.util.Map;
  26. import javax.servlet.http.HttpServletResponse;
  27. /**
  28. * Downloadable stream.
  29. * <p>
  30. * Note that the methods in a DownloadStream are called without locking the
  31. * session to prevent locking the session during long file downloads. If your
  32. * DownloadStream uses anything from the session, you must handle the locking.
  33. * </p>
  34. *
  35. * @author Vaadin Ltd.
  36. * @since 3.0
  37. */
  38. @SuppressWarnings("serial")
  39. public class DownloadStream implements Serializable {
  40. public static final String CONTENT_DISPOSITION = "Content-Disposition";
  41. /**
  42. * Maximum cache time.
  43. */
  44. public static final long MAX_CACHETIME = Long.MAX_VALUE;
  45. /**
  46. * Default cache time.
  47. */
  48. public static final long DEFAULT_CACHETIME = 1000 * 60 * 60 * 24;
  49. private InputStream stream;
  50. private String contentType;
  51. private String fileName;
  52. private Map<String, String> params;
  53. private long cacheTime = DEFAULT_CACHETIME;
  54. private int bufferSize = 0;
  55. /**
  56. * Creates a new instance of DownloadStream.
  57. */
  58. public DownloadStream(InputStream stream, String contentType,
  59. String fileName) {
  60. setStream(stream);
  61. setContentType(contentType);
  62. setFileName(fileName);
  63. }
  64. /**
  65. * Gets downloadable stream.
  66. *
  67. * @return output stream.
  68. */
  69. public InputStream getStream() {
  70. return stream;
  71. }
  72. /**
  73. * Sets the stream.
  74. *
  75. * @param stream
  76. * The stream to set
  77. */
  78. public void setStream(InputStream stream) {
  79. this.stream = stream;
  80. }
  81. /**
  82. * Gets stream content type.
  83. *
  84. * @return type of the stream content.
  85. */
  86. public String getContentType() {
  87. return contentType;
  88. }
  89. /**
  90. * Sets stream content type.
  91. *
  92. * @param contentType
  93. * the contentType to set
  94. */
  95. public void setContentType(String contentType) {
  96. this.contentType = contentType;
  97. }
  98. /**
  99. * Returns the file name.
  100. *
  101. * @return the name of the file.
  102. */
  103. public String getFileName() {
  104. return fileName;
  105. }
  106. /**
  107. * Sets the file name.
  108. *
  109. * @param fileName
  110. * the file name to set.
  111. */
  112. public void setFileName(String fileName) {
  113. this.fileName = fileName;
  114. }
  115. /**
  116. * Sets a paramater for download stream. Parameters are optional information
  117. * about the downloadable stream and their meaning depends on the used
  118. * adapter. For example in WebAdapter they are interpreted as HTTP response
  119. * headers.
  120. *
  121. * If the parameters by this name exists, the old value is replaced.
  122. *
  123. * @param name
  124. * the Name of the parameter to set.
  125. * @param value
  126. * the Value of the parameter to set.
  127. */
  128. public void setParameter(String name, String value) {
  129. if (params == null) {
  130. params = new HashMap<String, String>();
  131. }
  132. params.put(name, value);
  133. }
  134. /**
  135. * Gets a paramater for download stream. Parameters are optional information
  136. * about the downloadable stream and their meaning depends on the used
  137. * adapter. For example in WebAdapter they are interpreted as HTTP response
  138. * headers.
  139. *
  140. * @param name
  141. * the Name of the parameter to set.
  142. * @return Value of the parameter or null if the parameter does not exist.
  143. */
  144. public String getParameter(String name) {
  145. if (params != null) {
  146. return params.get(name);
  147. }
  148. return null;
  149. }
  150. /**
  151. * Gets the names of the parameters.
  152. *
  153. * @return Iterator of names or null if no parameters are set.
  154. */
  155. public Iterator<String> getParameterNames() {
  156. if (params != null) {
  157. return params.keySet().iterator();
  158. }
  159. return null;
  160. }
  161. /**
  162. * Gets length of cache expiration time. This gives the adapter the
  163. * possibility cache streams sent to the client. The caching may be made in
  164. * adapter or at the client if the client supports caching. Default is
  165. * <code>DEFAULT_CACHETIME</code>.
  166. *
  167. * @return Cache time in milliseconds
  168. */
  169. public long getCacheTime() {
  170. return cacheTime;
  171. }
  172. /**
  173. * Sets length of cache expiration time. This gives the adapter the
  174. * possibility cache streams sent to the client. The caching may be made in
  175. * adapter or at the client if the client supports caching. Zero or negavive
  176. * value disbales the caching of this stream.
  177. *
  178. * @param cacheTime
  179. * the cache time in milliseconds.
  180. */
  181. public void setCacheTime(long cacheTime) {
  182. this.cacheTime = cacheTime;
  183. }
  184. /**
  185. * Gets the size of the download buffer.
  186. *
  187. * @return int The size of the buffer in bytes.
  188. */
  189. public int getBufferSize() {
  190. return bufferSize;
  191. }
  192. /**
  193. * Sets the size of the download buffer.
  194. *
  195. * @param bufferSize
  196. * the size of the buffer in bytes.
  197. *
  198. * @since 7.0
  199. */
  200. public void setBufferSize(int bufferSize) {
  201. this.bufferSize = bufferSize;
  202. }
  203. /**
  204. * Writes this download stream to a Vaadin response. This takes care of
  205. * setting response headers according to what is defined in this download
  206. * stream ({@link #getContentType()}, {@link #getCacheTime()},
  207. * {@link #getFileName()}) and transferring the data from the stream (
  208. * {@link #getStream()}) to the response. Defined parameters (
  209. * {@link #getParameterNames()}) are also included as headers in the
  210. * response. If there's is a parameter named <code>Location</code>, a
  211. * redirect (302 Moved temporarily) is sent instead of the contents of this
  212. * stream.
  213. *
  214. * @param request
  215. * the request for which the response should be written
  216. * @param response
  217. * the Vaadin response to write this download stream to
  218. *
  219. * @throws IOException
  220. * passed through from the Vaadin response
  221. *
  222. * @since 7.0
  223. */
  224. public void writeResponse(VaadinRequest request, VaadinResponse response)
  225. throws IOException {
  226. if (getParameter("Location") != null) {
  227. response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
  228. response.setHeader("Location", getParameter("Location"));
  229. return;
  230. }
  231. // Download from given stream
  232. final InputStream data = getStream();
  233. if (data == null) {
  234. response.setStatus(HttpServletResponse.SC_NOT_FOUND);
  235. return;
  236. }
  237. if (data != null) {
  238. OutputStream out = null;
  239. try {
  240. // Sets content type
  241. response.setContentType(getContentType());
  242. // Sets cache headers
  243. response.setCacheTime(getCacheTime());
  244. // Copy download stream parameters directly
  245. // to HTTP headers.
  246. final Iterator<String> i = getParameterNames();
  247. if (i != null) {
  248. while (i.hasNext()) {
  249. final String param = i.next();
  250. response.setHeader(param, getParameter(param));
  251. }
  252. }
  253. // Content-Disposition: attachment generally forces download
  254. String contentDisposition = getParameter(CONTENT_DISPOSITION);
  255. if (contentDisposition == null) {
  256. contentDisposition = getContentDispositionFilename(getFileName());
  257. }
  258. response.setHeader(CONTENT_DISPOSITION, contentDisposition);
  259. int bufferSize = getBufferSize();
  260. if (bufferSize <= 0 || bufferSize > Constants.MAX_BUFFER_SIZE) {
  261. bufferSize = Constants.DEFAULT_BUFFER_SIZE;
  262. }
  263. final byte[] buffer = new byte[bufferSize];
  264. int bytesRead = 0;
  265. out = response.getOutputStream();
  266. long totalWritten = 0;
  267. while ((bytesRead = data.read(buffer)) > 0) {
  268. out.write(buffer, 0, bytesRead);
  269. totalWritten += bytesRead;
  270. if (totalWritten >= buffer.length) {
  271. // Avoid chunked encoding for small resources
  272. out.flush();
  273. }
  274. }
  275. } finally {
  276. tryToCloseStream(out);
  277. tryToCloseStream(data);
  278. }
  279. }
  280. }
  281. /**
  282. * Returns the filename formatted for inclusion in a Content-Disposition
  283. * header. Includes both a plain version of the name and a UTF-8 version
  284. *
  285. * @since 7.4.8
  286. * @param filename
  287. * The filename to include
  288. * @return A value for inclusion in a Content-Disposition header
  289. */
  290. public static String getContentDispositionFilename(String filename) {
  291. try {
  292. String encodedFilename = URLEncoder.encode(filename, "UTF-8");
  293. return String.format("filename=\"%s\"; filename*=utf-8''%s",
  294. encodedFilename, encodedFilename);
  295. } catch (UnsupportedEncodingException e) {
  296. return null;
  297. }
  298. }
  299. /**
  300. * Helper method that tries to close an output stream and ignores any
  301. * exceptions.
  302. *
  303. * @param out
  304. * the output stream to close, <code>null</code> is also
  305. * supported
  306. */
  307. static void tryToCloseStream(OutputStream out) {
  308. try {
  309. // try to close output stream (e.g. file handle)
  310. if (out != null) {
  311. out.close();
  312. }
  313. } catch (IOException e1) {
  314. // NOP
  315. }
  316. }
  317. /**
  318. * Helper method that tries to close an input stream and ignores any
  319. * exceptions.
  320. *
  321. * @param in
  322. * the input stream to close, <code>null</code> is also supported
  323. */
  324. static void tryToCloseStream(InputStream in) {
  325. try {
  326. // try to close output stream (e.g. file handle)
  327. if (in != null) {
  328. in.close();
  329. }
  330. } catch (IOException e1) {
  331. // NOP
  332. }
  333. }
  334. }