Merge pull request #347 from JamesB7/master
[mono.git] / mcs / class / System.ServiceModel.Web / System / UriTemplate.cs
1 //
2 // UriTemplate.cs
3 //
4 // Author:
5 //      Atsushi Enomoto  <atsushi@ximian.com>
6 //
7 // Copyright (C) 2008 Novell, Inc (http://www.novell.com)
8 // Copyright 2011 Xamarin Inc (http://www.xamarin.com).
9 //
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:
17 // 
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
20 // 
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.
28 //
29 using System;
30 using System.Collections.Generic;
31 using System.Collections.ObjectModel;
32 using System.Collections.Specialized;
33 using System.Globalization;
34 using System.Text;
35
36 #if NET_2_1
37 using NameValueCollection = System.Object;
38 #endif
39
40 namespace System
41 {
42         public class UriTemplate
43         {
44                 static readonly ReadOnlyCollection<string> empty_strings = new ReadOnlyCollection<string> (new string [0]);
45
46                 string template;
47                 ReadOnlyCollection<string> path, query;
48                 string wild_path_name;
49                 Dictionary<string,string> query_params = new Dictionary<string,string> ();
50
51                 public UriTemplate (string template)
52                         : this (template, false)
53                 {
54                 }
55
56                 public UriTemplate (string template, IDictionary<string,string> additionalDefaults)
57                         : this (template, false, additionalDefaults)
58                 {
59                 }
60
61                 public UriTemplate (string template, bool ignoreTrailingSlash)
62                         : this (template, ignoreTrailingSlash, null)
63                 {
64                 }
65
66                 public UriTemplate (string template, bool ignoreTrailingSlash, IDictionary<string,string> additionalDefaults)
67                 {
68                         if (template == null)
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);
76
77                         string p = template;
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://"
81                                 if (idx > 0)
82                                         p = template.Substring (idx);
83                         }
84                         int q = p.IndexOf ('?');
85                         path = ParsePathTemplate (p, 0, q >= 0 ? q : p.Length);
86                         if (q >= 0)
87                                 ParseQueryTemplate (p, q, p.Length);
88                         else
89                                 query = empty_strings;
90                 }
91
92                 public bool IgnoreTrailingSlash { get; private set; }
93
94                 public IDictionary<string,string> Defaults { get; private set; }
95
96                 public ReadOnlyCollection<string> PathSegmentVariableNames {
97                         get { return path; }
98                 }
99
100                 public ReadOnlyCollection<string> QueryValueVariableNames {
101                         get { return query; }
102                 }
103
104                 public override string ToString ()
105                 {
106                         return template;
107                 }
108
109                 // Bind
110
111 #if !MOONLIGHT
112                 public Uri BindByName (Uri baseAddress, NameValueCollection parameters)
113                 {
114                         return BindByName (baseAddress, parameters, false);
115                 }
116
117                 public Uri BindByName (Uri baseAddress, NameValueCollection parameters, bool omitDefaults)
118                 {
119                         return BindByNameCommon (baseAddress, parameters, null, omitDefaults);
120                 }
121 #endif
122
123                 public Uri BindByName (Uri baseAddress, IDictionary<string,string> parameters)
124                 {
125                         return BindByName (baseAddress, parameters, false);
126                 }
127
128                 public Uri BindByName (Uri baseAddress, IDictionary<string,string> parameters, bool omitDefaults)
129                 {
130                         return BindByNameCommon (baseAddress, null, parameters, omitDefaults);
131                 }
132
133                 string SuffixEndRenderedUri (string s)
134                 {
135                         return s.Length > 0 && s [s.Length - 1] == '/' ? s : s + '/';
136                 }
137
138                 string TrimStartRenderedUri (StringBuilder sb)
139                 {
140                         if (sb.Length == 0)
141                                 return String.Empty;
142                         
143                         if (sb [0] == '/')
144                                 return sb.ToString (1, sb.Length - 1);
145
146                         return sb.ToString ();
147                 }
148                 
149                 Uri BindByNameCommon (Uri baseAddress, NameValueCollection nvc, IDictionary<string,string> dic, bool omitDefaults)
150                 {
151                         CheckBaseAddress (baseAddress);
152
153                         // take care of case sensitivity.
154                         if (dic != null)
155                                 dic = new Dictionary<string,string> (dic, StringComparer.OrdinalIgnoreCase);
156
157                         int src = 0;
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));
163                 }
164
165                 void BindByName (ref int src, StringBuilder sb, ReadOnlyCollection<string> names, NameValueCollection nvc, IDictionary<string,string> dic, bool omitDefaults, bool query)
166                 {
167                         if (query) {
168                                 int idx = template.IndexOf ('?', src);
169                                 if (idx > 0) {
170                                         sb.Append (template.Substring (src, idx - src));
171                                         src = idx;
172                                         // note that it doesn't append '?'. It is added only when there is actual parameter binding.
173                                 }
174                         }
175
176                         foreach (string name in names) {
177                                 int s = template.IndexOf ('{', src);
178                                 int e = template.IndexOf ('}', s + 1);
179 #if NET_2_1
180                                 string value = null;
181 #else
182                                 string value = nvc != null ? nvc [name] : null;
183 #endif
184                                 if (dic != null)
185                                         dic.TryGetValue (name, out value);
186
187                                 if (query) {
188                                         if (value != null || (!omitDefaults && Defaults.TryGetValue (name, out value))) {
189                                                 sb.Append (template.Substring (src, s - src));
190                                                 sb.Append (value);
191                                         }
192                                 } else {
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");
195
196                                         sb.Append (template.Substring (src, s - src));
197                                         sb.Append (value);
198                                 }
199                                 src = e + 1;
200                         }
201                 }
202
203                 public Uri BindByPosition (Uri baseAddress, params string [] values)
204                 {
205                         CheckBaseAddress (baseAddress);
206
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));
209
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));
216                 }
217
218                 void BindByPosition (ref int src, StringBuilder sb, ReadOnlyCollection<string> names, string [] values, ref int index)
219                 {
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++];
225                                 if (value == null)
226                                         throw new FormatException (String.Format ("The argument value collection contains null at {0}", index - 1));
227                                 sb.Append (value);
228                                 src = e + 1;
229                         }
230                 }
231
232                 // Compare
233
234                 public bool IsEquivalentTo (UriTemplate other)
235                 {
236                         if (other == null)
237                                 throw new ArgumentNullException ("other");
238                         return this.template == other.template;
239                 }
240
241                 // Match
242
243                 static readonly char [] slashSep = {'/'};
244
245                 public UriTemplateMatch Match (Uri baseAddress, Uri candidate)
246                 {
247                         CheckBaseAddress (baseAddress);
248                         if (candidate == null)
249                                 throw new ArgumentNullException ("candidate");
250
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
256                                 );
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
263                                         );
264                         }
265
266                         int i = 0, c = 0;
267                         UriTemplateMatch m = new UriTemplateMatch ();
268                         m.BaseUri = baseAddress;
269                         m.Template = this;
270                         m.RequestUri = candidate;
271                         var vc = m.BoundVariables;
272
273                         string cp = baseAddress.MakeRelativeUri (new Uri (
274                                 baseAddress,
275                                 candidate.GetComponents (UriComponents.PathAndQuery, UriFormat.UriEscaped)
276                         ))
277                                 .ToString ();
278                         if (IgnoreTrailingSlash && cp [cp.Length - 1] == '/')
279                                 cp = cp.Substring (0, cp.Length - 1);
280
281                         int tEndCp = cp.IndexOf ('?');
282                         if (tEndCp >= 0)
283                                 cp = cp.Substring (0, tEndCp);
284
285                         if (template.Length > 0 && template [0] == '/')
286                                 i++;
287                         if (cp.Length > 0 && cp [0] == '/')
288                                 c++;
289
290                         foreach (string name in path) {
291                                 if (name == wild_path_name) {
292                                         vc [name] = Uri.UnescapeDataString (cp.Substring (c)); // all remaining paths.
293                                         continue;
294                                 }
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.
298                                 c += n - i;
299                                 i = n + 2 + name.Length;
300                                 int ce = cp.IndexOf ('/', c);
301                                 if (ce < 0)
302                                         ce = cp.Length;
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);
309                                 c += value.Length;
310                         }
311                         int tEnd = template.IndexOf ('?');
312                         int wildIdx = template.IndexOf ('*');
313                         bool wild = wildIdx >= 0;
314                         if (tEnd < 0)
315                                 tEnd = template.Length;
316                         if (wild)
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
321                         if (wild) {
322                                 c += tEnd - i;
323                                 foreach (var pe in cp.Substring (c).Split (slashSep, StringSplitOptions.RemoveEmptyEntries))
324                                         m.WildcardPathSegments.Add (pe);
325                         }
326                         if (candidate.Query.Length == 0)
327                                 return m;
328
329
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]))
335                                         continue;
336                                 string templateName = query_params [pair [0]];
337                                 vc.Add (templateName, pair [1]);
338                         }
339
340                         return m;
341                 }
342
343                 int StringIndexOf (string s, string pattern, int idx)
344                 {
345                         return CultureInfo.InvariantCulture.CompareInfo.IndexOf (s, pattern, idx, CompareOptions.OrdinalIgnoreCase);
346                 }
347
348                 // Helpers
349
350                 void CheckBaseAddress (Uri baseAddress)
351                 {
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)
358                                 return;
359                         throw new ArgumentException ("baseAddress scheme must be either http or https.");
360                 }
361
362                 ReadOnlyCollection<string> ParsePathTemplate (string template, int index, int end)
363                 {
364                         int widx = template.IndexOf ('*', index, end);
365                         if (widx >= 0)
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;
369                         int prevEnd = -2;
370                         for (int i = index; i <= end; ) {
371                                 i = template.IndexOf ('{', i);
372                                 if (i < 0 || i > end)
373                                         break;
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));
379                                 prevEnd = e;
380                                 if (list == null)
381                                         list = new List<string> ();
382                                 i++;
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));
389                                 list.Add (uname);
390                                 i = e + 1;
391                         }
392                         return list != null ? new ReadOnlyCollection<string> (list) : empty_strings;
393                 }
394
395                 void ParseQueryTemplate (string template, int index, int end)
396                 {
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);
409                                         if (list == null)
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);
414                                 }
415                         }
416                         query = list != null ? new ReadOnlyCollection<string> (list.ToArray ()) : empty_strings;
417                 }
418         }
419 }