1 13 package info.magnolia.cms.util; 14 15 import info.magnolia.context.MgnlContext; 16 17 import java.io.PrintWriter ; 18 import java.io.StringWriter ; 19 import java.io.Writer ; 20 import java.util.HashMap ; 21 import java.util.Map ; 22 23 import org.apache.commons.lang.StringUtils; 24 import org.slf4j.Logger; 25 import org.slf4j.LoggerFactory; 26 27 import freemarker.template.Configuration; 28 import freemarker.template.ObjectWrapper; 29 import freemarker.template.Template; 30 31 32 37 public class FreeMarkerUtil { 38 39 42 private static Configuration cfg; 43 44 private static Logger log = LoggerFactory.getLogger(FreeMarkerUtil.class); 45 46 static { 47 cfg = new Configuration(); 48 cfg.setObjectWrapper(ObjectWrapper.DEFAULT_WRAPPER); 49 cfg.setClassForTemplateLoading(FreeMarkerUtil.class, "/"); 50 cfg.setTagSyntax(Configuration.AUTO_DETECT_TAG_SYNTAX); 51 cfg.setDefaultEncoding("UTF8"); 52 } 53 54 60 public static String process(String name, Map data) { 61 Writer writer = new StringWriter (); 62 process(name, data, writer); 63 return writer.toString(); 64 } 65 66 71 public static String process(Object thisObj) { 72 return process(thisObj.getClass(), thisObj); 73 } 74 75 81 public static String process(Class klass, Object thisObj) { 82 return process(klass, thisObj, "html"); 83 } 84 85 92 public static String process(Class klass, Object thisObj, String ext) { 93 Map data = new HashMap (); 94 data.put("this", thisObj); 95 return process(klass, data, ext); 96 } 97 98 105 public static String process(Class klass, Map data, String ext) { 106 return process(createTemplateName(klass, ext), data); 107 } 108 109 115 public static void process(String name, Map data, Writer writer) { 116 try { 117 Template tmpl = cfg.getTemplate(name); 118 data.put("contextPath", MgnlContext.getContextPath()); 120 if (AlertUtil.isMessageSet()) { 121 data.put("message", AlertUtil.getMessage()); 122 } 123 tmpl.process(data, writer); 124 } 125 catch (Exception e) { 126 e.printStackTrace(new PrintWriter (writer)); 127 log.error("exception in template", e); 128 } 129 } 130 131 public static String createTemplateName(Class klass, String ext) { 132 return "/" + StringUtils.replace(klass.getName(), ".", "/") + "." + ext; 133 } 134 135 138 public static Configuration getDefaultConfiguration() { 139 return cfg; 140 } 141 142 } 143 | Popular Tags |