Search This Blog

Friday 29 October 2010

Using Apache Velocity From JDeveloper 11g

I needed to support various output formats (console, HTML, SQL) for a Java console application I was creating and so saw Apache Velocity as a good fit for this. Here are some quick steps to get this setup in JDeveloper 11g.

1. Add the velocity JAR files to your project classpath as shown below.


2. Create a velocity.properties file as follows. In this example the templates files will be read from the file system , you can read them from the classpath if you wish. You will see that from this example below the velocity template files are in the SRC directory of the project so I can edit them from the IDE itself.

resource.loader = file
file.resource.loader.class = org.apache.velocity.runtime.resource.loader.FileResourceLoader
file.resource.loader.path = C:/jdev/jdevprod/11113/jdeveloper/jdev/mywork/VelocityDemo/Demo/src/templates
file.resource.loader.cache = true

3. In the directory "C:/jdev/jdevprod/11113/jdeveloper/jdev/mywork/VelocityDemo/Demo/src/templates" create a helloworld.vm template file as follows

Hello $name!  Welcome to Velocity!

4. Now create a java class as follows
package support.au.demos.velocity;

import java.io.StringWriter;

import java.net.URL;

import java.util.Properties;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;


public class HelloWorld
{
  public HelloWorld()
  {
  }
  
  public static void main(String[] args) throws Exception
  {
    /*  first, get and initialize an engine  */
    VelocityEngine ve = new VelocityEngine();

    Properties props = new Properties();
    
    URL url = ClassLoader.getSystemResource("velocity.properties");
    props.load(url.openStream());
    
    ve.init(props);
    /*  next, get the Template  */
    Template t = ve.getTemplate( "helloworld.vm" );
    /*  create a context and add data */
    VelocityContext context = new VelocityContext();
    context.put("name", "World");
    /* now render the template into a StringWriter */
    StringWriter writer = new StringWriter();
    t.merge( context, writer );
    /* show the World */
    System.out.println( writer.toString() ); 
  }
}

5. Your project would look something like this


6. Run HelloWorld to verify the output as shown below.

Hello World!  Welcome to Velocity!

1 comment:

Anonymous said...

Thanks alot for this usefull tutorial! This is the one that works for me.