Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java and YAML: how to parse multiple yaml documents and merge them to a single YAML representation?

Let's say I have one 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 runtime, how do I read both files and merge them into one such that the application 'sees' the following?

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

Is this possible with, say, SnakeYAML? Any other tools?

I know one option is to read multiple files in as Maps and then merge them myself, render the merge to a single temporary file and then read that, but that's a heavyweight solution. Can an existing tool do this already?

like image 878
Les Hazlewood Avatar asked Oct 13 '14 17:10

Les Hazlewood


1 Answers

You can use Jackson, the key is using ObjectMapper.readerForUpdating() and annotate the field with @JsonMerge (or all the missing fields in next 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;
    }
}
like image 186
yelliver Avatar answered Nov 24 '22 08:11

yelliver