1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * The contents of this file are subject to the terms of the Liferay Enterprise
5    * Subscription License ("License"). You may not use this file except in
6    * compliance with the License. You can obtain a copy of the License by
7    * contacting Liferay, Inc. See the License for the specific language governing
8    * permissions and limitations under the License, including but not limited to
9    * distribution rights of the Software.
10   *
11   *
12   *
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();
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  }