NVelocity 'Package' of event handlers... Called during Velocity merge before a reference value will be inserted into the output stream. the stack of objects used to reach this reference reference from template about to be inserted value about to be inserted (after toString() ) Object on which toString() should be called for output. Called during Velocity merge to determine if when a #set() results in a null assignment, a warning is logged. true if to be logged, false otherwise Called during Velocity merge if a reference is null Class that is causing the exception method called that causes the exception Exception thrown by the method Object to return as method result exception to be wrapped and propagated to app Attached the EventCartridge to the context context to attach to true if successful, false otherwise Base interface for all event handlers * Geir Magnusson Jr. $Id: EventHandler.cs,v 1.3 2003/10/27 13:54:07 corts Exp $ Lets an app approve / veto writing a log message when RHS of #set() is null. Reference literal of left-hand-side of set statement reference literal of right-hand-side of set statement Formatting tool for inserting into the Velocity WebContext. Can format dates or lists of objects. Here's an example of some uses:
            $formatter.formatShortDate($object.Date)
            $formatter.formatLongDate($db.getRecord(232).getDate())
            $formatter.formatArray($array)
            $formatter.limitLen(30, $object.Description)
            
Sean Legassick Daniel Rall $Id: VelocityFormatter.cs,v 1.5 2003/11/05 04:15:02 corts Exp $
Constructor needs a backPointer to the context. A Context. Formats a date in 'short' style. A Date. A String. Formats a date in 'long' style. A Date. A String. Formats a date/time in 'short' style. A Date. A String. Formats a date/time in 'long' style. A Date. A String. Formats an array into the form "A, B and C". An Object. A String. Formats an array into the form "A<delim>B<delim>C". An Object. A String. A String. Formats an array into the form "A<delim>B<finalDelimiter>C". An Object. A String. A String. A String. Formats a list into the form "A, B and C". A list. A String. Formats a list into the form "A<delim>B<delim>C". A list. A String. A String. Formats a list into the form "Adelim>B<finalDelimiter>C". A list. A String. A String. A String. Limits 'string' to 'maximumLength' characters. If the string gets curtailed, "..." is appended to it. An int with the maximum length. A String. A String. Limits 'string' to 'maximumLength' character. If the string gets curtailed, 'suffix' is appended to it. An int with the maximum length. A String. A String. A String. Makes an alternator object that alternates between two values. Example usage in a Velocity template: <table> $formatter.makeAlternator("rowColor", "#c0c0c0", "#e0e0e0") #foreach $item in $items <tr><td bgcolor="$rowColor">$item.Name</td></tr> $rowColor.alternate() #end </table> The name for the alternator int the context. The first alternate. The second alternate. The newly created instance. Makes an alternator object that alternates between three values. Makes an alternator object that alternates between four values. Makes an alternator object that alternates between two values automatically. Returns a default value if the object passed is null. Class that returns alternating values in a template. It stores a list of alternate Strings, whenever alternate() is called it switches to the next in the list. The current alternate is retrieved through toString() - i.e. just by referencing the object in a Velocity template. For an example of usage see the makeAlternator() method below. Constructor takes an array of Strings. A String[]. Alternates to the next in the list. The current alternate in the sequence. Returns the current alternate. A String. As VelocityAlternator, but calls alternate() automatically on rendering in a template. Constructor takes an array of Strings. A String[]. Returns the current alternate, and automatically alternates to the next alternate in its sequence (triggered upon rendering). The current alternate in the sequence. This is a small utility class allow easy access to static fields in a class, such as string constants. Velocity will not introspect for class fields (and won't in the future :), but writing setter/getter methods to do this really is a pain, so use this if you really have to access fields. The idea it so enable access to the fields just like you would in Java. For example, in Java, you would access a static field like
             MyClass.STRING_CONSTANT
             
and that is the same thing we are trying to allow here.
So to use in your Java code, do something like this :
             context.put("runtime", new FieldMethodizer( "NVelocity.Runtime.Runtime" ));
             
and then in your template, you can access any of your static fields in this way :
             $runtime.RUNTIME_LOG_WARN_STACKTRACE
             
Right now, this class only methodizes public static fields. It seems that anything else is too dangerous. This class is for convenience accessing 'constants'. If you have fields that aren't static it may be better to handle them by explicitly placing them into the context.
Geir Magnusson Jr. $Id: FieldMethodizer.cs,v 1.3 2003/10/27 13:54:07 corts Exp $
Hold the field objects by field name Hold the class objects by field name Allow object to be initialized without any data. You would use addObject() to add data later. Constructor that takes as it's arg the name of the class to methodize. Name of class to methodize. Constructor that takes as it's arg a living object to methodize. Note that it will still only methodized the public static fields of the class. object to methodize. Add the Name of the class to methodize Add an Object to methodize Accessor method to get the fields by name. Name of static field to retrieve The value of the given field. Method that retrieves all public static fields in the class we are methodizing. This class provides services to the application developer, such as :
  • Simple Velocity Runtime engine initialization methods.
  • Functions to apply the template engine to streams and strings
  • to allow embedding and dynamic template generation.
  • Methods to access Velocimacros directly.


While the most common way to use NVelocity is via templates, as Velocity is a general-purpose template engine, there are other uses that NVelocity is well suited for, such as processing dynamically created templates, or processing content streams.

The methods herein were developed to allow easy access to the NVelocity facilities without direct spelunking of the internals. If there is something you feel is necessary to add here, please, send a patch.
initialize the NVelocity runtime engine, using the default properties of the NVelocity distribution initialize the Velocity runtime engine, using default properties plus the properties in the properties file passed in as the arg file containing properties to use to initialize the Velocity runtime initialize the Velocity runtime engine, using default properties plus the properties in the passed in java.util.Properties object Proprties object containing initialization properties Set a Velocity Runtime property. key value Add a Velocity Runtime property. key value Clear a NVelocity Runtime property. of property to clear 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. Get a Velocity Runtime property. property to retrieve property value or null if the property not currently set 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. context to use in rendering input string Writer in which to render the output string to be used as the template name for log messages in case of error input string containing the VTL to be rendered true if successful, false otherwise. If false, see Velocity runtime log 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. context to use in rendering input string Writer in which to render the output string to be used as the template name for log messages in case of error input stream containing the VTL to be rendered true if successful, false otherwise. If false, see Velocity runtime log 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. context to use in rendering input string Writer in which to render the output string to be used as the template name for log messages in case of error Reader containing the VTL to be rendered true if successful, false otherwise. If false, see Velocity runtime log Invokes a currently registered Velocimacro with the parameters provided and places the rendered stream into the writer. Note : currently only accepts args to the VM if they are in the context. name of Velocimacro to call string to be used for template name in case of error args used to invoke Velocimacro. In context key format : eg "foo","bar" (rather than "$foo","$bar") Context object containing data/objects used for rendering. Writer for output stream true if Velocimacro exists and successfully invoked, false otherwise. merges a template and puts the rendered stream into the writer name of template to be used in merge filled context to be used in merge writer to write template into true if successful, false otherwise. Errors logged to velocity log. merges a template and puts the rendered stream into the writer name of template to be used in merge encoding used in template filled context to be used in merge writer to write template into true if successful, false otherwise. Errors logged to velocity log Returns a Template from the Velocity resource management system. The file name of the desired template. The template. @throws ResourceNotFoundException if template not found from any available source. @throws ParseErrorException if template cannot be parsed due to syntax (or other) error. @throws Exception if an error occurs in template initialization Returns a Template from the Velocity resource management system. The file name of the desired template. The character encoding to use for the template. The instance. If template is not found from any available source. If template cannot be parsed due to syntax (or other) error. If an error occurs in template initialization.

Determines whether a resource is accessible via the currently configured resource loaders. is the generic description of templates, static content, etc.

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.

name of the template to search for Whether the resource was located.
Log a warning message. message to log Log an info message. message to log Log an error message. message to log Log a debug message. message to log

Set the an ApplicationAttribute, which is an Object set by the application which is 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 loaders and loggers.

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.

object 'name' under which the object is stored object to store under this key
#ResourceExists(String) 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. Please ensure that you call one of the init() variants. This is critical for proper behavior. Coming soon : 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 almost certainly won't function in the way you intend, so please make sure to call init(). Geir Magnusson Jr. Init-less CTOR CTOR that invokes an init(String), initializing the engine using the properties file specified name of properties file to init with CTOR that invokes an init(String), initializing the engine using the Properties specified name of properties to init with 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. initialize the Velocity runtime engine, using the default properties of the Velocity distribution initialize the Velocity runtime engine, using default properties plus the properties in the properties file passed in as the arg file containing properties to use to initialize the Velocity runtime initialize the Velocity runtime engine, using default properties plus the properties in the passed in java.util.Properties object Properties object containing initialization properties Set a Velocity Runtime property. Add a Velocity Runtime property. Clear a Velocity Runtime property. key of property to clear Get a Velocity Runtime property. property to retrieve property value or null if the property not currently set 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. context to use in rendering input string Writer in which to render the output string to be used as the template name for log messages in case of error input string containing the VTL to be rendered true if successful, false otherwise. If false, see Velocity runtime log 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. context to use in rendering input string Writer in which to render the output string to be used as the template name for log messages in case of error input stream containing the VTL to be rendered true if successful, false otherwise. If false, see Velocity runtime log 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. context to use in rendering input string Writer in which to render the output string to be used as the template name for log messages in case of error Reader containing the VTL to be rendered true if successful, false otherwise. If false, see Velocity runtime log Invokes a currently registered Velocimacro with the parameters provided and places the rendered stream into the writer. Note : currently only accepts args to the VM if they are in the context. name of Velocimacro to call string to be used for template name in case of error args used to invoke Velocimacro. In context key format : eg "foo","bar" (rather than "$foo","$bar") Context object containing data/objects used for rendering. Writer for output stream true if Velocimacro exists and successfully invoked, false otherwise. merges a template and puts the rendered stream into the writer name of template to be used in merge filled context to be used in merge writer to write template into true if successful, false otherwise. Errors logged to velocity log. merges a template and puts the rendered stream into the writer name of template to be used in merge encoding used in template filled context to be used in merge writer to write template into true if successful, false otherwise. Errors logged to velocity log Returns a Template from the Velocity resource management system. The file name of the desired template. The template. if template not found from any available source. if template cannot be parsed due to syntax (or other) error. if an error occurs in template initialization Returns a Template from the Velocity resource management system. The file name of the desired template. The character encoding to use for the template. The template. if template not found from any available source. if template cannot be parsed due to syntax (or other) error. if an error occurs in template initialization Determines if a template is accessible 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 laziness and sloth, and the author has been flogged.
name of the template to search for true if found, false otherwise
Log a warning message. message to log Log an info message. message to log Log an error message. message to log Log a debug message. message to log

Set the an ApplicationAttribute, which is an Object set by the application which is 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 loaders and loggers.

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.

