001/*
002 * Copyright 2012-2015 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 java.io.InputStreamReader;
020import java.io.Reader;
021
022import com.samskivert.mustache.Mustache;
023import com.samskivert.mustache.Mustache.TemplateLoader;
024
025import org.springframework.context.ResourceLoaderAware;
026import org.springframework.core.io.DefaultResourceLoader;
027import org.springframework.core.io.Resource;
028import org.springframework.core.io.ResourceLoader;
029
030/**
031 * Mustache TemplateLoader implementation that uses a prefix, suffix and the Spring
032 * Resource abstraction to load a template from a file, classpath, URL etc. A
033 * TemplateLoader is needed in the Compiler when you want to render partials (i.e.
034 * tiles-like features).
035 *
036 * @author Dave Syer
037 * @since 1.2.2
038 * @see Mustache
039 * @see Resource
040 */
041public class MustacheResourceTemplateLoader
042                implements TemplateLoader, ResourceLoaderAware {
043
044        private String prefix = "";
045
046        private String suffix = "";
047
048        private String charSet = "UTF-8";
049
050        private ResourceLoader resourceLoader = new DefaultResourceLoader();
051
052        public MustacheResourceTemplateLoader() {
053        }
054
055        public MustacheResourceTemplateLoader(String prefix, String suffix) {
056                super();
057                this.prefix = prefix;
058                this.suffix = suffix;
059        }
060
061        /**
062         * Set the charset.
063         * @param charSet the charset
064         */
065        public void setCharset(String charSet) {
066                this.charSet = charSet;
067        }
068
069        /**
070         * Set the resource loader.
071         * @param resourceLoader the resource loader
072         */
073        @Override
074        public void setResourceLoader(ResourceLoader resourceLoader) {
075                this.resourceLoader = resourceLoader;
076        }
077
078        @Override
079        public Reader getTemplate(String name) throws Exception {
080                return new InputStreamReader(this.resourceLoader
081                                .getResource(this.prefix + name + this.suffix).getInputStream(),
082                                this.charSet);
083        }
084
085}