aboutsummaryrefslogtreecommitdiff
path: root/velocity-engine-core/src/test/java/org/apache/velocity/test/BuiltInEventHandlerTestCase.java
blob: 63e106760147fbbb227a21a32451e4d02d1efdbd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
package org.apache.velocity.test;

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.app.event.EventCartridge;
import org.apache.velocity.app.event.implement.EscapeHtmlReference;
import org.apache.velocity.app.event.implement.EscapeJavaScriptReference;
import org.apache.velocity.app.event.implement.EscapeReference;
import org.apache.velocity.app.event.implement.EscapeSqlReference;
import org.apache.velocity.app.event.implement.EscapeXmlReference;
import org.apache.velocity.app.event.implement.InvalidReferenceInfo;
import org.apache.velocity.app.event.implement.ReportInvalidReferences;
import org.apache.velocity.context.Context;
import org.apache.velocity.runtime.RuntimeConstants;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

/**
 * Tests the operation of the built in event handlers.
 *
 * @author <a href="mailto:wglass@forio.com">Will Glass-Husain</a>
 * @version $Id$
 */
public class BuiltInEventHandlerTestCase extends BaseTestCase {

    protected boolean DEBUG = false;

    /**
    * VTL file extension.
    */
   private static final String TMPL_FILE_EXT = "vm";

   /**
    * Comparison file extension.
    */
   private static final String CMP_FILE_EXT = "cmp";

   /**
    * Comparison file extension.
    */
   private static final String RESULT_FILE_EXT = "res";

   /**
    * Path for templates. This property will override the
    * value in the default velocity properties file.
    */
   private final static String FILE_RESOURCE_LOADER_PATH = TEST_COMPARE_DIR + "/includeevent";

   /**
    * Results relative to the build directory.
    */
   private static final String RESULTS_DIR = TEST_RESULT_DIR + "/includeevent";

   /**
    * Results relative to the build directory.
    */
   private static final String COMPARE_DIR = TEST_COMPARE_DIR + "/includeevent/compare";

    /**
     * Default constructor.
     */
    public BuiltInEventHandlerTestCase(String name)
    {
        super(name);
    }

    @Override
    public void setUp() throws Exception
    {
        assureResultsDirectoryExists(RESULTS_DIR);
        super.setUp();
    }

    public static Test suite()
    {
       return new TestSuite(BuiltInEventHandlerTestCase.class);
    }

    protected void log(String out)
    {
        if (DEBUG)
        {
            System.out.println (out);
        }
    }

    /**
     * Test reporting of invalid syntax
     * @throws Exception
     */
    public void testReportInvalidReferences1() throws Exception
    {
        VelocityEngine ve = new VelocityEngine();
        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(2,errors.size());
        assertEquals("$c1",((InvalidReferenceInfo) errors.get(0)).getInvalidReference());
        assertEquals("$a1.foobar()",((InvalidReferenceInfo) errors.get(1)).getInvalidReference());

        log("Caught invalid references (local configuration).");
    }

    public void testReportInvalidReferences2() throws Exception
    {
        VelocityEngine ve = new VelocityEngine();
        ve.setProperty("event_handler.invalid_references.exception","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");
        Writer writer = new StringWriter();

        ve.evaluate(context,writer,"test","$a1 no problem");

        try {
            ve.evaluate(context,writer,"test","$a1 $c1 $a1.length() $a1.foobar()");
            fail ("Expected exception.");
        } catch (RuntimeException E) {}


        log("Caught invalid references (global configuration).");

    }

    /**
     * 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).");
    }

    /**
     * Test reporting of invalid syntax
     * @throws Exception
     */
    public void testReportNullInvalidReferences() throws Exception
    {
        VelocityEngine ve = new VelocityEngine();
        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(3,errors.size());
        assertEquals("$c1",((InvalidReferenceInfo) errors.get(0)).getInvalidReference());
        assertEquals("$a1.foobar()",((InvalidReferenceInfo) errors.get(1)).getInvalidReference());
        assertEquals("$n1",((InvalidReferenceInfo) errors.get(2)).getInvalidReference());

        log("Caught invalid references (local configuration).");
    }

