How to generate code with Apache Velocity | Opensource.com

How to generate code with Apache Velocity

Get started with Velocity, an open source, Java-based template engine and code generator that converts templates into source code.

Binary code on a computer screen
Image credits : 

Public Domain via LibreShot

x

Subscribe now

Get the highlights in your inbox every week.

Apache Velocity is an open source, Java-based template engine and code generator that converts templates into source code. Because it is implemented in Java, it is capable of interpreting varied templates and generating code for any language (web, service, SQL, scripts, etc.), although it seems to be oriented mostly toward web development.

Velocity's structure

Velocity's structure is comprised of an engine and tools. Its core is the Velocity Engine, which uses the defined template, interprets the template language, and generates the code.

Templates are defined with Velocity Template Language (VTL), a simple language with effective directives. VTL statements are directives or variables, and variables can be standalone or class methods.

Examples of VTL expressions include:

package ${packagename};
Inserts a package statement in Java where the package name is defined as packagename
public ${classname} implements Serializable {
Adds a class with name classname
#foreach( $property in $properties )
 public ${property.fieldType} get${property.getField()}() {
     return this.${property.fieldName};
 }
#end
Creates getter methods for all defined properties

Velocity tools are collections of basic user-friendly capabilities. There are GenericTools, a "set of classes that provide basic infrastructure for using tools in standard Java SE Velocity projects, as well as a set of tools for use in generic Velocity templates." They include DateTool, MathTool, NumberTool, SortTool, and XmlTool. There are also VelocityView tools, which include "all of the GenericTools and adds infrastructure and specialized tools for using Velocity in the view layer of web applications (Java EE projects)." VelocityView tools include BrowserTool, CookieTool, and ImportTool

Velocity advantages and disadvantages

Velocity is easy to use and has the capability to generate any language. On the downside, there is a learning curve to understand and apply its template language. Velocity is morphology- and ontology-free. It has no knowledge of the design capability of the module it generates. As a practical example, Velocity may use a template for a controller (e.g., Model-View-Controller or an architecture style) and generate the code, but it has no awareness of the concept of a controller. This is both an advantage and disadvantage, with a generator being simple and easy to use but with no awareness of the design's aptitude.

Using Velocity

Velocity's Java library is available on the Maven repository. To use the .jar file, define Velocity's latest version in your Maven build config. (Velocity 1.7 is the latest version, as of this writing.) For example, enter the following in your Maven Project Object Model (POM):

<dependency>
        <groupId>org.apache.velocity</groupId>
        <artifactId>velocity</artifactId>
        <version>1.7</version>
</dependency>

Java Hello World example

To generate code, you need two things:

  1. The Velocity template to be used for generation, e.g., java_example.vm:
    public class ${className} {

        public static void main(String[] args) {
            System.out.println("${message}");
        }

    }
  1. The Velocity generator that uses the template to generate code, e.g., VelocityStartGenerator.java:
    public class VelocityStartGenerator {
     
        static String inputTemplate = "java_example.vm";
        static String className = "VelocityExample";
        static String message = "Hello World!";
        static String outputFile = className + ".java";
           
        public static void main(String[] args) throws IOException {
           
            VelocityEngine velocityEngine = new VelocityEngine();
            velocityEngine.init();
         
            VelocityContext context = new VelocityContext();
            context.put("className", className);
            context.put("message", message);

            Writer writer = new FileWriter(new File(outputFile));
            Velocity.mergeTemplate(inputTemplate, "UTF-8", context, writer);
            writer.flush();
            writer.close();
           
            System.out.println("Generated " + outputFile);
        }
    }

Build the Velocity generator and run it. With Maven:

$ mvn clean install
$ mvn exec:java -Dexec.mainClass=velocity_generator.VelocityStartGenerator

This generates the file VelocityExample.java, which looks like this:

public class VelocityExample {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }

}

Build and run it, and it will say: "Hello World!"

$ javac VelocityExample.java
$ java VelocityExample
Hello World!

Play around with the generator. Can you make the generated file say "Howdy"?

Next, check out the following HTML and shell script generation examples.

HTML Hello World example

Velocity template
(html_example.vm)
<!DOCTYPE html>
<html>
<body>

<h1>$message</h1>

</body>
</html>
Velocity generator
(VelocityStartGenerator.java)
public class VelocityStartGenerator {
 
    static String inputTemplate = "http_example.vm";
    static String message = "Hello World!";
    static String outputFile = "helloworld.html";
       
    public static void main(String[] args) throws IOException {
       
        VelocityEngine velocityEngine = new VelocityEngine();
        velocityEngine.init();
     
        VelocityContext context = new VelocityContext();
        context.put("message", message);

        Writer writer = new FileWriter(new File(outputFile));
        Velocity.mergeTemplate(inputTemplate
                        , "UTF-8", context, writer);
        writer.flush();
        writer.close();
       
        System.out.println("Generated " + outputFile);
    }
}
Generated file
(helloworld.html)
<!DOCTYPE html>
<html>
<body>

<h1>Hello World!</h1>

</body>
</html>
Generated output

Shell script Hello World example

Velocity template
(sh_example.vm)
echo $message
Velocity generator
(VelocityStartGenerator.java)
public class VelocityStartGenerator {
 
    static String inputTemplate = "sh_example.vm";
    static String message = "Hello World!";
    static String outputFile = "helloworld.sh";
       
    public static void main(String[] args) throws IOException {
       
        VelocityEngine velocityEngine = new VelocityEngine();
        velocityEngine.init();
     
        VelocityContext context = new VelocityContext();
        context.put("message", message);

        Writer writer = new FileWriter(new File(outputFile));
        Velocity.mergeTemplate(inputTemplate, "UTF-8", context, writer);
        writer.flush();
        writer.close();
       
        System.out.println("Generated " + outputFile);
    }
}
Generated file
(helloworld.sh)
echo Hello World!
Generated output

Conclusion

You can find Velocity in Apache's GitHub repo, and you can find examples of its use on GitLab and GitHub.

This was a brief and quick rundown on Apache Velocity. Have you used it? What do you think? Please share your thoughts in the comments.

HTML code

These templates will help you get started designing a modern codebase for your next web project.
Hands searching a library card catalogue

Does your next Python project need a templating engine to automatically generate HTML? Here are a few options.
Sustainable data

Introduction to Apache Hadoop, an open source software framework for storage and large scale...

Topics

About the author

Girish Managoli - Girish has over 20 years’ experience in technology and software at a global IT Services organization based in India. Girish is architect of "I Got" cloud platform to uplift the bottom of the pyramid built with open source stack and contemporary architectural patterns such as microservices, containerisation and multi tenancy. Girish writes on open source and tech topics. Views expressed here-in are his own and not necessarily that of his organization