TemplateUtil.java 2.1 KB
Newer Older
Kim Gyeongeun committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
package jp.agentec.sinaburocast.common.util.velocity;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Properties;

import jp.agentec.sinaburocast.common.exception.SystemException;
import jp.agentec.sinaburocast.common.util.PropertyUtil;

import org.apache.log4j.Logger;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

/**
 * Velocityのテンプレートエンジンを使って文字列を生成する。
 *
 * @author tsukada
 *
 */
public class TemplateUtil {
	private static final Logger LOGGER = Logger.getLogger(TemplateUtil.class);

	static {
		init();
	}

	private static void init() {
		Properties p = new Properties();
		//p.setProperty("file.resource.loader.path", SinaburoUtil.getClassesPath());
		
		//p.setProperty("file.resource.loader.path", "C:/workspace/em/src/main/webapp"+ServletContextUtil.getViewPrefix());
		p.setProperty("file.resource.loader.path", PropertyUtil.getProperty("TEMP_UTIL_ROOT_PATH"));
		
		
		
		
		p.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.Log4JLogSystem");
		p.setProperty("runtime.log.logsystem.log4j.logger", "velocity");
		p.setProperty("runtime.introspector.uberspect", "org.apache.velocity.tools.generic.introspection.PublicFieldUberspect");
		try {
			Velocity.init(p);
		} catch (Exception e) {
			LOGGER.fatal("TemplateUtil init error.", e);
		}
	}

	/**
	 * テンプレートから文字列を生成して返す
	 *
	 * @param filePath classes以下の相対パス
	 * @param context
	 * @return
	 * @throws Exception
	 */
	public static String parse(String filePath, VelocityContext context) throws SystemException {

		StringWriter sw = new StringWriter();
		try {
			Template template = Velocity.getTemplate(filePath, "UTF-8");
			template.merge(context,sw);
			sw.flush();
		} catch (Exception e) {
			LOGGER.fatal("template parse failed.", e);
			throw new SystemException(e.toString(), "E001");
		}
		finally {
			try {
				sw.close();
			} catch (IOException e) {
				LOGGER.error("StringWriter close failed.", e);
			}
		}
		return sw.toString();
	}
}