1 24 package org.ofbiz.base.util.template; 25 26 import java.util.Map ; 27 import java.util.HashMap ; 28 import java.util.Set ; 29 import java.util.Iterator ; 30 import java.net.URL ; 31 import java.net.URLConnection ; 32 import java.io.InputStream ; 33 import java.io.InputStreamReader ; 34 35 import org.ofbiz.base.util.URLConnector; 36 import org.ofbiz.base.util.cache.UtilCache; 37 import org.ofbiz.base.location.FlexibleLocation; 38 import java.io.IOException ; 39 import java.io.Writer ; 40 41 import freemarker.ext.beans.BeansWrapper; 42 import freemarker.template.SimpleHash; 43 import freemarker.template.Template; 44 import freemarker.template.TemplateException; 45 import freemarker.template.WrappingTemplateModel; 46 import freemarker.template.Configuration; 47 48 49 60 public final class FtlTransform { 61 62 public static final String module = FtlTransform.class.getName(); 63 public static UtilCache ftlTemplatesCache = new UtilCache("FtlTemplates", 0, 0); 64 private static Configuration cfg = new Configuration(); 65 private static Map templateRoot = new HashMap (); 66 67 static { 68 69 WrappingTemplateModel.setDefaultObjectWrapper(BeansWrapper.getDefaultInstance()); 70 try { 71 cfg.setObjectWrapper(BeansWrapper.getDefaultInstance()); 72 cfg.setSetting("datetime_format", "yyyy-MM-dd HH:mm:ss.SSS"); 73 } catch (TemplateException e) { 74 throw new RuntimeException ("Freemarker TemplateException", e.getCause()); 75 } 76 prepOfbizRoot(templateRoot); 77 } 78 79 public FtlTransform() { 80 } 81 82 public static void transform(Writer writer, String path, Map params) 83 throws TemplateException, IOException { 84 85 Template template = (Template)ftlTemplatesCache.get(path); 86 if (template == null) { 87 template = getTemplate(path); 88 if (template != null) { 89 ftlTemplatesCache.put(path, template); 90 } 91 } 92 93 SimpleHash templateContext = new SimpleHash(); 94 templateContext.putAll(templateRoot); 95 if (params != null) { 96 Set entrySet = params.entrySet(); 97 Iterator iter = entrySet.iterator(); 98 while (iter.hasNext()) { 99 Map.Entry entry = (Map.Entry )iter.next(); 100 String key = (String )entry.getKey(); 101 Object val = entry.getValue(); 102 if (val != null) { 103 templateContext.put(key, val); 104 } 105 } 106 } 107 template.process(templateContext, writer); 108 return; 109 } 110 111 private static Template getTemplate( String inputUrl) throws IOException { 112 113 URL url = FlexibleLocation.resolveLocation(inputUrl); 114 URLConnection conn = URLConnector.openConnection(url); 115 InputStream in = conn.getInputStream(); 116 InputStreamReader rdr = new InputStreamReader (in); 117 Template template = new Template(inputUrl, rdr, cfg); 118 template.setObjectWrapper(BeansWrapper.getDefaultInstance()); 119 return template; 120 } 121 122 public static void prepOfbizRoot(Map root) { 123 FreeMarkerWorker.addAllOfbizTransforms(root); 124 } 125 } 126 | Popular Tags |