001    /**
002     * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
013     */
014    
015    package com.liferay.portal.velocity;
016    
017    import com.liferay.portal.kernel.io.unsync.UnsyncStringWriter;
018    import com.liferay.portal.kernel.util.Validator;
019    
020    import java.util.Iterator;
021    import java.util.Map;
022    
023    import org.apache.velocity.VelocityContext;
024    import org.apache.velocity.app.Velocity;
025    
026    /**
027     * @author Brian Wing Shun Chan
028     */
029    public class VelocityUtil {
030    
031            public static String evaluate(String input) throws Exception {
032                    return evaluate(input, null);
033            }
034    
035            public static String evaluate(String input, Map<String, Object> variables)
036                    throws Exception {
037    
038                    Velocity.init();
039    
040                    VelocityContext velocityContext = new VelocityContext();
041    
042                    if (variables != null) {
043                            Iterator<Map.Entry<String, Object>> itr =
044                                    variables.entrySet().iterator();
045    
046                            while (itr.hasNext()) {
047                                    Map.Entry<String, Object> entry = itr.next();
048    
049                                    String key = entry.getKey();
050                                    Object value = entry.getValue();
051    
052                                    if (Validator.isNotNull(key)) {
053                                            velocityContext.put(key, value);
054                                    }
055                            }
056                    }
057    
058                    UnsyncStringWriter unsyncStringWriter = new UnsyncStringWriter();
059    
060                    Velocity.evaluate(
061                            velocityContext, unsyncStringWriter, VelocityUtil.class.getName(),
062                            input);
063    
064                    return unsyncStringWriter.toString();
065            }
066    
067    }