KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > EventExample


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

16
17 import java.io.StringWriter JavaDoc;
18 import java.util.Properties JavaDoc;
19 import org.apache.velocity.app.Velocity;
20 import org.apache.velocity.VelocityContext;
21
22 import org.apache.velocity.exception.ParseErrorException;
23 import org.apache.velocity.exception.MethodInvocationException;
24
25 import org.apache.velocity.runtime.log.LogSystem;
26 import org.apache.velocity.runtime.RuntimeServices;
27
28 import org.apache.velocity.app.event.EventCartridge;
29 import org.apache.velocity.app.event.ReferenceInsertionEventHandler;
30 import org.apache.velocity.app.event.MethodExceptionEventHandler;
31 import org.apache.velocity.app.event.NullSetEventHandler;
32
33 import org.apache.velocity.context.Context;
34
35 /**
36  * This class is a simple demonstration of how the event handling
37  * features of the Velocity Servlet Engine are used. It uses a
38  * custom logger as well to check the log message stream
39  * when testing the NullSetEventHandler
40  *
41  * @author <a HREF="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
42  * @version $Id: EventExample.java,v 1.3.10.1 2004/03/04 00:18:29 geirm Exp $
43  */

44
45 public class EventExample implements ReferenceInsertionEventHandler,
46                                      NullSetEventHandler, MethodExceptionEventHandler,
47                                      LogSystem
48 {
49
50     private boolean logOutput = false;
51     private boolean exceptionSwitch = false;
52
53     public static void main( String JavaDoc args[] )
54     {
55         EventExample ee = new EventExample();
56     }
57
58     public EventExample()
59     {
60         try
61         {
62             /*
63              * this class implements the LogSystem interface, so we
64              * can use it as a logger for Velocity
65              */

66             
67             Velocity.setProperty(Velocity.RUNTIME_LOG_LOGSYSTEM, this );
68             Velocity.init();
69         }
70         catch(Exception JavaDoc e)
71         {
72             System.out.println("Problem initializing Velocity : " + e );
73             return;
74         }
75
76         /*
77          * lets make a Context and add some data
78          */

79
80         VelocityContext context = new VelocityContext();
81
82         context.put("name", "Velocity");
83
84         /*
85          * Now make an event cartridge, register all the
86          * event handlers (at once) and attach it to the
87          * Context
88          */

89
90         EventCartridge ec = new EventCartridge();
91         ec.addEventHandler(this);
92         ec.attachToContext( context );
93   
94         try
95         {
96             /*
97              * lets test each type of event handler individually
98              * using 'dynamic' templates
99              *
100              * First, the reference insertion handler
101              */

102
103             System.out.println("");
104             System.out.println("Velocity Event Handling Demo");
105             System.out.println("============================");
106             System.out.println("");
107
108             String JavaDoc s = "The word 'Velocity' should be bounded by emoticons : $name.";
109             
110             StringWriter JavaDoc w = new StringWriter JavaDoc();
111             Velocity.evaluate( context, w, "mystring", s );
112
113             System.out.println("Reference Insertion Test : ");
114             System.out.println(" " + w.toString());
115             System.out.println("");
116
117             /*
118              * using the same handler, we can deal with
119              * null references as well
120              */

121
122             s = "There is no reference $floobie, $nullvalue or anything in the brackets : >$!silentnull<";
123
124             w = new StringWriter JavaDoc();
125             Velocity.evaluate( context, w, "mystring", s );
126
127             System.out.println("Reference Insertion Test with null references : ");
128             System.out.println(" " + w.toString());
129             System.out.println("");
130
131             /*
132              * now lets test setting a null value - this test
133              * should result in *no* log output.
134              * Turn on the logger output.
135              */

136
137             logOutput = true;
138
139             s = "#set($settest = $NotAReference)";
140             w = new StringWriter JavaDoc();
141
142             System.out.println("NullSetEventHandler test : " );
143             System.out.print(" There should be nothing between >");
144             Velocity.evaluate( context, w, "mystring", s );
145             System.out.println("< the brackets.");
146             System.out.println("");
147
148             /*
149              * now lets test setting a null value - this test
150              * should result in log output.
151              */

152
153             s = "#set($logthis = $NotAReference)";
154             w = new StringWriter JavaDoc();
155
156             System.out.println("NullSetEventHandler test : " );
157             System.out.print(" There should be a log message between >");
158             Velocity.evaluate( context, w, "mystring", s );
159             System.out.println("< the brackets.");
160             System.out.println("");
161
162             logOutput = false;
163
164             /*
165              * finally, we test a method exception event - we do this
166              * by putting this class in the context, and calling
167              * a method that does nothing but throw an exception.
168              * we use a little switch to turn the event handling
169              * on and off
170              *
171              * Note also how the reference insertion process
172              * happens as well
173              */

174             
175             exceptionSwitch = true;
176
177             context.put("this", this );
178
179             s = " $this.throwException()";
180             w = new StringWriter JavaDoc();
181
182             System.out.println("MethodExceptionEventHandler test : " );
183             System.out.print(" This exception will be controlled and converted into a string : ");
184             Velocity.evaluate( context, w, "mystring", s );
185             System.out.println(" " + w.toString());
186             System.out.println("");
187
188             /*
189              * now, we turn the switch off, and we can see that the
190              * exception will propgate all the way up here, and
191              * wil be caught by the catch() block below
192              */

193
194             exceptionSwitch = false;
195
196             s = " $this.throwException()";
197             w = new StringWriter JavaDoc();
198
199             System.out.println("MethodExceptionEventHandler test : " );
200             System.out.println(" This exception will NOT be controlled. "
201                              + " The next thing you should see is the catch() output ");
202             Velocity.evaluate( context, w, "mystring", s );
203             System.out.println("If you see this, it didn't work!");
204
205         }
206         catch( ParseErrorException pee )
207         {
208             /*
209              * thrown if something is wrong with the
210              * syntax of our template string
211              */

212             System.out.println("ParseErrorException : " + pee );
213         }
214         catch( MethodInvocationException mee )
215         {
216             /*
217              * thrown if a method of a reference
218              * called by the template
219              * throws an exception. That won't happen here
220              * as we aren't calling any methods in this
221              * example, but we have to catch them anyway
222              */

223             System.out.println(" Catch Block : MethodInvocationException : " + mee );
224         }
225         catch( Exception JavaDoc e )
226         {
227             System.out.println("Exception : " + e );
228         }
229     }
230
231     /**
232      * silly method to throw an exception to demonstrate
233      * the method invocation exception event handling
234      */

235     public void throwException()
236         throws Exception JavaDoc
237     {
238         throw new Exception JavaDoc("Hello from throwException()");
239     }
240
241     /**
242      * Event handler for when a reference is inserted into the output stream.
243      */

244     public Object JavaDoc referenceInsert( String JavaDoc reference, Object JavaDoc value )
245     {
246         /*
247          * if we have a value
248          * lets decorate the reference with emoticons
249          */

250
251         String JavaDoc s = null;
252
253         if( value != null )
254         {
255             s = " ;) " + value.toString() + " :-)";
256         }
257         else
258         {
259             /*
260              * we only want to deal with $floobie - anything
261              * else we let go
262              */

263             if ( reference.equals("floobie") )
264             {
265                 s = "<no floobie value>";
266             }
267         }
268         return s;
269     }
270
271     /**
272      * Event handler for when the right hand side of
273      * a #set() directive is null, which results in
274      * a log message. This method gives the application
275      * a chance to 'vote' on msg generation
276      */

277     public boolean shouldLogOnNullSet( String JavaDoc lhs, String JavaDoc rhs )
278     {
279         if (lhs.equals("$settest"))
280             return false;
281         
282         return true;
283     }
284
285     public Object JavaDoc methodException( Class JavaDoc claz, String JavaDoc method, Exception JavaDoc e )
286          throws Exception JavaDoc
287     {
288         /*
289          * only do processing if the switch is on
290          */

291
292         if( exceptionSwitch && method.equals("throwException"))
293         {
294             return "Hello from the methodException() event handler method.";
295         }
296
297         throw e;
298     }
299
300     /**
301      * Required init method for LogSystem
302      * to get access to RuntimeServices
303      */

304      public void init( RuntimeServices rs )
305      {
306         return;
307      }
308
309     /**
310      * This is the key method needed to implement a logging interface
311      * for Velocity.
312      */

313     public void logVelocityMessage(int level, String JavaDoc message)
314     {
315         if (logOutput)
316         {
317             System.out.print("Velocity Log : level : " + level + " msg : " + message);
318         }
319     }
320
321 }
322
Popular Tags