Merge branch 'master' of github.com:mono/mono into masterwork
[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 !NET_2_1
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                 Uri BindByNameCommon (Uri baseAddress, NameValueCollection nvc, IDictionary<string,string> dic, bool omitDefaults)
132                 {
133                         CheckBaseAddress (baseAddress);
134
135                         // take care of case sensitivity.
136                         if (dic != null)
137                                 dic = new Dictionary<string,string> (dic, StringComparer.OrdinalIgnoreCase);
138
139                         int src = 0;
140                         StringBuilder sb = new StringBuilder (template.Length);
141                         BindByName (ref src, sb, path, nvc, dic, omitDefaults, false);
142                         BindByName (ref src, sb, query, nvc, dic, omitDefaults, true);
143                         sb.Append (template.Substring (src));
144                         return new Uri (baseAddress.ToString () + sb.ToString ());
145                 }
146
147                 void BindByName (ref int src, StringBuilder sb, ReadOnlyCollection<string> names, NameValueCollection nvc, IDictionary<string,string> dic, bool omitDefaults, bool query)
148                 {
149                         foreach (string name in names) {
150                                 int s = template.IndexOf ('{', src);
151                                 int e = template.IndexOf ('}', s + 1);
152 #if NET_2_1
153                                 string value = null;
154 #else
155                                 string value = nvc != null ? nvc [name] : null;
156 #endif
157                                 if (dic != null)
158                                         dic.TryGetValue (name, out value);
159                                 if (query) {
160                                         if (value != null || (!omitDefaults && Defaults.TryGetValue (name, out value))) {
161                                                 sb.Append (template.Substring (src, s - src));
162                                                 sb.Append (value);
163                                         }
164                                 } else
165                                         if (value == null && (omitDefaults || !Defaults.TryGetValue(name, out value)))
166                                                 throw new ArgumentException(string.Format("The argument name value collection does not contain non-nul vaalue for '{0}'", name), "parameters");
167                                         else {
168                                                 sb.Append (template.Substring (src, s - src));
169                                                 sb.Append (value);
170                                         }
171                                 src = e + 1;
172                         }
173                 }
174
175                 public Uri BindByPosition (Uri baseAddress, params string [] values)
176                 {
177                         CheckBaseAddress (baseAddress);
178
179                         if (values.Length != path.Count + query.Count)
180                                 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));
181
182                         int src = 0, index = 0;
183                         StringBuilder sb = new StringBuilder (template.Length);
184                         BindByPosition (ref src, sb, path, values, ref index);
185                         BindByPosition (ref src, sb, query, values, ref index);
186                         sb.Append (template.Substring (src));
187                         return new Uri (baseAddress.ToString () + sb.ToString ());
188                 }
189
190                 void BindByPosition (ref int src, StringBuilder sb, ReadOnlyCollection<string> names, string [] values, ref int index)
191                 {
192                         for (int i = 0; i < names.Count; i++) {
193                                 int s = template.IndexOf ('{', src);
194                                 int e = template.IndexOf ('}', s + 1);
195                                 sb.Append (template.Substring (src, s - src));
196                                 string value = values [index++];
197                                 if (value == null)
198                                         throw new FormatException (String.Format ("The argument value collection contains null at {0}", index - 1));
199                                 sb.Append (value);
200                                 src = e + 1;
201                         }
202                 }
203
204                 // Compare
205
206                 public bool IsEquivalentTo (UriTemplate other)
207                 {
208                         if (other == null)
209                                 throw new ArgumentNullException ("other");
210                         return this.template == other.template;
211                 }
212
213                 // Match
214
215                 static readonly char [] slashSep = {'/'};
216
217                 public UriTemplateMatch Match (Uri baseAddress, Uri candidate)
218                 {
219                         CheckBaseAddress (baseAddress);
220                         if (candidate == null)
221                                 throw new ArgumentNullException ("candidate");
222
223                         var us = baseAddress.LocalPath;
224                         if (us [us.Length - 1] != '/')
225                                 baseAddress = new Uri (baseAddress.GetComponents (UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.Unescaped) + '/' + baseAddress.Query, baseAddress.IsAbsoluteUri ? UriKind.Absolute : UriKind.RelativeOrAbsolute);
226                         if (IgnoreTrailingSlash) {
227                                 us = candidate.LocalPath;
228                                 if (us.Length > 0 && us [us.Length - 1] != '/')
229                                         candidate = new Uri(candidate.GetComponents (UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.Unescaped) + '/' + candidate.Query, candidate.IsAbsoluteUri ? UriKind.Absolute : UriKind.RelativeOrAbsolute);
230                         }
231
232                         if (Uri.Compare (baseAddress, candidate, UriComponents.StrongAuthority, UriFormat.SafeUnescaped, StringComparison.Ordinal) != 0)
233                                 return null;
234
235                         int i = 0, c = 0;
236                         UriTemplateMatch m = new UriTemplateMatch ();
237                         m.BaseUri = baseAddress;
238                         m.Template = this;
239                         m.RequestUri = candidate;
240                         var vc = m.BoundVariables;
241
242                         string cp = Uri.UnescapeDataString (baseAddress.MakeRelativeUri (candidate).ToString ());
243                         if (IgnoreTrailingSlash && cp [cp.Length - 1] == '/')
244                                 cp = cp.Substring (0, cp.Length - 1);
245
246                         int tEndCp = cp.IndexOf ('?');
247                         if (tEndCp >= 0)
248                                 cp = cp.Substring (0, tEndCp);
249
250                         if (template.Length > 0 && template [0] == '/')
251                                 i++;
252                         if (cp.Length > 0 && cp [0] == '/')
253                                 c++;
254
255                         foreach (string name in path) {
256                                 int n = StringIndexOf (template, '{' + name + '}', i);
257                                 if (String.CompareOrdinal (cp, c, template, i, n - i) != 0)
258                                         return null; // doesn't match before current template part.
259                                 c += n - i;
260                                 i = n + 2 + name.Length;
261                                 int ce = cp.IndexOf ('/', c);
262                                 if (ce < 0)
263                                         ce = cp.Length;
264                                 string value = cp.Substring (c, ce - c);
265                                 if (value.Length == 0)
266                                         return null; // empty => mismatch
267                                 vc [name] = value;
268                                 m.RelativePathSegments.Add (value);
269                                 c += value.Length;
270                         }
271                         int tEnd = template.IndexOf ('?');
272                         if (tEnd < 0)
273                                 tEnd = template.Length;
274                         bool wild = (template [tEnd - 1] == '*');
275                         if (wild)
276                                 tEnd--;
277                         if (!wild && (cp.Length - c) != (tEnd - i) ||
278                             String.CompareOrdinal (cp, c, template, i, tEnd - i) != 0)
279                                 return null; // suffix doesn't match
280                         if (wild) {
281                                 c += tEnd - i;
282                                 foreach (var pe in cp.Substring (c).Split (slashSep, StringSplitOptions.RemoveEmptyEntries))
283                                         m.WildcardPathSegments.Add (pe);
284                         }
285                         if (candidate.Query.Length == 0)
286                                 return m;
287
288
289                         string [] parameters = Uri.UnescapeDataString (candidate.Query.Substring (1)).Split ('&'); // chop first '?'
290                         foreach (string parameter in parameters) {
291                                 string [] pair = parameter.Split ('=');
292                                 m.QueryParameters.Add (pair [0], pair [1]);
293                                 if (!query_params.ContainsKey (pair [0]))
294                                         continue;
295                                 string templateName = query_params [pair [0]];
296                                 vc.Add (templateName, pair [1]);
297                         }
298
299                         return m;
300                 }
301
302                 int StringIndexOf (string s, string pattern, int idx)
303                 {
304                         return CultureInfo.InvariantCulture.CompareInfo.IndexOf (s, pattern, idx, CompareOptions.OrdinalIgnoreCase);
305                 }
306
307                 // Helpers
308
309                 void CheckBaseAddress (Uri baseAddress)
310                 {
311                         if (baseAddress == null)
312                                 throw new ArgumentNullException ("baseAddress");
313                         if (!baseAddress.IsAbsoluteUri)
314                                 throw new ArgumentException ("baseAddress must be an absolute URI.");
315                         if (baseAddress.Scheme == Uri.UriSchemeHttp ||
316                             baseAddress.Scheme == Uri.UriSchemeHttps)
317                                 return;
318                         throw new ArgumentException ("baseAddress scheme must be either http or https.");
319                 }
320
321                 ReadOnlyCollection<string> ParsePathTemplate (string template, int index, int end)
322                 {
323                         int widx = template.IndexOf ('*', index, end);
324                         if (widx >= 0 && widx != end - 1)
325                                 throw new FormatException (String.Format ("Wildcard in UriTemplate is valid only if it is placed at the last part of the path: '{0}'", template));
326                         List<string> list = null;
327                         int prevEnd = -2;
328                         for (int i = index; i <= end; ) {
329                                 i = template.IndexOf ('{', i);
330                                 if (i < 0 || i > end)
331                                         break;
332                                 if (i == prevEnd + 1)
333                                         throw new ArgumentException (String.Format ("The UriTemplate '{0}' contains adjacent templated segments, which is invalid.", template));
334                                 int e = template.IndexOf ('}', i + 1);
335                                 if (e < 0 || i > end)
336                                         throw new FormatException (String.Format ("Missing '}' in URI template '{0}'", template));
337                                 prevEnd = e;
338                                 if (list == null)
339                                         list = new List<string> ();
340                                 i++;
341                                 string name = template.Substring (i, e - i);
342                                 string uname = name.ToUpper (CultureInfo.InvariantCulture);
343                                 if (list.Contains (uname) || (path != null && path.Contains (uname)))
344                                         throw new InvalidOperationException (String.Format ("The URI template string contains duplicate template item {{'{0}'}}", name));
345                                 list.Add (uname);
346                                 i = e + 1;
347                         }
348                         return list != null ? new ReadOnlyCollection<string> (list) : empty_strings;
349                 }
350
351                 void ParseQueryTemplate (string template, int index, int end)
352                 {
353                         // template starts with '?'
354                         string [] parameters = template.Substring (index + 1, end - index - 1).Split ('&');
355                         List<string> list = null;
356                         foreach (string parameter in parameters) {
357                                 string [] pair = parameter.Split ('=');
358                                 if (pair.Length != 2)
359                                         throw new FormatException ("Invalid URI query string format");
360                                 string pname = pair [0];
361                                 string pvalue = pair [1];
362                                 if (pvalue.Length >= 2 && pvalue [0] == '{' && pvalue [pvalue.Length - 1] == '}') {
363                                         string ptemplate = pvalue.Substring (1, pvalue.Length - 2).ToUpper (CultureInfo.InvariantCulture);
364                                         query_params.Add (pname, ptemplate);
365                                         if (list == null)
366                                                 list = new List<string> ();
367                                         if (list.Contains (ptemplate) || (path != null && path.Contains (ptemplate)))
368                                                 throw new InvalidOperationException (String.Format ("The URI template string contains duplicate template item {{'{0}'}}", pvalue));
369                                         list.Add (ptemplate);
370                                 }
371                         }
372                         query = list != null ? new ReadOnlyCollection<string> (list.ToArray ()) : empty_strings;
373                 }
374         }
375 }