EmailFormatter { public String formatSubject(String subjectTemplateLocation, Event event) { VelocityContext velocityContext = new VelocityContext(); velocityContext.put("event", getEventAsData(event)); Template subjectTemplate; if (event.getProperty("subject.template.location") != null) { subjectTemplate = velocityEngine.getTemplate(event.getProperty("subject.template.location").toString()); } else if (subjectTemplateLocation != null) { subjectTemplate = velocityEngine.getTemplate(subjectTemplateLocation); } else { subjectTemplate = velocityEngine.getTemplate("defaultSubjectTemplate.vm"); } StringWriter writer = new StringWriter(); subjectTemplate.merge(velocityContext, writer); return writer.toString(); } EmailFormatter(); String formatSubject(String subjectTemplateLocation, Event event); String formatBody(String bodyTemplateLocation, Event event);  }
@Test public void testSubjectDefaultTemplate() { String subject = formatter.formatSubject(null, createEvent()); Assert.assertEquals("[SEVERE] Alert TestPattern", subject.trim()); Map<String, Object> data = new HashMap<>(); data.put("alertLevel", "CRITICAL"); data.put("alertAttribute", "recovery"); data.put("alertBackToNormal", true); data.put("alertPattern", "message:*"); Event event = new Event("foo", data); subject = formatter.formatSubject(null, event); Assert.assertEquals("Alert on message:* is back to normal", subject.trim()); }
@Test public void testSubjectExternalTemplate() { String subject = formatter.formatSubject(this.getClass().getClassLoader().getResource("subjectTemplate.vm").getPath(), createEvent()); Assert.assertEquals("Simple TestAttribute for SEVERE", subject); }
@Test public void testSubjectEventDefinedTemplate() { Map<String, Object> data = new HashMap<>(); data.put("subject.template.location", this.getClass().getClassLoader().getResource("propertySubjectTemplate.vm").getPath()); data.put("alertLevel", "SEVERE"); data.put("alertAttribute", "TestAttribute"); Event event = new Event("foo", data); String subject = formatter.formatSubject(null, event); Assert.assertEquals("Property defined TestAttribute with SEVERE", subject); }