1/*
2 * Copyright (C) 2008 The Guava Authors
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 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.google.common.testing;
18
19import com.google.common.annotations.Beta;
20import com.google.common.annotations.GwtCompatible;
21
22import java.util.ArrayList;
23import java.util.LinkedList;
24import java.util.List;
25import java.util.logging.Level;
26import java.util.logging.Logger;
27
28/**
29 * A {@code TearDownStack} contains a stack of {@link TearDown} instances.
30 *
31 * @author Kevin Bourrillion
32 * @since 10.0
33 */
34@Beta
35@GwtCompatible
36public class TearDownStack implements TearDownAccepter {
37  public static final Logger logger
38      = Logger.getLogger(TearDownStack.class.getName());
39
40  final LinkedList<TearDown> stack = new LinkedList<TearDown>();
41
42  private final boolean suppressThrows;
43
44  public TearDownStack() {
45    this.suppressThrows = false;
46  }
47
48  public TearDownStack(boolean suppressThrows) {
49    this.suppressThrows = suppressThrows;
50  }
51
52  @Override
53  public final void addTearDown(TearDown tearDown) {
54    stack.addFirst(tearDown);
55  }
56
57  /**
58   * Causes teardown to execute.
59   */
60  public final void runTearDown() {
61    List<Throwable> exceptions = new ArrayList<Throwable>();
62    for (TearDown tearDown : stack) {
63      try {
64        tearDown.tearDown();
65      } catch (Throwable t) {
66        if (suppressThrows) {
67          TearDownStack.logger.log(Level.INFO,
68              "exception thrown during tearDown: " + t.getMessage(), t);
69        } else {
70          exceptions.add(t);
71        }
72      }
73    }
74    stack.clear();
75    if ((!suppressThrows) && (exceptions.size() > 0)) {
76      throw ClusterException.create(exceptions);
77    }
78  }
79}
80