your code is working perfectly fine. I wouldn't recommend such usage and it isn't efficient to do it this way, but it works. What I see on a first glance that the Java code and the template code differs, perhaps you double check this?
Otherwise please use a simpler test code and work your way from there. Eg something like this: