com.ctrip.framework.apollo.util.yaml.YamlParser Maven / Gradle / Ivy
The newest version!
package com.ctrip.framework.apollo.util.yaml;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;
import org.yaml.snakeyaml.nodes.MappingNode;
import org.yaml.snakeyaml.parser.ParserException;
import com.ctrip.framework.apollo.core.utils.StringUtils;
/**
* Transplanted from org.springframework.beans.factory.config.YamlProcessor since apollo can't depend on Spring directly
*
* @since 1.3.0
*/
public class YamlParser {
private static final Logger logger = LoggerFactory.getLogger(YamlParser.class);
/**
* Transform yaml content to properties
*/
public Properties yamlToProperties(String yamlContent) {
Yaml yaml = createYaml();
final Properties result = new Properties();
process(new MatchCallback() {
@Override
public void process(Properties properties, Map map) {
result.putAll(properties);
}
}, yaml, yamlContent);
return result;
}
/**
* Create the {@link Yaml} instance to use.
*/
private Yaml createYaml() {
return new Yaml(new StrictMapAppenderConstructor());
}
private boolean process(MatchCallback callback, Yaml yaml, String content) {
int count = 0;
if (logger.isDebugEnabled()) {
logger.debug("Loading from YAML: " + content);
}
for (Object object : yaml.loadAll(content)) {
if (object != null && process(asMap(object), callback)) {
count++;
}
}
if (logger.isDebugEnabled()) {
logger.debug("Loaded " + count + " document" + (count > 1 ? "s" : "") + " from YAML resource: " + content);
}
return (count > 0);
}
@SuppressWarnings("unchecked")
private Map asMap(Object object) {
// YAML can have numbers as keys
Map result = new LinkedHashMap<>();
if (!(object instanceof Map)) {
// A document can be a text literal
result.put("document", object);
return result;
}
Map