object 'name' under which the object is stored object to store under this key
Static utility methods for collections This class extends normal Java properties by adding the possibility to use the same key many times concatenating the value strings instead of overwriting them. The Extended Properties syntax is explained here:
  • Each property has the syntax key = value
  • The key may use any character but the equal sign '='.
  • value may be separated on different lines if a backslash is placed at the end of the line that continues below.
  • If value is a list of strings, each token is separated by a comma ','.
  • Commas in each token are escaped placing a backslash right before the comma.
  • If a key is used more than once, the values are appended like if they were on the same line separated with commas.
  • Blank lines and lines starting with character '#' are skipped.
  • If a property is named "include" (or whatever is defined by setInclude() and getInclude() and the value of that property is the full path to a file on disk, that file will be included into the ConfigurationsRepository. You can also pull in files relative to the parent configuration file. So if you have something like the following: include = additional.properties Then "additional.properties" is expected to be in the same directory as the parent configuration file. Duplicate name values will be replaced, so be careful.
Here is an example of a valid extended properties file:
             # lines starting with # are comments
            
             # This is the simplest property
             key = value
            
             # A long property may be separated on multiple lines
             longvalue = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \
             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
            
             # This is a property with many tokens
             tokens_on_a_line = first token, second token
            
             # This sequence generates exactly the same result
             tokens_on_multiple_lines = first token
             tokens_on_multiple_lines = second token
            
             # commas may be escaped in tokens
             commas.excaped = Hi\, what'up?
             
NOTE: this class has not been written for performance nor low memory usage. In fact, it's way slower than it could be and generates too much memory garbage. But since performance is not an issue during intialization (and there is not much time to improve it), I wrote it this way. If you don't like it, go ahead and tune it up!
Default configurations repository. The file connected to this repository (holding comments and such). Base path of the configuration file used to create this ExtendedProperties object. File separator. Has this configuration been initialized. This is the name of the property that can point to other properties file for including other properties files. These are the keys in the order they listed in the configuration file. This is useful when you wish to perform operations with configuration information in a particular order. Creates an empty extended properties object. Creates and loads the extended properties from the specified file. A String. Creates and loads the extended properties from the specified file. A String. File to load defaults from. Indicate to client code whether property resources have been initialized or not. Load the properties from the given input stream and using the specified encoding. An InputStream. An encoding. Gets a property from the configuration. * property to retrieve value as object. Will return user value if exists, if not then default value if exists, otherwise null 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"] * Adds a key/value pair to the map. This routine does no magic morphing. It ensures the keyList is maintained * key to use for mapping object to store Sets a string property w/o checking for commas - used internally when a property has been broken up into strings that could contain escaped commas to prevent the inadvertent vectorization. Thanks to Leon Messerschmidt for this one. Set a property, this will replace any previously set values. Set values is implicitly a call to clearProperty(key), addProperty(key,value). Save the properties to the given outputStream. An OutputStream. A String. Combines an existing Hashtable with this Hashtable. * Warning: It will overwrite previous entries without warning. * ExtendedProperties Clear a property in the configuration. * key to remove along with corresponding value. Get the list of the keys contained in the configuration repository. * An Iterator. Get the list of the keys contained in the configuration repository that match the specified prefix. * The prefix to test against. An Iterator of keys that match the prefix. Create an ExtendedProperties object that is a subset of this one. Take into account duplicate keys by using the setProperty() in ExtendedProperties. * prefix Display the configuration for debugging purposes. Get a string associated with the given configuration key. * The configuration key. The associated string. is thrown if the key maps to an object that is not a String. Get a string associated with the given configuration key. * The configuration key. The default value. The associated string if key is found, default value otherwise. is thrown if the key maps to an object that is not a String. Get a list of properties associated with the given configuration key. * The configuration key. The associated properties if key is found. is thrown if the key maps to an object that is not a String/Vector. if one of the tokens is malformed (does not contain an equals sign). Get a list of properties associated with the given configuration key. * The configuration key. Default property values. The associated properties if key is found. is thrown if the key maps to an object that is not a String/Vector. if one of the tokens is malformed (does not contain an equals sign). Get an array of strings associated with the given configuration key. * The configuration key. The associated string array if key is found. is thrown if the key maps to an object that is not a String/Vector. Get a Vector of strings associated with the given configuration key. * The configuration key. The associated Vector. is thrown if the key maps to an object that is not a Vector. Gets the string list. The key. Get a Vector of strings associated with the given configuration key. * The configuration key. The default value. The associated Vector. is thrown if the key maps to an object that is not a Vector. Get a boolean associated with the given configuration key. * The configuration key. The associated boolean. is thrown if the key doesn't map to an existing object. is thrown if the key maps to an object that is not a Boolean. Get a boolean associated with the given configuration key. * The configuration key. The default value. The associated boolean if key is found and has valid format, default value otherwise. is thrown if the key maps to an object that is not a Boolean. Test whether the string represent by value maps to a boolean value or not. We will allow true, on, and yes for a true boolean value, and false, off, and no for false boolean values. Case of value to test for boolean status is ignored. * The value to test for boolean state. true or false if the supplied text maps to a boolean value, or null otherwise. Get a byte associated with the given configuration key. * The configuration key. The associated byte if key is found and has valid format, otherwise. is thrown if the key doesn't map to an existing object. is thrown if the key maps to an object that is not a Byte. Get a byte associated with the given configuration key. * The configuration key. The default value. The associated byte if key is found and has valid format, default value otherwise. is thrown if the key maps to an object that is not a Byte. Get a byte associated with the given configuration key. * The configuration key. The default value. The associated byte if key is found and has valid format, default value otherwise. is thrown if the key maps to an object that is not a Byte. The purpose of this method is to get the configuration resource with the given name as an integer. * The resource name. The value of the resource as an integer. The purpose of this method is to get the configuration resource with the given name as an integer, or a default value. * The resource name The default value of the resource. The value of the resource as an integer. Get a int associated with the given configuration key. * The configuration key. The associated int if key is found and has valid format, otherwise. is thrown if the key doesn't map to an existing object. is thrown if the key maps to an object that is not a Integer. Get a int associated with the given configuration key. * The configuration key. The default value. The associated int if key is found and has valid format, otherwise. The associated int if key is found and has valid format, default value otherwise. is thrown if the key maps to an object that is not a Integer. Get a long associated with the given configuration key. * The configuration key. The associated long if key is found and has valid format, otherwise. is thrown if the key doesn't map to an existing object. is thrown if the key maps to an object that is not a Long. Get a long associated with the given configuration key. * The configuration key. The default value. The associated long if key is found and has valid format, otherwise. is thrown if the key maps to an object that is not a Long. Get a float associated with the given configuration key. * The configuration key. The associated float if key is found and has valid format, otherwise. is thrown if the key doesn't map to an existing object. is thrown if the key maps to an object that is not a Float. Get a float associated with the given configuration key. * The configuration key. The default value. The associated float if key is found and has valid format, otherwise. is thrown if the key maps to an object that is not a Float. Get a double associated with the given configuration key. * The configuration key. The associated double if key is found and has valid format, otherwise. is thrown if the key doesn't map to an existing object. is thrown if the key maps to an object that is not a Double. Get a double associated with the given configuration key. * The configuration key. The default value. The associated double if key is found and has valid format, otherwise. is thrown if the key maps to an object that is not a Double. Convert a standard properties class into a configuration class. properties object to convert into a ExtendedProperties object. ExtendedProperties configuration created from the properties object. A keyed list with a fixed maximum size which removes the least recently used entry if an entry is added when full. Default maximum size Maximum size Remove the least recently used entry (the last one in the list) Gets the maximum size of the map (the bound). This class is used to read properties lines. These lines do not terminate with new-line chars but rather when there is no backslash sign a the end of the line. This is used to concatenate multiple lines for readability. Constructor. A Reader. Read a property. A String. This class divides into tokens a property value. Token separator is "," but commas into the property value are escaped using the backslash in front. The property delimiter used while parsing (a comma). Constructor. A String Get next token. A String This class is the abstract base class for all conventional Velocity Context implementations. Simply extend this class and implement the abstract routines that access your preferred storage method. * Takes care of context chaining. * Also handles / enforces policy on null keys and values : *
  • Null keys and values are accepted and basically dropped.
  • If you place an object into the context with a null key, it will be ignored and logged.
  • If you try to place a null into the context with any key, it will be dropped and logged.
* The default implementation of this for application use is org.apache.velocity.VelocityContext. * All thanks to Fedor for the chaining idea. *
Geir Magnusson Jr. Fedor Karpelevitch Jason van Zyl $Id: AbstractContext.cs,v 1.4 2003/10/27 13:54:08 corts Exp $
class to encapsulate the 'stuff' for internal operation of velocity. We use the context as a thread-safe storage : we take advantage of the fact that it's a visitor of sorts to all nodes (that matter) of the AST during init() and render(). Currently, it carries the template name for namespace support, as well as node-local context data introspection caching. * Note that this is not a public class. It is for package access only to keep application code from accessing the internals, as AbstractContext is derived from this. * Geir Magnusson Jr. $Id: InternalContextBase.cs,v 1.4 2003/10/27 13:54:08 corts Exp $ interface to encapsulate the 'stuff' for internal operation of velocity. We use the context as a thread-safe storage : we take advantage of the fact that it's a visitor of sorts to all nodes (that matter) of the AST during init() and render(). Currently, it carries the template name for namespace support, as well as node-local context data introspection caching. Geir Magnusson Jr. Christoph Reck $Id: InternalHousekeepingContext.cs,v 1.4 2003/10/27 13:54:08 corts Exp $ set the current template name on top of stack current template name remove the current template name from stack Gets the object if exists for the key key to find in cache cache object Sets the object for the key key IntrospectionCacheData object to place in cache get the current template name String current template name Returns the template name stack in form of an array. Object[] with the template name stack contents. temporary fix to enable #include() to figure out current encoding. Interface for event support. Note that this is a public internal interface, as it is something that will be accessed from outside of the .context package. cache for node/context specific introspection information Template name stack. The stack top contains the current template name. EventCartridge we are to carry. Set by application Current resource - used for carrying encoding and other information down into the rendering process set the current template name on top of stack current template name remove the current template name from stack Interface describing the application data context. This set of routines is used by the application to set and remove 'named' data object to pass them to the template engine to use when rendering a template. This is the same set of methods supported by the original Context class Jason van Zyl Geir Magnusson Jr. Adds a name/value pair to the context. The name to key the provided value with. The corresponding value. Gets the value corresponding to the provided key from the context. The name of the desired value. The value corresponding to the provided key. Indicates whether the specified key is in the context. The key to look for. Whether the key is in the context. Removes the value associated with the specified key from the context. The name of the value to remove. The value that the key was mapped to, or null if unmapped. Returns the number of elements in this context The count. Get all the keys for the values in the context the chained Context if any default CTOR Chaining constructor accepts a Context argument. It will relay get() operations into this Context in the even the 'local' get() returns null. context to be chained Implement to return a value from the context storage.

The implementation of this method is required for proper operation of a Context implementation in general Velocity use.
key whose associated value is to be returned object stored in the context
Implement to put a value into the context storage.

The implementation of this method is required for proper operation of a Context implementation in general Velocity use. *
key with which to associate the value value to be associated with the key previously stored value if exists, or null
Implement to determine if a key is in the storage.

Currently, this method is not used internally by the Velocity core. *
key to test for existance true if found, false if not
Implement to return an object array of key strings from your storage.

Currently, this method is not used internally by the Velocity core. *
array of keys
Implement to remove an item from your storage.

Currently, this method is not used internally by the Velocity core. *
key to remove object removed if exists, else null
Adds a name/value pair to the context. The name to key the provided value with. The corresponding value. Object that was replaced in the the Context if applicable or null if not. Gets the value corresponding to the provided key from the context. * Supports the chaining context mechanism. If the 'local' context doesn't have the value, we try to get it from the chained context. * The name of the desired value. The value corresponding to the provided key or null if the key param is null. Indicates whether the specified key is in the context. Provided for debugging purposes. * The key to look for. true if the key is in the context, false if not. Get all the keys for the values in the context Object[] of keys in the Context. Does not return keys in chained context. Removes the value associated with the specified key from the context. * The name of the value to remove. The value that the key was mapped to, or null if unmapped. interface to bring all necessary internal and user contexts together. this is what the AST expects to deal with. If anything new comes along, add it here. * I will rename soon :) * Geir Magnusson Jr. $Id: InternalContextAdapter.cs,v 1.3 2003/10/27 13:54:08 corts Exp $ interface for internal context wrapping functionality Geir Magnusson Jr. $Id: InternalWrapperContext.cs,v 1.4 2003/10/27 13:54:08 corts Exp $ returns the wrapped user context returns the base full context impl Need to define this method here otherwise since both and contains a Remove(Object key) method we will need to cast the object to either interface before calling this method, for backward compatibility we make the IContext.Remove the default This adapter class is the container for all context types for internal use. The AST now uses this class rather than the app-level Context interface to allow flexibility in the future. * Currently, we have two context interfaces which must be supported :
  • Context : used for application/template data access
  • InternalHousekeepingContext : used for internal housekeeping and caching
  • InternalWrapperContext : used for getting root cache context and other such.
  • InternalEventContext : for event handling.
* This class implements the two interfaces to ensure that all methods are supported. When adding to the interfaces, or adding more context functionality, the interface is the primary definition, so alter that first and then all classes as necessary. As of this writing, this would be the only class affected by changes to InternalContext * This class ensures that an InternalContextBase is available for internal use. If an application constructs their own Context-implementing object w/o sub-classing AbstractContext, it may be that support for InternalContext is not available. Therefore, InternalContextAdapter will create an InternalContextBase if necessary for this support. Note that if this is necessary, internal information such as node-cache data will be lost from use to use of the context. This may or may not be important, depending upon application. *
Geir Magnusson Jr. $Id: InternalContextAdapterImpl.cs,v 1.4 2003/10/27 13:54:08 corts Exp $
the user data Context that we are wrapping the ICB we are wrapping. We may need to make one if the user data context implementation doesn't support one. The default AbstractContext-derived VelocityContext does, and it's recommended that people derive new contexts from AbstractContext rather than piecing things together The InternalEventContext that we are wrapping. If the context passed to us doesn't support it, no biggie. We don't make it for them - since its a user context thing, nothing gained by making one for them now CTOR takes a Context and wraps it, delegating all 'data' calls to it. For support of internal contexts, it will create an InternalContextBase if need be. returns the user data context that we are wrapping Returns the base context that we are wrapping. Here, its this, but for other thing like VM related context contortions, it can be something else This is a special, internal-use-only context implementation to be used for the new Velocimacro implementation. * The main distinguishing feature is the management of the VMProxyArg objects in the put() and get() methods. * Further, this context also supports the 'VM local context' mode, where any get() or put() of references that aren't args to the VM are considered local to the vm, protecting the global context. Geir Magnusson Jr. $Id: VMContext.cs,v 1.4 2003/10/27 13:54:08 corts Exp $ container for our VMProxy Objects container for any local or constant VMProxy items the base context store. This is the 'global' context context that we are wrapping support for local context scope feature, where all references are local CTOR, wraps an ICA return the inner / user context Used to put VMProxyArgs into this context. It separates the VMProxyArgs into constant and non-constant types pulling out the value of the constant types so they can be modified w/o damaging the VMProxyArg, and leaving the dynamic ones, as they modify context rather than their own state VMProxyArg to add Impl of the Context.put() method. * name of item to set object to set to key old stored object Impl of the Context.gut() method. * name of item to get stored object or null not yet impl impl badly impl badly Application-level exception thrown when a reference method is invoked and an exception is thrown.
When this exception is thrown, a best effort will be made to have useful information in the exception's message. For complete information, consult the runtime log.
Geir Magnusson Jr. $Id: MethodInvocationException.cs,v 1.3 2003/10/27 13:54:08 corts Exp $
Base class for Velocity exceptions thrown to the application layer. Wraps the passed in exception for examination later Application-level exception thrown when a resource of any type has a syntax or other error which prevents it from being parsed.
When this resource is thrown, a best effort will be made to have useful information in the exception's message. For complete information, consult the runtime log. *
Geir Magnusson Jr. $Id: ParseErrorException.cs,v 1.3 2003/10/27 13:54:08 corts Exp $
Application-level exception thrown when a resource of any type isn't found by the Velocity engine.
When this exception is thrown, a best effort will be made to have useful information in the exception's message. For complete information, consult the runtime log.
Base class for all directives used in Velocity. Jason van Zyl $Id: Directive.cs,v 1.3 2003/10/27 13:54:10 corts Exp $ How this directive is to be initialized. Allows the template location to be set How this directive is to be rendered Return the name of this directive Get the directive type BLOCK/LINE for log msg purposes for log msg purposes Directive Types Foreach directive used for moving through arrays, or objects that provide an Iterator. The name of the variable to use when placing the counter value into the context. Right now the default is $velocityCount. What value to start the loop counter at. The reference name used to access each of the elements in the list object. It is the $item in the following: #foreach ($item in $list) This can be used class wide because it is immutable. simple init - init the tree and get the elementKey from the AST returns an Iterator to the collection in the #foreach() current context AST node Iterator to do the dataset renders the #foreach() block Return name of this directive. Return type of this directive. Pluggable directive that handles the #include() statement in VTL. This #include() can take multiple arguments of either StringLiteral or Reference. Notes: ----- 1) The included source material can only come from somewhere in the TemplateRoot tree for security reasons. There is no way around this. If you want to include content from elsewhere on your disk, use a link from somewhere under Template Root to that content. 2) By default, there is no output to the render stream in the event of a problem. You can override this behavior with two property values : include.output.errormsg.start include.output.errormsg.end If both are defined in velocity.properties, they will be used to in the render output to bracket the arg string that caused the problem. Ex. : if you are working in html then include.output.errormsg.start= might be an excellent way to start... 3) As noted above, #include() can take multiple arguments. Ex : #include( "foo.vm" "bar.vm" $foo ) will simply include all three if valid to output w/o any special separator. Geir Magnusson Jr. Jason van Zyl Kasper Nielsen $Id: Include.cs,v 1.3 2003/10/27 13:54:10 corts Exp $ simple init - init the tree and get the elementKey from the AST iterates through the argument list and renders every argument that is appropriate. Any non appropriate arguments are logged, but render() continues. does the actual rendering of the included file AST argument of type StringLiteral or Reference valid context so we can render References output Writer boolean success or failure. failures are logged Puts a message to the render output stream if ERRORMSG_START / END are valid property strings. Mainly used for end-user template debugging. Return name of this directive. Return type of this directive. A very simple directive that leverages the Node.literal() to grab the literal rendition of a node. We basically grab the literal value on init(), then repeatedly use that during render(). Jason van Zyl $Id: Literal.cs,v 1.3 2003/10/27 13:54:10 corts Exp $ Store the literal rendition of a node using the Node.literal(). Throw the literal rendition of the block between #literal()/#end into the writer. Return name of this directive. Return type of this directive. Macro implements the macro definition directive of VTL. example : #macro( isnull $i ) #if( $i ) $i #end #end This object is used at parse time to mainly process and register the macro. It is used inline in the parser when processing a directive. Geir Magnusson Jr. $Id: Macro.cs,v 1.3 2003/10/27 13:54:10 corts Exp $ Return name of this directive. Return type of this directive. render() doesn't do anything in the final output rendering. There is no output from a #macro() directive. Used by Parser.java to process VMs within the parsing process processAndRegister() doesn't actually render the macro to the output Processes the macro body into the internal representation used by the VelocimacroProxy objects, and if not currently used, adds it to the macro Factory creates an array containing the literal strings in the macro argument Returns an array of the literal rep of the AST Pluggable directive that handles the #parse() statement in VTL. Notes: ----- 1) The parsed source material can only come from somewhere in the TemplateRoot tree for security reasons. There is no way around this. If you want to include content from elsewhere on your disk, use a link from somewhere under Template Root to that content. 2) There is a limited parse depth. It is set as a property "parse_directive.maxdepth = 10" for example. There is a 20 iteration safety in the event that the parameter isn't set. Geir Magnusson Jr. Jason van Zyl Christoph Reck $Id: Parse.cs,v 1.4 2003/10/27 13:54:10 corts Exp $ iterates through the argument list and renders every argument that is appropriate. Any non appropriate arguments are logged, but render() continues. See if we have exceeded the configured depth. If it isn't configured, put a stop at 20 just in case. Return name of this directive. Return type of this directive. Exception for #parse() problems * Geir Magnusson Jr. $Id: ParseDirectiveException.cs,v 1.3 2003/10/27 13:54:10 corts Exp $ Constructor Get a message. Add a file to the filename stack VelocimacroProxy a proxy Directive-derived object to fit with the current directive system Geir Magnusson Jr. $Id: VelocimacroProxy.cs,v 1.4 2003/10/27 13:54:10 corts Exp $ The major meat of VelocimacroProxy, init() checks the # of arguments, patches the macro body, renders the macro into an AST, and then initiates the AST, so it is ready for quick rendering. Note that this is only AST dependant stuff. Not context. Renders the macro using the context basic VM setup. Sets up the proxy args for this use, and parses the tree parses the macro. We need to do this here, at init time, or else the local-scope template feature is hard to get to work :) Gets the args to the VM from the instance-use AST The name of this Velocimacro. Velocimacros are always LINE type directives. Sets the array of arguments specified in the macro definition Returns the number of arguments needed for this VM Sets the original macro body. This is simply the cat of the macroArray, but the Macro object creates this once during parsing, and everyone shares it. Note : it must not be modified. The function of this class is to proxy for the calling parameter to the VM. * This class is designed to be used in conjunction with the VMContext class which knows how to get and set values via it, rather than a simple get() or put() from a hashtable-like object. * There is probably a lot of undocumented subtlety here, so step lightly. * We rely on the observation that an instance of this object has a constant state throughout its lifetime as it's bound to the use-instance of a VM. In other words, it's created by the VelocimacroProxy class, to represent one of the arguments to a VM in a specific template. Since the template is fixed (it's a file...), we don't have to worry that the args to the VM will change. Yes, the VM will be called in other templates, or in other places on the same template, bit those are different use-instances. * These arguments can be, in the lingo of the parser, one of :
  • Reference() : anything that starts with '$'
  • StringLiteral() : something like "$foo" or "hello geir"
  • NumberLiteral() : 1, 2 etc
  • IntegerRange() : [ 1..2] or [$foo .. $bar]
  • ObjectArray() : [ "a", "b", "c"]
  • True() : true
  • False() : false
  • Word() : not likely - this is simply allowed by the parser so we can have syntactical sugar like #foreach($a in $b) where 'in' is the Word
Now, Reference(), StringLit, NumberLit, IntRange, ObjArr are all dynamic things, so their value is gotten with the use of a context. The others are constants. The trick we rely on is that the context rather than this class really represents the state of the argument. We are simply proxying for the thing, returning the proper value when asked, and storing the proper value in the appropriate context when asked. * So, the hope here, so an instance of this can be shared across threads, is to keep any dynamic stuff out of it, relying on trick of having the appropriate context handed to us, and when a constant argument, letting VMContext punch that into a local context.
Geir Magnusson Jr. $Id: VMProxyArg.cs,v 1.4 2003/10/27 13:54:10 corts Exp $
in the event our type is switched - we don't care really what it is type of arg I will have the AST if the type is such that it's dynamic (ex. JJTREFERENCE ) reference for the object if we proxy for a static arg like an NumberLiteral not used in this impl : carries the appropriate user context number of children in our tree if a reference our identity in the current context the reference we are proxying for the 'de-dollared' reference if we are a ref but don't have a method attached by default, we are dynamic. safest ctor for current impl * takes the reference literal we are proxying for, the literal the VM we are for is called with... * reference arg in the definition of the VM, used in the VM reference used by the caller as an arg to the VM type of arg : JJTREFERENCE, JJTTRUE, etc tells if arg we are proxying for is dynamic or constant. * true of constant, false otherwise Invoked by VMContext when Context.put() is called for a proxied reference. * context to modify via direct placement, or AST.setValue() new value of reference Object currently null returns the value of the reference. Generally, this is only called for dynamic proxies, as the static ones should have been stored in the VMContext's localContext store * Context to use for getting current value Object value * does the housekeeping upon creating. If a dynamic type it needs to make an AST for further get()/set() operations Anything else is constant. not used in current impl * Constructor for alternate impl where VelProxy class would make new VMProxyArg objects, and use this constructor to avoid re-parsing the reference args * that impl also had the VMProxyArg carry it's context Exception thrown when a bad reference is found. * Geir Magnusson Jr. $Id: ReferenceException.cs,v 1.3 2003/10/27 13:54:10 corts Exp $ Prefix for debug messages. Prefix for info messages. Prefix for warning messages. Prefix for error messages. Base interface that Logging systems need to implement. Jon S. Stevens Geir Magnusson Jr. init() Send a log message from Velocity.

This class is responsible for instantiating the correct LoggingSystem

The approach is :

  • First try to see if the user is passing in a living object that is a LogSystem, allowing the app to give is living custom loggers.
  • Next, run through the (possible) list of classes specified specified as loggers, taking the first one that appears to work. This is how we support finding either log4j or logkit, whichever is in the classpath, as both are listed as defaults.
  • Finally, we turn to 'faith-based' logging, and hope that logkit is in the classpath, and try for an AvalonLogSystem as a final gasp. After that, there is nothing we can do.
Jason van Zyl Jon S. Stevens Geir Magnusson Jr.
Creates a new logging system or returns an existing one specified by the application. Logger used in case of failure. Does nothing. * Geir Magnusson Jr. $Id: NullLogSystem.cs,v 1.4 2003/10/27 13:54:10 corts Exp $ logs messages to the great Garbage Collector in the sky severity level complete error message Abstract class that is used to execute an arbitrary method that is in introspected. This is the superclass for the GetExecutor and PropertyExecutor. Method to be executed. Execute method against context. Handles integer addition of nodes Please look at the Parser.jjt file which is what controls the generation of this class. Jason van Zyl Geir Magnusson Jr. $Id: ASTAddNode.cs,v 1.3 2003/10/27 13:54:10 corts Exp $ All AST nodes must implement this interface. It provides basic machinery for constructing the parent and child relationships between nodes. This method is called after the node has been made the current node. It indicates that child nodes can now be added to it. This method is called after all the child nodes have been added. This method tells the node to add its argument to the node's list of children. This method returns a child node. The children are numbered from zero, left to right. Accept the visitor. Accept the visitor. * Accept the visitor. * Accept the visitor. Computes the sum of the two nodes. Currently only integer operations are supported. Integer object with value, or null Please look at the Parser.jjt file which is what controls the generation of this class. Jason van Zyl Geir Magnusson Jr. $Id: ASTAndNode.cs,v 1.3 2003/10/27 13:54:10 corts Exp $ Accept the visitor. Returns the value of the expression. Since the value of the expression is simply the boolean result of evaluate(), lets return that. logical and : null && right = false left && null = false null && null = false Accept the visitor. Accept the visitor. Accept the visitor. This class is responsible for handling the pluggable directives in VTL. ex. #foreach() Please look at the Parser.jjt file which is what controls the generation of this class. Accept the visitor. Gets or sets the directive name. Used by the parser. This keeps us from having to dig it out of the token stream and gives the parse the change to override. Handles integer division of nodes Please look at the Parser.jjt file which is what controls the generation of this class. Jason van Zyl Geir Magnusson Jr. $Id: ASTDivNode.cs,v 1.3 2003/10/27 13:54:10 corts Exp $ Accept the visitor. Computes the result of the division. Currently limited to Integers. Integer(value) or null This class is responsible for handling the ElseIf VTL control statement. Please look at the Parser.jjt file which is what controls the generation of this class. * Jason van Zyl Geir Magnusson Jr. $Id: ASTElseIfStatement.cs,v 1.3 2003/10/27 13:54:10 corts Exp $ Accept the visitor. An ASTElseStatement is true if the expression it contains evaluates to true. Expressions know how to evaluate themselves, so we do that here and return the value back to ASTIfStatement where this node was originally asked to evaluate itself. renders the block This class is responsible for handling the Else VTL control statement. Please look at the Parser.jjt file which is what controls the generation of this class. Jason van Zyl Geir Magnusson Jr. $Id: ASTElseStatement.cs,v 1.3 2003/10/27 13:54:10 corts Exp $ Accept the visitor. An ASTElseStatement always evaluates to true. Basically behaves like an #if(true). Handles the equivalence operator <arg1> == <arg2> This operator requires that the LHS and RHS are both of the same Class. $Id: ASTEQNode.cs,v 1.3 2003/10/27 13:54:10 corts Exp $ Accept the visitor. * Calculates the value of the logical expression arg1 == arg2 All class types are supported. Uses equals() to determine equivalence. This should work as we represent with the types we already support, and anything else that implements equals() to mean more than identical references. internal context used to evaluate the LHS and RHS true if equivalent, false if not equivalent, false if not compatible arguments, or false if either LHS or RHS is null This class is responsible for handling Escapes in VTL. Please look at the Parser.jjt file which is what controls the generation of this class. * Accept the visitor. * This class is responsible for handling EscapedDirectives in VTL. Please look at the Parser.jjt file which is what controls the generation of this class. Geir Magnusson Jr. $Id: ASTEscapedDirective.cs,v 1.3 2003/10/27 13:54:10 corts Exp $ Accept the visitor. Accept the visitor. Accept the visitor. Accept the visitor. Accept the visitor. ASTIdentifier.java Method support for identifiers : $foo mainly used by ASTReference Introspection is now moved to 'just in time' or at render / execution time. There are many reasons why this has to be done, but the primary two are thread safety, to remove any context-derived information from class member variables. Jason van Zyl Geir Magnusson Jr. $Id: ASTIdentifier.cs,v 1.5 2004/12/27 05:55:30 corts Exp $ Accept the visitor. simple init - don't do anything that is context specific. just get what we need from the AST, which is static. invokes the method on the object passed in Accept the visitor. Accept the visitor. Accept the visitor. does the real work. Creates an Vector of Integers with the right value range app context used if Left or Right of .. is a ref Object array of Integers Accept the visitor. * Accept the visitor. AST Node for creating a map / dictionary. This class was originally generated from Parset.jjt. $Id: ASTMap.cs,v 1.2 2004/12/27 05:50:11 corts Exp $ Accept the visitor. Evaluate the node. Method support for references : $foo.method() NOTE : introspection is now done at render time. Please look at the Parser.jjt file which is what controls the generation of this class. Accept the visitor. simple init - init our subtree and get what we can from the AST invokes the method. Returns null if a problem, the actual return if the method returns something, or an empty string "" if the method returns void does the introspection of the class for the method needed. NOTE: this will try to flip the case of the first character for convince (compatibility with Java version). If there are no arguments, it will also try to find a property with the same name (also flipping first character). Accept the visitor. Handles integer multiplication Please look at the Parser.jjt file which is what controls the generation of this class. Jason van Zyl Geir Magnusson Jr. $Id: ASTMulNode.cs,v 1.3 2003/10/27 13:54:10 corts Exp $ Accept the visitor. * Computes the product of the two args. Returns null if either arg is null or if either arg is not an integer Accept the visitor. Accept the visitor. Accept the visitor. * Initialization method - doesn't do much but do the object creation. We only need to do it once. Accept the visitor. Please look at the Parser.jjt file which is what controls the generation of this class. Jason van Zyl Geir Magnusson Jr. $Id: ASTOrNode.cs,v 1.3 2003/10/27 13:54:10 corts Exp $ Accept the visitor. * Returns the value of the expression. Since the value of the expression is simply the boolean result of evaluate(), lets return that. the logical or : the rule : left || null -> left null || right -> right null || null -> false left || right -> left || right Accept the visitor. Accept the visitor. * Reference types This class is responsible for handling the references in VTL ($foo). Please look at the Parser.jjt file which is what controls the generation of this class. Jason van Zyl Geir Magnusson Jr. Christoph Reck Kent Johnson $Id: ASTReference.cs,v 1.4 2003/10/27 13:54:10 corts Exp $ Accept the visitor. gets an Object that 'is' the value of the reference gets the value of the reference and outputs it to the writer. context of data to use in getting value writer to render to Computes boolean value of this reference Returns the actual value of reference return type boolean, and 'true' if value is not null context to compute value with Sets the value of a complex reference (something like $foo.bar) Currently used by ASTSetReference() context object containing this reference Object to set as value true if successful, false otherwise Returns the 'root string', the reference key Node for the #set directive Accept the visitor. * simple init. We can get the RHS and LHS as the the tree structure is static puts the value of the RHS into the context under the key of the LHS ASTStringLiteral support. Initializes a new instance of the class. The id. Initializes a new instance of the class. The p. The id. init : we don't have to do much. Init the tree (there shouldn't be one) and then see if interpolation is turned on. Accept the visitor. * renders the value of the string literal If the properties allow, and the string literal contains a $ or a # the literal is rendered against the context Otherwise, the stringlit is returned. Interpolates the dictionary string. dictionary string is any string in the format "%{ key='value' [,key2='value2' }" "%{ key='value' [,key2='value2'] }" If valid input a HybridDictionary with zero or more items, otherwise the input string NVelocity runtime context Handles integer subtraction of nodes (in #set() ) Please look at the Parser.jjt file which is what controls the generation of this class. Jason van Zyl Geir Magnusson Jr. $Id: ASTSubtractNode.cs,v 1.3 2003/10/27 13:54:10 corts Exp $ Accept the visitor. Computes the value of the subtraction. Currently limited to integers. Integer(value) or null Accept the visitor. Accept the visitor. Accept the visitor. Accept the visitor. Handles discovery and valuation of a boolean object property, of the form public boolean is<property> when executed. We do this separately as to preserve the current quasi-broken semantics of get<as is property> get< flip 1st char> get("property") and now followed by is<Property> Returned the value of object property when executed. Execute property against context. Executor that simply tries to execute a get(key) operation. This will try to find a get(key) method for any type of object, not just objects that implement the Map interface as was previously the case. Jason van Zyl Add discovery for .NET default property, using . Container to hold the 'key' part of get(key). Default constructor. Execute method against context. Utilities for dealing with the AST node structure. * Jason van Zyl Geir Magnusson Jr. $Id: NodeUtils.cs,v 1.4 2003/10/27 13:54:10 corts Exp $ Collect all the <SPECIAL_TOKEN>s that are carried along with a token. Special tokens do not participate in parsing but can still trigger certain lexical actions. In some cases you may want to retrieve these special tokens, this is simply a way to extract them. complete node literal * Utility method to interpolate context variables into string literals. So that the following will work: * #set $name = "candy" $image.getURI("${name}.jpg") * And the string literal argument will be transformed into "candy.jpg" before the method is executed. ObjectComparer allows you to compare primitive types and some others using IComparable interface whenever possible, and performing type conversions to get the best possible result. Tries to compare two random objects. -1 is returned if x is smaller than y, 1 the other way around, or 0 if they are equal. This interface describes a character stream that maintains line and column number positions of the characters. It also has the capability to backup the stream to some extent. An implementation of this interface is used in the TokenManager implementation generated by JavaCCParser. All the methods except backup can be implemented in any fashion. backup needs to be implemented correctly for the correct operation of the lexer. Rest of the methods are all used to get information like line number, column number and the String that constitutes a token and are not used by the lexer. Hence their implementation won't affect the generated lexer's operation. Returns the next character from the selected input. The method of selecting the input is the responsibility of the class implementing this interface. Can throw any java.io.IOException. Backs up the input stream by amount steps. Lexer calls this method if it had already read some characters, but could not use them to match a (longer) token. So, they will be used again as the prefix of the next token and it is the implemetation's responsibility to do this right. Returns the next character that marks the beginning of the next token. All characters must remain in the buffer between two successive calls to this method to implement backup correctly. Returns a string made up of characters from the marked token beginning to the current buffer position. Implementations have the choice of returning anything that they want to. For example, for efficiency, one might decide to just return null, which is a valid implementation. Returns an array of characters that make up the suffix of length 'len' for the currently matched token. This is used to build up the matched string for use in actions in the case of MORE. A simple and inefficient implementation of this is as follows : { String t = GetImage(); return t.substring(t.length() - len, t.length()).toCharArray(); } The lexer calls this function to indicate that it is done with the stream and hence implementations can free any resources held by this class. Again, the body of this function can be just empty and it will not affect the lexer's operation. The currenct character. Gets the column. The column. Gets the line. The line. Gets the end column. The end column. Gets the end line. The end line. Gets the begin column. The begin column. Gets the begin line. The begin line. This exception is thrown when parse errors are encountered. You can explicitly create objects of this exception type by calling the method generateParseException in the generated parser. * You can modify this class to customize your error reporting mechanisms so long as you retain the public fields. The end of line string for this machine. This constructor is used by the method "generateParseException" in the generated parser. Calling this constructor generates a new object of this type with the fields "currentToken", "expectedTokenSequences", and "tokenImage" set. The boolean flag "specialConstructor" is also set to true to indicate that this constructor was used to create this object. This constructor calls its super class with the empty string to force the "toString" method of parent class "Throwable" to print the error message in the form: ParseException: <result of getMessage> The following constructors are for use by you for whatever purpose you can think of. Constructing the exception in this manner makes the exception behave in the normal way - i.e., as documented in the class "Throwable". The fields "errorToken", "expectedTokenSequences", and "tokenImage" do not contain relevant information. The JavaCC generated code does not use these constructors. This variable determines which constructor was used to create this object and thereby affects the semantics of the "getMessage" method (see below). This is the last token that has been consumed successfully. If this object has been created due to a parse error, the token following this token will (therefore) be the first error token. Each entry in this array is an array of integers. Each array of integers represents a sequence of tokens (by their ordinal values) that is expected at this point of the parse. This is a reference to the "tokenImage" array of the generated parser within which the parse error occurred. This array is defined in the generated ...Constants interface. This method has the standard behavior when this object has been created using the standard constructors. Otherwise, it uses "currentToken" and "expectedTokenSequences" to generate a parse error message and returns it. If this object has been created due to a parse error, and you do not catch it (it gets thrown from the parser), then this method is called during the printing of the final stack trace, and hence the correct error message gets displayed. Used to convert raw characters to their escaped version when these raw version cannot be used as part of an ASCII string literal. This class is responsible for parsing a Velocity template. This class was generated by JavaCC using the JJTree extension to produce an Abstract Syntax Tree (AST) of the template. Please look at the Parser.jjt file which is what controls the generation of this class. This Hashtable contains a list of all of the dynamic directives. Name of current template we are parsing. Passed to us in parse() This constructor was added to allow the re-use of parsers. The normal constructor takes a single argument which an InputStream. This simply creates a re-usable parser object, we satisfy the requirement of an InputStream by using a newline character as an input stream. This was also added to allow parsers to be re-usable. Normal JavaCC use entails passing an input stream to the constructor and the parsing process is carried out once. We want to be able to re-use parsers: we do this by adding this method and re-initializing the lexer with the new stream that we want parsed. This method finds out of the directive exists in the directives Hashtable. Produces a processed output for an escaped control or pluggable directive This method is what starts the whole parsing process. After the parsing is complete and the template has been turned into an AST, this method returns the root of AST which can subsequently be traversed by a visitor which implements the ParserVisitor interface which is generated automatically by JavaCC These are the types of statements that are acceptable in Velocity templates. used to separate the notion of a valid directive that has been escaped, versus something that looks like a directive and is just schmoo. This is important to do as a separate production that creates a node, because we want this, in either case, to stop the further parsing of the Directive() tree. Used to catch and process escape sequences in grammatical constructs as escapes outside of VTL are just characters. Right now we have both this and the EscapeDirective() construction because in the EscapeDirective() case, we want to suck in the #<directive> and here we don't. We just want the escapes to render correctly This method corresponds to variable references in Velocity templates. The following are examples of variable references that may be found in a template: * $foo $bar * Supports the arguments for the Pluggable Directives We add whitespace in here as a token so the VMs can easily reconstruct a macro body from the token stream See Directive() Supports the Pluggable Directives #foo( arg+ ) supports the [n..m] vector generator for use in the #foreach() to generate measured ranges w/o needing explicit support from the app/servlet This method has yet to be fully implemented but will allow arbitrarily nested method calls This method has yet to be fully implemented but will allow arbitrarily nested method calls This method is responsible for allowing all non-grammar text to pass through unscathed. Currently support both types of set : #set( expr ) #set expr This method corresponds to the #stop directive which just simulates and EOF so that parsing stops. The #stop directive is useful for end-user debugging purposes. Determines whether the current node was actually closed and pushed. This should only be called in the final user action of a node scope. Call this to reinitialize the node stack. It is called automatically by the parser's ReInit() method. Pushes a node on to the stack. Returns the node on the top of the stack, and remove it from the stack. Returns the node currently on the top of the stack. Returns the number of children on the stack in the current node scope. A definite node is constructed from a specified number of children. That number of nodes are popped from the stack and made the children of the definite node. Then the definite node is pushed on to the stack. A conditional node is constructed if its condition is true. All the nodes that have been pushed since the node was opened are made children of the the conditional node, which is then pushed on to the stack. If the condition is false the node is not constructed and they are left on the stack. Returns the root node of the AST. It only makes sense to call this after a successful parse. pushes the current state onto the 'state stack', and maintains the parens counts public because we need it in PD & VM handling @return bool : success. It can fail if the state machine gets messed up (do don't mess it up :) pops a state off the stack, and restores paren counts @return bool : success of operation Clears all state variables, resets to start values, clears stateStack. Call before parsing. @return void handles the dropdown logic when encountering a RPAREN private constructor as class is meant to hold constants only. Class was originally an interface in Java, but as C# does not support Fields in an interface and the jjtNodeName field, I converted it to a class with no constructor. Describes the input token stream. An integer that describes the kind of this token. This numbering system is determined by JavaCCParser, and a table of these numbers is stored in the file ...Constants.java. beginLine and beginColumn describe the position of the first character of this token; endLine and endColumn describe the position of the last character of this token. beginLine and beginColumn describe the position of the first character of this token; endLine and endColumn describe the position of the last character of this token. beginLine and beginColumn describe the position of the first character of this token; endLine and endColumn describe the position of the last character of this token. beginLine and beginColumn describe the position of the first character of this token; endLine and endColumn describe the position of the last character of this token. The string image of the token. A reference to the next regular (non-special) token from the input stream. If this is the last token from the input stream, or if the token manager has not read tokens beyond this one, this field is set to null. This is true only if this token is also a regular token. Otherwise, see below for a description of the contents of this field. This field is used to access special tokens that occur prior to this token, but after the immediately preceding regular (non-special) token. If there are no such special tokens, this field is set to null. When there are more than one such special token, this field refers to the last of these special tokens, which in turn refers to the next previous special token through its specialToken field, and so on until the first special token (whose specialToken field is null). The next fields of special tokens refer to other special tokens that immediately follow it (without an intervening regular token). If there is no such token, this field is null. Returns the image. Returns a new Token object, by default. However, if you want, you can create and return subclass objects based on the value of ofKind. Simply add the cases to the switch for all those special cases. For example, if you have a subclass of Token called IDToken that you want to create if ofKind is ID, simply add something like : case MyParserConstants.ID : return new IDToken(); to the following switch statement. Then you can cast matchedToken variable to the appropriate type and use it in your lexical actions. Lexical error occurred. An attempt was made to create a second instance of a static token manager. Tried to change to an invalid lexical state. Detected (and bailed out of) an infinite loop in the token manager. Indicates the reason why the exception is thrown. It will have one of the above 4 values. Replaces unprintable characters by their escaped (or unicode escaped) equivalents in the given string Returns a detailed message for the Error when it is thrown by the token manager to indicate a lexical error. Parameters : EOFSeen : indicates if EOF caused the lexical error curLexState : lexical state in which this error occurred errorLine : line number when the error occurred errorColumn : column number when the error occurred errorAfter : prefix that was seen before this error occurred currentCharacter : the offending character Note: You can customize the lexical error message by modifying this method. You can also modify the body of this method to customize your error messages. For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE are not of end-users concern, so you can return something like : * "Internal Error : Please file a bug report .... " * from this method for such cases in the release version of your parser. NOTE : This class was originally an ASCII_CharStream autogenerated by Javacc. It was then modified via changing class name with appropriate fixes for CTORS, and mods to readChar(). This is safe because we *always* use Reader with this class, and never a InputStream. This guarantees that we have a correct stream of 16-bit chars - all encoding transformations have been done elsewhere, so we believe that there is no risk in doing this. Time will tell :) An implementation of interface CharStream, where the stream is assumed to contain only ASCII characters (without unicode processing). Method to adjust line and column numbers for the start of a token.
This is abstract class the all text resource loaders should extend. Jason van Zyl Geir Magnusson Jr. $Id: ResourceLoader.cs,v 1.3 2003/10/27 13:54:11 corts Exp $ Does this loader want templates produced with it cached in the Runtime. This property will be passed on to the templates that are created with this loader. Class name for this loader, for logging/debugging purposes. This initialization is used by all resource loaders and must be called to set up common properties shared by all resource loaders Initialize the template loader with a a resources class. Get the InputStream that the Runtime will parse to create a template. Given a template, check to see if the source of InputStream has been modified. Get the last modified time of the InputStream source that was used to create the template. We need the template here because we have to extract the name of the template in order to locate the InputStream source. Return the class name of this resource Loader Set the caching state. If true, then this loader would like the Runtime to cache templates that have been created with InputStreams provided by this loader. Initialize the template loader with a a resources class. Get the InputStream that the Runtime will parse to create a template. Given a template, check to see if the source of InputStream has been modified. Get the last modified time of the InputStream source that was used to create the template. We need the template here because we have to extract the name of the template in order to locate the InputStream source. Initialize the template loader with a resources class. Get the InputStream that the Runtime will parse to create a template. Given a template, check to see if the source of InputStream has been modified. Get the last modified time of the InputStream source that was used to create the template. We need the template here because we have to extract the name of the template in order to locate the InputStream source. A loader for templates stored on the file system. The paths to search for templates. Used to map the path that a template was found on so that we can properly check the modification times of the files. Get an InputStream so that the Runtime can build a template with it. name of template to get InputStream containing the template @throws ResourceNotFoundException if template not found in the file template path. Try to find a template given a normalized path. a normalized path filename of template to get InputStream input stream that will be parsed How to keep track of all the modified times across the paths. Factory to grab a template loader. Jason van Zyl Gets the loader specified in the configuration file. TemplateLoader This class represent a general text resource that may have been retrieved from any number of possible sources. Also of interest is Velocity's {@link org.apache.velocity.Template} Resource. Jason van Zyl Geir Magnusson Jr. $Id: ContentResource.cs,v 1.5 2004/01/02 00:09:23 corts Exp $ This class represent a general text resource that may have been retrieved from any number of possible sources. Jason van Zyl Geir Magnusson Jr. $Id: Resource.cs,v 1.5 2004/01/02 00:13:51 corts Exp $ The number of milliseconds in a minute, used to calculate the check interval. Resource might require ancillary storage of some kind Character encoding of this resource The file modification time (in milliseconds) for the cached template. How often the file modification time is checked (in milliseconds). Name of the resource The next time the file modification time will be checked (in milliseconds). The template loader that initially loaded the input stream for this template, and knows how to check the source of the input stream for modification. Perform any subsequent processing that might need to be done by a resource. In the case of a template the actual parsing of the input stream needs to be performed. Whether the resource could be processed successfully. For a {@link org.apache.velocity.Template} or {@link org.apache.velocity.runtime.resource.ContentResource}, this indicates whether the resource could be read. @exception ResourceNotFoundException Similar in semantics as returning false. Set the modification check interval. Is it time to check to see if the resource source has been updated? 'Touch' this template and thereby resetting the nextCheck field. Set arbitrary data object that might be used by the resource. Get arbitrary data object that might be used by the resource. set the encoding of this resource for example, "ISO-8859-1" get the encoding of this resource for example, "ISO-8859-1" Return the lastModified time of this template. Set the last modified time for this template. Set the name of this resource, for example test.vm. Get the name of this template. Return the template loader that pulled in the template stream Set the template loader for this template. Set when the Runtime determines where this template came from the list of possible sources. Default empty constructor Pull in static content and store it. @exception ResourceNotFoundException Resource could not be found. Interface that defines the shape of a pluggable resource cache for the included ResourceManager * Geir Magnusson Jr. $Id: ResourceCache.cs,v 1.3 2003/10/27 13:54:11 corts Exp $ initializes the ResourceCache. Will be called before any utilization * RuntimeServices to use for logging, etc retrieves a Resource from the cache * key for Resource to be retrieved Resource specified or null if not found stores a Resource in the cache * key to associate with the Resource Resource to be stored existing Resource stored under this key, or null if none removes a Resource from the cache * resource to be removed returns an Iterator of Keys in the cache Default implementation of the resource cache for the default ResourceManager. The cache uses a least recently used (LRU) algorithm, with a maximum size specified via the resource.manager.cache.size property (identified by the {@link org.apache.velocity.runtime.RuntimeConstants#RESOURCE_MANAGER_CACHE_SIZE} constant). This property get be set to 0 or less for a greedy, unbounded cache (the behavior from pre-v1.5). * Geir Magnusson Jr. Daniel Rall $Id: ResourceCacheImpl.cs,v 1.5 2004/12/23 08:14:32 corts Exp $ Cache storage, assumed to be thread-safe. Runtime services, generally initialized by the initialize() method. Class responsible for instantiating Resource objects, given name and type. Jason van Zyl Geir Magnusson Jr. $Id: ResourceFactory.cs,v 1.3 2003/10/27 13:54:11 corts Exp $ Class to manage the text resource for the Velocity Runtime. A template resources. A static content resource. Initialize the ResourceManager. Gets the named resource. Returned class type corresponds to specified type (i.e. Template to Template). The name of the resource to retrieve. The type of resource (Template, Content, etc.). The character encoding to use. Resource with the template parsed and ready. if template not found from any available source. if template cannot be parsed due to syntax (or other) error. if a problem in parse Determines is a template exists, and returns name of the loader that provides it. This is a slightly less hokey way to support the Velocity.templateExists() utility method, which was broken when per-template encoding was introduced. We can revisit this. Name of template or content resource class name of loader than can provide it Class to manage the text resource for the Velocity Runtime. token used to identify the loader internally Object implementing ResourceCache to be our resource manager's Resource cache. The List of templateLoaders that the Runtime will use to locate the InputStream source of a template. This is a list of the template input stream source initializers, basically properties for a particular template stream source. The order in this list reflects numbering of the properties i.e. <loader-id>.resource.loader.<property> = <value> Each loader needs a configuration object for its initialization, this flags keeps track of whether or not the configuration objects have been created for the resource loaders. switch to turn off log notice when a resource is found for the first time. Initialize the ResourceManager. This will produce a List of Hashtables, each hashtable contains the initialization info for a particular resource loader. This Hashtable will be passed in when initializing the the template loader. Gets the named resource. Returned class type corresponds to specified type (i.e. Template to Template). * The name of the resource to retrieve. The type of resource (Template, Content, etc.). The character encoding to use. Resource with the template parsed and ready. @throws ResourceNotFoundException if template not found from any available source. @throws ParseErrorException if template cannot be parsed due to syntax (or other) error. @throws Exception if a problem in parse Loads a resource from the current set of resource loaders The name of the resource to retrieve. The type of resource (Template, Content, etc.). The character encoding to use. Resource with the template parsed and ready. @throws ResourceNotFoundException if template not found from any available source. @throws ParseErrorException if template cannot be parsed due to syntax (or other) error. @throws Exception if a problem in parse Takes an existing resource, and 'refreshes' it. This generally means that the source of the resource is checked for changes according to some cache/check algorithm and if the resource changed, then the resource data is reloaded and re-parsed. * resource to refresh * @throws ResourceNotFoundException if template not found from current source for this Resource @throws ParseErrorException if template cannot be parsed due to syntax (or other) error. @throws Exception if a problem in parse Gets the named resource. Returned class type corresponds to specified type (i.e. Template to Template). * The name of the resource to retrieve. The type of resource (Template, Content, etc.). Resource with the template parsed and ready. @throws ResourceNotFoundException if template not found from any available source. @throws ParseErrorException if template cannot be parsed due to syntax (or other) error. @throws Exception if a problem in parse * Use {@link #GetResource(String resourceName, int resourceType, String encoding )} Determines is a template exists, and returns name of the loader that provides it. This is a slightly less hokey way to support the Velocity.templateExists() utility method, which was broken when per-template encoding was introduced. We can revisit this. Name of template or content resource class name of loader than can provide it This is the base class for all visitors. For each AST node, this class will provide a bare-bones method for traversal. * Jason van Zyl Geir Magnusson Jr. $Id: BaseVisitor.cs,v 1.3 2003/10/27 13:54:11 corts Exp $ Context used during traversal Writer used as the output sink This class is simply a visitor implementation that traverses the AST, produced by the Velocity parsing process, and creates a visual structure of the AST. This is primarily used for debugging, but it useful for documentation as well. * Jason van Zyl $Id: NodeViewMode.cs,v 1.3 2003/10/27 13:54:11 corts Exp $ Indent child nodes to help visually identify the structure of the AST. Display the type of nodes and optionally the first token. Display a SimpleNode Display an ASTprocess node Display an ASTExpression node Display an ASTAssignment node ( = ) Display an ASTOrNode ( || ) Display an ASTAndNode ( && ) Display an ASTEQNode ( == ) Display an ASTNENode ( != ) Display an ASTLTNode ( < ) Display an ASTGTNode ( > ) Display an ASTLENode ( <= ) Display an ASTGENode ( >= ) Display an ASTAddNode ( + ) Display an ASTSubtractNode ( - ) Display an ASTMulNode ( * ) Display an ASTDivNode ( / ) Display an ASTModNode ( % ) Display an ASTNotNode ( ! ) Display an ASTNumberLiteral node Display an ASTStringLiteral node Display an ASTIdentifier node Display an ASTMethod node Display an ASTReference node Display an ASTTrue node Display an ASTFalse node Display an ASTBlock node Display an ASTText node Display an ASTIfStatement node Display an ASTElseStatement node Display an ASTElseIfStatement node This class is a visitor used by the VM proxy to change the literal representation of a reference in a VM. The reason is to preserve the 'render literal if null' behavior w/o making the VMProxy stuff more complicated than it is already. Geir Magnusson Jr. $Id: VMReferenceMungeVisitor.cs,v 1.3 2003/10/27 13:54:11 corts Exp $ Map containing VM arg to instance-use reference Passed in with CTOR CTOR - takes a map of args to reference Visitor method - if the literal is right, will set the literal in the ASTReference node ASTReference to work on Object to pass down from caller Interface for internal runtime logging services that are needed by the Geir Magusson Jr. $Id: RuntimeLogger.cs,v 1.1 2004/01/02 00:04:50 corts Exp $ Log a warning message. message to log Log an info message. message to log Log an error message. message to log Log a debug message. message to log Interface for internal runtime services that are needed by the various components w/in Velocity. This was taken from the old Runtime singleton, and anything not necessary was removed. Currently implemented by RuntimeInstance. Allows an external system to set a property in the Velocity Runtime. property key property value 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"] * key value Clear the values pertaining to a particular property. key of property to clear 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. * property to return Initialize the Velocity Runtime with the name of ExtendedProperties object. Properties 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. inputStream retrieved by a resource loader name of the template being parsed Parse the input and return the root of the AST node structure. inputStream retrieved by a resource loader name of the template being parsed flag to dump the Velocimacro namespace for this template Returns a Template from the resource manager. This method assumes that the character encoding of the template is set by the input.encoding property. The default is "ISO-8859-1" * The file name of the desired template. The template. @throws ResourceNotFoundException if template not found from any available source. @throws ParseErrorException if template cannot be parsed due to syntax (or other) error. @throws Exception if an error occurs in template initialization Returns a Template from the resource manager * The name of the desired template. Character encoding of the template The template. @throws ResourceNotFoundException if template not found from any available source. @throws ParseErrorException if template cannot be parsed due to syntax (or other) error. @throws Exception if an error occurs in template initialization Returns a static content resource from the resource manager. Uses the current value if INPUT_ENCODING as the character encoding. * Name of content resource to get parsed ContentResource object ready for use @throws ResourceNotFoundException if template not found from any available source. Returns a static content resource from the resource manager. * Name of content resource to get Character encoding to use parsed ContentResource object ready for use @throws ResourceNotFoundException if template not found from any available source. Determines is a template exists, and returns name of the loader that provides it. This is a slightly less hokey way to support the Velocity.templateExists() utility method, which was broken when per-template encoding was introduced. We can revisit this. * Name of template or content resource class name of loader than can provide it String property accessor method with default to hide the configuration implementation. key property key default value to return if key not found in resource manager. value of key or default Returns the appropriate VelocimacroProxy object if vmName is a valid current Velocimacro. Name of velocimacro requested Template Name VelocimacroProxy Adds a new Velocimacro. Usually called by Macro only while parsing. name Name of velocimacro macro String form of macro body argArray Array of strings, containing the #macro() arguments. the 0th is the name. Source Template True if added, false if rejected for some reason (either parameters or permission settings) Checks to see if a VM exists Name of velocimacro Template Name True if VM by that name exists, false if not tells the vmFactory to dump the specified namespace. This is to support clearing the VM list when in inline-VM-local-scope mode String property accessor method to hide the configuration implementation. property key value Int property accessor method to hide the configuration implementation. property key value Int property accessor method to hide the configuration implementation. property key default value value Boolean property accessor method to hide the configuration implementation. property key default value value Return the specified application attribute Sets the specified application attribute. Return the velocity runtime configuration object. @return ExtendedProperties configuration object which houses the velocity runtime properties. Returns the configured class introspection/reflection implementation. Returns the configured method introspection/reflection implementation. This class defines the keys that are used in the velocity.properties file so that they can be referenced as a constant within Java code. Jon S. Stevens Geir Magnusson Jr. Jason van Zyl The resource.manager.cache.class property specifies the name of the implementation to use. The resource.manager.cache.size property specifies the cache upper bound (if relevant). The default number of parser instances to create. Configurable via the parameter named by the constant. key name for uberspector 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 like Turbine. Runtime properties can set and then the Runtime is initialized. Turbine for example knows where the templates are to be loaded from, and where the velocity log file should be placed. So in the case of Velocity cooperating with Turbine the code might look something like the following: Runtime.setProperty(Runtime.FILE_RESOURCE_LOADER_PATH, templatePath); Runtime.setProperty(Runtime.RUNTIME_LOG, pathToVelocityLog); Runtime.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
             -----------------------------------------------------------------------
             Runtime.init()
            
             If Runtime.init() is called by itself the Runtime will
             initialize with a set of default values.
             -----------------------------------------------------------------------
             Runtime.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.
             -----------------------------------------------------------------------
             
VelocimacroFactory object to manage VMs The Runtime parser pool Indicate whether the Runtime has been fully initialized. These are the properties that are laid down over top of the default properties when requested. Object that houses the configuration options for the velocity runtime. The ExtendedProperties object allows the convenient retrieval of a subset of properties. For example all the properties for a resource loader can be retrieved from the main ExtendedProperties object using something like the following: ExtendedProperties loaderConfiguration = configuration.subset(loaderID); And a configuration is a lot more convenient to deal with then conventional properties objects, or Maps. Each runtime instance has it's own introspector to ensure that each instance is completely separate. Opaque reference to something specified by the application for use in application supplied/specified pluggable components. Gets the classname for the Uberspect introspection package and instantiates an instance. Initializes the Velocity Runtime with properties file. The properties file may be in the file system proper, or the properties file may be in the classpath. Allows an external system to set a property in the Velocity Runtime. property key property value 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 like the following: ["file", "classpath"] key value Clear the values pertaining to a particular property. key of property to clear 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. property to return Initialize Velocity properties, if the default properties have not been laid down first then do so. Then proceed to process any overriding properties. Laying down the default properties gives a much greater chance of having a working system. Initialize the Velocity Runtime with a Properties object. Properties Initialize the Velocity Runtime with the name of ExtendedProperties object. Properties Initialize the Velocity logging system. * @throws Exception This methods initializes all the directives that are used by the Velocity Runtime. The directives to be initialized are listed in the RUNTIME_DEFAULT_DIRECTIVES properties file. @throws Exception Initializes the Velocity parser pool. This still needs to be implemented. Returns a JavaCC generated Parser. Parser javacc generated parser 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. inputstream retrieved by a resource loader name of the template being parsed Parse the input and return the root of the AST node structure. inputstream retrieved by a resource loader name of the template being parsed flag to dump the Velocimacro namespace for this template Returns a Template from the resource manager. This method assumes that the character encoding of the template is set by the input.encoding property. The default is "ISO-8859-1" The file name of the desired template. The template. if template not found from any available source if template cannot be parsed due to syntax (or other) error. if an error occurs in template initialization Returns a Template from the resource manager The name of the desired template. Character encoding of the template The template. if template not found from any available source. if template cannot be parsed due to syntax (or other) error. if an error occurs in template initialization Returns a static content resource from the resource manager. Uses the current value if INPUT_ENCODING as the character encoding. Name of content resource to get ContentResource object ready for use if template not found from any available source. Returns a static content resource from the resource manager. Name of content resource to get Character encoding to use ContentResource object ready for use if template not found from any available source. Determines is a template exists, and returns name of the loader that provides it. This is a slightly less hokey way to support the Velocity.templateExists() utility method, which was broken when per-template encoding was introduced. We can revisit this. Name of template or content resource class name of loader than can provide it Added this to check and make sure that the configuration is initialized before trying to get properties from it. This occurs when there are errors during initialization and the default properties have yet to be layed down. Handle logging. log level message to log Log a warning message. message to log Log an info message. message to log Log an error message. message to log Log a debug message. message to log String property accessor method with default to hide the configuration implementation. key property key default value to return if key not found in resource manager. String value of key or default Returns the appropriate VelocimacroProxy object if strVMname is a valid current Velocimacro. Name of velocimacro requested Name of template VelocimacroProxy Adds a new Velocimacro. Usually called by Macro only while parsing. Name of velocimacro String form of macro body Array of strings, containing the #macro() arguments. the 0th is the name. Name of template True if added, false if rejected for some reason (either parameters or permission settings) Checks to see if a VM exists Name of velocimacro Name of template True if VM by that name exists, false if not Tells the vmFactory to dump the specified namespace. This is to support clearing the VM list when in inline-VM-local-scope mode. String property accessor method to hide the configuration implementation property key value of key or null Int property accessor method to hide the configuration implementation. property key value Int property accessor method to hide the configuration implementation. property key default value value Boolean property accessor method to hide the configuration implementation. property key default value if property not found boolean value of key or default value Return the velocity runtime configuration object. ExtendedProperties configuration object which houses the velocity runtime properties. Return the Introspector for this instance 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 like Turbine. Runtime properties can set and then the Runtime is initialized. Turbine for example knows where the templates are to be loaded from, and where the velocity log file should be placed. So in the case of Velocity cooperating with Turbine the code might look something like the following:
             RuntimeSingleton.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, templatePath);
             RuntimeSingleton.setProperty(RuntimeConstants.RUNTIME_LOG, pathToVelocityLog);
             RuntimeSingleton.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
             -----------------------------------------------------------------------
             RuntimeSingleton.init()
            
             If Runtime.init() is called by itself the Runtime will
             initialize with a set of default values.
             -----------------------------------------------------------------------
             RuntimeSingleton.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.
             -----------------------------------------------------------------------
             
Jason van Zyl Jeff Bowden Geir Magusson Jr. Daniel Rall $Id: RuntimeSingleton.cs,v 1.5 2004/12/27 05:59:46 corts Exp $
This is the primary initialization method in the Velocity Runtime. The systems that are setup/initialized here are as follows: Logging System ResourceManager Parser Pool Global Cache Static Content Include System Velocimacro System Allows an external system to set a property in the Velocity Runtime. property key property value 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 an ArrayList like the following: ["file", "classpath"] key value Clear the values pertaining to a particular property. key of property to clear 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. property to return Initialize the Velocity Runtime with an ExtendedProperties object. Properties Initialize the Velocity Runtime with a configuration file. configuration file Returns a JavaCC generated Parser. Parser javacc generated parser 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. TextReader retrieved by a resource loader name of the template being parsed Parse the input and return the root of the AST node structure. TextReader retrieved by a resource loader name of the template being parsed flag to dump the Velocimacro namespace for this template Returns a Template from the resource manager. This method assumes that the character encoding of the template is set by the input.encoding property. The default is "ISO-8859-1" * The file name of the desired template. The template. @throws ResourceNotFoundException if template not found from any available source. @throws ParseErrorException if template cannot be parsed due to syntax (or other) error. @throws Exception if an error occurs in template initialization Returns a Template from the resource manager * The name of the desired template. Character encoding of the template The template. @throws ResourceNotFoundException if template not found from any available source. @throws ParseErrorException if template cannot be parsed due to syntax (or other) error. @throws Exception if an error occurs in template initialization Returns a static content resource from the resource manager. Uses the current value if INPUT_ENCODING as the character encoding. * Name of content resource to get parsed ContentResource object ready for use @throws ResourceNotFoundException if template not found from any available source. Returns a static content resource from the resource manager. * Name of content resource to get Character encoding to use parsed ContentResource object ready for use @throws ResourceNotFoundException if template not found from any available source. Determines is a template exists, and returns name of the loader that provides it. This is a slightly less hokey way to support the Velocity.templateExists() utility method, which was broken when per-template encoding was introduced. We can revisit this. * Name of template or content resource class name of loader than can provide it Log a warning message. message to log Log an info message. message to log Log an error message. message to log Log a debug message. message to log String property accessor method with default to hide the configuration implementation. property key default value to return if key not found in resource manager. String value of key or default Returns the appropriate VelocimacroProxy object if vmName is a valid current Velocimacro. Name of velocimacro requested Template Name VelocimacroProxy Adds a new Velocimacro. Usually called by Macro only while parsing. Name of velocimacro String form of macro body Array of strings, containing the #macro() arguments. The 0th is the name. Source template True if added, false if rejected for some reason (either parameters or permission settings) Checks to see if a VM exists Name of velocimacro Template Name True if VM by that name exists, false if not Tells the vmFactory to dump the specified namespace. This is to support clearing the VM list when in inline-VM-local-scope mode String property accessor method to hide the configuration implementation. property key Value of key or null Int property accessor method to hide the configuration implementation. property key value Int property accessor method to hide the configuration implementation. property key default value value Boolean property accessor method to hide the configuration implementation. property key default value if property not found value of key or default value key value Return the velocity runtime configuration object. ExtendedProperties configuration object which houses the velocity runtime properties. Return the Introspector for this RuntimeInstance Introspector object for this runtime instance Returns the RuntimeInstance object for this singleton. For internal use only. The used by this Singleton instance. VelocimacroFactory.java * manages the set of VMs in a running Velocity engine. * Geir Magnusson Jr. $Id: VelocimacroFactory.cs,v 1.5 2003/10/27 15:37:24 corts Exp $ runtime services for this instance VMManager : deal with namespace management and actually keeps all the VM definitions determines if replacement of global VMs are allowed controlled by VM_PERM_ALLOW_INLINE_REPLACE_GLOBAL controls if new VMs can be added. Set by VM_PERM_ALLOW_INLINE Note the assumption that only through inline defs can this happen. additions through auto-loaded VMs is allowed sets if template-local namespace in used controls log output determines if the libraries are auto-loaded when they change vector of the library names map of the library Template objects used for reload determination CTOR : requires a runtime services from now on initialize the factory - setup all permissions load all global libraries. adds a macro to the factory. determines if a given macro/namespace (name, source) combo is allowed to be added * Name of VM to add Source template that contains the definition of the VM true if it is allowed to be added, false otherwise localization of the logging logic localization of the logging logic Tells the world if a given directive string is a Velocimacro actual factory : creates a Directive that will behave correctly wrt getting the framework to dig out the correct # of args tells the velocimacroManager to dump the specified namespace sets permission to have VMs local in scope to their declaring template note that this is really taken care of in the VMManager class, but we need it here for gating purposes in addVM eventually, I will slide this all into the manager, maybe. sets the permission to add new macros sets the permission for allowing addMacro() calls to replace existing VM's set output message mode get output message mode set the switch for automatic reloading of global library-based VMs get the switch for automatic reloading of global library-based VMs small container class to hold the duple of a template and modification time. We keep the modification time so we can 'override' it on a reload to prevent recursive reload due to inter-calling VMs in a library Manages VMs in namespaces. Currently, two namespace modes are supported: *
  • flat - all allowable VMs are in the global namespace
  • local - inline VMs are added to it's own template namespace
* Thanks to Jose Alberto Fernandez for some ideas incorporated here. *
Geir Magnusson Jr. Jose Alberto Fernandez
Hash of namespace hashes. map of names of library templates/namespaces Adds the global namespace to the hash. Adds a VM definition to the cache. Whether everything went okay. gets a new living VelocimacroProxy object by the name / source template duple Removes the VMs and the namespace from the manager. Used when a template is reloaded to avoid accumulating drek namespace to dump boolean representing success public switch to let external user of manager to control namespace usage indep of properties. That way, for example, at startup the library files are loaded into global namespace returns the hash for the specified namespace. Will not create a new one if it doesn't exist name of the namespace :) namespace Hashtable of VMs or null if doesn't exist returns the hash for the specified namespace, and if it doesn't exist will create a new one and add it to the namespaces name of the namespace :) flag to add a new namespace if it doesn't exist namespace Hashtable of VMs or null if doesn't exist adds a namespace to the namespaces name of namespace to add Hash added to namespaces, ready for use determines if currently using namespaces. currently ignored true if using namespaces, false if not wrapper class for holding VM information ToolInfo implementation to handle "primitive" data types. It currently supports String, Number, and Boolean data. * Nathan Bubna * $Id: DataInfo.cs,v 1.2 2003/10/27 13:54:12 corts Exp $ Interface to simplify and abstract tool handling. * Implementations of this class should hold both the context key for the tool and sufficient information to return an instance of the tool. * Nathan Bubna * $Id: IToolInfo.cs,v 1.2 2003/10/27 13:54:12 corts Exp $ the context key for the tool the fully qualified classname for the tool Returns an instance of the tool. * Instances returned may be new on each call, pooled, or the be same instance every time depending on the implementation. The object passed to this method may be used to initialize or create the tool that is returned, or it may be null if no such data is required. * an object that may be used to initialize the instance an instance of the tool Parses the value string into a recognized type. If the type specified is not supported, the data will be held and returned as a string. * the context key for the data the data type the data Returns the data. Always returns the same object since the data is a constant. Initialization data is ignored.

A view tool that allows template designers to load an arbitrary object into the context. Any object with a public constructor without parameters can be used as a view tool.

THIS CLASS IS HERE AS A PROOF OF CONCEPT ONLY. IT IS NOT INTENDED FOR USE IN PRODUCTION ENVIRONMENTS. USE AT YOUR OWN RISK.

Gabe Sidler Geir Magnusson Jr.
Creates and returns an object of the specified classname. The object must have a valid default constructor. the fully qualified class name of the object an instance of the specified class or null if the class could not be instantiated. Simple distinguishable exception, used when we run across ambiguous overloading Initializes a new instance of the class. The message. Initializes a new instance of the class. The message. The inner exception. Initializes a new instance of the class. The that holds the serialized object data about the exception being thrown. The that contains contextual information about the source or destination. The class name is null or is zero (0). The info parameter is null. A cache of introspection information for a specific class instance. Keys objects by a concatenation of the method name and the names of classes that make up the parameters. Cache of Methods, or CACHE_MISS, keyed by method name and actual arguments used to find it. Standard constructor Find a Method using the methodKey provided. Look in the methodMap for an entry. If found, it'll either be a CACHE_MISS, in which case we simply give up, or it'll be a Method, in which case, we return it. If nothing is found, then we must actually go and introspect the method from the MethodMap. the class object whose methods are cached by this map. Find a Method using the methodKey provided. Look in the methodMap for an entry. If found, it'll either be a CACHE_MISS, in which case we simply give up, or it'll be a Method, in which case, we return it. If nothing is found, then we must actually go and introspect the method from the MethodMap. Populate the Map of direct hits. These are taken from all the public methods that our class provides. Make a methodKey for the given method using the concatenation of the name and the types of the method parameters. Retrieves public methods for a class. Class passed into the constructor used to as the basis for the Method map. Little class to carry in info such as template name, line and column for information error reporting from the uberspector implementations * Geir Magnusson Jr. $Id: Info.cs,v 1.1 2004/12/27 05:55:08 corts Exp $ Usually a template name. The line number from source. The column number from source. Formats a textual representation of this object as SOURCE [line X, column Y]. Holds information for node-local context data introspection information. Geir Magnusson Jr. $Id: IntrospectionCacheData.cs,v 1.3 2003/10/27 13:54:12 corts Exp $ Object to pair with class - currently either a Method or AbstractExecutor. It can be used in any way the using node wishes. Class of context data object associated with the introspection information This basic function of this class is to return a Method object for a particular class given the name of a method and the parameters to the method in the form of an Object[] The first time the Introspector sees a class it creates a class method map for the class in question. Basically the class method map is a Hashtable where Method objects are keyed by a concatenation of the method name and the names of classes that make up the parameters. For example, a method with the following signature: public void method(String a, StringBuffer b) would be mapped by the key: "method" + "java.lang.String" + "java.lang.StringBuffer" This mapping is performed for all the methods in a class and stored for This basic function of this class is to return a Method object for a particular class given the name of a method and the parameters to the method in the form of an Object[] The first time the Introspector sees a class it creates a class method map for the class in question. Basically the class method map is a Hashtable where Method objects are keyed by a concatenation of the method name and the names of classes that make up the parameters. For example, a method with the following signature: public void method(String a, StringBuffer b) would be mapped by the key: "method" + "java.lang.String" + "java.lang.StringBuffer" This mapping is performed for all the methods in a class and stored for $Id: IntrospectorBase.cs,v 1.3 2003/10/27 13:54:12 corts Exp $ Holds the method maps for the classes we know about, keyed by Class object. Holds the qualified class names for the classes we hold in the classMethodMaps hash Gets the method defined by name and params for the Class c. Class in which the method search is taking place Name of the method being searched for An array of Objects (not Classes) that describe the the parameters The desired object. Gets the method defined by name for the Class c. Class in which the method search is taking place Name of the method being searched for The desired object. Creates a class map for specific class and registers it in the cache. Also adds the qualified name to the name->class map for later Classloader change detection. our engine runtime services Receives our RuntimeServices object Gets the method defined by name and params for the Class c. Class in which the method search is taking place Name of the method being searched for An array of Objects (not Classes) that describe the the parameters The desired Method object. Gets the method defined by name for the Class c. Class in which the method search is taking place Name of the method being searched for The desired object. 'Federated' introspection/reflection interface to allow the introspection behavior in Velocity to be customized. * Geir Magusson Jr. $Id: Uberspect.cs,v 1.1 2004/12/27 05:55:08 corts Exp $ Initializer - will be called before use Returns a general method, corresponding to $foo.bar( $woogie ) Property getter - returns VelPropertyGet appropos for #set($foo = $bar.woogie) Property setter - returns VelPropertySet appropos for #set($foo.bar = "geir") Method used for regular method invocation * $foo.bar() * * Geir Magnusson Jr. $Id: VelMethod.cs,v 1.1 2004/12/27 05:55:08 corts Exp $ invocation method - called when the method invocation should be performed and a value returned specifies if this VelMethod is cacheable and able to be reused for this class of object it was returned for * true if can be reused for this class, false if not returns the method name used returns the return type of the method invoked Interface defining a 'getter'. For uses when looking for resolution of property references $foo.bar Geir Magnusson Jr. $Id: VelPropertyGet.cs,v 1.1 2004/12/27 05:55:08 corts Exp $ invocation method - called when the 'get action' should be performed and a value returned specifies if this VelPropertyGet is cacheable and able to be reused for this class of object it was returned for true if can be reused for this class, false if not returns the method name used to return this 'property' Interface used for setting values that appear to be properties in Velocity. Ex. * #set($foo.bar = "hello") * Geir Magnusson Jr. $Id: VelPropertySet.cs,v 1.1 2004/12/27 05:55:08 corts Exp $ method used to set the value in the object * Object on which the method will be called with the arg value to be set the value returned from the set operation (impl specific) specifies if this VelPropertySet is cacheable and able to be reused for this class of object it was returned for * true if can be reused for this class, false if not returns the method name used to set this 'property' Keep track of all methods with the same name. Add a method to a list of methods by name. For a particular class we are keeping track of all the methods with the same name. Return a list of methods with the same name. key List list of methods Find a method. Attempts to find the most specific applicable method using the algorithm described in the JLS section 15.12.2 (with the exception that it can't distinguish a primitive type argument from an object type argument, since in reflection primitive type arguments are represented by their object counterparts, so for an argument of type (say) java.lang.Integer, it will not be able to decide between a method that takes int and a method that takes java.lang.Integer as a parameter. This turns out to be a relatively rare case where this is needed - however, functionality like this is needed. name of method the actual arguments with which the method is called the most specific applicable method, or null if no method is applicable. if there is more than one maximally specific applicable method Determines which method signature (represented by a class array) is more specific. This defines a partial ordering on the method signatures. first signature to compare second signature to compare MORE_SPECIFIC if c1 is more specific than c2, LESS_SPECIFIC if c1 is less specific than c2, INCOMPARABLE if they are incomparable. Returns all methods that are applicable to actual argument types. list of all candidate methods the actual types of the arguments a list that contains only applicable methods (number of formal and actual arguments matches, and argument types are assignable to formal types through a method invocation conversion). TODO: this used to return a LinkedList -- changed to an ArrayList for now until I can figure out what is really needed Returns true if the supplied method is applicable to actual argument types. Determines whether a type represented by a class object is convertible to another type represented by a class object using a method invocation conversion, treating object types of primitive types as if they were primitive types (that is, a Boolean actual parameter type matches boolean primitive formal type). This behavior is because this method is used to determine applicable methods for an actual parameter list, and primitive types are represented by their object duals in reflective method calls. the formal parameter type to which the actual parameter type should be convertible the actual parameter type. true if either formal type is assignable from actual type, or formal is a primitive type and actual is its corresponding object type or an object type of a primitive type that can be converted to the formal type. Determines whether a type represented by a class object is convertible to another type represented by a class object using a method invocation conversion, without matching object and primitive types. This method is used to determine the more specific type when comparing signatures of methods. the formal parameter type to which the actual parameter type should be convertible the actual parameter type. true if either formal type is assignable from actual type, or formal and actual are both primitive types and actual can be subject to widening conversion to formal. Implementation of Uberspect to provide the default introspective functionality of Velocity * Geir Magnusson Jr. $Id: UberspectImpl.cs,v 1.1 2004/12/27 05:55:08 corts Exp $ Marker interface to let an uberspector indicate it can and wants to log * Thanks to Paulo for the suggestion * Geir Magnusson Jr. $Id: UberspectLoggable.cs,v 1.1 2004/12/27 05:55:08 corts Exp $ * Sets the logger. This will be called before any calls to the uberspector Our runtime logger. the default Velocity introspector init - does nothing - we need to have setRuntimeLogger called before getting our introspector, as the default vel introspector depends upon it. Method Property getter Property setter Sets the runtime logger - this must be called before anything else besides init() as to get the logger. Makes the pull model appealing... Implementation of . Implementation of . Simple object pool. Based on ThreadPool and few other classes The pool will ignore overflow and return null if empty. max amount of objects to be managed set via CTOR index of previous to next free slot Add the object to the pool, silent nothing if the pool is full Get an object from the pool, null if the pool is empty. Return the size of the pool This class provides some methods for dynamically invoking methods in objects, and some string manipulation methods used by torque. The string methods will soon be moved into the turbine string utilities class. * Jason van Zyl Daniel Rall $Id: StringUtils.cs,v 1.3 2003/10/27 13:54:12 corts Exp $ Line separator for the OS we are operating on.

Makes the first letter caps and the rest lowercase.

*

For example fooBar becomes Foobar.

*
capitalize this String
Read the contents of a file and place them in a string object. * path to file. String contents of the file. Return a context-relative path, beginning with a "/", that represents the canonical version of the specified path after ".." and "." elements are resolved out. If the specified path attempts to go outside the boundaries of the current context (i.e. too many ".." path elements are present), return null instead. * Path to be normalized String normalized path Defines the behavior when a property is read Property name. value back to the template Defines the behavior when a property is written Property name. The value to assign. Invokes the specified method. The method name. The method arguments. value back to the template Creates an instance of a received Type The Type of the new class instance to return An Object containing the new instance This class is used for controlling all template operations. This class uses a parser created by JavaCC to create an AST that is subsequently traversed by a Visitor. Template template = Velocity.getTemplate("test.wm"); IContext context = new VelocityContext(); context.Put("foo", "bar"); context.Put("customer", new Customer()); template.Merge(context, writer); Gets the named resource as a stream, parses and inits. true if successful if template not found from any available source. if template cannot be parsed due to syntax (or other) error. some other problem, should only be from initialization of the template AST. initializes the document. init() is not longer dependant upon context, but we need to let the init() carry the template name down through for VM namespace features The AST node structure is merged with the context to produce the final output. Throws IOException if failure is due to a file related issue, and Exception otherwise Context with data elements accessed by template writer for rendered template if template not found from any available source. if template cannot be parsed due to syntax (or other) error. anything else. General purpose implementation of the application Context interface for general application use. This class should be used in place of the original Context class. This context implementation cannot be shared between threads without those threads synchronizing access between them, as the HashMap is not synchronized, nor are some of the fundamentals of AbstractContext. If you need to share a Context between threads with simultaneous access for some reason, please create your own and extend the interface Context Storage for key/value pairs. Creates a new instance (with no inner context). Creates a new instance with the provided storage (and no inner context). Chaining constructor, used when you want to wrap a context in another. The inner context will be 'read only' - put() calls to the wrapping context will only effect the outermost context The Context implementation to wrap. Initializes internal storage (never to null), and inner context. Internal storage, or null to create default storage. Inner context. retrieves value for key from internal storage name of value to get value as object stores the value for key to internal storage name of value to store value to store previous value of key as Object determines if there is a value for the given key name of value to check true if non-null value in store returns array of keys keys as [] remove a key/value pair from the internal storage name of value to remove value removed