org.apache.velocity.app
Class VelocityEngine

java.lang.Object
  extended by org.apache.velocity.app.VelocityEngine
All Implemented Interfaces:
RuntimeConstants

public class VelocityEngine
extends Object
implements RuntimeConstants

This class provides a separate new-able instance of the Velocity template engine. The alternative model for use is using the Velocity class which employs the singleton model.

Velocity will call the parameter-less init() at the first use of this class if the init() wasn't explicitly called. While this will ensure that Velocity functions, it probably won't function in the way you intend, so it is strongly recommended that you call an init() method yourself if you use the default constructor.

Version:
$Id: VelocityEngine.java 894920 2009-12-31 18:35:25Z nbubna $

Field Summary
 
Fields inherited from interface org.apache.velocity.runtime.RuntimeConstants
COUNTER_INITIAL_VALUE, COUNTER_NAME, DEBUG_PREFIX, DEFAULT_RUNTIME_DIRECTIVES, DEFAULT_RUNTIME_PROPERTIES, DEFINE_DIRECTIVE_MAXDEPTH, DIRECTIVE_IF_TOSTRING_NULLCHECK, ENCODING_DEFAULT, ERROR_PREFIX, ERRORMSG_END, ERRORMSG_START, EVALUATE_CONTEXT_CLASS, EVENTHANDLER_INCLUDE, EVENTHANDLER_INVALIDREFERENCES, EVENTHANDLER_METHODEXCEPTION, EVENTHANDLER_NULLSET, EVENTHANDLER_REFERENCEINSERTION, FILE_RESOURCE_LOADER_CACHE, FILE_RESOURCE_LOADER_PATH, HAS_NEXT_NAME, INFO_PREFIX, INPUT_ENCODING, INTERPOLATE_STRINGLITERALS, INTROSPECTOR_RESTRICT_CLASSES, INTROSPECTOR_RESTRICT_PACKAGES, MAX_NUMBER_LOOPS, NUMBER_OF_PARSERS, OUTPUT_ENCODING, PARSE_DIRECTIVE_MAXDEPTH, PARSER_POOL_CLASS, PARSER_POOL_SIZE, PROVIDE_SCOPE_CONTROL, RESOURCE_LOADER, RESOURCE_MANAGER_CACHE_CLASS, RESOURCE_MANAGER_CLASS, RESOURCE_MANAGER_DEFAULTCACHE_SIZE, RESOURCE_MANAGER_LOGWHENFOUND, RUNTIME_LOG, RUNTIME_LOG_ERROR_STACKTRACE, RUNTIME_LOG_INFO_STACKTRACE, RUNTIME_LOG_LOGSYSTEM, RUNTIME_LOG_LOGSYSTEM_CLASS, RUNTIME_LOG_REFERENCE_LOG_INVALID, RUNTIME_LOG_WARN_STACKTRACE, RUNTIME_REFERENCES_STRICT, RUNTIME_REFERENCES_STRICT_ESCAPE, SET_NULL_ALLOWED, SKIP_INVALID_ITERATOR, STRICT_MATH, TRACE_PREFIX, UBERSPECT_CLASSNAME, UNKNOWN_PREFIX, VM_ARGUMENTS_STRICT, VM_BODY_REFERENCE, VM_CONTEXT_LOCALSCOPE, VM_LIBRARY, VM_LIBRARY_AUTORELOAD, VM_LIBRARY_DEFAULT, VM_MAX_DEPTH, VM_MESSAGES_ON, VM_PERM_ALLOW_INLINE, VM_PERM_ALLOW_INLINE_REPLACE_GLOBAL, VM_PERM_INLINE_LOCAL, WARN_PREFIX
 
Constructor Summary
VelocityEngine()
          Init-less CTOR
VelocityEngine(Properties p)
          Construct a VelocityEngine instance with the specified initial properties.
VelocityEngine(String propsFilename)
          Construct a VelocityEngine with the initial properties defined in the file propsFilename
 
