001/*
002 * Copyright 2012-2017 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.autoconfigure.mustache;
018
019import com.samskivert.mustache.DefaultCollector;
020import com.samskivert.mustache.Mustache.Collector;
021import com.samskivert.mustache.Mustache.VariableFetcher;
022
023import org.springframework.context.EnvironmentAware;
024import org.springframework.core.env.ConfigurableEnvironment;
025import org.springframework.core.env.Environment;
026
027/**
028 * Mustache {@link Collector} to expose properties from the Spring {@link Environment}.
029 *
030 * @author Dave Syer
031 * @author Madhura Bhave
032 * @since 1.2.2
033 */
034public class MustacheEnvironmentCollector extends DefaultCollector
035                implements EnvironmentAware {
036
037        private ConfigurableEnvironment environment;
038
039        private final VariableFetcher propertyFetcher = new PropertyVariableFetcher();
040
041        @Override
042        public void setEnvironment(Environment environment) {
043                this.environment = (ConfigurableEnvironment) environment;
044        }
045
046        @Override
047        public VariableFetcher createFetcher(Object ctx, String name) {
048                VariableFetcher fetcher = super.createFetcher(ctx, name);
049                if (fetcher != null) {
050                        return fetcher;
051                }
052                if (this.environment.containsProperty(name)) {
053                        return this.propertyFetcher;
054                }
055                return null;
056        }
057
058        private class PropertyVariableFetcher implements VariableFetcher {
059
060                @Override
061                public Object get(Object ctx, String name) throws Exception {
062                        return MustacheEnvironmentCollector.this.environment.getProperty(name);
063                }
064
065        }
066
067}