KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > velocity > app > VelocityEngine


1 package org.apache.velocity.app;
2
3 /*
4  * Copyright 2000-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.Writer JavaDoc;
20 import java.util.Properties JavaDoc;
21 import java.io.InputStream JavaDoc;
22 import java.io.IOException JavaDoc;
23 import java.io.Reader JavaDoc;
24 import java.io.BufferedReader JavaDoc;
25 import java.io.StringReader JavaDoc;
26 import java.io.InputStreamReader JavaDoc;
27 import java.io.UnsupportedEncodingException JavaDoc;
28
29 import org.apache.velocity.context.Context;
30 import org.apache.velocity.Template;
31 import org.apache.velocity.context.InternalContextAdapterImpl;
32 import org.apache.velocity.runtime.RuntimeInstance;
33 import org.apache.velocity.runtime.RuntimeConstants;
34 import org.apache.velocity.runtime.parser.node.SimpleNode;
35 import org.apache.velocity.runtime.configuration.Configuration;
36
37 import org.apache.velocity.exception.ResourceNotFoundException;
38 import org.apache.velocity.exception.ParseErrorException;
39 import org.apache.velocity.exception.MethodInvocationException;
40
41 import org.apache.velocity.runtime.parser.ParseException;
42
43 import org.apache.commons.collections.ExtendedProperties;
44
45 /**
46  * <p>
47  * This class provides a separate new-able instance of the
48  * Velocity template engine. The alternative model for use
49  * is using the Velocity class which employs the singleton
50  * model.
51  * </p>
52  *
53  * <p>
54  * Please ensure that you call one of the init() variants.
55  * This is critical for proper behavior.
56  * </p>
57  *
58  * <p> Coming soon : Velocity will call
59  * the parameter-less init() at the first use of this class
60  * if the init() wasn't explicitly called. While this will
61  * ensure that Velocity functions, it almost certainly won't
62  * function in the way you intend, so please make sure to
63  * call init().
64  * </p>
65  *
66  * @author <a HREF="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
67  * @version $Id: VelocityEngine.java,v 1.6.4.1 2004/03/03 23:22:53 geirm Exp $
68  */

