5 // Atsushi Enomoto <atsushi@ximian.com>
7 // Copyright (C) 2008 Novell, Inc (http://www.novell.com)
8 // Copyright 2011 Xamarin Inc (http://www.xamarin.com).
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:
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
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.
30 using System.Collections.Generic;
31 using System.Collections.ObjectModel;
32 using System.Collections.Specialized;
33 using System.Globalization;
37 using NameValueCollection = System.Object;
42 public class UriTemplate
44 static readonly ReadOnlyCollection<string> empty_strings = new ReadOnlyCollection<string> (new string [0]);
47 ReadOnlyCollection<string> path, query;
48 string wild_path_name;
49 Dictionary<string,string> query_params = new Dictionary<string,string> ();
51 public UriTemplate (string template)
52 : this (template, false)
56 public UriTemplate (string template, IDictionary<string,string> additionalDefaults)
57 : this (template, false, additionalDefaults)
61 public UriTemplate (string template, bool ignoreTrailingSlash)
62 : this (template, ignoreTrailingSlash, null)
66 public UriTemplate (string template, bool ignoreTrailingSlash, IDictionary<string,string> additionalDefaults)
69 throw new ArgumentNullException ("template");
70 this.template = template;
71 IgnoreTrailingSlash = ignoreTrailingSlash;
72 Defaults = new Dictionary<string,string> (StringComparer.InvariantCultureIgnoreCase);
73 if (additionalDefaults != null)
74 foreach (var pair in additionalDefaults)
75 Defaults.Add (pair.Key, pair.Value);
78 // Trim scheme, host name and port if exist.
79 if (CultureInfo.InvariantCulture.CompareInfo.IsPrefix (template, "http")) {
80 int idx = template.IndexOf ('/', 8); // after "http://x" or "https://"
82 p = template.Substring (idx);
84 int q = p.IndexOf ('?');
85 path = ParsePathTemplate (p, 0, q >= 0 ? q : p.Length);
87 ParseQueryTemplate (p, q, p.Length);
89 query = empty_strings;
92 public bool IgnoreTrailingSlash { get; private set; }
94 public IDictionary<string,string> Defaults { get; private set; }
96 public ReadOnlyCollection<string> PathSegmentVariableNames {
100 public ReadOnlyCollection<string> QueryValueVariableNames {
101 get { return query; }
104 public override string ToString ()
111 public Uri BindByName (Uri baseAddress, NameValueCollection parameters)
113 return BindByName (baseAddress, parameters, false);
116 public Uri BindByName (Uri baseAddress, NameValueCollection parameters, bool omitDefaults)
118 return BindByNameCommon (baseAddress, parameters, null, omitDefaults);
121 public Uri BindByName (Uri baseAddress, IDictionary<string,string> parameters)
123 return BindByName (baseAddress, parameters, false);
126 public Uri BindByName (Uri baseAddress, IDictionary<string,string> parameters, bool omitDefaults)
128 return BindByNameCommon (baseAddress, null, parameters, omitDefaults);
131 string SuffixEndRenderedUri (string s)
133 return s.Length > 0 && s [s.Length - 1] == '/' ? s : s + '/';
136 string TrimStartRenderedUri (StringBuilder sb)
142 return sb.ToString (1, sb.Length - 1);
144 return sb.ToString ();
147 Uri BindByNameCommon (Uri baseAddress, NameValueCollection nvc, IDictionary<string,string> dic, bool omitDefaults)
149 CheckBaseAddress (baseAddress);
151 // take care of case sensitivity.
153 dic = new Dictionary<string,string> (dic, StringComparer.OrdinalIgnoreCase);
156 StringBuilder sb = new StringBuilder (template.Length);
157 BindByName (ref src, sb, path, nvc, dic, omitDefaults, false);
158 BindByName (ref src, sb, query, nvc, dic, omitDefaults, true);
159 sb.Append (template.Substring (src));
160 return new Uri (SuffixEndRenderedUri (baseAddress.ToString ()) + TrimStartRenderedUri (sb));
163 void BindByName (ref int src, StringBuilder sb, ReadOnlyCollection<string> names, NameValueCollection nvc, IDictionary<string,string> dic, bool omitDefaults, bool query)
166 int idx = template.IndexOf ('?', src);
168 sb.Append (template.Substring (src, idx - src));
170 // note that it doesn't append '?'. It is added only when there is actual parameter binding.
174 foreach (string name in names) {
175 int s = template.IndexOf ('{', src);
176 int e = template.IndexOf ('}', s + 1);
180 string value = nvc != null ? nvc [name] : null;
183 dic.TryGetValue (name, out value);
186 if (value != null || (!omitDefaults && Defaults.TryGetValue (name, out value))) {
187 sb.Append (template.Substring (src, s - src));
191 if (value == null && (omitDefaults || !Defaults.TryGetValue (name, out value)))
192 throw new ArgumentException (string.Format("The argument name value collection does not contain non-null value for '{0}'", name), "parameters");
194 sb.Append (template.Substring (src, s - src));
201 public Uri BindByPosition (Uri baseAddress, params string [] values)
203 CheckBaseAddress (baseAddress);
205 if (values.Length != path.Count + query.Count)
206 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));
208 int src = 0, index = 0;
209 StringBuilder sb = new StringBuilder (template.Length);
210 BindByPosition (ref src, sb, path, values, ref index);
211 BindByPosition (ref src, sb, query, values, ref index);
212 sb.Append (template.Substring (src));
213 return new Uri (SuffixEndRenderedUri (baseAddress.ToString ()) + TrimStartRenderedUri (sb));
216 void BindByPosition (ref int src, StringBuilder sb, ReadOnlyCollection<string> names, string [] values, ref int index)
218 for (int i = 0; i < names.Count; i++) {
219 int s = template.IndexOf ('{', src);
220 int e = template.IndexOf ('}', s + 1);
221 sb.Append (template.Substring (src, s - src));
222 string value = values [index++];
224 throw new FormatException (String.Format ("The argument value collection contains null at {0}", index - 1));
232 public bool IsEquivalentTo (UriTemplate other)
235 throw new ArgumentNullException ("other");
236 return this.template == other.template;
241 static readonly char [] slashSep = {'/'};
243 public UriTemplateMatch Match (Uri baseAddress, Uri candidate)
245 CheckBaseAddress (baseAddress);
246 if (candidate == null)
247 throw new ArgumentNullException ("candidate");
249 var us = baseAddress.LocalPath;
250 if (us [us.Length - 1] != '/')
251 baseAddress = new Uri (
252 baseAddress.GetComponents (UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.UriEscaped) + '/' + baseAddress.Query,
253 baseAddress.IsAbsoluteUri ? UriKind.Absolute : UriKind.RelativeOrAbsolute
255 if (IgnoreTrailingSlash) {
256 us = candidate.LocalPath;
257 if (us.Length > 0 && us [us.Length - 1] != '/')
258 candidate = new Uri (
259 candidate.GetComponents (UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.UriEscaped) + '/' + candidate.Query,
260 candidate.IsAbsoluteUri ? UriKind.Absolute : UriKind.RelativeOrAbsolute
265 UriTemplateMatch m = new UriTemplateMatch ();
266 m.BaseUri = baseAddress;
268 m.RequestUri = candidate;
269 var vc = m.BoundVariables;
271 string cp = baseAddress.MakeRelativeUri (new Uri (
273 candidate.GetComponents (UriComponents.PathAndQuery, UriFormat.UriEscaped)
276 if (IgnoreTrailingSlash && cp [cp.Length - 1] == '/')
277 cp = cp.Substring (0, cp.Length - 1);
279 int tEndCp = cp.IndexOf ('?');
281 cp = cp.Substring (0, tEndCp);
283 if (template.Length > 0 && template [0] == '/')
285 if (cp.Length > 0 && cp [0] == '/')
288 foreach (string name in path) {
289 if (name == wild_path_name) {
290 vc [name] = Uri.UnescapeDataString (cp.Substring (c)); // all remaining paths.
293 int n = StringIndexOf (template, '{' + name + '}', i);
294 if (String.CompareOrdinal (cp, c, template, i, n - i) != 0)
295 return null; // doesn't match before current template part.
297 i = n + 2 + name.Length;
298 int ce = cp.IndexOf ('/', c);
301 string value = cp.Substring (c, ce - c);
302 string unescapedVaule = Uri.UnescapeDataString (value);
303 if (value.Length == 0)
304 return null; // empty => mismatch
305 vc [name] = unescapedVaule;
306 m.RelativePathSegments.Add (unescapedVaule);
309 int tEnd = template.IndexOf ('?');
310 int wildIdx = template.IndexOf ('*');
311 bool wild = wildIdx >= 0;
313 tEnd = template.Length;
315 tEnd = Math.Max (wildIdx - 1, 0);
316 if (!wild && (cp.Length - c) != (tEnd - i) ||
317 String.CompareOrdinal (cp, c, template, i, tEnd - i) != 0)
318 return null; // suffix doesn't match
321 foreach (var pe in cp.Substring (c).Split (slashSep, StringSplitOptions.RemoveEmptyEntries))
322 m.WildcardPathSegments.Add (pe);
324 if (candidate.Query.Length == 0)
328 string [] parameters = Uri.UnescapeDataString (candidate.Query.Substring (1)).Split ('&'); // chop first '?'
329 foreach (string parameter in parameters) {
330 string [] pair = parameter.Split ('=');
331 m.QueryParameters.Add (pair [0], pair [1]);
332 if (!query_params.ContainsKey (pair [0]))
334 string templateName = query_params [pair [0]];
335 vc.Add (templateName, pair [1]);
341 int StringIndexOf (string s, string pattern, int idx)
343 return CultureInfo.InvariantCulture.CompareInfo.IndexOf (s, pattern, idx, CompareOptions.OrdinalIgnoreCase);
348 void CheckBaseAddress (Uri baseAddress)
350 if (baseAddress == null)
351 throw new ArgumentNullException ("baseAddress");
352 if (!baseAddress.IsAbsoluteUri)
353 throw new ArgumentException ("baseAddress must be an absolute URI.");
354 if (baseAddress.Scheme == Uri.UriSchemeHttp ||
355 baseAddress.Scheme == Uri.UriSchemeHttps)
357 throw new ArgumentException ("baseAddress scheme must be either http or https.");
360 ReadOnlyCollection<string> ParsePathTemplate (string template, int index, int end)
362 int widx = template.IndexOf ('*', index, end);
364 if (widx != end - 1 && template.IndexOf ('}', widx) != end - 1)
365 throw new FormatException (String.Format ("Wildcard in UriTemplate is valid only if it is placed at the last part of the path: '{0}'", template));
366 List<string> list = null;
368 for (int i = index; i <= end; ) {
369 i = template.IndexOf ('{', i);
370 if (i < 0 || i > end)
372 if (i == prevEnd + 1)
373 throw new ArgumentException (String.Format ("The UriTemplate '{0}' contains adjacent templated segments, which is invalid.", template));
374 int e = template.IndexOf ('}', i + 1);
375 if (e < 0 || i > end)
376 throw new FormatException (String.Format ("Missing '}' in URI template '{0}'", template));
379 list = new List<string> ();
381 string name = template.Substring (i, e - i);
382 string uname = name.ToUpper (CultureInfo.InvariantCulture);
383 if (uname [0] == '*')
384 uname = wild_path_name = uname.Substring (1);
385 if (list.Contains (uname) || (path != null && path.Contains (uname)))
386 throw new InvalidOperationException (String.Format ("The URI template string contains duplicate template item {{'{0}'}}", name));
390 return list != null ? new ReadOnlyCollection<string> (list) : empty_strings;
393 void ParseQueryTemplate (string template, int index, int end)
395 // template starts with '?'
396 string [] parameters = template.Substring (index + 1, end - index - 1).Split ('&');
397 List<string> list = null;
398 foreach (string parameter in parameters) {
399 string [] pair = parameter.Split ('=');
400 if (pair.Length != 2)
401 throw new FormatException ("Invalid URI query string format");
402 string pname = pair [0];
403 string pvalue = pair [1];
404 if (pvalue.Length >= 2 && pvalue [0] == '{' && pvalue [pvalue.Length - 1] == '}') {
405 string ptemplate = pvalue.Substring (1, pvalue.Length - 2).ToUpper (CultureInfo.InvariantCulture);
406 query_params.Add (pname, ptemplate);
408 list = new List<string> ();
409 if (list.Contains (ptemplate) || (path != null && path.Contains (ptemplate)))
410 throw new InvalidOperationException (String.Format ("The URI template string contains duplicate template item {{'{0}'}}", pvalue));
411 list.Add (ptemplate);
414 query = list != null ? new ReadOnlyCollection<string> (list.ToArray ()) : empty_strings;