Add unit test for AggregateException.GetBaseException that works on .net but is broke...
[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                 public Uri BindByName (Uri baseAddress, NameValueCollection parameters)
112                 {
113                         return BindByName (baseAddress, parameters, false);
114                 }
115
116                 public Uri BindByName (Uri baseAddress, NameValueCollection parameters, bool omitDefaults)
117                 {
118                         return BindByNameCommon (baseAddress, parameters, null, omitDefaults);
119                 }
120
121                 public Uri BindByName (Uri baseAddress, IDictionary<string,string> parameters)
122                 {
123                         return BindByName (baseAddress, parameters, false);
124                 }
125
126                 public Uri BindByName (Uri baseAddress, IDictionary<string,string> parameters, bool omitDefaults)
127                 {
128                         return BindByNameCommon (baseAddress, null, parameters, omitDefaults);
129                 }
130
131                 string SuffixEndRenderedUri (string s)
132                 {
133                         return s.Length > 0 && s [s.Length - 1] == '/' ? s : s + '/';
134                 }
135
136                 string TrimStartRenderedUri (StringBuilder sb)
137                 {
138                         if (sb.Length == 0)
139                                 return String.Empty;
140                         
141                         if (sb [0] == '/')
142                                 return sb.ToString (1, sb.Length - 1);
143
144                         return sb.ToString ();
145                 }
146                 
147                 Uri BindByNameCommon (Uri baseAddress, NameValueCollection nvc, IDictionary<string,string> dic, bool omitDefaults)
148                 {
149                         CheckBaseAddress (baseAddress);
150
151                         // take care of case sensitivity.
152                         if (dic != null)
153                                 dic = new Dictionary<string,string> (dic, StringComparer.OrdinalIgnoreCase);
154
155                         int src = 0;
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));
161                 }
162
163                 void BindByName (ref int src, StringBuilder sb, ReadOnlyCollection<string> names, NameValueCollection nvc, IDictionary<string,string> dic, bool omitDefaults, bool query)
164                 {
165                         if (query) {
166                                 int idx = template.IndexOf ('?', src);
167                                 if (idx > 0) {
168                                         sb.Append (template.Substring (src, idx - src));
169                                         src = idx;
170                                         // note that it doesn't append '?'. It is added only when there is actual parameter binding.
171                                 }
172                         }
173
174                         foreach (string name in names) {
175                                 int s = template.IndexOf ('{', src);
176                                 int e = template.IndexOf ('}', s + 1);
177 #if NET_2_1
178                                 string value = null;
179 #else
180                                 string value = nvc != null ? nvc [name] : null;
181 #endif
182                                 if (dic != null)
183                                         dic.TryGetValue (name, out value);
184
185                                 if (query) {
186                                         if (value != null || (!omitDefaults && Defaults.TryGetValue (name, out value))) {
187                                                 sb.Append (template.Substring (src, s - src));
188                                                 sb.Append (value);
189                                         }
190                                 } else {
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");
193
194                                         sb.Append (template.Substring (src, s - src));
195                                         sb.Append (value);
196                                 }
197                                 src = e + 1;
198                         }
199                 }
200
201                 public Uri BindByPosition (Uri baseAddress, params string [] values)
202                 {
203                         CheckBaseAddress (baseAddress);
204
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));
207
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));
214                 }
215
216                 void BindByPosition (ref int src, StringBuilder sb, ReadOnlyCollection<string> names, string [] values, ref int index)
217                 {
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++];
223                                 if (value == null)
224                                         throw new FormatException (String.Format ("The argument value collection contains null at {0}", index - 1));
225                                 sb.Append (value);
226                                 src = e + 1;
227                         }
228                 }
229
230                 // Compare
231
232                 public bool IsEquivalentTo (UriTemplate other)
233                 {
234                         if (other == null)
235                                 throw new ArgumentNullException ("other");
236                         return this.template == other.template;
237                 }
238
239                 // Match
240
241                 static readonly char [] slashSep = {'/'};
242
243                 public UriTemplateMatch Match (Uri baseAddress, Uri candidate)
244                 {
245                         CheckBaseAddress (baseAddress);
246                         if (candidate == null)
247                                 throw new ArgumentNullException ("candidate");
248
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
254                                 );
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
261                                         );
262                         }
263
264                         int i = 0, c = 0;
265                         UriTemplateMatch m = new UriTemplateMatch ();
266                         m.BaseUri = baseAddress;
267                         m.Template = this;
268                         m.RequestUri = candidate;
269                         var vc = m.BoundVariables;
270
271                         string cp = baseAddress.MakeRelativeUri (new Uri (
272                                 baseAddress,
273                                 candidate.GetComponents (UriComponents.PathAndQuery, UriFormat.UriEscaped)
274                         ))
275                                 .ToString ();
276                         if (IgnoreTrailingSlash && cp [cp.Length - 1] == '/')
277                                 cp = cp.Substring (0, cp.Length - 1);
278
279                         int tEndCp = cp.IndexOf ('?');
280                         if (tEndCp >= 0)
281                                 cp = cp.Substring (0, tEndCp);
282
283                         if (template.Length > 0 && template [0] == '/')
284                                 i++;
285                         if (cp.Length > 0 && cp [0] == '/')
286                                 c++;
287
288                         foreach (string name in path) {
289                                 if (name == wild_path_name) {
290                                         vc [name] = Uri.UnescapeDataString (cp.Substring (c)); // all remaining paths.
291                                         continue;
292                                 }
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.
296                                 c += n - i;
297                                 i = n + 2 + name.Length;
298                                 int ce = cp.IndexOf ('/', c);
299                                 if (ce < 0)
300                                         ce = cp.Length;
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);
307                                 c += value.Length;
308                         }
309                         int tEnd = template.IndexOf ('?');
310                         int wildIdx = template.IndexOf ('*');
311                         bool wild = wildIdx >= 0;
312                         if (tEnd < 0)
313                                 tEnd = template.Length;
314                         if (wild)
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
319                         if (wild) {
320                                 c += tEnd - i;
321                                 foreach (var pe in cp.Substring (c).Split (slashSep, StringSplitOptions.RemoveEmptyEntries))
322                                         m.WildcardPathSegments.Add (pe);
323                         }
324                         if (candidate.Query.Length == 0)
325                                 return m;
326
327
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]))
333                                         continue;
334                                 string templateName = query_params [pair [0]];
335                                 vc.Add (templateName, pair [1]);
336                         }
337
338                         return m;
339                 }
340
341                 int StringIndexOf (string s, string pattern, int idx)
342                 {
343                         return CultureInfo.InvariantCulture.CompareInfo.IndexOf (s, pattern, idx, CompareOptions.OrdinalIgnoreCase);
344                 }
345
346                 // Helpers
347
348                 void CheckBaseAddress (Uri baseAddress)
349                 {
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)
356                                 return;
357                         throw new ArgumentException ("baseAddress scheme must be either http or https.");
358                 }
359
360                 ReadOnlyCollection<string> ParsePathTemplate (string template, int index, int end)
361                 {
362                         int widx = template.IndexOf ('*', index, end);
363                         if (widx >= 0)
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;
367                         int prevEnd = -2;
368                         for (int i = index; i <= end; ) {
369                                 i = template.IndexOf ('{', i);
370                                 if (i < 0 || i > end)
371                                         break;
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));
377                                 prevEnd = e;
378                                 if (list == null)
379                                         list = new List<string> ();
380                                 i++;
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));
387                                 list.Add (uname);
388                                 i = e + 1;
389                         }
390                         return list != null ? new ReadOnlyCollection<string> (list) : empty_strings;
391                 }
392
393                 void ParseQueryTemplate (string template, int index, int end)
394                 {
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);
407                                         if (list == null)
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);
412                                 }
413                         }
414                         query = list != null ? new ReadOnlyCollection<string> (list.ToArray ()) : empty_strings;
415                 }
416         }
417 }