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.velocity;
16  
17  import com.liferay.portal.kernel.io.unsync.UnsyncStringWriter;
18  import com.liferay.portal.kernel.util.Validator;
19  
20  import java.util.Iterator;
21  import java.util.Map;
22  
23  import org.apache.velocity.VelocityContext;
24  import org.apache.velocity.app.Velocity;
25  
26  /**
27   * <a href="VelocityUtil.java.html"><b><i>View Source</i></b></a>
28   *
29   * @author Brian Wing Shun Chan
30   */
31  public class VelocityUtil {
32  
33      public static String evaluate(String input) throws Exception {
34          return evaluate(input, null);
35      }
36  
37      public static String evaluate(String input, Map<String, Object> variables)
38          throws Exception {
39  
40          Velocity.init();
41  
42          VelocityContext velocityContext = new VelocityContext();
43  
44          if (variables != null) {
45              Iterator<Map.Entry<String, Object>> itr =
46                  variables.entrySet().iterator();
47  
48              while (itr.hasNext()) {
49                  Map.Entry<String, Object> entry = itr.next();
50  
51                  String key = entry.getKey();
52                  Object value = entry.getValue();
53  
54                  if (Validator.isNotNull(key)) {
55                      velocityContext.put(key, value);
56                  }
57              }
58          }
59  
60          UnsyncStringWriter unsyncStringWriter = new UnsyncStringWriter();
61  
62          Velocity.evaluate(
63              velocityContext, unsyncStringWriter, VelocityUtil.class.getName(),
64              input);
65  
66          return unsyncStringWriter.toString();
67      }
68  
69  }