JavaBlog.fr / Java.lu DEVELOPMENT,Java Java – Apache – Velocity: Simple example of Velocity 2/2

Java – Apache – Velocity: Simple example of Velocity 2/2

Hi,

It’s my first post of this year, after my first post concerning the library Apache Velocity Simple Presentation of Velocity, I would expose you an article about simple example of use of Velocity. A memo to use speedly Velocity.

First, our project needs the following jars to the classpath of your project:

  • velocity-1.7.jar
  • velocity-tools-2.0.jar

It is necessary to initialize Velocity, via the method Velocity.init(…) which allow to set the properties. To target this goal, we create a singleton class named VelocityInitializer:

01/**
02 * Singleton that initializes velocity (see Apache Velocity project)
03 *
04 * @author huseyin
05 *
06 */
07public class VelocityInitializer {
08     
09    private boolean isInitialized = false;
10     
11     
12    // SINGLETON
13    public static VelocityInitializer getInstance(){
14        return SingletonHolder.instance;
15    }
16     
17    // ---------------------------------------- INNER CLASS
18    private static class SingletonHolder{
19        private static final VelocityInitializer instance = new VelocityInitializer();
20    }
21     
22    // ---------------------------------------- CONSTRUCTOR
23    private VelocityInitializer(){ }
24 
25    // INITIALIZATION METHOD
26     
27    /**
28     * Initialize Velocity (template engine library)
29     */
30    public void initializeVelocity(){
31        if(!isInitialized){
32            // We configure Velocity to load template
33            //files from the classpath
34            Properties velocityProps = new Properties();
35            velocityProps.setProperty("resource.loader", "class");
36            //File logging disabled
37            velocityProps.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
38            velocityProps.setProperty("runtime.log", "");
39            velocityProps.setProperty("directive.foreach.counter.initial.value", "0");
40            try{
41                Velocity.init(velocityProps);
42            }catch(Exception e){
43                throw new RuntimeException("Internal error : impossible to initialize velocity.",e);
44            }
45            isInitialized = true;
46        }
47    }
48}

Then, this initialization of Velocity must be done – in a Spring-based application – after the loading of Spring context. For example, we could implement the ApplicationContextAware interface:

01public class ContextUtil implements ApplicationContextAware{
02 
03    private static final Logger log = Logger.getLogger(ContextUtil.class);
04     
05    private static ApplicationContext context;
06     
07    @Override
08    public void setApplicationContext(ApplicationContext context) throws BeansException{
09        ContextUtil.context = context;
10        log.info("Spring initialized");
11         
12        // Initiliaze Velocity
13        VelocityInitializer.getInstance().initializeVelocity();
14    }
15     
16    public static ApplicationContext getContext(){
17        return context;
18    }
19     
20    @SuppressWarnings("unchecked")
21    public static<T> getBean(String name){
22        return (T) context.getBean(name);
23    }  
24}

To use the Velocity templates, we create a Singleton VelocityUtil allowing the merge of template and data:

01public class VelocityUtil {
02     
03    private VelocityUtil(){}
04     
05    private static VelocityUtil instance;
06     
07     
08    public static VelocityUtil getInstance(){
09        if(instance == null){
10            instance = new VelocityUtil();
11        }
12        return instance;
13    }
14     
15     
16    public void render(String templatePath, Map<String, Object> context, Writer writer){
17        try{
18            VelocityContext velocityContext = new VelocityContext(context);
19            Template template = null;
20            try{
21                template = Velocity.getTemplate(templatePath);
22            }catch(Exception e){
23                throw new RuntimeException("Internal error : impossible to load the Velocity template: "+ templatePath, e);
24            }
25            template.merge(velocityContext, writer);
26        }catch(Throwable th) {
27            th.printStackTrace();
28        }
29    }
30     
31     
32    public CharSequence render(String templatePath, Map<String, Object> context){
33        StringWriter writer = new StringWriter(1024);
34        render(templatePath,context, writer);
35        CharSequence ret = writer.getBuffer();
36        return ret;
37    }
38}

So, for example, below a Template:

1Hi,
2It's a test of Apache Velocity on JAVABLOG.FR website.
3#if ($myobj.code == "ID")
4The object ID is $!{myobj.objectID}.
5#else
6The object name is $!{myobj.objectName}.
7#end

…and a POJO class used for our example:

01public class MyObject {
02     
03    private String objectName;
04    private String objectID;
05    private String code;
06    private String label;
07     
08     
09    // ----- CONSTRUCTOR
10    public MyObject(){}
11 
12     
13    // ----- SET / GETTERS
14    public String getCode() {
15        return code;
16    }
17//...
18}

… and finally, the main class or JUNIT will be:

01public class MainTest {
02     
03    private static final String TEMPLATE = "/src/com/ho/apache/velocity/test1/test1.vm";
04     
05    public static void main(String[] args) {
06        {
07            final Map<String, Object> context = new HashMap<String, Object>();
08            MyObject aObject = new MyObject();
09            aObject.setObjectID("Object id");
10            aObject.setObjectName("Object name");
11            aObject.setCode("ID");
12            aObject.setLabel("Object created for Velocity tests");
13            //
14            context.put("myobj", aObject);
15            context.put("name", "ozveren");
16            context.put("firstname", "huseyin");
17            //
18            CharSequence result = VelocityUtil.getInstance().render(TEMPLATE, context);
19            String resultStr = result.toString();
20            System.out.println("Result :");
21            System.out.println(resultStr);
22        }
23        System.out.println("-------------------------------");
24        {
25            final Map<String, Object> context = new HashMap<String, Object>();
26            MyObject aObject = new MyObject();
27            aObject.setObjectID("Object id");
28            aObject.setObjectName("Object name");
29            aObject.setCode("NAME");
30            aObject.setLabel("Object created for Velocity tests");
31            //
32            context.put("myobj", aObject);
33            context.put("name", "ozveren");
34            context.put("firstname", "huseyin");
35            //
36            CharSequence result = VelocityUtil.getInstance().render(TEMPLATE, context);
37            String resultStr = result.toString();
38            System.out.println("Result :");
39            System.out.println(resultStr);
40        }  
41    }
42}

The outputs are:

1Hi,
2It's a test of Apache Velocity on JAVABLOG.FR website.
3The object ID is Object id.
1Result :
2Hi,
3It's a test of Apache Velocity on JAVABLOG.FR website.
4The object name is Object name.

That’s all!!!!

Huseyin OZVEREN

Source : velocity-test1.zip

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.

Related Post