aboutsummaryrefslogtreecommitdiff
path: root/velocity-engine-core/src/test/java/org/apache/velocity/test/InvalidEventHandlerTestCase.java
blob: 48ba8e61b23f32f7f8ae88bac93b93b64c8ab8c7 (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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
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.TestCase;
import junit.framework.TestSuite;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.app.event.EventCartridge;
import org.apache.velocity.app.event.InvalidReferenceEventHandler;
import org.apache.velocity.context.Context;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.RuntimeServices;
import org.apache.velocity.util.RuntimeServicesAware;
import org.apache.velocity.util.introspection.Info;

import java.io.StringWriter;
import java.io.Writer;

/**
 * Tests event handling for all event handlers except IncludeEventHandler.  This is tested
 * separately due to its complexity.
 *
 * @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
 * @version $Id$
 */
public class InvalidEventHandlerTestCase
extends TestCase
{
    // @@ VELOCITY-553
    public class TestObject {
        private String nullValueAttribute = null;

        public String getNullValueAttribute() {
            return nullValueAttribute;
        }

        public String getRealString() {
            return new String("helloFooRealStr");
        }

        public String getString() {
            return new String("helloFoo");
        }

        public String getNullString() {
            return null;
        }

        public java.util.Date getNullDate() {
            return null;
        }

        @Override
        public String toString() {
            StringBuilder builder = new StringBuilder();
            builder.append("TestObject [nullValueAttribute=");
            builder.append(nullValueAttribute);
            builder.append("]");
            return builder.toString();
        }
    }
    // @@ VELOCITY-553


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

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

    public void testManualEventHandlers()
    throws Exception
    {
        TestEventCartridge te = new TestEventCartridge();

        /*
         * Test attaching the event cartridge to the context
         */
        VelocityEngine ve = new VelocityEngine();
        ve.init();

        /*
         *  lets make a Context and add the event cartridge
         */

        VelocityContext inner = new VelocityContext();

        /*
         *  Now make an event cartridge, register all the
         *  event handlers (at once) and attach it to the
         *  Context
         */

        EventCartridge ec = new EventCartridge();
        ec.addEventHandler(te);
        ec.attachToContext( inner );

        doTestInvalidReferenceEventHandler0(ve, inner);
        doTestInvalidReferenceEventHandler1(ve, inner);
        doTestInvalidReferenceEventHandler2(ve, inner);
        doTestInvalidReferenceEventHandler3(ve, inner);
        doTestInvalidReferenceEventHandler4(ve, inner);
    }

    /**
     * Test assigning the event handlers via properties
     */
    public void testConfigurationEventHandlers()
            throws Exception
    {
        VelocityEngine ve = new VelocityEngine();
        ve.setProperty(RuntimeConstants.EVENTHANDLER_INVALIDREFERENCES, TestEventCartridge.class.getName());

        ve.init();
        doTestInvalidReferenceEventHandler0(ve, null);
        doTestInvalidReferenceEventHandler1(ve, null);
        doTestInvalidReferenceEventHandler2(ve, null);
        doTestInvalidReferenceEventHandler3(ve, null);
        doTestInvalidReferenceEventHandler4(ve, null);
    }

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

    }

    /**
     * Test invalid #set
     * @param ve
     * @param vc
     * @throws Exception
     */
    private void doTestInvalidReferenceEventHandler3(VelocityEngine ve, VelocityContext vc)
    throws Exception
    {
        VelocityContext context = new VelocityContext(vc);
        context.put("a1", 5);
        context.put("a4", 5);
        context.put("b1","abc");

        String s;
        Writer w;

        // good object, bad right hand side
        s = "#set($xx = $a1.afternoon())";
        w = new StringWriter();
        try {
            ve.evaluate( context, w, "mystring", s );
            fail("Expected exception.");
        } catch (RuntimeException e) {}

        // good object, bad right hand reference
        s = "#set($yy = $q1)";
        w = new StringWriter();
        try {
            ve.evaluate( context, w, "mystring", s );
            fail("Expected exception.");
        } catch (RuntimeException e) {}

    }

    /**
     * Test invalid method calls
     * @param ve
     * @param vc
     * @throws Exception
     */
    private void doTestInvalidReferenceEventHandler2(VelocityEngine ve, VelocityContext vc)
    throws Exception
    {
        VelocityContext context = new VelocityContext(vc);
        context.put("a1", 5);
        context.put("a4", 5);
        context.put("b1","abc");

        String s;
        Writer w;

        // good object, bad method
        s = "$a1.afternoon()";
        w = new StringWriter();
        try {
            ve.evaluate( context, w, "mystring", s );
            fail("Expected exception.");
        } catch (RuntimeException e) {}

        // good object, bad method, quiet reference
        s = "$!a1.afternoon()";
        w = new StringWriter();
        ve.evaluate( context, w, "mystring", s );
        assertEquals("", w.toString());

        // bad object, bad method -- fails on get
        s = "$zz.daylight()";
        w = new StringWriter();
        try {
            ve.evaluate( context, w, "mystring", s );
            fail("Expected exception.");
        } catch (RuntimeException e) {}

        // bad object, bad method, quiet reference
        s = "$!zz.daylight()";
        w = new StringWriter();
        ve.evaluate( context, w, "mystring", s );
        assertEquals("", w.toString());

        // change result
        s = "$b1.baby()";
        w = new StringWriter();
        ve.evaluate( context, w, "mystring", s );
        assertEquals("www",w.toString());
    }

    /**
     * Test invalid gets/references
     * @param ve
     * @param vc
     * @throws Exception
     */
    private void doTestInvalidReferenceEventHandler1(VelocityEngine ve, VelocityContext vc)
    throws Exception
    {
        String result;

        VelocityContext context = new VelocityContext(vc);
        context.put("a1", 5);
        context.put("a4", 5);
        context.put("b1","abc");

        // normal - should be no calls to handler
        String s = "$a1 $a1.intValue() $b1 $b1.length() #set($c1 = '5')";
        Writer w = new StringWriter();
        ve.evaluate(context, w, "mystring", s);

        // good object, bad property
        s = "$a1.foobar";
        w = new StringWriter();
        try {
            ve.evaluate( context, w, "mystring", s );
            fail("Expected exception.");
        } catch (RuntimeException e) {}

        // same one as a quiet reference should not fail
        s = "$!a1.foobar";
        w = new StringWriter();
        ve.evaluate( context, w, "mystring", s );
        assertEquals("",w.toString());

        // same one inside an #if statement should not fail
        s = "#if($a1.foobar)yes#{else}no#end";
        w = new StringWriter();
        ve.evaluate( context, w, "mystring", s );
        assertEquals("no",w.toString());


        // bad object, bad property
        s = "$a2.foobar";
        w = new StringWriter();
        try {
            ve.evaluate( context, w, "mystring", s );
            fail("Expected exception.");
        } catch (RuntimeException e) {}

        // same one as a quiet reference should not fail
        s = "$!a2.foobar";
        w = new StringWriter();
        ve.evaluate( context, w, "mystring", s );
        assertEquals("",w.toString());

        // same one inside an #if statement should still fail
        s = "#if($a2.foobar)yes#{else}no#end";
        w = new StringWriter();
        try {
            ve.evaluate( context, w, "mystring", s );
            fail("Expected exception.");
        } catch (RuntimeException e) {}

        // except if object is tested first
        s = "#if($a2 and $a2.foobar)yes#{else}no#end";
        w = new StringWriter();
        ve.evaluate( context, w, "mystring", s );
        assertEquals("no", w.toString());

        // bad object, no property
        s = "$a3";
        w = new StringWriter();
        try {
            ve.evaluate( context, w, "mystring", s );
            fail("Expected exception.");
        } catch (RuntimeException e) {}

        // bad object, no property as quiet reference should not fail
        s = "$!a3";
        w = new StringWriter();
        ve.evaluate(context, w, "mystring", s);
        result = w.toString();
        assertEquals("", result);

        // bad object, no property as #if condition should not fail
        s = "#if($a3)yes#{else}no#end";
        w = new StringWriter();
        ve.evaluate( context, w, "mystring", s );
        result = w.toString();
        assertEquals("no", result);

        // good object, bad property; change the value
        s = "$a4.foobar";
        w = new StringWriter();
        ve.evaluate( context, w, "mystring", s );
        result = w.toString();
        assertEquals("zzz", result);

    }

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

    }



    /**
     * Test assigning the event handlers via properties
     */

    public static class TestEventCartridge
    implements InvalidReferenceEventHandler,
    RuntimeServicesAware
    {
        private RuntimeServices rs;

        public TestEventCartridge()
        {
        }

        /**
         * Required by EventHandler
         */
        @Override
        public void setRuntimeServices(RuntimeServices rs )
        {
            // make sure this is only called once
            if (this.rs == null)
                this.rs = rs;

            else
                fail("initialize called more than once.");
        }


        @Override
        public Object invalidGetMethod(Context context, String reference, Object object, String property, Info info)
        {
            // as a test, make sure this EventHandler is initialized
            if (rs == null)
                fail ("Event handler not initialized!");

            switch (reference)
            {
                // good object, bad property
                case "$a1.foobar":
                    assertEquals(Integer.valueOf(5), object);
                    assertEquals("foobar", property);
                    throw new RuntimeException("expected exception");

                // bad object, bad property
                case "$a2":
                    assertNull(object);
                    assertNull(property);
                    throw new RuntimeException("expected exception");


                // bad object, no property
                case "$a3":
                    assertNull(object);
                    assertNull(property);
                    throw new RuntimeException("expected exception");


                // good object, bad property; change the value
                case "$a4.foobar":
                    assertEquals(Integer.valueOf(5), object);
                    assertEquals("foobar", property);
                    return "zzz";


                // bad object, bad method -- fail on the object
                case "$zz":
                    assertNull(object);
                    assertNull(property);
                    throw new RuntimeException("expected exception");


                // pass q1 through
                case "$q1":

                    break;
                case "$tree.x":
                    assertEquals("x", property);
                    break;
                case "$tree.field.x":
                    assertEquals("x", property);
                    break;
                case "$tree.child.y":
                    assertEquals("y", property);
                    break;
                case "$tree.child.Field.y":
                    assertEquals("y", property);
                    break;
                default:
                    fail("invalidGetMethod: unexpected reference: " + reference);
                    break;
            }
            return null;
        }

        @Override
        public Object invalidMethod(Context context, String reference, Object object, String method, Info info)
        {
            // as a test, make sure this EventHandler is initialized
            if (rs == null)
                fail ("Event handler not initialized!");

            // good reference, bad method
            if (object.getClass().equals(Integer.class))
            {
                assertEquals("$a1.afternoon()",reference);
                assertEquals("afternoon",method);
                throw new RuntimeException("expected exception");
            }

            else if (object.getClass().equals(String.class) && "baby".equals(method))
            {
                return "www";
            }

            else
            {
                fail("Unexpected invalid method.  " + method);
            }

            return null;
        }


        @Override
        public boolean invalidSetMethod(Context context, String leftreference, String rightreference, Info info)
        {

            // as a test, make sure this EventHandler is initialized
            if (rs == null)
                fail ("Event handler not initialized!");

            // good object, bad method
            if (leftreference.equals("xx"))
            {
                assertEquals("q1.afternoon()",rightreference);
                throw new RuntimeException("expected exception");
            }
            if (leftreference.equals("yy"))
            {
                assertEquals("$q1",rightreference);
                throw new RuntimeException("expected exception");
            }
            else
            {
                fail("Unexpected left hand side.  " + leftreference);
            }

            return false;
        }

    }

    public static class Tree
    {
        String field;
        Tree child;

        public Tree()
        {

        }

        public String getField()
        {
            return field;
        }

        public void setField(String field)
        {
            this.field = field;
        }

        public Tree getChild()
        {
            return child;
        }

        public void setChild(Tree child)
        {
            this.child = child;
        }

        public String testMethod()
        {
            return "123";
        }
    }

}