Method Summary
 void addProperty(String key, Object value)
          Add a Velocity Runtime property.
 void clearProperty(String key)
          Clear a Velocity Runtime property.
 void debug(Object message)
          Deprecated. Use getLog() and call warn() on it.
 void error(Object message)
          Deprecated. Use getLog() and call warn() on it.
 boolean evaluate(Context context, Writer writer, String logTag, InputStream instream)
          Deprecated. Use evaluate( Context context, Writer writer, String logTag, Reader reader )
 boolean evaluate(Context context, Writer writer, String logTag, Reader reader)
          Renders the input reader using the context into the output writer.
 boolean evaluate(Context context, Writer out, String logTag, String instring)
          renders the input string using the context into the output writer.
 Object getApplicationAttribute(Object key)
           Return an application attribute (which can be any Object) that was set by the application in order to be accessible from any component of the system that gets a RuntimeServices.
 Log getLog()
          Returns a convenient Log instance that wraps the current LogChute.
 Object getProperty(String key)
          Get a Velocity Runtime property.
 Template getTemplate(String name)
          Returns a Template from the Velocity resource management system.
 Template getTemplate(String name, String encoding)
          Returns a Template from the Velocity resource management system.
 void info(Object message)
          Deprecated. Use getLog() and call warn() on it.
 void init()
          initialize the Velocity runtime engine, using the default properties of the Velocity distribution
 void init(Properties p)
          initialize the Velocity runtime engine, using default properties plus the properties in the passed in java.util.Properties object
 void init(String propsFilename)
          initialize the Velocity runtime engine, using default properties plus the properties in the properties file passed in as the arg
 boolean invokeVelocimacro(String vmName, String logTag, String[] params, Context context, Writer writer)
          Invokes a currently registered Velocimacro with the params provided and places the rendered stream into the writer.
 void loadDirective(String directiveClass)
          Instantiates and loads the directive with some basic checks.
 boolean mergeTemplate(String templateName, Context context, Writer writer)
          Deprecated. Use mergeTemplate( String templateName, String encoding, Context context, Writer writer )
 boolean mergeTemplate(String templateName, String encoding, Context context, Writer writer)
          merges a template and puts the rendered stream into the writer
 void removeDirective(String name)
          Remove a directive.
 boolean resourceExists(String resourceName)
          Determines if a resource is accessable via the currently configured resource loaders.
 void setApplicationAttribute(Object key, Object value)
           Sets an application attribute (which can be any Object) that will be accessible from any component of the system that gets a RuntimeServices.
 void setExtendedProperties(ExtendedProperties configuration)
          Set an entire configuration at once.
 void setProperty(String key, Object value)
          Set a Velocity Runtime property.
 boolean templateExists(String resourceName)
          Deprecated. Use resourceExists(String) instead.
 void warn(Object message)
          Deprecated. Use getLog() and call warn() on it.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

VelocityEngine

public VelocityEngine()
Init-less CTOR


VelocityEngine

public VelocityEngine(String propsFilename)
Construct a VelocityEngine with the initial properties defined in the file propsFilename


VelocityEngine

public VelocityEngine(Properties p)
Construct a VelocityEngine instance with the specified initial properties.

Method Detail

init

public void init()
initialize the Velocity runtime engine, using the default properties of the Velocity distribution


init

public void init(String propsFilename)
initialize the Velocity runtime engine, using default properties plus the properties in the properties file passed in as the arg

Parameters:
propsFilename - file containing properties to use to initialize the Velocity runtime

init

public void init(Properties p)
initialize the Velocity runtime engine, using default properties plus the properties in the passed in java.util.Properties object

Parameters:
p - Proprties object containing initialization properties

setProperty

public void setProperty(String key,
                        Object value)
Set a Velocity Runtime property.

Parameters:
key -
value -

addProperty

public void addProperty(String key,
                        Object value)
Add a Velocity Runtime property.

Parameters:
key -
value -

clearProperty

public void clearProperty(String key)
Clear a Velocity Runtime property.

Parameters:
key - of property to clear

setExtendedProperties

