Java Code Examples for org.apache.velocity.app.VelocityEngine#evaluate()
The following examples show how to use
org.apache.velocity.app.VelocityEngine#evaluate() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: InvalidEventHandlerTestCase.java From velocity-engine with Apache License 2.0 | 7 votes |
/** * Test deeper structures * @param ve * @param vc * @throws Exception */ private void doTestInvalidReferenceEventHandler4(VelocityEngine ve, VelocityContext vc) throws Exception { VelocityContext context = new VelocityContext(vc); Tree test = new Tree(); test.setField("10"); Tree test2 = new Tree(); test2.setField("12"); test.setChild(test2); context.put("tree",test); String s; Writer w; // show work fine s = "$tree.Field $tree.field $tree.child.Field"; w = new StringWriter(); ve.evaluate(context, w, "mystring", s); s = "$tree.x $tree.field.x $tree.child.y $tree.child.Field.y"; w = new StringWriter(); ve.evaluate(context, w, "mystring", s); }
Example 2
Source File: EvaluateTestCase.java From velocity-engine with Apache License 2.0 | 6 votes |
/** * Test that the event handlers work in #evaluate (since they are * attached to the context). Only need to check one - they all * work the same. * @throws Exception */ public void testEventHandler() throws Exception { VelocityEngine ve = new VelocityEngine(); ve.setProperty(RuntimeConstants.EVENTHANDLER_REFERENCEINSERTION, EscapeHtmlReference.class.getName()); ve.init(); Context context = new VelocityContext(); context.put("lt","<"); context.put("gt",">"); StringWriter writer = new StringWriter(); ve.evaluate(context, writer, "test","${lt}test${gt} #evaluate('${lt}test2${gt}')"); assertEquals("<test> <test2>", writer.toString()); }
Example 3
Source File: VelocityHelper.java From PackageTemplates with Apache License 2.0 | 6 votes |
public static String fromTemplate(String velocityTemplate, Map<String, String> mapVariables) { StringWriter stringWriter = new StringWriter(); try { VelocityEngine velocityEngine = getVelocityEngine(); VelocityContext velocityContext = new VelocityContext(); for (Map.Entry<String, String> entry : mapVariables.entrySet()) { velocityContext.put(entry.getKey(), entry.getValue()); } velocityEngine.evaluate(velocityContext, stringWriter, "PackageTemplatesVelocity", velocityTemplate); } catch (Exception e) { Logger.log("fromTemplate Error in Velocity code generator"); return null; } return stringWriter.getBuffer().toString(); }
Example 4
Source File: VelocityNonStrictHelper.java From herd with Apache License 2.0 | 6 votes |
/** * Wrapper for {@link Velocity#evaluate(org.apache.velocity.context.Context, java.io.Writer, String, java.io.InputStream)} * * @param templateReader A {@link Reader} of a Velocity template. * @param variables Variables to add to context * @param logTag The log tag * @param strict The strict boolean flag determines whether or not to require runtime references or not during velocity evaluate. * * @return {@link String} result of evaluation */ private String evaluate(Reader templateReader, Map<String, Object> variables, String logTag, boolean strict) { /* Get and initialize a velocity engine */ VelocityEngine velocityEngine = new VelocityEngine(); velocityEngine.setProperty(RuntimeConstants.RUNTIME_REFERENCES_STRICT, strict); velocityEngine.init(); VelocityContext velocityContext = new VelocityContext(variables); StringWriter writer = new StringWriter(); if (!velocityEngine.evaluate(velocityContext, writer, logTag, templateReader)) { // Although the velocityEngine.evaluate method's Javadoc states that it will return false to indicate a failure when the template couldn't be // processed and to see the Velocity log messages for more details, upon examining the method's implementation, it doesn't look like // it will ever return false. Instead, other RuntimeExceptions will be thrown (e.g. ParseErrorException). // Nonetheless, we'll leave this checking here to honor the method's contract in case the implementation changes in the future. // Having said that, there will be no way to JUnit test this flow. throw new IllegalStateException("Error evaluating velocity template. See velocity log message for more details."); } return writer.toString(); }
Example 5
Source File: ExceptionTestCase.java From velocity-engine with Apache License 2.0 | 5 votes |
public void assertException(VelocityEngine ve, Context context, String input) throws Exception { try { StringWriter writer = new StringWriter(); ve.evaluate(context,writer,"test",input); fail("Expected RuntimeException"); } catch (RuntimeException E) { // do nothing } }
Example 6
Source File: CustomTitle.java From openemm with GNU Affero General Public License v3.0 | 5 votes |
/** * Runs the velocity engine on the script with the provided * content for one recipient. * * @param titleType one of the valid constants TITLE_* from org.agnitas.util.Title * @param gender the gender of the recipient * @param title his title * @param firstname his firstname * @param lastname his lastname * @param columns and all other known database columns for this recipient * @param error optional Buffer to collect error message * @return the output of the velocity script, i.e. the generated title for this recipient */ public String makeTitle (int titleType, int gender, String title, String firstname, String lastname, Map <String, String> columns, StringBuffer error) { String rc = null; logTo = error; try { VelocityEngine ve = new VelocityEngine (); VelocityContext vc = new VelocityContext (); ve.setProperty (VelocityEngine.RUNTIME_LOG_LOGSYSTEM, this); ve.setProperty (VelocityEngine.VM_LIBRARY, ""); ve.init (); StringWriter out = new StringWriter (); vc.put ("type", titleType); vc.put ("gender", gender); vc.put ("title", (title == null || titleType == Title.TITLE_FIRST ? "" : title)); vc.put ("firstname", (firstname == null || titleType == Title.TITLE_DEFAULT ? "" : firstname)); vc.put ("lastname", (lastname == null || titleType == Title.TITLE_FIRST ? "" : lastname)); vc.put ("cust", columns); ve.evaluate (vc, out, "title", titleText); rc = shrink (out.toString ()); } catch (Exception e) { if (error != null) { error.append ("CustomTitle: \"" + titleText + "\" leads to " + e.toString () + "\n"); } } logTo = null; return rc; }
Example 7
Source File: ParserTestCase.java From velocity-engine with Apache License 2.0 | 5 votes |
/** * Test to see if we force the first arg to #macro() to be a word */ public void testMacro() throws Exception { VelocityEngine ve = new VelocityEngine(); TestLogger logger = new TestLogger(); ve.setProperty(RuntimeConstants.RUNTIME_LOG_INSTANCE, logger); ve.init(); /* * this should work */ String template = "#macro(foo) foo #end"; ve.evaluate(new VelocityContext(), new StringWriter(), "foo", template); /* * this should throw an exception */ template = "#macro($x) foo #end"; try { ve.evaluate(new VelocityContext(), new StringWriter(), "foo", template); fail("Could evaluate macro with errors!"); } catch(ParseErrorException pe) { // Do nothing } }
Example 8
Source File: BuiltInEventHandlerTestCase.java From velocity-engine with Apache License 2.0 | 5 votes |
/** * Test reporting of invalid syntax * @throws Exception */ public void testReportNullQuietInvalidReferences() throws Exception { VelocityEngine ve = new VelocityEngine(); ve.setProperty("event_handler.invalid_references.quiet","true"); ve.setProperty("event_handler.invalid_references.null","true"); ReportInvalidReferences reporter = new ReportInvalidReferences(); ve.init(); VelocityContext context = new VelocityContext(); EventCartridge ec = new EventCartridge(); ec.addEventHandler(reporter); ec.attachToContext(context); context.put("a1","test"); context.put("b1","test"); context.put("n1", null); Writer writer = new StringWriter(); ve.evaluate(context,writer,"test","$a1 $c1 $a1.length() $a1.foobar() $!c1 $n1 $!n1 #if($c1) nop #end"); List errors = reporter.getInvalidReferences(); assertEquals(5,errors.size()); assertEquals("$c1",((InvalidReferenceInfo) errors.get(0)).getInvalidReference()); assertEquals("$a1.foobar()",((InvalidReferenceInfo) errors.get(1)).getInvalidReference()); assertEquals("$c1",((InvalidReferenceInfo) errors.get(2)).getInvalidReference()); assertEquals("$n1",((InvalidReferenceInfo) errors.get(3)).getInvalidReference()); assertEquals("$n1",((InvalidReferenceInfo) errors.get(4)).getInvalidReference()); log("Caught invalid references (local configuration)."); }
Example 9
Source File: BuiltInEventHandlerTestCase.java From velocity-engine with Apache License 2.0 | 5 votes |
/** * Test reporting of invalid syntax * @throws Exception */ public void testReportTestedInvalidReferences() throws Exception { VelocityEngine ve = new VelocityEngine(); ve.setProperty("event_handler.invalid_references.tested","true"); ReportInvalidReferences reporter = new ReportInvalidReferences(); ve.init(); VelocityContext context = new VelocityContext(); EventCartridge ec = new EventCartridge(); ec.addEventHandler(reporter); ec.attachToContext(context); context.put("a1","test"); context.put("b1","test"); context.put("n1", null); Writer writer = new StringWriter(); ve.evaluate(context,writer,"test","$a1 $c1 $a1.length() $a1.foobar() $!c1 $n1 $!n1 #if($c1) nop #end"); List errors = reporter.getInvalidReferences(); assertEquals(3,errors.size()); assertEquals("$c1",((InvalidReferenceInfo) errors.get(0)).getInvalidReference()); assertEquals("$a1.foobar()",((InvalidReferenceInfo) errors.get(1)).getInvalidReference()); assertEquals("$c1",((InvalidReferenceInfo) errors.get(2)).getInvalidReference()); log("Caught invalid references (local configuration)."); }
Example 10
Source File: CommentsTestCase.java From velocity-engine with Apache License 2.0 | 5 votes |
/** * Test multiline comments * @throws Exception */ public void testMultiLine() throws Exception { VelocityEngine ve = new VelocityEngine(); ve.init(); Context context = new VelocityContext(); StringWriter writer = new StringWriter(); ve.evaluate(context, writer, "test","abc #* test\r\ntest2*#\r\ndef"); assertEquals("abc \r\ndef", writer.toString()); }
Example 11
Source File: SecureIntrospectionTestCase.java From velocity-engine with Apache License 2.0 | 5 votes |
private boolean doesStringEvaluate(VelocityEngine ve, Context c, String inputString) throws ParseErrorException, MethodInvocationException, ResourceNotFoundException, IOException { // assume that an evaluation is bad if the input and result are the same (e.g. a bad reference) // or the result is an empty string (e.g. bad #foreach) Writer w = new StringWriter(); ve.evaluate(c, w, "foo", inputString); String result = w.toString(); return (result.length() > 0 ) && !result.equals(inputString); }
Example 12
Source File: ConversionHandlerTestCase.java From velocity-engine with Apache License 2.0 | 5 votes |
public void testOtherConversions() throws Exception { VelocityEngine ve = createEngine(false); VelocityContext context = createContext(); StringWriter writer = new StringWriter(); ve.evaluate(context, writer,"test", "$strings.join(['foo', 'bar'], ',')"); assertEquals("foo,bar", writer.toString()); }
Example 13
Source File: EmailTransformer.java From website with GNU Affero General Public License v3.0 | 5 votes |
private String mergeTemplateIntoString(VelocityEngine velocityEngine, String templateContents, Map model) throws VelocityException { StringWriter writer = new StringWriter(); VelocityContext velocityContext = new VelocityContext(model); velocityEngine.evaluate(velocityContext, writer, this.getClass().getName(), templateContents); return writer.toString(); }
Example 14
Source File: Telegraf.java From vespa with Apache License 2.0 | 5 votes |
protected static void writeConfig(TelegrafConfig telegrafConfig, Writer writer, String logFilePath) { VelocityContext context = new VelocityContext(); context.put("logFilePath", logFilePath); context.put("intervalSeconds", telegrafConfig.intervalSeconds()); context.put("cloudwatchPlugins", telegrafConfig.cloudWatch()); context.put("protocol", telegrafConfig.isHostedVespa() ? "https" : "http"); // TODO: Add node cert if hosted VelocityEngine velocityEngine = new VelocityEngine(); velocityEngine.init(); velocityEngine.evaluate(context, writer, "TelegrafConfigWriter", getTemplateReader()); uncheck(writer::close); }
Example 15
Source File: MicroServiceTemplateUtil.java From nh-micro with Apache License 2.0 | 5 votes |
public static String sqlTemplateService(String template,Map paramMap,List placeList){ VelocityEngine ve = new VelocityEngine(); ve.addProperty("userdirective", "com.nh.micro.template.vext.MicroSqlReplace"); ve.init(); VelocityContext context = new VelocityContext(); context.put("param", paramMap); context.put("placeList", placeList); StringWriter writer = new StringWriter(); ve.evaluate(context, writer, "", template); return writer.toString(); }
Example 16
Source File: BuiltInEventHandlerTestCase.java From velocity-engine with Apache License 2.0 | 5 votes |
/** * Test reporting of invalid syntax * @throws Exception */ public void testReportQuietInvalidReferences() throws Exception { VelocityEngine ve = new VelocityEngine(); ve.setProperty("event_handler.invalid_references.quiet","true"); ReportInvalidReferences reporter = new ReportInvalidReferences(); ve.init(); VelocityContext context = new VelocityContext(); EventCartridge ec = new EventCartridge(); ec.addEventHandler(reporter); ec.attachToContext(context); context.put("a1","test"); context.put("b1","test"); context.put("n1", null); Writer writer = new StringWriter(); ve.evaluate(context,writer,"test","$a1 $c1 $a1.length() $a1.foobar() $!c1 $n1 $!n1 #if($c1) nop #end"); List errors = reporter.getInvalidReferences(); assertEquals(3,errors.size()); assertEquals("$c1",((InvalidReferenceInfo) errors.get(0)).getInvalidReference()); assertEquals("$a1.foobar()",((InvalidReferenceInfo) errors.get(1)).getInvalidReference()); assertEquals("$c1",((InvalidReferenceInfo) errors.get(2)).getInvalidReference()); log("Caught invalid references (local configuration)."); }
Example 17
Source File: Generator.java From flash-waimai with MIT License | 5 votes |
public String generateCode(String packageName, String templatePath) throws IOException { VelocityContext context = new VelocityContext(); context.put("table", table); context.put("packageName", packageName); StringWriter writer = new StringWriter(); String template = new String(Streams.readBytes(ClassLoader.getSystemResourceAsStream(templatePath)), Charset.forName("utf8")); VelocityEngine engine = new VelocityEngine(); engine.setProperty("runtime.references.strict", false); engine.init(); engine.evaluate(context, writer, "generator", template); return writer.toString(); }
Example 18
Source File: VelocityViewTag.java From velocity-tools with Apache License 2.0 | 4 votes |
protected void evalBody(Writer out) throws Exception { VelocityEngine engine = getVelocityView().getVelocityEngine(); engine.evaluate(getViewToolContext(), out, getLogId(), getBodyContent().getReader()); }
Example 19
Source File: BuiltInEventHandlerTestCase.java From velocity-engine with Apache License 2.0 | 4 votes |
/** * test that escape reference handler works with match restrictions * @throws Exception */ public void testEscapeReferenceMatch() throws Exception { // set up HTML match on everything, JavaScript match on _js* VelocityEngine ve = new VelocityEngine(); ve.setProperty(RuntimeConstants.EVENTHANDLER_REFERENCEINSERTION, "org.apache.velocity.app.event.implement.EscapeHtmlReference,org.apache.velocity.app.event.implement.EscapeJavaScriptReference"); ve.setProperty("eventhandler.escape.javascript.match", "/.*_js.*/"); ve.init(); Writer writer; // Html no JavaScript writer = new StringWriter(); ve.evaluate(newEscapeContext(),writer,"test","$test1"); assertEquals("Jimmy's <b>pizza</b>",writer.toString()); // comment out bad test -- requires latest commons-lang /** // JavaScript and HTML writer = new StringWriter(); ve.evaluate(newEscapeContext(),writer,"test","$test1_js"); assertEquals("Jimmy\\'s <b>pizza</b>",writer.toString()); // JavaScript and HTML writer = new StringWriter(); ve.evaluate(newEscapeContext(),writer,"test","$test1_js_test"); assertEquals("Jimmy\\'s <b>pizza</b>",writer.toString()); // JavaScript and HTML (method call) writer = new StringWriter(); ve.evaluate(newEscapeContext(),writer,"test","$test1_js.substring(0,7)"); assertEquals("Jimmy\\'s",writer.toString()); **/ log("Escape selected references (global configuration)"); }
Example 20
Source File: InvalidEventHandlerTestCase.java From velocity-engine with Apache License 2.0 | 4 votes |
/** * Test invalidGetMethod * * Test behaviour (which should be the same) of * $objRef.myAttribute and $objRef.getMyAttribute() * * @param ve * @param vc * @throws Exception */ private void doTestInvalidReferenceEventHandler0(VelocityEngine ve, VelocityContext vc) throws Exception { String result; Writer w; String s; boolean rc; VelocityContext context = new VelocityContext(vc); context.put("propertyAccess", new String("lorem ipsum")); context.put("objRef", new TestObject()); java.util.ArrayList arrayList = new java.util.ArrayList(); arrayList.add("firstOne"); arrayList.add(null); java.util.HashMap hashMap = new java.util.HashMap(); hashMap.put(41, "41 is not 42"); context.put("objRefArrayList", arrayList); context.put("objRefHashMap", hashMap); // good object, good property (returns non null value) s = "#set($resultVar = $propertyAccess.bytes)"; // -> getBytes() w = new StringWriter(); rc = ve.evaluate( context, w, "mystring", s ); // good object, good property accessor method (returns non null value) s = "#set($resultVar = $propertyAccess.getBytes())"; // -> getBytes() w = new StringWriter(); ve.evaluate( context, w, "mystring", s ); // good object, good property (returns non null value) s = "$objRef.getRealString()"; w = new StringWriter(); ve.evaluate( context, w, "mystring", s ); // good object, good property accessor method (returns null value) // No exception shall be thrown, as returning null should be valid s = "$objRef.getNullValueAttribute()"; w = new StringWriter(); ve.evaluate( context, w, "mystring", s ); // good object, good property (returns null value) // No exception shall be thrown, as returning null should be valid s = "$objRef.nullValueAttribute"; // -> getNullValueAttribute() w = new StringWriter(); ve.evaluate( context, w, "mystring", s ); // good object, good accessor method which returns a non-null object reference // Test removing a hashmap element which exists s = "$objRefHashMap.remove(41)"; w = new StringWriter(); ve.evaluate( context, w, "mystring", s ); // good object, good accessor method which returns null // Test removing a hashmap element which DOES NOT exist // Expected behaviour: Returning null as a value should be // OK and not result in an exception s = "$objRefHashMap.remove(42)"; // will return null, as the key does not exist w = new StringWriter(); ve.evaluate( context, w, "mystring", s ); // good object, good method invocation (returns non-null object reference) s = "$objRefArrayList.get(0)"; // element 0 is NOT NULL w = new StringWriter(); ve.evaluate( context, w, "mystring", s ); // good object, good method invocation (returns null value) // Expected behaviour: Returning null as a value should be // OK and not result in an exception s = "$objRefArrayList.get(1)"; // element 1 is null w = new StringWriter(); ve.evaluate( context, w, "mystring", s ); }