View Javadoc
1   /*
2    * Copyright (c) 2002-2025 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.ObjectInputStream;
19  import java.util.ArrayList;
20  import java.util.List;
21  
22  import org.htmlunit.Page;
23  import org.htmlunit.WebAssert;
24  
25  /**
26   * An {@link AttachmentHandler} implementation which creates an {@link Attachment} for
27   * each attached page, collecting all created attachments into a list.
28   *
29   * @author Bruce Chapman
30   * @author Sudhan Moghe
31   * @author Daniel Gredler
32   * @author Ronald Brill
33   * @author Lai Quang Duong
34   */
35  public class CollectingAttachmentHandler implements AttachmentHandler {
36  
37      private transient List<Attachment> collectedAttachments_;
38  
39      /**
40       * Creates a new instance.
41       */
42      public CollectingAttachmentHandler() {
43          this(new ArrayList<>());
44      }
45  
46      /**
47       * Creates a new instance which collects attachments into the specified list.
48       * @param list the list to store attachments in
49       */
50      public CollectingAttachmentHandler(final List<Attachment> list) {
51          WebAssert.notNull("list", list);
52          collectedAttachments_ = list;
53      }
54  
55      /**
56       * {@inheritDoc}
57       */
58      @Override
59      public void handleAttachment(final Page page, final String attachmentFilename) {
60          collectedAttachments_.add(new Attachment(page, attachmentFilename));
61      }
62  
63      /**
64       * Returns the list of attachments collected by this attachment handler. The returned
65       * list is modifiable, so that attachments can be removed after being processed.
66       * @return the list of attachments collected by this attachment handler
67       */
68      public List<Attachment> getCollectedAttachments() {
69          return collectedAttachments_;
70      }
71  
72      private void readObject(final ObjectInputStream ois) throws ClassNotFoundException, IOException {
73          ois.defaultReadObject();
74          collectedAttachments_ = new ArrayList<>();
75      }
76  }