Class RuntimeInstance
- All Implemented Interfaces:
DeprecatedRuntimeConstants
,RuntimeConstants
,RuntimeServices
This is the Runtime system for Velocity. It is the single access point for all functionality in Velocity. It adheres to the mediator pattern and is the only structure that developers need to be familiar with in order to get Velocity to perform.
The Runtime will also cooperate with external systems, which can make all needed setProperty() calls before calling init().
----------------------------------------------------------------------- N O T E S O N R U N T I M E I N I T I A L I Z A T I O N ----------------------------------------------------------------------- init() If init() is called by itself the RuntimeInstance will initialize with a set of default values. ----------------------------------------------------------------------- init(String/Properties) In this case the default velocity properties are layed down first to provide a solid base, then any properties provided in the given properties object will override the corresponding default property. -----------------------------------------------------------------------
- Version:
- $Id$
- Author:
- Jason van Zyl, Jeff Bowden, Geir Magusson Jr.
-
Nested Class Summary
Nested classes/interfaces inherited from interface org.apache.velocity.runtime.RuntimeConstants
RuntimeConstants.SpaceGobbling
-
Field Summary
Fields inherited from interface org.apache.velocity.runtime.DeprecatedRuntimeConstants
OLD_CHECK_EMPTY_OBJECTS, OLD_CONTEXT_AUTOREFERENCE_KEY, OLD_CONVERSION_HANDLER_CLASS, OLD_CUSTOM_DIRECTIVES, OLD_DEFINE_DIRECTIVE_MAXDEPTH, OLD_DS_RESOURCE_LOADER_DATASOURCE, OLD_DS_RESOURCE_LOADER_KEY_COLUMN, OLD_DS_RESOURCE_LOADER_TEMPLATE_COLUMN, OLD_DS_RESOURCE_LOADER_TIMESTAMP_COLUMN, OLD_ERRORMSG_END, OLD_ERRORMSG_START, OLD_EVENTHANDLER_INCLUDE, OLD_EVENTHANDLER_INVALIDREFERENCES, OLD_EVENTHANDLER_METHODEXCEPTION, OLD_EVENTHANDLER_REFERENCEINSERTION, OLD_FILE_RESOURCE_LOADER_CACHE, OLD_FILE_RESOURCE_LOADER_PATH, OLD_INPUT_ENCODING, OLD_INTERPOLATE_STRINGLITERALS, OLD_MAX_NUMBER_LOOPS, OLD_PARSE_DIRECTIVE_MAXDEPTH, OLD_RESOURCE_LOADER_CHECK_INTERVAL, OLD_RESOURCE_LOADERS, OLD_RESOURCE_MANAGER_DEFAULTCACHE_SIZE, OLD_RESOURCE_MANAGER_LOGWHENFOUND, OLD_RUNTIME_LOG_REFERENCE_LOG_INVALID, OLD_RUNTIME_REFERENCES_STRICT, OLD_RUNTIME_REFERENCES_STRICT_ESCAPE, OLD_SKIP_INVALID_ITERATOR, OLD_SPACE_GOBBLING, OLD_STRICT_MATH, OLD_UBERSPECT_CLASSNAME, OLD_VM_BODY_REFERENCE, OLD_VM_ENABLE_BC_MODE, OLD_VM_LIBRARY, OLD_VM_LIBRARY_DEFAULT, OLD_VM_MAX_DEPTH, OLD_VM_PERM_ALLOW_INLINE, OLD_VM_PERM_ALLOW_INLINE_REPLACE_GLOBAL, OLD_VM_PERM_INLINE_LOCAL
Fields inherited from interface org.apache.velocity.runtime.RuntimeConstants
CHECK_EMPTY_OBJECTS, CONTEXT_AUTOREFERENCE_KEY, CONTEXT_SCOPE_CONTROL, CONVERSION_HANDLER_CLASS, CONVERSION_HANDLER_INSTANCE, CUSTOM_DIRECTIVES, DEFAULT_PARSER_CLASS, DEFAULT_RUNTIME_DIRECTIVES, DEFAULT_RUNTIME_LOG_NAME, DEFAULT_RUNTIME_PROPERTIES, DEFINE_DIRECTIVE_MAXDEPTH, DS_RESOURCE_LOADER_DATASOURCE, DS_RESOURCE_LOADER_DATASOURCE_URL, DS_RESOURCE_LOADER_KEY_COLUMN, DS_RESOURCE_LOADER_STMT_POOL_MAX_SIZE, DS_RESOURCE_LOADER_TABLE, DS_RESOURCE_LOADER_TEMPLATE_COLUMN, DS_RESOURCE_LOADER_TIMESTAMP_COLUMN, ENCODING_DEFAULT, ERRORMSG_END, ERRORMSG_START, EVENTHANDLER_INCLUDE, EVENTHANDLER_INVALIDREFERENCES, EVENTHANDLER_INVALIDREFERENCES_NULL, EVENTHANDLER_INVALIDREFERENCES_QUIET, EVENTHANDLER_INVALIDREFERENCES_TESTED, EVENTHANDLER_METHODEXCEPTION, EVENTHANDLER_REFERENCEINSERTION, FILE_RESOURCE_LOADER_CACHE, FILE_RESOURCE_LOADER_PATH, IMMUTABLE_RANGES, INPUT_ENCODING, INTERPOLATE_STRINGLITERALS, INTROSPECTOR_RESTRICT_CLASSES, INTROSPECTOR_RESTRICT_PACKAGES, MAX_NUMBER_LOOPS, NUMBER_OF_PARSERS, PARSE_DIRECTIVE_MAXDEPTH, PARSER_CLASS, PARSER_HYPHEN_ALLOWED, PARSER_POOL_CLASS, PARSER_POOL_SIZE, PROVIDE_SCOPE_CONTROL, RESOURCE_LOADER, RESOURCE_LOADER_CACHE, RESOURCE_LOADER_CHECK_INTERVAL, RESOURCE_LOADER_CLASS, RESOURCE_LOADER_IDENTIFIER, RESOURCE_LOADER_INSTANCE, RESOURCE_LOADER_PATHS, RESOURCE_LOADERS, RESOURCE_MANAGER_CACHE_CLASS, RESOURCE_MANAGER_CLASS, RESOURCE_MANAGER_DEFAULTCACHE_SIZE, RESOURCE_MANAGER_INSTANCE, RESOURCE_MANAGER_LOGWHENFOUND, RUNTIME_LOG_INSTANCE, RUNTIME_LOG_METHOD_CALL_LOG_INVALID, RUNTIME_LOG_NAME, RUNTIME_LOG_REFERENCE_LOG_INVALID, RUNTIME_LOG_TRACK_LOCATION, RUNTIME_REFERENCES_STRICT, RUNTIME_REFERENCES_STRICT_ESCAPE, RUNTIME_STRING_INTERNING, SKIP_INVALID_ITERATOR, SPACE_GOBBLING, STRICT_MATH, UBERSPECT_CLASSNAME, VM_ARGUMENTS_STRICT, VM_BODY_REFERENCE, VM_ENABLE_BC_MODE, 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
-
Constructor Summary
-
Method Summary
Modifier and TypeMethodDescriptionvoid
addDirective
(Directive directive) Programatically add a directive.void
addProperty
(String key, Object value) Add a property to the configuration.boolean
addVelocimacro
(String name, Node macro, List<Macro.MacroArg> macroArgs, Template definingTemplate) Adds a new Velocimacro.void
clearProperty
(String key) Clear the values pertaining to a particular property.Returns a JavaCC generated Parser.boolean
Renders the input reader using the context into the output writer.boolean
Renders the input string using the context into the output writer.Gets the application attribute for the given keyReturns the event handlers for the application.boolean
getBoolean
(String key, boolean def) Boolean property accessor method to hide the configuration implementation.Return the velocity runtime configuration object.getContent
(String name) Returns a static content resource from the resource manager.getContent
(String name, String encoding) Returns a static content resource from the resource manager.getDirective
(String name) Retrieve a previously instantiated directive.int
Int property accessor method to hide the configuration implementation.int
Int property accessor method to hide the configuration implementation.getLoaderNameForResource
(String resourceName) Determines if a template exists and returns name of the loader that provides it.org.slf4j.Logger
getLog()
Returns the configured logger.org.slf4j.Logger
Get a logger for the specified child namespace.Get the LogContext object used to tack locations in templates.Get the replacement characters configured for this runtime service's parsergetProperty
(String key) Allows an external caller to get a property.get space gobbling modeString property accessor method to hide the configuration implementationString property accessor method with default to hide the configuration implementation.getTemplate
(String name) Returns aTemplate
from the resource manager.getTemplate
(String name, String encoding) Returns aTemplate
from the resource managerReturns the Uberspect object for this Instance.getVelocimacro
(String vmName, Template renderingTemplate, Template template) Returns the appropriate VelocimacroProxy object if vmName is a valid current Velocimacro.void
init()
This is the primary initialization method in the Velocity Runtime.void
Initialize the Velocity Runtime with a properties file path.void
init
(Properties p) Initialize the Velocity Runtime with a Properties object.boolean
Invokes a currently registered Velocimacro with the params provided and places the rendered stream into the writer.boolean
get whether hyphens are allowed in identifiersboolean
Returns true if the RuntimeInstance has been successfully initialized.boolean
isScopeControlEnabled
(String scopeName) Get whether to provide a scope control object for this scopeboolean
isVelocimacro
(String vmName, Template template) Checks to see if a VM existsvoid
loadDirective
(String directiveClass) instantiates and loads the directive with some basic checksParse the input and return the root of AST node structure.void
removeDirective
(String name) Remove a directive.boolean
render
(Context context, Writer writer, String logTag, SimpleNode nodeTree) Initializes and renders the ASTSimpleNode
using the context into the output writer.void
reset()
Resets the instance, so Velocity can be re-initialized again.setApplicationAttribute
(Object key, Object o) Sets the application attribute for the given keyvoid
setConfiguration
(ExtProperties configuration) Allow an external system to set an ExtProperties object to use.void
setProperties
(String fileName) Add all properties contained in the file fileName to the RuntimeInstance propertiesvoid
setProperties
(Properties props) Add all the properties in props to the RuntimeInstance propertiesvoid
setProperty
(String key, Object value) Allows an external system to set a property in the Velocity Runtime.boolean
Whether to use string interning
-
Constructor Details
-
RuntimeInstance
public RuntimeInstance()Creates a new RuntimeInstance object.
-
-
Method Details
-
init
public void init()This is the primary initialization method in the Velocity Runtime. The systems that are setup/initialized here are as follows:- Logging System
- ResourceManager
- EventHandler
- Parser Pool
- Global Cache
- Static Content Include System
- Velocimacro System
- Specified by:
init
in interfaceRuntimeServices
-
reset
public void reset()Resets the instance, so Velocity can be re-initialized again.- Since:
- 2.0.0
-
isInitialized
public boolean isInitialized()Returns true if the RuntimeInstance has been successfully initialized.- Specified by:
isInitialized
in interfaceRuntimeServices
- Returns:
- True if the RuntimeInstance has been successfully initialized.
- Since:
- 1.5
-
setProperty
Allows an external system to set a property in the Velocity Runtime.- Specified by:
setProperty
in interfaceRuntimeServices
- Parameters:
key
- property keyvalue
- property value
-
setProperties
Add all properties contained in the file fileName to the RuntimeInstance properties- Parameters:
fileName
-
-
setProperties
Add all the properties in props to the RuntimeInstance properties- Parameters:
props
-
-
setConfiguration
Allow an external system to set an ExtProperties object to use.- Specified by:
setConfiguration
in interfaceRuntimeServices
- Parameters:
configuration
-- Since:
- 2.0
-
addProperty
Add a property to the configuration. If it already exists then the value stated here will be added to the configuration entry. For example, if resource.loader = file is already present in the configuration and you addProperty("resource.loader", "classpath") Then you will end up with a Vector like the following: ["file", "classpath"]- Specified by:
addProperty
in interfaceRuntimeServices
- Parameters:
key
-value
-
-
clearProperty
Clear the values pertaining to a particular property.- Specified by:
clearProperty
in interfaceRuntimeServices
- Parameters:
key
- of property to clear
-
getProperty
Allows an external caller to get a property. The calling routine is required to know the type, as this routine will return an Object, as that is what properties can be.- Specified by:
getProperty
in interfaceRuntimeServices
- Parameters:
key
- property to return- Returns:
- Value of the property or null if it does not exist.
-
init
Initialize the Velocity Runtime with a Properties object.- Specified by:
init
in interfaceRuntimeServices
- Parameters:
p
- Velocity properties for initialization
-
init
Initialize the Velocity Runtime with a properties file path.- Specified by:
init
in interfaceRuntimeServices
- Parameters:
configurationFile
-
-
addDirective
Programatically add a directive.- Parameters:
directive
-
-
getDirective
Retrieve a previously instantiated directive.- Specified by:
getDirective
in interfaceRuntimeServices
- Parameters:
name
- name of the directive- Returns:
- the
Directive
for that name
-
removeDirective
Remove a directive.- Parameters:
name
- name of the directive.
-
loadDirective
instantiates and loads the directive with some basic checks- Parameters:
directiveClass
- classname of directive to load
-
createNewParser
Returns a JavaCC generated Parser.- Specified by:
createNewParser
in interfaceRuntimeServices
- Returns:
- Parser javacc generated parser
-
parse
Parse the input and return the root of AST node structure.
In the event that it runs out of parsers in the pool, it will create and let them be GC'd dynamically, logging that it has to do that. This is considered an exceptional condition. It is expected that the user will set the PARSER_POOL_SIZE property appropriately for their application. We will revisit this.- Specified by:
parse
in interfaceRuntimeServices
- Parameters:
reader
- Reader retrieved by a resource loadertemplate
- template being parsed- Returns:
- A root node representing the template as an AST tree.
- Throws:
ParseException
- When the template could not be parsed.
-
evaluate
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.
Note! Macros defined in evaluate() calls are not persisted in memory so next evaluate() call does not know about macros defined during previous calls.- Specified by:
evaluate
in interfaceRuntimeServices
- Parameters:
context
- context to use in rendering input stringout
- Writer in which to render the outputlogTag
- string to be used as the template name for log messages in case of errorinstring
- 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.- Since:
- Velocity 1.6
-
evaluate
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.
Note! Macros defined in evaluate() calls are not persisted in memory so next evaluate() call does not know about macros defined during previous calls.- Specified by:
evaluate
in interfaceRuntimeServices
- Parameters:
context
- context to use in rendering input stringwriter
- Writer in which to render the outputlogTag
- string to be used as the template name for log messages in case of errorreader
- 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 1.6
-
render
Initializes and renders the AST
SimpleNode
using the context into the output writer.Note that the
nodeTree
argument should be a fresh AST tree obtained by theparse(Reader, Template)
method.If you wish to reuse AST trees but bypass the resource loading mechanism, you should rely on the Template API, as follow:
RuntimeInstance runtimeInstance = new RuntimeInstance(); Template template = new Template(); template.setName("my_template"); template.setRuntimeServices(runtimeInstance); SimpleNode astTree = runtimeInstance.parse(new StringReader("Some template..."), template); template.setData(astTree); template.initDocument();
You will then be able to render several times the template with
template.render(context, writer)
.- Parameters:
context
- context to use in rendering input stringwriter
- Writer in which to render the outputlogTag
- string to be used as the template name for log messages in case of errornodeTree
- SimpleNode which is the root of the AST to be rendered- Returns:
- true if successful, false otherwise. If false, see Velocity runtime log for errors
- 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 1.6
-
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.
Note: only macros in the global context can be called. This method doesn't find macros defined by templates during previous mergeTemplate calls if Velocity.VM_PERM_INLINE_LOCAL has been enabled.- Specified by:
invokeVelocimacro
in interfaceRuntimeServices
- Parameters:
vmName
- name of Velocimacro to calllogTag
- string to be used for template name in case of error. if null, the vmName will be usedparams
- 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.
- Since:
- 1.6
-
getTemplate
Returns aTemplate
from the resource manager. This method assumes that the character encoding of the template is set by theresource.default_encoding
property. The default is UTF-8.- Specified by:
getTemplate
in interfaceRuntimeServices
- 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 aTemplate
from the resource manager- Specified by:
getTemplate
in interfaceRuntimeServices
- Parameters:
name
- The name of the desired template.encoding
- Character encoding of 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.
-
getContent
public ContentResource getContent(String name) throws ResourceNotFoundException, ParseErrorException Returns a static content resource from the resource manager. Uses the current value if INPUT_ENCODING as the character encoding.- Specified by:
getContent
in interfaceRuntimeServices
- Parameters:
name
- Name of content resource to get- Returns:
- parsed ContentResource object ready for use
- Throws:
ResourceNotFoundException
- if template not found from any available source.ParseErrorException
- When the template could not be parsed.
-
getContent
public ContentResource getContent(String name, String encoding) throws ResourceNotFoundException, ParseErrorException Returns a static content resource from the resource manager.- Specified by:
getContent
in interfaceRuntimeServices
- Parameters:
name
- Name of content resource to getencoding
- Character encoding to use- Returns:
- parsed ContentResource object ready for use
- Throws:
ResourceNotFoundException
- if template not found from any available source.ParseErrorException
- When the template could not be parsed.
-
getLoaderNameForResource
Determines if a template exists and returns name of the loader that provides it. This is a slightly less hokey way to support the Velocity.resourceExists() utility method, which was broken when per-template encoding was introduced. We can revisit this.- Specified by:
getLoaderNameForResource
in interfaceRuntimeServices
- Parameters:
resourceName
- Name of template or content resource- Returns:
- class name of loader than can provide it
-
getLog
public org.slf4j.Logger getLog()Returns the configured logger.- Specified by:
getLog
in interfaceRuntimeServices
- Returns:
- A Logger instance
- Since:
- 1.5
-
getLog
Get a logger for the specified child namespace. If a logger was configured using the runtime.log.instance configuration property, returns this instance. Otherwise, uses SLF4J LoggerFactory on baseNamespace '.' childNamespace.- Specified by:
getLog
in interfaceRuntimeServices
- Parameters:
childNamespace
-- Returns:
- child namespace logger
-
getLogContext
Get the LogContext object used to tack locations in templates.- Specified by:
getLogContext
in interfaceRuntimeServices
- Returns:
- LogContext object
- Since:
- 2.2
-
getString
String property accessor method with default to hide the configuration implementation.- Specified by:
getString
in interfaceRuntimeServices
- Parameters:
key
- property keydefaultValue
- default value to return if key not found in resource manager.- Returns:
- value of key or default
-
getVelocimacro
Returns the appropriate VelocimacroProxy object if vmName is a valid current Velocimacro.- Specified by:
getVelocimacro
in interfaceRuntimeServices
- Parameters:
vmName
- Name of velocimacro requestedrenderingTemplate
- Template we are currently rendering. This information is needed when VM_PERM_ALLOW_INLINE_REPLACE_GLOBAL setting is true and template contains a macro with the same name as the global macro library.template
- Template which acts as the host for the macro- Returns:
- VelocimacroProxy
-
addVelocimacro
public boolean addVelocimacro(String name, Node macro, List<Macro.MacroArg> macroArgs, Template definingTemplate) Adds a new Velocimacro. Usually called by Macro only while parsing.- Specified by:
addVelocimacro
in interfaceRuntimeServices
- Parameters:
name
- Name of velocimacromacro
- root AST node of the parsed macromacroArgs
- Array of macro arguments, containing the #macro() arguments and default values. the 0th is the name.definingTemplate
- Template containing the source of the macro- Returns:
- boolean True if added, false if rejected for some reason (either parameters or permission settings)
-
isVelocimacro
Checks to see if a VM exists- Specified by:
isVelocimacro
in interfaceRuntimeServices
- Parameters:
vmName
- Name of the Velocimacro.template
- Template on which to look for the Macro.- Returns:
- True if VM by that name exists, false if not
-
getString
String property accessor method to hide the configuration implementation- Specified by:
getString
in interfaceRuntimeServices
- Parameters:
key
- property key- Returns:
- value of key or null
-
getInt
Int property accessor method to hide the configuration implementation.- Specified by:
getInt
in interfaceRuntimeServices
- Parameters:
key
- Property key- Returns:
- value
-
getInt
Int property accessor method to hide the configuration implementation.- Specified by:
getInt
in interfaceRuntimeServices
- Parameters:
key
- property keydefaultValue
- The default value.- Returns:
- value
-
getBoolean
Boolean property accessor method to hide the configuration implementation.- Specified by:
getBoolean
in interfaceRuntimeServices
- Parameters:
key
- property keydef
- The default value if property not found.- Returns:
- value of key or default value
-
getConfiguration
Return the velocity runtime configuration object.- Specified by:
getConfiguration
in interfaceRuntimeServices
- Returns:
- Configuration object which houses the Velocity runtime properties.
-
getApplicationEventCartridge
Returns the event handlers for the application.- Specified by:
getApplicationEventCartridge
in interfaceRuntimeServices
- Returns:
- The event handlers for the application.
- Since:
- 1.5
-
getApplicationAttribute
Gets the application attribute for the given key- Specified by:
getApplicationAttribute
in interfaceRuntimeServices
- Parameters:
key
-- Returns:
- The application attribute for the given key.
-
setApplicationAttribute
Sets the application attribute for the given key- Specified by:
setApplicationAttribute
in interfaceRuntimeServices
- Parameters:
key
-o
- The new application attribute.- Returns:
- The old value of this attribute or null if it hasn't been set before.
-
getUberspect
Returns the Uberspect object for this Instance.- Specified by:
getUberspect
in interfaceRuntimeServices
- Returns:
- The Uberspect object for this Instance.
-
useStringInterning
public boolean useStringInterning()Whether to use string interning- Specified by:
useStringInterning
in interfaceRuntimeServices
- Returns:
- boolean
-
getSpaceGobbling
get space gobbling mode- Specified by:
getSpaceGobbling
in interfaceRuntimeServices
- Returns:
- indentation mode
-
isHyphenAllowedInIdentifiers
public boolean isHyphenAllowedInIdentifiers()get whether hyphens are allowed in identifiers- Specified by:
isHyphenAllowedInIdentifiers
in interfaceRuntimeServices
- Returns:
- configured boolean flag
-
isScopeControlEnabled
Get whether to provide a scope control object for this scope- Specified by:
isScopeControlEnabled
in interfaceRuntimeServices
- Parameters:
scopeName
-- Returns:
- scope control enabled
- Since:
- 2.1
-
getParserConfiguration
Description copied from interface:RuntimeServices
Get the replacement characters configured for this runtime service's parser- Specified by:
getParserConfiguration
in interfaceRuntimeServices
- Returns:
- configured replacement characters
-