All files
[pithos-ms-client] / trunk / Libraries / Json40r2 / Source / Src / Newtonsoft.Json / Schema / JsonSchemaBuilder.cs
1 #region License
2 // Copyright (c) 2007 James Newton-King
3 //
4 // Permission is hereby granted, free of charge, to any person
5 // obtaining a copy of this software and associated documentation
6 // files (the "Software"), to deal in the Software without
7 // restriction, including without limitation the rights to use,
8 // copy, modify, merge, publish, distribute, sublicense, and/or sell
9 // copies of the Software, and to permit persons to whom the
10 // Software is furnished to do so, subject to the following
11 // conditions:
12 //
13 // The above copyright notice and this permission notice shall be
14 // included in all copies or substantial portions of the Software.
15 //
16 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
18 // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
20 // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
21 // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22 // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
23 // OTHER DEALINGS IN THE SOFTWARE.
24 #endregion
25
26 using System;
27 using System.Collections.Generic;
28 using System.Linq;
29 using System.Text;
30 using System.Globalization;
31 using Newtonsoft.Json.Utilities;
32 using Newtonsoft.Json.Linq;
33
34 namespace Newtonsoft.Json.Schema
35 {
36   internal class JsonSchemaBuilder
37   {
38     private JsonReader _reader;
39     private readonly IList<JsonSchema> _stack;
40     private readonly JsonSchemaResolver _resolver;
41     private JsonSchema _currentSchema;
42
43     private void Push(JsonSchema value)
44     {
45       _currentSchema = value;
46       _stack.Add(value);
47       _resolver.LoadedSchemas.Add(value);
48     }
49
50     private JsonSchema Pop()
51     {
52       JsonSchema poppedSchema = _currentSchema;
53       _stack.RemoveAt(_stack.Count - 1);
54       _currentSchema = _stack.LastOrDefault();
55
56       return poppedSchema;
57     }
58
59     private JsonSchema CurrentSchema
60     {
61       get { return _currentSchema; }
62     }
63
64     public JsonSchemaBuilder(JsonSchemaResolver resolver)
65     {
66       _stack = new List<JsonSchema>();
67       _resolver = resolver;
68     }
69
70     internal JsonSchema Parse(JsonReader reader)
71     {
72       _reader = reader;
73
74       if (reader.TokenType == JsonToken.None)
75         _reader.Read();
76
77       return BuildSchema();
78     }
79
80     private JsonSchema BuildSchema()
81     {
82       if (_reader.TokenType != JsonToken.StartObject)
83         throw new Exception("Expected StartObject while parsing schema object, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
84
85       _reader.Read();
86       // empty schema object
87       if (_reader.TokenType == JsonToken.EndObject)
88       {
89         Push(new JsonSchema());
90         return Pop();
91       }
92
93       string propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture);
94       _reader.Read();
95       
96       // schema reference
97       if (propertyName == JsonSchemaConstants.ReferencePropertyName)
98       {
99         string id = (string)_reader.Value;
100         _reader.Read();
101         JsonSchema referencedSchema = _resolver.GetSchema(id);
102         if (referencedSchema == null)
103           throw new Exception("Could not resolve schema reference for Id '{0}'.".FormatWith(CultureInfo.InvariantCulture, id));
104
105         return referencedSchema;
106       }
107
108       // regular ol' schema object
109       Push(new JsonSchema());
110
111       ProcessSchemaProperty(propertyName);
112
113       while (_reader.Read() && _reader.TokenType != JsonToken.EndObject)
114       {
115         propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture);
116         _reader.Read();
117
118         ProcessSchemaProperty(propertyName);
119       }
120
121       return Pop();
122     }
123
124     private void ProcessSchemaProperty(string propertyName)
125     {
126       switch (propertyName)
127       {
128         case JsonSchemaConstants.TypePropertyName:
129           CurrentSchema.Type = ProcessType();
130           break;
131         case JsonSchemaConstants.IdPropertyName:
132           CurrentSchema.Id = (string) _reader.Value;
133           break;
134         case JsonSchemaConstants.TitlePropertyName:
135           CurrentSchema.Title = (string) _reader.Value;
136           break;
137         case JsonSchemaConstants.DescriptionPropertyName:
138           CurrentSchema.Description = (string)_reader.Value;
139           break;
140         case JsonSchemaConstants.PropertiesPropertyName:
141           ProcessProperties();
142           break;
143         case JsonSchemaConstants.ItemsPropertyName:
144           ProcessItems();
145           break;
146         case JsonSchemaConstants.AdditionalPropertiesPropertyName:
147           ProcessAdditionalProperties();
148           break;
149         case JsonSchemaConstants.PatternPropertiesPropertyName:
150           ProcessPatternProperties();
151           break;
152         case JsonSchemaConstants.RequiredPropertyName:
153           CurrentSchema.Required = (bool)_reader.Value;
154           break;
155         case JsonSchemaConstants.RequiresPropertyName:
156           CurrentSchema.Requires = (string) _reader.Value;
157           break;
158         case JsonSchemaConstants.IdentityPropertyName:
159           ProcessIdentity();
160           break;
161         case JsonSchemaConstants.MinimumPropertyName:
162           CurrentSchema.Minimum = Convert.ToDouble(_reader.Value, CultureInfo.InvariantCulture);
163           break;
164         case JsonSchemaConstants.MaximumPropertyName:
165           CurrentSchema.Maximum = Convert.ToDouble(_reader.Value, CultureInfo.InvariantCulture);
166           break;
167         case JsonSchemaConstants.ExclusiveMinimumPropertyName:
168           CurrentSchema.ExclusiveMinimum = (bool)_reader.Value;
169           break;
170         case JsonSchemaConstants.ExclusiveMaximumPropertyName:
171           CurrentSchema.ExclusiveMaximum = (bool)_reader.Value;
172           break;
173         case JsonSchemaConstants.MaximumLengthPropertyName:
174           CurrentSchema.MaximumLength = Convert.ToInt32(_reader.Value, CultureInfo.InvariantCulture);
175           break;
176         case JsonSchemaConstants.MinimumLengthPropertyName:
177           CurrentSchema.MinimumLength = Convert.ToInt32(_reader.Value, CultureInfo.InvariantCulture);
178           break;
179         case JsonSchemaConstants.MaximumItemsPropertyName:
180           CurrentSchema.MaximumItems = Convert.ToInt32(_reader.Value, CultureInfo.InvariantCulture);
181           break;
182         case JsonSchemaConstants.MinimumItemsPropertyName:
183           CurrentSchema.MinimumItems = Convert.ToInt32(_reader.Value, CultureInfo.InvariantCulture);
184           break;
185         case JsonSchemaConstants.DivisibleByPropertyName:
186           CurrentSchema.DivisibleBy = Convert.ToDouble(_reader.Value, CultureInfo.InvariantCulture);
187           break;
188         case JsonSchemaConstants.DisallowPropertyName:
189           CurrentSchema.Disallow = ProcessType();
190           break;
191         case JsonSchemaConstants.DefaultPropertyName:
192           ProcessDefault();
193           break;
194         case JsonSchemaConstants.HiddenPropertyName:
195           CurrentSchema.Hidden = (bool) _reader.Value;
196           break;
197         case JsonSchemaConstants.ReadOnlyPropertyName:
198           CurrentSchema.ReadOnly = (bool) _reader.Value;
199           break;
200         case JsonSchemaConstants.FormatPropertyName:
201           CurrentSchema.Format = (string) _reader.Value;
202           break;
203         case JsonSchemaConstants.PatternPropertyName:
204           CurrentSchema.Pattern = (string) _reader.Value;
205           break;
206         case JsonSchemaConstants.OptionsPropertyName:
207           ProcessOptions();
208           break;
209         case JsonSchemaConstants.EnumPropertyName:
210           ProcessEnum();
211           break;
212         case JsonSchemaConstants.ExtendsPropertyName:
213           ProcessExtends();
214           break;
215         default:
216           _reader.Skip();
217           break;
218       }
219     }
220
221     private void ProcessExtends()
222     {
223       CurrentSchema.Extends = BuildSchema();
224     }
225
226     private void ProcessEnum()
227     {
228       if (_reader.TokenType != JsonToken.StartArray)
229         throw new Exception("Expected StartArray token while parsing enum values, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
230
231       CurrentSchema.Enum = new List<JToken>();
232
233       while (_reader.Read() && _reader.TokenType != JsonToken.EndArray)
234       {
235         JToken value = JToken.ReadFrom(_reader);
236         CurrentSchema.Enum.Add(value);
237       }
238     }
239
240     private void ProcessOptions()
241     {
242       CurrentSchema.Options = new Dictionary<JToken, string>(new JTokenEqualityComparer());
243
244       switch (_reader.TokenType)
245       {
246         case JsonToken.StartArray:
247           while (_reader.Read() && _reader.TokenType != JsonToken.EndArray)
248           {
249             if (_reader.TokenType != JsonToken.StartObject)
250               throw new Exception("Expect object token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
251
252             string label = null;
253             JToken value = null;
254
255             while (_reader.Read() && _reader.TokenType != JsonToken.EndObject)
256             {
257               string propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture);
258               _reader.Read();
259
260               switch (propertyName)
261               {
262                 case JsonSchemaConstants.OptionValuePropertyName:
263                   value = JToken.ReadFrom(_reader);
264                   break;
265                 case JsonSchemaConstants.OptionLabelPropertyName:
266                   label = (string) _reader.Value;
267                   break;
268                 default:
269                   throw new Exception("Unexpected property in JSON schema option: {0}.".FormatWith(CultureInfo.InvariantCulture, propertyName));
270               }
271             }
272
273             if (value == null)
274               throw new Exception("No value specified for JSON schema option.");
275
276             if (CurrentSchema.Options.ContainsKey(value))
277               throw new Exception("Duplicate value in JSON schema option collection: {0}".FormatWith(CultureInfo.InvariantCulture, value));
278
279             CurrentSchema.Options.Add(value, label);
280           }
281           break;
282         default:
283           throw new Exception("Expected array token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
284       }
285     }
286
287     private void ProcessDefault()
288     {
289       CurrentSchema.Default = JToken.ReadFrom(_reader);
290     }
291
292     private void ProcessIdentity()
293     {
294       CurrentSchema.Identity = new List<string>();
295
296       switch (_reader.TokenType)
297       {
298         case JsonToken.String:
299           CurrentSchema.Identity.Add(_reader.Value.ToString());
300           break;
301         case JsonToken.StartArray:
302           while (_reader.Read() && _reader.TokenType != JsonToken.EndArray)
303           {
304             if (_reader.TokenType != JsonToken.String)
305               throw new Exception("Exception JSON property name string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
306
307             CurrentSchema.Identity.Add(_reader.Value.ToString());
308           }
309           break;
310         default:
311           throw new Exception("Expected array or JSON property name string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
312       }
313     }
314
315     private void ProcessAdditionalProperties()
316     {
317       if (_reader.TokenType == JsonToken.Boolean)
318         CurrentSchema.AllowAdditionalProperties = (bool)_reader.Value;
319       else
320         CurrentSchema.AdditionalProperties = BuildSchema();
321     }
322
323     private void ProcessPatternProperties()
324     {
325       Dictionary<string, JsonSchema> patternProperties = new Dictionary<string, JsonSchema>();
326
327       if (_reader.TokenType != JsonToken.StartObject)
328         throw new Exception("Expected start object token.");
329
330       while (_reader.Read() && _reader.TokenType != JsonToken.EndObject)
331       {
332         string propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture);
333         _reader.Read();
334
335         if (patternProperties.ContainsKey(propertyName))
336           throw new Exception("Property {0} has already been defined in schema.".FormatWith(CultureInfo.InvariantCulture, propertyName));
337
338         patternProperties.Add(propertyName, BuildSchema());
339       }
340
341       CurrentSchema.PatternProperties = patternProperties;
342     }
343
344     private void ProcessItems()
345     {
346       CurrentSchema.Items = new List<JsonSchema>();
347
348       switch (_reader.TokenType)
349       {
350         case JsonToken.StartObject:
351           CurrentSchema.Items.Add(BuildSchema());
352           break;
353         case JsonToken.StartArray:
354           while (_reader.Read() && _reader.TokenType != JsonToken.EndArray)
355           {
356             CurrentSchema.Items.Add(BuildSchema());
357           }
358           break;
359         default:
360           throw new Exception("Expected array or JSON schema object token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
361       }
362     }
363
364     private void ProcessProperties()
365     {
366       IDictionary<string, JsonSchema> properties = new Dictionary<string, JsonSchema>();
367
368       if (_reader.TokenType != JsonToken.StartObject)
369         throw new Exception("Expected StartObject token while parsing schema properties, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
370
371       while (_reader.Read() && _reader.TokenType != JsonToken.EndObject)
372       {
373         string propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture);
374         _reader.Read();
375
376         if (properties.ContainsKey(propertyName))
377           throw new Exception("Property {0} has already been defined in schema.".FormatWith(CultureInfo.InvariantCulture, propertyName));
378
379         properties.Add(propertyName, BuildSchema());
380       }
381
382       CurrentSchema.Properties = properties;
383     }
384
385     private JsonSchemaType? ProcessType()
386     {
387       switch (_reader.TokenType)
388       {
389         case JsonToken.String:
390           return MapType(_reader.Value.ToString());
391         case JsonToken.StartArray:
392           // ensure type is in blank state before ORing values
393           JsonSchemaType? type = JsonSchemaType.None;
394
395           while (_reader.Read() && _reader.TokenType != JsonToken.EndArray)
396           {
397             if (_reader.TokenType != JsonToken.String)
398               throw new Exception("Exception JSON schema type string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
399
400             type = type | MapType(_reader.Value.ToString());
401           }
402
403           return type;
404         default:
405           throw new Exception("Expected array or JSON schema type string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
406       }
407     }
408
409     internal static JsonSchemaType MapType(string type)
410     {
411       JsonSchemaType mappedType;
412       if (!JsonSchemaConstants.JsonSchemaTypeMapping.TryGetValue(type, out mappedType))
413         throw new Exception("Invalid JSON schema type: {0}".FormatWith(CultureInfo.InvariantCulture, type));
414
415       return mappedType;
416     }
417
418     internal static string MapType(JsonSchemaType type)
419     {
420       return JsonSchemaConstants.JsonSchemaTypeMapping.Single(kv => kv.Value == type).Key;
421     }
422   }
423 }