View Javadoc
1   /*
2    * Copyright (c) 2002-2026 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
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   * Implementation of an {@link AttachmentHandler} that mimics how browsers handle attachments.
32   * Specifically
33   * <ul>
34   * <li>download file into a default folder when attachment response is detected</li>
35   * <li>infer filename from octet stream response and use that when saving file</li>
36   * <li>if a file already exists, append number to it.
37   * Keep incrementing numbers until you find a slot that is free (that's how Chrome handles duplicate filenames).</li>
38   * </ul>
39   *
40   * @author Marek Andreansky
41   * @author Ronald Brill
42   * @author Vidya m
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       * Creates a new DownloadingAttachmentHandler that stores all downloaded files in the
52       * provided directory. The directory must exist and be writable.
53       *
54       * @param downloadFolder the path to the folder for storing all downloaded files
55       * @throws IOException if the folder does not exist or the folder is not writable
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       * Creates a new DownloadingAttachmentHandler that stores all downloaded files in the
71       * 'temp'-dir (System.getProperty("java.io.tmpdir")).
72       *
73       * @throws IOException if the folder does not exist or the folder is not writable
74       */
75      public DownloadingAttachmentHandler() throws IOException {
76          this(Path.of(System.getProperty("java.io.tmpdir")));
77      }
78  
79      /**
80       * {@inheritDoc}
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         // the name can come from the page (download attribute), sanitize it like
101         // a name from the Content-Disposition header to stay inside the download folder
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 }