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.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(true);
61  
62          Velocity.evaluate(
63              velocityContext, unsyncStringWriter, VelocityUtil.class.getName(),
64              input);
65  
66          return unsyncStringWriter.toString();
67      }
68  
69  }