using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Apache.Ibatis.Common.Contracts;
using Apache.Ibatis.Common.Logging;
using Apache.Ibatis.DataMapper.Exceptions;
using Apache.Ibatis.DataMapper.MappedStatements;
using Apache.Ibatis.DataMapper.Model.Sql.External;
using NVelocity;
using NVelocity.App;
namespace Apache.Ibatis.DataMapper.SqlClient.Test.Domain
{
///
/// NVelocity implemantation of
/// which parse sql string using Velocity language
///
///
/// See http://www.castleproject.org/others/nvelocity/index.html
///
public class NVelocityDynamicEngine : ISqlSource
{
private readonly VelocityEngine velocityEngine = null;
private const string VELOCITY_DIRECTIVE = "$";
private static readonly ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
///
/// Initializes a new instance of the class.
///
public NVelocityDynamicEngine()
{
velocityEngine = new VelocityEngine();
velocityEngine.Init();
}
#region ISqlSource Members
///
/// Gets the SQL.
///
/// The mapped statement.
/// The parameter object.
///
///
/// Paremeters should be typeof IDictionary
///
public string GetSql(IMappedStatement mappedStatement, object parameterObject)
{
Contract.Assert.That(parameterObject, Is.TypeOf>()).When("Processing NVelocity source for statement :" + mappedStatement.Id);
StringWriter sw = new StringWriter();
ExternalSql externalSql = (ExternalSql)mappedStatement.Statement.Sql;
string commandText = externalSql.CommandText;
if (commandText.Contains(VELOCITY_DIRECTIVE))
{
VelocityContext velocityContext = new VelocityContext();
IDictionary dico = (IDictionary)parameterObject;
foreach(string key in dico.Keys)
{
velocityContext.Put(key, dico[key]);
}
try
{
velocityEngine.Evaluate(velocityContext, sw, "error", commandText);
}
catch (Exception ex)
{
if (logger.IsDebugEnabled)
{
logger.Debug("Could not parse velocity string '" + commandText + "' for " + mappedStatement.Id);
}
throw new DataMapperException("Could not parse velocity string '" + commandText + "' for " + mappedStatement.Id);
}
commandText = sw.GetStringBuilder().ToString();
}
if (logger.IsDebugEnabled)
{
logger.Debug("SQL command text parse by velocity: " + commandText);
}
return commandText;
}
#endregion
}
}