From 7323c373391f54cbeaf56ac27bd7b702c2c97d31 Mon Sep 17 00:00:00 2001 From: Jason Tedor Date: Wed, 23 Mar 2016 21:06:53 -0400 Subject: [PATCH] Refactor PropertiesSettingsLoader This commit refactors PropertiesSettingsLoader to remove some duplicate code. --- .../loader/PropertiesSettingsLoader.java | 38 ++++++++++--------- 1 file changed, 21 insertions(+), 17 deletions(-) diff --git a/core/src/main/java/org/elasticsearch/common/settings/loader/PropertiesSettingsLoader.java b/core/src/main/java/org/elasticsearch/common/settings/loader/PropertiesSettingsLoader.java index 57c9419f5b2..849a4354427 100644 --- a/core/src/main/java/org/elasticsearch/common/settings/loader/PropertiesSettingsLoader.java +++ b/core/src/main/java/org/elasticsearch/common/settings/loader/PropertiesSettingsLoader.java @@ -24,10 +24,12 @@ import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.common.io.FastStringReader; import org.elasticsearch.common.io.stream.StreamInput; +import java.io.Closeable; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Properties; +import java.util.function.Supplier; /** * Settings loader that loads (parses) the settings in a properties format. @@ -36,36 +38,38 @@ public class PropertiesSettingsLoader implements SettingsLoader { @Override public Map load(String source) throws IOException { - Properties props = new NoDuplicatesProperties(); - FastStringReader reader = new FastStringReader(source); - try { - props.load(reader); - Map result = new HashMap<>(); - for (Map.Entry entry : props.entrySet()) { - result.put((String) entry.getKey(), (String) entry.getValue()); - } - return result; - } finally { - IOUtils.closeWhileHandlingException(reader); - } + return load(() -> new FastStringReader(source), (reader, props) -> props.load(reader)); } @Override public Map load(byte[] source) throws IOException { - Properties props = new NoDuplicatesProperties(); - StreamInput stream = StreamInput.wrap(source); + return load(() -> StreamInput.wrap(source), (inStream, props) -> props.load(inStream)); + } + + private final Map load( + Supplier supplier, + IOExceptionThrowingBiConsumer properties + ) throws IOException { + T t = null; try { - props.load(stream); - Map result = new HashMap<>(); + t = supplier.get(); + final Properties props = new NoDuplicatesProperties(); + properties.accept(t, props); + final Map result = new HashMap<>(); for (Map.Entry entry : props.entrySet()) { result.put((String) entry.getKey(), (String) entry.getValue()); } return result; } finally { - IOUtils.closeWhileHandlingException(stream); + IOUtils.closeWhileHandlingException(t); } } + @FunctionalInterface + private interface IOExceptionThrowingBiConsumer { + void accept(T t, U u) throws IOException; + } + class NoDuplicatesProperties extends Properties { @Override public synchronized Object put(Object key, Object value) {