velocity 模板解析类

package com.renhenet.util;

import java.io.StringWriter;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context;

import com.renhenet.fw.ServiceLocator;
import com.renhenet.modules.cache.CacheNeedsRefreshException;
import com.renhenet.modules.cache.CacheService;
import com.renhenet.web.VMUtils;
import com.renhenet.web.WebConstants;
import com.spinn3r.log5j.Logger;

public class VMParser {

	private static final Logger logger = Logger.getLogger();
	private static final CacheService cacheService = (CacheService) ServiceLocator.getService("cacheService");

	private static VelocityEngine engine;
	
	private static VMUtils vMUtils = (VMUtils) ServiceLocator.getService("vMUtils");
	// 配置文件的文件名,配置文件位于$BASE/conf下
	private static final String DEFAULT_CONF_FILE = "/velocity.properties";

	static {
		engine = new VelocityEngine();
		try {
			String absolutePath = VMParser.class.getResource(DEFAULT_CONF_FILE).getFile();
			engine.init(absolutePath);
		} catch (Exception e) {
			logger.error("init velocity engine occur exception.", e);
		}
	}

	private static Template getTemplateByName(String templateName) {
		Template template = null;
		try {
			template = engine.getTemplate(templateName);
		} catch (Exception e) {
			logger.error("getTemplateByName occur exception.", e);
		}
		return template;
	}

	private static Template getTemplateFromCache(String templateName) {
		Template template = null;
		if(StringUtils.isNotEmpty(templateName)) {
			try {
				template = (Template) cacheService.getFromCache("tempate", templateName, 5 * 60);
			} catch (CacheNeedsRefreshException nre) {
				template = getTemplateByName(templateName);
				if (template != null) {
					cacheService.putInCache("tempate", templateName, template);
				}
			}
		}
		return template;
	}

	public static String substitute(String templateName) {
		return substitute(templateName, new VelocityContext());
	}

	public static String substitute(String templateName, Context context) {
		// 设置一些公用的变量
		putCommonVelocityContext(context);
		if (StringUtils.isEmpty(templateName)) {
			return StringUtils.EMPTY;
		}
		Template tmplate = getTemplateFromCache(templateName);
		if (tmplate != null) {
			StringWriter writer = new StringWriter();
			try {
				tmplate.merge(context, writer);
				String restring = writer.toString();
				writer.flush();
				writer.close();
				return restring;
			} catch (Exception ex) {
				logger.error("merge velocity with template occur exception.", ex);
			}
		}
		return StringUtils.EMPTY;
	}

	private static void putCommonVelocityContext(Context context) {
		context.put("vMUtils", vMUtils);
	}
}


你可能感兴趣的:(velocity)