Skip to content
zml edited this page Nov 14, 2020 · 5 revisions

Cookbook

There are many common operations that may be done on configurations that are still specialized enough that they will be customized from project to project. Examples are written assuming they are written within a main() method of a program.

Loading a default config (mergeValues usage)

TODO

Converting from one format to another

Because the data structures of loaded configurations are fairly decoupled from how those configurations are loaded, converting between formats is not much more complicated than simply loading and saving in one format. Here's a simple example of converting a YAML configuration to HOCON:

        // First off: we build two loaders, one with our old format pointing to the old location
        final YamlConfigurationLoader oldFormat = YamlConfigurationLoader.builder()
                .path(Paths.get("widgets.yml"))
                .build();

        // and a second one for our target format, pointing to the new location
        final HoconConfigurationLoader newFormat = HoconConfigurationLoader.builder()
                .path(Paths.get("widgets.conf"))
                .build();

        // We try to load the file into a node using the source format
        final ConfigurationNode oldNode;
        try {
            oldNode = oldFormat.load();
        } catch (IOException e) {
            System.err.println("Unable to read YAML configuration: " + e.getMessage());
            if (e.getCause() != null) {
                e.getCause().printStackTrace();
            }
            System.exit(1);
            return;
        }

        // And if we're successful, we save the loaded node using the new loader
        try {
            newFormat.save(oldNode);
        } catch (IOException e) {
            System.out.println("Unable to save HOCON format configuration: " + e.getMessage());
            System.exit(2);
            return;
        }

        System.out.println("Successfully converted widgets.yml to widgets.conf!");