Skip to content

Easy Extension Via Interfaces

Mihai edited this page Apr 2, 2020 · 9 revisions

Since the library is encapsulated and you only work with Java Interfaces, you can implement these interfaces yourself in order to create new functionality.

We also offer a few extensions ourselves:

Edit YAML

Both YamlMapping and YamlSequence are immutable objects. Once created via building or reading, they cannot be changed in any way. However, editing is possible thanks to the above mentioned classes:

Here is how to add a pair to YamlMapping:

final YamlMapping original = Yaml
    .createYamlInput("key: value") 
    .readYamlMapping();
final YamlMapping edited = new MergedYamlMapping(
    original,
    () -> Yaml.createYamlMappingBuilder()
              .add("key2", "value2")
              .build()
);
System.out.println(edited)
key: value
key2: value2

To remove a key from the mapping, simply specify it as null in the changed mapping and provide the overrideConflicts flag as true in the constructor of MergedYamlMapping (by default conflicting keys are not overriden).

In the case of YamlSequence, merging means simply adding the element from the changed sequence to the original one. If you want to override elements which are at the same index, just set the flag overrideIndices to true in the constructor.

Complain If Node Is Missing

  • StrictYamlMapping and StrictYamlSequence
    • By default, YamlMapping and YamlSequence will return null if the required node does not exist or is of a different type. You can change this by simply wrapping it inside the "strict" decorator:
      final YamlMapping original = new StrictYamlMapping(
          Yaml.createYamlInput(...).readYamlMapping()
      );
      original.string("missing");// now it will throw YamlNodeNotFoundException
      //if "missing" is not a plain Scalar or if there is no key mapping it.