At work I am using Velocity in a number of web applications and was looking into using it for a newsletter application we have. This would allow authors to write more dynamic newsletters, and insert user-specific information in the subject and body of the newsletter.
I already had an implementation in Java that would replace macros using String operations. While the current solution works flawlessly but I was looking for support for if’s statements etc. which Velocity has.
I turned out that replacing my own implementation was a matter of replacing the Decorator implementation I was using with a new one using Velocity:
import java.io.StringWriter;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import dk.itinspiration.newsletter.*;
public class VelocityMacroDecorator extends Decorator {
public void decorate(Message msg) {
try {
// get the intended recipient
Person p = msg.getRecipient();
// get newsletter contents
String content = msg.getContent();
// initialize Velocity
Velocity.init();
// create and populate context
VelocityContext ctx = new VelocityContext();
ctx.put("email", p.getEmail());
ctx.put("firstname", p.getFirstname());
ctx.put("lastname", p.getLastname());
ctx.put("password", p.getPassword());
// create a string writer for the result
StringWriter sw = new StringWriter();
// replace macros
Velocity.evaluate(ctx, sw, null, content);
// set email contents
msg.setContent(sw.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
This’s it! Surely very simple. Now it is just a matter of populating the VelocityContext with more information from the Person object (the newsletter subscriber) and about the newsletter in general (number of subscribers etc.).
The only caveat is that you must allow the agent to run with restricted operations due to Velocity requesting information about the system (dangerous stuff such as line separator and the like).
A sample newsletter could now be something like the following:
Hello $firstname $lastname You are subscribed using '$email' #if ($password != "") and your password is '$password'. #else . #end