5 // Atsushi Enomoto <atsushi@ximian.com>
7 // Copyright (C) 2008 Novell, Inc (http://www.novell.com)
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:
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
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.
29 using System.Collections.Generic;
30 using System.Collections.ObjectModel;
31 using System.Collections.Specialized;
32 using System.Globalization;
36 using NameValueCollection = System.Object;
41 public class UriTemplate
43 static readonly ReadOnlyCollection<string> empty_strings = new ReadOnlyCollection<string> (new string [0]);
46 ReadOnlyCollection<string> path, query;
47 string wild_path_name;
48 Dictionary<string,string> query_params = new Dictionary<string,string> ();
50 public UriTemplate (string template)
51 : this (template, false)
55 public UriTemplate (string template, IDictionary<string,string> additionalDefaults)
56 : this (template, false, additionalDefaults)
60 public UriTemplate (string template, bool ignoreTrailingSlash)
61 : this (template, ignoreTrailingSlash, null)
65 public UriTemplate (string template, bool ignoreTrailingSlash, IDictionary<string,string> additionalDefaults)
68 throw new ArgumentNullException ("template");
69 this.template = template;
70 IgnoreTrailingSlash = ignoreTrailingSlash;
71 Defaults = new Dictionary<string,string> (StringComparer.InvariantCultureIgnoreCase);
72 if (additionalDefaults != null)
73 foreach (var pair in additionalDefaults)
74 Defaults.Add (pair.Key, pair.Value);
77 // Trim scheme, host name and port if exist.
78 if (CultureInfo.InvariantCulture.CompareInfo.IsPrefix (template, "http")) {
79 int idx = template.IndexOf ('/', 8); // after "http://x" or "https://"
81 p = template.Substring (idx);
83 int q = p.IndexOf ('?');
84 path = ParsePathTemplate (p, 0, q >= 0 ? q : p.Length);
86 ParseQueryTemplate (p, q, p.Length);
88 query = empty_strings;
91 public bool IgnoreTrailingSlash { get; private set; }
93 public IDictionary<string,string> Defaults { get; private set; }
95 public ReadOnlyCollection<string> PathSegmentVariableNames {
99 public ReadOnlyCollection<string> QueryValueVariableNames {
100 get { return query; }
103 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);
122 public Uri BindByName (Uri baseAddress, IDictionary<string,string> parameters)
124 return BindByName (baseAddress, parameters, false);
127 public Uri BindByName (Uri baseAddress, IDictionary<string,string> parameters, bool omitDefaults)
129 return BindByNameCommon (baseAddress, null, parameters, omitDefaults);
132 string SuffixEndRenderedUri (string s)
134 return s.Length > 0 && s [s.Length - 1] == '/' ? s : s + '/';
137 string TrimStartRenderedUri (StringBuilder sb)
143 return sb.ToString (1, sb.Length - 1);
145 return sb.ToString ();
148 Uri BindByNameCommon (Uri baseAddress, NameValueCollection nvc, IDictionary<string,string> dic, bool omitDefaults)
150 CheckBaseAddress (baseAddress);
152 // take care of case sensitivity.
154 dic = new Dictionary<string,string> (dic, StringComparer.OrdinalIgnoreCase);
157 StringBuilder sb = new StringBuilder (template.Length);
158 BindByName (ref src, sb, path, nvc, dic, omitDefaults, false);
159 BindByName (ref src, sb, query, nvc, dic, omitDefaults, true);
160 sb.Append (template.Substring (src));
161 return new Uri (SuffixEndRenderedUri (baseAddress.ToString ()) + TrimStartRenderedUri (sb));
164 void BindByName (ref int src, StringBuilder sb, ReadOnlyCollection<string> names, NameValueCollection nvc, IDictionary<string,string> dic, bool omitDefaults, bool query)
166 foreach (string name in names) {
167 int s = template.IndexOf ('{', src);
168 int e = template.IndexOf ('}', s + 1);
172 string value = nvc != null ? nvc [name] : null;
175 dic.TryGetValue (name, out value);
177 if (value != null || (!omitDefaults && Defaults.TryGetValue (name, out value))) {
178 sb.Append (template.Substring (src, s - src));
182 if (value == null && (omitDefaults || !Defaults.TryGetValue(name, out value)))
183 throw new ArgumentException(string.Format("The argument name value collection does not contain non-nul vaalue for '{0}'", name), "parameters");
185 sb.Append (template.Substring (src, s - src));
192 public Uri BindByPosition (Uri baseAddress, params string [] values)
194 CheckBaseAddress (baseAddress);
196 if (values.Length != path.Count + query.Count)
197 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));
199 int src = 0, index = 0;
200 StringBuilder sb = new StringBuilder (template.Length);
201 BindByPosition (ref src, sb, path, values, ref index);
202 BindByPosition (ref src, sb, query, values, ref index);
203 sb.Append (template.Substring (src));
204 return new Uri (SuffixEndRenderedUri (baseAddress.ToString ()) + TrimStartRenderedUri (sb));
207 void BindByPosition (ref int src, StringBuilder sb, ReadOnlyCollection<string> names, string [] values, ref int index)
209 for (int i = 0; i < names.Count; i++) {
210 int s = template.IndexOf ('{', src);
211 int e = template.IndexOf ('}', s + 1);
212 sb.Append (template.Substring (src, s - src));
213 string value = values [index++];
215 throw new FormatException (String.Format ("The argument value collection contains null at {0}", index - 1));
223 public bool IsEquivalentTo (UriTemplate other)
226 throw new ArgumentNullException ("other");
227 return this.template == other.template;
232 static readonly char [] slashSep = {'/'};
234 public UriTemplateMatch Match (Uri baseAddress, Uri candidate)
236 CheckBaseAddress (baseAddress);
237 if (candidate == null)
238 throw new ArgumentNullException ("candidate");
240 var us = baseAddress.LocalPath;
241 if (us [us.Length - 1] != '/')
242 baseAddress = new Uri (baseAddress.GetComponents (UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.Unescaped) + '/' + baseAddress.Query, baseAddress.IsAbsoluteUri ? UriKind.Absolute : UriKind.RelativeOrAbsolute);
243 if (IgnoreTrailingSlash) {
244 us = candidate.LocalPath;
245 if (us.Length > 0 && us [us.Length - 1] != '/')
246 candidate = new Uri(candidate.GetComponents (UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.Unescaped) + '/' + candidate.Query, candidate.IsAbsoluteUri ? UriKind.Absolute : UriKind.RelativeOrAbsolute);
250 UriTemplateMatch m = new UriTemplateMatch ();
251 m.BaseUri = baseAddress;
253 m.RequestUri = candidate;
254 var vc = m.BoundVariables;
256 string cp = Uri.UnescapeDataString (baseAddress.MakeRelativeUri (new Uri (baseAddress, candidate.GetComponents (UriComponents.PathAndQuery, UriFormat.Unescaped))).ToString ());
257 if (IgnoreTrailingSlash && cp [cp.Length - 1] == '/')
258 cp = cp.Substring (0, cp.Length - 1);
260 int tEndCp = cp.IndexOf ('?');
262 cp = cp.Substring (0, tEndCp);
264 if (template.Length > 0 && template [0] == '/')
266 if (cp.Length > 0 && cp [0] == '/')
269 foreach (string name in path) {
270 if (name == wild_path_name) {
271 vc [name] = cp.Substring (c); // all remaining paths.
274 int n = StringIndexOf (template, '{' + name + '}', i);
275 if (String.CompareOrdinal (cp, c, template, i, n - i) != 0)
276 return null; // doesn't match before current template part.
278 i = n + 2 + name.Length;
279 int ce = cp.IndexOf ('/', c);
282 string value = cp.Substring (c, ce - c);
283 if (value.Length == 0)
284 return null; // empty => mismatch
286 m.RelativePathSegments.Add (value);
289 int tEnd = template.IndexOf ('?');
290 int wildIdx = template.IndexOf ('*');
291 bool wild = wildIdx >= 0;
293 tEnd = template.Length;
296 if (!wild && (cp.Length - c) != (tEnd - i) ||
297 String.CompareOrdinal (cp, c, template, i, tEnd - i) != 0)
298 return null; // suffix doesn't match
301 foreach (var pe in cp.Substring (c).Split (slashSep, StringSplitOptions.RemoveEmptyEntries))
302 m.WildcardPathSegments.Add (pe);
304 if (candidate.Query.Length == 0)
308 string [] parameters = Uri.UnescapeDataString (candidate.Query.Substring (1)).Split ('&'); // chop first '?'
309 foreach (string parameter in parameters) {
310 string [] pair = parameter.Split ('=');
311 m.QueryParameters.Add (pair [0], pair [1]);
312 if (!query_params.ContainsKey (pair [0]))
314 string templateName = query_params [pair [0]];
315 vc.Add (templateName, pair [1]);
321 int StringIndexOf (string s, string pattern, int idx)
323 return CultureInfo.InvariantCulture.CompareInfo.IndexOf (s, pattern, idx, CompareOptions.OrdinalIgnoreCase);
328 void CheckBaseAddress (Uri baseAddress)
330 if (baseAddress == null)
331 throw new ArgumentNullException ("baseAddress");
332 if (!baseAddress.IsAbsoluteUri)
333 throw new ArgumentException ("baseAddress must be an absolute URI.");
334 if (baseAddress.Scheme == Uri.UriSchemeHttp ||
335 baseAddress.Scheme == Uri.UriSchemeHttps)
337 throw new ArgumentException ("baseAddress scheme must be either http or https.");
340 ReadOnlyCollection<string> ParsePathTemplate (string template, int index, int end)
342 int widx = template.IndexOf ('*', index, end);
344 if (widx != end - 1 && template.IndexOf ('}', widx) != end - 1)
345 throw new FormatException (String.Format ("Wildcard in UriTemplate is valid only if it is placed at the last part of the path: '{0}'", template));
346 List<string> list = null;
348 for (int i = index; i <= end; ) {
349 i = template.IndexOf ('{', i);
350 if (i < 0 || i > end)
352 if (i == prevEnd + 1)
353 throw new ArgumentException (String.Format ("The UriTemplate '{0}' contains adjacent templated segments, which is invalid.", template));
354 int e = template.IndexOf ('}', i + 1);
355 if (e < 0 || i > end)
356 throw new FormatException (String.Format ("Missing '}' in URI template '{0}'", template));
359 list = new List<string> ();
361 string name = template.Substring (i, e - i);
362 string uname = name.ToUpper (CultureInfo.InvariantCulture);
363 if (uname [0] == '*')
364 uname = wild_path_name = uname.Substring (1);
365 if (list.Contains (uname) || (path != null && path.Contains (uname)))
366 throw new InvalidOperationException (String.Format ("The URI template string contains duplicate template item {{'{0}'}}", name));
370 return list != null ? new ReadOnlyCollection<string> (list) : empty_strings;
373 void ParseQueryTemplate (string template, int index, int end)
375 // template starts with '?'
376 string [] parameters = template.Substring (index + 1, end - index - 1).Split ('&');
377 List<string> list = null;
378 foreach (string parameter in parameters) {
379 string [] pair = parameter.Split ('=');
380 if (pair.Length != 2)
381 throw new FormatException ("Invalid URI query string format");
382 string pname = pair [0];
383 string pvalue = pair [1];
384 if (pvalue.Length >= 2 && pvalue [0] == '{' && pvalue [pvalue.Length - 1] == '}') {
385 string ptemplate = pvalue.Substring (1, pvalue.Length - 2).ToUpper (CultureInfo.InvariantCulture);
386 query_params.Add (pname, ptemplate);
388 list = new List<string> ();
389 if (list.Contains (ptemplate) || (path != null && path.Contains (ptemplate)))
390 throw new InvalidOperationException (String.Format ("The URI template string contains duplicate template item {{'{0}'}}", pvalue));
391 list.Add (ptemplate);
394 query = list != null ? new ReadOnlyCollection<string> (list.ToArray ()) : empty_strings;