1
#region Copyright & License
3
// Copyright 2001-2005 The Apache Software Foundation
5
// Licensed under the Apache License, Version 2.0 (the "License");
6
// you may not use this file except in compliance with the License.
7
// You may obtain a copy of the License at
9
// http://www.apache.org/licenses/LICENSE-2.0
11
// Unless required by applicable law or agreed to in writing, software
12
// distributed under the License is distributed on an "AS IS" BASIS,
13
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
// See the License for the specific language governing permissions and
15
// limitations under the License.
20
using System.Collections;
21
using System.Globalization;
22
using System.Reflection;
26
using log4net.Util.TypeConverters;
28
namespace log4net.Util
31
/// A convenience class to convert property values to specific types.
35
/// Utility functions for converting types and parsing values.
38
/// <author>Nicko Cadell</author>
39
/// <author>Gert Driesen</author>
40
public sealed class OptionConverter
42
#region Private Instance Constructors
45
/// Initializes a new instance of the <see cref="OptionConverter" /> class.
49
/// Uses a private access modifier to prevent instantiation of this class.
52
private OptionConverter()
56
#endregion Private Instance Constructors
58
#region Public Static Methods
61
// /// Concatenates two string arrays.
63
// /// <param name="l">Left array.</param>
64
// /// <param name="r">Right array.</param>
65
// /// <returns>Array containing both left and right arrays.</returns>
66
// public static string[] ConcatenateArrays(string[] l, string[] r)
68
// return (string[])ConcatenateArrays(l, r);
72
// /// Concatenates two arrays.
74
// /// <param name="l">Left array</param>
75
// /// <param name="r">Right array</param>
76
// /// <returns>Array containing both left and right arrays.</returns>
77
// public static Array ConcatenateArrays(Array l, Array r)
81
// throw new ArgumentNullException("l");
85
// throw new ArgumentNullException("r");
88
// int len = l.Length + r.Length;
89
// Array a = Array.CreateInstance(l.GetType(), len);
91
// Array.Copy(l, 0, a, 0, l.Length);
92
// Array.Copy(r, 0, a, l.Length, r.Length);
98
// /// Converts string escape characters back to their correct values.
100
// /// <param name="s">String to convert.</param>
101
// /// <returns>Converted result.</returns>
102
// public static string ConvertSpecialChars(string s)
106
// throw new ArgumentNullException("s");
109
// int len = s.Length;
110
// StringBuilder buf = new StringBuilder(len);
119
// if (c == 'n') c = '\n';
120
// else if (c == 'r') c = '\r';
121
// else if (c == 't') c = '\t';
122
// else if (c == 'f') c = '\f';
123
// else if (c == '\b') c = '\b';
124
// else if (c == '\"') c = '\"';
125
// else if (c == '\'') c = '\'';
126
// else if (c == '\\') c = '\\';
130
// return buf.ToString();
134
/// Converts a string to a <see cref="bool" /> value.
136
/// <param name="argValue">String to convert.</param>
137
/// <param name="defaultValue">The default value.</param>
138
/// <returns>The <see cref="bool" /> value of <paramref name="argValue" />.</returns>
141
/// If <paramref name="argValue"/> is "true", then <c>true</c> is returned.
142
/// If <paramref name="argValue"/> is "false", then <c>false</c> is returned.
143
/// Otherwise, <paramref name="defaultValue"/> is returned.
146
public static bool ToBoolean(string argValue, bool defaultValue)
148
if (argValue != null && argValue.Length > 0)
152
return bool.Parse(argValue);
156
LogLog.Error("OptionConverter: [" + argValue + "] is not in proper bool form.", e);
163
// /// Converts a string to an integer.
165
// /// <param name="argValue">String to convert.</param>
166
// /// <param name="defaultValue">The default value.</param>
167
// /// <returns>The <see cref="int" /> value of <paramref name="argValue" />.</returns>
170
// /// <paramref name="defaultValue"/> is returned when <paramref name="argValue"/>
171
// /// cannot be converted to a <see cref="int" /> value.
174
// public static int ToInt(string argValue, int defaultValue)
176
// if (argValue != null)
178
// string s = argValue.Trim();
181
// return int.Parse(s, NumberFormatInfo.InvariantInfo);
183
// catch (Exception e)
185
// LogLog.Error("OptionConverter: [" + s + "] is not in proper int form.", e);
188
// return defaultValue;
192
/// Parses a file size into a number.
194
/// <param name="argValue">String to parse.</param>
195
/// <param name="defaultValue">The default value.</param>
196
/// <returns>The <see cref="long" /> value of <paramref name="argValue" />.</returns>
199
/// Parses a file size of the form: number[KB|MB|GB] into a
200
/// long value. It is scaled with the appropriate multiplier.
203
/// <paramref name="defaultValue"/> is returned when <paramref name="argValue"/>
204
/// cannot be converted to a <see cref="long" /> value.
207
public static long ToFileSize(string argValue, long defaultValue)
209
if (argValue == null)
214
string s = argValue.Trim().ToUpper(CultureInfo.InvariantCulture);
218
if ((index = s.IndexOf("KB")) != -1)
221
s = s.Substring(0, index);
223
else if ((index = s.IndexOf("MB")) != -1)
225
multiplier = 1024 * 1024;
226
s = s.Substring(0, index);
228
else if ((index = s.IndexOf("GB")) != -1)
230
multiplier = 1024 * 1024 * 1024;
231
s = s.Substring(0, index);
235
// Try again to remove whitespace between the number and the size specifier
239
if (SystemInfo.TryParse(s, out longVal))
241
return longVal * multiplier;
245
LogLog.Error("OptionConverter: ["+ s +"] is not in the correct file size syntax.");
252
/// Converts a string to an object.
254
/// <param name="target">The target type to convert to.</param>
255
/// <param name="txt">The string to convert to an object.</param>
257
/// The object converted from a string or <c>null</c> when the
258
/// conversion failed.
262
/// Converts a string to an object. Uses the converter registry to try
263
/// to convert the string value into the specified target type.
266
public static object ConvertStringTo(Type target, string txt)
270
throw new ArgumentNullException("target");
273
// If we want a string we already have the correct type
274
if (typeof(string) == target || typeof(object) == target)
279
// First lets try to find a type converter
280
IConvertFrom typeConverter = ConverterRegistry.GetConvertFrom(target);
281
if (typeConverter != null && typeConverter.CanConvertFrom(typeof(string)))
283
// Found appropriate converter
284
return typeConverter.ConvertFrom(txt);
290
// Target type is an enum.
292
// Use the Enum.Parse(EnumType, string) method to get the enum value
293
return ParseEnum(target, txt, true);
297
// We essentially make a guess that to convert from a string
298
// to an arbitrary type T there will be a static method defined on type T called Parse
299
// that will take an argument of type string. i.e. T.Parse(string)->T we call this
300
// method to convert the string to the type required by the property.
301
System.Reflection.MethodInfo meth = target.GetMethod("Parse", new Type[] {typeof(string)});
304
// Call the Parse method
305
return meth.Invoke(null, BindingFlags.InvokeMethod, null, new object[] {txt}, CultureInfo.InvariantCulture);
309
// No Parse() method found.
317
// /// Looks up the <see cref="IConvertFrom"/> for the target type.
319
// /// <param name="target">The type to lookup the converter for.</param>
320
// /// <returns>The converter for the specified type.</returns>
321
// public static IConvertFrom GetTypeConverter(Type target)
323
// IConvertFrom converter = ConverterRegistry.GetConverter(target);
324
// if (converter == null)
326
// throw new InvalidOperationException("No type converter defined for [" + target + "]");
332
/// Checks if there is an appropriate type conversion from the source type to the target type.
334
/// <param name="sourceType">The type to convert from.</param>
335
/// <param name="targetType">The type to convert to.</param>
336
/// <returns><c>true</c> if there is a conversion from the source type to the target type.</returns>
338
/// Checks if there is an appropriate type conversion from the source type to the target type.
342
public static bool CanConvertTypeTo(Type sourceType, Type targetType)
344
if (sourceType == null || targetType == null)
349
// Check if we can assign directly from the source type to the target type
350
if (targetType.IsAssignableFrom(sourceType))
355
// Look for a To converter
356
IConvertTo tcSource = ConverterRegistry.GetConvertTo(sourceType, targetType);
357
if (tcSource != null)
359
if (tcSource.CanConvertTo(targetType))
365
// Look for a From converter
366
IConvertFrom tcTarget = ConverterRegistry.GetConvertFrom(targetType);
367
if (tcTarget != null)
369
if (tcTarget.CanConvertFrom(sourceType))
379
/// Converts an object to the target type.
381
/// <param name="sourceInstance">The object to convert to the target type.</param>
382
/// <param name="targetType">The type to convert to.</param>
383
/// <returns>The converted object.</returns>
386
/// Converts an object to the target type.
389
public static object ConvertTypeTo(object sourceInstance, Type targetType)
391
Type sourceType = sourceInstance.GetType();
393
// Check if we can assign directly from the source type to the target type
394
if (targetType.IsAssignableFrom(sourceType))
396
return sourceInstance;
399
// Look for a TO converter
400
IConvertTo tcSource = ConverterRegistry.GetConvertTo(sourceType, targetType);
401
if (tcSource != null)
403
if (tcSource.CanConvertTo(targetType))
405
return tcSource.ConvertTo(sourceInstance, targetType);
409
// Look for a FROM converter
410
IConvertFrom tcTarget = ConverterRegistry.GetConvertFrom(targetType);
411
if (tcTarget != null)
413
if (tcTarget.CanConvertFrom(sourceType))
415
return tcTarget.ConvertFrom(sourceInstance);
419
throw new ArgumentException("Cannot convert source object [" + sourceInstance.ToString() + "] to target type [" + targetType.Name + "]", "sourceInstance");
423
// /// Finds the value corresponding to <paramref name="key"/> in
424
// /// <paramref name="props"/> and then perform variable substitution
425
// /// on the found value.
427
// /// <param name="key">The key to lookup.</param>
428
// /// <param name="props">The association to use for lookups.</param>
429
// /// <returns>The substituted result.</returns>
430
// public static string FindAndSubst(string key, System.Collections.IDictionary props)
432
// if (props == null)
434
// throw new ArgumentNullException("props");
437
// string v = props[key] as string;
445
// return SubstituteVariables(v, props);
447
// catch(Exception e)
449
// LogLog.Error("OptionConverter: Bad option value [" + v + "].", e);
455
/// Instantiates an object given a class name.
457
/// <param name="className">The fully qualified class name of the object to instantiate.</param>
458
/// <param name="superClass">The class to which the new object should belong.</param>
459
/// <param name="defaultValue">The object to return in case of non-fulfillment.</param>
461
/// An instance of the <paramref name="className"/> or <paramref name="defaultValue"/>
462
/// if the object could not be instantiated.
466
/// Checks that the <paramref name="className"/> is a subclass of
467
/// <paramref name="superClass"/>. If that test fails or the object could
468
/// not be instantiated, then <paramref name="defaultValue"/> is returned.
471
public static object InstantiateByClassName(string className, Type superClass, object defaultValue)
473
if (className != null)
477
Type classObj = SystemInfo.GetTypeFromString(className, true, true);
478
if (!superClass.IsAssignableFrom(classObj))
480
LogLog.Error("OptionConverter: A [" + className + "] object is not assignable to a [" + superClass.FullName + "] variable.");
483
return Activator.CreateInstance(classObj);
487
LogLog.Error("OptionConverter: Could not instantiate class [" + className + "].", e);
494
/// Performs variable substitution in string <paramref name="val"/> from the
495
/// values of keys found in <paramref name="props"/>.
497
/// <param name="value">The string on which variable substitution is performed.</param>
498
/// <param name="props">The dictionary to use to lookup variables.</param>
499
/// <returns>The result of the substitutions.</returns>
502
/// The variable substitution delimiters are <b>${</b> and <b>}</b>.
505
/// For example, if props contains <c>key=value</c>, then the call
509
/// string s = OptionConverter.SubstituteVariables("Value of key is ${key}.");
513
/// will set the variable <c>s</c> to "Value of key is value.".
516
/// If no value could be found for the specified key, then substitution
517
/// defaults to an empty string.
520
/// For example, if system properties contains no value for the key
521
/// "nonExistentKey", then the call
525
/// string s = OptionConverter.SubstituteVariables("Value of nonExistentKey is [${nonExistentKey}]");
529
/// will set <s>s</s> to "Value of nonExistentKey is []".
532
/// An Exception is thrown if <paramref name="value"/> contains a start
533
/// delimiter "${" which is not balanced by a stop delimiter "}".
536
public static string SubstituteVariables(string value, System.Collections.IDictionary props)
538
StringBuilder buf = new StringBuilder();
545
j = value.IndexOf(DELIM_START, i);
554
buf.Append(value.Substring(i, value.Length - i));
555
return buf.ToString();
560
buf.Append(value.Substring(i, j - i));
561
k = value.IndexOf(DELIM_STOP, j);
564
throw new LogException("[" + value + "] has no closing brace. Opening brace at position [" + j + "]");
568
j += DELIM_START_LEN;
569
string key = value.Substring(j, k - j);
571
string replacement = props[key] as string;
573
if (replacement != null)
575
buf.Append(replacement);
577
i = k + DELIM_STOP_LEN;
583
#endregion Public Static Methods
585
#region Private Static Methods
588
/// Converts the string representation of the name or numeric value of one or
589
/// more enumerated constants to an equivalent enumerated object.
591
/// <param name="enumType">The type to convert to.</param>
592
/// <param name="value">The enum string value.</param>
593
/// <param name="ignoreCase">If <c>true</c>, ignore case; otherwise, regard case.</param>
594
/// <returns>An object of type <paramref name="enumType" /> whose value is represented by <paramref name="value" />.</returns>
595
private static object ParseEnum(System.Type enumType, string value, bool ignoreCase)
598
return Enum.Parse(enumType, value, ignoreCase);
600
FieldInfo[] fields = enumType.GetFields(BindingFlags.Public | BindingFlags.Static);
602
string[] names = value.Split(new char[] {','});
603
for (int i = 0; i < names.Length; ++i)
605
names[i] = names [i].Trim();
612
// Attempt to convert to numeric type
613
return Enum.ToObject(enumType, Convert.ChangeType(value, typeof(long), CultureInfo.InvariantCulture));
617
foreach (string name in names)
620
foreach(FieldInfo field in fields)
622
if (String.Compare(name, field.Name, ignoreCase) == 0)
624
retVal |= ((IConvertible) field.GetValue(null)).ToInt64(CultureInfo.InvariantCulture);
631
throw new ArgumentException("Failed to lookup member [" + name + "] from Enum type [" + enumType.Name + "]");
634
return Enum.ToObject(enumType, retVal);
638
#endregion Private Static Methods
640
#region Private Static Fields
642
private const string DELIM_START = "${";
643
private const char DELIM_STOP = '}';
644
private const int DELIM_START_LEN = 2;
645
private const int DELIM_STOP_LEN = 1;
647
#endregion Private Static Fields