UriTemplate.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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. public UriTemplate (string template)
  43. : this (template, false)
  44. {
  45. }
  46. public UriTemplate (string template, IDictionary<string,string> additionalDefaults)
  47. : this (template, false, additionalDefaults)
  48. {
  49. }
  50. public UriTemplate (string template, bool ignoreTrailingSlash)
  51. : this (template, ignoreTrailingSlash, null)
  52. {
  53. }
  54. public UriTemplate (string template, bool ignoreTrailingSlash, IDictionary<string,string> additionalDefaults)
  55. {
  56. if (template == null)
  57. throw new ArgumentNullException ("template");
  58. this.template = template;
  59. IgnoreTrailingSlash = ignoreTrailingSlash;
  60. Defaults = new Dictionary<string,string> (StringComparer.InvariantCultureIgnoreCase);
  61. if (additionalDefaults != null)
  62. foreach (var pair in additionalDefaults)
  63. Defaults.Add (pair.Key, pair.Value);
  64. string p = template;
  65. // Trim scheme, host name and port if exist.
  66. if (CultureInfo.InvariantCulture.CompareInfo.IsPrefix (template, "http")) {
  67. int idx = template.IndexOf ('/', 8); // after "http://x" or "https://"
  68. if (idx > 0)
  69. p = template.Substring (idx);
  70. }
  71. int q = p.IndexOf ('?');
  72. path = ParsePathTemplate (p, 0, q >= 0 ? q : p.Length);
  73. if (q >= 0)
  74. ParseQueryTemplate (p, q, p.Length);
  75. else
  76. query = empty_strings;
  77. }
  78. public bool IgnoreTrailingSlash { get; private set; }
  79. public IDictionary<string,string> Defaults { get; private set; }
  80. public ReadOnlyCollection<string> PathSegmentVariableNames {
  81. get { return path; }
  82. }
  83. public ReadOnlyCollection<string> QueryValueVariableNames {
  84. get { return query; }
  85. }
  86. public override string ToString ()
  87. {
  88. return template;
  89. }
  90. // Bind
  91. public Uri BindByName (Uri baseAddress, NameValueCollection parameters)
  92. {
  93. return BindByName (baseAddress, parameters, false);
  94. }
  95. public Uri BindByName (Uri baseAddress, NameValueCollection parameters, bool omitDefaults)
  96. {
  97. return BindByNameCommon (baseAddress, parameters, null, omitDefaults);
  98. }
  99. public Uri BindByName (Uri baseAddress, Dictionary<string,string> parameters)
  100. {
  101. return BindByName (baseAddress, parameters, false);
  102. }
  103. public Uri BindByName (Uri baseAddress, Dictionary<string,string> parameters, bool omitDefaults)
  104. {
  105. return BindByNameCommon (baseAddress, null, parameters, omitDefaults);
  106. }
  107. Uri BindByNameCommon (Uri baseAddress, NameValueCollection nvc, Dictionary<string,string> dic, bool omitDefaults)
  108. {
  109. CheckBaseAddress (baseAddress);
  110. int src = 0;
  111. StringBuilder sb = new StringBuilder (template.Length);
  112. BindByName (ref src, sb, path, nvc, dic, omitDefaults);
  113. BindByName (ref src, sb, query, nvc, dic, omitDefaults);
  114. sb.Append (template.Substring (src));
  115. return new Uri (baseAddress.ToString () + sb.ToString ());
  116. }
  117. void BindByName (ref int src, StringBuilder sb, ReadOnlyCollection<string> names, NameValueCollection nvc, Dictionary<string,string> dic, bool omitDefaults)
  118. {
  119. foreach (string name in names) {
  120. int s = template.IndexOf ('{', src);
  121. int e = template.IndexOf ('}', s + 1);
  122. sb.Append (template.Substring (src, s - src));
  123. string value = nvc != null ? nvc [name] : null;
  124. if (dic != null)
  125. dic.TryGetValue (name, out value);
  126. if (value == null && (omitDefaults || !Defaults.TryGetValue (name, out value)))
  127. throw new ArgumentException (String.Format ("The argument name value collection does not contain value for '{0}'", name), "parameters");
  128. sb.Append (value);
  129. src = e + 1;
  130. }
  131. }
  132. public Uri BindByPosition (Uri baseAddress, params string [] values)
  133. {
  134. CheckBaseAddress (baseAddress);
  135. if (values.Length != path.Count + query.Count)
  136. 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));
  137. int src = 0, index = 0;
  138. StringBuilder sb = new StringBuilder (template.Length);
  139. BindByPosition (ref src, sb, path, values, ref index);
  140. BindByPosition (ref src, sb, query, values, ref index);
  141. sb.Append (template.Substring (src));
  142. return new Uri (baseAddress.ToString () + sb.ToString ());
  143. }
  144. void BindByPosition (ref int src, StringBuilder sb, ReadOnlyCollection<string> names, string [] values, ref int index)
  145. {
  146. for (int i = 0; i < names.Count; i++) {
  147. int s = template.IndexOf ('{', src);
  148. int e = template.IndexOf ('}', s + 1);
  149. sb.Append (template.Substring (src, s - src));
  150. string value = values [index++];
  151. if (value == null)
  152. throw new FormatException (String.Format ("The argument value collection contains null at {0}", index - 1));
  153. sb.Append (value);
  154. src = e + 1;
  155. }
  156. }
  157. // Compare
  158. public bool IsEquivalentTo (UriTemplate other)
  159. {
  160. if (other == null)
  161. throw new ArgumentNullException ("other");
  162. return this.template == other.template;
  163. }
  164. // Match
  165. static readonly char [] slashSep = {'/'};
  166. public UriTemplateMatch Match (Uri baseAddress, Uri candidate)
  167. {
  168. CheckBaseAddress (baseAddress);
  169. if (candidate == null)
  170. throw new ArgumentNullException ("candidate");
  171. var us = baseAddress.LocalPath;
  172. if (us [us.Length - 1] != '/')
  173. baseAddress = new Uri (baseAddress.GetLeftPart (UriPartial.Path) + '/' + baseAddress.Query, baseAddress.IsAbsoluteUri ? UriKind.Absolute : UriKind.RelativeOrAbsolute);
  174. if (IgnoreTrailingSlash) {
  175. us = candidate.LocalPath;
  176. if (us.Length > 0 && us [us.Length - 1] != '/')
  177. candidate = new Uri (candidate.GetLeftPart (UriPartial.Path) + '/' + candidate.Query, candidate.IsAbsoluteUri ? UriKind.Absolute : UriKind.RelativeOrAbsolute);
  178. }
  179. if (Uri.Compare (baseAddress, candidate, UriComponents.StrongAuthority, UriFormat.SafeUnescaped, StringComparison.Ordinal) != 0)
  180. return null;
  181. int i = 0, c = 0;
  182. UriTemplateMatch m = new UriTemplateMatch ();
  183. m.BaseUri = baseAddress;
  184. m.Template = this;
  185. m.RequestUri = candidate;
  186. var vc = m.BoundVariables;
  187. string cp = baseAddress.MakeRelativeUri(candidate).ToString ();
  188. if (IgnoreTrailingSlash && cp [cp.Length - 1] == '/')
  189. cp = cp.Substring (0, cp.Length - 1);
  190. int tEndCp = cp.IndexOf ('?');
  191. if (tEndCp >= 0)
  192. cp = cp.Substring (0, tEndCp);
  193. if (template.Length > 0 && template [0] == '/')
  194. i++;
  195. if (cp.Length > 0 && cp [0] == '/')
  196. c++;
  197. foreach (string name in path) {
  198. int n = StringIndexOf (template, '{' + name + '}', i);
  199. if (String.CompareOrdinal (cp, c, template, i, n - i) != 0)
  200. return null; // doesn't match before current template part.
  201. c += n - i;
  202. i = n + 2 + name.Length;
  203. int ce = cp.IndexOf ('/', c);
  204. if (ce < 0)
  205. ce = cp.Length;
  206. string value = cp.Substring (c, ce - c);
  207. if (value.Length == 0)
  208. return null; // empty => mismatch
  209. vc [name] = value;
  210. m.RelativePathSegments.Add (value);
  211. c += value.Length;
  212. }
  213. int tEnd = template.IndexOf ('?');
  214. if (tEnd < 0)
  215. tEnd = template.Length;
  216. bool wild = (template [tEnd - 1] == '*');
  217. if (wild)
  218. tEnd--;
  219. if (!wild && (cp.Length - c) != (tEnd - i) ||
  220. String.CompareOrdinal (cp, c, template, i, tEnd - i) != 0)
  221. return null; // suffix doesn't match
  222. if (wild) {
  223. c += tEnd - i;
  224. foreach (var pe in cp.Substring (c).Split (slashSep, StringSplitOptions.RemoveEmptyEntries))
  225. m.WildcardPathSegments.Add (pe);
  226. }
  227. if (candidate.Query.Length == 0)
  228. return m;
  229. string [] parameters = candidate.Query.Substring (1).Split ('&'); // chop first '?'
  230. foreach (string parameter in parameters) {
  231. string [] pair = parameter.Split ('=');
  232. m.QueryParameters.Add (pair [0], pair [1]);
  233. if (!query_params.ContainsKey (pair [0]))
  234. continue;
  235. string templateName = query_params [pair [0]];
  236. vc.Add (templateName, pair [1]);
  237. }
  238. return m;
  239. }
  240. int StringIndexOf (string s, string pattern, int idx)
  241. {
  242. return CultureInfo.InvariantCulture.CompareInfo.IndexOf (s, pattern, idx, CompareOptions.OrdinalIgnoreCase);
  243. }
  244. // Helpers
  245. void CheckBaseAddress (Uri baseAddress)
  246. {
  247. if (baseAddress == null)
  248. throw new ArgumentNullException ("baseAddress");
  249. if (!baseAddress.IsAbsoluteUri)
  250. throw new ArgumentException ("baseAddress must be an absolute URI.");
  251. if (baseAddress.Scheme == Uri.UriSchemeHttp ||
  252. baseAddress.Scheme == Uri.UriSchemeHttps)
  253. return;
  254. throw new ArgumentException ("baseAddress scheme must be either http or https.");
  255. }
  256. ReadOnlyCollection<string> ParsePathTemplate (string template, int index, int end)
  257. {
  258. int widx = template.IndexOf ('*', index, end);
  259. if (widx >= 0 && widx != end - 1)
  260. throw new FormatException (String.Format ("Wildcard in UriTemplate is valid only if it is placed at the last part of the path: '{0}'", template));
  261. List<string> list = null;
  262. int prevEnd = -2;
  263. for (int i = index; i <= end; ) {
  264. i = template.IndexOf ('{', i);
  265. if (i < 0 || i > end)
  266. break;
  267. if (i == prevEnd + 1)
  268. throw new ArgumentException (String.Format ("The UriTemplate '{0}' contains adjacent templated segments, which is invalid.", template));
  269. int e = template.IndexOf ('}', i + 1);
  270. if (e < 0 || i > end)
  271. throw new FormatException (String.Format ("Missing '}' in URI template '{0}'", template));
  272. prevEnd = e;
  273. if (list == null)
  274. list = new List<string> ();
  275. i++;
  276. string name = template.Substring (i, e - i);
  277. string uname = name.ToUpper (CultureInfo.InvariantCulture);
  278. if (list.Contains (uname) || (path != null && path.Contains (uname)))
  279. throw new InvalidOperationException (String.Format ("The URI template string contains duplicate template item {{'{0}'}}", name));
  280. list.Add (uname);
  281. i = e + 1;
  282. }
  283. return list != null ? new ReadOnlyCollection<string> (list) : empty_strings;
  284. }
  285. void ParseQueryTemplate (string template, int index, int end)
  286. {
  287. // template starts with '?'
  288. string [] parameters = template.Substring (index + 1, end - index - 1).Split ('&');
  289. List<string> list = null;
  290. foreach (string parameter in parameters) {
  291. string [] pair = parameter.Split ('=');
  292. if (pair.Length != 2)
  293. throw new FormatException ("Invalid URI query string format");
  294. string pname = pair [0];
  295. string pvalue = pair [1];
  296. if (pvalue.Length >= 2 && pvalue [0] == '{' && pvalue [pvalue.Length - 1] == '}') {
  297. string ptemplate = pvalue.Substring (1, pvalue.Length - 2).ToUpperInvariant ();
  298. query_params.Add (pname, ptemplate);
  299. if (list == null)
  300. list = new List<string> ();
  301. if (list.Contains (ptemplate) || (path != null && path.Contains (ptemplate)))
  302. throw new InvalidOperationException (String.Format ("The URI template string contains duplicate template item {{'{0}'}}", pvalue));
  303. list.Add (ptemplate);
  304. }
  305. }
  306. query = list != null ? new ReadOnlyCollection<string> (list.ToArray ()) : empty_strings;
  307. }
  308. }
  309. }