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;
16  
17  import java.io.Serializable;
18  import java.util.ArrayList;
19  import java.util.List;
20  
21  /**
22   * A simple alert handler that keeps track of alerts in a list.
23   *
24   * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
25   */
26  public class CollectingAlertHandler implements AlertHandler, Serializable {
27  
28      private final List<String> collectedAlerts_;
29  
30      /**
31       * Creates a new instance, initializing it with an empty list.
32       */
33      public CollectingAlertHandler() {
34          this(new ArrayList<>());
35      }
36  
37      /**
38       * Creates an instance with the specified list.
39       *
40       * @param list the list to store alerts in
41       */
42      public CollectingAlertHandler(final List<String> list) {
43          WebAssert.notNull("list", list);
44          collectedAlerts_ = list;
45      }
46  
47      /**
48       * Handles the alert. This implementation will store the message in a list
49       * for retrieval later.
50       *
51       * @param page the page that triggered the alert
52       * @param message the message in the alert
53       */
54      @Override
55      public void handleAlert(final Page page, final String message) {
56          collectedAlerts_.add(message);
57      }
58  
59      /**
60       * Returns a list containing the message portion of any collected alerts.
61       * @return a list of alert messages
62       */
63      public List<String> getCollectedAlerts() {
64          return collectedAlerts_;
65      }
66  
67      /**
68       * Removes all alerts.
69       */
70      public void clear() {
71          collectedAlerts_.clear();
72      }
73  }