69 public class VelocityEngine implements RuntimeConstants
70 {
71     private RuntimeInstance ri = new RuntimeInstance();
72
73     /**
74      * initialize the Velocity runtime engine, using the default
75      * properties of the Velocity distribution
76      */

77     public void init()
78         throws Exception JavaDoc
79     {
80         ri.init();
81     }
82
83     /**
84      * initialize the Velocity runtime engine, using default properties
85      * plus the properties in the properties file passed in as the arg
86      *
87      * @param propsFilename file containing properties to use to initialize
88      * the Velocity runtime
89      */

90     public void init( String JavaDoc propsFilename )
91         throws Exception JavaDoc
92     {
93         ri.init(propsFilename);
94     }
95
96     /**
97      * initialize the Velocity runtime engine, using default properties
98      * plus the properties in the passed in java.util.Properties object
99      *
100      * @param p Proprties object containing initialization properties
101      *
102      */

103     public void init( Properties JavaDoc p )
104         throws Exception JavaDoc
105     {
106         ri.init( p );
107     }
108     
109     /**
110      * Set a Velocity Runtime property.
111      *
112      * @param String key
113      * @param Object value
114      */

115     public void setProperty(String JavaDoc key, Object JavaDoc value)
116     {
117         ri.setProperty(key,value);
118     }
119
120     /**
121      * Add a Velocity Runtime property.
122      *
123      * @param String key
124      * @param Object value
125      */

126     public void addProperty(String JavaDoc key, Object JavaDoc value)
127     {
128         ri.addProperty(key,value);
129     }
130
131     /**
132      * Clear a Velocity Runtime property.
133      *
134      * @param key of property to clear
135      */

136     public void clearProperty(String JavaDoc key)
137     {
138         ri.clearProperty(key);
139     }
140
141     /**
142      * Set an entire configuration at once. This is
143      * useful in cases where the parent application uses
144      * the Configuration class and the velocity configuration
145      * is a subset of the parent application's configuration.
146      *
147      * @param Configuration configuration
148      *
149      * @deprecated Use
150      * {@link #setExtendedProperties( ExtendedProperties ) }
151      */

152     public void setConfiguration(Configuration configuration)
153     {
154         /*
155          * Yuk. We added a little helper to Configuration to
156          * help with deprecation. The Configuration class
157          * contains a 'shadow' ExtendedProperties
158          */

159
160         ExtendedProperties ep = configuration.getExtendedProperties();
161
162         ri.setConfiguration( ep );
163     }
164
165     /**
166      * Set an entire configuration at once. This is
167      * useful in cases where the parent application uses
168      * the ExtendedProperties class and the velocity configuration
169      * is a subset of the parent application's configuration.
170      *
171      * @param ExtendedProperties configuration
172      *
173      */

174     public void setExtendedProperties( ExtendedProperties configuration)
175     {
176         ri.setConfiguration( configuration );
177     }
178
179     /**
180      * Get a Velocity Runtime property.
181      *
182      * @param key property to retrieve
183      * @return property value or null if the property
184      * not currently set
185      */

186     public Object JavaDoc getProperty( String JavaDoc key )
187     {
188         return ri.getProperty( key );
189     }
190
191     /**
192      * renders the input string using the context into the output writer.
193      * To be used when a template is dynamically constructed, or want to use
194      * Velocity as a token replacer.
195      *
196      * @param context context to use in rendering input string
197      * @param out Writer in which to render the output
198      * @param logTag string to be used as the template name for log
199      * messages in case of error
200      * @param instring input string containing the VTL to be rendered
201      *
202      * @return true if successful, false otherwise. If false, see
203      * Velocity runtime log
204      */

205     public boolean evaluate( Context context, Writer JavaDoc out,
206                                      String JavaDoc logTag, String JavaDoc instring )
207         throws ParseErrorException, MethodInvocationException,
208             ResourceNotFoundException, IOException JavaDoc
209     {
210         return evaluate( context, out, logTag, new BufferedReader JavaDoc( new StringReader JavaDoc( instring )) );
211     }
212
213     /**
214      * Renders the input stream using the context into the output writer.
215      * To be used when a template is dynamically constructed, or want to
216      * use Velocity as a token replacer.
217      *
218      * @param context context to use in rendering input string
219      * @param out Writer in which to render the output
220      * @param logTag string to be used as the template name for log messages
221      * in case of error
222      * @param instream input stream containing the VTL to be rendered
223      *
224      * @return true if successful, false otherwise. If false, see
225      * Velocity runtime log
226      * @deprecated Use
227      * {@link #evaluate( Context context, Writer writer,
228      * String logTag, Reader reader ) }
229      */

230     public boolean evaluate( Context context, Writer JavaDoc writer,
231                                     String JavaDoc logTag, InputStream JavaDoc instream )
232         throws ParseErrorException, MethodInvocationException,
233             ResourceNotFoundException, IOException JavaDoc
234     {
235         /*
236          * first, parse - convert ParseException if thrown
237          */

238
239         BufferedReader JavaDoc br = null;
240         String JavaDoc encoding = null;
241
242         try
243         {
244             encoding = ri.getString(INPUT_ENCODING,ENCODING_DEFAULT);
245             br = new BufferedReader JavaDoc( new InputStreamReader JavaDoc( instream, encoding));
246         }
247         catch( UnsupportedEncodingException JavaDoc uce )
248         {
249             String JavaDoc msg = "Unsupported input encoding : " + encoding
250                 + " for template " + logTag;
251             throw new ParseErrorException( msg );
252         }
253
254         return evaluate( context, writer, logTag, br );
255     }
256
257     /**
258      * Renders the input reader using the context into the output writer.
259      * To be used when a template is dynamically constructed, or want to
260      * use Velocity as a token replacer.
261      *
262      * @param context context to use in rendering input string
263      * @param out Writer in which to render the output
264      * @param logTag string to be used as the template name for log messages
265      * in case of error
266      * @param reader Reader containing the VTL to be rendered
267      *
268      * @return true if successful, false otherwise. If false, see
269      * Velocity runtime log
270      *
271      * @since Velocity v1.1
272      */

273     public boolean evaluate( Context context, Writer JavaDoc writer,
274                                     String JavaDoc logTag, Reader JavaDoc reader )
275         throws ParseErrorException, MethodInvocationException,
276             ResourceNotFoundException,IOException JavaDoc
277     {
278         SimpleNode nodeTree = null;
279         
280         try
281         {
282             nodeTree = ri.parse( reader, logTag );
283         }
284         catch ( ParseException pex )
285         {
286             throw new ParseErrorException( pex.getMessage() );
287         }
288      
289         /*
290          * now we want to init and render
291          */

292
293         if (nodeTree != null)
294         {
295             InternalContextAdapterImpl ica =
296                 new InternalContextAdapterImpl( context );
297             
298             ica.pushCurrentTemplateName( logTag );
299             
300             try
301             {
302                 try
303                 {
304                     nodeTree.init( ica, ri );
305                 }
306                 catch( Exception JavaDoc e )
307                 {
308                     ri.error("Velocity.evaluate() : init exception for tag = "
309                                   + logTag + " : " + e );
310                 }
311                 
312                 /*
313                  * now render, and let any exceptions fly
314                  */

315
316                 nodeTree.render( ica, writer );
317             }
318             finally
319             {
320                 ica.popCurrentTemplateName();
321             }
322             
323             return true;
324         }
325         
326         return false;
327     }
328
329    
330     /**
331      * Invokes a currently registered Velocimacro with the parms provided
332      * and places the rendered stream into the writer.
333      *
334      * Note : currently only accepts args to the VM if they are in the context.
335      *
336      * @param vmName name of Velocimacro to call
337      * @param logTag string to be used for template name in case of error
338      * @param params[] args used to invoke Velocimacro. In context key format :
339      * eg "foo","bar" (rather than "$foo","$bar")
340      * @param context Context object containing data/objects used for rendering.
341      * @param writer Writer for output stream
342      * @return true if Velocimacro exists and successfully invoked, false otherwise.
343      */

344     public boolean invokeVelocimacro( String JavaDoc vmName, String JavaDoc logTag,
345                                               String JavaDoc params[], Context context,
346                                               Writer JavaDoc writer )
347         throws Exception JavaDoc
348     {
349         /*
350          * check parms
351          */

352
353         if ( vmName == null || params == null || context == null
354              || writer == null || logTag == null)
355         {
356             ri.error( "VelocityEngine.invokeVelocimacro() : invalid parameter");
357             return false;
358         }
359
360         /*
361          * does the VM exist?
362          */

363           
364         if (!ri.isVelocimacro( vmName, logTag ))
365         {
366             ri.error( "VelocityEngine.invokeVelocimacro() : VM '"+ vmName
367                            + "' not registered.");
368             return false;
369         }
370
371         /*
372          * now just create the VM call, and use evaluate
373          */

374
375         StringBuffer JavaDoc construct = new StringBuffer JavaDoc("#");
376
377         construct.append( vmName );
378         construct.append( "(" );
379  
380         for( int i = 0; i < params.length; i++)
381         {
382             construct.append( " $" );
383             construct.append( params[i] );
384         }
385
386         construct.append(" )");
387
388         try
389         {
390             boolean retval = evaluate( context, writer,
391                                          logTag, construct.toString() );
392   
393             return retval;
394         }
395         catch( Exception JavaDoc e )
396         {
397             ri.error( "VelocityEngine.invokeVelocimacro() : error " + e );
398             throw e;
399         }
400     }
401
402     /**
403      * merges a template and puts the rendered stream into the writer
404      *
405      * @param templateName name of template to be used in merge
406      * @param context filled context to be used in merge
407      * @param writer writer to write template into
408      *
409      * @return true if successful, false otherwise. Errors
410      * logged to velocity log.
411      * * @deprecated Use
412      * {@link #mergeTemplate( String templateName, String encoding,
413      * Context context, Writer writer )}
414      */

415     public boolean mergeTemplate( String JavaDoc templateName,
416                                          Context context, Writer JavaDoc writer )
417         throws ResourceNotFoundException, ParseErrorException, MethodInvocationException, Exception JavaDoc
418     {
419         return mergeTemplate( templateName, ri.getString(INPUT_ENCODING,ENCODING_DEFAULT),
420                                context, writer );
421     }
422
423     /**
424      * merges a template and puts the rendered stream into the writer
425      *
426      * @param templateName name of template to be used in merge
427      * @param encoding encoding used in template
428      * @param context filled context to be used in merge
429      * @param writer writer to write template into
430      *
431      * @return true if successful, false otherwise. Errors
432      * logged to velocity log
433      *
434      * @since Velocity v1.1
435      */

436     public boolean mergeTemplate( String JavaDoc templateName, String JavaDoc encoding,
437                                       Context context, Writer JavaDoc writer )
438         throws ResourceNotFoundException, ParseErrorException, MethodInvocationException, Exception JavaDoc
439     {
440         Template template = ri.getTemplate(templateName, encoding);
441         
442         if ( template == null )
443         {
444             ri.error("Velocity.parseTemplate() failed loading template '"
445                           + templateName + "'" );
446             return false;
447         }
448         else
449         {
450             template.merge(context, writer);
451             return true;
452          }
453     }
454
455     /**
456      * Returns a <code>Template</code> from the Velocity
457      * resource management system.
458      *
459      * @param name The file name of the desired template.
460      * @return The template.
461      * @throws ResourceNotFoundException if template not found
462      * from any available source.
463      * @throws ParseErrorException if template cannot be parsed due
464      * to syntax (or other) error.
465      * @throws Exception if an error occurs in template initialization
466      */

467     public Template getTemplate(String JavaDoc name)
468         throws ResourceNotFoundException, ParseErrorException, Exception JavaDoc
469     {
470         return ri.getTemplate( name );
471     }
472
473     /**
474      * Returns a <code>Template</code> from the Velocity
475      * resource management system.
476      *
477      * @param name The file name of the desired template.
478      * @param encoding The character encoding to use for the template.
479      * @return The template.
480      * @throws ResourceNotFoundException if template not found
481      * from any available source.
482      * @throws ParseErrorException if template cannot be parsed due
483      * to syntax (or other) error.
484      * @throws Exception if an error occurs in template initialization
485      *
486      * @since Velocity v1.1
487      */

488     public Template getTemplate(String JavaDoc name, String JavaDoc encoding)
489         throws ResourceNotFoundException, ParseErrorException, Exception JavaDoc
490     {
491         return ri.getTemplate( name, encoding );
492     }
493
494     /**
495      * Determines if a template is accessable via the currently
496      * configured resource loaders.
497      * <br><br>
498      * Note that the current implementation will <b>not</b>
499      * change the state of the system in any real way - so this
500      * cannot be used to pre-load the resource cache, as the
501      * previous implementation did as a side-effect.
502      * <br><br>
503      * The previous implementation exhibited extreme lazyness and
504      * sloth, and the author has been flogged.
505      *
506      * @param templateName name of the temlpate to search for
507      * @return true if found, false otherwise
508      */

509     public boolean templateExists( String JavaDoc templateName )
510     {
511         return (ri.getLoaderNameForResource(templateName) != null);
512     }
513     
514     /**
515      * Log a warning message.
516      *
517      * @param Object message to log
518      */

519     public void warn(Object JavaDoc message)
520     {
521         ri.warn( message );
522     }
523     
524     /**
525      * Log an info message.
526      *
527      * @param Object message to log
528      */

529     public void info(Object JavaDoc message)
530     {
531         ri.info( message );
532     }
533     
534     /**
535      * Log an error message.
536      *
537      * @param Object message to log
538      */

539     public void error(Object JavaDoc message)
540     {
541         ri.error( message );
542     }
543     
544     /**
545      * Log a debug message.
546      *
547      * @param Object message to log
548      */

549     public void debug(Object JavaDoc message)
550     {
551         ri.debug( message );
552     }
553
554     /**
555      * <p>
556      * Set the an ApplicationAttribue, which is an Object
557      * set by the application which is accessable from
558      * any component of the system that gets a RuntimeServices.
559      * This allows communication between the application
560      * environment and custom pluggable components of the
561      * Velocity engine, such as loaders and loggers.
562      * </p>
563      *
564      * <p>
565      * Note that there is no enfocement or rules for the key
566      * used - it is up to the application developer. However, to
567      * help make the intermixing of components possible, using
568      * the target Class name (e.g. com.foo.bar ) as the key
569      * might help avoid collision.
570      * </p>
571      *
572      * @param key object 'name' under which the object is stored
573      * @param value object to store under this key
574      */

575      public void setApplicationAttribute( Object JavaDoc key, Object JavaDoc value )
576      {
577         ri.setApplicationAttribute( key, value );
578      }
579 }
580
581
582
583
Popular Tags