TemplateUtils.java 2.7 KB
package com.cjs.cms.util.file;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import com.cjs.cms.util.net.RestException;

import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * FreeMarker模板工具类
 * 
 * @author trunks
 * @version $Id: TemplateUtils.java, v 0.1 2012-3-7 下午03:25:08 trunks Exp $
 */
public class TemplateUtils {

    private Map<String, Object> result = new HashMap<String, Object>();

    public TemplateUtils() {
    }

    /**
     * 添加要在模板显示的数据
     */
    public void put(String key, Object value) {
        result.put(key, value);
    }

    /**
     * 生成静态文件
     * 
     * @param tpl 模板文件名
     * @param target 生成文件目标路径
     */
    public void createHtml(String tpl, String target) {
        ConfigurationInstance cfg = ConfigurationInstance.getInstance();
        BufferedWriter writer = null;
        try {
            File file = new File(target.substring(0, target.lastIndexOf("/")));
            if (!file.exists()) {
                file.mkdirs();
            }
            Template template = cfg.getTemplate(tpl);
            writer = new BufferedWriter(new FileWriter(target));
            template.process(result, writer);
            writer.flush();
        } catch (IOException e) {
            throw new RestException("生成静态文件出错:" + e.getMessage());
        } catch (TemplateException e) {
            throw new RestException("生成静态文件出错:" + e.getMessage());
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                }
            }
        }
    }

    /**
     * 读取处理后的模板内容
     * 
     * @param tpl 模板名
     * @return 处理后的模板内容
     */
    public String readProcessedTemplate(String tpl) {
        StringWriter writer = new StringWriter();
        try {
            ConfigurationInstance cfg = ConfigurationInstance.getInstance();
            Template template = cfg.getTemplate(tpl);
            template.process(result, writer);
        } catch (IOException e) {
            throw new RestException("读取模板文件出错:" + e.getMessage());
        } catch (TemplateException e) {
            throw new RestException("读取模板文件出错:" + e.getMessage());
        }
        return writer.toString();
    }

    public Map<String, Object> getResult() {
        return result;
    }

    public void setResult(Map<String, Object> result) {
        this.result = result;
    }

}