    /**
     * 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).");
    }

    /**
     * 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).");
    }

    /**
     * Test escaping
     * @throws Exception
     */
    public void testEscapeHtml() throws Exception
    {
        EscapeReference esc = new EscapeHtmlReference();
        assertEquals("test string&amp;another&lt;b&gt;bold&lt;/b&gt;test",esc.referenceInsert(null,"","test string&another<b>bold</b>test"));
        assertEquals("&lt;&quot;&gt;",esc.referenceInsert(null,"","<\">"));
        assertEquals("test string",esc.referenceInsert(null,"","test string"));

        log("Correctly escaped HTML");

    }

    /**
     * Test escaping
     * @throws Exception
     */
    public void testEscapeXml() throws Exception
    {
        EscapeReference esc = new EscapeXmlReference();
        assertEquals("test string&amp;another&lt;b&gt;bold&lt;/b&gt;test",esc.referenceInsert(null,"","test string&another<b>bold</b>test"));
        assertEquals("&lt;&quot;&gt;",esc.referenceInsert(null,"","<\">"));
        assertEquals("&apos;",esc.referenceInsert(null,"","'"));
        assertEquals("test string",esc.referenceInsert(null,"","test string"));

        log("Correctly escaped XML");

    }

    /**
     * Test escaping
     * @throws Exception
     */
    public void testEscapeSql() throws Exception
    {
        EscapeReference esc = new EscapeSqlReference();
        assertEquals("Jimmy''s Pizza",esc.referenceInsert(null,"","Jimmy's Pizza"));
        assertEquals("test string",esc.referenceInsert(null,"","test string"));

        log("Correctly escaped SQL");

    }

    /**
     * Test escaping
     * @throws Exception
     */
    public void testEscapeJavaScript() throws Exception
    {
        EscapeReference esc = new EscapeJavaScriptReference();
        assertEquals("Jimmy\\'s Pizza",esc.referenceInsert(null,"","Jimmy's Pizza"));
        assertEquals("test string",esc.referenceInsert(null,"","test string"));


        log("Correctly escaped Javascript");
    }

    /**
     * test that escape reference handler works with no match restrictions
     * @throws Exception
     */
    public void testEscapeReferenceMatchAll() throws Exception
    {
        VelocityEngine ve = new VelocityEngine();
        ve.setProperty(RuntimeConstants.EVENTHANDLER_REFERENCEINSERTION, "org.apache.velocity.app.event.implement.EscapeHtmlReference");
        ve.init();

        Context context;
        Writer writer;

        // test normal reference
        context = new VelocityContext();
        writer = new StringWriter();
        context.put("bold","<b>");
        ve.evaluate(context,writer,"test","$bold test & test");
        assertEquals("&lt;b&gt; test & test",writer.toString());

        // test method reference
        context = new VelocityContext();
        writer = new StringWriter();
        context.put("bold","<b>");
        ve.evaluate(context,writer,"test","$bold.substring(0,1)");
        assertEquals("&lt;",writer.toString());

        log("Escape matched all references (global configuration)");

    }

