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