1 48 49 package org.jpublish.view.freemarker; 50 51 import java.io.*; 52 53 import com.anthonyeden.lib.config.Configuration; 54 import com.anthonyeden.lib.config.ConfigurationException; 55 import freemarker.template.Template; 56 import org.apache.commons.logging.Log; 57 import org.apache.commons.logging.LogFactory; 58 import org.jpublish.RequestContext; 59 import org.jpublish.page.Page; 60 import org.jpublish.view.AbstractViewRenderer; 61 import org.jpublish.view.ViewRenderException; 62 63 68 69 public class FreeMarkerViewRenderer extends AbstractViewRenderer { 70 71 private Log log = LogFactory.getLog(FreeMarkerViewRenderer.class); 72 private JPublishTemplateLoader templateLoader = null; 73 private freemarker.template.Configuration fmConfig = null; 74 75 78 79 public void init() { 80 fmConfig = new freemarker.template.Configuration(); 81 82 templateLoader = new JPublishTemplateLoader(); 83 templateLoader.setSiteContext(siteContext); 84 fmConfig.setTemplateLoader(templateLoader); 85 fmConfig.setLocalizedLookup(false); 86 } 87 88 97 98 public void render(RequestContext context, String path, Writer out) 99 throws IOException, ViewRenderException { 100 if (log.isDebugEnabled()) { 101 log.debug("render(" + path + ")"); 102 } 103 104 try { 105 Page page = context.getPage(); 106 Object viewContext = createViewContext(context, path); 107 Template template = fmConfig.getTemplate(path, page.getLocale(), 108 page.getEncoding()); 109 template.process(viewContext, out); 110 } catch (IOException e) { 111 throw e; 112 } catch (Exception e) { 113 throw new ViewRenderException(e); 114 } 115 } 116 117 126 127 public void render(RequestContext context, String path, OutputStream out) 128 throws IOException, ViewRenderException { 129 render(context, path, new OutputStreamWriter(out)); 130 } 131 132 145 146 public void render(RequestContext context, String path, Reader in, 147 Writer out) throws IOException, ViewRenderException { 148 if (log.isDebugEnabled()) { 149 log.debug("render(" + path + ")"); 150 } 151 152 try { 153 Page page = context.getPage(); 154 Object viewContext = createViewContext(context, path); 155 Template template = new Template(path, in); 156 template.process(viewContext, out); 157 } catch (IOException e) { 158 throw e; 159 } catch (Exception e) { 160 throw new ViewRenderException(e); 161 } 162 } 163 164 177 178 public void render(RequestContext context, String path, InputStream in, 179 OutputStream out) throws IOException, ViewRenderException { 180 render(context, path, new InputStreamReader(in), 181 new OutputStreamWriter(out)); 182 } 183 184 189 190 public void loadConfiguration(Configuration configuration) 191 throws ConfigurationException { 192 193 } 194 195 205 206 protected Object createViewContext(RequestContext context, String path) 207 throws ViewRenderException { 208 FreeMarkerViewContext viewContext = 209 new FreeMarkerViewContext(context); 210 return viewContext; 211 } 212 213 } 214 | Popular Tags |