001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.freemarker;
016    
017    import com.liferay.portal.kernel.io.unsync.UnsyncStringWriter;
018    import com.liferay.portal.kernel.util.StringPool;
019    
020    import freemarker.cache.ClassTemplateLoader;
021    
022    import freemarker.template.Configuration;
023    import freemarker.template.DefaultObjectWrapper;
024    import freemarker.template.Template;
025    
026    import java.io.Writer;
027    
028    /**
029     * @author Tariq Dweik
030     * @author Brian Wing Shun Chan
031     */
032    public class FreeMarkerUtil {
033    
034            public static String process(String name, Object context) throws Exception {
035                    UnsyncStringWriter unsyncStringWriter = new UnsyncStringWriter();
036    
037                    process(name, context, unsyncStringWriter);
038    
039                    return unsyncStringWriter.toString();
040            }
041    
042            public static void process(String name, Object context, Writer writer)
043                    throws Exception {
044    
045                    Template template = _getConfiguration().getTemplate(name);
046    
047                    template.process(context, writer);
048            }
049    
050            private static Configuration _getConfiguration() {
051                    if (_configuration != null) {
052                            return _configuration;
053                    }
054    
055                    _configuration = new Configuration();
056    
057                    _configuration.setObjectWrapper(new DefaultObjectWrapper());
058                    _configuration.setTemplateLoader(
059                            new ClassTemplateLoader(FreeMarkerUtil.class, StringPool.SLASH));
060                    _configuration.setTemplateUpdateDelay(Integer.MAX_VALUE);
061    
062                    return _configuration;
063            }
064    
065            private static Configuration _configuration;
066    
067    }