001    /**
002     * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
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    }