public void setExtendedProperties(ExtendedProperties configuration)
Set an entire configuration at once. This is useful in cases where the parent application uses the ExtendedProperties class and the velocity configuration is a subset of the parent application's configuration.

Parameters:
configuration -

getProperty

public Object getProperty(String key)
Get a Velocity Runtime property.

Parameters:
key - property to retrieve
Returns:
property value or null if the property not currently set

evaluate

public boolean evaluate(Context context,
                        Writer out,
                        String logTag,
                        String instring)
                 throws ParseErrorException,
                        MethodInvocationException,
                        ResourceNotFoundException
renders the input string using the context into the output writer. To be used when a template is dynamically constructed, or want to use Velocity as a token replacer.

Parameters:
context - context to use in rendering input string
out - Writer in which to render the output
logTag - string to be used as the template name for log messages in case of error
instring - input string containing the VTL to be rendered
Returns:
true if successful, false otherwise. If false, see Velocity runtime log
Throws:
ParseErrorException - The template could not be parsed.
MethodInvocationException - A method on a context object could not be invoked.
ResourceNotFoundException - A referenced resource could not be loaded.

evaluate

public boolean evaluate(Context context,
                        Writer writer,
                        String logTag,
                        InputStream instream)
                 throws ParseErrorException,
                        MethodInvocationException,
                        ResourceNotFoundException,
                        IOException
Deprecated. Use evaluate( Context context, Writer writer, String logTag, Reader reader )

Renders the input stream using the context into the output writer. To be used when a template is dynamically constructed, or want to use Velocity as a token replacer.

Parameters:
context - context to use in rendering input string
writer - Writer in which to render the output
logTag - string to be used as the template name for log messages in case of error
instream - input stream containing the VTL to be rendered
Returns:
true if successful, false otherwise. If false, see Velocity runtime log
Throws:
ParseErrorException
MethodInvocationException
ResourceNotFoundException
IOException

evaluate

public boolean evaluate(Context context,
                        Writer writer,
                        String logTag,
                        Reader reader)
                 throws ParseErrorException,
                        MethodInvocationException,
                        ResourceNotFoundException
Renders the input reader using the context into the output writer. To be used when a template is dynamically constructed, or want to use Velocity as a token replacer.

Parameters:
context - context to use in rendering input string
writer - Writer in which to render the output
logTag - string to be used as the template name for log messages in case of error
reader - Reader containing the VTL to be rendered
Returns:
true if successful, false otherwise. If false, see Velocity runtime log
Throws:
ParseErrorException - The template could not be parsed.
MethodInvocationException - A method on a context object could not be invoked.
ResourceNotFoundException - A referenced resource could not be loaded.
Since:
Velocity v1.1

invokeVelocimacro

public boolean invokeVelocimacro(String vmName,
                                 String logTag,
                                 String[] params,
                                 Context context,
                                 Writer writer)
Invokes a currently registered Velocimacro with the params provided and places the rendered stream into the writer.
Note : currently only accepts args to the VM if they are in the context.

Parameters:
vmName - name of Velocimacro to call
logTag - string to be used for template name in case of error. if null, the vmName will be used
params - keys for args used to invoke Velocimacro, in java format rather than VTL (eg "foo" or "bar" rather than "$foo" or "$bar")
context - Context object containing data/objects used for rendering.
writer - Writer for output stream
Returns:
true if Velocimacro exists and successfully invoked, false otherwise.

mergeTemplate

public boolean mergeTemplate(String templateName,
                             Context context,
                             Writer writer)
                      throws ResourceNotFoundException,
                             ParseErrorException,
                             MethodInvocationException
Deprecated. Use mergeTemplate( String templateName, String encoding, Context context, Writer writer )

Merges a template and puts the rendered stream into the writer. The default encoding that Velocity uses to read template files is defined in the property input.encoding and defaults to ISO-8859-1.

Parameters:
templateName - name of template to be used in merge
context - filled context to be used in merge
writer - writer to write template into
Returns:
true if successful, false otherwise. Errors logged to velocity log.
Throws:
ResourceNotFoundException
ParseErrorException
MethodInvocationException

