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 ()
112 public Uri BindByName (Uri baseAddress, NameValueCollection parameters)
114 return BindByName (baseAddress, parameters, false);
117 public Uri BindByName (Uri baseAddress, NameValueCollection parameters, bool omitDefaults)
119 return BindByNameCommon (baseAddress, parameters, null, omitDefaults);
123 public Uri BindByName (Uri baseAddress, IDictionary<string,string> parameters)
125 return BindByName (baseAddress, parameters, false);
128 public Uri BindByName (Uri baseAddress, IDictionary<string,string> parameters, bool omitDefaults)
130 return BindByNameCommon (baseAddress, null, parameters, omitDefaults);
133 string SuffixEndRenderedUri (string s)
135 return s.Length > 0 && s [s.Length - 1] == '/' ? s : s + '/';
138 string TrimStartRenderedUri (StringBuilder sb)
144 return sb.ToString (1, sb.Length - 1);
146 return sb.ToString ();
149 Uri BindByNameCommon (Uri baseAddress, NameValueCollection nvc, IDictionary<string,string> dic, bool omitDefaults)
151 CheckBaseAddress (baseAddress);
153 // take care of case sensitivity.
155 dic = new Dictionary<string,string> (dic, StringComparer.OrdinalIgnoreCase);
158 StringBuilder sb = new StringBuilder (template.Length);
159 BindByName (ref src, sb, path, nvc, dic, omitDefaults, false);
160 BindByName (ref src, sb, query, nvc, dic, omitDefaults, true);
161 sb.Append (template.Substring (src));
162 return new Uri (SuffixEndRenderedUri (baseAddress.ToString ()) + TrimStartRenderedUri (sb));
165 void BindByName (ref int src, StringBuilder sb, ReadOnlyCollection<string> names, NameValueCollection nvc, IDictionary<string,string> dic, bool omitDefaults, bool query)
168 int idx = template.IndexOf ('?', src);
170 sb.Append (template.Substring (src, idx - src));
172 // note that it doesn't append '?'. It is added only when there is actual parameter binding.
176 foreach (string name in names) {
177 int s = template.IndexOf ('{', src);
178 int e = template.IndexOf ('}', s + 1);
182 string value = nvc != null ? nvc [name] : null;
185 dic.TryGetValue (name, out value);
188 if (value != null || (!omitDefaults && Defaults.TryGetValue (name, out value))) {
189 sb.Append (template.Substring (src, s - src));
193 if (value == null && (omitDefaults || !Defaults.TryGetValue (name, out value)))
194 throw new ArgumentException (string.Format("The argument name value collection does not contain non-null value for '{0}'", name), "parameters");
196 sb.Append (template.Substring (src, s - src));
203 public Uri BindByPosition (Uri baseAddress, params string [] values)
205 CheckBaseAddress (baseAddress);
207 if (values.Length != path.Count + query.Count)
208 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));
210 int src = 0, index = 0;
211 StringBuilder sb = new StringBuilder (template.Length);
212 BindByPosition (ref src, sb, path, values, ref index);
213 BindByPosition (ref src, sb, query, values, ref index);
214 sb.Append (template.Substring (src));
215 return new Uri (SuffixEndRenderedUri (baseAddress.ToString ()) + TrimStartRenderedUri (sb));
218 void BindByPosition (ref int src, StringBuilder sb, ReadOnlyCollection<string> names, string [] values, ref int index)
220 for (int i = 0; i < names.Count; i++) {
221 int s = template.IndexOf ('{', src);
222 int e = template.IndexOf ('}', s + 1);
223 sb.Append (template.Substring (src, s - src));
224 string value = values [index++];
226 throw new FormatException (String.Format ("The argument value collection contains null at {0}", index - 1));
234 public bool IsEquivalentTo (UriTemplate other)
237 throw new ArgumentNullException ("other");
238 return this.template == other.template;
243 static readonly char [] slashSep = {'/'};
245 public UriTemplateMatch Match (Uri baseAddress, Uri candidate)
247 CheckBaseAddress (baseAddress);
248 if (candidate == null)
249 throw new ArgumentNullException ("candidate");
251 var us = baseAddress.LocalPath;
252 if (us [us.Length - 1] != '/')
253 baseAddress = new Uri (
254 baseAddress.GetComponents (UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.UriEscaped) + '/' + baseAddress.Query,
255 baseAddress.IsAbsoluteUri ? UriKind.Absolute : UriKind.RelativeOrAbsolute
257 if (IgnoreTrailingSlash) {
258 us = candidate.LocalPath;
259 if (us.Length > 0 && us [us.Length - 1] != '/')
260 candidate = new Uri (
261 candidate.GetComponents (UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.UriEscaped) + '/' + candidate.Query,
262 candidate.IsAbsoluteUri ? UriKind.Absolute : UriKind.RelativeOrAbsolute
267 UriTemplateMatch m = new UriTemplateMatch ();
268 m.BaseUri = baseAddress;
270 m.RequestUri = candidate;
271 var vc = m.BoundVariables;
273 string cp = baseAddress.MakeRelativeUri (new Uri (
275 candidate.GetComponents (UriComponents.PathAndQuery, UriFormat.UriEscaped)
278 if (IgnoreTrailingSlash && cp [cp.Length - 1] == '/')
279 cp = cp.Substring (0, cp.Length - 1);
281 int tEndCp = cp.IndexOf ('?');
283 cp = cp.Substring (0, tEndCp);
285 if (template.Length > 0 && template [0] == '/')
287 if (cp.Length > 0 && cp [0] == '/')
290 foreach (string name in path) {
291 if (name == wild_path_name) {
292 vc [name] = Uri.UnescapeDataString (cp.Substring (c)); // all remaining paths.
295 int n = StringIndexOf (template, '{' + name + '}', i);
296 if (String.CompareOrdinal (cp, c, template, i, n - i) != 0)
297 return null; // doesn't match before current template part.
299 i = n + 2 + name.Length;
300 int ce = cp.IndexOf ('/', c);
303 string value = cp.Substring (c, ce - c);
304 string unescapedVaule = Uri.UnescapeDataString (value);
305 if (value.Length == 0)
306 return null; // empty => mismatch
307 vc [name] = unescapedVaule;
308 m.RelativePathSegments.Add (unescapedVaule);
311 int tEnd = template.IndexOf ('?');
312 int wildIdx = template.IndexOf ('*');
313 bool wild = wildIdx >= 0;
315 tEnd = template.Length;
317 tEnd = Math.Max (wildIdx - 1, 0);
318 if (!wild && (cp.Length - c) != (tEnd - i) ||
319 String.CompareOrdinal (cp, c, template, i, tEnd - i) != 0)
320 return null; // suffix doesn't match
323 foreach (var pe in cp.Substring (c).Split (slashSep, StringSplitOptions.RemoveEmptyEntries))
324 m.WildcardPathSegments.Add (pe);
326 if (candidate.Query.Length == 0)
330 string [] parameters = Uri.UnescapeDataString (candidate.Query.Substring (1)).Split ('&'); // chop first '?'
331 foreach (string parameter in parameters) {
332 string [] pair = parameter.Split ('=');
333 m.QueryParameters.Add (pair [0], pair [1]);
334 if (!query_params.ContainsKey (pair [0]))
336 string templateName = query_params [pair [0]];
337 vc.Add (templateName, pair [1]);
343 int StringIndexOf (string s, string pattern, int idx)
345 return CultureInfo.InvariantCulture.CompareInfo.IndexOf (s, pattern, idx, CompareOptions.OrdinalIgnoreCase);
350 void CheckBaseAddress (Uri baseAddress)
352 if (baseAddress == null)
353 throw new ArgumentNullException ("baseAddress");
354 if (!baseAddress.IsAbsoluteUri)
355 throw new ArgumentException ("baseAddress must be an absolute URI.");
356 if (baseAddress.Scheme == Uri.UriSchemeHttp ||
357 baseAddress.Scheme == Uri.UriSchemeHttps)
359 throw new ArgumentException ("baseAddress scheme must be either http or https.");
362 ReadOnlyCollection<string> ParsePathTemplate (string template, int index, int end)
364 int widx = template.IndexOf ('*', index, end);
366 if (widx != end - 1 && template.IndexOf ('}', widx) != end - 1)
367 throw new FormatException (String.Format ("Wildcard in UriTemplate is valid only if it is placed at the last part of the path: '{0}'", template));
368 List<string> list = null;
370 for (int i = index; i <= end; ) {
371 i = template.IndexOf ('{', i);
372 if (i < 0 || i > end)
374 if (i == prevEnd + 1)
375 throw new ArgumentException (String.Format ("The UriTemplate '{0}' contains adjacent templated segments, which is invalid.", template));
376 int e = template.IndexOf ('}', i + 1);
377 if (e < 0 || i > end)
378 throw new FormatException (String.Format ("Missing '}' in URI template '{0}'", template));
381 list = new List<string> ();
383 string name = template.Substring (i, e - i);
384 string uname = name.ToUpper (CultureInfo.InvariantCulture);
385 if (uname [0] == '*')
386 uname = wild_path_name = uname.Substring (1);
387 if (list.Contains (uname) || (path != null && path.Contains (uname)))
388 throw new InvalidOperationException (String.Format ("The URI template string contains duplicate template item {{'{0}'}}", name));
392 return list != null ? new ReadOnlyCollection<string> (list) : empty_strings;
395 void ParseQueryTemplate (string template, int index, int end)
397 // template starts with '?'
398 string [] parameters = template.Substring (index + 1, end - index - 1).Split ('&');
399 List<string> list = null;
400 foreach (string parameter in parameters) {
401 string [] pair = parameter.Split ('=');
402 if (pair.Length != 2)
403 throw new FormatException ("Invalid URI query string format");
404 string pname = pair [0];
405 string pvalue = pair [1];
406 if (pvalue.Length >= 2 && pvalue [0] == '{' && pvalue [pvalue.Length - 1] == '}') {
407 string ptemplate = pvalue.Substring (1, pvalue.Length - 2).ToUpper (CultureInfo.InvariantCulture);
408 query_params.Add (pname, ptemplate);
410 list = new List<string> ();
411 if (list.Contains (ptemplate) || (path != null && path.Contains (ptemplate)))
412 throw new InvalidOperationException (String.Format ("The URI template string contains duplicate template item {{'{0}'}}", pvalue));
413 list.Add (ptemplate);
416 query = list != null ? new ReadOnlyCollection<string> (list.ToArray ()) : empty_strings;