UriTemplate.cs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. //
  2. // UriTemplate.cs
  3. //
  4. // Author:
  5. // Atsushi Enomoto <[email protected]>
  6. //
  7. // Copyright (C) 2008 Novell, Inc (http://www.novell.com)
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining
  10. // a copy of this software and associated documentation files (the
  11. // "Software"), to deal in the Software without restriction, including
  12. // without limitation the rights to use, copy, modify, merge, publish,
  13. // distribute, sublicense, and/or sell copies of the Software, and to
  14. // permit persons to whom the Software is furnished to do so, subject to
  15. // the following conditions:
  16. //
  17. // The above copyright notice and this permission notice shall be
  18. // included in all copies or substantial portions of the Software.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  21. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  23. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  24. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  25. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  26. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  27. //
  28. using System;
  29. using System.Collections.Generic;
  30. using System.Collections.ObjectModel;
  31. using System.Collections.Specialized;
  32. using System.Globalization;
  33. using System.Text;
  34. namespace System
  35. {
  36. public class UriTemplate
  37. {
  38. static readonly ReadOnlyCollection<string> empty_strings = new ReadOnlyCollection<string> (new string [0]);
  39. string template;
  40. ReadOnlyCollection<string> path, query;
  41. Dictionary<string,string> query_params = new Dictionary<string,string> ();
  42. [MonoTODO ("It needs some rewrite: template bindings should be available only one per segment")]
  43. public UriTemplate (string template)
  44. {
  45. if (template == null)
  46. throw new ArgumentNullException ("template");
  47. this.template = template;
  48. string p = template;
  49. // Trim scheme, host name and port if exist.
  50. if (CultureInfo.InvariantCulture.CompareInfo.IsPrefix (template, "http")) {
  51. int idx = template.IndexOf ('/', 8); // after "http://x" or "https://"
  52. if (idx > 0)
  53. p = template.Substring (idx);
  54. }
  55. int q = p.IndexOf ('?');
  56. path = ParsePathTemplate (p, 0, q >= 0 ? q : p.Length);
  57. if (q >= 0)
  58. ParseQueryTemplate (p, q, p.Length);
  59. else
  60. query = empty_strings;
  61. }
  62. public ReadOnlyCollection<string> PathSegmentVariableNames {
  63. get { return path; }
  64. }
  65. public ReadOnlyCollection<string> QueryValueVariableNames {
  66. get { return query; }
  67. }
  68. public override string ToString ()
  69. {
  70. return template;
  71. }
  72. // Bind
  73. public Uri BindByName (Uri baseAddress, NameValueCollection parameters)
  74. {
  75. CheckBaseAddress (baseAddress);
  76. int src = 0;
  77. StringBuilder sb = new StringBuilder (template.Length);
  78. BindByName (ref src, sb, path, parameters);
  79. BindByName (ref src, sb, query, parameters);
  80. sb.Append (template.Substring (src));
  81. return new Uri (baseAddress.ToString () + sb.ToString ());
  82. }
  83. void BindByName (ref int src, StringBuilder sb, ReadOnlyCollection<string> names, NameValueCollection parameters)
  84. {
  85. foreach (string name in names) {
  86. int s = template.IndexOf ('{', src);
  87. int e = template.IndexOf ('}', s + 1);
  88. sb.Append (template.Substring (src, s - src));
  89. string value = parameters [name];
  90. if (value == null)
  91. throw new FormatException (String.Format ("The argument name value collection does not contain value for '{0}'", name));
  92. sb.Append (value);
  93. src = e + 1;
  94. }
  95. }
  96. public Uri BindByPosition (Uri baseAddress, params string [] values)
  97. {
  98. CheckBaseAddress (baseAddress);
  99. if (values.Length != path.Count + query.Count)
  100. throw new FormatException (String.Format ("Template '{0}' contains {1} parameters but the argument values to bind are {2}", template, path.Count + query.Count, values.Length));
  101. int src = 0, index = 0;
  102. StringBuilder sb = new StringBuilder (template.Length);
  103. BindByPosition (ref src, sb, path, values, ref index);
  104. BindByPosition (ref src, sb, query, values, ref index);
  105. sb.Append (template.Substring (src));
  106. return new Uri (baseAddress.ToString () + sb.ToString ());
  107. }
  108. void BindByPosition (ref int src, StringBuilder sb, ReadOnlyCollection<string> names, string [] values, ref int index)
  109. {
  110. for (int i = 0; i < names.Count; i++) {
  111. int s = template.IndexOf ('{', src);
  112. int e = template.IndexOf ('}', s + 1);
  113. sb.Append (template.Substring (src, s - src));
  114. string value = values [index++];
  115. if (value == null)
  116. throw new FormatException (String.Format ("The argument value collection contains null at {0}", index - 1));
  117. sb.Append (value);
  118. src = e + 1;
  119. }
  120. }
  121. // Compare
  122. [MonoTODO]
  123. public bool IsEquivalentTo (UriTemplate other)
  124. {
  125. if (other == null)
  126. throw new ArgumentNullException ("other");
  127. return new UriTemplateEquivalenceComparer ().Equals (this, other);
  128. }
  129. // Match
  130. public UriTemplateMatch Match (Uri baseAddress, Uri candidate)
  131. {
  132. CheckBaseAddress (baseAddress);
  133. if (candidate == null)
  134. throw new ArgumentNullException ("candidate");
  135. if (!baseAddress.AbsoluteUri.EndsWith ("/"))
  136. baseAddress = new Uri (baseAddress.AbsoluteUri + "/");
  137. if (Uri.Compare (baseAddress, candidate, UriComponents.StrongAuthority, UriFormat.SafeUnescaped, StringComparison.Ordinal) != 0)
  138. return null;
  139. int i = 0, c = 0;
  140. UriTemplateMatch m = new UriTemplateMatch ();
  141. m.BaseUri = baseAddress;
  142. m.Template = this;
  143. m.RequestUri = candidate;
  144. var vc = m.BoundVariables;
  145. string cp = baseAddress.MakeRelativeUri(candidate).ToString();
  146. int tEndCp = cp.IndexOf ('?');
  147. if (tEndCp >= 0)
  148. cp = cp.Substring (0, tEndCp);
  149. if (template.Length > 0 && template [0] == '/')
  150. i++;
  151. if (cp.Length > 0 && cp [0] == '/')
  152. c++;
  153. foreach (string name in path) {
  154. int n = StringIndexOf (template, '{' + name + '}', i);
  155. if (String.CompareOrdinal (cp, c, template, i, n - i) != 0)
  156. return null; // doesn't match before current template part.
  157. c += n - i;
  158. i = n + 2 + name.Length;
  159. int ce = cp.IndexOf ('/', c);
  160. if (ce < 0)
  161. ce = cp.Length;
  162. string value = cp.Substring (c, ce - c);
  163. vc [name] = value;
  164. m.RelativePathSegments.Add (value);
  165. c += value.Length;
  166. }
  167. int tEnd = template.IndexOf ('?');
  168. if (tEnd < 0)
  169. tEnd = template.Length;
  170. if ((cp.Length - c) != (tEnd - i) ||
  171. String.CompareOrdinal (cp, c, template, i, tEnd - i) != 0)
  172. return null; // suffix doesn't match
  173. if (candidate.Query.Length == 0)
  174. return m;
  175. string [] parameters = candidate.Query.Substring (1).Split ('&'); // chop first '?'
  176. foreach (string parameter in parameters) {
  177. string [] pair = parameter.Split ('=');
  178. m.QueryParameters.Add (pair [0], pair [1]);
  179. if (!query_params.ContainsKey (pair [0]))
  180. continue;
  181. string templateName = query_params [pair [0]];
  182. vc.Add (templateName, pair [1]);
  183. }
  184. return m;
  185. }
  186. int StringIndexOf (string s, string pattern, int idx)
  187. {
  188. return CultureInfo.InvariantCulture.CompareInfo.IndexOf (s, pattern, idx, CompareOptions.OrdinalIgnoreCase);
  189. }
  190. // Helpers
  191. void CheckBaseAddress (Uri baseAddress)
  192. {
  193. if (baseAddress == null)
  194. throw new ArgumentNullException ("baseAddress");
  195. if (!baseAddress.IsAbsoluteUri)
  196. throw new ArgumentException ("baseAddress must be an absolute URI.");
  197. if (baseAddress.Scheme == Uri.UriSchemeHttp ||
  198. baseAddress.Scheme == Uri.UriSchemeHttps)
  199. return;
  200. throw new ArgumentException ("baseAddress scheme must be either http or https.");
  201. }
  202. ReadOnlyCollection<string> ParsePathTemplate (string template, int index, int end)
  203. {
  204. List<string> list = null;
  205. for (int i = index; i <= end; ) {
  206. i = template.IndexOf ('{', i);
  207. if (i < 0 || i > end)
  208. break;
  209. int e = template.IndexOf ('}', i + 1);
  210. if (e < 0 || i > end)
  211. break;
  212. if (list == null)
  213. list = new List<string> ();
  214. i++;
  215. string name = template.Substring (i, e - i);
  216. string uname = name.ToUpper (CultureInfo.InvariantCulture);
  217. if (list.Contains (uname) || (path != null && path.Contains (uname)))
  218. throw new InvalidOperationException (String.Format ("The URI template string contains duplicate template item {{'{0}'}}", name));
  219. list.Add (uname);
  220. i = e + 1;
  221. }
  222. return list != null ? new ReadOnlyCollection<string> (list) : empty_strings;
  223. }
  224. void ParseQueryTemplate (string template, int index, int end)
  225. {
  226. // template starts with '?'
  227. string [] parameters = template.Substring (index + 1, end - index - 1).Split ('&');
  228. List<string> list = null;
  229. foreach (string parameter in parameters) {
  230. string [] pair = parameter.Split ('=');
  231. if (pair.Length != 2)
  232. throw new FormatException ("Invalid URI query string format");
  233. string pname = pair [0];
  234. string pvalue = pair [1];
  235. if (pvalue.Length >= 2 && pvalue [0] == '{' && pvalue [pvalue.Length - 1] == '}') {
  236. string ptemplate = pvalue.Substring (1, pvalue.Length - 2).ToUpperInvariant ();
  237. query_params.Add (pname, ptemplate);
  238. if (list == null)
  239. list = new List<string> ();
  240. if (list.Contains (ptemplate) || (path != null && path.Contains (ptemplate)))
  241. throw new InvalidOperationException (String.Format ("The URI template string contains duplicate template item {{'{0}'}}", pvalue));
  242. list.Add (ptemplate);
  243. }
  244. }
  245. query = list != null ? new ReadOnlyCollection<string> (list.ToArray ()) : empty_strings;
  246. }
  247. }
  248. }