ConfigBuilder { public <T> T build(T config) { List<MapBuilder> mapBuilders = new ArrayList<>(); File yamlFile = new File(basename + ".yaml"); if (yamlFile.isFile()) { mapBuilders.add(new YamlBuilder(fileConfigKeys, getFileReader(yamlFile))); } File jsonFile = new File(basename + ".json"); if (jsonFile.isFile()) { mapBuilders.add(new JsonBuilder(fileConfigKeys, getFileReader(jsonFile))); } if(annotation != null) { mapBuilders.add(new AnnotationBuilder(annotation)); } mapBuilders.add(new StringMapBuilder(environmentVariablePrefix, systemProperties)); mapBuilders.add(new StringMapBuilder(environmentVariablePrefix, environmentVariables)); mapBuilders.add(new OptparseBuilder(config, optparseSurplusKey, asList(commandLineArgs), optparseAliases)); FieldSetter fieldSetter = new FieldSetter(config); for (MapBuilder mapBuilder : mapBuilders) { fieldSetter.setFields(mapBuilder.buildMap()); } return config; } ConfigBuilder(String basename, String[] fileConfigKeys, Annotation annotation, Map<?, ?> systemProperties, Map<?, ?> environmentVariables, String environmentVariablePrefix, String[] commandLineArgs, Map<String, String> optparseAliases, String optparseSurplusKey); T build(T config);  }
@Test public void builds_object_from_files_and_command_line() { ConfigBuilder configBuilder = new ConfigBuilder( "src/test/resources/test-config", new String[]{"testing"}, null, new HashMap<>(), new HashMap<>(), "testing", "--somebool something else".split(" "), new HashMap<String, String>(), "stringlist" ); MyConfig config = configBuilder.build(new MyConfig()); assertEquals(43, config.meaning); assertEquals("Hello from YAML", config.message); assertEquals(asList("something", "else"), config.stringlist); assertTrue(config.somebool); }
@Test public void builds_object_from_env_and_system_properties() { ConfigBuilder configBuilder = new ConfigBuilder( "src/test/resources/does-not-exist", new String[]{"not-used"}, null, new HashMap<String, String>() {{ put("testing.meaning", "43"); }}, new HashMap<String, String>() {{ put("TESTING_MESSAGE", "Hello from ENV"); put("TESTING_SOMEBOOL", "true"); }}, "testing.", new String[0], new HashMap<String, String>(), "not-used" ); MyConfig config = configBuilder.build(new MyConfig()); assertEquals(43, config.meaning); assertEquals("Hello from ENV", config.message); assertTrue(config.somebool); }