UriTemplate.cs 13 KB

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