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.GwtIncompatible; 020import com.google.common.annotations.J2ktIncompatible; 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 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 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@J2ktIncompatible 091@GwtIncompatible 092@ElementTypesAreNonnullByDefault 093public final class Closer implements Closeable { 094 095 /** The suppressor implementation to use for the current Java version. */ 096 private static final Suppressor SUPPRESSOR; 097 098 static { 099 SuppressingSuppressor suppressingSuppressor = SuppressingSuppressor.tryCreate(); 100 SUPPRESSOR = suppressingSuppressor == null ? LoggingSuppressor.INSTANCE : suppressingSuppressor; 101 } 102 103 /** Creates a new {@link Closer}. */ 104 public static Closer create() { 105 return new Closer(SUPPRESSOR); 106 } 107 108 @VisibleForTesting final Suppressor suppressor; 109 110 // only need space for 2 elements in most cases, so try to use the smallest array possible 111 private final Deque<Closeable> stack = new ArrayDeque<>(4); 112 @CheckForNull private Throwable thrown; 113 114 @VisibleForTesting 115 Closer(Suppressor suppressor) { 116 this.suppressor = checkNotNull(suppressor); // checkNotNull to satisfy null tests 117 } 118 119 /** 120 * Registers the given {@code closeable} to be closed when this {@code Closer} is {@linkplain 121 * #close closed}. 122 * 123 * @return the given {@code closeable} 124 */ 125 // close. this word no longer has any meaning to me. 126 @CanIgnoreReturnValue 127 @ParametricNullness 128 public <C extends @Nullable Closeable> C register(@ParametricNullness C closeable) { 129 if (closeable != null) { 130 stack.addFirst(closeable); 131 } 132 133 return closeable; 134 } 135 136 /** 137 * Stores the given throwable and rethrows it. It will be rethrown as is if it is an {@code 138 * IOException}, {@code RuntimeException} or {@code Error}. Otherwise, it will be rethrown wrapped 139 * in a {@code RuntimeException}. <b>Note:</b> Be sure to declare all of the checked exception 140 * types your try block can throw when calling an overload of this method so as to avoid losing 141 * the original exception type. 142 * 143 * <p>This method always throws, and as such should be called as {@code throw closer.rethrow(e);} 144 * to ensure the compiler knows that it will throw. 145 * 146 * @return this method does not return; it always throws 147 * @throws IOException when the given throwable is an IOException 148 */ 149 public RuntimeException rethrow(Throwable e) throws IOException { 150 checkNotNull(e); 151 thrown = e; 152 Throwables.propagateIfPossible(e, IOException.class); 153 throw new RuntimeException(e); 154 } 155 156 /** 157 * Stores the given throwable and rethrows it. It will be rethrown as is if it is an {@code 158 * IOException}, {@code RuntimeException}, {@code Error} or a checked exception of the given type. 159 * Otherwise, it will be rethrown wrapped in a {@code RuntimeException}. <b>Note:</b> Be sure to 160 * declare all of the checked exception types your try block can throw when calling an overload of 161 * this method so as to avoid losing the original exception type. 162 * 163 * <p>This method always throws, and as such should be called as {@code throw closer.rethrow(e, 164 * ...);} to ensure the compiler knows that it will throw. 165 * 166 * @return this method does not return; it always throws 167 * @throws IOException when the given throwable is an IOException 168 * @throws X when the given throwable is of the declared type X 169 */ 170 public <X extends Exception> RuntimeException rethrow(Throwable e, Class<X> declaredType) 171 throws IOException, X { 172 checkNotNull(e); 173 thrown = e; 174 Throwables.propagateIfPossible(e, IOException.class); 175 Throwables.propagateIfPossible(e, declaredType); 176 throw new RuntimeException(e); 177 } 178 179 /** 180 * Stores the given throwable and rethrows it. It will be rethrown as is if it is an {@code 181 * IOException}, {@code RuntimeException}, {@code Error} or a checked exception of either of the 182 * given types. Otherwise, it will be rethrown wrapped in a {@code RuntimeException}. <b>Note:</b> 183 * Be sure to declare all of the checked exception types your try block can throw when calling an 184 * overload of this method so as to avoid losing the original exception type. 185 * 186 * <p>This method always throws, and as such should be called as {@code throw closer.rethrow(e, 187 * ...);} to ensure the compiler knows that it will throw. 188 * 189 * @return this method does not return; it always throws 190 * @throws IOException when the given throwable is an IOException 191 * @throws X1 when the given throwable is of the declared type X1 192 * @throws X2 when the given throwable is of the declared type X2 193 */ 194 public <X1 extends Exception, X2 extends Exception> RuntimeException rethrow( 195 Throwable e, Class<X1> declaredType1, Class<X2> declaredType2) throws IOException, X1, X2 { 196 checkNotNull(e); 197 thrown = e; 198 Throwables.propagateIfPossible(e, IOException.class); 199 Throwables.propagateIfPossible(e, declaredType1, declaredType2); 200 throw new RuntimeException(e); 201 } 202 203 /** 204 * Closes all {@code Closeable} instances that have been added to this {@code Closer}. If an 205 * exception was thrown in the try block and passed to one of the {@code exceptionThrown} methods, 206 * any exceptions thrown when attempting to close a closeable will be suppressed. Otherwise, the 207 * <i>first</i> exception to be thrown from an attempt to close a closeable will be thrown and any 208 * additional exceptions that are thrown after that will be suppressed. 209 */ 210 @Override 211 public void close() throws IOException { 212 Throwable throwable = thrown; 213 214 // close closeables in LIFO order 215 while (!stack.isEmpty()) { 216 Closeable closeable = stack.removeFirst(); 217 try { 218 closeable.close(); 219 } catch (Throwable e) { 220 if (throwable == null) { 221 throwable = e; 222 } else { 223 suppressor.suppress(closeable, throwable, e); 224 } 225 } 226 } 227 228 if (thrown == null && throwable != null) { 229 Throwables.propagateIfPossible(throwable, IOException.class); 230 throw new AssertionError(throwable); // not possible 231 } 232 } 233 234 /** Suppression strategy interface. */ 235 @VisibleForTesting 236 interface Suppressor { 237 /** 238 * Suppresses the given exception ({@code suppressed}) which was thrown when attempting to close 239 * the given closeable. {@code thrown} is the exception that is actually being thrown from the 240 * method. Implementations of this method should not throw under any circumstances. 241 */ 242 void suppress(Closeable closeable, Throwable thrown, Throwable suppressed); 243 } 244 245 /** Suppresses exceptions by logging them. */ 246 @VisibleForTesting 247 static final class LoggingSuppressor implements Suppressor { 248 249 static final LoggingSuppressor INSTANCE = new LoggingSuppressor(); 250 251 @Override 252 public void suppress(Closeable closeable, Throwable thrown, Throwable suppressed) { 253 // log to the same place as Closeables 254 Closeables.logger.log( 255 Level.WARNING, "Suppressing exception thrown when closing " + closeable, suppressed); 256 } 257 } 258 259 /** 260 * Suppresses exceptions by adding them to the exception that will be thrown using JDK7's 261 * addSuppressed(Throwable) mechanism. 262 */ 263 @VisibleForTesting 264 static final class SuppressingSuppressor implements Suppressor { 265 @CheckForNull 266 static SuppressingSuppressor tryCreate() { 267 Method addSuppressed; 268 try { 269 addSuppressed = Throwable.class.getMethod("addSuppressed", Throwable.class); 270 } catch (Throwable e) { 271 return null; 272 } 273 return new SuppressingSuppressor(addSuppressed); 274 } 275 276 private final Method addSuppressed; 277 278 private SuppressingSuppressor(Method addSuppressed) { 279 this.addSuppressed = addSuppressed; 280 } 281 282 @Override 283 public void suppress(Closeable closeable, Throwable thrown, Throwable suppressed) { 284 // ensure no exceptions from addSuppressed 285 if (thrown == suppressed) { 286 return; 287 } 288 try { 289 addSuppressed.invoke(thrown, suppressed); 290 } catch (Throwable e) { 291 // if, somehow, IllegalAccessException or another exception is thrown, fall back to logging 292 LoggingSuppressor.INSTANCE.suppress(closeable, thrown, suppressed); 293 } 294 } 295 } 296}