OptionConverter.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. #region Apache License
  2. //
  3. // Licensed to the Apache Software Foundation (ASF) under one or more
  4. // contributor license agreements. See the NOTICE file distributed with
  5. // this work for additional information regarding copyright ownership.
  6. // The ASF licenses this file to you under the Apache License, Version 2.0
  7. // (the "License"); you may not use this file except in compliance with
  8. // the License. You may obtain a copy of the License at
  9. //
  10. // http://www.apache.org/licenses/LICENSE-2.0
  11. //
  12. // Unless required by applicable law or agreed to in writing, software
  13. // distributed under the License is distributed on an "AS IS" BASIS,
  14. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. // See the License for the specific language governing permissions and
  16. // limitations under the License.
  17. //
  18. #endregion
  19. using System;
  20. using System.Collections;
  21. using System.Globalization;
  22. using System.Reflection;
  23. using System.Text;
  24. using log4net.Core;
  25. using log4net.Util.TypeConverters;
  26. namespace log4net.Util
  27. {
  28. /// <summary>
  29. /// A convenience class to convert property values to specific types.
  30. /// </summary>
  31. /// <remarks>
  32. /// <para>
  33. /// Utility functions for converting types and parsing values.
  34. /// </para>
  35. /// </remarks>
  36. /// <author>Nicko Cadell</author>
  37. /// <author>Gert Driesen</author>
  38. public sealed class OptionConverter
  39. {
  40. #region Private Instance Constructors
  41. /// <summary>
  42. /// Initializes a new instance of the <see cref="OptionConverter" /> class.
  43. /// </summary>
  44. /// <remarks>
  45. /// <para>
  46. /// Uses a private access modifier to prevent instantiation of this class.
  47. /// </para>
  48. /// </remarks>
  49. private OptionConverter()
  50. {
  51. }
  52. #endregion Private Instance Constructors
  53. #region Public Static Methods
  54. // /// <summary>
  55. // /// Concatenates two string arrays.
  56. // /// </summary>
  57. // /// <param name="l">Left array.</param>
  58. // /// <param name="r">Right array.</param>
  59. // /// <returns>Array containing both left and right arrays.</returns>
  60. // public static string[] ConcatenateArrays(string[] l, string[] r)
  61. // {
  62. // return (string[])ConcatenateArrays(l, r);
  63. // }
  64. // /// <summary>
  65. // /// Concatenates two arrays.
  66. // /// </summary>
  67. // /// <param name="l">Left array</param>
  68. // /// <param name="r">Right array</param>
  69. // /// <returns>Array containing both left and right arrays.</returns>
  70. // public static Array ConcatenateArrays(Array l, Array r)
  71. // {
  72. // if (l == null)
  73. // {
  74. // throw new ArgumentNullException("l");
  75. // }
  76. // if (r == null)
  77. // {
  78. // throw new ArgumentNullException("r");
  79. // }
  80. //
  81. // int len = l.Length + r.Length;
  82. // Array a = Array.CreateInstance(l.GetType(), len);
  83. //
  84. // Array.Copy(l, 0, a, 0, l.Length);
  85. // Array.Copy(r, 0, a, l.Length, r.Length);
  86. //
  87. // return a;
  88. // }
  89. // /// <summary>
  90. // /// Converts string escape characters back to their correct values.
  91. // /// </summary>
  92. // /// <param name="s">String to convert.</param>
  93. // /// <returns>Converted result.</returns>
  94. // public static string ConvertSpecialChars(string s)
  95. // {
  96. // if (s == null)
  97. // {
  98. // throw new ArgumentNullException("s");
  99. // }
  100. // char c;
  101. // int len = s.Length;
  102. // StringBuilder buf = new StringBuilder(len);
  103. //
  104. // int i = 0;
  105. // while(i < len)
  106. // {
  107. // c = s[i++];
  108. // if (c == '\\')
  109. // {
  110. // c = s[i++];
  111. // if (c == 'n') c = '\n';
  112. // else if (c == 'r') c = '\r';
  113. // else if (c == 't') c = '\t';
  114. // else if (c == 'f') c = '\f';
  115. // else if (c == '\b') c = '\b';
  116. // else if (c == '\"') c = '\"';
  117. // else if (c == '\'') c = '\'';
  118. // else if (c == '\\') c = '\\';
  119. // }
  120. // buf.Append(c);
  121. // }
  122. // return buf.ToString();
  123. // }
  124. /// <summary>
  125. /// Converts a string to a <see cref="bool" /> value.
  126. /// </summary>
  127. /// <param name="argValue">String to convert.</param>
  128. /// <param name="defaultValue">The default value.</param>
  129. /// <returns>The <see cref="bool" /> value of <paramref name="argValue" />.</returns>
  130. /// <remarks>
  131. /// <para>
  132. /// If <paramref name="argValue"/> is "true", then <c>true</c> is returned.
  133. /// If <paramref name="argValue"/> is "false", then <c>false</c> is returned.
  134. /// Otherwise, <paramref name="defaultValue"/> is returned.
  135. /// </para>
  136. /// </remarks>
  137. public static bool ToBoolean(string argValue, bool defaultValue)
  138. {
  139. if (argValue != null && argValue.Length > 0)
  140. {
  141. try
  142. {
  143. return bool.Parse(argValue);
  144. }
  145. catch(Exception e)
  146. {
  147. LogLog.Error(declaringType, "[" + argValue + "] is not in proper bool form.", e);
  148. }
  149. }
  150. return defaultValue;
  151. }
  152. // /// <summary>
  153. // /// Converts a string to an integer.
  154. // /// </summary>
  155. // /// <param name="argValue">String to convert.</param>
  156. // /// <param name="defaultValue">The default value.</param>
  157. // /// <returns>The <see cref="int" /> value of <paramref name="argValue" />.</returns>
  158. // /// <remarks>
  159. // /// <para>
  160. // /// <paramref name="defaultValue"/> is returned when <paramref name="argValue"/>
  161. // /// cannot be converted to a <see cref="int" /> value.
  162. // /// </para>
  163. // /// </remarks>
  164. // public static int ToInt(string argValue, int defaultValue)
  165. // {
  166. // if (argValue != null)
  167. // {
  168. // string s = argValue.Trim();
  169. // try
  170. // {
  171. // return int.Parse(s, NumberFormatInfo.InvariantInfo);
  172. // }
  173. // catch (Exception e)
  174. // {
  175. // LogLog.Error(declaringType, "OptionConverter: [" + s + "] is not in proper int form.", e);
  176. // }
  177. // }
  178. // return defaultValue;
  179. // }
  180. /// <summary>
  181. /// Parses a file size into a number.
  182. /// </summary>
  183. /// <param name="argValue">String to parse.</param>
  184. /// <param name="defaultValue">The default value.</param>
  185. /// <returns>The <see cref="long" /> value of <paramref name="argValue" />.</returns>
  186. /// <remarks>
  187. /// <para>
  188. /// Parses a file size of the form: number[KB|MB|GB] into a
  189. /// long value. It is scaled with the appropriate multiplier.
  190. /// </para>
  191. /// <para>
  192. /// <paramref name="defaultValue"/> is returned when <paramref name="argValue"/>
  193. /// cannot be converted to a <see cref="long" /> value.
  194. /// </para>
  195. /// </remarks>
  196. public static long ToFileSize(string argValue, long defaultValue)
  197. {
  198. if (argValue == null)
  199. {
  200. return defaultValue;
  201. }
  202. string s = argValue.Trim().ToUpper(CultureInfo.InvariantCulture);
  203. long multiplier = 1;
  204. int index;
  205. if ((index = s.IndexOf("KB")) != -1)
  206. {
  207. multiplier = 1024;
  208. s = s.Substring(0, index);
  209. }
  210. else if ((index = s.IndexOf("MB")) != -1)
  211. {
  212. multiplier = 1024 * 1024;
  213. s = s.Substring(0, index);
  214. }
  215. else if ((index = s.IndexOf("GB")) != -1)
  216. {
  217. multiplier = 1024 * 1024 * 1024;
  218. s = s.Substring(0, index);
  219. }
  220. if (s != null)
  221. {
  222. // Try again to remove whitespace between the number and the size specifier
  223. s = s.Trim();
  224. long longVal;
  225. if (SystemInfo.TryParse(s, out longVal))
  226. {
  227. return longVal * multiplier;
  228. }
  229. else
  230. {
  231. LogLog.Error(declaringType, "OptionConverter: ["+ s +"] is not in the correct file size syntax.");
  232. }
  233. }
  234. return defaultValue;
  235. }
  236. /// <summary>
  237. /// Converts a string to an object.
  238. /// </summary>
  239. /// <param name="target">The target type to convert to.</param>
  240. /// <param name="txt">The string to convert to an object.</param>
  241. /// <returns>
  242. /// The object converted from a string or <c>null</c> when the
  243. /// conversion failed.
  244. /// </returns>
  245. /// <remarks>
  246. /// <para>
  247. /// Converts a string to an object. Uses the converter registry to try
  248. /// to convert the string value into the specified target type.
  249. /// </para>
  250. /// </remarks>
  251. public static object ConvertStringTo(Type target, string txt)
  252. {
  253. if (target == null)
  254. {
  255. throw new ArgumentNullException("target");
  256. }
  257. // If we want a string we already have the correct type
  258. if (typeof(string) == target || typeof(object) == target)
  259. {
  260. return txt;
  261. }
  262. // First lets try to find a type converter
  263. IConvertFrom typeConverter = ConverterRegistry.GetConvertFrom(target);
  264. if (typeConverter != null && typeConverter.CanConvertFrom(typeof(string)))
  265. {
  266. // Found appropriate converter
  267. return typeConverter.ConvertFrom(txt);
  268. }
  269. else
  270. {
  271. #if NETSTANDARD1_3
  272. if (target.GetTypeInfo().IsEnum)
  273. #else
  274. if (target.IsEnum)
  275. #endif
  276. {
  277. // Target type is an enum.
  278. // Use the Enum.Parse(EnumType, string) method to get the enum value
  279. return ParseEnum(target, txt, true);
  280. }
  281. else
  282. {
  283. // We essentially make a guess that to convert from a string
  284. // to an arbitrary type T there will be a static method defined on type T called Parse
  285. // that will take an argument of type string. i.e. T.Parse(string)->T we call this
  286. // method to convert the string to the type required by the property.
  287. System.Reflection.MethodInfo meth = target.GetMethod("Parse", new Type[] {typeof(string)});
  288. if (meth != null)
  289. {
  290. // Call the Parse method
  291. #if NETSTANDARD1_3
  292. return meth.Invoke(target, new[] { txt });
  293. #else
  294. return meth.Invoke(null, BindingFlags.InvokeMethod, null, new object[] {txt}, CultureInfo.InvariantCulture);
  295. #endif
  296. }
  297. else
  298. {
  299. // No Parse() method found.
  300. }
  301. }
  302. }
  303. return null;
  304. }
  305. // /// <summary>
  306. // /// Looks up the <see cref="IConvertFrom"/> for the target type.
  307. // /// </summary>
  308. // /// <param name="target">The type to lookup the converter for.</param>
  309. // /// <returns>The converter for the specified type.</returns>
  310. // public static IConvertFrom GetTypeConverter(Type target)
  311. // {
  312. // IConvertFrom converter = ConverterRegistry.GetConverter(target);
  313. // if (converter == null)
  314. // {
  315. // throw new InvalidOperationException("No type converter defined for [" + target + "]");
  316. // }
  317. // return converter;
  318. // }
  319. /// <summary>
  320. /// Checks if there is an appropriate type conversion from the source type to the target type.
  321. /// </summary>
  322. /// <param name="sourceType">The type to convert from.</param>
  323. /// <param name="targetType">The type to convert to.</param>
  324. /// <returns><c>true</c> if there is a conversion from the source type to the target type.</returns>
  325. /// <remarks>
  326. /// Checks if there is an appropriate type conversion from the source type to the target type.
  327. /// <para>
  328. /// </para>
  329. /// </remarks>
  330. public static bool CanConvertTypeTo(Type sourceType, Type targetType)
  331. {
  332. if (sourceType == null || targetType == null)
  333. {
  334. return false;
  335. }
  336. // Check if we can assign directly from the source type to the target type
  337. if (targetType.IsAssignableFrom(sourceType))
  338. {
  339. return true;
  340. }
  341. // Look for a To converter
  342. IConvertTo tcSource = ConverterRegistry.GetConvertTo(sourceType, targetType);
  343. if (tcSource != null)
  344. {
  345. if (tcSource.CanConvertTo(targetType))
  346. {
  347. return true;
  348. }
  349. }
  350. // Look for a From converter
  351. IConvertFrom tcTarget = ConverterRegistry.GetConvertFrom(targetType);
  352. if (tcTarget != null)
  353. {
  354. if (tcTarget.CanConvertFrom(sourceType))
  355. {
  356. return true;
  357. }
  358. }
  359. return false;
  360. }
  361. /// <summary>
  362. /// Converts an object to the target type.
  363. /// </summary>
  364. /// <param name="sourceInstance">The object to convert to the target type.</param>
  365. /// <param name="targetType">The type to convert to.</param>
  366. /// <returns>The converted object.</returns>
  367. /// <remarks>
  368. /// <para>
  369. /// Converts an object to the target type.
  370. /// </para>
  371. /// </remarks>
  372. public static object ConvertTypeTo(object sourceInstance, Type targetType)
  373. {
  374. Type sourceType = sourceInstance.GetType();
  375. // Check if we can assign directly from the source type to the target type
  376. if (targetType.IsAssignableFrom(sourceType))
  377. {
  378. return sourceInstance;
  379. }
  380. // Look for a TO converter
  381. IConvertTo tcSource = ConverterRegistry.GetConvertTo(sourceType, targetType);
  382. if (tcSource != null)
  383. {
  384. if (tcSource.CanConvertTo(targetType))
  385. {
  386. return tcSource.ConvertTo(sourceInstance, targetType);
  387. }
  388. }
  389. // Look for a FROM converter
  390. IConvertFrom tcTarget = ConverterRegistry.GetConvertFrom(targetType);
  391. if (tcTarget != null)
  392. {
  393. if (tcTarget.CanConvertFrom(sourceType))
  394. {
  395. return tcTarget.ConvertFrom(sourceInstance);
  396. }
  397. }
  398. throw new ArgumentException("Cannot convert source object [" + sourceInstance.ToString() + "] to target type [" + targetType.Name + "]", "sourceInstance");
  399. }
  400. // /// <summary>
  401. // /// Finds the value corresponding to <paramref name="key"/> in
  402. // /// <paramref name="props"/> and then perform variable substitution
  403. // /// on the found value.
  404. // /// </summary>
  405. // /// <param name="key">The key to lookup.</param>
  406. // /// <param name="props">The association to use for lookups.</param>
  407. // /// <returns>The substituted result.</returns>
  408. // public static string FindAndSubst(string key, System.Collections.IDictionary props)
  409. // {
  410. // if (props == null)
  411. // {
  412. // throw new ArgumentNullException("props");
  413. // }
  414. //
  415. // string v = props[key] as string;
  416. // if (v == null)
  417. // {
  418. // return null;
  419. // }
  420. //
  421. // try
  422. // {
  423. // return SubstituteVariables(v, props);
  424. // }
  425. // catch(Exception e)
  426. // {
  427. // LogLog.Error(declaringType, "OptionConverter: Bad option value [" + v + "].", e);
  428. // return v;
  429. // }
  430. // }
  431. /// <summary>
  432. /// Instantiates an object given a class name.
  433. /// </summary>
  434. /// <param name="className">The fully qualified class name of the object to instantiate.</param>
  435. /// <param name="superClass">The class to which the new object should belong.</param>
  436. /// <param name="defaultValue">The object to return in case of non-fulfillment.</param>
  437. /// <returns>
  438. /// An instance of the <paramref name="className"/> or <paramref name="defaultValue"/>
  439. /// if the object could not be instantiated.
  440. /// </returns>
  441. /// <remarks>
  442. /// <para>
  443. /// Checks that the <paramref name="className"/> is a subclass of
  444. /// <paramref name="superClass"/>. If that test fails or the object could
  445. /// not be instantiated, then <paramref name="defaultValue"/> is returned.
  446. /// </para>
  447. /// </remarks>
  448. public static object InstantiateByClassName(string className, Type superClass, object defaultValue)
  449. {
  450. if (className != null)
  451. {
  452. try
  453. {
  454. #if NETSTANDARD1_3
  455. Type classObj = SystemInfo.GetTypeFromString(superClass.GetTypeInfo().Assembly, className, true, true);
  456. #else
  457. Type classObj = SystemInfo.GetTypeFromString(className, true, true);
  458. #endif
  459. if (!superClass.IsAssignableFrom(classObj))
  460. {
  461. LogLog.Error(declaringType, "OptionConverter: A [" + className + "] object is not assignable to a [" + superClass.FullName + "] variable.");
  462. return defaultValue;
  463. }
  464. return Activator.CreateInstance(classObj);
  465. }
  466. catch (Exception e)
  467. {
  468. LogLog.Error(declaringType, "Could not instantiate class [" + className + "].", e);
  469. }
  470. }
  471. return defaultValue;
  472. }
  473. /// <summary>
  474. /// Performs variable substitution in string <paramref name="value"/> from the
  475. /// values of keys found in <paramref name="props"/>.
  476. /// </summary>
  477. /// <param name="value">The string on which variable substitution is performed.</param>
  478. /// <param name="props">The dictionary to use to lookup variables.</param>
  479. /// <returns>The result of the substitutions.</returns>
  480. /// <remarks>
  481. /// <para>
  482. /// The variable substitution delimiters are <b>${</b> and <b>}</b>.
  483. /// </para>
  484. /// <para>
  485. /// For example, if props contains <c>key=value</c>, then the call
  486. /// </para>
  487. /// <para>
  488. /// <code lang="C#">
  489. /// string s = OptionConverter.SubstituteVariables("Value of key is ${key}.");
  490. /// </code>
  491. /// </para>
  492. /// <para>
  493. /// will set the variable <c>s</c> to "Value of key is value.".
  494. /// </para>
  495. /// <para>
  496. /// If no value could be found for the specified key, then substitution
  497. /// defaults to an empty string.
  498. /// </para>
  499. /// <para>
  500. /// For example, if system properties contains no value for the key
  501. /// "nonExistentKey", then the call
  502. /// </para>
  503. /// <para>
  504. /// <code lang="C#">
  505. /// string s = OptionConverter.SubstituteVariables("Value of nonExistentKey is [${nonExistentKey}]");
  506. /// </code>
  507. /// </para>
  508. /// <para>
  509. /// will set <s>s</s> to "Value of nonExistentKey is []".
  510. /// </para>
  511. /// <para>
  512. /// An Exception is thrown if <paramref name="value"/> contains a start
  513. /// delimiter "${" which is not balanced by a stop delimiter "}".
  514. /// </para>
  515. /// </remarks>
  516. public static string SubstituteVariables(string value, System.Collections.IDictionary props)
  517. {
  518. StringBuilder buf = new StringBuilder();
  519. int i = 0;
  520. int j, k;
  521. while(true)
  522. {
  523. j = value.IndexOf(DELIM_START, i);
  524. if (j == -1)
  525. {
  526. if (i == 0)
  527. {
  528. return value;
  529. }
  530. else
  531. {
  532. buf.Append(value.Substring(i, value.Length - i));
  533. return buf.ToString();
  534. }
  535. }
  536. else
  537. {
  538. buf.Append(value.Substring(i, j - i));
  539. k = value.IndexOf(DELIM_STOP, j);
  540. if (k == -1)
  541. {
  542. throw new LogException("[" + value + "] has no closing brace. Opening brace at position [" + j + "]");
  543. }
  544. else
  545. {
  546. j += DELIM_START_LEN;
  547. string key = value.Substring(j, k - j);
  548. string replacement = props[key] as string;
  549. if (replacement != null)
  550. {
  551. buf.Append(replacement);
  552. }
  553. i = k + DELIM_STOP_LEN;
  554. }
  555. }
  556. }
  557. }
  558. #endregion Public Static Methods
  559. #region Private Static Methods
  560. /// <summary>
  561. /// Converts the string representation of the name or numeric value of one or
  562. /// more enumerated constants to an equivalent enumerated object.
  563. /// </summary>
  564. /// <param name="enumType">The type to convert to.</param>
  565. /// <param name="value">The enum string value.</param>
  566. /// <param name="ignoreCase">If <c>true</c>, ignore case; otherwise, regard case.</param>
  567. /// <returns>An object of type <paramref name="enumType" /> whose value is represented by <paramref name="value" />.</returns>
  568. private static object ParseEnum(System.Type enumType, string value, bool ignoreCase)
  569. {
  570. #if !NETCF
  571. return Enum.Parse(enumType, value, ignoreCase);
  572. #else
  573. FieldInfo[] fields = enumType.GetFields(BindingFlags.Public | BindingFlags.Static);
  574. string[] names = value.Split(new char[] {','});
  575. for (int i = 0; i < names.Length; ++i)
  576. {
  577. names[i] = names [i].Trim();
  578. }
  579. long retVal = 0;
  580. try
  581. {
  582. // Attempt to convert to numeric type
  583. return Enum.ToObject(enumType, Convert.ChangeType(value, typeof(long), CultureInfo.InvariantCulture));
  584. }
  585. catch {}
  586. foreach (string name in names)
  587. {
  588. bool found = false;
  589. foreach(FieldInfo field in fields)
  590. {
  591. if (String.Compare(name, field.Name, ignoreCase) == 0)
  592. {
  593. retVal |= ((IConvertible) field.GetValue(null)).ToInt64(CultureInfo.InvariantCulture);
  594. found = true;
  595. break;
  596. }
  597. }
  598. if (!found)
  599. {
  600. throw new ArgumentException("Failed to lookup member [" + name + "] from Enum type [" + enumType.Name + "]");
  601. }
  602. }
  603. return Enum.ToObject(enumType, retVal);
  604. #endif
  605. }
  606. #endregion Private Static Methods
  607. #region Private Static Fields
  608. /// <summary>
  609. /// The fully qualified type of the OptionConverter class.
  610. /// </summary>
  611. /// <remarks>
  612. /// Used by the internal logger to record the Type of the
  613. /// log message.
  614. /// </remarks>
  615. private readonly static Type declaringType = typeof(OptionConverter);
  616. private const string DELIM_START = "${";
  617. private const char DELIM_STOP = '}';
  618. private const int DELIM_START_LEN = 2;
  619. private const int DELIM_STOP_LEN = 1;
  620. #endregion Private Static Fields
  621. }
  622. }