Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

DownloadStream.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. /*
  2. * Copyright 2000-2018 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.util.HashMap;
  22. import java.util.Iterator;
  23. import java.util.Map;
  24. import javax.servlet.http.HttpServletResponse;
  25. import com.vaadin.util.EncodeUtil;
  26. /**
  27. * Downloadable stream.
  28. * <p>
  29. * Note that the methods in a DownloadStream are called without locking the
  30. * session to prevent locking the session during long file downloads. If your
  31. * DownloadStream uses anything from the session, you must handle the locking.
  32. * </p>
  33. *
  34. * @author Vaadin Ltd.
  35. * @since 3.0
  36. */
  37. @SuppressWarnings("serial")
  38. public class DownloadStream implements Serializable {
  39. public static final String CONTENT_DISPOSITION = "Content-Disposition";
  40. /**
  41. * Maximum cache time.
  42. */
  43. public static final long MAX_CACHETIME = Long.MAX_VALUE;
  44. /**
  45. * Default cache time.
  46. */
  47. public static final long DEFAULT_CACHETIME = 1000 * 60 * 60 * 24;
  48. private InputStream stream;
  49. private String contentType;
  50. private String fileName;
  51. private Map<String, String> params;
  52. private long cacheTime = DEFAULT_CACHETIME;
  53. private int bufferSize = 0;
  54. /**
  55. * Creates a new instance of DownloadStream.
  56. */
  57. public DownloadStream(InputStream stream, String contentType,
  58. String fileName) {
  59. setStream(stream);
  60. setContentType(contentType);
  61. setFileName(fileName);
  62. }
  63. /**
  64. * Gets downloadable stream.
  65. *
  66. * @return output stream.
  67. */
  68. public InputStream getStream() {
  69. return stream;
  70. }
  71. /**
  72. * Sets the stream.
  73. *
  74. * @param stream
  75. * The stream to set
  76. */
  77. public void setStream(InputStream stream) {
  78. this.stream = stream;
  79. }
  80. /**
  81. * Gets stream content type.
  82. *
  83. * @return type of the stream content.
  84. */
  85. public String getContentType() {
  86. return contentType;
  87. }
  88. /**
  89. * Sets stream content type.
  90. *
  91. * @param contentType
  92. * the contentType to set
  93. */
  94. public void setContentType(String contentType) {
  95. this.contentType = contentType;
  96. }
  97. /**
  98. * Returns the file name.
  99. *
  100. * @return the name of the file.
  101. */
  102. public String getFileName() {
  103. return fileName;
  104. }
  105. /**
  106. * Sets the file name.
  107. *
  108. * @param fileName
  109. * the file name to set.
  110. */
  111. public void setFileName(String fileName) {
  112. this.fileName = fileName;
  113. }
  114. /**
  115. * Sets a parameter for download stream. Parameters are optional information
  116. * about the downloadable stream and their meaning depends on the used
  117. * adapter. For example in WebAdapter they are interpreted as HTTP response
  118. * headers.
  119. *
  120. * If the parameters by this name exists, the old value is replaced.
  121. *
  122. * @param name
  123. * the Name of the parameter to set.
  124. * @param value
  125. * the Value of the parameter to set.
  126. */
  127. public void setParameter(String name, String value) {
  128. if (params == null) {
  129. params = new HashMap<>();
  130. }
  131. params.put(name, value);
  132. }
  133. /**
  134. * Gets a paramater for download stream. Parameters are optional information
  135. * about the downloadable stream and their meaning depends on the used
  136. * adapter. For example in WebAdapter they are interpreted as HTTP response
  137. * headers.
  138. *
  139. * @param name
  140. * the Name of the parameter to set.
  141. * @return Value of the parameter or null if the parameter does not exist.
  142. */
  143. public String getParameter(String name) {
  144. if (params != null) {
  145. return params.get(name);
  146. }
  147. return null;
  148. }
  149. /**
  150. * Gets the names of the parameters.
  151. *
  152. * @return Iterator of names or null if no parameters are set.
  153. */
  154. public Iterator<String> getParameterNames() {
  155. if (params != null) {
  156. return params.keySet().iterator();
  157. }
  158. return null;
  159. }
  160. /**
  161. * Gets length of cache expiration time. This gives the adapter the
  162. * possibility cache streams sent to the client. The caching may be made in
  163. * adapter or at the client if the client supports caching. Default is
  164. * <code>DEFAULT_CACHETIME</code>.
  165. *
  166. * @return Cache time in milliseconds
  167. */
  168. public long getCacheTime() {
  169. return cacheTime;
  170. }
  171. /**
  172. * Sets length of cache expiration time. This gives the adapter the
  173. * possibility cache streams sent to the client. The caching may be made in
  174. * adapter or at the client if the client supports caching. Zero or negative
  175. * value disables the caching of this stream.
  176. *
  177. * @param cacheTime
  178. * the cache time in milliseconds.
  179. */
  180. public void setCacheTime(long cacheTime) {
  181. this.cacheTime = cacheTime;
  182. }
  183. /**
  184. * Gets the size of the download buffer.
  185. *
  186. * @return The size of the buffer in bytes.
  187. */
  188. public int getBufferSize() {
  189. return bufferSize;
  190. }
  191. /**
  192. * Sets the size of the download buffer.
  193. *
  194. * @param bufferSize
  195. * the size of the buffer in bytes.
  196. *
  197. * @since 7.0
  198. */
  199. public void setBufferSize(int bufferSize) {
  200. this.bufferSize = bufferSize;
  201. }
  202. /**
  203. * Writes this download stream to a Vaadin response. This takes care of
  204. * setting response headers according to what is defined in this download
  205. * stream ({@link #getContentType()}, {@link #getCacheTime()},
  206. * {@link #getFileName()}) and transferring the data from the stream (
  207. * {@link #getStream()}) to the response. Defined parameters (
  208. * {@link #getParameterNames()}) are also included as headers in the
  209. * response. If there's is a parameter named <code>Location</code>, a
  210. * redirect (302 Moved temporarily) is sent instead of the contents of this
  211. * stream.
  212. *
  213. * @param request
  214. * the request for which the response should be written
  215. * @param response
  216. * the Vaadin response to write this download stream to
  217. *
  218. * @throws IOException
  219. * passed through from the Vaadin response
  220. *
  221. * @since 7.0
  222. */
  223. public void writeResponse(VaadinRequest request, VaadinResponse response)
  224. throws IOException {
  225. if (getParameter("Location") != null) {
  226. response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
  227. response.setHeader("Location", getParameter("Location"));
  228. return;
  229. }
  230. // Download from given stream
  231. final InputStream data = getStream();
  232. if (data == null) {
  233. response.setStatus(HttpServletResponse.SC_NOT_FOUND);
  234. return;
  235. }
  236. if (data != null) {
  237. OutputStream out = null;
  238. try {
  239. // Sets content type
  240. response.setContentType(getContentType());
  241. // Sets cache headers
  242. response.setCacheTime(getCacheTime());
  243. // Copy download stream parameters directly
  244. // to HTTP headers.
  245. final Iterator<String> i = getParameterNames();
  246. if (i != null) {
  247. while (i.hasNext()) {
  248. final String param = i.next();
  249. response.setHeader(param, getParameter(param));
  250. }
  251. }
  252. // Content-Disposition: attachment generally forces download
  253. String contentDisposition = getParameter(CONTENT_DISPOSITION);
  254. if (contentDisposition == null) {
  255. contentDisposition = getContentDispositionFilename(
  256. 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. String encodedFilename = EncodeUtil.rfc5987Encode(filename);
  292. return String.format("filename=\"%s\"; filename*=utf-8''%s",
  293. encodedFilename, encodedFilename);
  294. }
  295. /**
  296. * Helper method that tries to close an output stream and ignores any
  297. * exceptions.
  298. *
  299. * @param out
  300. * the output stream to close, <code>null</code> is also
  301. * supported
  302. */
  303. static void tryToCloseStream(OutputStream out) {
  304. try {
  305. // try to close output stream (e.g. file handle)
  306. if (out != null) {
  307. out.close();
  308. }
  309. } catch (IOException e1) {
  310. // NOP
  311. }
  312. }
  313. /**
  314. * Helper method that tries to close an input stream and ignores any
  315. * exceptions.
  316. *
  317. * @param in
  318. * the input stream to close, <code>null</code> is also supported
  319. */
  320. static void tryToCloseStream(InputStream in) {
  321. try {
  322. // try to close output stream (e.g. file handle)
  323. if (in != null) {
  324. in.close();
  325. }
  326. } catch (IOException e1) {
  327. // NOP
  328. }
  329. }
  330. }