-
Notifications
You must be signed in to change notification settings - Fork 0
Using OptionalBetterYaml
OptionalBetterYaml was added later, as an improvement to the existing BetterYaml class which is now meant for internal use only.
First, make sure your project meets the setup requirements described in the setup wiki page.
When using the OptionalBetterYaml class to handle our files, we can simply do the following:
// Auto-updates the config on the server and loads a YamlConfiguration and File
OptionalBetterYaml ourConfig = new OptionalBetterYaml("ourConfig.yml", javaPlugin);
// Get the Optional container
Optional<YamlConfiguration> loadResult = ourConfig.getYamlConfiguration();
// Check if the configuration was loaded correctly
boolean isReadingSuccess = loadResult.isPresent(); // True if it was loaded correctly, false if an Exception occurred. This is the other way around for Optional#isEmpty()
// Get a YamlConfiguration to do your regular config reading. ONLY do this if `loadResult.isPresent()` returns true!
YamlConfiguration yaml = loadResult.get();
// Not enough? You can also get a File instance and handle it the same way we handled the YamlConfiguration
Optional<File> file = ourConfig.getFile();
BetterYaml supports printing information about the config file (when a new file is copied or missing options are found). If you want your users to see this info, simply pass a boolean in the constructor. It is considered to be false by default.
// Simply pass a boolean as the last argument
OptionalBetterYaml ourConfig = new OptionalBetterYaml("ourConfig.yml", javaPlugin, true);
Not sure how to handle Optionals yet?
They are used to prevent NPEs and never contain a null value. In the case of BetterYaml, we can assure that we never return null so no explicit null checks are required on your end.
The snippet below explains how to handle an Optional properly. We assume that optionalBetterYaml is an OptionalBetterYaml instance.
Optional<YamlConfiguration> config = optionalBetterYaml.get();
// If a value is present: handle config reading
if (config.isPresent())
{
// You can safely call config.get() and go about your usual business
// All values are present in the YamlConfigurationSection that you just fetched and you can just read it as you would normally
}
else
{
// Should only happen if a file is missing in your resources
// Handle the case where no configuration can be loaded, eg. disabling your plugin or fetch default values from somewhere and work with those (but this should never happen)
// We recommend disabling your plugin in this case, but that is totally up to you
}
Please use OptionalBetterYaml instead.
Auto-correct faulty configuration values! You can create your own, custom validators.