package envoy.data; import java.util.*; import envoy.exception.EnvoyException; /** * Manages all application settings that are set during application startup by * either loading them from the {@link Properties} file * {@code client.properties} or parsing them from the command line arguments of * the application.
*
* Project: envoy-client
* File: Config.java
* Created: 12 Oct 2019
* * @author Kai S. K. Engelbart * @since Envoy Common v0.1-beta */ public class Config { protected Map> items = new HashMap<>(); /** * Parses config items from a properties object. * * @param properties the properties object to parse * @since Envoy Common v0.1-beta */ public void load(Properties properties) { items.entrySet() .stream() .filter(e -> properties.containsKey(e.getKey())) .forEach(e -> e.getValue().parse(properties.getProperty(e.getKey()))); } /** * Parses config items from an array of command line arguments. * * @param args the command line arguments to parse * @throws EnvoyException if the command line arguments contain an unknown token * @since Envoy Common v0.1-beta */ public void load(String[] args) throws EnvoyException { for (int i = 0; i < args.length; i++) for (ConfigItem item : items.values()) if (args[i].startsWith("--")) { if (args[i].length() == 2) throw new EnvoyException("Malformed command line argument at position " + i); final String commandLong = args[i].substring(2); if (item.getCommandLong().equals(commandLong)) { item.parse(args[++i]); break; } } else if (args[i].startsWith("-")) { if (args[i].length() == 1) throw new EnvoyException("Malformed command line argument at position " + i); final String commandShort = args[i].substring(1); if (item.getCommandShort().equals(commandShort)) { item.parse(args[++i]); break; } } else throw new EnvoyException("Malformed command line argument at position " + i); } /** * Initializes config items from a map. * * @param items the items to include in this config * @since Envoy Common v0.1-beta */ public void load(Map> items) { this.items.putAll(items); } /** * @return {@code true} if all mandatory config items are initialized * @since Envoy Common v0.1-beta */ public boolean isInitialized() { return items.values().stream().filter(ConfigItem::isMandatory).map(ConfigItem::get).noneMatch(Objects::isNull); } /** * @param name the name of the config item to return * @return the config item with the specified name * @since Envoy Common v0.1-beta */ public ConfigItem get(String name) { return items.get(name); } }