Skip to content

Latest commit

 

History

History
212 lines (152 loc) · 10.7 KB

nodes.rst

File metadata and controls

212 lines (152 loc) · 10.7 KB

Configuration Nodes

Warning

These docs were written for SpongeAPI 7 and are likely out of date. If you feel like you can help update them, please submit a PR!

.. javadoc-import::
    com.google.common.reflect.TypeToken
    org.spongepowered.configurate.ConfigurationNode
    org.spongepowered.configurate.ConfigurationOptions
    org.spongepowered.configurate.commented.CommentedConfigurationNode
    org.spongepowered.configurate.loader.ConfigurationLoader
    org.spongepowered.configurate.objectmapping.ObjectMappingException
    org.spongepowered.configurate.objectmapping.serialize.TypeSerializer
    java.lang.Class
    java.lang.Object
    java.util.UUID
    org.spongepowered.api.util.TypeTokens

In memory, the configuration is represented using :javadoc:`ConfigurationNode`s. A ConfigurationNode either holds a value (like a number, a string or a list) or has child nodes, a tree-like configuration structure. When using a :javadoc:`ConfigurationLoader` to load or create new configurations, it will return the root node. We recommend that you always keep a reference to that root node stored somewhere, to prevent loading the configuration every time you need to access it. As a side effect, this will keep the comments that were present in the file. As an alternative, you could store a reference to a :doc:`serializable config instance <serialization>` that holds the entire configuration of your plugin.

Note

Depending on the ConfigurationLoader used, you might even get a :javadoc:`CommentedConfigurationNode`, which in addition to normal ConfigurationNode behavior is able to retain a comment that will persist on the saved config file.

Navigating Nodes

Every child node is identified by a key, most commonly a string. When going from one node (for example the root node) to a specific child node, it may be necessary to move through multiple layers of child nodes. The keys of the child nodes passed make up the path of the target node. In the following example, there is a node holding the value false at the path modules blockCheats enabled (from the root node) in the following HOCON representation of a config.

Note

When written down, paths are commonly represented by joining the keys together with a separator char, usually .. The above mentioned path would be written modules.blockCheats.enabled.

modules {
    blockCheats {
        enabled=true
    }
}

In Java, you can get the child node for a path using the getNode(...) method. The method accepts any number of arguments, where each argument is one key in the path. The path modules.blockCheats.enabled from a root node is acquired as follows.

import org.spongepowered.configurate.ConfigurationNode;

ConfigurationNode rootNode = ...;
ConfigurationNode targetNode = rootNode.getNode("modules", "blockCheats", "enabled");

Note

The function calls node.getNode("foo", "bar") and node.getNode("foo").getNode("bar") are equivalent.

Values

Basic Values

Basic value types like int, double, boolean or String each have their own convenience getter method which will return the value or a default if the node does not contain a value of that type. Let's check if the server administrator wants our plugin to enable its blockCheats module by checking the value at the modules.blockCheats.enabled path.

boolean shouldEnable = rootNode.getNode("modules", "blockCheats", "enabled").getBoolean();

Yes, it's really as simple as that. Similar to the above example, methods like :javadoc:`ConfigurationNode#getInt()`, :javadoc:`ConfigurationNode#getDouble()` or :javadoc:`ConfigurationNode#getString()` exist that allow you to conveniently grab a value of that type.

To set a basic value to a node, just use the :javadoc:`ConfigurationNode#setValue(Object)` method. Don't be confused that it accepts an :javadoc:`Object` - this means that it can take anything and will determine how to proceed from there by itself.

Imagine the blockCheats module is deactivated by a user command. This change will need to be reflected in the config and can be done as follows:

rootNode.getNode("modules", "blockCheats", "enabled").setValue(false);

Warning

Anything other than basic value types cannot be handled by those basic functions, and must instead be read and written using the (de)serializing Methods described below. Basic types are those that are natively handled by the underlying implementation of the file format used by the ConfigurationLoader, but generally include the primitive data types, Strings as well as Lists and Maps of basic types.

(De)Serialization

If you attempt to read or write an object that is not one of the basic types mentioned above, you will need to pass it through deserialization first. In the :javadoc:`ConfigurationOptions` used to create your root ConfigurationNode, there is a collection of :javadoc:`TypeSerializer`s that Configurate uses to convert your objects to a ConfigurationNode and vice versa.

