KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > velocity > test > misc > Test


1 package org.apache.velocity.test.misc;
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.BufferedWriter JavaDoc;
20 import java.io.File JavaDoc;
21 import java.io.FileInputStream JavaDoc;
22 import java.io.OutputStreamWriter JavaDoc;
23 import java.io.Writer JavaDoc;
24 import java.io.StringWriter JavaDoc;
25
26 import java.util.ArrayList JavaDoc;
27 import java.util.Hashtable JavaDoc;
28 import java.util.HashMap JavaDoc;
29 import java.util.Properties JavaDoc;
30 import java.util.Stack JavaDoc;
31 import java.util.Vector JavaDoc;
32 import java.util.Enumeration JavaDoc;
33
34 import org.apache.velocity.VelocityContext;
35 import org.apache.velocity.Template;
36
37 import org.apache.velocity.app.FieldMethodizer;
38 import org.apache.velocity.app.Velocity;
39
40 import org.apache.velocity.exception.ParseErrorException;
41 import org.apache.velocity.exception.ResourceNotFoundException;
42 import org.apache.velocity.exception.MethodInvocationException;
43
44 import org.apache.velocity.runtime.RuntimeSingleton;
45 import org.apache.velocity.test.provider.TestProvider;
46
47 import org.apache.velocity.app.event.EventCartridge;
48 import org.apache.velocity.app.event.ReferenceInsertionEventHandler;
49 import org.apache.velocity.app.event.MethodExceptionEventHandler;
50 import org.apache.velocity.app.event.NullSetEventHandler;
51
52 import org.apache.velocity.context.Context;
53
54
55 /**
56  * This class the testbed for Velocity. It is used to
57  * test all the directives support by Velocity.
58  *
59  * @author <a HREF="mailto:jvanzyl@apache.org">Jason van Zyl</a>
60  * @author <a HREF="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
61  * @version $Id: Test.java,v 1.34.8.1 2004/03/03 23:23:05 geirm Exp $
62  */

