Added tests, corrected documentation and made some minor enhancements to the engine factory.

This commit is contained in:
erezmazor
2009-06-06 19:33:57 +00:00
parent b52f540a62
commit 5ef2b47007
11 changed files with 452 additions and 282 deletions

View File

@@ -1,21 +1,21 @@
#region License
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#region License
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using Common.Logging;
@@ -27,24 +27,24 @@ using LogManager=Common.Logging.LogManager;
namespace Spring.Template.Velocity
{
/// <summary>
/// Velocity LogSystem implementation for Jakarta Commons Logging.
/// NVelocity LogSystem implementation for Commons Logging.
/// </summary>
/// <author>Erez Mazor</author>
public class CommonsLoggingLogSystem : ILogSystem {
protected static readonly ILog log = LogManager.GetLogger(typeof(CommonsLoggingLogSystem));
/// <summary>
/// Inits the specified runtime services. No-op in current implementatin
/// Initializes the specified runtime services. No-op in current implementatin
/// </summary>
/// <param name="runtimeServices">The runtime services.</param>
/// <param name="runtimeServices">the runtime services.</param>
public void Init(IRuntimeServices runtimeServices) {
}
/// <summary>
/// Log a velocity message using the commons logging system
/// Log a NVelocity message using the commons logging system
/// </summary>
/// <param name="level">LogLevel to match</param>
/// <param name="message">Message to log</param>
/// <param name="message">message to log</param>
public void LogVelocityMessage(LogLevel level, string message) {
switch (level) {
case LogLevel.Error:

View File

@@ -1,21 +1,21 @@
#region License
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#region License
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
@@ -26,34 +26,55 @@ using NVelocity.Runtime.Resource;
using NVelocity.Runtime.Resource.Loader;
using Spring.Core.IO;
namespace Spring.Template.Velocity
{
namespace Spring.Template.Velocity {
/// <summary>
/// Velocity ResourceLoader adapter that loads via a Spring IResourceLoader.
/// Used by VelocityEngineFactory for any resource loader path that cannot
/// be resolved to a File
///
/// <p>Take notoce that this loader does not allow for modification detection:
/// Use Velocity's default FileResourceLoader for File resources.
///
/// <p>Expects "spring.resource.loader" and "spring.resource.loader.path"
/// application attributes in the Velocity runtime: the former of type
/// <code>IResourceLoader</code>, the latter a String.
/// NVelocity's abstract ResourceLoader extension which serves
/// as an adapter that loads templates via a Spring IResourceLoader.
///
/// <br/>
/// Used by VelocityEngineFactory for any resource loader path that
/// cannot be resolved to a File or an Assembly or for
/// implementations which rely on spring's IResourceLoader
/// mechanism.
///
/// <br/>
/// <b>Important</b>: this loader does not allow for modification detection.
///<br/>
/// Expects "spring.resource.loader" (IResourceLoader implementations)
/// and "spring.resource.loader.path" application attributes in the
/// NVelocity runtime.
/// </summary>
/// <see cref="VelocityEngineFactory.ResourceLoaderPath"/>
/// <see cref="IResourceLoader"/>
/// <see cref="FileResourceLoader"/>
/// <see cref="ResourceLoader"/>
/// <see cref="AssemblyResourceLoader"/>
/// <author>Erez Mazor (.NET) </author>
public class SpringResourceLoader : ResourceLoader {
public static readonly string NAME = "spring";
///<summary>
/// Prefix used for the NVelocity Configuration
///</summary>
public const string NAME = "spring";
public static readonly string SPRING_RESOURCE_LOADER_CLASS = "spring.resource.loader.class";
/// <summary>
/// The IResourceLoader implementation type
/// </summary>
public const string SPRING_RESOURCE_LOADER_CLASS = "spring.resource.loader.class";
public static readonly string SPRING_RESOURCE_LOADER_CACHE = "spring.resource.loader.cache";
/// <summary>
/// A flag indicating weather a template cache is used
/// </summary>
public const string SPRING_RESOURCE_LOADER_CACHE = "spring.resource.loader.cache";
public static readonly string SPRING_RESOURCE_LOADER = "spring.resource.loader";
///<summary>
/// Fully qualified name of the IResourceLoader implementation class
///</summary>
public const string SPRING_RESOURCE_LOADER = "spring.resource.loader";
public static readonly string SPRING_RESOURCE_LOADER_PATH = "spring.resource.loader.path";
/// <summary>
/// A comma delimited list of paths used by the spring IResourceLoader implementation
/// </summary>
public const string SPRING_RESOURCE_LOADER_PATH = "spring.resource.loader.path";
protected static readonly ILog log = LogManager.GetLogger(typeof(SpringResourceLoader));
@@ -65,14 +86,14 @@ namespace Spring.Template.Velocity
/// <summary>
/// Initialize the template loader with a resources class.
/// </summary>
/// <param name="configuration">The configuration.</param>
/// <param name="configuration">The ExtendedProperties representing the Velocity configuration.</param>
public override void Init(ExtendedProperties configuration) {
resourceLoader = (IResourceLoader)rsvc.GetApplicationAttribute(SPRING_RESOURCE_LOADER);
string resourceLoaderPath = (string)rsvc.GetApplicationAttribute(SPRING_RESOURCE_LOADER_PATH);
if (resourceLoader == null) {
throw new ArgumentException("'resourceLoader' application attribute must be present for SpringResourceLoader");
}
if (resourceLoaderPath == null) {
if (null == resourceLoaderPath) {
throw new ArgumentException("'resourceLoaderPath' application attribute must be present for SpringResourceLoader");
}
resourceLoaderPaths = resourceLoaderPath.Split(',');
@@ -88,17 +109,17 @@ namespace Spring.Template.Velocity
}
/// <summary>
/// Get the InputStream that the Runtime will parse to create a template.
/// Get the <code>System.IO.Stream</code> that the Runtime will parse to create a template.
/// </summary>
/// <param name="source">The source.</param>
/// <returns></returns>
/// <param name="source">the source template name</param>
/// <returns>a System.IO.Stream representation of the resource</returns>
public override Stream GetResourceStream(string source) {
if (log.IsDebugEnabled) {
log.Debug(string.Format("Looking for Velocity resource with name [{0}]", source));
}
for (int i = 0; i < resourceLoaderPaths.Length; i++) {
IResource resource =
resourceLoader.GetResource(resourceLoaderPaths[i] + source);
foreach (string resourceLoaderPath in resourceLoaderPaths){
IResource resource = resourceLoader.GetResource(resourceLoaderPath + source);
try {
return resource.InputStream;
} catch (IOException ex) {

View File

@@ -1,21 +1,21 @@
#region License
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#region License
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
@@ -32,43 +32,48 @@ using NVelocity.Runtime.Resource.Loader;
using Spring.Context.Support;
using Spring.Core.IO;
namespace Spring.Template.Velocity{
namespace Spring.Template.Velocity {
/// <summary>
/// Factory that configures a VelocityEngine. Can be used standalone,
/// but typically you will either use {@link VelocityEngineFactoryBean}
/// but typically you will use VelocityEngineFactoryObject
/// for preparing a VelocityEngine as bean reference.
///
/// <p>The optional "ConfigLocation" property sets the location of the Velocity
/// <br/>
/// The optional "ConfigLocation" property sets the location of the Velocity
/// properties file, within the current application. Velocity properties can be
/// overridden via "VelocityProperties", or even completely specified locally,
/// avoiding the need for an external properties file.
///
/// <p>The "ResourceLoaderPath" property can be used to specify the Velocity
/// resource loader path via Spring's Resource abstraction, possibly relative
/// <br/>
/// The "ResourceLoaderPath" property can be used to specify the Velocity
/// resource loader path via Spring's IResource abstraction, possibly relative
/// to the Spring application context.
///
/// <p>If "OverrideLogging" is true (the default), the VelocityEngine will be
/// <br/>
/// If "OverrideLogging" is true (the default), the VelocityEngine will be
/// configured to log via Commons Logging, that is, using the Spring-provided
/// "CommonsLoggingLogSystem" as log system.
/// CommonsLoggingLogSystem as log system.
///
/// <p>The simplest way to use this class is to specify a ResourceLoaderPath
/// property; the VelocityEngine typically then does not need any further
/// <br/>
/// The simplest way to use this class is to specify a ResourceLoaderPath
/// property. the VelocityEngine typically then does not need any further
/// configuration.
///
/// </summary>
/// <see cref="CommonsLoggingLogSystem" />
/// <see cref="VelocityEngineFactoryObject" />
/// <see cref="CommonsLoggingLogSystem" />
/// <author>Erez Mazor (.NET) </author>
/// <author>Erez Mazor</author>
public class VelocityEngineFactory {
private const char DELIMITER = ',';
protected static readonly ILog log = LogManager.GetLogger(typeof(VelocityEngineFactory));
private IResource configLocation;
private IDictionary<string, object> velocityProperties = new Dictionary<string, object>();
private String resourceLoaderPath;
private IList resourceLoaderPaths = new ArrayList();
private IResourceLoader resourceLoader = new ConfigurableResourceLoader();
@@ -86,7 +91,7 @@ namespace Spring.Template.Velocity{
}
/// <summary>
/// Set Velocity properties as Map, to allow for non-String values like "ds.resource.loader.instance".
/// Set local NVelocity properties.
/// </summary>
/// <see cref="VelocityProperties"/>
public IDictionary<string, object> VelocityProperties {
@@ -94,35 +99,47 @@ namespace Spring.Template.Velocity{
}
/// <summary>
///
/// Single ResourceLoaderPath
/// </summary>
/// <see cref="ResourceLoaderPaths"/>
public string ResourceLoaderPath {
set { resourceLoaderPaths.Add(value); }
}
/// <summary>
/// Set the Velocity resource loader path via a Spring resource location.
/// Accepts multiple locations in Velocity's comma-separated path style.
/// <p>When populated via a String, standard URLs like "file:" and "assembly:"
/// pseudo URLs are supported, as understood by ResourceLoader. Allows for
/// <br/>
/// When populated via a String, standard URLs like "file:" and "assembly:"
/// pseudo URLs are supported, as understood by IResourceLoader. Allows for
/// relative paths when running in an ApplicationContext.
/// <p>Will define a path for the default Velocity resource loader with the name
/// "file". If the specified resource cannot be resolved to a <code>java.io.File</code>,
/// <br/>
/// Will define a path for the default Velocity resource loader with the name
/// "file". If the specified resource cannot be resolved to a File,
/// a generic SpringResourceLoader will be used under the name "spring", without
/// modification detection.
/// <p> Take notice that resource caching will be enabled in any case. With the file
/// <br/>
/// Take notice that resource caching will be enabled in any case. With the file
/// resource loader, the last-modified timestamp will be checked on access to
/// detect changes. With SpringResourceLoader, the resource will be cached
/// forever (for example for class path resources).
/// <p>To specify a modification check interval for files, use Velocity's
/// detect changes. With SpringResourceLoader, the resource will be throughout
/// the life time of the application context (for example for class path resources).
/// <br/>
/// To specify a modification check interval for files, use Velocity's
/// standard "file.resource.loader.modificationCheckInterval" property. By default,
/// the file timestamp is checked on every access (which is surprisingly fast).
/// Of course, this just applies when loading resources from the file system.
/// <p>To enforce the use of SpringResourceLoader, i.e. to not resolve a path
/// <br/>
/// To enforce the use of SpringResourceLoader, i.e. to not resolve a path
/// as file system resource in any case, turn off the "preferFileSystemAccess"
/// flag. See the latter's javadoc for details.
/// flag. See the latter's documentation for details.
/// </summary>
/// <see cref="ResourceLoader"/>
/// <see cref="VelocityProperties"/>
/// <see cref="PreferFileSystemAccess"/>
/// <see cref="SpringResourceLoader"/>
/// <see cref="FileResourceLoader"/>
public string ResourceLoaderPath {
set { resourceLoaderPath = value; }
public IList ResourceLoaderPaths {
set { resourceLoaderPaths = value; }
}
/// <summary>
@@ -139,18 +156,17 @@ namespace Spring.Template.Velocity{
set { resourceLoader = value; }
}
/// <summary>
/// Set whether to prefer file system access for template loading.
/// File system access enables hot detection of template changes.
/// <p>If this is enabled, VelocityEngineFactory will try to resolve the
/// specified "resourceLoaderPath" as file system resource (which will work
/// for expanded class path resources and ServletContext resources too).
/// <p>Default is "true". Turn this off to always load via SpringResourceLoader
/// <br/>
/// If this is enabled, VelocityEngineFactory will try to resolve the
/// specified "resourceLoaderPath" as file system resource.
/// <br/>
/// Default is "true". Turn this off to always load via SpringResourceLoader
/// (i.e. as stream, without hot detection of template changes), which might
/// be necessary if some of your templates reside in an expanded classes
/// directory while others reside in jar files.
/// be necessary if some of your templates reside in a directory while
/// others reside in assembly files.
/// </summary>
/// <see cref="ResourceLoaderPath"/>
public bool PreferFileSystemAccess {
@@ -170,7 +186,7 @@ namespace Spring.Template.Velocity{
/// <summary>
/// Prepare the VelocityEngine instance and return it.
/// Create and initialize the VelocityEngine instance and return it
/// </summary>
/// <returns>VelocityEngine</returns>
/// <exception cref="VelocityException" />
@@ -180,25 +196,33 @@ namespace Spring.Template.Velocity{
/// <see cref="VelocityEngine.Init()" />
public VelocityEngine CreateVelocityEngine() {
VelocityEngine velocityEngine = NewVelocityEngine();
ExtendedProperties props = new ExtendedProperties();
ExtendedProperties extendedProperties = new ExtendedProperties();
// load defaults - see documentation why this is needed
LoadDefaultProperties(velocityEngine);
// Load config file if set.
if (configLocation != null) {
if (log.IsInfoEnabled) {
log.Info(string.Format("Loading Velocity config from [{0}]", configLocation));
}
FillProperties(props, configLocation);
FillProperties(extendedProperties, configLocation);
}
// Merge local properties if set.
// merge local properties if set.
if (velocityProperties.Count > 0) {
foreach (KeyValuePair<string, object> pair in velocityProperties) {
props.Add(pair.Key, pair.Value);
extendedProperties.SetProperty(pair.Key, pair.Value);
}
}
// Set a resource loader path, if required.
if (null != resourceLoaderPath) {
InitVelocityResourceLoader(velocityEngine, resourceLoaderPath);
if( !preferFileSystemAccess && resourceLoaderPaths.Count == 0){
throw new ArgumentException("When using SpringResourceLoader you must provide a path using the ResourceLoaderPath property");
}
if (resourceLoaderPaths.Count > 0) {
InitVelocityResourceLoader(velocityEngine, resourceLoaderPaths);
}
// Log via Commons Logging?
@@ -210,11 +234,11 @@ namespace Spring.Template.Velocity{
try {
// do not init with extended properties rather set one by one
foreach (DictionaryEntry prop in props) {
velocityEngine.SetProperty(Convert.ToString(prop.Key), prop.Value);
foreach (DictionaryEntry property in extendedProperties) {
velocityEngine.SetProperty(Convert.ToString(property.Key), property.Value);
}
// Perform actual initialization.
// velocity engine initialization - required
velocityEngine.Init();
} catch (Exception ex) {
throw new VelocityException(ex.ToString(), ex);
@@ -224,90 +248,128 @@ namespace Spring.Template.Velocity{
}
/// <summary>
/// Return a new VelocityEngine. Subclasses can override this for*
/// custom initialization, or for using a mock object for testing. * <p>Called by
/// <code>CreateVelocityEngine()</code>
/// This is to overcome an issue with the current NVelocity library, it seems the
/// default runetime properties/directives (nvelocity.properties and directive.properties
/// files) are not being properly located in the library at load time. A jira should
/// be filed but for now we attempt to do this on our own. Particularly our
/// concern here is with several required properties which I don't want
/// to require users to re-defined. e.g.,:
/// <br/>
///
/// Pre-requisites:<br/>
/// resource.manager.class=NVelocity.Runtime.Resource.ResourceManagerImpl <br/>
/// directive.manager=NVelocity.Runtime.Directive.DirectiveManager <br/>
/// runtime.introspector.uberspect=NVelocity.Util.Introspection.UberspectImpl <br/>
/// </summary>
/// <returns>VelocityEngine</returns>
/// <param name="velocityEngine">the instance of the velocity engine unto which we load the default properties</param>
private static void LoadDefaultProperties(VelocityEngine velocityEngine) {
ExtendedProperties extendedProperties = new ExtendedProperties();
IResource defaultRuntimeProperties = new AssemblyResource("assembly://NVelocity/NVelocity.Runtime.Defaults/nvelocity.properties");
IResource defaultRuntimeDirectives = new AssemblyResource("assembly://NVelocity/NVelocity.Runtime.Defaults/directive.properties");
FillProperties(extendedProperties, defaultRuntimeProperties);
FillProperties(extendedProperties, defaultRuntimeDirectives);
foreach (DictionaryEntry property in extendedProperties) {
velocityEngine.SetProperty(Convert.ToString(property.Key), property.Value);
}
}
/// <summary>
/// Return a new VelocityEngine. Subclasses can override this for
/// custom initialization, or for using a mock object for testing. <br/>
/// Called by CreateVelocityEngine()
/// </summary>
/// <returns>VelocityEngine instance (non-configured)</returns>
/// <see cref="CreateVelocityEngine"/>
protected static VelocityEngine NewVelocityEngine() {
return new VelocityEngine();
}
/// <summary>
/// Initialize a Velocity resource loader for the given VelocityEngine:*
/// Initialize a Velocity resource loader for the given VelocityEngine:
/// either a standard Velocity FileResourceLoader or a SpringResourceLoader.
/// <p>Called by <code>CreateVelocityEngine()</code>.
/// <br/>Called by <code>CreateVelocityEngine()</code>.
/// </summary>
/// <param name="velocityEngine">velocityEngine the VelocityEngine to configure</param>
/// <param name="resourceLoaderFullPath">resourceLoaderPath the path to load Velocity resources from</param>
/// <param name="paths">paths the path list to load Velocity resources from</param>
/// <see cref="FileResourceLoader"/>
/// <see cref="SpringResourceLoader"/>
/// <see cref="InitSpringResourceLoader"/>
/// <see cref="CreateVelocityEngine"/>
protected void InitVelocityResourceLoader(VelocityEngine velocityEngine, String resourceLoaderFullPath) {
protected void InitVelocityResourceLoader(VelocityEngine velocityEngine, IList paths) {
if (PreferFileSystemAccess) {
// Try to load via the file system, fall back to SpringResourceLoader
// (for hot detection of template changes, if possible).
IList resolvedPaths = new ArrayList();
foreach (string path in paths){
IResource resource = ResourceLoader.GetResource(path);
resolvedPaths.Add(resource.File.FullName);
}
try {
StringBuilder resolvedPath = new StringBuilder();
String[] paths = resourceLoaderFullPath.Split(DELIMITER);
for (int i = 0; i < paths.Length; i++) {
string path = paths[i];
IResource resource = ResourceLoader.GetResource(path);
if (log.IsDebugEnabled) {
log.Debug(string.Format("Resource loader path [{0}] resolved to file [{1}]", path, resource.File.FullName));
}
resolvedPath.Append(resource.File.FullName);
if (i < paths.Length - 1) {
resolvedPath.Append(',');
}
}
velocityEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, "file");
velocityEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, "true");
velocityEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, resolvedPath.ToString());
velocityEngine.SetProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, joinList(resolvedPaths));
} catch (IOException ex) {
if (log.IsDebugEnabled) {
log.Error(string.Format("Cannot resolve resource loader path [{0}] to [File]: using SpringResourceLoader", resourceLoaderFullPath), ex);
log.Error(string.Format("Cannot resolve resource loader path [{0}] to [File]: using SpringResourceLoader", joinList(resolvedPaths)), ex);
}
InitSpringResourceLoader(velocityEngine, resourceLoaderFullPath);
InitSpringResourceLoader(velocityEngine, joinList(paths));
}
} else {
// Always load via SpringResourceLoader
// (without hot detection of template changes).
// Always load via SpringResourceLoader (without hot detection of template changes).
if (log.IsDebugEnabled) {
log.Debug("File system access not preferred: using SpringResourceLoader");
}
InitSpringResourceLoader(velocityEngine, resourceLoaderFullPath);
InitSpringResourceLoader(velocityEngine, joinList(paths));
}
}
/// <summary>
/// Join the list of strings to a comma delimited string
/// </summary>
/// <param name="values">values list of strings to join</param>
/// <returns>comma delimited string representation of the list</returns>
private static string joinList(IList values) {
StringBuilder result = new StringBuilder();
foreach (string value in values) {
result.Append(value);
result.Append(DELIMITER);
}
return result.ToString(0, result.Length < 1 ? 0 : result.Length - 1);
}
/// <summary>
/// Initialize a SpringResourceLoader for the given VelocityEngine.
/// <p>Called by <code>InitVelocityResourceLoader</code>.
/// <br/>Called by <code>InitVelocityResourceLoader</code>.
///
/// <b>Important</b>: the NVeloctity ResourceLoaderFactory.getLoader
/// method replaces ';' with ',' when attempting to construct our resource
/// loader. The name on the SPRING_RESOURCE_LOADER_CLASS property
/// has to be in the form of "ClassFullName; AssemblyName" in replacement
/// of the tranditional "ClassFullName, AssemblyName" to work.
/// </summary>
/// <param name="velocityEngine">velocityEngine the VelocityEngine to configure</param>
/// <param name="resourceLoaderPathString">resourceLoaderPath the path to load Velocity resources from</param>
/// <see cref="SpringResourceLoader"/>
/// <see cref="InitVelocityResourceLoader"/>
protected void InitSpringResourceLoader(VelocityEngine velocityEngine, string resourceLoaderPathString) {
velocityEngine.SetProperty(
RuntimeConstants.RESOURCE_LOADER, SpringResourceLoader.NAME);
velocityEngine.SetProperty(
SpringResourceLoader.SPRING_RESOURCE_LOADER_CLASS, typeof(SpringResourceLoader).Name);
velocityEngine.SetProperty(
SpringResourceLoader.SPRING_RESOURCE_LOADER_CACHE, "true");
velocityEngine.SetApplicationAttribute(
SpringResourceLoader.SPRING_RESOURCE_LOADER, ResourceLoader);
velocityEngine.SetApplicationAttribute(
SpringResourceLoader.SPRING_RESOURCE_LOADER_PATH, resourceLoaderPathString);
velocityEngine.SetProperty(RuntimeConstants.RESOURCE_LOADER, SpringResourceLoader.NAME);
Type springResourceLoaderType = typeof(SpringResourceLoader);
string springResourceLoaderTypeName = springResourceLoaderType.FullName + "; " + springResourceLoaderType.Assembly.GetName().Name;
velocityEngine.SetProperty(SpringResourceLoader.SPRING_RESOURCE_LOADER_CLASS, springResourceLoaderTypeName);
velocityEngine.SetProperty(SpringResourceLoader.SPRING_RESOURCE_LOADER_CACHE, "true");
velocityEngine.SetApplicationAttribute(SpringResourceLoader.SPRING_RESOURCE_LOADER, ResourceLoader);
velocityEngine.SetApplicationAttribute(SpringResourceLoader.SPRING_RESOURCE_LOADER_PATH, resourceLoaderPathString);
}
/// <summary>
/// To be implemented by subclasses that want to to perform custom
/// post-processing of the VelocityEngine after this FactoryBean
/// post-processing of the VelocityEngine after this FactoryObject
/// performed its default configuration (but before VelocityEngine.init)
/// <p>Called by <code>CreateVelocityEngine()</code>
/// <br/>
/// Called by CreateVelocityEngine
/// </summary>
/// <param name="velocityEngine">velocityEngine the current VelocityEngine</param>
/// <exception cref="IOException" />
@@ -319,11 +381,11 @@ namespace Spring.Template.Velocity{
/// <summary>
/// Populates the velocity properties from the given resource
/// </summary>
/// <param name="props">ExtendedProperties instance to populate</param>
/// <param name="extendedProperties">ExtendedProperties instance to populate</param>
/// <param name="resource">The resource from which to load the properties</param>
private static void FillProperties(ExtendedProperties props, IInputStreamSource resource) {
private static void FillProperties(ExtendedProperties extendedProperties, IInputStreamSource resource) {
try {
props.Load(resource.InputStream);
extendedProperties.Load(resource.InputStream);
} finally {
resource.InputStream.Close();
}

View File

@@ -1,21 +1,21 @@
#region License
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#region License
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
@@ -26,14 +26,14 @@ using Spring.Objects.Factory;
namespace Spring.Template.Velocity
{
/// <summary>
/// FactoryObject implementation that configures a VelocityEngine and provides it as an object
/// reference. This object is intended for any kind of usage of Velocity in
/// FactoryObject implementation that configures a VelocityEngine and provides it
/// as an object reference. This object is intended for any kind of usage of Velocity in
/// application code, e.g. for generating email content.
///
/// See the base class VelocityEngineFactory for configuration details.
/// </summary>
/// <see cref="VelocityEngineFactory"/>
/// <author>Erez Mazor (.NET) </author>
/// <author>Erez Mazor</author>
public class VelocityEngineFactoryObject : VelocityEngineFactory, IFactoryObject, IInitializingObject, IResourceLoaderAware {
private VelocityEngine velocityEngine;
/// <summary>
@@ -53,7 +53,7 @@ namespace Spring.Template.Velocity
}
/// <summary>
/// Returns true
/// Singleton
/// </summary>
public bool IsSingleton {
get { return true; }

View File

@@ -1,21 +1,21 @@
#region License
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#region License
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
@@ -30,32 +30,11 @@ namespace Spring.Template.Velocity{
/// <summary>
/// Generalized Utility class for merging velocity templates into a text writer or return the result as a string
/// </summary>
/// <author>Erez Mazor (.NET) </author>
/// <author>Erez Mazor</author>
public class VelocityEngineUtils {
protected static readonly ILog log = LogManager.GetLogger(typeof(VelocityEngineUtils));
/// <summary>
/// Merge the specified Velocity template with the given model and write
/// the result to the given Writer.
/// </summary>
/// <param name="velocityEngine">VelocityEngine to work with</param>
/// <param name="templateLocation">the location of template, relative to Velocity's resource loader path</param>
/// <param name="model">the Hashtable that contains model names as keys and model objects</param>
/// <param name="writer">writer the TextWriter to write the result to</param>
/// <exception cref="VelocityException">thrown if any exception is thrown by the velocity engine</exception>
[Obsolete("Use the overload that takes the encoding as parameter")]
public static void MergeTemplate(VelocityEngine velocityEngine, string templateLocation, Hashtable model, TextWriter writer) {
try {
VelocityContext velocityContext = new VelocityContext(model);
velocityEngine.MergeTemplate(templateLocation, velocityContext, writer);
} catch (VelocityException) {
throw;
} catch (Exception ex) {
throw new VelocityException(ex.ToString(), ex);
}
}
/// <summary>
/// Merge the specified Velocity template with the given model and write
/// the result to the given Writer.
@@ -79,33 +58,12 @@ namespace Spring.Template.Velocity{
}
}
/// <summary>
/// Merge the specified Velocity template with the given model into a string.
/// <p>When using this method to prepare a text for a mail to be sent with Spring's
/// mail support, consider wrapping VelocityException in MailPreparationException.
/// </summary>
/// <param name="velocityEngine">VelocityEngine to work with</param>
/// <param name="templateLocation">the location of template, relative to Velocity's resource loader path</param>
/// <param name="model">the Hashtable that contains model names as keys and model objects</param>
/// <returns>the result as string</returns>
/// <exception cref="VelocityException">thrown if any exception is thrown by the velocity engine</exception>
[Obsolete("Use the overload that takes the encoding as parameter")]
public static string MergeTemplateIntostring(
VelocityEngine velocityEngine, string templateLocation, Hashtable model) {
TextWriter result = new StringWriter();
MergeTemplate(velocityEngine, templateLocation, model, result);
return result.ToString();
}
/// <summary>
/// Merge the specified Velocity template with the given model into a string.
/// <p>When using this method to prepare a text for a mail to be sent with Spring's
/// mail support, consider wrapping VelocityException in MailPreparationException.
/// </summary>
/// <param name="velocityEngine">VelocityEngine to work with</param>
/// <param name="templateLocation">the location of template, relative to Velocity's resource loader path</param>
/// <param name="encoding">the encoding string to use for the merge</param>
/// <param name="model">the Hashtable that contains model names as keys and model objects</param>
/// <returns>the result as string</returns>
/// <exception cref="VelocityException">thrown if any exception is thrown by the velocity engine</exception>

View File

@@ -26,17 +26,19 @@
<exclude name="${project::get-name()}.dll" />
</references>
<resources basedir="." prefix="Spring.Template.Velocity.Tests" dynamicprefix="true" failonempty="true">
<include name="**/*.xml" />
</resources>
</csc>
<copy todir="${current.bin.dir}">
<fileset basedir="${project::get-name()}/Data">
<include name="**/*.xml" />
<include name="**/*.test" />
</fileset>
</copy>
<copy todir="${current.bin.dir}">
<fileset basedir="${project::get-name()}">
<include name="**/*.vm" />
<include name="**/*.properties" />
<include name="**/*.config" />
</resources>
</csc>
<copy todir="${current.bin.dir}" failonerror="true">
<fileset basedir="${project::get-base-directory()}">
<include name="**/*.xml" />
<include name="**/*.test" />
<include name="**/*.vm" />
<include name="**/*.properties" />
<include name="**/*.config" />
</fileset>
</copy>

View File

@@ -66,6 +66,16 @@
<ItemGroup>
<EmbeddedResource Include="Template\Velocity\VelocityEngineFactoryObjectTests.xml" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Template\Velocity\SimpleTemplate.vm">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="Template\Velocity\config.properties">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<Folder Include="Properties\" />
</ItemGroup>

View File

@@ -0,0 +1 @@
value=${var1}

View File

@@ -20,6 +20,9 @@
#region Imports
using System;
using System.Collections;
using System.Text;
using NUnit.Framework;
using NVelocity.App;
using Spring.Context.Support;
@@ -27,29 +30,111 @@ using Spring.Objects.Factory.Xml;
#endregion
namespace Spring.Template.Velocity.Tests.Template.Velocity
{
namespace Spring.Template.Velocity.Tests.Template.Velocity {
/// <summary>
/// This class contains tests for VelocityEngineFactoryObject
/// </summary>
/// <author>Mark Pollack</author>
/// <author>Erez Mazor</author>
[TestFixture]
public class VelocityEngineFactoryObjectTests
{
public class VelocityEngineFactoryObjectTests {
private const string TEST_VALUE = "TEST_VALUE";
private XmlApplicationContext appContext;
private readonly Hashtable model = new Hashtable();
[SetUp]
public void Setup()
{
public void Setup() {
appContext = new XmlApplicationContext(false,
ReadOnlyXmlTestResource.GetFilePath(
"VelocityEngineFactoryObjectTests.xml",
typeof(VelocityEngineFactoryObjectTests)));
model.Add("var1", TEST_VALUE);
}
[TearDown]
public void TearDown() {
appContext.Dispose();
model.Clear();
}
/// <summary>
/// Test the assemblyBasedVelocityEngine bean configuration from VelocityEngineFactoryObjectTests.xml
/// </summary>
[Test]
public void Test()
{
XmlApplicationContext appContext = new XmlApplicationContext(false,
ReadOnlyXmlTestResource.GetFilePath(
"VelocityEngineFactoryObjectTests.xml",
typeof (VelocityEngineFactoryObjectTests)));
VelocityEngine velocityEngine = appContext.GetObject("velocityEngine") as VelocityEngine;
Assert.IsNotNull(velocityEngine);
public void TestMergeUsingAssembly() {
VelocityEngine velocityEngine = appContext.GetObject("assemblyBasedVelocityEngine") as VelocityEngine;
Assert.IsNotNull(velocityEngine, "velocityEngine is null");
string mergedTemplate = VelocityEngineUtils.MergeTemplateIntostring(velocityEngine, "Spring.Template.Velocity.Tests.Template.Velocity.SimpleTemplate.vm", Encoding.UTF8.WebName, model);
Assert.AreEqual(string.Format("value={0}", TEST_VALUE), mergedTemplate);
}
/// <summary>
/// Test the fileBasedVelocityEngine bean configuration from VelocityEngineFactoryObjectTests.xml
/// </summary>
[Test]
public void TestMergeUsingFile() {
VelocityEngine velocityEngine = appContext.GetObject("fileBasedVelocityEngine") as VelocityEngine;
Assert.IsNotNull(velocityEngine, "velocityEngine is null");
string mergedTemplate = VelocityEngineUtils.MergeTemplateIntostring(
velocityEngine, "Template/Velocity/SimpleTemplate.vm", Encoding.UTF8.WebName, model);
Assert.AreEqual(string.Format("value={0}", TEST_VALUE), mergedTemplate);
}
/// <summary>
/// Test using definition of ResourceLoaderPath (file-based configuration) referencing just the template name
/// </summary>
[Test]
public void TestMergeUsingResourceLoaderPath() {
VelocityEngine velocityEngine =
appContext.GetObject("pathBasedVelocityEngine") as VelocityEngine;
Assert.IsNotNull(velocityEngine, "velocityEngine is null");
string mergedTemplate = VelocityEngineUtils.MergeTemplateIntostring(velocityEngine, "SimpleTemplate.vm",
Encoding.UTF8.WebName, model);
Assert.AreEqual(string.Format("value={0}", "TEST_VALUE"), mergedTemplate);
}
/// <summary>
/// Test using a custom properties file (assembly-based configuration)
/// </summary>
[Test]
public void TestMergeUsingConfigPropertiesFile() {
VelocityEngine velocityEngine =
appContext.GetObject("propertiesFileBasedVelocityEngine") as VelocityEngine;
Assert.IsNotNull(velocityEngine, "velocityEngine is null");
string mergedTemplate = VelocityEngineUtils.MergeTemplateIntostring(velocityEngine,
"Spring.Template.Velocity.Tests.Template.Velocity.SimpleTemplate.vm",
Encoding.UTF8.WebName, model);
Assert.AreEqual(string.Format("value={0}", "TEST_VALUE"), mergedTemplate);
}
/// <summary>
/// Test using spring resource loader
/// </summary>
[Test]
public void TestMergeUsingSpringResourceLoader() {
VelocityEngine velocityEngine =
appContext.GetObject("springResourceLoaderBasedVelocityEngine") as VelocityEngine;
Assert.IsNotNull(velocityEngine, "velocityEngine is null");
string mergedTemplate = VelocityEngineUtils.MergeTemplateIntostring(velocityEngine, "SimpleTemplate.vm",
Encoding.UTF8.WebName, model);
Assert.AreEqual(string.Format("value={0}", "TEST_VALUE"), mergedTemplate);
}
/// <summary>
/// Test using invalid configuration
/// </summary>
[Test]
public void TestInvalidConfiguration() {
VelocityEngineFactory velocityEngineFactory = new VelocityEngineFactory();
velocityEngineFactory.PreferFileSystemAccess = false;
VelocityEngine velocityEngine = null;
try {
velocityEngineFactory.CreateVelocityEngine();
throw new TestException(
"Should not be able to construct VelocityEngineFactory with SpringResourceLoader and no path");
} catch (ArgumentException) {
Assert.IsNull(velocityEngine, "velocityEngine should be null");
}
}
}
}

View File

@@ -1,15 +1,43 @@
<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net">
<object id="velocityEngine" type="Spring.Template.Velocity.VelocityEngineFactoryObject, Spring.Template.Velocity">
<!-- Does file system access with hot tracking with NVelocity assembly resource loader -->
<object id="assemblyBasedVelocityEngine" type="Spring.Template.Velocity.VelocityEngineFactoryObject, Spring.Template.Velocity">
<property name="VelocityProperties">
<dictionary key-type="string" value-type="object">
<entry key="resource.loader" value="assembly"/>
<entry key="assembly.resource.loader.class" value="NVelocity.Runtime.Resource.Loader.AssemblyResourceLoader"/>
<entry key="assembly.resource.loader.assembly" value="MyAssembly"/>
<entry key="resource.manager.class" value="NVelocity.Runtime.Resource.ResourceManagerImpl"/>
<entry key="directive.manager" value="NVelocity.Runtime.Directive.DirectiveManager"/>
<entry key="runtime.introspector.uberspect" value="NVelocity.Util.Introspection.UberspectImpl"/>
<entry key="assembly.resource.loader.assembly" value="Spring.Template.Velocity.Tests"/>
</dictionary>
</property>
</object>
<!-- Simple no arg file based configuration use's NVeclocity default file resource loader -->
<object id="fileBasedVelocityEngine" type="Spring.Template.Velocity.VelocityEngineFactoryObject, Spring.Template.Velocity" />
<!-- File based NVelocity resource loader, directory based configuration-->
<object id="pathBasedVelocityEngine" type="Spring.Template.Velocity.VelocityEngineFactoryObject, Spring.Template.Velocity" >
<property name="ResourceLoaderPath " value="Template/Velocity/" />
<!--
<property name="ResourceLoaderPaths" >
<list>
<value>Path1</value>
<value>Path2</value>
</list>
</property>
-->
</object>
<!-- Configuration comes from a properties file -->
<object id="propertiesFileBasedVelocityEngine" type="Spring.Template.Velocity.VelocityEngineFactoryObject, Spring.Template.Velocity" >
<property name="ConfigLocation " value="file://Template/Velocity/config.properties" />
</object>
<!-- Use (ConfigurableResourceLoader) spring resource abstraction for templates that are not file or assembly based -->
<object id="springResourceLoaderBasedVelocityEngine" type="Spring.Template.Velocity.VelocityEngineFactoryObject, Spring.Template.Velocity" >
<!--<property name="ResourceLoaderPath " value="http://somesite/template.vm" />-->
<property name="ResourceLoaderPath " value="Template/Velocity/" />
<property name="PreferFileSystemAccess " value="false" />
</object>
</objects>

View File

@@ -0,0 +1,3 @@
resource.loader=assembly
assembly.resource.loader.class=NVelocity.Runtime.Resource.Loader.AssemblyResourceLoader
assembly.resource.loader.assembly=Spring.Template.Velocity.Tests