-
Notifications
You must be signed in to change notification settings - Fork 1
Configuration Manager
ConfigurationFactory supports reading and writing from java.io.InputStream and java.io.OutputStream, as well as java.nio.channels.ReadableByteChannel and java.nio.channels.WritableByteChannel.
How these streams or channels are created is intentionally left to the user. However, there are some helper classes which remove much of the boilerplate work which would otherwise be required.
MyConfigManager
will support:
- Writing YAML comments
- Automatically updating old configurations with the latest keys
- Informing the user when something goes wrong, and falling back to the default configuration
This example uses System.err, but it may be desirable to use one's preferred logging framework.
public class MyConfigManager<C> extends ConfigurationHelper<C> {
private volatile C configData;
private MyConfigManager(Path configFolder, String fileName, ConfigurationFactory<C> factory) {
super(configFolder, fileName, factory);
}
public static <C> MyConfigManager<C> create(Path configFolder, String fileName, Class<C> configClass) {
// SnakeYaml example
SnakeYamlOptions yamlOptions = new SnakeYamlOptions.Builder()
.useCommentingWriter(true) // Enables writing YAML comments
.build();
return new MyConfigManager<>(configFolder, fileName,
new SnakeYamlConfigurationFactory<>(configClass, ConfigurationOptions.defaults(), yamlOptions));
}
public void reloadConfig() {
try {
configData = reloadConfigData();
} catch (IOException ex) {
throw new UncheckedIOException(ex);
} catch (ConfigFormatSyntaxException ex) {
configData = getFactory().loadDefaults();
System.err.println("Uh-oh! The syntax of your configuration are invalid. "
+ "Check your YAML syntax with a tool such as https://yaml-online-parser.appspot.com/");
ex.printStackTrace();
} catch (InvalidConfigException ex) {
configData = getFactory().loadDefaults();
System.err.println("Uh-oh! The values in your configuration are invalid. "
+ "Check to make sure you have specified the right data types.");
ex.printStackTrace();
}
}
public C getConfigData() {
C configData = this.configData;
if (configData == null) {
throw new IllegalStateException("Configuration has not been loaded yet");
}
return configData;
}
}
How to use:
Path configFolder;
String fileName;
MyConfigManager<Config> configManager = MyConfigManager.create(configFolder, fileName, Config.class);
configManager.reloadConfig();
Config config = configManager.getConfigData();
MyConfigManager
is responsible for error handling, while delegating the grunt work to ConfigurationHelper
(the superclass, where reloadConfigData() comes from).
ConfigurationFactory implementations use a BufferedReader with UTF-8 encoding by default.
This can be changed by setting the relevant charset option on GsonOptions
or SnakeYamlOptions
, depending on which format you use.