UriTemplate.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. //
  2. // UriTemplate.cs
  3. //
  4. // Author:
  5. // Atsushi Enomoto <[email protected]>
  6. //
  7. // Copyright (C) 2008 Novell, Inc (http://www.novell.com)
  8. // Copyright 2011 Xamarin Inc (http://www.xamarin.com).
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. using System;
  30. using System.Collections.Generic;
  31. using System.Collections.ObjectModel;
  32. using System.Collections.Specialized;
  33. using System.Globalization;
  34. using System.Text;
  35. namespace System
  36. {
  37. public class UriTemplate
  38. {
  39. static readonly ReadOnlyCollection<string> empty_strings = new ReadOnlyCollection<string> (new string [0]);
  40. string template;
  41. ReadOnlyCollection<string> path, query;
  42. string wild_path_name;
  43. Dictionary<string,string> query_params = new Dictionary<string,string> ();
  44. public UriTemplate (string template)
  45. : this (template, false)
  46. {
  47. }
  48. public UriTemplate (string template, IDictionary<string,string> additionalDefaults)
  49. : this (template, false, additionalDefaults)
  50. {
  51. }
  52. public UriTemplate (string template, bool ignoreTrailingSlash)
  53. : this (template, ignoreTrailingSlash, null)
  54. {
  55. }
  56. public UriTemplate (string template, bool ignoreTrailingSlash, IDictionary<string,string> additionalDefaults)
  57. {
  58. if (template == null)
  59. throw new ArgumentNullException ("template");
  60. this.template = template;
  61. IgnoreTrailingSlash = ignoreTrailingSlash;
  62. Defaults = new Dictionary<string,string> (StringComparer.InvariantCultureIgnoreCase);
  63. if (additionalDefaults != null)
  64. foreach (var pair in additionalDefaults)
  65. Defaults.Add (pair.Key, pair.Value);
  66. string p = template;
  67. // Trim scheme, host name and port if exist.
  68. if (CultureInfo.InvariantCulture.CompareInfo.IsPrefix (template, "http")) {
  69. int idx = template.IndexOf ('/', 8); // after "http://x" or "https://"
  70. if (idx > 0)
  71. p = template.Substring (idx);
  72. }
  73. int q = p.IndexOf ('?');
  74. path = ParsePathTemplate (p, 0, q >= 0 ? q : p.Length);
  75. if (q >= 0)
  76. ParseQueryTemplate (p, q, p.Length);
  77. else
  78. query = empty_strings;
  79. }
  80. public bool IgnoreTrailingSlash { get; private set; }
  81. public IDictionary<string,string> Defaults { get; private set; }
  82. public ReadOnlyCollection<string> PathSegmentVariableNames {
  83. get { return path; }
  84. }
  85. public ReadOnlyCollection<string> QueryValueVariableNames {
  86. get { return query; }
  87. }
  88. public override string ToString ()
  89. {
  90. return template;
  91. }
  92. // Bind
  93. public Uri BindByName (Uri baseAddress, NameValueCollection parameters)
  94. {
  95. return BindByName (baseAddress, parameters, false);
  96. }
  97. public Uri BindByName (Uri baseAddress, NameValueCollection parameters, bool omitDefaults)
  98. {
  99. return BindByNameCommon (baseAddress, parameters, null, omitDefaults);
  100. }
  101. public Uri BindByName (Uri baseAddress, IDictionary<string,string> parameters)
  102. {
  103. return BindByName (baseAddress, parameters, false);
  104. }
  105. public Uri BindByName (Uri baseAddress, IDictionary<string,string> parameters, bool omitDefaults)
  106. {
  107. return BindByNameCommon (baseAddress, null, parameters, omitDefaults);
  108. }
  109. string SuffixEndRenderedUri (string s)
  110. {
  111. return s.Length > 0 && s [s.Length - 1] == '/' ? s : s + '/';
  112. }
  113. string TrimStartRenderedUri (StringBuilder sb)
  114. {
  115. if (sb.Length == 0)
  116. return String.Empty;
  117. if (sb [0] == '/')
  118. return sb.ToString (1, sb.Length - 1);
  119. return sb.ToString ();
  120. }
  121. Uri BindByNameCommon (Uri baseAddress, NameValueCollection nvc, IDictionary<string,string> dic, bool omitDefaults)
  122. {
  123. CheckBaseAddress (baseAddress);
  124. // take care of case sensitivity.
  125. if (dic != null)
  126. dic = new Dictionary<string,string> (dic, StringComparer.OrdinalIgnoreCase);
  127. int src = 0;
  128. StringBuilder sb = new StringBuilder (template.Length);
  129. BindByName (ref src, sb, path, nvc, dic, omitDefaults, false);
  130. BindByName (ref src, sb, query, nvc, dic, omitDefaults, true);
  131. sb.Append (template.Substring (src));
  132. return new Uri (SuffixEndRenderedUri (baseAddress.ToString ()) + TrimStartRenderedUri (sb));
  133. }
  134. void BindByName (ref int src, StringBuilder sb, ReadOnlyCollection<string> names, NameValueCollection nvc, IDictionary<string,string> dic, bool omitDefaults, bool query)
  135. {
  136. if (query) {
  137. int idx = template.IndexOf ('?', src);
  138. if (idx > 0) {
  139. sb.Append (template.Substring (src, idx - src));
  140. src = idx;
  141. // note that it doesn't append '?'. It is added only when there is actual parameter binding.
  142. }
  143. }
  144. foreach (string name in names) {
  145. int s = template.IndexOf ('{', src);
  146. int e = template.IndexOf ('}', s + 1);
  147. string value = nvc != null ? nvc [name] : null;
  148. if (dic != null)
  149. dic.TryGetValue (name, out value);
  150. if (query) {
  151. if (value != null || (!omitDefaults && Defaults.TryGetValue (name, out value))) {
  152. sb.Append (template.Substring (src, s - src));
  153. sb.Append (value);
  154. }
  155. } else {
  156. if (value == null && (omitDefaults || !Defaults.TryGetValue (name, out value)))
  157. throw new ArgumentException (string.Format("The argument name value collection does not contain non-null value for '{0}'", name), "parameters");
  158. sb.Append (template.Substring (src, s - src));
  159. sb.Append (value);
  160. }
  161. src = e + 1;
  162. }
  163. }
  164. public Uri BindByPosition (Uri baseAddress, params string [] values)
  165. {
  166. CheckBaseAddress (baseAddress);
  167. if (values.Length != path.Count + query.Count)
  168. 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));
  169. int src = 0, index = 0;
  170. StringBuilder sb = new StringBuilder (template.Length);
  171. BindByPosition (ref src, sb, path, values, ref index);
  172. BindByPosition (ref src, sb, query, values, ref index);
  173. sb.Append (template.Substring (src));
  174. return new Uri (SuffixEndRenderedUri (baseAddress.ToString ()) + TrimStartRenderedUri (sb));
  175. }
  176. void BindByPosition (ref int src, StringBuilder sb, ReadOnlyCollection<string> names, string [] values, ref int index)
  177. {
  178. for (int i = 0; i < names.Count; i++) {
  179. int s = template.IndexOf ('{', src);
  180. int e = template.IndexOf ('}', s + 1);
  181. sb.Append (template.Substring (src, s - src));
  182. string value = values [index++];
  183. if (value == null)
  184. throw new FormatException (String.Format ("The argument value collection contains null at {0}", index - 1));
  185. sb.Append (value);
  186. src = e + 1;
  187. }
  188. }
  189. // Compare
  190. public bool IsEquivalentTo (UriTemplate other)
  191. {
  192. if (other == null)
  193. throw new ArgumentNullException ("other");
  194. return this.template == other.template;
  195. }
  196. // Match
  197. static readonly char [] slashSep = {'/'};
  198. public UriTemplateMatch Match (Uri baseAddress, Uri candidate)
  199. {
  200. CheckBaseAddress (baseAddress);
  201. if (candidate == null)
  202. throw new ArgumentNullException ("candidate");
  203. var us = baseAddress.LocalPath;
  204. if (us [us.Length - 1] != '/')
  205. baseAddress = new Uri (
  206. baseAddress.GetComponents (UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.UriEscaped) + '/' + baseAddress.Query,
  207. baseAddress.IsAbsoluteUri ? UriKind.Absolute : UriKind.RelativeOrAbsolute
  208. );
  209. if (IgnoreTrailingSlash) {
  210. us = candidate.LocalPath;
  211. if (us.Length > 0 && us [us.Length - 1] != '/')
  212. candidate = new Uri (
  213. candidate.GetComponents (UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.UriEscaped) + '/' + candidate.Query,
  214. candidate.IsAbsoluteUri ? UriKind.Absolute : UriKind.RelativeOrAbsolute
  215. );
  216. }
  217. int i = 0, c = 0;
  218. UriTemplateMatch m = new UriTemplateMatch ();
  219. m.BaseUri = baseAddress;
  220. m.Template = this;
  221. m.RequestUri = candidate;
  222. var vc = m.BoundVariables;
  223. string cp = baseAddress.MakeRelativeUri (new Uri (
  224. baseAddress,
  225. candidate.GetComponents (UriComponents.PathAndQuery, UriFormat.UriEscaped)
  226. ))
  227. .ToString ();
  228. if (IgnoreTrailingSlash && cp [cp.Length - 1] == '/')
  229. cp = cp.Substring (0, cp.Length - 1);
  230. int tEndCp = cp.IndexOf ('?');
  231. if (tEndCp >= 0)
  232. cp = cp.Substring (0, tEndCp);
  233. if (template.Length > 0 && template [0] == '/')
  234. i++;
  235. if (cp.Length > 0 && cp [0] == '/')
  236. c++;
  237. foreach (string name in path) {
  238. if (name == wild_path_name) {
  239. vc [name] = Uri.UnescapeDataString (cp.Substring (c)); // all remaining paths.
  240. continue;
  241. }
  242. int n = StringIndexOf (template, '{' + name + '}', i);
  243. if (String.CompareOrdinal (cp, c, template, i, n - i) != 0)
  244. return null; // doesn't match before current template part.
  245. c += n - i;
  246. i = n + 2 + name.Length;
  247. int ce = cp.IndexOf ('/', c);
  248. if (ce < 0)
  249. ce = cp.Length;
  250. string value = cp.Substring (c, ce - c);
  251. string unescapedVaule = Uri.UnescapeDataString (value);
  252. if (value.Length == 0)
  253. return null; // empty => mismatch
  254. vc [name] = unescapedVaule;
  255. m.RelativePathSegments.Add (unescapedVaule);
  256. c += value.Length;
  257. }
  258. int tEnd = template.IndexOf ('?');
  259. int wildIdx = template.IndexOf ('*');
  260. bool wild = wildIdx >= 0;
  261. if (tEnd < 0)
  262. tEnd = template.Length;
  263. if (wild)
  264. tEnd = Math.Max (wildIdx - 1, 0);
  265. if (!wild && (cp.Length - c) != (tEnd - i) ||
  266. String.CompareOrdinal (cp, c, template, i, tEnd - i) != 0)
  267. return null; // suffix doesn't match
  268. if (wild) {
  269. c += tEnd - i;
  270. foreach (var pe in cp.Substring (c).Split (slashSep, StringSplitOptions.RemoveEmptyEntries))
  271. m.WildcardPathSegments.Add (pe);
  272. }
  273. if (candidate.Query.Length == 0)
  274. return m;
  275. string [] parameters = Uri.UnescapeDataString (candidate.Query.Substring (1)).Split ('&'); // chop first '?'
  276. foreach (string parameter in parameters) {
  277. string [] pair = parameter.Split ('=');
  278. if (pair.Length > 0) {
  279. m.QueryParameters.Add (pair [0], pair.Length == 2 ? pair [1] : null);
  280. if (!query_params.ContainsKey (pair [0]))
  281. continue;
  282. if (pair.Length > 1) {
  283. string templateName = query_params [pair [0]];
  284. vc.Add (templateName, pair [1]);
  285. }
  286. }
  287. }
  288. return m;
  289. }
  290. int StringIndexOf (string s, string pattern, int idx)
  291. {
  292. return CultureInfo.InvariantCulture.CompareInfo.IndexOf (s, pattern, idx, CompareOptions.OrdinalIgnoreCase);
  293. }
  294. // Helpers
  295. void CheckBaseAddress (Uri baseAddress)
  296. {
  297. if (baseAddress == null)
  298. throw new ArgumentNullException ("baseAddress");
  299. if (!baseAddress.IsAbsoluteUri)
  300. throw new ArgumentException ("baseAddress must be an absolute URI.");
  301. if (baseAddress.Scheme == Uri.UriSchemeHttp ||
  302. baseAddress.Scheme == Uri.UriSchemeHttps)
  303. return;
  304. throw new ArgumentException ("baseAddress scheme must be either http or https.");
  305. }
  306. ReadOnlyCollection<string> ParsePathTemplate (string template, int index, int end)
  307. {
  308. int widx = template.IndexOf ('*', index, end);
  309. if (widx >= 0)
  310. if (widx != end - 1 && template.IndexOf ('}', widx) != end - 1)
  311. throw new FormatException (String.Format ("Wildcard in UriTemplate is valid only if it is placed at the last part of the path: '{0}'", template));
  312. List<string> list = null;
  313. int prevEnd = -2;
  314. for (int i = index; i <= end; ) {
  315. i = template.IndexOf ('{', i);
  316. if (i < 0 || i > end)
  317. break;
  318. if (i == prevEnd + 1)
  319. throw new ArgumentException (String.Format ("The UriTemplate '{0}' contains adjacent templated segments, which is invalid.", template));
  320. int e = template.IndexOf ('}', i + 1);
  321. if (e < 0 || i > end)
  322. throw new FormatException (String.Format ("Missing '}' in URI template '{0}'", template));
  323. prevEnd = e;
  324. if (list == null)
  325. list = new List<string> ();
  326. i++;
  327. string name = template.Substring (i, e - i);
  328. string uname = name.ToUpper (CultureInfo.InvariantCulture);
  329. if (uname [0] == '*')
  330. uname = wild_path_name = uname.Substring (1);
  331. if (list.Contains (uname) || (path != null && path.Contains (uname)))
  332. throw new InvalidOperationException (String.Format ("The URI template string contains duplicate template item {{'{0}'}}", name));
  333. list.Add (uname);
  334. i = e + 1;
  335. }
  336. return list != null ? new ReadOnlyCollection<string> (list) : empty_strings;
  337. }
  338. void ParseQueryTemplate (string template, int index, int end)
  339. {
  340. // template starts with '?'
  341. string [] parameters = template.Substring (index + 1, end - index - 1).Split ('&');
  342. List<string> list = null;
  343. foreach (string parameter in parameters) {
  344. string [] pair = parameter.Split ('=');
  345. if (pair.Length != 2)
  346. throw new FormatException ("Invalid URI query string format");
  347. string pname = pair [0];
  348. string pvalue = pair [1];
  349. if (pvalue.Length >= 2 && pvalue [0] == '{' && pvalue [pvalue.Length - 1] == '}') {
  350. string ptemplate = pvalue.Substring (1, pvalue.Length - 2).ToUpper (CultureInfo.InvariantCulture);
  351. query_params.Add (pname, ptemplate);
  352. if (list == null)
  353. list = new List<string> ();
  354. if (list.Contains (ptemplate) || (path != null && path.Contains (ptemplate)))
  355. throw new InvalidOperationException (String.Format ("The URI template string contains duplicate template item {{'{0}'}}", pvalue));
  356. list.Add (ptemplate);
  357. }
  358. }
  359. query = list != null ? new ReadOnlyCollection<string> (list.ToArray ()) : empty_strings;
  360. }
  361. }
  362. }