001/* 002 * (C) Copyright 2006-2007 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * dragos 018 * 019 * $Id$ 020 */ 021 022package org.nuxeo.ecm.platform.rendering.template; 023 024import java.io.IOException; 025 026import org.nuxeo.ecm.platform.ec.notification.email.templates.NuxeoTemplatesLoader; 027import org.nuxeo.ecm.platform.rendering.RenderingContext; 028import org.nuxeo.ecm.platform.rendering.RenderingEngine; 029import org.nuxeo.ecm.platform.rendering.RenderingException; 030import org.nuxeo.ecm.platform.rendering.RenderingResult; 031 032import freemarker.template.Configuration; 033import freemarker.template.TemplateException; 034 035/** 036 * Base class for RenderingEngine implementation that will work with freemarker. 037 * 038 * @author <a href="mailto:[email protected]">Dragos Mihalache</a> 039 */ 040public abstract class FreemarkerRenderingEngine implements RenderingEngine { 041 042 protected Configuration cfg; 043 044 /** 045 * TODO : It works like this but this default implementation should return just a <code>new Configuration()</code> 046 * There should be a class that extends this class and overrides this but that brokes it right now. TODO: write a 047 * clear TODO 048 */ 049 public Configuration createConfiguration() { 050 Configuration config = new Configuration(); 051 config.setTemplateLoader(new NuxeoTemplatesLoader()); 052 config.setDefaultEncoding("UTF-8"); 053 config.setClassicCompatible(true); 054 return config; 055 } 056 057 protected abstract FreemarkerRenderingJob createJob(RenderingContext ctx); 058 059 public RenderingResult process(RenderingContext ctx) throws RenderingException { 060 try { 061 if (cfg == null) { 062 cfg = createConfiguration(); 063 } 064 FreemarkerRenderingJob job = createJob(ctx); 065 cfg.getTemplate(job.getTemplate(), cfg.getDefaultEncoding()).process(ctx, job.getWriter()); 066 return job.getResult(); 067 } catch (IOException | TemplateException e) { 068 throw new RenderingException("Freemarker processing failed", e); 069 } 070 } 071 072}