    /**
     * 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 &lt;b&gt;pizza&lt;/b&gt;",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 &lt;b&gt;pizza&lt;/b&gt;",writer.toString());

        // JavaScript and HTML
        writer = new StringWriter();
        ve.evaluate(newEscapeContext(),writer,"test","$test1_js_test");
        assertEquals("Jimmy\\'s &lt;b&gt;pizza&lt;/b&gt;",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)");



    }

    private Context newEscapeContext()
    {
        Context context = new VelocityContext();
        context.put("test1","Jimmy's <b>pizza</b>");
        context.put("test1_js","Jimmy's <b>pizza</b>");
        context.put("test1_js_test","Jimmy's <b>pizza</b>");
        return context;
    }

    public void testPrintExceptionHandler() throws Exception
    {
        VelocityEngine ve1 = new VelocityEngine();
        ve1.setProperty(RuntimeConstants.EVENTHANDLER_METHODEXCEPTION, "org.apache.velocity.app.event.implement.PrintExceptions");
        ve1.init();

        VelocityEngine ve2 = new VelocityEngine();
        ve2.setProperty(RuntimeConstants.EVENTHANDLER_METHODEXCEPTION, "org.apache.velocity.app.event.implement.PrintExceptions");
        ve2.setProperty("eventhandler.methodexception.templateinfo","true");
        ve2.init();

        VelocityEngine ve3 = new VelocityEngine();
        ve3.setProperty(RuntimeConstants.EVENTHANDLER_METHODEXCEPTION, "org.apache.velocity.app.event.implement.PrintExceptions");
        ve3.setProperty("eventhandler.methodexception.stacktrace","true");
        ve3.init();

        Context context;
        StringWriter writer;

        context = new VelocityContext();
        context.put("list",new ArrayList());

        // exception and message only
        writer = new StringWriter();
        ve1.evaluate(context, writer, "test", "$list.get(0)");
        String result = writer.toString();
        assertTrue(result.contains("IndexOutOfBoundsException"));
        assertTrue(result.contains("Index: 0, Size: 0"));
        assertTrue(!result.contains("at test (line 1, column 7)"));
        assertTrue(!result.contains("rangeCheck"));

        // exception, message and template info
        writer = new StringWriter();
        ve2.evaluate(context,writer,"test","$list.get(0)");
        result = writer.toString();
        assertTrue(result.contains("IndexOutOfBoundsException"));
        assertTrue(result.contains("Index: 0, Size: 0"));
        assertTrue(result.contains("at test (line 1, column 7)"));
        assertTrue(!result.contains("rangeCheck"));

        // exception, message and stack trace
        writer = new StringWriter();
        ve3.evaluate(context,writer,"test","$list.get(0)");
        result = writer.toString();
        assertTrue(result.contains("IndexOutOfBoundsException"));
        assertTrue(result.contains("Index: 0, Size: 0"));
        assertTrue(!result.contains("at test (line 1, column 7)"));
        assertTrue(result.contains("rangeCheck"));

        log("PrintException handler successful.");

    }

    public void testIncludeNotFound() throws Exception
    {
        VelocityEngine ve = new VelocityEngine();
        ve.setProperty(RuntimeConstants.EVENTHANDLER_INCLUDE, "org.apache.velocity.app.event.implement.IncludeNotFound");
        ve.addProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, FILE_RESOURCE_LOADER_PATH);
        ve.init();

        Template template;
        FileOutputStream fos;
        Writer fwriter;
        Context context;

        template = ve.getTemplate( getFileName(null, "test6", TMPL_FILE_EXT) );

        fos = new FileOutputStream (
                getFileName(RESULTS_DIR, "test6", RESULT_FILE_EXT));

        fwriter = new BufferedWriter( new OutputStreamWriter(fos) );

        context = new VelocityContext();
        template.merge(context, fwriter);
        fwriter.flush();
        fwriter.close();

        if (!isMatch(RESULTS_DIR, COMPARE_DIR, "test6", RESULT_FILE_EXT, CMP_FILE_EXT))
        {
            fail("Output incorrect.");
        }

        log("IncludeNotFound handler successful.");

    }

    public void testIncludeNotFoundMissingResourceName() throws Exception
    {
        // uses base test support
        engine.setProperty(RuntimeConstants.EVENTHANDLER_INCLUDE, "org.apache.velocity.app.event.implement.IncludeNotFound");
        addTemplate("notfound.vm", "$missingResource");
        assertEvalEquals("foo", "#parse('foo')");
    }

    public void testIncludeRelativePath() throws Exception
    {
        VelocityEngine ve = new VelocityEngine();
        ve.setProperty(RuntimeConstants.EVENTHANDLER_INCLUDE, "org.apache.velocity.app.event.implement.IncludeRelativePath");
        ve.addProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, FILE_RESOURCE_LOADER_PATH);
        ve.init();

        Template template;
        FileOutputStream fos;
        Writer fwriter;
        Context context;

        template = ve.getTemplate( getFileName(null, "subdir/test2", TMPL_FILE_EXT) );

        fos = new FileOutputStream (
                getFileName(RESULTS_DIR, "test2", RESULT_FILE_EXT));

        fwriter = new BufferedWriter( new OutputStreamWriter(fos) );

        context = new VelocityContext();
        template.merge(context, fwriter);
        fwriter.flush();
        fwriter.close();

        if (!isMatch(RESULTS_DIR, COMPARE_DIR, "test2", RESULT_FILE_EXT, CMP_FILE_EXT))
        {
            fail("Output incorrect.");
        }

        log("IncludeRelativePath handler successful.");

    }
}