All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.microprofileext.config.source.yaml.YamlConfigSource Maven / Gradle / Ivy

There is a newer version: 3.0.1
Show newest version
package org.microprofileext.config.source.yaml;

import java.io.InputStream;
import java.util.Map;
import java.util.TreeMap;
import lombok.extern.java.Log;
import org.microprofileext.config.source.base.file.AbstractUrlBasedSource;
import org.yaml.snakeyaml.Yaml;

/**
 * Yaml config source
 * @author Phillip Kruger
 */
@Log
public class YamlConfigSource extends AbstractUrlBasedSource {

    @Override
    protected String getFileExtension() {
        return "yaml";
    }

    @Override
    @SuppressWarnings("unchecked")
    protected Map toMap(InputStream inputStream) {
        final Map properties = new TreeMap<>();
        Yaml yaml = new Yaml();
        TreeMap yamlInput = yaml.loadAs(inputStream, TreeMap.class);
        
        for (String key : yamlInput.keySet()) {
            populateMap(properties,key, yamlInput.get(key));
        }
        return properties;
    }
    
    @SuppressWarnings("unchecked")
    private void populateMap(Map properties, String key, Object o) {
        if (o instanceof Map) {
            Map map = (Map)o;
            for (Object mapKey : map.keySet()) {
                populateEntry(properties, key,mapKey.toString(),map);
            }
        }else{
            if(o!=null)properties.put(key,o.toString());
        }
    }
    
    @SuppressWarnings("unchecked")
    private void populateEntry(Map properties, String key, String mapKey, Map map){
        String format = "%s" + super.getKeySeparator() + "%s";
        if (map.get(mapKey) instanceof Map) {
            populateMap(properties, String.format(format, key, mapKey), (Map) map.get(mapKey));
        } else {
            properties.put(String.format(format, key, mapKey), map.get(mapKey).toString());
        }   
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy