2
0

UriTemplate.cs 14 KB

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