Header Ads

  • Breaking Now

    EMailing Through Velocity Framework

    Velocity Framework helps in creating a pre-formatted template based email response mechanism. The code snippet in this post elaborates how one can use this feature from Velocity framework.

    While running this application, ensure you have all required Velocity framework related library classes/jars in you project build path.

    Here the code is distributed in following java files:

    1.EMailer.java
    2.EMailClient.java
    3.Customer.java
    4.Order.java

    Template file:
    5.email.vm

    Here goes:

    1. EMailer.java
    import java.io.StringWriter; import java.util.HashMap; import java.util.Properties; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader; public class Emailer { /** * Field description * * @since 1.0 */ VelocityEngine engine = new VelocityEngine(); /** * Constructor description. * * @throws Exception Description */ public Emailer() throws Exception { configure(engine); } /** * "Sends" (actually writes to System.out for demonstration purposes) a * receipt e-mail for the specified order. * * @param order Description */ public void sendReceipt(Order order) throws Exception { Template template = engine.getTemplate("email.vm"); VelocityContext context = createContext(); context.put("order", order); StringWriter writer = new StringWriter(); template.merge(context, writer); writer.close(); System.out.println("To: " + order.getCustomer().getEmail()); System.out.println("Subject: " + context.get("subject")); System.out.println(writer.getBuffer()); } /** * Configures the engine to use classpath to find templates * * @param engine Description */ private void configure(VelocityEngine engine) throws Exception { Properties props = new Properties(); props.setProperty(VelocityEngine.RESOURCE_LOADER, "classpath"); props.setProperty("classpath." + VelocityEngine.RESOURCE_LOADER + ".class", ClasspathResourceLoader.class.getName()); engine.init(props); } /** * Creates a Velocity context and adds a formatter tool * and store information. */ private VelocityContext createContext() { VelocityContext context = new VelocityContext(); context.put("formatter", new Formatter()); HashMap store = new HashMap(); store.put("name", "Amazon.com Bookstore"); store.put("url", "http://amazon.comm"); context.put("store", store); return context; } }



    2.EMailClient.java

    import java.util.ArrayList; public class EmailClient { /** * Example usage of Emailer functionality * * @param args Description */ public static void main(String[] args) throws Exception { Emailer emailer = new Emailer(); ArrayList lineItems = new ArrayList(); lineItems.add(new Item("Thinking in Java", 24.05f)); lineItems.add(new Item("Core Java Volume I", 34.30f)); Customer customer = new Customer("John", "Brown", "jb@gmail.com"); emailer.sendReceipt(new Order(customer, lineItems)); } }


    3.Customer.java

    public class Customer { private String firstName; private String lastName; private String email; /** * Constructor */ public Customer(String firstName, String lastName, String email) { this.firstName = firstName; this.lastName = lastName; this.email = email; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String getEmail() { return email; } public String getId() { return "" + firstName.charAt(0) + lastName.charAt(0); } }


    4. Order.java
    import java.util.Date; import java.util.Iterator; import java.util.List; public class Order { private Customer customer; private List lineItems; private String orderNumber; public Order(Customer customer, List lineItems) { this.customer = customer; this.lineItems = lineItems; orderNumber = customer.getId() + "-" + new Date().getTime(); } public Customer getCustomer() { return customer; } public List getLineItems() { return lineItems; } public String getOrderNumber() { return orderNumber; } public float total() { float total = 0; for (Iterator iterator = lineItems.iterator(); iterator.hasNext();) { Item item = (Item)iterator.next(); total += item.getCost(); } return total; } }


    5. email.vm file

    #set ($customer = ${order.customer}) #macro(currency $amount)${formatter.currency($amount)}#end #macro(pad $string)${formatter.pad($string, 30)}#end #macro(description $item)#pad($item.description)#end ${customer.firstName}, Thank you for your purchase. Your order number is ${order.orderNumber}. #pad("Description") Cost #foreach ($item in ${order.lineItems}) #description($item) #currency(${item.cost}) #end #pad("Total") #currency($order.total()) Visit us again at ${store.url}! #set ($subject="${store.name} receipt")


    This is how the result looks like:

    To: jb@gmail.com Subject: Amazon.com Bookstore receipt John, Thank you for your purchase. Your order number is JB-1253195547000. Description Cost Thinking in Java $24.05 Core Java Volume I $34.30 Total $58.35 Visit us again at http://amazon.comm!

    No comments

    Post Top Ad

    Post Bottom Ad