1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package com.hack23.cia.web.impl.ui.application.views.common.pagelinks.impl;
20
21 import java.io.ByteArrayInputStream;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.net.URL;
25
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28
29 import com.vaadin.server.StreamResource;
30 import com.vaadin.ui.Link;
31
32
33
34
35 public final class ExternalAttachmentDownloadLink extends Link {
36
37
38 private static final long serialVersionUID = 1L;
39
40
41 private static final Logger LOGGER = LoggerFactory.getLogger(ExternalAttachmentDownloadLink.class);
42
43
44 private final String fileName;
45
46
47 private final String fileType;
48
49
50 private final String fileUrl;
51
52
53
54
55
56
57
58
59
60
61
62 public ExternalAttachmentDownloadLink(final String fileName, final String fileType, final String fileUrl) {
63 super();
64 this.fileName = fileName;
65 this.fileType = fileType;
66 this.fileUrl = fileUrl;
67 setCaption(fileName);
68 setDescription("Download " + fileName);
69 setTargetName("_blank");
70 }
71
72 @Override
73 public void attach() {
74 super.attach();
75
76 final StreamResource.StreamSource source = new StreamResource.StreamSource() {
77
78
79 private static final long serialVersionUID = 1L;
80
81 @Override
82 public InputStream getStream() {
83
84 try {
85 return new URL(fileUrl).openStream();
86 } catch (final IOException e) {
87 LOGGER.warn("Problem opening url:"+ fileUrl,e);
88 return new ByteArrayInputStream(new byte[0]);
89 }
90 }
91 };
92
93 final StreamResource resource = new StreamResource(source, fileName);
94
95 resource.getStream().setParameter("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
96 resource.setMIMEType("application/" + fileType);
97 resource.setCacheTime(0);
98
99 setResource(resource);
100 }
101 }