001/*
002 * (C) Copyright 2006-2007 Nuxeo SAS (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     dragos
016 *
017 * $Id$
018 */
019
020package org.nuxeo.ecm.platform.rendering.template;
021
022import java.io.IOException;
023
024import org.nuxeo.ecm.platform.ec.notification.email.templates.NuxeoTemplatesLoader;
025import org.nuxeo.ecm.platform.rendering.RenderingContext;
026import org.nuxeo.ecm.platform.rendering.RenderingEngine;
027import org.nuxeo.ecm.platform.rendering.RenderingException;
028import org.nuxeo.ecm.platform.rendering.RenderingResult;
029
030import freemarker.template.Configuration;
031import freemarker.template.TemplateException;
032
033/**
034 * Base class for RenderingEngine implementation that will work with freemarker.
035 *
036 * @author <a href="mailto:dm@nuxeo.com">Dragos Mihalache</a>
037 */
038public abstract class FreemarkerRenderingEngine implements RenderingEngine {
039
040    protected Configuration cfg;
041
042    /**
043     * TODO : It works like this but this default implementation should return just a <code>new Configuration()</code>
044     * There should be a class that extends this class and overrides this but that brokes it right now. TODO: write a
045     * clear TODO
046     */
047    public Configuration createConfiguration() {
048        Configuration config = new Configuration();
049        config.setTemplateLoader(new NuxeoTemplatesLoader());
050        config.setDefaultEncoding("UTF-8");
051        config.setClassicCompatible(true);
052        return config;
053    }
054
055    protected abstract FreemarkerRenderingJob createJob(RenderingContext ctx);
056
057    public RenderingResult process(RenderingContext ctx) throws RenderingException {
058        try {
059            if (cfg == null) {
060                cfg = createConfiguration();
061            }
062            FreemarkerRenderingJob job = createJob(ctx);
063            cfg.getTemplate(job.getTemplate(), cfg.getDefaultEncoding()).process(ctx, job.getWriter());
064            return job.getResult();
065        } catch (IOException | TemplateException e) {
066            throw new RenderingException("Freemarker processing failed", e);
067        }
068    }
069
070}