I have put this working code snippet for future references. The code sample was written with Apache velocity version 1.7 with embedded Jetty.
Velocity template path is located at the resource folder email_templates subfolder.
Code Snippet in Java (Snippets are worked both running on eclipse and inside a Jar)
templateName = "/email_templates/byoa.tpl.vm"
VelocityEngine ve = new VelocityEngine();
ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
ve.init();
Template t = ve.getTemplate(this.templateName);
VelocityContext velocityContext = new VelocityContext();
velocityContext.put("","") // put your template values here
StringWriter writer = new StringWriter();
t.merge(this.velocityContext, writer);
System.out.println(writer.toString()); // print the updated template as string
For OSGI plugging code snippets.
final String TEMPLATE = "resources/template.vm" // located in the resources folder
Thread current = Thread.currentThread();
ClassLoader oldLoader = current.getContextClassLoader();
try {
current.setContextClassLoader(TemplateHelper.class.getClassLoader()); // TemplateHelper is a class inside your jar file
Properties p = new Properties();
p.setProperty("resource.loader", "class");
p.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
Velocity.init( p );
VelocityEngine ve = new VelocityEngine();
Template template = Velocity.getTemplate( TEMPLATE );
VelocityContext context = new VelocityContext();
context.put("tc", obj);
StringWriter writer = new StringWriter();
template.merge( context, writer );
return writer.toString() ;
} catch(Exception e){
e.printStackTrace();
} finally {
current.setContextClassLoader(oldLoader);
}