Search code examples
javavelocity

Velocity 1.7 - Sometimes Directive.postRender throws NullPointerException in Velocity.evaluate


I have came across an issue while using Velocity template. It is throwing NullPointerException for Directive.postRender for a foreach function used in my template.

Strange behavior is that with exactly same template and same input data, Velocity is successfully able to complete the evaluation process. It fails say 1 in 100 times.

Can anyone share insights please? Thanks in advance!

Version : Velocity 1.7

java.lang.NullPointerException: null
    at org.apache.velocity.runtime.directive.Directive.postRender(Directive.java:202) ~[velocity-1.7.jar:1.7]
    at org.apache.velocity.runtime.directive.Foreach.clean(Foreach.java:489) ~[velocity-1.7.jar:1.7]
    at org.apache.velocity.runtime.directive.Foreach.render(Foreach.java:443) ~[velocity-1.7.jar:1.7]
    at org.apache.velocity.runtime.parser.node.ASTDirective.render(ASTDirective.java:207) ~[velocity-1.7.jar:1.7]
    at org.apache.velocity.runtime.parser.node.SimpleNode.render(SimpleNode.java:342) ~[velocity-1.7.jar:1.7]
    at org.apache.velocity.runtime.RuntimeInstance.render(RuntimeInstance.java:1378) ~[velocity-1.7.jar:1.7]
    at org.apache.velocity.runtime.RuntimeInstance.evaluate(RuntimeInstance.java:1314) ~[velocity-1.7.jar:1.7]
    at org.apache.velocity.app.Velocity.evaluate(Velocity.java:254) ~[velocity-1.7.jar:1.7]


Solution

  • Managed to fix by changing code from using Velocity.init() to

    VelocityEngine vc = new VelocityEngine();
    vc.init();
    

    1st one was a singleton implementation and Velocity might be loosing some data in heavily multi-threaded mode. By changing it to use new instance for each pdf generation call, it is working like a charm.

    Thanks!