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;
38 public class UriTemplate
40 static readonly ReadOnlyCollection<string> empty_strings = new ReadOnlyCollection<string> (new string [0]);
43 ReadOnlyCollection<string> path, query;
44 string wild_path_name;
45 Dictionary<string,string> query_params = new Dictionary<string,string> ();
47 public UriTemplate (string template)
48 : this (template, false)
52 public UriTemplate (string template, IDictionary<string,string> additionalDefaults)
53 : this (template, false, additionalDefaults)
57 public UriTemplate (string template, bool ignoreTrailingSlash)
58 : this (template, ignoreTrailingSlash, null)
62 public UriTemplate (string template, bool ignoreTrailingSlash, IDictionary<string,string> additionalDefaults)
65 throw new ArgumentNullException ("template");
66 this.template = template;
67 IgnoreTrailingSlash = ignoreTrailingSlash;
68 Defaults = new Dictionary<string,string> (StringComparer.InvariantCultureIgnoreCase);
69 if (additionalDefaults != null)
70 foreach (var pair in additionalDefaults)
71 Defaults.Add (pair.Key, pair.Value);
74 // Trim scheme, host name and port if exist.
75 if (CultureInfo.InvariantCulture.CompareInfo.IsPrefix (template, "http")) {
76 int idx = template.IndexOf ('/', 8); // after "http://x" or "https://"
78 p = template.Substring (idx);
80 int q = p.IndexOf ('?');
81 path = ParsePathTemplate (p, 0, q >= 0 ? q : p.Length);
83 ParseQueryTemplate (p, q, p.Length);
85 query = empty_strings;
88 public bool IgnoreTrailingSlash { get; private set; }
90 public IDictionary<string,string> Defaults { get; private set; }
92 public ReadOnlyCollection<string> PathSegmentVariableNames {
96 public ReadOnlyCollection<string> QueryValueVariableNames {
100 public override string ToString ()
107 public Uri BindByName (Uri baseAddress, NameValueCollection parameters)
109 return BindByName (baseAddress, parameters, false);
112 public Uri BindByName (Uri baseAddress, NameValueCollection parameters, bool omitDefaults)
114 return BindByNameCommon (baseAddress, parameters, null, omitDefaults);
117 public Uri BindByName (Uri baseAddress, IDictionary<string,string> parameters)
119 return BindByName (baseAddress, parameters, false);
122 public Uri BindByName (Uri baseAddress, IDictionary<string,string> parameters, bool omitDefaults)
124 return BindByNameCommon (baseAddress, null, parameters, omitDefaults);
127 string SuffixEndRenderedUri (string s)
129 return s.Length > 0 && s [s.Length - 1] == '/' ? s : s + '/';
132 string TrimStartRenderedUri (StringBuilder sb)
138 return sb.ToString (1, sb.Length - 1);
140 return sb.ToString ();
143 Uri BindByNameCommon (Uri baseAddress, NameValueCollection nvc, IDictionary<string,string> dic, bool omitDefaults)
145 CheckBaseAddress (baseAddress);
147 // take care of case sensitivity.
149 dic = new Dictionary<string,string> (dic, StringComparer.OrdinalIgnoreCase);
152 StringBuilder sb = new StringBuilder (template.Length);
153 BindByName (ref src, sb, path, nvc, dic, omitDefaults, false);
154 BindByName (ref src, sb, query, nvc, dic, omitDefaults, true);
155 sb.Append (template.Substring (src));
156 return new Uri (SuffixEndRenderedUri (baseAddress.ToString ()) + TrimStartRenderedUri (sb));
159 void BindByName (ref int src, StringBuilder sb, ReadOnlyCollection<string> names, NameValueCollection nvc, IDictionary<string,string> dic, bool omitDefaults, bool query)
162 int idx = template.IndexOf ('?', src);
164 sb.Append (template.Substring (src, idx - src));
166 // note that it doesn't append '?'. It is added only when there is actual parameter binding.
170 foreach (string name in names) {
171 int s = template.IndexOf ('{', src);
172 int e = template.IndexOf ('}', s + 1);
173 string value = nvc != null ? nvc [name] : null;
176 dic.TryGetValue (name, out value);
179 if (value != null || (!omitDefaults && Defaults.TryGetValue (name, out value))) {
180 sb.Append (template.Substring (src, s - src));
184 if (value == null && (omitDefaults || !Defaults.TryGetValue (name, out value)))
185 throw new ArgumentException (string.Format("The argument name value collection does not contain non-null value for '{0}'", name), "parameters");
187 sb.Append (template.Substring (src, s - src));
194 public Uri BindByPosition (Uri baseAddress, params string [] values)
196 CheckBaseAddress (baseAddress);
198 if (values.Length != path.Count + query.Count)
199 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));
201 int src = 0, index = 0;
202 StringBuilder sb = new StringBuilder (template.Length);
203 BindByPosition (ref src, sb, path, values, ref index);
204 BindByPosition (ref src, sb, query, values, ref index);
205 sb.Append (template.Substring (src));
206 return new Uri (SuffixEndRenderedUri (baseAddress.ToString ()) + TrimStartRenderedUri (sb));
209 void BindByPosition (ref int src, StringBuilder sb, ReadOnlyCollection<string> names, string [] values, ref int index)
211 for (int i = 0; i < names.Count; i++) {
212 int s = template.IndexOf ('{', src);
213 int e = template.IndexOf ('}', s + 1);
214 sb.Append (template.Substring (src, s - src));
215 string value = values [index++];
217 throw new FormatException (String.Format ("The argument value collection contains null at {0}", index - 1));
225 public bool IsEquivalentTo (UriTemplate other)
228 throw new ArgumentNullException ("other");
229 return this.template == other.template;
234 static readonly char [] slashSep = {'/'};
236 public UriTemplateMatch Match (Uri baseAddress, Uri candidate)
238 CheckBaseAddress (baseAddress);
239 if (candidate == null)
240 throw new ArgumentNullException ("candidate");
242 var us = baseAddress.LocalPath;
243 if (us [us.Length - 1] != '/')
244 baseAddress = new Uri (
245 baseAddress.GetComponents (UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.UriEscaped) + '/' + baseAddress.Query,
246 baseAddress.IsAbsoluteUri ? UriKind.Absolute : UriKind.RelativeOrAbsolute
248 if (IgnoreTrailingSlash) {
249 us = candidate.LocalPath;
250 if (us.Length > 0 && us [us.Length - 1] != '/')
251 candidate = new Uri (
252 candidate.GetComponents (UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.UriEscaped) + '/' + candidate.Query,
253 candidate.IsAbsoluteUri ? UriKind.Absolute : UriKind.RelativeOrAbsolute
258 UriTemplateMatch m = new UriTemplateMatch ();
259 m.BaseUri = baseAddress;
261 m.RequestUri = candidate;
262 var vc = m.BoundVariables;
264 string cp = baseAddress.MakeRelativeUri (new Uri (
266 candidate.GetComponents (UriComponents.PathAndQuery, UriFormat.UriEscaped)
269 if (IgnoreTrailingSlash && cp [cp.Length - 1] == '/')
270 cp = cp.Substring (0, cp.Length - 1);
272 int tEndCp = cp.IndexOf ('?');
274 cp = cp.Substring (0, tEndCp);
276 if (template.Length > 0 && template [0] == '/')
278 if (cp.Length > 0 && cp [0] == '/')
281 foreach (string name in path) {
282 if (name == wild_path_name) {
283 vc [name] = Uri.UnescapeDataString (cp.Substring (c)); // all remaining paths.
286 int n = StringIndexOf (template, '{' + name + '}', i);
287 if (String.CompareOrdinal (cp, c, template, i, n - i) != 0)
288 return null; // doesn't match before current template part.
290 i = n + 2 + name.Length;
291 int ce = cp.IndexOf ('/', c);
294 string value = cp.Substring (c, ce - c);
295 string unescapedVaule = Uri.UnescapeDataString (value);
296 if (value.Length == 0)
297 return null; // empty => mismatch
298 vc [name] = unescapedVaule;
299 m.RelativePathSegments.Add (unescapedVaule);
302 int tEnd = template.IndexOf ('?');
303 int wildIdx = template.IndexOf ('*');
304 bool wild = wildIdx >= 0;
306 tEnd = template.Length;
308 tEnd = Math.Max (wildIdx - 1, 0);
309 if (!wild && (cp.Length - c) != (tEnd - i) ||
310 String.CompareOrdinal (cp, c, template, i, tEnd - i) != 0)
311 return null; // suffix doesn't match
314 foreach (var pe in cp.Substring (c).Split (slashSep, StringSplitOptions.RemoveEmptyEntries))
315 m.WildcardPathSegments.Add (pe);
317 if (candidate.Query.Length == 0)
321 string [] parameters = Uri.UnescapeDataString (candidate.Query.Substring (1)).Split ('&'); // chop first '?'
322 foreach (string parameter in parameters) {
323 string [] pair = parameter.Split ('=');
324 m.QueryParameters.Add (pair [0], pair [1]);
325 if (!query_params.ContainsKey (pair [0]))
327 string templateName = query_params [pair [0]];
328 vc.Add (templateName, pair [1]);
334 int StringIndexOf (string s, string pattern, int idx)
336 return CultureInfo.InvariantCulture.CompareInfo.IndexOf (s, pattern, idx, CompareOptions.OrdinalIgnoreCase);
341 void CheckBaseAddress (Uri baseAddress)
343 if (baseAddress == null)
344 throw new ArgumentNullException ("baseAddress");
345 if (!baseAddress.IsAbsoluteUri)
346 throw new ArgumentException ("baseAddress must be an absolute URI.");
347 if (baseAddress.Scheme == Uri.UriSchemeHttp ||
348 baseAddress.Scheme == Uri.UriSchemeHttps)
350 throw new ArgumentException ("baseAddress scheme must be either http or https.");
353 ReadOnlyCollection<string> ParsePathTemplate (string template, int index, int end)
355 int widx = template.IndexOf ('*', index, end);
357 if (widx != end - 1 && template.IndexOf ('}', widx) != end - 1)
358 throw new FormatException (String.Format ("Wildcard in UriTemplate is valid only if it is placed at the last part of the path: '{0}'", template));
359 List<string> list = null;
361 for (int i = index; i <= end; ) {
362 i = template.IndexOf ('{', i);
363 if (i < 0 || i > end)
365 if (i == prevEnd + 1)
366 throw new ArgumentException (String.Format ("The UriTemplate '{0}' contains adjacent templated segments, which is invalid.", template));
367 int e = template.IndexOf ('}', i + 1);
368 if (e < 0 || i > end)
369 throw new FormatException (String.Format ("Missing '}' in URI template '{0}'", template));
372 list = new List<string> ();
374 string name = template.Substring (i, e - i);
375 string uname = name.ToUpper (CultureInfo.InvariantCulture);
376 if (uname [0] == '*')
377 uname = wild_path_name = uname.Substring (1);
378 if (list.Contains (uname) || (path != null && path.Contains (uname)))
379 throw new InvalidOperationException (String.Format ("The URI template string contains duplicate template item {{'{0}'}}", name));
383 return list != null ? new ReadOnlyCollection<string> (list) : empty_strings;
386 void ParseQueryTemplate (string template, int index, int end)
388 // template starts with '?'
389 string [] parameters = template.Substring (index + 1, end - index - 1).Split ('&');
390 List<string> list = null;
391 foreach (string parameter in parameters) {
392 string [] pair = parameter.Split ('=');
393 if (pair.Length != 2)
394 throw new FormatException ("Invalid URI query string format");
395 string pname = pair [0];
396 string pvalue = pair [1];
397 if (pvalue.Length >= 2 && pvalue [0] == '{' && pvalue [pvalue.Length - 1] == '}') {
398 string ptemplate = pvalue.Substring (1, pvalue.Length - 2).ToUpper (CultureInfo.InvariantCulture);
399 query_params.Add (pname, ptemplate);
401 list = new List<string> ();
402 if (list.Contains (ptemplate) || (path != null && path.Contains (ptemplate)))
403 throw new InvalidOperationException (String.Format ("The URI template string contains duplicate template item {{'{0}'}}", pvalue));
404 list.Add (ptemplate);
407 query = list != null ? new ReadOnlyCollection<string> (list.ToArray ()) : empty_strings;