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 9.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. /*
  2. @VaadinApache2LicenseForJavaFiles@
  3. */
  4. package com.vaadin.terminal;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.io.OutputStream;
  8. import java.io.Serializable;
  9. import java.util.HashMap;
  10. import java.util.Iterator;
  11. import java.util.Map;
  12. import javax.servlet.http.HttpServletResponse;
  13. import com.vaadin.terminal.gwt.server.Constants;
  14. /**
  15. * Downloadable stream.
  16. *
  17. * @author Vaadin Ltd.
  18. * @since 3.0
  19. */
  20. @SuppressWarnings("serial")
  21. public class DownloadStream implements Serializable {
  22. /**
  23. * Maximum cache time.
  24. */
  25. public static final long MAX_CACHETIME = Long.MAX_VALUE;
  26. /**
  27. * Default cache time.
  28. */
  29. public static final long DEFAULT_CACHETIME = 1000 * 60 * 60 * 24;
  30. private InputStream stream;
  31. private String contentType;
  32. private String fileName;
  33. private Map<String, String> params;
  34. private long cacheTime = DEFAULT_CACHETIME;
  35. private int bufferSize = 0;
  36. /**
  37. * Creates a new instance of DownloadStream.
  38. */
  39. public DownloadStream(InputStream stream, String contentType,
  40. String fileName) {
  41. setStream(stream);
  42. setContentType(contentType);
  43. setFileName(fileName);
  44. }
  45. /**
  46. * Gets downloadable stream.
  47. *
  48. * @return output stream.
  49. */
  50. public InputStream getStream() {
  51. return stream;
  52. }
  53. /**
  54. * Sets the stream.
  55. *
  56. * @param stream
  57. * The stream to set
  58. */
  59. public void setStream(InputStream stream) {
  60. this.stream = stream;
  61. }
  62. /**
  63. * Gets stream content type.
  64. *
  65. * @return type of the stream content.
  66. */
  67. public String getContentType() {
  68. return contentType;
  69. }
  70. /**
  71. * Sets stream content type.
  72. *
  73. * @param contentType
  74. * the contentType to set
  75. */
  76. public void setContentType(String contentType) {
  77. this.contentType = contentType;
  78. }
  79. /**
  80. * Returns the file name.
  81. *
  82. * @return the name of the file.
  83. */
  84. public String getFileName() {
  85. return fileName;
  86. }
  87. /**
  88. * Sets the file name.
  89. *
  90. * @param fileName
  91. * the file name to set.
  92. */
  93. public void setFileName(String fileName) {
  94. this.fileName = fileName;
  95. }
  96. /**
  97. * Sets a paramater for download stream. Parameters are optional information
  98. * about the downloadable stream and their meaning depends on the used
  99. * adapter. For example in WebAdapter they are interpreted as HTTP response
  100. * headers.
  101. *
  102. * If the parameters by this name exists, the old value is replaced.
  103. *
  104. * @param name
  105. * the Name of the parameter to set.
  106. * @param value
  107. * the Value of the parameter to set.
  108. */
  109. public void setParameter(String name, String value) {
  110. if (params == null) {
  111. params = new HashMap<String, String>();
  112. }
  113. params.put(name, value);
  114. }
  115. /**
  116. * Gets 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. * @param name
  122. * the Name of the parameter to set.
  123. * @return Value of the parameter or null if the parameter does not exist.
  124. */
  125. public String getParameter(String name) {
  126. if (params != null) {
  127. return params.get(name);
  128. }
  129. return null;
  130. }
  131. /**
  132. * Gets the names of the parameters.
  133. *
  134. * @return Iterator of names or null if no parameters are set.
  135. */
  136. public Iterator<String> getParameterNames() {
  137. if (params != null) {
  138. return params.keySet().iterator();
  139. }
  140. return null;
  141. }
  142. /**
  143. * Gets length of cache expiration time. This gives the adapter the
  144. * possibility cache streams sent to the client. The caching may be made in
  145. * adapter or at the client if the client supports caching. Default is
  146. * <code>DEFAULT_CACHETIME</code>.
  147. *
  148. * @return Cache time in milliseconds
  149. */
  150. public long getCacheTime() {
  151. return cacheTime;
  152. }
  153. /**
  154. * Sets length of cache expiration time. This gives the adapter the
  155. * possibility cache streams sent to the client. The caching may be made in
  156. * adapter or at the client if the client supports caching. Zero or negavive
  157. * value disbales the caching of this stream.
  158. *
  159. * @param cacheTime
  160. * the cache time in milliseconds.
  161. */
  162. public void setCacheTime(long cacheTime) {
  163. this.cacheTime = cacheTime;
  164. }
  165. /**
  166. * Gets the size of the download buffer.
  167. *
  168. * @return int The size of the buffer in bytes.
  169. */
  170. public int getBufferSize() {
  171. return bufferSize;
  172. }
  173. /**
  174. * Sets the size of the download buffer.
  175. *
  176. * @param bufferSize
  177. * the size of the buffer in bytes.
  178. *
  179. * @since 7.0
  180. */
  181. public void setBufferSize(int bufferSize) {
  182. this.bufferSize = bufferSize;
  183. }
  184. /**
  185. * Writes this download stream to a wrapped response. This takes care of
  186. * setting response headers according to what is defined in this download
  187. * stream ({@link #getContentType()}, {@link #getCacheTime()},
  188. * {@link #getFileName()}) and transferring the data from the stream (
  189. * {@link #getStream()}) to the response. Defined parameters (
  190. * {@link #getParameterNames()}) are also included as headers in the
  191. * response. If there's is a parameter named <code>Location</code>, a
  192. * redirect (302 Moved temporarily) is sent instead of the contents of this
  193. * stream.
  194. *
  195. * @param response
  196. * the wrapped response to write this download stream to
  197. * @throws IOException
  198. * passed through from the wrapped response
  199. *
  200. * @since 7.0
  201. */
  202. public void writeTo(WrappedResponse response) throws IOException {
  203. if (getParameter("Location") != null) {
  204. response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
  205. response.setHeader("Location", getParameter("Location"));
  206. return;
  207. }
  208. // Download from given stream
  209. final InputStream data = getStream();
  210. if (data != null) {
  211. OutputStream out = null;
  212. try {
  213. // Sets content type
  214. response.setContentType(getContentType());
  215. // Sets cache headers
  216. response.setCacheTime(getCacheTime());
  217. // Copy download stream parameters directly
  218. // to HTTP headers.
  219. final Iterator<String> i = getParameterNames();
  220. if (i != null) {
  221. while (i.hasNext()) {
  222. final String param = i.next();
  223. response.setHeader(param, getParameter(param));
  224. }
  225. }
  226. // suggest local filename from DownloadStream if
  227. // Content-Disposition
  228. // not explicitly set
  229. String contentDispositionValue = getParameter("Content-Disposition");
  230. if (contentDispositionValue == null) {
  231. contentDispositionValue = "filename=\"" + getFileName()
  232. + "\"";
  233. response.setHeader("Content-Disposition",
  234. contentDispositionValue);
  235. }
  236. int bufferSize = getBufferSize();
  237. if (bufferSize <= 0 || bufferSize > Constants.MAX_BUFFER_SIZE) {
  238. bufferSize = Constants.DEFAULT_BUFFER_SIZE;
  239. }
  240. final byte[] buffer = new byte[bufferSize];
  241. int bytesRead = 0;
  242. out = response.getOutputStream();
  243. long totalWritten = 0;
  244. while ((bytesRead = data.read(buffer)) > 0) {
  245. out.write(buffer, 0, bytesRead);
  246. totalWritten += bytesRead;
  247. if (totalWritten >= buffer.length) {
  248. // Avoid chunked encoding for small resources
  249. out.flush();
  250. }
  251. }
  252. } finally {
  253. tryToCloseStream(out);
  254. tryToCloseStream(data);
  255. }
  256. }
  257. }
  258. /**
  259. * Helper method that tries to close an output stream and ignores any
  260. * exceptions.
  261. *
  262. * @param out
  263. * the output stream to close, <code>null</code> is also
  264. * supported
  265. */
  266. static void tryToCloseStream(OutputStream out) {
  267. try {
  268. // try to close output stream (e.g. file handle)
  269. if (out != null) {
  270. out.close();
  271. }
  272. } catch (IOException e1) {
  273. // NOP
  274. }
  275. }
  276. /**
  277. * Helper method that tries to close an input stream and ignores any
  278. * exceptions.
  279. *
  280. * @param in
  281. * the input stream to close, <code>null</code> is also supported
  282. */
  283. static void tryToCloseStream(InputStream in) {
  284. try {
  285. // try to close output stream (e.g. file handle)
  286. if (in != null) {
  287. in.close();
  288. }
  289. } catch (IOException e1) {
  290. // NOP
  291. }
  292. }
  293. }