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.lang.reflect.Method;
028import java.util.ArrayDeque;
029import java.util.Deque;
030import java.util.logging.Level;
031import javax.annotation.CheckForNull;
032import org.checkerframework.checker.nullness.qual.Nullable;
033
034/**
035 * A {@link Closeable} that collects {@code Closeable} resources and closes them all when it is
036 * {@linkplain #close closed}. This is intended to approximately emulate the behavior of Java 7's <a
037 * href="http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html"
038 * >try-with-resources</a> statement in JDK6-compatible code. Running on Java 7, code using this
039 * should be approximately equivalent in behavior to the same code written with try-with-resources.
040 * Running on Java 6, exceptions that cannot be thrown must be logged rather than being added to the
041 * thrown exception as a suppressed exception.
042 *
043 * <p>This class is intended to be used in the following pattern:
044 *
045 * <pre>{@code
046 * Closer closer = Closer.create();
047 * try {
048 *   InputStream in = closer.register(openInputStream());
049 *   OutputStream out = closer.register(openOutputStream());
050 *   // do stuff
051 * } catch (Throwable e) {
052 *   // ensure that any checked exception types other than IOException that could be thrown are
053 *   // provided here, e.g. throw closer.rethrow(e, CheckedException.class);
054 *   throw closer.rethrow(e);
055 * } finally {
056 *   closer.close();
057 * }
058 * }</pre>
059 *
060 * <p>Note that this try-catch-finally block is not equivalent to a try-catch-finally block using
061 * try-with-resources. To get the equivalent of that, you must wrap the above code in <i>another</i>
062 * try block in order to catch any exception that may be thrown (including from the call to {@code
063 * close()}).
064 *
065 * <p>This pattern ensures the following:
066 *
067 * <ul>
068 *   <li>Each {@code Closeable} resource that is successfully registered will be closed later.
069 *   <li>If a {@code Throwable} is thrown in the try block, no exceptions that occur when attempting
070 *       to close resources will be thrown from the finally block. The throwable from the try block
071 *       will be thrown.
072 *   <li>If no exceptions or errors were thrown in the try block, the <i>first</i> exception thrown
073 *       by an attempt to close a resource will be thrown.
074 *   <li>Any exception caught when attempting to close a resource that is <i>not</i> thrown (because
075 *       another exception is already being thrown) is <i>suppressed</i>.
076 * </ul>
077 *
078 * <p>An exception that is suppressed is not thrown. The method of suppression used depends on the
079 * version of Java the code is running on:
080 *
081 * <ul>
082 *   <li><b>Java 7+:</b> Exceptions are suppressed by adding them to the exception that <i>will</i>
083 *       be thrown using {@code Throwable.addSuppressed(Throwable)}.
084 *   <li><b>Java 6:</b> Exceptions are suppressed by logging them instead.
085 * </ul>
086 *
087 * @author Colin Decker
088 * @since 14.0
089 */
090// Coffee's for {@link Closer closers} only.
091@J2ktIncompatible
092@GwtIncompatible
093@ElementTypesAreNonnullByDefault
094public final class Closer implements Closeable {
095
096  /** The suppressor implementation to use for the current Java version. */
097  private static final Suppressor SUPPRESSOR;
098
099  static {
100    SuppressingSuppressor suppressingSuppressor = SuppressingSuppressor.tryCreate();
101    SUPPRESSOR = suppressingSuppressor == null ? LoggingSuppressor.INSTANCE : suppressingSuppressor;
102  }
103
104  /** Creates a new {@link Closer}. */
105  public static Closer create() {
106    return new Closer(SUPPRESSOR);
107  }
108
109  @VisibleForTesting final Suppressor suppressor;
110
111  // only need space for 2 elements in most cases, so try to use the smallest array possible
112  private final Deque<Closeable> stack = new ArrayDeque<>(4);
113  @CheckForNull private Throwable thrown;
114
115  @VisibleForTesting
116  Closer(Suppressor suppressor) {
117    this.suppressor = checkNotNull(suppressor); // checkNotNull to satisfy null tests
118  }
119
120  /**
121   * Registers the given {@code closeable} to be closed when this {@code Closer} is {@linkplain
122   * #close closed}.
123   *
124   * @return the given {@code closeable}
125   */
126  // close. this word no longer has any meaning to me.
127  @CanIgnoreReturnValue
128  @ParametricNullness
129  public <C extends @Nullable Closeable> C register(@ParametricNullness C closeable) {
130    if (closeable != null) {
131      stack.addFirst(closeable);
132    }
133
134    return closeable;
135  }
136
137  /**
138   * Stores the given throwable and rethrows it. It will be rethrown as is if it is an {@code
139   * IOException}, {@code RuntimeException} or {@code Error}. Otherwise, it will be rethrown wrapped
140   * in a {@code RuntimeException}. <b>Note:</b> Be sure to declare all of the checked exception
141   * types your try block can throw when calling an overload of this method so as to avoid losing
142   * the original exception type.
143   *
144   * <p>This method always throws, and as such should be called as {@code throw closer.rethrow(e);}
145   * to ensure the compiler knows that it will throw.
146   *
147   * @return this method does not return; it always throws
148   * @throws IOException when the given throwable is an IOException
149   */
150  public RuntimeException rethrow(Throwable e) throws IOException {
151    checkNotNull(e);
152    thrown = e;
153    throwIfInstanceOf(e, IOException.class);
154    throwIfUnchecked(e);
155    throw new RuntimeException(e);
156  }
157
158  /**
159   * Stores the given throwable and rethrows it. It will be rethrown as is if it is an {@code
160   * IOException}, {@code RuntimeException}, {@code Error} or a checked exception of the given type.
161   * Otherwise, it will be rethrown wrapped in a {@code RuntimeException}. <b>Note:</b> Be sure to
162   * declare all of the checked exception types your try block can throw when calling an overload of
163   * this method so as to avoid losing the original exception type.
164   *
165   * <p>This method always throws, and as such should be called as {@code throw closer.rethrow(e,
166   * ...);} to ensure the compiler knows that it will throw.
167   *
168   * @return this method does not return; it always throws
169   * @throws IOException when the given throwable is an IOException
170   * @throws X when the given throwable is of the declared type X
171   */
172  public <X extends Exception> RuntimeException rethrow(Throwable e, Class<X> declaredType)
173      throws IOException, X {
174    checkNotNull(e);
175    thrown = e;
176    throwIfInstanceOf(e, IOException.class);
177    throwIfInstanceOf(e, declaredType);
178    throwIfUnchecked(e);
179    throw new RuntimeException(e);
180  }
181
182  /**
183   * Stores the given throwable and rethrows it. It will be rethrown as is if it is an {@code
184   * IOException}, {@code RuntimeException}, {@code Error} or a checked exception of either of the
185   * given types. Otherwise, it will be rethrown wrapped in a {@code RuntimeException}. <b>Note:</b>
186   * Be sure to declare all of the checked exception types your try block can throw when calling an
187   * overload of this method so as to avoid losing the original exception type.
188   *
189   * <p>This method always throws, and as such should be called as {@code throw closer.rethrow(e,
190   * ...);} to ensure the compiler knows that it will throw.
191   *
192   * @return this method does not return; it always throws
193   * @throws IOException when the given throwable is an IOException
194   * @throws X1 when the given throwable is of the declared type X1
195   * @throws X2 when the given throwable is of the declared type X2
196   */
197  public <X1 extends Exception, X2 extends Exception> RuntimeException rethrow(
198      Throwable e, Class<X1> declaredType1, Class<X2> declaredType2) throws IOException, X1, X2 {
199    checkNotNull(e);
200    thrown = e;
201    throwIfInstanceOf(e, IOException.class);
202    throwIfInstanceOf(e, declaredType1);
203    throwIfInstanceOf(e, declaredType2);
204    throwIfUnchecked(e);
205    throw new RuntimeException(e);
206  }
207
208  /**
209   * Closes all {@code Closeable} instances that have been added to this {@code Closer}. If an
210   * exception was thrown in the try block and passed to one of the {@code exceptionThrown} methods,
211   * any exceptions thrown when attempting to close a closeable will be suppressed. Otherwise, the
212   * <i>first</i> exception to be thrown from an attempt to close a closeable will be thrown and any
213   * additional exceptions that are thrown after that will be suppressed.
214   */
215  @Override
216  public void close() throws IOException {
217    Throwable throwable = thrown;
218
219    // close closeables in LIFO order
220    while (!stack.isEmpty()) {
221      Closeable closeable = stack.removeFirst();
222      try {
223        closeable.close();
224      } catch (Throwable e) {
225        if (throwable == null) {
226          throwable = e;
227        } else {
228          suppressor.suppress(closeable, throwable, e);
229        }
230      }
231    }
232
233    if (thrown == null && throwable != null) {
234      throwIfInstanceOf(throwable, IOException.class);
235      throwIfUnchecked(throwable);
236      throw new AssertionError(throwable); // not possible
237    }
238  }
239
240  /** Suppression strategy interface. */
241  @VisibleForTesting
242  interface Suppressor {
243    /**
244     * Suppresses the given exception ({@code suppressed}) which was thrown when attempting to close
245     * the given closeable. {@code thrown} is the exception that is actually being thrown from the
246     * method. Implementations of this method should not throw under any circumstances.
247     */
248    void suppress(Closeable closeable, Throwable thrown, Throwable suppressed);
249  }
250
251  /** Suppresses exceptions by logging them. */
252  @VisibleForTesting
253  static final class LoggingSuppressor implements Suppressor {
254
255    static final LoggingSuppressor INSTANCE = new LoggingSuppressor();
256
257    @Override
258    public void suppress(Closeable closeable, Throwable thrown, Throwable suppressed) {
259      // log to the same place as Closeables
260      Closeables.logger.log(
261          Level.WARNING, "Suppressing exception thrown when closing " + closeable, suppressed);
262    }
263  }
264
265  /**
266   * Suppresses exceptions by adding them to the exception that will be thrown using JDK7's
267   * addSuppressed(Throwable) mechanism.
268   */
269  @VisibleForTesting
270  static final class SuppressingSuppressor implements Suppressor {
271    @CheckForNull
272    static SuppressingSuppressor tryCreate() {
273      Method addSuppressed;
274      try {
275        addSuppressed = Throwable.class.getMethod("addSuppressed", Throwable.class);
276      } catch (Throwable e) {
277        return null;
278      }
279      return new SuppressingSuppressor(addSuppressed);
280    }
281
282    private final Method addSuppressed;
283
284    private SuppressingSuppressor(Method addSuppressed) {
285      this.addSuppressed = addSuppressed;
286    }
287
288    @Override
289    public void suppress(Closeable closeable, Throwable thrown, Throwable suppressed) {
290      // ensure no exceptions from addSuppressed
291      if (thrown == suppressed) {
292        return;
293      }
294      try {
295        addSuppressed.invoke(thrown, suppressed);
296      } catch (Throwable e) {
297        // if, somehow, IllegalAccessException or another exception is thrown, fall back to logging
298        LoggingSuppressor.INSTANCE.suppress(closeable, thrown, suppressed);
299      }
300    }
301  }
302}