PageRenderTime 111ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/worldedit-core/src/main/java/com/sk89q/worldedit/util/io/Closer.java

https://gitlab.com/Skull3x/WorldEdit
Java | 258 lines | 123 code | 29 blank | 106 comment | 15 complexity | c0655f334981f30cf8a83ef19622edca MD5 | raw file
  1. /*
  2. * WorldEdit, a Minecraft world manipulation toolkit
  3. * Copyright (C) sk89q <http://www.sk89q.com>
  4. * Copyright (C) WorldEdit team and contributors
  5. *
  6. * This program is free software: you can redistribute it and/or modify it
  7. * under the terms of the GNU Lesser General Public License as published by the
  8. * Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful, but WITHOUT
  12. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13. * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
  14. * for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. package com.sk89q.worldedit.util.io;
  20. import com.google.common.annotations.VisibleForTesting;
  21. import com.google.common.base.Throwables;
  22. import java.io.Closeable;
  23. import java.io.IOException;
  24. import java.lang.reflect.Method;
  25. import java.util.ArrayDeque;
  26. import java.util.Deque;
  27. import java.util.logging.Level;
  28. import java.util.logging.Logger;
  29. import java.util.zip.ZipFile;
  30. import static com.google.common.base.Preconditions.checkNotNull;
  31. public final class Closer implements Closeable {
  32. private static final Logger logger = Logger.getLogger(Closer.class.getCanonicalName());
  33. /**
  34. * The suppressor implementation to use for the current Java version.
  35. */
  36. private static final Suppressor SUPPRESSOR = SuppressingSuppressor.isAvailable()
  37. ? SuppressingSuppressor.INSTANCE
  38. : LoggingSuppressor.INSTANCE;
  39. /**
  40. * Creates a new {@link Closer}.
  41. */
  42. public static Closer create() {
  43. return new Closer(SUPPRESSOR);
  44. }
  45. @VisibleForTesting
  46. final Suppressor suppressor;
  47. // only need space for 2 elements in most cases, so try to use the smallest array possible
  48. private final Deque<Closeable> stack = new ArrayDeque<Closeable>(4);
  49. private final Deque<ZipFile> zipStack = new ArrayDeque<ZipFile>(4);
  50. private Throwable thrown;
  51. @VisibleForTesting Closer(Suppressor suppressor) {
  52. this.suppressor = checkNotNull(suppressor); // checkNotNull to satisfy null tests
  53. }
  54. /**
  55. * Registers the given {@code closeable} to be closed when this {@code Closer} is
  56. * {@linkplain #close closed}.
  57. *
  58. * @return the given {@code closeable}
  59. */
  60. // close. this word no longer has any meaning to me.
  61. public <C extends Closeable> C register(C closeable) {
  62. stack.push(closeable);
  63. return closeable;
  64. }
  65. /**
  66. * Registers the given {@code zipFile} to be closed when this {@code Closer} is
  67. * {@linkplain #close closed}.
  68. *
  69. * @return the given {@code closeable}
  70. */
  71. public <Z extends ZipFile> Z register(Z zipFile) {
  72. zipStack.push(zipFile);
  73. return zipFile;
  74. }
  75. /**
  76. * Stores the given throwable and rethrows it. It will be rethrown as is if it is an
  77. * {@code IOException}, {@code RuntimeException} or {@code Error}. Otherwise, it will be rethrown
  78. * wrapped in a {@code RuntimeException}. <b>Note:</b> Be sure to declare all of the checked
  79. * exception types your try block can throw when calling an overload of this method so as to avoid
  80. * losing the original exception type.
  81. *
  82. * <p>This method always throws, and as such should be called as
  83. * {@code throw closer.rethrow(e);} to ensure the compiler knows that it will throw.
  84. *
  85. * @return this method does not return; it always throws
  86. * @throws IOException when the given throwable is an IOException
  87. */
  88. public RuntimeException rethrow(Throwable e) throws IOException {
  89. thrown = e;
  90. Throwables.propagateIfPossible(e, IOException.class);
  91. throw Throwables.propagate(e);
  92. }
  93. /**
  94. * Stores the given throwable and rethrows it. It will be rethrown as is if it is an
  95. * {@code IOException}, {@code RuntimeException}, {@code Error} or a checked exception of the
  96. * given type. Otherwise, it will be rethrown wrapped in a {@code RuntimeException}. <b>Note:</b>
  97. * Be sure to declare all of the checked exception types your try block can throw when calling an
  98. * overload of this method so as to avoid losing the original exception type.
  99. *
  100. * <p>This method always throws, and as such should be called as
  101. * {@code throw closer.rethrow(e, ...);} to ensure the compiler knows that it will throw.
  102. *
  103. * @return this method does not return; it always throws
  104. * @throws IOException when the given throwable is an IOException
  105. * @throws X when the given throwable is of the declared type X
  106. */
  107. public <X extends Exception> RuntimeException rethrow(Throwable e,
  108. Class<X> declaredType) throws IOException, X {
  109. thrown = e;
  110. Throwables.propagateIfPossible(e, IOException.class);
  111. Throwables.propagateIfPossible(e, declaredType);
  112. throw Throwables.propagate(e);
  113. }
  114. /**
  115. * Stores the given throwable and rethrows it. It will be rethrown as is if it is an
  116. * {@code IOException}, {@code RuntimeException}, {@code Error} or a checked exception of either
  117. * of the given types. Otherwise, it will be rethrown wrapped in a {@code RuntimeException}.
  118. * <b>Note:</b> Be sure to declare all of the checked exception types your try block can throw
  119. * when calling an overload of this method so as to avoid losing the original exception type.
  120. *
  121. * <p>This method always throws, and as such should be called as
  122. * {@code throw closer.rethrow(e, ...);} to ensure the compiler knows that it will throw.
  123. *
  124. * @return this method does not return; it always throws
  125. * @throws IOException when the given throwable is an IOException
  126. * @throws X1 when the given throwable is of the declared type X1
  127. * @throws X2 when the given throwable is of the declared type X2
  128. */
  129. public <X1 extends Exception, X2 extends Exception> RuntimeException rethrow(
  130. Throwable e, Class<X1> declaredType1, Class<X2> declaredType2) throws IOException, X1, X2 {
  131. thrown = e;
  132. Throwables.propagateIfPossible(e, IOException.class);
  133. Throwables.propagateIfPossible(e, declaredType1, declaredType2);
  134. throw Throwables.propagate(e);
  135. }
  136. /**
  137. * Closes all {@code Closeable} instances that have been added to this {@code Closer}. If an
  138. * exception was thrown in the try block and passed to one of the {@code exceptionThrown} methods,
  139. * any exceptions thrown when attempting to close a closeable will be suppressed. Otherwise, the
  140. * <i>first</i> exception to be thrown from an attempt to close a closeable will be thrown and any
  141. * additional exceptions that are thrown after that will be suppressed.
  142. */
  143. @Override
  144. public void close() throws IOException {
  145. Throwable throwable = thrown;
  146. // close closeables in LIFO order
  147. while (!stack.isEmpty()) {
  148. Closeable closeable = stack.pop();
  149. try {
  150. closeable.close();
  151. } catch (Throwable e) {
  152. if (throwable == null) {
  153. throwable = e;
  154. } else {
  155. suppressor.suppress(closeable, throwable, e);
  156. }
  157. }
  158. }
  159. while (!zipStack.isEmpty()) {
  160. ZipFile zipFile = zipStack.pop();
  161. try {
  162. zipFile.close();
  163. } catch (Throwable e) {
  164. if (throwable == null) {
  165. throwable = e;
  166. } else {
  167. suppressor.suppress(zipFile, throwable, e);
  168. }
  169. }
  170. }
  171. if (thrown == null && throwable != null) {
  172. Throwables.propagateIfPossible(throwable, IOException.class);
  173. throw new AssertionError(throwable); // not possible
  174. }
  175. }
  176. /**
  177. * Suppression strategy interface.
  178. */
  179. @VisibleForTesting interface Suppressor {
  180. /**
  181. * Suppresses the given exception ({@code suppressed}) which was thrown when attempting to close
  182. * the given closeable. {@code thrown} is the exception that is actually being thrown from the
  183. * method. Implementations of this method should not throw under any circumstances.
  184. */
  185. void suppress(Object closeable, Throwable thrown, Throwable suppressed);
  186. }
  187. /**
  188. * Suppresses exceptions by logging them.
  189. */
  190. @VisibleForTesting static final class LoggingSuppressor implements Suppressor {
  191. static final LoggingSuppressor INSTANCE = new LoggingSuppressor();
  192. @Override
  193. public void suppress(Object closeable, Throwable thrown, Throwable suppressed) {
  194. // log to the same place as Closeables
  195. logger.log(Level.WARNING, "Suppressing exception thrown when closing " + closeable, suppressed);
  196. }
  197. }
  198. /**
  199. * Suppresses exceptions by adding them to the exception that will be thrown using JDK7's
  200. * addSuppressed(Throwable) mechanism.
  201. */
  202. @VisibleForTesting static final class SuppressingSuppressor implements Suppressor {
  203. static final SuppressingSuppressor INSTANCE = new SuppressingSuppressor();
  204. static boolean isAvailable() {
  205. return addSuppressed != null;
  206. }
  207. static final Method addSuppressed = getAddSuppressed();
  208. private static Method getAddSuppressed() {
  209. try {
  210. return Throwable.class.getMethod("addSuppressed", Throwable.class);
  211. } catch (Throwable e) {
  212. return null;
  213. }
  214. }
  215. @Override
  216. public void suppress(Object closeable, Throwable thrown, Throwable suppressed) {
  217. // ensure no exceptions from addSuppressed
  218. if (thrown == suppressed) {
  219. return;
  220. }
  221. try {
  222. addSuppressed.invoke(thrown, suppressed);
  223. } catch (Throwable e) {
  224. // if, somehow, IllegalAccessException or another exception is thrown, fall back to logging
  225. LoggingSuppressor.INSTANCE.suppress(closeable, thrown, suppressed);
  226. }
  227. }
  228. }
  229. }