Interview Questions On Java,Java EE

Enter your email address:

Add to Technorati Favorites
Google PageRank Checker
Showing posts with label Velocity Framework. Show all posts
Showing posts with label Velocity Framework. Show all posts

Wednesday, September 23, 2009

Velocity With XML

In this post, a code snippet describing a basic integration of XML with Velocity framework. Please ensure all runtime jar files associated with Velocity and Xerces XML parser are in your build path.

The following files are part of this code snippet;

Here goes the Java code i.e.

import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import; import org.jdom.Document; import org.jdom.input.SAXBuilder; import; import; import; public class XMLVelocityExample { public XMLVelocityExample(String templateFile) { Writer writer = null; try { Velocity.init(); SAXBuilder builder; Document root = null; try { builder = new SAXBuilder("org.apache.xerces.parsers.SAXParser"); root ="book.xml"); } catch (Exception exception) { exception.printStackTrace(); } VelocityContext context = new VelocityContext(); context.put("root", root); Template template = Velocity.getTemplate(templateFile); writer = new BufferedWriter(new OutputStreamWriter(System.out)); template.merge(context, writer); } catch (Exception ex) { ex.printStackTrace(); } finally { if (writer != null) { try { writer.flush(); writer.close(); } catch (Exception ex) { ex.printStackTrace(); } } } } public static void main(String[] args) { XMLVelocityExample test = new XMLVelocityExample("xml.vm"); } }

xml.vm looks like:

#macro ( recursive $xml $indent ) #if( $xml.getChildren().size() > 0 ) $indent <$xml.getName()> #foreach ($child in $xml.getChildren() ) #recursive( $child "$indent " ) #end $indent </$xml.getName()> #else $indent <$xml.getName()> $indent $xml.getTextTrim() $indent </$xml.getName()> #end #end #set($i = " ") Here goes document tree with a recursive Velocity macro : #recursive( $root.getRootElement() $i ) Now accessing data directly : email : $root.getRootElement().getChild("properties").getChild("author").getChild("email").getText() last name : $root.getRootElement().getChild("properties").getChild("author").getChild("name").getChild("fullname").getText()

book.xml file looks like:

<?xml version="1.0" encoding="UTF-8"?> <document> <properties> <author> <email></email> <name> <lastname> Gavaskar </lastname> <first> Sunil </first> <fullname>Sunil Gavaskar</fullname> </name> </author> <title> Sunny Days </title> </properties> <body> Sunny within a body. </body> </document>

This is how output looks like:
Here goes document tree with a recursive Velocity macro : <document> <properties> <author> <email> </email> <name> <lastname> Gavaskar </lastname> <first> Sunil </first> <fullname> Sunil Gavaskar </fullname> </name> </author> <title> Sunny Days </title> </properties> <body> Sunny within a body. </body> </document> Now accessing data directly : email : last name : Sunil Gavaskar
Continue reading...

Thursday, September 17, 2009

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:

Template file:

Here goes:

import; import java.util.HashMap; import java.util.Properties; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import; 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", " Bookstore"); store.put("url", "http://amazon.comm"); context.put("store", store); return context; } }

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", ""); emailer.sendReceipt(new Order(customer, lineItems)); } }

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; = 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); } }

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); 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($ Visit us again at ${store.url}! #set ($subject="${} receipt")

This is how the result looks like:

To: Subject: 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!
Continue reading...

Sunday, November 18, 2007

Velocity Framework

What is Velocity Framework?
Velocity is a Java based template engine.It permits anyone to use a simple yet powerful template language to reference objects defined in Java code.Velocity is inspired from 'WebMacro' , an alternative to JSP,PHP and ASP(

Where can Velocity be used?

Velocity framework can be used in following areas:
- Web apps, dynamic HTML pages are created and processed with VelocityViewServlet or number of frameworks that support Velocity
- Source code generation
- Automatic e-mails
- XML transformation, provides an ant task called Anakia which reads an XML file and makes it available to a Velocity template.

What are the features of Velocity?
Velocity framework has following features:
- Velocity is MVC based
- It segregates HTML template code from Java code
- It emphasizes on role based web app development
- Velocity offers better maintainable web applications

How Velocity works?
When using Velocity in an application program or in a servlet (or anywhere, actually), you will generally do the following :
- Initialize Velocity. This applies to both usage patterns for Velocity, the Singleton as well as the 'separate runtime instance', and you only do this once.
- Create a Context object.
- Add your data objects to the Context.
- Choose a template.
- 'Merge' the template and your data to produce the output.

An Emailing template creation using Velocity framework
Velocity With XML
Continue reading...

Interview Questions On Java,Java EE Copyright © 2017. Reads: best tracker