001    /**
002     * Copyright (c) 2000-2010 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)
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    }