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:
/** * Singleton that initializes velocity (see Apache Velocity project) * * @author huseyin * */ public class VelocityInitializer { private boolean isInitialized = false; // SINGLETON public static VelocityInitializer getInstance(){ return SingletonHolder.instance; } // ---------------------------------------- INNER CLASS private static class SingletonHolder{ private static final VelocityInitializer instance = new VelocityInitializer(); } // ---------------------------------------- CONSTRUCTOR private VelocityInitializer(){ } // INITIALIZATION METHOD /** * Initialize Velocity (template engine library) */ public void initializeVelocity(){ if(!isInitialized){ // We configure Velocity to load template //files from the classpath Properties velocityProps = new Properties(); velocityProps.setProperty("resource.loader", "class"); //File logging disabled velocityProps.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); velocityProps.setProperty("runtime.log", ""); velocityProps.setProperty("directive.foreach.counter.initial.value", "0"); try{ Velocity.init(velocityProps); }catch(Exception e){ throw new RuntimeException("Internal error : impossible to initialize velocity.",e); } isInitialized = true; } } }
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:
public class ContextUtil implements ApplicationContextAware{ private static final Logger log = Logger.getLogger(ContextUtil.class); private static ApplicationContext context; @Override public void setApplicationContext(ApplicationContext context) throws BeansException{ ContextUtil.context = context; log.info("Spring initialized"); // Initiliaze Velocity VelocityInitializer.getInstance().initializeVelocity(); } public static ApplicationContext getContext(){ return context; } @SuppressWarnings("unchecked") public static<T> getBean(String name){ return (T) context.getBean(name); } }
To use the Velocity templates, we create a Singleton VelocityUtil allowing the merge of template and data:
public class VelocityUtil { private VelocityUtil(){} private static VelocityUtil instance; public static VelocityUtil getInstance(){ if(instance == null){ instance = new VelocityUtil(); } return instance; } public void render(String templatePath, Map<String, Object> context, Writer writer){ try{ VelocityContext velocityContext = new VelocityContext(context); Template template = null; try{ template = Velocity.getTemplate(templatePath); }catch(Exception e){ throw new RuntimeException("Internal error : impossible to load the Velocity template: "+ templatePath, e); } template.merge(velocityContext, writer); }catch(Throwable th) { th.printStackTrace(); } } public CharSequence render(String templatePath, Map<String, Object> context){ StringWriter writer = new StringWriter(1024); render(templatePath,context, writer); CharSequence ret = writer.getBuffer(); return ret; } }
So, for example, below a Template:
Hi, It's a test of Apache Velocity on JAVABLOG.FR website. #if ($myobj.code == "ID") The object ID is $!{myobj.objectID}. #else The object name is $!{myobj.objectName}. #end
…and a POJO class used for our example:
public class MyObject { private String objectName; private String objectID; private String code; private String label; // ----- CONSTRUCTOR public MyObject(){} // ----- SET / GETTERS public String getCode() { return code; } //... }
… and finally, the main class or JUNIT will be:
public class MainTest { private static final String TEMPLATE = "/src/com/ho/apache/velocity/test1/test1.vm"; public static void main(String[] args) { { final Map<String, Object> context = new HashMap<String, Object>(); MyObject aObject = new MyObject(); aObject.setObjectID("Object id"); aObject.setObjectName("Object name"); aObject.setCode("ID"); aObject.setLabel("Object created for Velocity tests"); // context.put("myobj", aObject); context.put("name", "ozveren"); context.put("firstname", "huseyin"); // CharSequence result = VelocityUtil.getInstance().render(TEMPLATE, context); String resultStr = result.toString(); System.out.println("Result :"); System.out.println(resultStr); } System.out.println("-------------------------------"); { final Map<String, Object> context = new HashMap<String, Object>(); MyObject aObject = new MyObject(); aObject.setObjectID("Object id"); aObject.setObjectName("Object name"); aObject.setCode("NAME"); aObject.setLabel("Object created for Velocity tests"); // context.put("myobj", aObject); context.put("name", "ozveren"); context.put("firstname", "huseyin"); // CharSequence result = VelocityUtil.getInstance().render(TEMPLATE, context); String resultStr = result.toString(); System.out.println("Result :"); System.out.println(resultStr); } } }
The outputs are:
Hi, It's a test of Apache Velocity on JAVABLOG.FR website. The object ID is Object id.
Result : Hi, It's a test of Apache Velocity on JAVABLOG.FR website. The object name is Object name.
That’s all!!!!
Huseyin OZVEREN
Source : velocity-test1.zip