1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package org.htmlunit.attachment;
16
17 import java.io.IOException;
18 import java.io.InputStream;
19 import java.nio.file.Files;
20 import java.nio.file.LinkOption;
21 import java.nio.file.Path;
22
23 import org.apache.commons.logging.Log;
24 import org.apache.commons.logging.LogFactory;
25 import org.htmlunit.Page;
26 import org.htmlunit.WebResponse;
27 import org.htmlunit.util.FileUtils;
28 import org.htmlunit.util.StringUtils;
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44 public class DownloadingAttachmentHandler implements AttachmentHandler {
45
46 private static final Log LOG = LogFactory.getLog(DownloadingAttachmentHandler.class);
47
48 private final Path downloadFolder_;
49
50
51
52
53
54
55
56
57 public DownloadingAttachmentHandler(final Path downloadFolder) throws IOException {
58 downloadFolder_ = downloadFolder;
59 if (Files.notExists(downloadFolder)) {
60 throw new IOException("The provided download folder '"
61 + downloadFolder + "' does not exist");
62 }
63 if (!Files.isWritable(downloadFolder)) {
64 throw new IOException("Can't write to the download folder '"
65 + downloadFolder + "'");
66 }
67 }
68
69
70
71
72
73
74
75 public DownloadingAttachmentHandler() throws IOException {
76 this(Path.of(System.getProperty("java.io.tmpdir")));
77 }
78
79
80
81
82 @Override
83 public void handleAttachment(final Page page, final String attachmentFilename) {
84 final Path destination = determineDestionationFile(page, attachmentFilename);
85
86 final WebResponse webResponse = page.getWebResponse();
87 try (InputStream contentAsStream = webResponse.getContentAsStream()) {
88 Files.copy(contentAsStream, destination);
89 }
90 catch (final Exception e) {
91 LOG.error("Failed to write attachment response content to '"
92 + destination.toAbsolutePath() + "'");
93 return;
94 }
95
96 webResponse.cleanUp();
97 }
98
99 private Path determineDestionationFile(final Page page, final String attachmentFilename) {
100
101
102 String fileName = FileUtils.sanitizeFilename(attachmentFilename);
103
104 if (StringUtils.isBlank(fileName)) {
105 final String file = page.getWebResponse().getWebRequest().getUrl().getFile();
106 fileName = file.substring(file.lastIndexOf('/') + 1);
107 }
108
109 if (StringUtils.isBlank(fileName)) {
110 fileName = "download";
111 }
112
113 Path newPath = downloadFolder_.resolve(fileName);
114 int count = 1;
115 while (Files.exists(newPath, LinkOption.NOFOLLOW_LINKS)) {
116 final String newFileName;
117 final int pos = fileName.lastIndexOf('.');
118 if (pos == -1) {
119 newFileName = fileName + "(" + count + ")";
120 }
121 else {
122 newFileName = fileName.substring(0, pos)
123 + "(" + count + ")"
124 + fileName.substring(pos);
125 }
126
127 newPath = downloadFolder_.resolve(newFileName);
128 count++;
129 }
130
131 return newPath.toAbsolutePath();
132 }
133 }