VelocityNonStrictHelper { private String evaluate(Reader templateReader, Map<String, Object> variables, String logTag, boolean strict) { VelocityEngine velocityEngine = new VelocityEngine(); velocityEngine.setProperty(RuntimeConstants.RUNTIME_REFERENCES_STRICT, strict); velocityEngine.setProperty(RuntimeConstants.UBERSPECT_CLASSNAME, SecureUberspector.class.getName()); velocityEngine.init(); VelocityContext velocityContext = new VelocityContext(variables); StringWriter writer = new StringWriter(); if (!velocityEngine.evaluate(velocityContext, writer, logTag, templateReader)) { throw new IllegalStateException("Error evaluating velocity template. See velocity log message for more details."); } return writer.toString(); }  String evaluate(String template, Map<String, Object> variables, String logTag); String evaluate(String template, Map<String, Object> variables, String logTag, boolean strict);  }
@Test public void testEvaluate() { String template = "${foo}"; Map<String, Object> variables = new HashMap<>(); variables.put("foo", "bar"); String logTag = "test"; String result = velocityNonStrictHelper.evaluate(template, variables, logTag); Assert.assertEquals("Result not equal.", "bar", result); }
@Test public void testEvaluateStrict() { String template = "${baz}"; Map<String, Object> variables = new HashMap<>(); variables.put("foo", "bar"); String logTag = "test"; try { velocityNonStrictHelper.evaluate(template, variables, logTag); fail(); } catch (MethodInvocationException methodInvocationException) { Assert.assertEquals("Exception message not equal.", "Variable $baz has not been set at test[line 1, column 1]", methodInvocationException.getMessage()); } }
@Test public void testEvaluateNonStrict() { String template = "${baz}"; Map<String, Object> variables = new HashMap<>(); variables.put("foo", "bar"); String logTag = "test"; String result = velocityNonStrictHelper.evaluate(template, variables, logTag, false); Assert.assertEquals("Result not equal.", "${baz}", result); }
@Test public void testEvaluateNonStrictReflection() { String template = "$foo.getClass().forName(\"java.lang.Runtime\").getRuntime().getName()"; Map<String, Object> variables = new HashMap<>(); variables.put("foo", "bar"); String logTag = "test"; try { velocityNonStrictHelper.evaluate(template, variables, logTag); fail(); } catch (MethodInvocationException methodInvocationException) { Assert.assertEquals("Exception message not equal.", "Object 'java.lang.Class' does not contain method forName(java.lang.String) at test[line 1, column 17]", methodInvocationException.getMessage()); } }