1 17 package org.alfresco.repo.template; 18 19 import java.io.IOException ; 20 import java.io.Writer ; 21 22 import org.alfresco.service.cmr.repository.ContentService; 23 import org.alfresco.service.cmr.repository.NodeService; 24 import org.alfresco.service.cmr.repository.TemplateException; 25 import org.alfresco.service.cmr.repository.TemplateProcessor; 26 import org.apache.log4j.Logger; 27 28 import freemarker.cache.MruCacheStorage; 29 import freemarker.template.Configuration; 30 import freemarker.template.Template; 31 import freemarker.template.TemplateExceptionHandler; 32 33 38 public class FreeMarkerProcessor implements TemplateProcessor 39 { 40 private final static String MSG_ERROR_NO_TEMPLATE = "error_no_template"; 41 private final static String MSG_ERROR_TEMPLATE_FAIL = "error_template_fail"; 42 private final static String MSG_ERROR_TEMPLATE_IO = "error_template_io"; 43 44 private static Logger logger = Logger.getLogger(FreeMarkerProcessor.class); 45 46 47 private Configuration config = null; 48 49 50 private NodeService nodeService; 51 52 53 private ContentService contentService; 54 55 60 public void setNodeService(NodeService nodeService) 61 { 62 this.nodeService = nodeService; 63 } 64 65 70 public void setContentService(ContentService contentService) 71 { 72 this.contentService = contentService; 73 } 74 75 78 private Configuration getConfig() 79 { 80 if (this.config == null) 81 { 82 Configuration config = new Configuration(); 83 84 config.setCacheStorage(new MruCacheStorage(20, 0)); 86 87 config.setTemplateLoader(new ClassPathRepoTemplateLoader(nodeService, contentService)); 89 90 config.setObjectWrapper(new QNameAwareObjectWrapper()); 92 93 config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); 95 96 this.config = config; 97 } 98 return this.config; 99 } 100 101 104 public void process(String template, Object model, Writer out) 105 { 106 if (template == null || template.length() == 0) 107 { 108 throw new IllegalArgumentException ("Template name is mandatory."); 109 } 110 if (model == null) 111 { 112 throw new IllegalArgumentException ("Model is mandatory."); 113 } 114 if (out == null) 115 { 116 throw new IllegalArgumentException ("Output Writer is mandatory."); 117 } 118 119 try 120 { 121 if (logger.isDebugEnabled()) 122 logger.debug("Executing template: " + template + " on model: " + model); 123 124 Template t = getConfig().getTemplate(template); 125 if (t != null) 126 { 127 try 128 { 129 t.process(model, out); 131 } 132 catch (Throwable err) 133 { 134 throw new TemplateException(MSG_ERROR_TEMPLATE_FAIL, new Object [] {err.getMessage()}, err); 135 } 136 } 137 else 138 { 139 throw new TemplateException(MSG_ERROR_NO_TEMPLATE, new Object [] {template}); 140 } 141 } 142 catch (IOException ioerr) 143 { 144 throw new TemplateException(MSG_ERROR_TEMPLATE_IO, new Object [] {template}, ioerr); 145 } 146 } 147 } 148 | Popular Tags |