NVelocity (or Velocity) as a stand-alone formula evaluator

Posted by dana on Stack Overflow See other posts from Stack Overflow or by dana
Published on 2010-05-13T22:58:06Z Indexed on 2010/05/13 23:04 UTC
Read the original article Hit count: 175

Filed under:
|
|
|

I am using NVelocity in my application to generate html emails. My application has an event-driven model, where saving and/or updating of objects causes these emails to be sent out. Each event can trigger zero, one or multiple multiple emails.

I want to be able to configure which emails get sent out at run-time without having to modify code. I was thinking I could leverage the NVelocity #if() directive to do this. Here is my idea...

Step 1) Prior to email sending, the administrator must configure a formula for NVelocity to evaluate. For example:

$User.FirstName == "Jack"

Step 2) When an object is saved or created, build an NVelocity template in memory based on the input formula. For example:

String formula = GetFormulaFromDB(); // $User.FirstName == "Jack"
String templ = "#if( " + formula + ") 1 #else 0 #end";

Step 3) Execute the NVelocity engine in memory against the template. Check the results to see if we have to send the email:

String result = VelocityMerge(templ); // utility function 
if( result.Trim() == "1" )
{
    SendEmail();
}

I know this is not exactly what NVelocity was intended to do, but I think it just might work :) One of the benefits of doing things this way is that the same syntax can be used for the formula as is used inside the template.

Does anybody have any words of caution or suggestions? Is there a way to execute the #if() directive without jumping through hoops like I have above? Is there a recommended way to validate the formula syntax ahead of time?

Thanks.

© Stack Overflow or respective owner

Related posts about nvelocity

Related posts about velocity