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

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 map = (Map) object;
    for (Map.Entry entry : map.entrySet()) {
      Object value = entry.getValue();
      if (value instanceof Map) {
        value = asMap(value);
      }
      Object key = entry.getKey();
      if (key instanceof CharSequence) {
        result.put(key.toString(), value);
      } else {
        // It has to be a map key in this case
        result.put("[" + key.toString() + "]", value);
      }
    }
    return result;
  }

  private boolean process(Map map, MatchCallback callback) {
    Properties properties = new Properties();
    properties.putAll(getFlattenedMap(map));

    if (logger.isDebugEnabled()) {
      logger.debug("Merging document (no matchers set): " + map);
    }
    callback.process(properties, map);
    return true;
  }

  private Map getFlattenedMap(Map source) {
    Map result = new LinkedHashMap<>();
    buildFlattenedMap(result, source, null);
    return result;
  }

  private void buildFlattenedMap(Map result, Map source, String path) {
    for (Map.Entry entry : source.entrySet()) {
      String key = entry.getKey();
      if (!StringUtils.isBlank(path)) {
        if (key.startsWith("[")) {
          key = path + key;
        } else {
          key = path + '.' + key;
        }
      }
      Object value = entry.getValue();
      if (value instanceof String) {
        result.put(key, value);
      } else if (value instanceof Map) {
        // Need a compound key
        @SuppressWarnings("unchecked")
        Map map = (Map) value;
        buildFlattenedMap(result, map, key);
      } else if (value instanceof Collection) {
        // Need a compound key
        @SuppressWarnings("unchecked")
        Collection collection = (Collection) value;
        int count = 0;
        for (Object object : collection) {
          buildFlattenedMap(result, Collections.singletonMap("[" + (count++) + "]", object), key);
        }
      } else {
        result.put(key, (value != null ? value.toString() : ""));
      }
    }
  }

  private interface MatchCallback {
    void process(Properties properties, Map map);
  }

  private static class StrictMapAppenderConstructor extends Constructor {

    // Declared as public for use in subclasses
    StrictMapAppenderConstructor() {
      super();
    }

    @Override
    protected Map constructMapping(MappingNode node) {
      try {
        return super.constructMapping(node);
      } catch (IllegalStateException ex) {
        throw new ParserException("while parsing MappingNode", node.getStartMark(), ex.getMessage(), node.getEndMark());
      }
    }

    @Override
    protected Map createDefaultMap() {
      final Map delegate = super.createDefaultMap();
      return new AbstractMap() {
        @Override
        public Object put(Object key, Object value) {
          if (delegate.containsKey(key)) {
            throw new IllegalStateException("Duplicate key: " + key);
          }
          return delegate.put(key, value);
        }

        @Override
        public Set> entrySet() {
          return delegate.entrySet();
        }
      };
    }
  }

}