[Adapdev-commits] Adapdev/src/Adapdev.NVelocity/App AppSupportClass.cs,1.2,1.3 FieldMethodizer.cs,1.
Status: Beta
Brought to you by:
intesar66
From: Sean M. <int...@us...> - 2005-11-16 05:45:33
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/App In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv22005/src/Adapdev.NVelocity/App Added Files: AppSupportClass.cs FieldMethodizer.cs Velocity.cs VelocityEngine.cs Log Message: --- NEW FILE: AppSupportClass.cs --- using System; public class AppSupportClass { public class TextNumberFormat { // Declaration of fields private System.Globalization.NumberFormatInfo numberFormat; private enum formatTypes { General, Number, Currency, Percent }; private int numberFormatType; private bool groupingActivated; private string separator; private int digits; // CONSTRUCTORS public TextNumberFormat() { this.numberFormat = new System.Globalization.NumberFormatInfo(); this.numberFormatType = (int)TextNumberFormat.formatTypes.General; this.groupingActivated = true; this.separator = this.GetSeparator( (int)TextNumberFormat.formatTypes.General ); this.digits = 3; } private TextNumberFormat(TextNumberFormat.formatTypes theType, int digits) { this.numberFormat = System.Globalization.NumberFormatInfo.CurrentInfo; this.numberFormatType = (int)theType; this.groupingActivated = true; this.separator = this.GetSeparator( (int)theType ); this.digits = digits; } private TextNumberFormat(TextNumberFormat.formatTypes theType, System.Globalization.CultureInfo cultureNumberFormat, int digits) { this.numberFormat = cultureNumberFormat.NumberFormat; this.numberFormatType = (int)theType; this.groupingActivated = true; this.separator = this.GetSeparator( (int)theType ); this.digits = digits; } public static TextNumberFormat getTextNumberInstance() { TextNumberFormat instance = new TextNumberFormat(TextNumberFormat.formatTypes.Number, 3); return instance; } public static TextNumberFormat getTextNumberCurrencyInstance() { TextNumberFormat instance = new TextNumberFormat(TextNumberFormat.formatTypes.Currency, 3); return instance; } public static TextNumberFormat getTextNumberPercentInstance() { TextNumberFormat instance = new TextNumberFormat(TextNumberFormat.formatTypes.Percent, 3); return instance; } public static TextNumberFormat getTextNumberInstance(System.Globalization.CultureInfo culture) { TextNumberFormat instance = new TextNumberFormat(TextNumberFormat.formatTypes.Number, culture, 3); return instance; } public static TextNumberFormat getTextNumberCurrencyInstance(System.Globalization.CultureInfo culture) { TextNumberFormat instance = new TextNumberFormat(TextNumberFormat.formatTypes.Currency, culture, 3); return instance; } public static TextNumberFormat getTextNumberPercentInstance(System.Globalization.CultureInfo culture) { TextNumberFormat instance = new TextNumberFormat(TextNumberFormat.formatTypes.Percent, culture, 3); return instance; } public System.Object Clone() { return (System.Object)this; } public override bool Equals(System.Object textNumberObject) { return System.Object.Equals((System.Object)this, textNumberObject); } public string FormatDouble(double number) { if (this.groupingActivated) { return number.ToString(this.GetCurrentFormatString() + this.digits , this.numberFormat); } else { return (number.ToString(this.GetCurrentFormatString() + this.digits , this.numberFormat)).Replace(this.separator,""); } } public string FormatLong(long number) { if (this.groupingActivated) { return number.ToString(this.GetCurrentFormatString() + this.digits , this.numberFormat); } else { return (number.ToString(this.GetCurrentFormatString() + this.digits , this.numberFormat)).Replace(this.separator,""); } } public static System.Globalization.CultureInfo[] GetAvailableCultures() { return System.Globalization.CultureInfo.GetCultures(System.Globalization.CultureTypes.AllCultures); } public override int GetHashCode() { return this.GetHashCode(); } private string GetCurrentFormatString() { string currentFormatString = "n"; //Default value switch (this.numberFormatType) { case (int)TextNumberFormat.formatTypes.Currency: currentFormatString = "c"; break; case (int)TextNumberFormat.formatTypes.General: currentFormatString = "n" + this.numberFormat.NumberDecimalDigits; break; case (int)TextNumberFormat.formatTypes.Number: currentFormatString = "n" + this.numberFormat.NumberDecimalDigits; break; case (int)TextNumberFormat.formatTypes.Percent: currentFormatString = "p"; break; } return currentFormatString; } private string GetSeparator(int numberFormatType) { string separatorItem = " "; //Default Separator switch (numberFormatType) { case (int)TextNumberFormat.formatTypes.Currency: separatorItem = this.numberFormat.CurrencyGroupSeparator; break; case (int)TextNumberFormat.formatTypes.General: separatorItem = this.numberFormat.NumberGroupSeparator; break; case (int)TextNumberFormat.formatTypes.Number: separatorItem = this.numberFormat.NumberGroupSeparator; break; case (int)TextNumberFormat.formatTypes.Percent: separatorItem = this.numberFormat.PercentGroupSeparator; break; } return separatorItem; } public bool GroupingUsed { get { return (this.groupingActivated); } set { this.groupingActivated = value; } } public int Digits { get { return this.digits; } set { this.digits = value; } } } /*******************************/ public class DateTimeFormatManager { static public DateTimeFormatHashTable manager = new DateTimeFormatHashTable(); public class DateTimeFormatHashTable :System.Collections.Hashtable { public void SetDateFormatPattern(System.Globalization.DateTimeFormatInfo format, System.String newPattern) { if (this[format] != null) ((DateTimeFormatProperties) this[format]).DateFormatPattern = newPattern; else { DateTimeFormatProperties tempProps = new DateTimeFormatProperties(); tempProps.DateFormatPattern = newPattern; Add(format, tempProps); } } public string GetDateFormatPattern(System.Globalization.DateTimeFormatInfo format) { if (this[format] == null) return "d-MMM-yy"; else return ((DateTimeFormatProperties) this[format]).DateFormatPattern; } public void SetTimeFormatPattern(System.Globalization.DateTimeFormatInfo format, System.String newPattern) { if (this[format] != null) ((DateTimeFormatProperties) this[format]).TimeFormatPattern = newPattern; else { DateTimeFormatProperties tempProps = new DateTimeFormatProperties(); tempProps.TimeFormatPattern = newPattern; Add(format, tempProps); } } public string GetTimeFormatPattern(System.Globalization.DateTimeFormatInfo format) { if (this[format] == null) return "h:mm:ss tt"; else return ((DateTimeFormatProperties) this[format]).TimeFormatPattern; } class DateTimeFormatProperties { public string DateFormatPattern = "d-MMM-yy"; public string TimeFormatPattern = "h:mm:ss tt"; } } } /*******************************/ public static string FormatDateTime(System.Globalization.DateTimeFormatInfo format, System.DateTime date) { string timePattern = DateTimeFormatManager.manager.GetTimeFormatPattern(format); string datePattern = DateTimeFormatManager.manager.GetDateFormatPattern(format); return date.ToString(datePattern + " " + timePattern, format); } /*******************************/ public static System.Globalization.DateTimeFormatInfo GetDateTimeFormatInstance(int dateStyle, int timeStyle, System.Globalization.CultureInfo culture) { System.Globalization.DateTimeFormatInfo format = culture.DateTimeFormat; switch (timeStyle) { case -1: DateTimeFormatManager.manager.SetTimeFormatPattern(format, ""); break; case 0: DateTimeFormatManager.manager.SetTimeFormatPattern(format, "h:mm:ss 'o clock' tt zzz"); break; case 1: DateTimeFormatManager.manager.SetTimeFormatPattern(format, "h:mm:ss tt zzz"); break; case 2: DateTimeFormatManager.manager.SetTimeFormatPattern(format, "h:mm:ss tt"); break; case 3: DateTimeFormatManager.manager.SetTimeFormatPattern(format, "h:mm tt"); break; } switch (dateStyle) { case -1: DateTimeFormatManager.manager.SetDateFormatPattern(format, ""); break; case 0: DateTimeFormatManager.manager.SetDateFormatPattern(format, "dddd, MMMM dd%, yyy"); break; case 1: DateTimeFormatManager.manager.SetDateFormatPattern(format, "MMMM dd%, yyy" ); break; case 2: DateTimeFormatManager.manager.SetDateFormatPattern(format, "d-MMM-yy" ); break; case 3: DateTimeFormatManager.manager.SetDateFormatPattern(format, "M/dd/yy"); break; } return format; } } --- NEW FILE: Velocity.cs --- namespace NVelocity.App { using System; using System.IO; using System.Text; using Commons.Collections; using NVelocity.Context; using NVelocity.Exception; using NVelocity.Runtime; using NVelocity.Runtime.Parser; using NVelocity.Runtime.Parser.Node; /// <summary> /// This class provides services to the application /// developer, such as : /// <ul> /// <li> Simple Velocity Runtime engine initialization methods. /// <li> Functions to apply the template engine to streams and strings /// to allow embedding and dynamic template generation. /// <li> Methods to access Velocimacros directly. /// </ul> /// <br><br> /// 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. /// <br><br> /// 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. /// </summary> public class Velocity : RuntimeConstants { /// <summary> /// initialize the NVelocity runtime engine, using the default /// properties of the NVelocity distribution /// </summary> public static void Init() { RuntimeSingleton.init(); } /// <summary> /// initialize the Velocity runtime engine, using default properties /// plus the properties in the properties file passed in as the arg /// </summary> /// <param name="propsFilename"> /// file containing properties to use to initialize /// the Velocity runtime /// </param> public static void Init(String propsFilename) { RuntimeSingleton.init(propsFilename); } /// <summary> /// initialize the Velocity runtime engine, using default properties /// plus the properties in the passed in java.util.Properties object /// </summary> /// <param name="p"> /// Proprties object containing initialization properties /// </param> public static void Init(ExtendedProperties p) { RuntimeSingleton.init(p); } /// <summary> /// Set a Velocity Runtime property. /// </summary> /// <param name="String">key</param> /// <param name="Object">value</param> public static void SetProperty(String key, Object value_Renamed) { RuntimeSingleton.setProperty(key, value_Renamed); } /// <summary> /// Add a Velocity Runtime property. /// </summary> /// <param name="String">key</param> /// <param name="Object">value</param> public static void AddProperty(String key, Object value_Renamed) { RuntimeSingleton.addProperty(key, value_Renamed); } /// <summary> /// Clear a NVelocity Runtime property. /// </summary> /// <param name="key">of property to clear</param> public static void ClearProperty(String key) { RuntimeSingleton.clearProperty(key); } /// <summary> /// 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. /// </summary> /// <param name="ExtendedProperties">configuration</param> public static ExtendedProperties ExtendedProperties { set { RuntimeSingleton.Configuration = value; } } /// <summary> /// Get a Velocity Runtime property. /// </summary> /// <param name="key">property to retrieve</param> /// <returns>property value or null if the property not currently set</returns> public static Object GetProperty(String key) { return RuntimeSingleton.getProperty(key); } /// <summary> /// 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. /// </summary> /// <param name="context">context to use in rendering input string /// </param> /// <param name="out"> Writer in which to render the output /// </param> /// <param name="logTag"> string to be used as the template name for log /// messages in case of error /// </param> /// <param name="instring">input string containing the VTL to be rendered /// </param> /// <returns>true if successful, false otherwise. If false, see /// Velocity runtime log /// </returns> public static bool Evaluate(IContext context, TextWriter out_Renamed, String logTag, String instring) { return Evaluate(context, out_Renamed, logTag, new StringReader(instring)); } /// <summary> /// 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. /// </summary> /// <param name="context">context to use in rendering input string /// </param> /// <param name="out"> Writer in which to render the output /// </param> /// <param name="logTag"> string to be used as the template name for log messages /// in case of error /// </param> /// <param name="instream">input stream containing the VTL to be rendered /// </param> /// <returns>true if successful, false otherwise. If false, see /// Velocity runtime log /// </returns> /// <deprecated>Use /// {@link #evaluate( Context context, Writer writer, /// String logTag, Reader reader ) } /// </deprecated> public static bool Evaluate(IContext context, TextWriter writer, String logTag, Stream instream) { /* * first, parse - convert ParseException if thrown */ TextReader reader = null; String encoding = null; try { encoding = RuntimeSingleton.getString(RuntimeConstants_Fields.INPUT_ENCODING, RuntimeConstants_Fields.ENCODING_DEFAULT); reader = new StreamReader(new StreamReader(instream, Encoding.GetEncoding(encoding)).BaseStream); } catch (IOException uce) { String msg = "Unsupported input encoding : " + encoding + " for template " + logTag; throw new ParseErrorException(msg); } return Evaluate(context, writer, logTag, reader); } /// <summary> /// 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. /// </summary> /// <param name="context">context to use in rendering input string</param> /// <param name="out"> Writer in which to render the output</param> /// <param name="logTag"> string to be used as the template name for log messages in case of error</param> /// <param name="reader">Reader containing the VTL to be rendered</param> /// <returns>true if successful, false otherwise. If false, see Velocity runtime log</returns> public static bool Evaluate(IContext context, TextWriter writer, String logTag, TextReader reader) { SimpleNode nodeTree = null; try { nodeTree = RuntimeSingleton.parse(reader, logTag); } catch (ParseException pex) { throw new ParseErrorException(pex.Message); } /* * now we want to init and render */ if (nodeTree != null) { InternalContextAdapterImpl ica = new InternalContextAdapterImpl(context); ica.PushCurrentTemplateName(logTag); try { try { nodeTree.init(ica, RuntimeSingleton.RuntimeServices); } catch (Exception e) { RuntimeSingleton.error("Velocity.evaluate() : init exception for tag = " + logTag + " : " + e); } /* * now render, and let any exceptions fly */ nodeTree.render(ica, writer); } finally { ica.PopCurrentTemplateName(); } return true; } return false; } /// <summary> /// Invokes a currently registered Velocimacro with the parms provided /// and places the rendered stream into the writer. /// <br> /// Note : currently only accepts args to the VM if they are in the context. /// </summary> /// <param name="vmName">name of Velocimacro to call /// </param> /// <param name="logTag">string to be used for template name in case of error /// </param> /// <param name="params[]">args used to invoke Velocimacro. In context key format : /// eg "foo","bar" (rather than "$foo","$bar") /// </param> /// <param name="context">Context object containing data/objects used for rendering. /// </param> /// <param name="writer"> Writer for output stream /// </param> /// <returns>true if Velocimacro exists and successfully invoked, false otherwise. /// </returns> public static bool InvokeVelocimacro(String vmName, String logTag, String[] params_Renamed, IContext context, TextWriter writer) { /* * check parms */ if (vmName == null || params_Renamed == null || context == null || writer == null || logTag == null) { RuntimeSingleton.error("Velocity.invokeVelocimacro() : invalid parameter"); return false; } /* * does the VM exist? */ if (!RuntimeSingleton.isVelocimacro(vmName, logTag)) { RuntimeSingleton.error("Velocity.invokeVelocimacro() : VM '" + vmName + "' not registered."); return false; } /* * now just create the VM call, and use evaluate */ StringBuilder construct = new StringBuilder("#"); construct.Append(vmName); construct.Append("("); for (int i = 0; i < params_Renamed.Length; i++) { construct.Append(" $"); construct.Append(params_Renamed[i]); } construct.Append(" )"); try { bool retval = Evaluate(context, writer, logTag, construct.ToString()); return retval; } catch (Exception e) { RuntimeSingleton.error("Velocity.invokeVelocimacro() : error " + e); } return false; } /// <summary> /// merges a template and puts the rendered stream into the writer /// </summary> /// <param name="templateName">name of template to be used in merge /// </param> /// <param name="context"> filled context to be used in merge /// </param> /// <param name="writer"> writer to write template into /// </param> /// <returns>true if successful, false otherwise. Errors /// logged to velocity log. /// </returns> /// <deprecated>Use /// {@link #mergeTemplate( String templateName, String encoding, /// Context context, Writer writer )} /// </deprecated> public static bool MergeTemplate(String templateName, IContext context, TextWriter writer) { return MergeTemplate(templateName, RuntimeSingleton.getString(RuntimeConstants_Fields.INPUT_ENCODING, RuntimeConstants_Fields.ENCODING_DEFAULT), context, writer); } /// <summary> /// merges a template and puts the rendered stream into the writer /// </summary> /// <param name="templateName">name of template to be used in merge /// </param> /// <param name="encoding">encoding used in template /// </param> /// <param name="context"> filled context to be used in merge /// </param> /// <param name="writer"> writer to write template into /// </param> /// <returns>true if successful, false otherwise. Errors /// logged to velocity log /// @since Velocity v1.1 /// </returns> public static bool MergeTemplate(String templateName, String encoding, IContext context, TextWriter writer) { Template template = RuntimeSingleton.getTemplate(templateName, encoding); if (template == null) { RuntimeSingleton.error("Velocity.parseTemplate() failed loading template '" + templateName + "'"); return false; } else { template.Merge(context, writer); return true; } } /// <summary> /// Returns a <code>Template</code> from the Velocity /// resource management system. /// </summary> /// <param name="name">The file name of the desired template. /// </param> /// <returns> 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> public static Template GetTemplate(String name) { return RuntimeSingleton.getTemplate(name); } /// <summary> /// Returns a <code>Template</code> from the Velocity /// resource management system. /// </summary> /// <param name="name">The file name of the desired template. /// </param> /// <param name="encoding">The character encoding to use for the template. /// </param> /// <returns> 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 /// @since Velocity v1.1 /// </returns> public static Template GetTemplate(String name, String encoding) { return RuntimeSingleton.getTemplate(name, encoding); } /// <summary> /// Determines if a template is accessable via the currently /// configured resource loaders. /// <br><br> /// Note that the current implementation will <b>not</b> /// 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. /// <br><br> /// The previous implementation exhibited extreme lazyness and /// sloth, and the author has been flogged. /// </summary> /// <param name="templateName"> name of the temlpate to search for /// </param> /// <returns>true if found, false otherwise /// </returns> public static bool TemplateExists(String templateName) { return (RuntimeSingleton.getLoaderNameForResource(templateName) != null); } /// <summary> /// Log a warning message. /// </summary> /// <param name="Object">message to log /// </param> public static void Warn(Object message) { RuntimeSingleton.warn(message); } /// <summary> /// Log an info message. /// </summary> /// <param name="Object">message to log</param> public static void Info(Object message) { RuntimeSingleton.info(message); } /// <summary> /// Log an error message. /// </summary> /// <param name="Object">message to log</param> public static void Error(Object message) { RuntimeSingleton.error(message); } /// <summary> /// Log a debug message. /// </summary> /// <param name="Object">message to log</param> public static void Debug(Object message) { RuntimeSingleton.debug(message); } /// <summary> /// <p> /// Set the an ApplicationAttribue, which is an Object /// set by the application which is accessable 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. /// </p> /// <p> /// Note that there is no enfocement 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. /// </p> /// </summary> /// <param name="key">object 'name' under which the object is stored /// </param> /// <param name="value">object to store under this key /// </param> public static void SetApplicationAttribute(Object key, Object value_Renamed) { RuntimeSingleton.RuntimeInstance.setApplicationAttribute(key, value_Renamed); } } } --- NEW FILE: VelocityEngine.cs --- namespace NVelocity.App { using System; using System.IO; using System.Text; using Commons.Collections; using NVelocity.Context; using NVelocity.Exception; using NVelocity.Runtime; using NVelocity.Runtime.Parser; using NVelocity.Runtime.Parser.Node; /// <summary> /// <p> /// 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. /// </p> /// <p> /// Please ensure that you call one of the init() variants. /// This is critical for proper behavior. /// </p> /// <p> 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(). /// </p> /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a></author> public class VelocityEngine : RuntimeConstants { private RuntimeInstance ri = new RuntimeInstance(); public VelocityEngine() { } /// <summary> /// 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. /// </summary> /// <param name="ExtendedProperties">configuration /// </param> public virtual ExtendedProperties ExtendedProperties { set { ri.Configuration = value; } } /// <summary> /// initialize the Velocity runtime engine, using the default /// properties of the Velocity distribution /// </summary> public virtual void Init() { ri.init(); } /// <summary> /// initialize the Velocity runtime engine, using default properties /// plus the properties in the properties file passed in as the arg /// </summary> /// <param name="propsFilename">file containing properties to use to initialize /// the Velocity runtime</param> public virtual void Init(String propsFilename) { ri.init(propsFilename); } /// <summary> /// initialize the Velocity runtime engine, using default properties /// plus the properties in the passed in java.util.Properties object /// </summary> /// <param name="p"> Proprties object containing initialization properties</param> public virtual void Init(ExtendedProperties p) { ri.init(p); } /// <summary> /// Set a Velocity Runtime property. /// </summary> /// <param name="String">key</param> /// <param name="Object">value</param> public virtual void SetProperty(String key, Object value_Renamed) { ri.setProperty(key, value_Renamed); } /// <summary> /// Add a Velocity Runtime property. /// </summary> /// <param name="String">key /// </param> /// <param name="Object">value /// </param> public virtual void AddProperty(String key, Object value_Renamed) { ri.addProperty(key, value_Renamed); } /// <summary> /// Clear a Velocity Runtime property. /// </summary> /// <param name="key">of property to clear /// </param> public virtual void ClearProperty(String key) { ri.clearProperty(key); } /// <summary> /// Get a Velocity Runtime property. /// </summary> /// <param name="key">property to retrieve /// </param> /// <returns>property value or null if the property /// not currently set /// </returns> public virtual Object GetProperty(String key) { return ri.getProperty(key); } /// <summary> /// 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. /// </summary> /// <param name="context">context to use in rendering input string /// </param> /// <param name="out"> Writer in which to render the output /// </param> /// <param name="logTag"> string to be used as the template name for log /// messages in case of error /// </param> /// <param name="instring">input string containing the VTL to be rendered /// </param> /// <returns>true if successful, false otherwise. If false, see /// Velocity runtime log /// </returns> public virtual bool Evaluate(IContext context, TextWriter out_Renamed, String logTag, String instring) { return Evaluate(context, out_Renamed, logTag, new StringReader(instring)); } /// <summary> /// 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. /// </summary> /// <param name="context">context to use in rendering input string /// </param> /// <param name="out"> Writer in which to render the output /// </param> /// <param name="logTag"> string to be used as the template name for log messages /// in case of error /// </param> /// <param name="instream">input stream containing the VTL to be rendered /// </param> /// <returns>true if successful, false otherwise. If false, see /// Velocity runtime log /// </returns> /// <deprecated>Use /// {@link #evaluate( Context context, Writer writer, /// String logTag, Reader reader ) } /// </deprecated> public virtual bool Evaluate(IContext context, TextWriter writer, String logTag, Stream instream) { /* * first, parse - convert ParseException if thrown */ TextReader br = null; String encoding = null; try { encoding = ri.getString(RuntimeConstants_Fields.INPUT_ENCODING, RuntimeConstants_Fields.ENCODING_DEFAULT); br = new StreamReader(new StreamReader(instream, Encoding.GetEncoding(encoding)).BaseStream); } catch (IOException uce) { String msg = "Unsupported input encoding : " + encoding + " for template " + logTag; throw new ParseErrorException(msg); } return Evaluate(context, writer, logTag, br); } /// <summary> /// 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. /// </summary> /// <param name="context">context to use in rendering input string /// </param> /// <param name="out"> Writer in which to render the output /// </param> /// <param name="logTag"> string to be used as the template name for log messages /// in case of error /// </param> /// <param name="reader">Reader containing the VTL to be rendered /// </param> /// <returns>true if successful, false otherwise. If false, see /// Velocity runtime log /// @since Velocity v1.1 /// </returns> public virtual bool Evaluate(IContext context, TextWriter writer, String logTag, TextReader reader) { SimpleNode nodeTree = null; try { nodeTree = ri.parse(reader, logTag); } catch (ParseException pex) { throw new ParseErrorException(pex.Message); } /* * now we want to init and render */ if (nodeTree != null) { InternalContextAdapterImpl ica = new InternalContextAdapterImpl(context); ica.PushCurrentTemplateName(logTag); try { try { nodeTree.init(ica, ri); } catch (Exception e) { ri.error("Velocity.evaluate() : init exception for tag = " + logTag + " : " + e); } /* * now render, and let any exceptions fly */ nodeTree.render(ica, writer); } finally { ica.PopCurrentTemplateName(); } return true; } return false; } /// <summary> /// Invokes a currently registered Velocimacro with the parms provided /// and places the rendered stream into the writer. /// Note : currently only accepts args to the VM if they are in the context. /// </summary> /// <param name="vmName">name of Velocimacro to call /// </param> /// <param name="logTag">string to be used for template name in case of error /// </param> /// <param name="params[]">args used to invoke Velocimacro. In context key format : /// eg "foo","bar" (rather than "$foo","$bar") /// </param> /// <param name="context">Context object containing data/objects used for rendering. /// </param> /// <param name="writer"> Writer for output stream /// </param> /// <returns>true if Velocimacro exists and successfully invoked, false otherwise. /// </returns> public virtual bool InvokeVelocimacro(String vmName, String logTag, String[] params_Renamed, IContext context, TextWriter writer) { /* * check parms */ if (vmName == null || params_Renamed == null || context == null || writer == null || logTag == null) { ri.error("VelocityEngine.invokeVelocimacro() : invalid parameter"); return false; } /* * does the VM exist? */ if (!ri.isVelocimacro(vmName, logTag)) { ri.error("VelocityEngine.invokeVelocimacro() : VM '" + vmName + "' not registered."); return false; } /* * now just create the VM call, and use evaluate */ StringBuilder construct = new StringBuilder("#"); construct.Append(vmName); construct.Append("("); for (int i = 0; i < params_Renamed.Length; i++) { construct.Append(" $"); construct.Append(params_Renamed[i]); } construct.Append(" )"); try { bool retval = Evaluate(context, writer, logTag, construct.ToString()); return retval; } catch (Exception e) { ri.error("VelocityEngine.invokeVelocimacro() : error " + e); throw e; } } /// <summary> /// merges a template and puts the rendered stream into the writer /// </summary> /// <param name="templateName">name of template to be used in merge /// </param> /// <param name="context"> filled context to be used in merge /// </param> /// <param name="writer"> writer to write template into /// </param> /// <returns>true if successful, false otherwise. Errors /// logged to velocity log. /// </returns> /// <deprecated>Use /// {@link #mergeTemplate( String templateName, String encoding, /// Context context, Writer writer )} /// </deprecated> public virtual bool MergeTemplate(String templateName, IContext context, TextWriter writer) { return MergeTemplate(templateName, ri.getString(RuntimeConstants_Fields.INPUT_ENCODING, RuntimeConstants_Fields.ENCODING_DEFAULT), context, writer); } /// <summary> /// merges a template and puts the rendered stream into the writer /// </summary> /// <param name="templateName">name of template to be used in merge /// </param> /// <param name="encoding">encoding used in template /// </param> /// <param name="context"> filled context to be used in merge /// </param> /// <param name="writer"> writer to write template into /// </param> /// <returns>true if successful, false otherwise. Errors /// logged to velocity log /// @since Velocity v1.1 /// </returns> public virtual bool MergeTemplate(String templateName, String encoding, IContext context, TextWriter writer) { Template template = ri.getTemplate(templateName, encoding); if (template == null) { ri.error("Velocity.parseTemplate() failed loading template '" + templateName + "'"); return false; } else { template.Merge(context, writer); return true; } } /// <summary> /// Returns a <code>Template</code> from the Velocity /// resource management system. /// </summary> /// <param name="name">The file name of the desired template. /// </param> /// <returns> 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> public virtual Template GetTemplate(String name) { return ri.getTemplate(name); } /// <summary> /// Returns a <code>Template</code> from the Velocity /// resource management system. /// </summary> /// <param name="name">The file name of the desired template. /// </param> /// <param name="encoding">The character encoding to use for the template. /// </param> /// <returns> 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 /// @since Velocity v1.1 /// </returns> public virtual Template GetTemplate(String name, String encoding) { return ri.getTemplate(name, encoding); } /// <summary> /// Determines if a template is accessable via the currently /// configured resource loaders. /// <br><br> /// Note that the current implementation will <b>not</b> /// 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. /// <br><br> /// The previous implementation exhibited extreme lazyness and /// sloth, and the author has been flogged. /// </summary> /// <param name="templateName"> name of the temlpate to search for /// </param> /// <returns>true if found, false otherwise /// </returns> public virtual bool TemplateExists(String templateName) { return (ri.getLoaderNameForResource(templateName) != null); } /// <summary> /// Log a warning message. /// </summary> /// <param name="Object">message to log</param> public virtual void Warn(Object message) { ri.warn(message); } /// /// <summary> /// Log an info message. /// </summary> /// <param name="Object">message to log</param> public virtual void Info(Object message) { ri.info(message); } /// <summary> /// Log an error message. /// </summary> /// <param name="Object">message to log</param> public virtual void Error(Object message) { ri.error(message); } /// <summary> /// Log a debug message. /// </summary> /// <param name="Object">message to log</param> public virtual void Debug(Object message) { ri.debug(message); } /// <summary> /// <p> /// Set the an ApplicationAttribue, which is an Object /// set by the application which is accessable 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. /// </p> /// <p> /// Note that there is no enfocement 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. /// </p> /// </summary> /// <param name="key">object 'name' under which the object is stored</param> /// <param name="value">object to store under this key</param> public virtual void SetApplicationAttribute(Object key, Object value_Renamed) { ri.setApplicationAttribute(key, value_Renamed); } } } --- NEW FILE: FieldMethodizer.cs --- namespace NVelocity.App { using System; using System.Collections; using System.Reflection; /// <summary> /// <p>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. /// /// <p>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 /// <blockquote><pre> /// MyClass.STRING_CONSTANT /// </pre></blockquote> /// and that is the same thing we are trying to allow here. /// /// <p>So to use in your Java code, do something like this : /// <blockquote><pre> /// context.put("runtime", new FieldMethodizer( "NVelocity.Runtime.Runtime" )); /// </pre></blockquote> /// and then in your template, you can access any of your static fields in this way : /// <blockquote><pre> /// $runtime.RUNTIME_LOG_WARN_STACKTRACE /// </pre></blockquote> /// /// <p>Right now, this class only methodizes <code>public static</code> fields. It seems /// that anything else is too dangerous. This class is for convenience accessing /// 'constants'. If you have fields that aren't <code>static</code> it may be better /// to handle them by explicitly placing them into the context. /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version>$Id: FieldMethodizer.cs,v 1.3 2005/11/16 05:45:22 intesar66 Exp $</version> public class FieldMethodizer { /// <summary> /// Hold the field objects by field name /// </summary> private Hashtable fieldHash = new Hashtable(); /// <summary> /// Hold the class objects by field name /// </summary> private Hashtable classHash = new Hashtable(); /// <summary> /// Allow object to be initialized without any data. You would use /// addObject() to add data later. /// </summary> public FieldMethodizer() { } /// <summary> /// Constructor that takes as it's arg the name of the class /// to methodize. /// </summary> /// <param name="s">Name of class to methodize.</param> public FieldMethodizer(String s) { try { addObject(s); } catch (Exception e) { Console.Out.WriteLine(e); } } /// <summary> /// 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. /// </summary> /// <param name="o">object to methodize.</param> public FieldMethodizer(Object o) { try { addObject(o); } catch (Exception e) { Console.Out.WriteLine(e); } } /// <summary> /// Add the Name of the class to methodize /// </summary> public virtual void addObject(String s) { Type type = Type.GetType(s); inspect(type); } /// <summary> Add an Object to methodize /// </summary> public virtual void addObject(Object o) { inspect(o.GetType()); } /// <summary> /// Accessor method to get the fields by name. /// </summary> /// <param name="fieldName">Name of static field to retrieve</param> /// <returns>The value of the given field.</returns> public virtual Object Get(String fieldName) { try { FieldInfo f = (FieldInfo) fieldHash[fieldName]; if (f != null) return f.GetValue((Type) classHash[fieldName]); } catch (Exception e) { } return null; } /// <summary> Method that retrieves all public static fields /// in the class we are methodizing. /// </summary> private void inspect(Type clas) { FieldInfo[] fields = clas.GetFields(); for (int i = 0; i < fields.Length; i++) { /* * only if public and static */ if (fields[i].IsPublic && fields[i].IsStatic) { fieldHash[fields[i].Name] = fields[i]; classHash[fields[i].Name] = clas; } } } } } |