KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > velocity > test > EventHandlingTestCase


1 package org.apache.velocity.test;
2
3 /*
4  * Copyright 2001,2004 The Apache Software Foundation.
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */

18
19 import java.io.StringWriter JavaDoc;
20
21 import junit.framework.TestCase;
22
23 import org.apache.velocity.app.Velocity;
24 import org.apache.velocity.VelocityContext;
25 import org.apache.velocity.runtime.log.LogSystem;
26
27 import org.apache.velocity.exception.ParseErrorException;
28 import org.apache.velocity.exception.MethodInvocationException;
29
30 import org.apache.velocity.app.event.EventCartridge;
31 import org.apache.velocity.app.event.ReferenceInsertionEventHandler;
32 import org.apache.velocity.app.event.MethodExceptionEventHandler;
33 import org.apache.velocity.app.event.NullSetEventHandler;
34
35 import org.apache.velocity.runtime.RuntimeServices;
36
37 /**
38  * Tests event handling
39  *
40  * @author <a HREF="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
41  * @version $Id: EventHandlingTestCase.java,v 1.5.10.1 2004/03/03 23:23:04 geirm Exp $
42  */

43 public class EventHandlingTestCase extends TestCase implements ReferenceInsertionEventHandler,
44                                      NullSetEventHandler, MethodExceptionEventHandler,
45                                      LogSystem
46 {
47    
48     private String JavaDoc logString = null;
49     private boolean exceptionSwitch = true;
50     private static String JavaDoc NO_REFERENCE_VALUE = "<no reference value>";
51     private static String JavaDoc REFERENCE_VALUE = "<reference value>";
52
53     /**
54      * Default constructor.
55      */

56     public EventHandlingTestCase()
57     {
58         super("EventHandlingTestCase");
59
60         try
61         {
62             /*
63              * use an alternative logger. Set it up here and pass it in.
64              */

65             
66             Velocity.setProperty(Velocity.RUNTIME_LOG_LOGSYSTEM, this );
67             Velocity.init();
68         }
69         catch (Exception JavaDoc e)
70         {
71             System.err.println("Cannot setup event handling test : " + e);
72             System.exit(1);
73         }
74     }
75
76     public void init( RuntimeServices rs )
77     {
78         /* don't need it...*/
79     }
80
81     public static junit.framework.Test suite ()
82     {
83         return new EventHandlingTestCase();
84     }
85
86     /**
87      * Runs the test.
88      */

89     public void runTest ()
90     {
91
92         /*
93          * lets make a Context and add the event cartridge
94          */

95         
96         VelocityContext inner = new VelocityContext();
97
98         /*
99          * Now make an event cartridge, register all the
100          * event handlers (at once) and attach it to the
101          * Context
102          */

103
104         EventCartridge ec = new EventCartridge();
105         ec.addEventHandler(this);
106         ec.attachToContext( inner );
107   
108         /*
109          * now wrap the event cartridge - we want to make sure that
110          * we can do this w/o harm
111          */

112
113         VelocityContext context = new VelocityContext( inner );
114
115         context.put("name", "Velocity");
116
117         try
118         {
119             /*
120              * First, the reference insertion handler
121              */

122
123             String JavaDoc s = "$name";
124             
125             StringWriter JavaDoc w = new StringWriter JavaDoc();
126             Velocity.evaluate( context, w, "mystring", s );
127             
128             if ( !w.toString().equals( REFERENCE_VALUE ))
129             {
130                 fail( "Reference insertion test 1");
131             }
132
133             /*
134              * using the same handler, we can deal with
135              * null references as well
136              */

137
138             s = "$floobie";
139
140             w = new StringWriter JavaDoc();
141             Velocity.evaluate( context, w, "mystring", s );
142
143             if ( !w.toString().equals( NO_REFERENCE_VALUE ))
144             {
145                 fail( "Reference insertion test 2");
146             }
147
148             /*
149              * now lets test setting a null value - this test
150              * should result in *no* log output.
151              */

152                  
153             s = "#set($settest = $NotAReference)";
154             w = new StringWriter JavaDoc();
155             logString = null;
156             Velocity.evaluate( context, w, "mystring", s );
157             
158             if( logString != null)
159             {
160                 fail( "NullSetEventHandler test 1");
161             }
162             
163             /*
164              * now lets test setting a null value - this test
165              * should result in log output.
166              */

167
168             s = "#set($logthis = $NotAReference)";
169             w = new StringWriter JavaDoc();
170             logString = null;
171             Velocity.evaluate( context, w, "mystring", s );
172            
173             if( logString == null)
174             {
175                 fail( "NullSetEventHandler test 1");
176             }
177
178             /*
179              * finally, we test a method exception event - we do this
180              * by putting this class in the context, and calling
181              * a method that does nothing but throw an exception.
182              * we use a little switch to turn the event handling
183              * on and off
184              *
185              * Note also how the reference insertion process
186              * happens as well
187              */

188             
189             exceptionSwitch = true;
190
191             context.put("this", this );
192
193             s = " $this.throwException()";
194             w = new StringWriter JavaDoc();
195             
196             try
197             {
198                 Velocity.evaluate( context, w, "mystring", s );
199             }
200             catch( MethodInvocationException mee )
201             {
202                 fail("MethodExceptionEvent test 1");
203             }
204             catch( Exception JavaDoc e )
205             {
206                 fail("MethodExceptionEvent test 1");
207             }
208
209             /*
210              * now, we turn the switch off, and we can see that the
211              * exception will propgate all the way up here, and
212              * wil be caught by the catch() block below
213              */

214
215             exceptionSwitch = false;
216
217             s = " $this.throwException()";
218             w = new StringWriter JavaDoc();
219
220             try
221             {
222                 Velocity.evaluate( context, w, "mystring", s );
223                 fail("MethodExceptionEvent test 2");
224             }
225             catch( MethodInvocationException mee )
226             {
227                 /*
228                  * correct - should land here...
229                  */

230             }
231             catch( Exception JavaDoc e )
232             {
233                 fail("MethodExceptionEvent test 2");
234             }
235         }
236         catch( ParseErrorException pee )
237         {
238             fail("ParseErrorException" + pee);
239         }
240         catch( MethodInvocationException mee )
241         {
242             fail("MethodInvocationException" + mee);
243         }
244         catch( Exception JavaDoc e )
245         {
246             fail("Exception" + e);
247          }
248     }
249
250     /**
251      * silly method to throw an exception to test
252      * the method invocation exception event handling
253      */

254     public void throwException()
255         throws Exception JavaDoc
256     {
257         throw new Exception JavaDoc("Hello from throwException()");
258     }
259
260     /**
261      * Event handler for when a reference is inserted into the output stream.
262      */

263     public Object JavaDoc referenceInsert( String JavaDoc reference, Object JavaDoc value )
264     {
265         /*
266          * if we have a value
267          * return a known value
268          */

269
270         String JavaDoc s = null;
271
272         if( value != null )
273         {
274             s = REFERENCE_VALUE;
275         }
276         else
277         {
278             /*
279              * we only want to deal with $floobie - anything
280              * else we let go
281              */

282             if ( reference.equals("$floobie") )
283             {
284                 s = NO_REFERENCE_VALUE;
285             }
286         }
287         return s;
288     }
289
290     /**
291      * Event handler for when the right hand side of
292      * a #set() directive is null, which results in
293      * a log message. This method gives the application
294      * a chance to 'vote' on msg generation
295      */

296     public boolean shouldLogOnNullSet( String JavaDoc lhs, String JavaDoc rhs )
297     {
298         if (lhs.equals("$settest"))
299             return false;
300         
301         return true;
302     }
303
304     /**
305      * Handles exceptions thrown during in-template method access
306      */

307     public Object JavaDoc methodException( Class JavaDoc claz, String JavaDoc method, Exception JavaDoc e )
308          throws Exception JavaDoc
309     {
310         /*
311          * only do processing if the switch is on
312          */

313
314         if( exceptionSwitch && method.equals("throwException"))
315         {
316             return "handler";
317         }
318
319         throw e;
320     }
321
322     /**
323      * handler for LogSystem interface
324      */

325     public void logVelocityMessage(int level, String JavaDoc message)
326     {
327         logString = message;
328     }
329
330 }
331
Popular Tags