package com.huawei.it.citools.utils;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;

import org.apache.log4j.Logger;

import com.huawei.it.citools.commons.ApplicationException;
import com.huawei.it.citools.commons.CiConstants;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
 
public class FreeMarkerUtils
{

private static Logger LOGGER = Logger.getLogger (FreeMarkerUtils.class);

private static FreeMarkerUtils freemarkerUtils = new FreeMarkerUtils();

private Configuration configuration;

private FreeMarkerUtils()
    {
        try
        {
            File currFile = new File ("");
            String templatePath = currFile.getCanonicalPath() + "/template/";

LOGGER.info ("freemarker template file path : " + templatePath);

configuration = new Configuration();
            File path = new File (templatePath);
            configuration.setDirectoryForTemplateLoading (path);
            configuration.setDefaultEncoding ("UTF-8");
        }
        catch (Exception e)
        {
            LOGGER.info ("freemarker configuration fail....." + e);

throw new ApplicationException ("freemarker configuration fail.....", e);
        }
    }
 
    public String process (Map rootMap, String ftlName) throws IOException, TemplateException
    {
        StringWriter sw = new StringWriter();
        try {
            Template template = configuration.getTemplate (ftlName);
            template.process (rootMap, sw);
            String result = sw.toString();
            return result;
        } finally {
            sw.close();
        }
    }
    public static FreeMarkerUtils newInstance()
    {
        return freemarkerUtils;
    }
}

05-11 22:19