Merge pull request #100 from Unity-Technologies/master-leak-descriptors
[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 //
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:
16 // 
17 // The above copyright notice and this permission notice shall be
18 // included in all copies or substantial portions of the Software.
19 // 
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.
27 //
28 using System;
29 using System.Collections.Generic;
30 using System.Collections.ObjectModel;
31 using System.Collections.Specialized;
32 using System.Globalization;
33 using System.Text;
34
35 #if NET_2_1
36 using NameValueCollection = System.Object;
37 #endif
38
39 namespace System
40 {
41         public class UriTemplate
42         {
43                 static readonly ReadOnlyCollection<string> empty_strings = new ReadOnlyCollection<string> (new string [0]);
44
45                 string template;
46                 ReadOnlyCollection<string> path, query;
47                 Dictionary<string,string> query_params = new Dictionary<string,string> ();
48
49                 public UriTemplate (string template)
50                         : this (template, false)
51                 {
52                 }
53
54                 public UriTemplate (string template, IDictionary<string,string> additionalDefaults)
55                         : this (template, false, additionalDefaults)
56                 {
57                 }
58
59                 public UriTemplate (string template, bool ignoreTrailingSlash)
60                         : this (template, ignoreTrailingSlash, null)
61                 {
62                 }
63
64                 public UriTemplate (string template, bool ignoreTrailingSlash, IDictionary<string,string> additionalDefaults)
65                 {
66                         if (template == null)
67                                 throw new ArgumentNullException ("template");
68                         this.template = template;
69                         IgnoreTrailingSlash = ignoreTrailingSlash;
70                         Defaults = new Dictionary<string,string> (StringComparer.InvariantCultureIgnoreCase);
71                         if (additionalDefaults != null)
72                                 foreach (var pair in additionalDefaults)
73                                         Defaults.Add (pair.Key, pair.Value);
74
75                         string p = template;
76                         // Trim scheme, host name and port if exist.
77                         if (CultureInfo.InvariantCulture.CompareInfo.IsPrefix (template, "http")) {
78                                 int idx = template.IndexOf ('/', 8); // after "http://x" or "https://"
79                                 if (idx > 0)
80                                         p = template.Substring (idx);
81                         }
82                         int q = p.IndexOf ('?');
83                         path = ParsePathTemplate (p, 0, q >= 0 ? q : p.Length);
84                         if (q >= 0)
85                                 ParseQueryTemplate (p, q, p.Length);
86                         else
87                                 query = empty_strings;
88                 }
89
90                 public bool IgnoreTrailingSlash { get; private set; }
91
92                 public IDictionary<string,string> Defaults { get; private set; }
93
94                 public ReadOnlyCollection<string> PathSegmentVariableNames {
95                         get { return path; }
96                 }
97
98                 public ReadOnlyCollection<string> QueryValueVariableNames {
99                         get { return query; }
100                 }
101
102                 public override string ToString ()
103                 {
104                         return template;
105                 }
106
107                 // Bind
108
109 #if !MOONLIGHT
110                 public Uri BindByName (Uri baseAddress, NameValueCollection parameters)
111                 {
112                         return BindByName (baseAddress, parameters, false);
113                 }
114
115                 public Uri BindByName (Uri baseAddress, NameValueCollection parameters, bool omitDefaults)
116                 {
117                         return BindByNameCommon (baseAddress, parameters, null, omitDefaults);
118                 }
119 #endif
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                         foreach (string name in names) {
166                                 int s = template.IndexOf ('{', src);
167                                 int e = template.IndexOf ('}', s + 1);
168 #if NET_2_1
169                                 string value = null;
170 #else
171                                 string value = nvc != null ? nvc [name] : null;
172 #endif
173                                 if (dic != null)
174                                         dic.TryGetValue (name, out value);
175                                 if (query) {
176                                         if (value != null || (!omitDefaults && Defaults.TryGetValue (name, out value))) {
177                                                 sb.Append (template.Substring (src, s - src));
178                                                 sb.Append (value);
179                                         }
180                                 } else
181                                         if (value == null && (omitDefaults || !Defaults.TryGetValue(name, out value)))
182                                                 throw new ArgumentException(string.Format("The argument name value collection does not contain non-nul vaalue for '{0}'", name), "parameters");
183                                         else {
184                                                 sb.Append (template.Substring (src, s - src));
185                                                 sb.Append (value);
186                                         }
187                                 src = e + 1;
188                         }
189                 }
190
191                 public Uri BindByPosition (Uri baseAddress, params string [] values)
192                 {
193                         CheckBaseAddress (baseAddress);
194
195                         if (values.Length != path.Count + query.Count)
196                                 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));
197
198                         int src = 0, index = 0;
199                         StringBuilder sb = new StringBuilder (template.Length);
200                         BindByPosition (ref src, sb, path, values, ref index);
201                         BindByPosition (ref src, sb, query, values, ref index);
202                         sb.Append (template.Substring (src));
203                         return new Uri (SuffixEndRenderedUri (baseAddress.ToString ()) + TrimStartRenderedUri (sb));
204                 }
205
206                 void BindByPosition (ref int src, StringBuilder sb, ReadOnlyCollection<string> names, string [] values, ref int index)
207                 {
208                         for (int i = 0; i < names.Count; i++) {
209                                 int s = template.IndexOf ('{', src);
210                                 int e = template.IndexOf ('}', s + 1);
211                                 sb.Append (template.Substring (src, s - src));
212                                 string value = values [index++];
213                                 if (value == null)
214                                         throw new FormatException (String.Format ("The argument value collection contains null at {0}", index - 1));
215                                 sb.Append (value);
216                                 src = e + 1;
217                         }
218                 }
219
220                 // Compare
221
222                 public bool IsEquivalentTo (UriTemplate other)
223                 {
224                         if (other == null)
225                                 throw new ArgumentNullException ("other");
226                         return this.template == other.template;
227                 }
228
229                 // Match
230
231                 static readonly char [] slashSep = {'/'};
232
233                 public UriTemplateMatch Match (Uri baseAddress, Uri candidate)
234                 {
235                         CheckBaseAddress (baseAddress);
236                         if (candidate == null)
237                                 throw new ArgumentNullException ("candidate");
238
239                         var us = baseAddress.LocalPath;
240                         if (us [us.Length - 1] != '/')
241                                 baseAddress = new Uri (baseAddress.GetComponents (UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.Unescaped) + '/' + baseAddress.Query, baseAddress.IsAbsoluteUri ? UriKind.Absolute : UriKind.RelativeOrAbsolute);
242                         if (IgnoreTrailingSlash) {
243                                 us = candidate.LocalPath;
244                                 if (us.Length > 0 && us [us.Length - 1] != '/')
245                                         candidate = new Uri(candidate.GetComponents (UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.Unescaped) + '/' + candidate.Query, candidate.IsAbsoluteUri ? UriKind.Absolute : UriKind.RelativeOrAbsolute);
246                         }
247
248                         int i = 0, c = 0;
249                         UriTemplateMatch m = new UriTemplateMatch ();
250                         m.BaseUri = baseAddress;
251                         m.Template = this;
252                         m.RequestUri = candidate;
253                         var vc = m.BoundVariables;
254
255                         string cp = Uri.UnescapeDataString (baseAddress.MakeRelativeUri (new Uri (baseAddress, candidate.GetComponents (UriComponents.PathAndQuery, UriFormat.Unescaped))).ToString ());
256                         if (IgnoreTrailingSlash && cp [cp.Length - 1] == '/')
257                                 cp = cp.Substring (0, cp.Length - 1);
258
259                         int tEndCp = cp.IndexOf ('?');
260                         if (tEndCp >= 0)
261                                 cp = cp.Substring (0, tEndCp);
262
263                         if (template.Length > 0 && template [0] == '/')
264                                 i++;
265                         if (cp.Length > 0 && cp [0] == '/')
266                                 c++;
267
268                         foreach (string name in path) {
269                                 int n = StringIndexOf (template, '{' + name + '}', i);
270                                 if (String.CompareOrdinal (cp, c, template, i, n - i) != 0)
271                                         return null; // doesn't match before current template part.
272                                 c += n - i;
273                                 i = n + 2 + name.Length;
274                                 int ce = cp.IndexOf ('/', c);
275                                 if (ce < 0)
276                                         ce = cp.Length;
277                                 string value = cp.Substring (c, ce - c);
278                                 if (value.Length == 0)
279                                         return null; // empty => mismatch
280                                 vc [name] = value;
281                                 m.RelativePathSegments.Add (value);
282                                 c += value.Length;
283                         }
284                         int tEnd = template.IndexOf ('?');
285                         if (tEnd < 0)
286                                 tEnd = template.Length;
287                         bool wild = (template [tEnd - 1] == '*');
288                         if (wild)
289                                 tEnd--;
290                         if (!wild && (cp.Length - c) != (tEnd - i) ||
291                             String.CompareOrdinal (cp, c, template, i, tEnd - i) != 0)
292                                 return null; // suffix doesn't match
293                         if (wild) {
294                                 c += tEnd - i;
295                                 foreach (var pe in cp.Substring (c).Split (slashSep, StringSplitOptions.RemoveEmptyEntries))
296                                         m.WildcardPathSegments.Add (pe);
297                         }
298                         if (candidate.Query.Length == 0)
299                                 return m;
300
301
302                         string [] parameters = Uri.UnescapeDataString (candidate.Query.Substring (1)).Split ('&'); // chop first '?'
303                         foreach (string parameter in parameters) {
304                                 string [] pair = parameter.Split ('=');
305                                 m.QueryParameters.Add (pair [0], pair [1]);
306                                 if (!query_params.ContainsKey (pair [0]))
307                                         continue;
308                                 string templateName = query_params [pair [0]];
309                                 vc.Add (templateName, pair [1]);
310                         }
311
312                         return m;
313                 }
314
315                 int StringIndexOf (string s, string pattern, int idx)
316                 {
317                         return CultureInfo.InvariantCulture.CompareInfo.IndexOf (s, pattern, idx, CompareOptions.OrdinalIgnoreCase);
318                 }
319
320                 // Helpers
321
322                 void CheckBaseAddress (Uri baseAddress)
323                 {
324                         if (baseAddress == null)
325                                 throw new ArgumentNullException ("baseAddress");
326                         if (!baseAddress.IsAbsoluteUri)
327                                 throw new ArgumentException ("baseAddress must be an absolute URI.");
328                         if (baseAddress.Scheme == Uri.UriSchemeHttp ||
329                             baseAddress.Scheme == Uri.UriSchemeHttps)
330                                 return;
331                         throw new ArgumentException ("baseAddress scheme must be either http or https.");
332                 }
333
334                 ReadOnlyCollection<string> ParsePathTemplate (string template, int index, int end)
335                 {
336                         int widx = template.IndexOf ('*', index, end);
337                         if (widx >= 0 && widx != end - 1)
338                                 throw new FormatException (String.Format ("Wildcard in UriTemplate is valid only if it is placed at the last part of the path: '{0}'", template));
339                         List<string> list = null;
340                         int prevEnd = -2;
341                         for (int i = index; i <= end; ) {
342                                 i = template.IndexOf ('{', i);
343                                 if (i < 0 || i > end)
344                                         break;
345                                 if (i == prevEnd + 1)
346                                         throw new ArgumentException (String.Format ("The UriTemplate '{0}' contains adjacent templated segments, which is invalid.", template));
347                                 int e = template.IndexOf ('}', i + 1);
348                                 if (e < 0 || i > end)
349                                         throw new FormatException (String.Format ("Missing '}' in URI template '{0}'", template));
350                                 prevEnd = e;
351                                 if (list == null)
352                                         list = new List<string> ();
353                                 i++;
354                                 string name = template.Substring (i, e - i);
355                                 string uname = name.ToUpper (CultureInfo.InvariantCulture);
356                                 if (list.Contains (uname) || (path != null && path.Contains (uname)))
357                                         throw new InvalidOperationException (String.Format ("The URI template string contains duplicate template item {{'{0}'}}", name));
358                                 list.Add (uname);
359                                 i = e + 1;
360                         }
361                         return list != null ? new ReadOnlyCollection<string> (list) : empty_strings;
362                 }
363
364                 void ParseQueryTemplate (string template, int index, int end)
365                 {
366                         // template starts with '?'
367                         string [] parameters = template.Substring (index + 1, end - index - 1).Split ('&');
368                         List<string> list = null;
369                         foreach (string parameter in parameters) {
370                                 string [] pair = parameter.Split ('=');
371                                 if (pair.Length != 2)
372                                         throw new FormatException ("Invalid URI query string format");
373                                 string pname = pair [0];
374                                 string pvalue = pair [1];
375                                 if (pvalue.Length >= 2 && pvalue [0] == '{' && pvalue [pvalue.Length - 1] == '}') {
376                                         string ptemplate = pvalue.Substring (1, pvalue.Length - 2).ToUpper (CultureInfo.InvariantCulture);
377                                         query_params.Add (pname, ptemplate);
378                                         if (list == null)
379                                                 list = new List<string> ();
380                                         if (list.Contains (ptemplate) || (path != null && path.Contains (ptemplate)))
381                                                 throw new InvalidOperationException (String.Format ("The URI template string contains duplicate template item {{'{0}'}}", pvalue));
382                                         list.Add (ptemplate);
383                                 }
384                         }
385                         query = list != null ? new ReadOnlyCollection<string> (list.ToArray ()) : empty_strings;
386                 }
387         }
388 }