Java and YAML: how to parse multiple yaml documents and combine them with one YAML representation?

Let's say I have a file defaults.yaml

:

pool:
  idleConnectionTestPeriodSeconds: 30
  idleMaxAgeInMinutes: 60
  partitionCount: 4
  acquireIncrement: 5
  username: dev
  password: dev_password

      

and another file production.yaml

:

pool:
  username: prod
  password: prod_password

      

At run time, how can I read both files and combine them into one so that the application "sees" the following?

pool:
  idleConnectionTestPeriodSeconds: 30
  idleMaxAgeInMinutes: 60
  partitionCount: 4
  acquireIncrement: 5
  username: prod
  password: prod_password

      

Is this possible with SnakeYAML for example? Any other tools?

I know one option is to read multiple files as Maps and then concatenate them yourself, display the merge to one temp file and then read, but this is a heavy decision. Can an existing tool do this?

+3


source to share


1 answer


You can use Jackson, the key uses ObjectMapper.readerForUpdating () and annotate the field with @JsonMerge (or any missing fields in the following objects will overwrite the old one):

Maven:

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.9</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.dataformat</groupId>
        <artifactId>jackson-dataformat-yaml</artifactId>
        <version>2.9.9</version>
    </dependency>

      



Code:

public class TestJackson {
    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
        MyConfig myConfig = new MyConfig();
        ObjectReader objectReader = mapper.readerForUpdating(myConfig);
        objectReader.readValue(new File("misc/a.yaml"));
        objectReader.readValue(new File("misc/b.yaml"));
        System.out.println(myConfig);
    }

    @Data
    public static class MyConfig {
        @JsonMerge
        private Pool pool;
    }

    @Data
    public static class Pool {
        private Integer idleConnectionTestPeriodSeconds;
        private Integer idleMaxAgeInMinutes;
        private Integer partitionCount;
        private Integer acquireIncrement;
        private String username;
        private String password;
    }
}

      

0


source







All Articles