|
| 1 | +package org.example.config; |
| 2 | + |
| 3 | +import tools.jackson.databind.ObjectMapper; |
| 4 | +import tools.jackson.databind.json.JsonMapper; |
| 5 | +import tools.jackson.dataformat.yaml.YAMLFactory; |
| 6 | +import tools.jackson.dataformat.yaml.YAMLMapper; |
| 7 | + |
| 8 | +import java.io.InputStream; |
| 9 | +import java.nio.file.Files; |
| 10 | +import java.nio.file.Path; |
| 11 | +import java.util.Objects; |
| 12 | + |
| 13 | +public final class ConfigLoader { |
| 14 | + |
| 15 | + private static volatile AppConfig cached; |
| 16 | + |
| 17 | + private ConfigLoader() {} |
| 18 | + |
| 19 | + public static AppConfig loadOnce(Path configPath) { |
| 20 | + if (cached != null) return cached; |
| 21 | + |
| 22 | + synchronized (ConfigLoader.class) { |
| 23 | + if (cached == null){ |
| 24 | + cached = load(configPath).withDefaultsApplied(); |
| 25 | + } |
| 26 | + return cached; |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + public static AppConfig get(){ |
| 31 | + if (cached == null){ |
| 32 | + throw new IllegalStateException("Config not loaded. call ConfigLoader.loadOnce(...) at startup."); |
| 33 | + } |
| 34 | + return cached; |
| 35 | + |
| 36 | + } |
| 37 | + |
| 38 | + public static AppConfig load(Path configPath) { |
| 39 | + Objects.requireNonNull(configPath, "configPath"); |
| 40 | + |
| 41 | + if (!Files.exists(configPath)) { |
| 42 | + return AppConfig.defaults(); |
| 43 | + } |
| 44 | + |
| 45 | + ObjectMapper objectMapper = createMapperFor(configPath); |
| 46 | + |
| 47 | + try (InputStream stream = Files.newInputStream(configPath)){ |
| 48 | + AppConfig config = objectMapper.readValue(stream, AppConfig.class); |
| 49 | + return config == null ? AppConfig.defaults() : config; |
| 50 | + } catch (Exception e){ |
| 51 | + throw new IllegalStateException("failed to read config file " + configPath.toAbsolutePath(), e); |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + private static ObjectMapper createMapperFor(Path configPath) { |
| 56 | + String name = configPath.getFileName().toString().toLowerCase(); |
| 57 | + |
| 58 | + if (name.endsWith(".yml") || name.endsWith(".yaml")) { |
| 59 | + return YAMLMapper.builder(new YAMLFactory()).build(); |
| 60 | + |
| 61 | + } else if (name.endsWith(".json")) { |
| 62 | + return JsonMapper.builder().build(); |
| 63 | + } else { |
| 64 | + return YAMLMapper.builder(new YAMLFactory()).build(); |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + static void resetForTests() { |
| 69 | + cached = null; |
| 70 | + } |
| 71 | +} |
0 commit comments