001/*
002 * Copyright (C) 2012 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.io;
016
017import static com.google.common.base.Preconditions.checkNotNull;
018import static com.google.common.base.Throwables.throwIfInstanceOf;
019import static com.google.common.base.Throwables.throwIfUnchecked;
020
021import com.google.common.annotations.GwtIncompatible;
022import com.google.common.annotations.J2ktIncompatible;
023import com.google.common.annotations.VisibleForTesting;
024import com.google.errorprone.annotations.CanIgnoreReturnValue;
025import java.io.Closeable;
026import java.io.IOException;
027import java.util.ArrayDeque;
028import java.util.Deque;
029import java.util.logging.Level;
030import javax.annotation.CheckForNull;
031import org.checkerframework.checker.nullness.qual.Nullable;
032
033/**
034 * A {@link Closeable} that collects {@code Closeable} resources and closes them all when it is
035 * {@linkplain #close closed}. This was intended to approximately emulate the behavior of Java 7's
036 * <a href="http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html"
037 * >try-with-resources</a> statement in JDK6-compatible code. Code using this should be
038 * approximately equivalent in behavior to the same code written with try-with-resources.
039 *
040 * <p>This class is intended to be used in the following pattern:
041 *
042 * <pre>{@code
043 * Closer closer = Closer.create();
044 * try {
045 *   InputStream in = closer.register(openInputStream());
046 *   OutputStream out = closer.register(openOutputStream());
047 *   // do stuff
048 * } catch (Throwable e) {
049 *   // ensure that any checked exception types other than IOException that could be thrown are
050 *   // provided here, e.g. throw closer.rethrow(e, CheckedException.class);
051 *   throw closer.rethrow(e);
052 * } finally {
053 *   closer.close();
054 * }
055 * }</pre>
056 *
057 * <p>Note that this try-catch-finally block is not equivalent to a try-catch-finally block using
058 * try-with-resources. To get the equivalent of that, you must wrap the above code in <i>another</i>
059 * try block in order to catch any exception that may be thrown (including from the call to {@code
060 * close()}).
061 *
062 * <p>This pattern ensures the following:
063 *
064 * <ul>
065 *   <li>Each {@code Closeable} resource that is successfully registered will be closed later.
066 *   <li>If a {@code Throwable} is thrown in the try block, no exceptions that occur when attempting
067 *       to close resources will be thrown from the finally block. The throwable from the try block
068 *       will be thrown.
069 *   <li>If no exceptions or errors were thrown in the try block, the <i>first</i> exception thrown
070 *       by an attempt to close a resource will be thrown.
071 *   <li>Any exception caught when attempting to close a resource that is <i>not</i> thrown (because
072 *       another exception is already being thrown) is <i>suppressed</i>.
073 * </ul>
074 *
075 * <p>An exception that is suppressed is added to the exception that <i>will</i> be thrown using
076 * {@code Throwable.addSuppressed(Throwable)}.
077 *
078 * @author Colin Decker
079 * @since 14.0
080 */
081// Coffee's for {@link Closer closers} only.
082@J2ktIncompatible
083@GwtIncompatible
084public final class Closer implements Closeable {
085  /** Creates a new {@link Closer}. */
086  public static Closer create() {
087    return new Closer(SUPPRESSING_SUPPRESSOR);
088  }
089
090  @VisibleForTesting final Suppressor suppressor;
091
092  // only need space for 2 elements in most cases, so try to use the smallest array possible
093  private final Deque<Closeable> stack = new ArrayDeque<>(4);
094  @CheckForNull private Throwable thrown;
095
096  @VisibleForTesting
097  Closer(Suppressor suppressor) {
098    this.suppressor = checkNotNull(suppressor); // checkNotNull to satisfy null tests
099  }
100
101  /**
102   * Registers the given {@code closeable} to be closed when this {@code Closer} is {@linkplain
103   * #close closed}.
104   *
105   * @return the given {@code closeable}
106   */
107  // close. this word no longer has any meaning to me.
108  @CanIgnoreReturnValue
109  @ParametricNullness
110  public <C extends @Nullable Closeable> C register(@ParametricNullness C closeable) {
111    if (closeable != null) {
112      stack.addFirst(closeable);
113    }
114
115    return closeable;
116  }
117
118  /**
119   * Stores the given throwable and rethrows it. It will be rethrown as is if it is an {@code
120   * IOException}, {@code RuntimeException} or {@code Error}. Otherwise, it will be rethrown wrapped
121   * in a {@code RuntimeException}. <b>Note:</b> Be sure to declare all of the checked exception
122   * types your try block can throw when calling an overload of this method so as to avoid losing
123   * the original exception type.
124   *
125   * <p>This method always throws, and as such should be called as {@code throw closer.rethrow(e);}
126   * to ensure the compiler knows that it will throw.
127   *
128   * @return this method does not return; it always throws
129   * @throws IOException when the given throwable is an IOException
130   */
131  public RuntimeException rethrow(Throwable e) throws IOException {
132    checkNotNull(e);
133    thrown = e;
134    throwIfInstanceOf(e, IOException.class);
135    throwIfUnchecked(e);
136    throw new RuntimeException(e);
137  }
138
139  /**
140   * Stores the given throwable and rethrows it. It will be rethrown as is if it is an {@code
141   * IOException}, {@code RuntimeException}, {@code Error} or a checked exception of the given type.
142   * Otherwise, it will be rethrown wrapped in a {@code RuntimeException}. <b>Note:</b> Be sure to
143   * declare all of the checked exception types your try block can throw when calling an overload of
144   * this method so as to avoid losing the original exception type.
145   *
146   * <p>This method always throws, and as such should be called as {@code throw closer.rethrow(e,
147   * ...);} to ensure the compiler knows that it will throw.
148   *
149   * @return this method does not return; it always throws
150   * @throws IOException when the given throwable is an IOException
151   * @throws X when the given throwable is of the declared type X
152   */
153  public <X extends Exception> RuntimeException rethrow(Throwable e, Class<X> declaredType)
154      throws IOException, X {
155    checkNotNull(e);
156    thrown = e;
157    throwIfInstanceOf(e, IOException.class);
158    throwIfInstanceOf(e, declaredType);
159    throwIfUnchecked(e);
160    throw new RuntimeException(e);
161  }
162
163  /**
164   * Stores the given throwable and rethrows it. It will be rethrown as is if it is an {@code
165   * IOException}, {@code RuntimeException}, {@code Error} or a checked exception of either of the
166   * given types. Otherwise, it will be rethrown wrapped in a {@code RuntimeException}. <b>Note:</b>
167   * Be sure to declare all of the checked exception types your try block can throw when calling an
168   * overload of this method so as to avoid losing the original exception type.
169   *
170   * <p>This method always throws, and as such should be called as {@code throw closer.rethrow(e,
171   * ...);} to ensure the compiler knows that it will throw.
172   *
173   * @return this method does not return; it always throws
174   * @throws IOException when the given throwable is an IOException
175   * @throws X1 when the given throwable is of the declared type X1
176   * @throws X2 when the given throwable is of the declared type X2
177   */
178  public <X1 extends Exception, X2 extends Exception> RuntimeException rethrow(
179      Throwable e, Class<X1> declaredType1, Class<X2> declaredType2) throws IOException, X1, X2 {
180    checkNotNull(e);
181    thrown = e;
182    throwIfInstanceOf(e, IOException.class);
183    throwIfInstanceOf(e, declaredType1);
184    throwIfInstanceOf(e, declaredType2);
185    throwIfUnchecked(e);
186    throw new RuntimeException(e);
187  }
188
189  /**
190   * Closes all {@code Closeable} instances that have been added to this {@code Closer}. If an
191   * exception was thrown in the try block and passed to one of the {@code exceptionThrown} methods,
192   * any exceptions thrown when attempting to close a closeable will be suppressed. Otherwise, the
193   * <i>first</i> exception to be thrown from an attempt to close a closeable will be thrown and any
194   * additional exceptions that are thrown after that will be suppressed.
195   */
196  @Override
197  public void close() throws IOException {
198    Throwable throwable = thrown;
199
200    // close closeables in LIFO order
201    while (!stack.isEmpty()) {
202      Closeable closeable = stack.removeFirst();
203      try {
204        closeable.close();
205      } catch (Throwable e) {
206        if (throwable == null) {
207          throwable = e;
208        } else {
209          suppressor.suppress(closeable, throwable, e);
210        }
211      }
212    }
213
214    if (thrown == null && throwable != null) {
215      throwIfInstanceOf(throwable, IOException.class);
216      throwIfUnchecked(throwable);
217      throw new AssertionError(throwable); // not possible
218    }
219  }
220
221  /** Suppression strategy interface. */
222  @VisibleForTesting
223  interface Suppressor {
224    /**
225     * Suppresses the given exception ({@code suppressed}) which was thrown when attempting to close
226     * the given closeable. {@code thrown} is the exception that is actually being thrown from the
227     * method. Implementations of this method should not throw under any circumstances.
228     */
229    void suppress(Closeable closeable, Throwable thrown, Throwable suppressed);
230  }
231
232  /**
233   * Suppresses exceptions by adding them to the exception that will be thrown using the
234   * addSuppressed(Throwable) mechanism.
235   */
236  private static final Suppressor SUPPRESSING_SUPPRESSOR =
237      (closeable, thrown, suppressed) -> {
238        // ensure no exceptions from addSuppressed
239        if (thrown == suppressed) {
240          return;
241        }
242        try {
243          thrown.addSuppressed(suppressed);
244        } catch (Throwable e) {
245          /*
246           * A Throwable is very unlikely, but we really don't want to throw from a Suppressor, so
247           * we catch everything. (Any Exception is either a RuntimeException or
248           * sneaky checked exception.) With no better options, we log anything to the same
249           * place as Closeables logs.
250           */
251          Closeables.logger.log(
252              Level.WARNING, "Suppressing exception thrown when closing " + closeable, suppressed);
253        }
254      };
255}