1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * This library is free software; you can redistribute it and/or modify it under
5    * the terms of the GNU Lesser General Public License as published by the Free
6    * Software Foundation; either version 2.1 of the License, or (at your option)
7    * any later version.
8    *
9    * This library is distributed in the hope that it will be useful, but WITHOUT
10   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11   * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
12   * details.
13   */
14  
15  package com.liferay.portal.freemarker;
16  
17  import com.liferay.portal.kernel.io.unsync.UnsyncStringWriter;
18  import com.liferay.portal.kernel.util.StringPool;
19  
20  import freemarker.cache.ClassTemplateLoader;
21  
22  import freemarker.template.Configuration;
23  import freemarker.template.DefaultObjectWrapper;
24  import freemarker.template.Template;
25  
26  import java.io.Writer;
27  
28  /**
29   * <a href="FreeMarkerUtil.java.html"><b><i>View Source</i></b></a>
30   *
31   * @author Tariq Dweik
32   * @author Brian Wing Shun Chan
33   */
34  public class FreeMarkerUtil {
35  
36      public static String process(String name, Object context)
37          throws Exception {
38  
39          UnsyncStringWriter unsyncStringWriter = new UnsyncStringWriter(true);
40  
41          process(name, context, unsyncStringWriter);
42  
43          return unsyncStringWriter.toString();
44      }
45  
46      public static void process(String name, Object context, Writer writer)
47          throws Exception {
48  
49          Template template = _getConfiguration().getTemplate(name);
50  
51          template.process(context, writer);
52      }
53  
54      private static Configuration _getConfiguration() {
55          if (_configuration != null) {
56              return _configuration;
57          }
58  
59          _configuration = new Configuration();
60  
61          _configuration.setObjectWrapper(new DefaultObjectWrapper());
62          _configuration.setTemplateLoader(
63              new ClassTemplateLoader(FreeMarkerUtil.class, StringPool.SLASH));
64  
65          return _configuration;
66      }
67  
68      private static Configuration _configuration;
69  
70  }