001    /**
002     * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
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)
035                    throws Exception {
036    
037                    UnsyncStringWriter unsyncStringWriter = new UnsyncStringWriter();
038    
039                    process(name, context, unsyncStringWriter);
040    
041                    return unsyncStringWriter.toString();
042            }
043    
044            public static void process(String name, Object context, Writer writer)
045                    throws Exception {
046    
047                    Template template = _getConfiguration().getTemplate(name);
048    
049                    template.process(context, writer);
050            }
051    
052            private static Configuration _getConfiguration() {
053                    if (_configuration != null) {
054                            return _configuration;
055                    }
056    
057                    _configuration = new Configuration();
058    
059                    _configuration.setObjectWrapper(new DefaultObjectWrapper());
060                    _configuration.setTemplateLoader(
061                            new ClassTemplateLoader(FreeMarkerUtil.class, StringPool.SLASH));
062    
063                    return _configuration;
064            }
065    
066            private static Configuration _configuration;
067    
068    }