001/*
002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     bstefanescu
011 *
012 * $Id$
013 */
014
015package org.nuxeo.ecm.platform.rendering.wiki.extensions;
016
017import java.io.IOException;
018import java.io.StringReader;
019import java.io.StringWriter;
020import java.io.Writer;
021
022import org.nuxeo.ecm.platform.rendering.wiki.WikiMacro;
023import org.nuxeo.ecm.platform.rendering.wiki.WikiSerializerHandler;
024import org.wikimodel.wem.WikiParameters;
025
026import freemarker.core.Environment;
027import freemarker.template.Template;
028import freemarker.template.TemplateException;
029
030/**
031 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
032 */
033public class FreemarkerMacro implements WikiMacro {
034
035    public String getName() {
036        return "freemarker";
037    }
038
039    public void eval(WikiParameters params, String content, WikiSerializerHandler serializer) throws IOException,
040            TemplateException {
041        Environment env = serializer.getEnvironment();
042        if (env != null) {
043            Template tpl = new Template("inline", new StringReader(content), env.getConfiguration(),
044                    env.getTemplate().getEncoding());
045            Writer oldw = env.getOut();
046            Writer neww = new StringWriter();
047            try {
048                env.setOut(neww);
049                env.include(tpl);
050            } finally {
051                env.setOut(oldw);
052            }
053            serializer.getWriter().print(neww.toString());
054        }
055    }
056
057    public void evalInline(WikiParameters params, String content, WikiSerializerHandler serializer) throws IOException,
058            TemplateException {
059        eval(params, content, serializer);
060    }
061
062}