1 4 package com.opensymphony.webwork.portlet.sitemesh; 5 6 import com.opensymphony.webwork.portlet.velocity.VelocityManager; 7 import org.apache.commons.logging.Log; 8 import org.apache.commons.logging.LogFactory; 9 import org.apache.velocity.Template; 10 import org.apache.velocity.VelocityContext; 11 import org.apache.velocity.app.VelocityEngine; 12 import org.apache.velocity.context.Context; 13 14 import java.io.StringWriter ; 15 import java.util.Map ; 16 17 21 public class VelocityUtils { 22 23 private static final Log log = LogFactory.getLog(com.opensymphony.webwork.portlet.sitemesh.VelocityUtils.class); 24 25 public VelocityUtils() { 26 } 27 28 public static String getRenderedTemplate(String templateName, Map contextMap) { 29 return getRenderedTemplate(templateName, ((Context) (new VelocityContext(contextMap)))); 30 } 31 32 public static String getRenderedTemplate(String templateName, Context context) { 33 try { 34 return getRenderedTemplateWithoutSwallowingErrors(templateName, context); 35 } catch (Exception e) { 36 log.error("Error occurred rendering template: " + templateName, e); 37 return ""; 38 } 39 } 40 41 public static String getRenderedTemplateWithoutSwallowingErrors(String templateName, Context context) throws Exception { 42 Template template = getTemplate(templateName); 43 StringWriter tempWriter = new StringWriter (); 44 template.merge(context, tempWriter); 45 return tempWriter.toString(); 46 } 47 48 public static Template getTemplate(String templateName) throws Exception { 49 VelocityEngine velocityEngine = VelocityManager.getInstance().getVelocityEngine(); 50 51 58 String encoding = "UTF-8"; 59 60 Template template = velocityEngine.getTemplate(templateName, encoding); 61 return template; 62 } 63 64 public static String getRenderedContent(String templateContent, Map contextMap) { 65 try { 66 StringWriter tempWriter = new StringWriter (); 67 VelocityContext context = new VelocityContext(contextMap); 68 69 VelocityManager.getInstance().getVelocityEngine().evaluate(context, tempWriter, "getRenderedContent", templateContent); 70 return tempWriter.toString(); 71 } catch (Exception e) { 72 log.error("Error occurred rendering template content", e); 73 throw new InfrastructureException("Error occurred rendering template content", e); 74 } 75 } 76 77 } | Popular Tags |