Created
July 7, 2011 15:49
-
-
Save bfuster/1069819 to your computer and use it in GitHub Desktop.
mail template
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.sample.utils.mail; | |
import java.io.BufferedReader; | |
import java.io.IOException; | |
import java.io.InputStreamReader; | |
import java.util.HashMap; | |
import java.util.Iterator; | |
import java.util.Map; | |
import java.util.regex.Matcher; | |
import java.util.regex.Pattern; | |
import org.apache.commons.io.IOUtils; | |
/** | |
* | |
* @author brunofuster | |
* | |
*/ | |
public class MailTemplateCreator { | |
private String template; | |
private Map<String, Object> map; | |
private MailTemplateCreator(MailTemplate mailTemplate, String language) throws IOException { | |
/* TODO FIXME cache file templates, do not read them all the time */ | |
String filepath = String.format("/mailTemplates/%1$s/%2$s", language, mailTemplate.file()); | |
BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(filepath))); | |
this.template = IOUtils.toString(reader); | |
this.map = new HashMap<String, Object>(); | |
} | |
public MailTemplateCreator put(String key, Object value) { | |
map.put(key, value); | |
return this; | |
} | |
public String parse() { | |
Iterator<String> keys = map.keySet().iterator(); | |
String newtemplate = new String(template.toString()); | |
while (keys.hasNext()) { | |
String key = keys.next(); | |
newtemplate = newtemplate.replaceAll(Pattern.quote("{" + key + "}"), | |
Matcher.quoteReplacement(map.get(key).toString())); | |
} | |
return newtemplate; | |
} | |
//factory method | |
public static MailTemplateCreator someTemplate(String language) { | |
return new MailTemplateCreator(MailTemplate.SOME_TEMPLATE, language); | |
} | |
private enum MailTemplate { | |
SOME_TEMPLATE("template1.mytpl"), | |
ANOTHER_TEMPLATE("template2.mytpl"); | |
private String file; | |
private MailTemplate(String file) { | |
this.file = file; | |
} | |
public String file() { return this.file; } | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment