diff options
author | Jon Bratseth <bratseth@yahoo-inc.com> | 2016-06-15 23:09:44 +0200 |
---|---|---|
committer | Jon Bratseth <bratseth@yahoo-inc.com> | 2016-06-15 23:09:44 +0200 |
commit | 72231250ed81e10d66bfe70701e64fa5fe50f712 (patch) | |
tree | 2728bba1131a6f6e5bdf95afec7d7ff9358dac50 /jdisc_core/src/main/java/com/yahoo/jdisc/core/ApplicationConfigModule.java |
Publish
Diffstat (limited to 'jdisc_core/src/main/java/com/yahoo/jdisc/core/ApplicationConfigModule.java')
-rw-r--r-- | jdisc_core/src/main/java/com/yahoo/jdisc/core/ApplicationConfigModule.java | 64 |
1 files changed, 64 insertions, 0 deletions
diff --git a/jdisc_core/src/main/java/com/yahoo/jdisc/core/ApplicationConfigModule.java b/jdisc_core/src/main/java/com/yahoo/jdisc/core/ApplicationConfigModule.java new file mode 100644 index 00000000000..00908df4249 --- /dev/null +++ b/jdisc_core/src/main/java/com/yahoo/jdisc/core/ApplicationConfigModule.java @@ -0,0 +1,64 @@ +// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. +package com.yahoo.jdisc.core; + +import com.google.common.collect.ImmutableMap; +import com.google.inject.AbstractModule; +import com.google.inject.name.Names; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.*; + +/** + * @author <a href="mailto:simon@yahoo-inc.com">Simon Thoresen Hult</a> + */ +class ApplicationConfigModule extends AbstractModule { + + private final Map<String, String> config; + + ApplicationConfigModule(Map<String, String> config) { + this.config = normalizeConfig(config); + } + + @Override + protected void configure() { + for (Map.Entry<String, String> entry : config.entrySet()) { + bind(String.class).annotatedWith(Names.named(entry.getKey())).toInstance(entry.getValue()); + } + } + + public static ApplicationConfigModule newInstanceFromFile(String fileName) throws IOException { + Properties props = new Properties(); + InputStream in = null; + try { + in = new FileInputStream(fileName); + props.load(in); + } finally { + if (in != null) { + in.close(); + } + } + Map<String, String> ret = new HashMap<>(); + for (String name : props.stringPropertyNames()) { + ret.put(name, props.getProperty(name)); + } + return new ApplicationConfigModule(ret); + } + + private static Map<String, String> normalizeConfig(Map<String, String> raw) { + List<String> names = new ArrayList<>(raw.keySet()); + Collections.sort(names, new Comparator<String>() { + + @Override + public int compare(String lhs, String rhs) { + return -lhs.compareTo(rhs); // reverse alphabetical order, i.e. lower-case before upper-case + } + }); + Map<String, String> ret = new HashMap<>(); + for (String name : names) { + ret.put(name.toLowerCase(Locale.US), raw.get(name)); + } + return ImmutableMap.copyOf(ret); + } +} |