1 import java.io.StringWriter; 2 import java.util.HashMap; 3 import java.util.Properties; 4 5 import org.apache.velocity.Template; 6 import org.apache.velocity.VelocityContext; 7 import org.apache.velocity.app.VelocityEngine; 8 import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader; 9 10 11 public class Emailer 12 { 13 /** 14 * Field description 15 * 16 * @since 1.0 17 */ 18 VelocityEngine engine = new VelocityEngine(); 19 20 /** 21 * Constructor description. 22 * 23 * @throws Exception Description 24 */ 25 public Emailer() throws Exception 26 { 27 configure(engine); 28 } 29 30 /** 31 * "Sends" (actually writes to System.out for demonstration purposes) a 32 * receipt e-mail for the specified order. 33 * 34 * @param order Description 35 */ 36 public void sendReceipt(Order order) throws Exception 37 { 38 Template template = engine.getTemplate("email.vm"); 39 VelocityContext context = createContext(); 40 context.put("order", order); 41 42 StringWriter writer = new StringWriter(); 43 template.merge(context, writer); 44 writer.close(); 45 System.out.println("To: " + order.getCustomer().getEmail()); 46 System.out.println("Subject: " + context.get("subject")); 47 System.out.println(writer.getBuffer()); 48 } 49 50 /** 51 * Configures the engine to use classpath to find templates 52 * 53 * @param engine Description 54 */ 55 private void configure(VelocityEngine engine) throws Exception 56 { 57 Properties props = new Properties(); 58 props.setProperty(VelocityEngine.RESOURCE_LOADER, "classpath"); 59 props.setProperty("classpath." + VelocityEngine.RESOURCE_LOADER + 60 ".class", 61 ClasspathResourceLoader.class.getName()); 62 engine.init(props); 63 } 64 /** 65 * Creates a Velocity context and adds a formatter tool 66 * and store information. 67 */ 68 private VelocityContext createContext() { 69 VelocityContext context = new VelocityContext(); 70 context.put("formatter", new Formatter()); 71 72 HashMap store = new HashMap(); 73 store.put("name", "Amazon.com Bookstore"); 74 store.put("url", "http://amazon.comm"); 75 76 context.put("store", store); 77 return context; 78 } 79 } 80