From 83fdc67e4a594d23cbfbfc287c4fa614a5c1d652 Mon Sep 17 00:00:00 2001 From: moparisthebest Date: Mon, 31 Aug 2020 21:48:55 -0400 Subject: [PATCH] Add AutoCloseableUtil.java for java8+ --- .../jdbc/util/AutoCloseableUtil.java | 47 +++++++++++++++++++ pom.xml | 1 + 2 files changed, 48 insertions(+) create mode 100644 common/src/main/java/com/moparisthebest/jdbc/util/AutoCloseableUtil.java diff --git a/common/src/main/java/com/moparisthebest/jdbc/util/AutoCloseableUtil.java b/common/src/main/java/com/moparisthebest/jdbc/util/AutoCloseableUtil.java new file mode 100644 index 0000000..0ee86ce --- /dev/null +++ b/common/src/main/java/com/moparisthebest/jdbc/util/AutoCloseableUtil.java @@ -0,0 +1,47 @@ +package com.moparisthebest.jdbc.util; + +import java.util.Iterator; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Supplier; +import java.util.stream.Stream; + +public interface AutoCloseableUtil { + + static R apply(final Supplier supplier, final Function action) { + try (final E stream = supplier.get()) { + return action.apply(stream); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + static void accept(final Supplier supplier, final Consumer action) { + try (final E stream = supplier.get()) { + action.accept(stream); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + static , T> void forEach(final Supplier supplier, final Consumer action) { + accept(supplier, s -> s.forEach(action)); + } + + static , T> void forEachIt(final Supplier supplier, final Consumer action) { + accept(supplier, s -> { + for (final T val : s) { + action.accept(val); + } + }); + } + + static void forEachRemove(final Iterator iterator, final Function action) { + while (iterator.hasNext()) { + if (action.apply(iterator.next())) { + iterator.remove(); + } + } + } + +} diff --git a/pom.xml b/pom.xml index 569497e..16128d7 100644 --- a/pom.xml +++ b/pom.xml @@ -246,6 +246,7 @@ **/module-info.java **/PrestoPersonDAO.java + **/AutoCloseableUtil.java **/com/moparisthebest/jdbc/cache/*