1 package club.wpia.gigi.output.template;
3 import java.io.IOException;
4 import java.io.PrintWriter;
6 import java.io.StringReader;
7 import java.io.StringWriter;
9 import java.util.Collection;
12 import club.wpia.gigi.email.SendMail;
13 import club.wpia.gigi.localisation.Language;
14 import club.wpia.gigi.util.ServerConstants;
16 public class MailTemplate extends Template {
18 private static final Template FOOTER = new Template(MailTemplate.class.getResource("MailFooter.templ"));
20 public static final String SUBJECT_TAG = "[" + ServerConstants.getAppName() + "] ";
22 private TemplateBlock subjectBlock;
24 public MailTemplate(URL u) {
28 public MailTemplate(Reader r) {
33 protected ParseResult parse(Reader r) throws IOException {
34 StringBuilder strb = new StringBuilder();
37 while ((c = r.read()) > 0) {
46 strb.append((char) c);
48 String[] lines = strb.toString().split("\n");
49 for (int i = 0; i < lines.length; i++) {
50 String[] lineParts = lines[i].split(": ", 2);
51 if (lineParts.length != 2) {
52 throw new IOException("Mail template header malformed.");
54 if (lineParts[0].equals("Subject")) {
55 subjectBlock = parseContent(new StringReader(lineParts[1])).getBlock(null);
58 if (subjectBlock == null) {
59 throw new IOException("Mail template without subject line.");
61 return parseContent(r);
64 public void sendMail(Language l, Map<String, Object> vars, String to) throws IOException {
66 vars.put(Outputable.OUT_KEY_PLAIN, true);
67 vars.put("appName", ServerConstants.getAppName());
69 String body = runTemplate(this, l, vars);
70 body += runTemplate(FOOTER, l, vars);
71 String subject = runTemplate(subjectBlock, l, vars);
73 SendMail.getInstance().sendMail(to, SUBJECT_TAG + subject, body, null, null, null, null, false);
76 private static String runTemplate(Outputable toRun, Language l, Map<String, Object> vars) {
77 StringWriter sw = new StringWriter();
78 PrintWriter pw = new PrintWriter(sw);
79 toRun.output(pw, l, vars);
85 public void addTranslations(Collection<String> s) {
86 subjectBlock.addTranslations(s);
87 super.addTranslations(s);