Created
September 16, 2014 19:00
-
-
Save dain/b26e8878aabc6124c22a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package io.airlift.testing; | |
import java.io.Closeable; | |
import java.io.IOException; | |
import static com.google.common.base.Preconditions.checkNotNull; | |
public final class Closeables | |
{ | |
private Closeables() | |
{ | |
} | |
public static void closeQuietly(Closeable... closeables) | |
{ | |
if (closeables == null) { | |
return; | |
} | |
for (Closeable closeable : closeables) { | |
try { | |
if (closeable != null) { | |
closeable.close(); | |
} | |
} | |
catch (IOException ignored) { | |
} | |
} | |
} | |
public static void closeAll(Closeable... closeables) | |
throws IOException | |
{ | |
IOException rootCause = null; | |
for (Closeable closeable : closeables) { | |
try { | |
if (closeable != null) { | |
closeable.close(); | |
} | |
} | |
catch (IOException e) { | |
if (rootCause == null) { | |
rootCause = e; | |
} else { | |
rootCause.addSuppressed(e); | |
} | |
} catch (RuntimeException e) { | |
if (rootCause == null) { | |
rootCause = new IOException(e); | |
} else { | |
rootCause.addSuppressed(e); | |
} | |
} | |
} | |
if (rootCause != null) { | |
throw rootCause; | |
} | |
} | |
public static void closeAllRuntimeException(Closeable... closeables) | |
{ | |
RuntimeException rootCause = null; | |
for (Closeable closeable : closeables) { | |
try { | |
if (closeable != null) { | |
closeable.close(); | |
} | |
} | |
catch (Throwable e) { | |
if (rootCause == null) { | |
rootCause = new RuntimeException(e); | |
} else { | |
rootCause.addSuppressed(e); | |
} | |
} | |
} | |
if (rootCause != null) { | |
throw rootCause; | |
} | |
} | |
public static <T extends Throwable> T closeAllSuppress(T rootCause, Closeable... closeables) | |
{ | |
checkNotNull(rootCause, "rootCause is null"); | |
if (closeables == null) { | |
return rootCause; | |
} | |
for (Closeable closeable : closeables) { | |
try { | |
if (closeable != null) { | |
closeable.close(); | |
} | |
} | |
catch (Throwable e) { | |
rootCause.addSuppressed(e); | |
} | |
} | |
return rootCause; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment