While programming my bukkit plugin, i realized that i needed to have my own config file so i can add comments into the file. I also needed to be able to update the config (if it has been created and is old).
I had also recently finished a simple jQuery plugin, where I used jQuery.extend and i merged two settings arrays. I wanted to know if this was possible in java with config files.
My Question:
Is there a way i can merge the new default config with the one the user already has? (Removing non-needed values or changing the names of the same strings)
An Explanation of the question:
Here is an example config.yml i might have:
# Comment here....
myString: defaultString
myBool: false
myList:
- Value
- Value 2
Pretty simple. Lets say this is my default config. The plugin has copied this config (if it is not already there) inside the plugin folder. But, this brings up one issue:
What if i need to update my config? (Add/Remove a bool, string, etc.)
One day, i say "I no longer need that boolean myBool". I remove it from the default config.yml and the config looks something like this:
# Comment here....
myString: defaultString
myList:
- Value
- Value 2
Or, i might need to add an extra string myNewString:
# Comment here....
myString: defaultString
myNewString: string
myList:
- Value
- Value 2
If i rewrite the config yml to my new "Default" config file, i will lose all the user's configuration settings.
Is there a way i can merge the new default config with the one the user already has and just add the new string with the default values?
If you are using Spring then you can make use of YamlPropertiesFactoryBean. It has built in support for reading multiple yaml files and merging them together. So that way you can obtain merged Map<String,Object> from your yaml files. Then if you wish you can make use of ObjectMapper to convert it to particular type.
eg.
YamlMapFactoryBean factory = new YamlMapFactoryBean();
factory.setResolutionMethod(ResolutionMethod.OVERRIDE_AND_IGNORE);
factory.setResources(...resources);
Map<String, Object> yamlValueMap = factory.getObject();
If multiple resources are provided the later ones will override entries in the earlier ones hierarchically; that is, all entries with the same nested key of type {@code Map} at any depth are merged. For example:
<pre class="code">
foo:
bar:
one: two
three: four
</pre>
plus (later in the list)
<pre class="code">
foo:
bar:
one: 2
five: six
</pre>
results in an effective input of
<pre class="code">
foo:
bar:
one: 2
three: four
five: six
</pre>
Note that the value of "foo" in the first document is not simply replaced
with the value in the second, but its nested values are merged.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With