KickJava   Java API By Example, From Geeks To Geeks.

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


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.RuntimeSingleton;
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  * This class provides services to the application
47  * developer, such as :
48  * <ul>
49  * <li> Simple Velocity Runtime engine initialization methods.
50  * <li> Functions to apply the template engine to streams and strings
51  * to allow embedding and dynamic template generation.
52  * <li> Methods to access Velocimacros directly.
53  * </ul>
54  *
55  * <br><br>
56  * While the most common way to use Velocity is via templates, as
57  * Velocity is a general-purpose template engine, there are other
58  * uses that Velocity is well suited for, such as processing dynamically
59  * created templates, or processing content streams.
60  *
61  * <br><br>
62  * The methods herein were developed to allow easy access to the Velocity
63  * facilities without direct spelunking of the internals. If there is
64  * something you feel is necessary to add here, please, send a patch.
65  *
66  * @author <a HREF="mailto:geirm@optonline.net">Geir Magnusson Jr.</a>
67  * @author <a HREF="mailto:Christoph.Reck@dlr.de">Christoph Reck</a>
68  * @author <a HREF="mailto:jvanzyl@apache.org">Jason van Zyl</a>
69  * @version $Id: Velocity.java,v 1.30.4.1 2004/03/03 23:22:53 geirm Exp $
70  */

71 public class Velocity implements RuntimeConstants
72 {
73     /**
74      * initialize the Velocity runtime engine, using the default
75      * properties of the Velocity distribution
76      */

77     public static void init()
78         throws Exception JavaDoc
79     {
80         RuntimeSingleton.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 static void init( String JavaDoc propsFilename )
91         throws Exception JavaDoc
92     {
93         RuntimeSingleton.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 static void init( Properties JavaDoc p )
104         throws Exception JavaDoc
105     {
106         RuntimeSingleton.init( p );
107     }
108
109     /**
110      * Set a Velocity Runtime property.
111      *
112      * @param String key
113      * @param Object value
114      */

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

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

136     public static void clearProperty(String JavaDoc key)
137     {
138         RuntimeSingleton.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 static 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         RuntimeSingleton.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 static void setExtendedProperties( ExtendedProperties configuration)
175     {
176         RuntimeSingleton.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 static Object JavaDoc getProperty( String JavaDoc key )
187     {
188         return RuntimeSingleton.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 static 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 static 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 = RuntimeSingleton.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 static 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 = RuntimeSingleton.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, RuntimeSingleton.getRuntimeServices() );
305                 }
306                 catch( Exception JavaDoc e )
307                 {
308                     RuntimeSingleton.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      * Invokes a currently registered Velocimacro with the parms provided
331      * and places the rendered stream into the writer.
332      *
333      * Note : currently only accepts args to the VM if they are in the context.
334      *
335      * @param vmName name of Velocimacro to call
336      * @param logTag string to be used for template name in case of error
337      * @param params[] args used to invoke Velocimacro. In context key format :
338      * eg "foo","bar" (rather than "$foo","$bar")
339      * @param context Context object containing data/objects used for rendering.
340      * @param writer Writer for output stream
341      * @return true if Velocimacro exists and successfully invoked, false otherwise.
342      */

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

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

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

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

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

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

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

487     public static Template getTemplate(String JavaDoc name, String JavaDoc encoding)
488         throws ResourceNotFoundException, ParseErrorException, Exception JavaDoc
489     {
490         return RuntimeSingleton.getTemplate( name, encoding );
491     }
492
493     /**
494      * <p>Determines whether a resource is accessable via the
495      * currently configured resource loaders. {@link
496      * org.apache.velocity.runtime.resource.Resource} is the generic
497      * description of templates, static content, etc.</p>
498      *
499      * <p>Note that the current implementation will <b>not</b> change
500      * the state of the system in any real way - so this cannot be
501      * used to pre-load the resource cache, as the previous
502      * implementation did as a side-effect.</p>
503      *
504      * @param resourceName The name of the resource to search for.
505      * @return Whether the resource was located.
506      */

507     public static boolean resourceExists(String JavaDoc resourceName)
508     {
509         return (RuntimeSingleton.getLoaderNameForResource(resourceName) != null);
510     }
511
512     /**
513      * Log a warning message.
514      *
515      * @param Object message to log
516      */

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

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

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

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

573      public static void setApplicationAttribute( Object JavaDoc key, Object JavaDoc value )
574      {
575         RuntimeSingleton.getRuntimeInstance().setApplicationAttribute( key, value);
576      }
577
578     /**
579      * @see #resourceExists(String)
580      * @deprecated Use resourceExists(String) instead.
581      */

582     public static boolean templateExists(String JavaDoc resourceName)
583     {
584         return resourceExists(resourceName);
585     }
586 }
587
Popular Tags