com.surveypanel.view.FreemarkerManager.java Source code

Java tutorial

Introduction

Here is the source code for com.surveypanel.view.FreemarkerManager.java

Source

/*
* SurveyPanel
* Copyright (C) 2009 Serge Tan Panza
* All rights reserved.
* License: GNU/GPL License v3 , see LICENSE.txt
* SurveyPanel is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.txt for copyright notices and details.
* 
*/
package com.surveypanel.view;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.ui.freemarker.SpringTemplateLoader;

import com.surveypanel.form.Form;
import com.surveypanel.view.tags.Anchor;
import com.surveypanel.view.tags.I18nTag;
import com.surveypanel.view.tags.Input;

import freemarker.cache.MultiTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.SimpleHash;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

public class FreemarkerManager {

    protected static Logger log = Logger.getLogger(FreemarkerManager.class);

    private static Map<Long, Configuration> configs = new Hashtable<Long, Configuration>();
    private static String encoding;
    private static int mruMaxStrongSize;

    public static synchronized Configuration getConfiguration(Form form) throws TemplateException {
        Configuration config = configs.get(form.getSurveyId());
        if (config == null) {
            config = createConfiguration(form);
            configs.put(form.getSurveyId(), config);
        } else {
            if (form.isDevMode()) {
                config.clearTemplateCache();
                ((I18nTag) config.getSharedVariable("text")).setQuestionnaire(form.getQuestionnaire());
            }
        }
        return config;
    }

    protected static SimpleHash buildTemplateModel(Form form) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("form", form);
        map.put("vars", form.getVariables());
        map.put("fields", form.getFieldValues());
        map.put("questions", form.getCurrentQuestions());
        return new SimpleHash(map);
    }

    /**
     * Create the instance of the freemarker Configuration object.
     * <p/>
     * this implementation
     * <ul>
     * <li>obtains the default configuration from Configuration.getDefaultConfiguration()
     * <li>sets up template loading from a ClassTemplateLoader and a WebappTemplateLoader
     * <li>sets up the object wrapper to be the BeansWrapper
     * <li>loads settings from the classpath file /freemarker.properties
     * </ul>
     * @param form 
     *
     * @param servletContext
     */
    protected static Configuration createConfiguration(Form form) throws TemplateException {
        Configuration configuration = new Configuration();
        configuration.setTemplateLoader(new MultiTemplateLoader(new TemplateLoader[] { form.getTemplateLoader(),
                new SpringTemplateLoader(new DefaultResourceLoader(), "") }));
        configuration.setTemplateExceptionHandler(TemplateExceptionHandler.HTML_DEBUG_HANDLER);
        if (mruMaxStrongSize > 0) {
            configuration.setSetting(freemarker.template.Configuration.CACHE_STORAGE_KEY,
                    "strong:" + mruMaxStrongSize);
        }
        if (encoding != null) {
            configuration.setDefaultEncoding(encoding);
        }
        loadSettings(configuration);

        configuration.setWhitespaceStripping(true);
        configuration.setSharedVariable("a", new Anchor());
        configuration.setSharedVariable("input", new Input());
        configuration.setSharedVariable("text", new I18nTag(form.getQuestionnaire()));

        return configuration;
    }

    /**
     * Load the settings from the /freemarker.properties file on the classpath
     *
     * @see freemarker.template.Configuration#setSettings for the definition of valid settings
     */
    protected static void loadSettings(Configuration configuration) {
        InputStream in = null;
        try {
            in = FreemarkerManager.class.getResourceAsStream("freemarker.properties");
            if (in != null) {
                Properties p = new Properties();
                p.load(in);
                configuration.setSettings(p);
            }
        } catch (IOException e) {
            log.error("Error while loading freemarker settings from /freemarker.properties", e);
        } catch (TemplateException e) {
            log.error("Error while loading freemarker settings from /freemarker.properties", e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException io) {
                    log.warn("Unable to close input stream", io);
                }
            }
        }
    }

    /**
     * @param context
     * @param location
     * @return
     */
    public static FreemarkerTemplate getTemplate(Form form, String location) {
        return new FreemarkerTemplate(form, location);
    }

}