diff --git a/search-services/alfresco-search/src/main/java/org/alfresco/solr/utils/Utils.java b/search-services/alfresco-search/src/main/java/org/alfresco/solr/utils/Utils.java index 2254b9cf0..3b586ca11 100644 --- a/search-services/alfresco-search/src/main/java/org/alfresco/solr/utils/Utils.java +++ b/search-services/alfresco-search/src/main/java/org/alfresco/solr/utils/Utils.java @@ -18,11 +18,18 @@ */ package org.alfresco.solr.utils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.Closeable; +import java.io.IOException; import java.util.Collection; import java.util.Collections; public abstract class Utils { + private static final Logger LOGGER = LoggerFactory.getLogger(Utils.class); + /** * Returns the same input collection if that is not null, otherwise a new empty collection. * Provides a safe way for iterating over a returned collection (which could be null). @@ -53,4 +60,41 @@ public abstract class Utils return null; } } + + /** + * Silently closes the given {@link Closeable} resource without raising any exception. + * This utility method is specifically useful when we have to close a resource in a lamba statement: since the + * close() method could throw an {@link IOException} the compiler requires an enclosing try / catch block which + * makes the code less readable. + * + *

+ *

+ * + * try { if (resource != null) resource.close } catch (IOException exception) { ... } + * + *

+ *
+ * + * In these contexts a call to this method reduces the amount of code needed: + * + *

+ *

+ * + * silentlyClose(resource); + * + *

+ * + * @param resource the {@link Closeable} resource we want to silently close. + */ + public static void silentyClose(Closeable resource) + { + try + { + if (resource != null) resource.close(); + } + catch(IOException ignore) + { + LOGGER.warn("Unable to properly close the resource instance {}. See the stacktrace below for further details.", resource, ignore); + } + } }