63 public class Test implements ReferenceInsertionEventHandler,
64                              NullSetEventHandler,
65                              MethodExceptionEventHandler
66 {
67     /**
68      * Cache of writers
69      */

70     private static Stack JavaDoc writerStack = new Stack JavaDoc();
71
72     public Test(String JavaDoc templateFile, String JavaDoc encoding)
73     {
74         Writer JavaDoc writer = null;
75         TestProvider provider = new TestProvider();
76         ArrayList JavaDoc al = provider.getCustomers();
77         Hashtable JavaDoc h = new Hashtable JavaDoc();
78   
79         /*
80          * put this in to test introspection $h.Bar or $h.get("Bar") etc
81          */

82         
83         h.put("Bar", "this is from a hashtable!");
84         h.put("Foo", "this is from a hashtable too!");
85        
86         /*
87          * adding simple vector with strings for testing late introspection stuff
88          */

89
90         Vector JavaDoc v = new Vector JavaDoc();
91
92         String JavaDoc str = "mystr";
93
94         v.addElement( new String JavaDoc("hello") );
95         v.addElement( new String JavaDoc("hello2") );
96         v.addElement( str );
97
98         try
99         {
100             /*
101              * this is another way to do properties when initializing Runtime.
102              * make a Properties
103              */

104
105             Properties JavaDoc p = new Properties JavaDoc();
106
107             /*
108              * now, if you want to, load it from a file (or whatever)
109              */

110             
111             try
112             {
113                 FileInputStream JavaDoc fis = new FileInputStream JavaDoc(
114                     new File JavaDoc("velocity.properties" ));
115             
116                 if( fis != null)
117                     p.load( fis );
118             }
119             catch (Exception JavaDoc ex)
120             {
121                 /* no worries. no file... */
122             }
123
124             /*
125              * iterate out the properties
126              */

127
128             for( Enumeration JavaDoc e = p.propertyNames(); e.hasMoreElements(); )
129             {
130                 String JavaDoc el = (String JavaDoc) e.nextElement();
131
132                 Velocity.setProperty( el, p.getProperty( el ) );
133             }
134
135             /*
136              * add some individual properties if you wish
137              */

138
139
140             Velocity.setProperty(Velocity.RUNTIME_LOG_ERROR_STACKTRACE, "true");
141             Velocity.setProperty(Velocity.RUNTIME_LOG_WARN_STACKTRACE, "true");
142             Velocity.setProperty(Velocity.RUNTIME_LOG_INFO_STACKTRACE, "true");
143
144             /*
145              * use an alternative logger. Set it up here and pass it in.
146              */

147             
148             // SimpleLogSystem sls = new SimpleLogSystem("velocity_simple.log");
149

150             // Velocity.setProperty(Velocity.RUNTIME_LOG_LOGSYSTEM, sls );
151

152             /*
153              * and now call init
154              */

155
156             Velocity.init();
157
158             /*
159              * now, do what we want to do. First, get the Template
160              */

161
162             if (templateFile == null)
163             {
164                 templateFile = "examples/example.vm";
165             }
166          
167
168             Template template = null;
169
170             try
171             {
172                 template = RuntimeSingleton.getTemplate(templateFile, encoding);
173             }
174             catch( ResourceNotFoundException rnfe )
175             {
176                 System.out.println("Test : RNFE : Cannot find template " + templateFile );
177             }
178             catch( ParseErrorException pee )
179             {
180                 System.out.println("Test : Syntax error in template " + templateFile + ":" + pee );
181             }
182
183             /*
184              * now, make a Context object and populate it.
185              */

186
187             VelocityContext context = new VelocityContext();
188
189             context.put("provider", provider);
190             context.put("name", "jason");
191             context.put("providers", provider.getCustomers2());
192             context.put("list", al);
193             context.put("hashtable", h);
194             context.put("search", provider.getSearch());
195             context.put("relatedSearches", provider.getRelSearches());
196             context.put("searchResults", provider.getRelSearches());
197             context.put("menu", provider.getMenu());
198             context.put("stringarray", provider.getArray());
199             context.put("vector", v);
200             context.put("mystring", new String JavaDoc());
201             context.put("hashmap", new HashMap JavaDoc() );
202             context.put("runtime", new FieldMethodizer( "org.apache.velocity.runtime.RuntimeSingleton" ));
203             context.put("fmprov", new FieldMethodizer( provider ));
204             context.put("Floog", "floogie woogie");
205             context.put("geirstring", str );
206             context.put("mylong", new Long JavaDoc(5) );
207             
208             /*
209              * we want to make sure we test all types of iterative objects
210              * in #foreach()
211              */

212              
213             int intarr[] = { 10, 20, 30, 40, 50 };
214
215             Object JavaDoc[] oarr = { "a","b","c","d" } ;
216             
217             context.put( "collection", v );
218             context.put("iterator", v.iterator());
219             context.put("map", h );
220             context.put("obarr", oarr );
221             context.put("intarr", intarr );
222             
223             String JavaDoc stest = " My name is $name -> $Floog";
224             StringWriter JavaDoc w = new StringWriter JavaDoc();
225             // Velocity.evaluate( context, w, "evaltest",stest );
226
// System.out.println("Eval = " + w );
227

228             w = new StringWriter JavaDoc();
229             //Velocity.mergeTemplate( "mergethis.vm", context, w );
230
//System.out.println("Merge = " + w );
231

232             w = new StringWriter JavaDoc();
233             //Velocity.invokeVelocimacro( "floog", "test", new String[2], context, w );
234
//System.out.println("Invoke = " + w );
235

236
237             /*
238              * event cartridge stuff
239              */

240
241             EventCartridge ec = new EventCartridge();
242             ec.addEventHandler(this);
243             ec.attachToContext( context );
244
245             /*
246              * make a writer, and merge the template 'against' the context
247              */

248
249             VelocityContext vc = new VelocityContext( context );
250
251             if( template != null)
252             {
253                 writer = new BufferedWriter JavaDoc(new OutputStreamWriter JavaDoc(System.out, encoding));
254                 template.merge( vc , writer);
255                 writer.flush();
256                 writer.close();
257             }
258  
259         }
260         catch( MethodInvocationException mie )
261         {
262             System.out.println("MIE : " + mie );
263         }
264         catch( Exception JavaDoc e )
265         {
266             RuntimeSingleton.error( "Test- exception : " + e);
267             e.printStackTrace();
268
269         }
270     }
271
272     public Object JavaDoc referenceInsert( String JavaDoc reference, Object JavaDoc value )
273     {
274         if (value != null)
275             ; // System.out.println("Woo! referenceInsert : " + reference + " = " + value.toString() );
276
return value;
277     }
278
279     public boolean shouldLogOnNullSet( String JavaDoc lhs, String JavaDoc rhs )
280     {
281         // System.out.println("Woo2! nullSetLogMessage : " + lhs + " : RHS = " + rhs);
282

283         if (lhs.equals("$woogie"))
284             return false;
285         
286         return true;
287     }
288
289    public Object JavaDoc methodException( Class JavaDoc claz, String JavaDoc method, Exception JavaDoc e )
290          throws Exception JavaDoc
291     {
292         if (method.equals("getThrow"))
293             return "I should have thrown";
294
295         throw e;
296     }
297
298
299     public static void main(String JavaDoc[] args)
300     {
301         Test t;
302
303         String JavaDoc encoding = "ISO-8859-1";
304
305         if( args.length > 1 )
306             encoding = args[1];
307
308         t = new Test(args[0], encoding);
309     }
310 }
311
312
313
314
315
316
317
318
Popular Tags