001/*
002 * Copyright 2012-2018 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.boot.env;
018
019import java.io.IOException;
020import java.util.ArrayList;
021import java.util.Collections;
022import java.util.List;
023import java.util.Map;
024
025import org.springframework.core.env.PropertySource;
026import org.springframework.core.io.Resource;
027import org.springframework.util.ClassUtils;
028
029/**
030 * Strategy to load '.yml' (or '.yaml') files into a {@link PropertySource}.
031 *
032 * @author Dave Syer
033 * @author Phillip Webb
034 * @author Andy Wilkinson
035 */
036public class YamlPropertySourceLoader implements PropertySourceLoader {
037
038        @Override
039        public String[] getFileExtensions() {
040                return new String[] { "yml", "yaml" };
041        }
042
043        @Override
044        public List<PropertySource<?>> load(String name, Resource resource)
045                        throws IOException {
046                if (!ClassUtils.isPresent("org.yaml.snakeyaml.Yaml", null)) {
047                        throw new IllegalStateException("Attempted to load " + name
048                                        + " but snakeyaml was not found on the classpath");
049                }
050                List<Map<String, Object>> loaded = new OriginTrackedYamlLoader(resource).load();
051                if (loaded.isEmpty()) {
052                        return Collections.emptyList();
053                }
054                List<PropertySource<?>> propertySources = new ArrayList<>(loaded.size());
055                for (int i = 0; i < loaded.size(); i++) {
056                        String documentNumber = (loaded.size() != 1) ? " (document #" + i + ")" : "";
057                        propertySources.add(new OriginTrackedMapPropertySource(name + documentNumber,
058                                        loaded.get(i)));
059                }
060                return propertySources;
061        }
062
063}