mergeTemplate

public boolean mergeTemplate(String templateName,
                             String encoding,
                             Context context,
                             Writer writer)
                      throws ResourceNotFoundException,
                             ParseErrorException,
                             MethodInvocationException
merges a template and puts the rendered stream into the writer

Parameters:
templateName - name of template to be used in merge
encoding - encoding used in template
context - filled context to be used in merge
writer - writer to write template into
Returns:
true if successful, false otherwise. Errors logged to velocity log
Throws:
ResourceNotFoundException
ParseErrorException
MethodInvocationException
Since:
Velocity v1.1

getTemplate

public Template getTemplate(String name)
                     throws ResourceNotFoundException,
                            ParseErrorException
Returns a Template from the Velocity resource management system.

Parameters:
name - The file name of the desired template.
Returns:
The template.
Throws:
ResourceNotFoundException - if template not found from any available source.
ParseErrorException - if template cannot be parsed due to syntax (or other) error.

getTemplate

public Template getTemplate(String name,
                            String encoding)
                     throws ResourceNotFoundException,
                            ParseErrorException
Returns a Template from the Velocity resource management system.

Parameters:
name - The file name of the desired template.
encoding - The character encoding to use for the template.
Returns:
The template.
Throws:
ResourceNotFoundException - if template not found from any available source.
ParseErrorException - if template cannot be parsed due to syntax (or other) error.
Since:
Velocity v1.1

resourceExists

public boolean resourceExists(String resourceName)
Determines if a resource is accessable via the currently configured resource loaders.

Note that the current implementation will not change the state of the system in any real way - so this cannot be used to pre-load the resource cache, as the previous implementation did as a side-effect.

The previous implementation exhibited extreme lazyness and sloth, and the author has been flogged.

Parameters:
resourceName - name of the resource to search for
Returns:
true if found, false otherwise
Since:
1.5

templateExists

public boolean templateExists(String resourceName)
Deprecated. Use resourceExists(String) instead.

Parameters:
resourceName -
Returns:
True if the template exists.
See Also:
resourceExists(String)

getLog

public Log getLog()
Returns a convenient Log instance that wraps the current LogChute. Use this to log error messages. It has the usual methods you'd expect.

Returns:
A log object.
Since:
1.5

warn

public void warn(Object message)
Deprecated. Use getLog() and call warn() on it.

Parameters:
message -

info

public void info(Object message)
Deprecated. Use getLog() and call warn() on it.

Parameters:
message -

error

public void error(Object message)
Deprecated. Use getLog() and call warn() on it.

Parameters:
message -

debug

public void debug(Object message)
Deprecated. Use getLog() and call warn() on it.

Parameters:
message -

setApplicationAttribute

public void setApplicationAttribute(Object key,
                                    Object value)

Sets an application attribute (which can be any Object) that will be accessible from any component of the system that gets a RuntimeServices. This allows communication between the application environment and custom pluggable components of the Velocity engine, such as ResourceLoaders and LogChutes.

Note that there is no enforcement or rules for the key used - it is up to the application developer. However, to help make the intermixing of components possible, using the target Class name (e.g. com.foo.bar ) as the key might help avoid collision.

Parameters:
key - object 'name' under which the object is stored
value - object to store under this key

getApplicationAttribute

public Object getApplicationAttribute(Object key)

Return an application attribute (which can be any Object) that was set by the application in order to be accessible from any component of the system that gets a RuntimeServices. This allows communication between the application environment and custom pluggable components of the Velocity engine, such as ResourceLoaders and LogChutes.

Parameters:
key - object 'name' under which the object is stored
Returns:
value object to store under this key
Since:
1.5

removeDirective

public void removeDirective(String name)
Remove a directive.

Parameters:
name - name of the directive.

loadDirective

public void loadDirective(String directiveClass)
Instantiates and loads the directive with some basic checks.

Parameters:
directiveClass - classname of directive to load


Copyright © 2000-2010 The Apache Software Foundation. All Rights Reserved.