Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Velocity templates not substituting methods

Tags:

velocity

In the Velocity User's Guide it seems pretty straight forward to use methods in templates. I tried, but could not make it work. Can someone tell me what I did wrong?

Thanks.

This is my code

@Test
public void testVelocity() {
  Velocity.init();
  VelocityContext map = new VelocityContext();
  map.put("test", "Success");
  map.put("ok", "OK!");
  map.put("func", new Object() {public String test() {return "Yay!";}});
  map.put("func2", new Object() {public String test(String t) {return t+t;}});

  String template = "${func.test()} $test $func2.test($ok)";
  StringWriter writer = new StringWriter();
  Velocity.evaluate(map, writer, "", new StringReader(template));
  assertEquals("Yay! Success OK!OK!", writer.toString());
}

and this is the output:

org.junit.ComparisonFailure: 
Expected :Yay! Success OK!OK!
Actual   :${func.test()} Success $func2.test($ok)

Variable substitutions seems to work fine, but not method calls.

Please help.

like image 574
Bennie Avatar asked Aug 14 '13 14:08

Bennie


1 Answers

The problem is that for security reasons Velocity only allows calling public methods of public classes. An anonymous class is not public, thus the call is blocked.

It would work if you put a real object, an instance of a public class.

It would also work if you disable the secure uberspector, but that is not a good idea, since it opens up the system.

like image 97
Sergiu Dumitriu Avatar answered Nov 05 '22 01:11

Sergiu Dumitriu