In order to tell Configurate what type it is dealing with, we have to provide a guava :javadoc:`TypeToken`. Imagine we want to read a player :javadoc:`UUID` from the config node towns.aFLARDia.mayor. To do so, we need to call the :javadoc:`ConfigurationNode#getValue(TypeToken) {getValue(...)}` method while providing a TypeToken representing the UUID class.

import java.util.UUID;

UUID mayor = rootNode.getNode("towns", "aFLARDia", "mayor").getValue(TypeToken.of(UUID.class));

This prompts Configurate to locate the proper TypeSerializer for UUIDs and then use it to convert the stored value into a UUID. The TypeSerializer (and by extension the above method) may throw an :javadoc:`ObjectMappingException` if it encounters incomplete or invalid data.

Now if we want to write a new UUID to that config node, the syntax is very similar. Use the :javadoc:`ConfigurationNode#setValue(TypeToken, Object) {setValue(...)}` method with a TypeToken and the object you want to serialize.

rootNode.getNode("towns","aFLARDia", "mayor").setValue(TypeToken.of(UUID.class), newUuid);

Note

Serializing a value will throw an ObjectMappingException if no TypeSerializer for the given TypeToken can be found.

For simple classes like UUID, you can just create a TypeToken using the static :javadoc:`TypeToken#of(Class)` method. However, UUIDs and some other types already have a constant for it, such as :javadoc:`TypeTokens#UUID_TOKEN`, which you should use instead. If the class you want to use has type parameters (like Map<String,UUID>) and no constant yet exists for it, the syntax gets a bit more complicated. In most cases you will know exactly what the type parameters will be at compile time, so you can just create the TypeToken as an anonymous class: new TypeToken<Map<String,UUID>>() {}. That way, even generic types can conveniently be written and read.

.. seealso::
    For more information about ``TypeToken``\s, refer to the `guava documentation
    <https://github.com/google/guava/wiki/ReflectionExplained>`_

Tip

The SpongeAPI provides a :javadoc:`TypeTokens {class}` with many pre-defined type tokens that you can use. If plugin developers need many different or complex TypeTokens, or use them frequently, we recommend creating a similar class for themselves to improve code readability. (Beware, it is not guaranteed that all of those entries have registered TypeSerializers).

You can find a non-exhaustive list of supported types, and ways to add support for new types on the :doc:`the config serialization page <serialization>`.

Defaults

Unlike SpongeAPI, the Configurate library does not use Optional for values that might not be present but null. While the getters for primitive methods (like getBoolean() or getInt()) might return false or 0, those that would return an object (like getString()) will return null if no value is present. If you do not want to manually handle those special cases, you can use default values. Every getXXX() method discussed above has an overloaded form accepting an additional parameter as a default value.

Let us take a look at the example for reading a boolean value again.

boolean shouldEnable = rootNode.getNode("modules", "blockCheats", "enabled").getBoolean();

This call will return false if either the value false is saved in the config or the value is not present in the config. Since those two cases are indistinguishable we have no simple way of setting our variable to false only if that is the value specified on the config. Unless we specify true as the default value.

boolean shouldEnable = rootNode.getNode("modules", "blockCheats", "enabled").getBoolean(true);

Similarly, you can specify defaults on any value you get from the config, thus avoiding null returns or ObjectMappingException caused by the absence of the whole value. It also works on the deserializing getValue() method. Some examples:

String greeting = rootNode.getNode("messages", "greeting")
        .getString("FLARD be with you good man!");

UUID mayor = rootNode.getNode("towns", "aFLARDia", "mayor")
        .getValue(TypeTokens.UUID_TOKEN, somePlayer.getUniqueId());

Another useful application of those defaults is that they can be copied to your configuration if needed. Upon creation of your root configuration node, you can create your ConfigurationOptions with :javadoc:`ConfigurationOptions#setShouldCopyDefaults(boolean) {setShouldCopyDefaults(true)}`. Subsequently, whenever you provide a default value, Configurate will first check if the value you're trying to get is present, and if it is not, it will first write your default value to the node before returning the default value.

Let's assume your plugin is running for the first time and the config file does not exist yet. You try to load it with ConfigurationOptions that enable copying of default values and get an empty config node. Now you run the line rootNode.getNode("modules", "blockCheats", "enabled").getBoolean(true). As the node does not yet exist, configurate creates it and writes the value true to it as per the ConfigurationOptions before returning it. When the config is then finished, the value true will persist on the node without ever being explicitly set.