package me.xhh.mail; import java.io.IOException; import java.io.StringWriter; import java.util.Locale; import java.util.Map; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; public class TemplateHandler { /** * For each template, there must be a file named<br/> * <code>template.toString() + ".ftl"</code><br/> * in the template folder. * * @see TemplateHandler#processTemplate(MailTemplate, Map) */ public enum MailTemplate { User_UserRegistration, Admin_UserRegistration, } /** Where the mail templates are placed. */ private static final String PATH_PREFIX = "/me/xhh/mail/"; private static final String TEMPLATE_FILE_SUFFIX = ".ftl"; private static Configuration fmConfig; static { fmConfig = new Configuration(); fmConfig.setClassForTemplateLoading(TemplateHandler.class, PATH_PREFIX); fmConfig.setEncoding(Locale.getDefault(), "UTF-8"); } /** * Process the email template. The template file to be used is:<br/> * "{@link #PATH_PREFIX}/str/{@link #TEMPLATE_FILE_SUFFIX}"<br/> * (where str is templateType.toString()) * * @param mailTemplate * the mail template to be used * @param valuesMap * the values to be used to replace the placeholder in the template file * @return the result of the template content parsed with the values * @throws IOException * @throws TemplateException */ public static String processTemplate(MailTemplate mailTemplate, Map<String, Object> valuesMap) throws IOException, TemplateException { Template template = fmConfig.getTemplate(mailTemplate.toString() + TEMPLATE_FILE_SUFFIX); StringWriter strWriter = new StringWriter(); template.process(valuesMap, strWriter); String resultStr = strWriter.toString(); return resultStr; } }