View Javadoc

1   package org.apache.velocity.runtime;
2   
3   /*
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *   http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing,
15   * software distributed under the License is distributed on an
16   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17   * KIND, either express or implied.  See the License for the
18   * specific language governing permissions and limitations
19   * under the License.    
20   */
21  
22  import java.io.Reader;
23  import java.io.Writer;
24  import java.util.Properties;
25  
26  import org.apache.commons.collections.ExtendedProperties;
27  import org.apache.velocity.Template;
28  import org.apache.velocity.app.event.EventCartridge;
29  import org.apache.velocity.context.Context;
30  import org.apache.velocity.exception.MethodInvocationException;
31  import org.apache.velocity.exception.ParseErrorException;
32  import org.apache.velocity.exception.ResourceNotFoundException;
33  import org.apache.velocity.runtime.directive.Directive;
34  import org.apache.velocity.runtime.log.Log;
35  import org.apache.velocity.runtime.parser.ParseException;
36  import org.apache.velocity.runtime.parser.Parser;
37  import org.apache.velocity.runtime.parser.node.Node;
38  import org.apache.velocity.runtime.parser.node.SimpleNode;
39  import org.apache.velocity.runtime.resource.ContentResource;
40  import org.apache.velocity.util.introspection.Introspector;
41  import org.apache.velocity.util.introspection.Uberspect;
42  
43  
44  /**
45   * Interface for internal runtime services that are needed by the
46   * various components w/in Velocity.  This was taken from the old
47   * Runtime singleton, and anything not necessary was removed.
48   *
49   *  Currently implemented by RuntimeInstance.
50   *
51   * @author <a href="mailto:geirm@optonline.net">Geir Magusson Jr.</a>
52   * @version $Id: RuntimeServices.java 898050 2010-01-11 20:15:31Z nbubna $
53   */
54  public interface RuntimeServices extends RuntimeLogger
55  {
56  
57     /**
58       * This is the primary initialization method in the Velocity
59       * Runtime. The systems that are setup/initialized here are
60       * as follows:
61       *
62       * <ul>
63       *   <li>Logging System</li>
64       *   <li>ResourceManager</li>
65       *   <li>Parser Pool</li>
66       *   <li>Global Cache</li>
67       *   <li>Static Content Include System</li>
68       *   <li>Velocimacro System</li>
69       * </ul>
70       */
71      public void init();
72  
73      /**
74       * Allows an external system to set a property in
75       * the Velocity Runtime.
76       *
77       * @param key property key
78       * @param value property value
79       */
80      public  void setProperty(String key, Object value);
81  
82      /**
83       * Allow an external system to set an ExtendedProperties
84       * object to use. This is useful where the external
85       * system also uses the ExtendedProperties class and
86       * the velocity configuration is a subset of
87       * parent application's configuration. This is
88       * the case with Turbine.
89       *
90       * @param configuration
91       */
92      public void setConfiguration( ExtendedProperties configuration);
93  
94      /**
95       * Add a property to the configuration. If it already
96       * exists then the value stated here will be added
97       * to the configuration entry. For example, if
98       *
99       * resource.loader = file
100      *
101      * is already present in the configuration and you
102      *
103      * addProperty("resource.loader", "classpath")
104      *
105      * Then you will end up with a Vector like the
106      * following:
107      *
108      * ["file", "classpath"]
109      *
110      * @param key
111      * @param value
112      */
113     public void addProperty(String key, Object value);
114 
115     /**
116      * Clear the values pertaining to a particular
117      * property.
118      *
119      * @param key of property to clear
120      */
121     public void clearProperty(String key);
122 
123     /**
124      *  Allows an external caller to get a property.  The calling
125      *  routine is required to know the type, as this routine
126      *  will return an Object, as that is what properties can be.
127      *
128      *  @param key property to return
129      * @return The value.
130      */
131     public  Object getProperty( String key );
132 
133     /**
134      * Initialize the Velocity Runtime with a Properties
135      * object.
136      *
137      * @param p
138      */
139     public void init(Properties p);
140 
141     /**
142      * Initialize the Velocity Runtime with the name of
143      * ExtendedProperties object.
144      *
145      * @param configurationFile
146      */
147     public void init(String configurationFile);
148 
149     /**
150      * Wraps the String in a StringReader and passes it off to
151      * {@link #parse(Reader,String)}.
152      * @since 1.6
153      */
154     public SimpleNode parse(String string, String templateName)
155         throws ParseException;
156 
157     /**
158      * Parse the input and return the root of
159      * AST node structure.
160      * <br><br>
161      *  In the event that it runs out of parsers in the
162      *  pool, it will create and let them be GC'd
163      *  dynamically, logging that it has to do that.  This
164      *  is considered an exceptional condition.  It is
165      *  expected that the user will set the
166      *  PARSER_POOL_SIZE property appropriately for their
167      *  application.  We will revisit this.
168      *
169      * @param reader inputstream retrieved by a resource loader
170      * @param templateName name of the template being parsed
171      * @return The AST representing the template.
172      * @throws ParseException
173      */
174     public  SimpleNode parse( Reader reader, String templateName )
175         throws ParseException;
176 
177     /**
178      *  Parse the input and return the root of the AST node structure.
179      *
180      * @param reader inputstream retrieved by a resource loader
181      * @param templateName name of the template being parsed
182      * @param dumpNamespace flag to dump the Velocimacro namespace for this template
183      * @return The AST representing the template.
184      * @throws ParseException
185      */
186     public SimpleNode parse( Reader reader, String templateName, boolean dumpNamespace )
187         throws ParseException;
188 
189     /**
190      * Renders the input string using the context into the output writer.
191      * To be used when a template is dynamically constructed, or want to use
192      * Velocity as a token replacer.
193      *
194      * @param context context to use in rendering input string
195      * @param out  Writer in which to render the output
196      * @param logTag  string to be used as the template name for log
197      *                messages in case of error
198      * @param instring input string containing the VTL to be rendered
199      *
200      * @return true if successful, false otherwise.  If false, see
201      *              Velocity runtime log
202      * @throws ParseErrorException The template could not be parsed.
203      * @throws MethodInvocationException A method on a context object could not be invoked.
204      * @throws ResourceNotFoundException A referenced resource could not be loaded.
205      * @throws IOException While rendering to the writer, an I/O problem occured.
206      * @since Velocity 1.6
207      */
208     public boolean evaluate(Context context, Writer out,
209                             String logTag, String instring);
210 
211     /**
212      * Renders the input reader using the context into the output writer.
213      * To be used when a template is dynamically constructed, or want to
214      * use Velocity as a token replacer.
215      *
216      * @param context context to use in rendering input string
217      * @param writer  Writer in which to render the output
218      * @param logTag  string to be used as the template name for log messages
219      *                in case of error
220      * @param reader Reader containing the VTL to be rendered
221      *
222      * @return true if successful, false otherwise.  If false, see
223      *              Velocity runtime log
224      * @throws ParseErrorException The template could not be parsed.
225      * @throws MethodInvocationException A method on a context object could not be invoked.
226      * @throws ResourceNotFoundException A referenced resource could not be loaded.
227      * @since Velocity 1.6
228      */
229     public boolean evaluate(Context context, Writer writer,
230                             String logTag, Reader reader);
231 
232     /**
233      * Invokes a currently registered Velocimacro with the params provided
234      * and places the rendered stream into the writer.
235      * <br>
236      * Note : currently only accepts args to the VM if they are in the context.
237      *
238      * @param vmName name of Velocimacro to call
239      * @param logTag string to be used for template name in case of error. if null,
240      *               the vmName will be used
241      * @param params keys for args used to invoke Velocimacro, in java format
242      *               rather than VTL (eg  "foo" or "bar" rather than "$foo" or "$bar")
243      * @param context Context object containing data/objects used for rendering.
244      * @param writer  Writer for output stream
245      * @return true if Velocimacro exists and successfully invoked, false otherwise.
246      * @since 1.6
247      */
248     public boolean invokeVelocimacro(final String vmName, String logTag,
249                                      String[] params, final Context context,
250                                      final Writer writer);
251 
252     /**
253      * Returns a <code>Template</code> from the resource manager.
254      * This method assumes that the character encoding of the
255      * template is set by the <code>input.encoding</code>
256      * property.  The default is "ISO-8859-1"
257      *
258      * @param name The file name of the desired template.
259      * @return     The template.
260      * @throws ResourceNotFoundException if template not found
261      *          from any available source.
262      * @throws ParseErrorException if template cannot be parsed due
263      *          to syntax (or other) error.
264      */
265     public Template getTemplate(String name)
266         throws ResourceNotFoundException, ParseErrorException;
267 
268     /**
269      * Returns a <code>Template</code> from the resource manager
270      *
271      * @param name The  name of the desired template.
272      * @param encoding Character encoding of the template
273      * @return     The template.
274      * @throws ResourceNotFoundException if template not found
275      *          from any available source.
276      * @throws ParseErrorException if template cannot be parsed due
277      *          to syntax (or other) error.
278      */
279     public Template getTemplate(String name, String  encoding)
280         throws ResourceNotFoundException, ParseErrorException;
281 
282     /**
283      * Returns a static content resource from the
284      * resource manager.  Uses the current value
285      * if INPUT_ENCODING as the character encoding.
286      *
287      * @param name Name of content resource to get
288      * @return parsed ContentResource object ready for use
289      * @throws ResourceNotFoundException if template not found
290      *          from any available source.
291      * @throws ParseErrorException
292      */
293     public ContentResource getContent(String name)
294         throws ResourceNotFoundException, ParseErrorException;
295 
296     /**
297      * Returns a static content resource from the
298      * resource manager.
299      *
300      * @param name Name of content resource to get
301      * @param encoding Character encoding to use
302      * @return parsed ContentResource object ready for use
303      * @throws ResourceNotFoundException if template not found
304      *          from any available source.
305      * @throws ParseErrorException
306      */
307     public ContentResource getContent( String name, String encoding )
308         throws ResourceNotFoundException, ParseErrorException;
309 
310     /**
311      *  Determines is a template exists, and returns name of the loader that
312      *  provides it.  This is a slightly less hokey way to support
313      *  the Velocity.templateExists() utility method, which was broken
314      *  when per-template encoding was introduced.  We can revisit this.
315      *
316      *  @param resourceName Name of template or content resource
317      *  @return class name of loader than can provide it
318      */
319     public String getLoaderNameForResource( String resourceName );
320 
321     /**
322      * String property accessor method with default to hide the
323      * configuration implementation.
324      *
325      * @param key property key
326      * @param defaultValue  default value to return if key not
327      *               found in resource manager.
328      * @return String  value of key or default
329      */
330     public String getString( String key, String defaultValue);
331 
332     /**
333      * Returns the appropriate VelocimacroProxy object if strVMname
334      * is a valid current Velocimacro.
335      *
336      * @param vmName  Name of velocimacro requested
337      * @param templateName Name of the namespace.
338      * @return VelocimacroProxy
339      */
340     public Directive getVelocimacro( String vmName, String templateName  );
341     
342     /**
343      * Returns the appropriate VelocimacroProxy object if strVMname
344      * is a valid current Velocimacro.
345      *
346      * @param vmName  Name of velocimacro requested
347      * @param templateName Name of the namespace.
348      * @param renderingTemplate Name of the template we are currently rendering. This
349      *    information is needed when VM_PERM_ALLOW_INLINE_REPLACE_GLOBAL setting is true
350      *    and template contains a macro with the same name as the global macro library.
351      * 
352      * @since Velocity 1.6
353      * 
354      * @return VelocimacroProxy
355      */
356     public Directive getVelocimacro( String vmName, String templateName, String renderingTemplate  );
357 
358    /**
359      * Adds a new Velocimacro. Usually called by Macro only while parsing.
360      *
361      * @param name  Name of velocimacro
362      * @param macro  String form of macro body
363      * @param argArray  Array of strings, containing the
364      *                         #macro() arguments.  the 0th is the name.
365      * @param sourceTemplate
366      * 
367      * @deprecated Use addVelocimacro(String, Node, String[], String) instead
368      *                   
369      * @return boolean  True if added, false if rejected for some
370      *                  reason (either parameters or permission settings)
371      */
372     public boolean addVelocimacro( String name,
373                                           String macro,
374                                           String argArray[],
375                                           String sourceTemplate );
376 
377     /**
378      * Adds a new Velocimacro. Usually called by Macro only while parsing.
379      *
380      * @param name  Name of velocimacro
381      * @param macro  root AST node of the parsed macro
382      * @param argArray  Array of strings, containing the
383      *                         #macro() arguments.  the 0th is the name.
384      * @param sourceTemplate
385      * 
386      * @since Velocity 1.6
387      *                   
388      * @return boolean  True if added, false if rejected for some
389      *                  reason (either parameters or permission settings)
390      */
391     public boolean addVelocimacro( String name,
392                                           Node macro,
393                                           String argArray[],
394                                           String sourceTemplate );
395                                           
396                                           
397     /**
398      *  Checks to see if a VM exists
399      *
400      * @param vmName  Name of velocimacro
401      * @param templateName
402      * @return boolean  True if VM by that name exists, false if not
403      */
404     public boolean isVelocimacro( String vmName, String templateName );
405 
406     /**
407      *  tells the vmFactory to dump the specified namespace.  This is to support
408      *  clearing the VM list when in inline-VM-local-scope mode
409      * @param namespace
410      * @return True if the Namespace was dumped.
411      */
412     public boolean dumpVMNamespace( String namespace );
413 
414     /**
415      * String property accessor method to hide the configuration implementation
416      * @param key  property key
417      * @return   value of key or null
418      */
419     public String getString(String key);
420 
421     /**
422      * Int property accessor method to hide the configuration implementation.
423      *
424      * @param key property key
425      * @return int value
426      */
427     public int getInt( String key );
428 
429     /**
430      * Int property accessor method to hide the configuration implementation.
431      *
432      * @param key  property key
433      * @param defaultValue default value
434      * @return int  value
435      */
436     public int getInt( String key, int defaultValue );
437 
438     /**
439      * Boolean property accessor method to hide the configuration implementation.
440      *
441      * @param key  property key
442      * @param def default default value if property not found
443      * @return boolean  value of key or default value
444      */
445     public boolean getBoolean( String key, boolean def );
446 
447     /**
448      * Return the velocity runtime configuration object.
449      *
450      * @return ExtendedProperties configuration object which houses
451      *                       the velocity runtime properties.
452      */
453     public ExtendedProperties getConfiguration();
454 
455     /**
456      * Return the specified application attribute.
457      *
458      * @param key The name of the attribute to retrieve.
459      * @return The value of the attribute.
460      */
461     public Object getApplicationAttribute( Object key );
462 
463     /**
464      * Set the specified application attribute.
465      *
466      * @param key The name of the attribute to set.
467      * @param value The attribute value to set.
468      * @return the displaced attribute value
469      */
470     public Object setApplicationAttribute( Object key, Object value );
471 
472     /**
473      * Returns the configured class introspection/reflection
474      * implementation.
475      * @return The current Uberspect object.
476      */
477     public Uberspect getUberspect();
478 
479     /**
480      * Returns a convenient Log instance that wraps the current LogChute.
481      * @return A log object.
482      */
483     public Log getLog();
484 
485     /**
486      * Returns the event handlers for the application.
487      * @return The event handlers for the application.
488      */
489     public EventCartridge getApplicationEventCartridge();
490 
491 
492     /**
493      * Returns the configured method introspection/reflection
494      * implementation.
495      * @return The configured method introspection/reflection
496      * implementation.
497      */
498     public Introspector getIntrospector();
499 
500     /**
501      * Returns true if the RuntimeInstance has been successfully initialized.
502      * @return True if the RuntimeInstance has been successfully initialized.
503      */
504     public boolean isInitialized();
505 
506     /**
507      * Create a new parser instance.
508      * @return A new parser instance.
509      */
510     public Parser createNewParser();
511 
512     /**
513      * Retrieve a previously instantiated directive.
514      * @param name name of the directive
515      * @return the directive with that name, if any
516      * @since 1.6
517      */
518     public Directive getDirective(String name);
519 
520 }