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