Class: JSON::Validator

Inherits:
Object
  • Object
show all
Defined in:
lib/json-schema/validator.rb

Constant Summary collapse

ValidationMethods =
[
  "type",
  "disallow",
  "minimum",
  "maximum",
  "minItems",
  "maxItems",
  "uniqueItems",
  "pattern",
  "minLength",
  "maxLength",
  "divisibleBy",
  "enum",
  "properties",
  "patternProperties",
  "additionalProperties",
  "items",
  "additionalItems",
  "dependencies",
  "extends",
  "$ref"
]
@@schemas =
{}
@@cache_schemas =
false
@@default_opts =
{
  :list => false
}

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(schema_data, data, opts = {}) ⇒ Validator

Returns a new instance of Validator.



51
52
53
54
55
56
# File 'lib/json-schema/validator.rb', line 51

def initialize(schema_data, data, opts={})
  @options = @@default_opts.clone.merge(opts)
  @base_schema = initialize_schema(schema_data)
  @data = initialize_data(data)    
  build_schemas(@base_schema)
end

Class Method Details

.add_schema(schema) ⇒ Object



604
605
606
# File 'lib/json-schema/validator.rb', line 604

def add_schema(schema)
  @@schemas[schema.uri.to_s] = schema if @@schemas[schema.uri.to_s].nil?
end

.cache_schemas=(val) ⇒ Object



608
609
610
# File 'lib/json-schema/validator.rb', line 608

def cache_schemas=(val)
  @@cache_schemas = val == true ? true : false
end

.clear_cacheObject



596
597
598
# File 'lib/json-schema/validator.rb', line 596

def clear_cache
  @@schemas = {} if @@cache_schemas == false
end

.schemasObject



600
601
602
# File 'lib/json-schema/validator.rb', line 600

def schemas
  @@schemas
end

.validate(schema, data, opts = {}) ⇒ Object



586
587
588
589
# File 'lib/json-schema/validator.rb', line 586

def validate(schema, data,opts={})
  validator = JSON::Validator.new(schema, data, opts)
  validator.validate
end

.validate2(schema, data, opts = {}) ⇒ Object



591
592
593
594
# File 'lib/json-schema/validator.rb', line 591

def validate2(schema, data,opts={})
  validator = JSON::Validator.new(schema, data, opts)
  validator.validate2
end

Instance Method Details

#build_fragment(fragments) ⇒ Object



492
493
494
# File 'lib/json-schema/validator.rb', line 492

def build_fragment(fragments)
  "#/#{fragments.join('/')}"
end

#build_schemas(parent_schema) ⇒ Object

Build all schemas with IDs, mapping out the namespace



528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
# File 'lib/json-schema/validator.rb', line 528

def build_schemas(parent_schema)
  
  # Check for schemas in union types
  ["type", "disallow"].each do |key|
    if parent_schema.schema[key] && parent_schema.schema[key].is_a?(Array)
      parent_schema.schema[key].each_with_index do |type,i|
        if type.is_a?(Hash) 
          handle_schema(parent_schema, type)
        end
      end
    end
  end
    
  # All properties are schemas
  if parent_schema.schema["properties"]
    parent_schema.schema["properties"].each do |k,v|
      handle_schema(parent_schema, v)
    end
  end
  
  # Items are always schemas
  if parent_schema.schema["items"]
    items = parent_schema.schema["items"].clone
    single = false
    if !items.is_a?(Array)
      items = [items]
      single = true
    end
    items.each_with_index do |item,i|
      handle_schema(parent_schema, item)
    end
  end
  
  # Each of these might be schemas
  ["additionalProperties", "additionalItems", "dependencies", "extends"].each do |key|
    if parent_schema.schema[key].is_a?(Hash) 
      handle_schema(parent_schema, parent_schema.schema[key])
    end
  end
  
end

#handle_schema(parent_schema, obj) ⇒ Object

Either load a reference schema or create a new schema



571
572
573
574
575
576
577
578
579
580
581
582
# File 'lib/json-schema/validator.rb', line 571

def handle_schema(parent_schema, obj)
  if obj['$ref']
     load_ref_schema(parent_schema, obj['$ref'])
   else
     schema_uri = parent_schema.uri.clone
     schema = JSON::Schema.new(obj,schema_uri)
     if obj['id']
       Validator.add_schema(schema)
     end
     build_schemas(schema)
   end
end

#load_ref_schema(parent_schema, ref) ⇒ Object



497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
# File 'lib/json-schema/validator.rb', line 497

def load_ref_schema(parent_schema,ref)
  uri = URI.parse(ref)
  if uri.relative?
    uri = parent_schema.uri.clone
    # Check for absolute path
    path = ref.split("#")[0]
    if path[0,1] == '/'
      uri.path = Pathname.new(path).cleanpath
    else
      uri.path = (Pathname.new(parent_schema.uri.path).parent + path).cleanpath
    end
    uri.fragment = nil
  end
  
  if Validator.schemas[uri.to_s].nil?
    begin
      schema = JSON::Schema.new(JSON.parse(open(uri.to_s).read), uri)
      Validator.add_schema(schema)
      build_schemas(schema)
    rescue JSON::ParserError
      # Don't rescue this error, we want JSON formatting issues to bubble up
      raise $!
    rescue
      # Failures will occur when this URI cannot be referenced yet. Don't worry about it,
      # the proper error will fall out if the ref isn't ever defined
    end
  end
end

#validateObject

Run a simple true/false validation of data against a schema



60
61
62
63
64
65
66
67
68
69
# File 'lib/json-schema/validator.rb', line 60

def validate()
  begin
    validate_schema(@base_schema, @data, [])
    Validator.clear_cache
    return true
  rescue ValidationError
    Validator.clear_cache
    return false
  end
end

#validate2Object

Validate data against a schema, returning nil if the data is valid. If the data is invalid, a ValidationError will be raised with links to the specific location that the first error occurred during validation



75
76
77
78
79
80
81
82
83
84
# File 'lib/json-schema/validator.rb', line 75

def validate2()
  begin
    validate_schema(@base_schema, @data, [])
    Validator.clear_cache
  rescue ValidationError
    Validator.clear_cache
    raise $!
  end
  nil
end

#validate_additionalItems(current_schema, data, fragments) ⇒ Object

Validate items in an array that are not part of the schema at least match a set of rules



396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
# File 'lib/json-schema/validator.rb', line 396

def validate_additionalItems(current_schema, data, fragments)
  if data.is_a?(Array) && current_schema.schema['items'].is_a?(Array)
    if current_schema.schema['additionalItems'] == false && current_schema.schema['items'].length != data.length
      message = "The property '#{build_fragment(fragments)}' contains additional array elements outside of the schema when none are allowed"
      raise ValidationError.new(message, fragments, current_schema)
    elsif current_schema.schema['additionalItems'].is_a?(Hash)
      schema = JSON::Schema.new(current_schema.schema['additionalItems'],current_schema.uri)
      data.each_with_index do |item,i|
        if i >= current_schema.schema['items'].length
          fragments << i.to_s
          validate_schema(schema, item, fragments)
          fragments.pop
        end
      end
    end
  end
end

#validate_additionalProperties(current_schema, data, fragments) ⇒ Object

Validate properties of an object that are not defined in the schema at least validate against a set of rules



338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
# File 'lib/json-schema/validator.rb', line 338

def validate_additionalProperties(current_schema, data, fragments)
  if data.is_a?(Hash)
    extra_properties = data.keys
    
    if current_schema.schema['properties']
      extra_properties = extra_properties - current_schema.schema['properties'].keys
    end
    
    if current_schema.schema['patternProperties']
      current_schema.schema['patternProperties'].each_key do |key|
        r = Regexp.new(key)
        extras_clone = extra_properties.clone
        extras_clone.each do |prop|
          if r.match(prop)
            extra_properties = extra_properties - [prop]
          end
        end
      end
    end
    
    if current_schema.schema['additionalProperties'] == false && !extra_properties.empty?
      message = "The property '#{build_fragment(fragments)}' contains additional properties outside of the schema when none are allowed"
      raise ValidationError.new(message, fragments, current_schema)
    elsif current_schema.schema['additionalProperties'].is_a?(Hash)
      extra_properties.each do |key|
        schema = JSON::Schema.new(current_schema.schema['additionalProperties'],current_schema.uri)
        fragments << key
        validate_schema(schema, data[key], fragments)
        fragments.pop
      end
    end
  end
end

#validate_dependencies(current_schema, data, fragments) ⇒ Object

Validate the dependencies of a property



416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
# File 'lib/json-schema/validator.rb', line 416

def validate_dependencies(current_schema, data, fragments)
  if data.is_a?(Hash)
    current_schema.schema['dependencies'].each do |property,dependency_value|
      if data.has_key?(property)
        if dependency_value.is_a?(String) && !data.has_key?(dependency_value)
          message = "The property '#{build_fragment(fragments)}' has a property '#{property}' that depends on a missing property '#{dependency_value}'"
          raise ValidationError.new(message, fragments, current_schema)
        elsif dependency_value.is_a?(Array)
          dependency_value.each do |value|
            if !data.has_key?(value)
              message = "The property '#{build_fragment(fragments)}' has a property '#{property}' that depends on a missing property '#{value}'"
              raise ValidationError.new(message, fragments, current_schema)
            end
          end
        else
          schema = JSON::Schema.new(dependency_value,current_schema.uri)
          validate_schema(schema, data, fragments)
        end
      end
    end
  end
end

#validate_disallow(current_schema, data, fragments) ⇒ Object

Validate the disallowed types



169
170
171
# File 'lib/json-schema/validator.rb', line 169

def validate_disallow(current_schema, data, fragments)
  validate_type(current_schema, data, fragments, true)
end

#validate_divisibleBy(current_schema, data, fragments) ⇒ Object

Validate a numeric is divisible by another numeric



264
265
266
267
268
269
270
271
272
273
# File 'lib/json-schema/validator.rb', line 264

def validate_divisibleBy(current_schema, data, fragments)
  if data.is_a?(Numeric)
    if current_schema.schema['divisibleBy'] == 0 || 
       current_schema.schema['divisibleBy'] == 0.0 ||
       (BigDecimal.new(data.to_s) % BigDecimal.new(current_schema.schema['divisibleBy'].to_s)).to_f != 0
       message = "The property '#{build_fragment(fragments)}' was not divisible by #{current_schema.schema['divisibleBy']}"
       raise ValidationError.new(message, fragments, current_schema)
    end
  end
end

#validate_enum(current_schema, data, fragments) ⇒ Object

Validate an item matches at least one of an array of values



277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
# File 'lib/json-schema/validator.rb', line 277

def validate_enum(current_schema, data, fragments)
  if !current_schema.schema['enum'].include?(data)
    message = "The property '#{build_fragment(fragments)}' did not match one of the following values:"
    current_schema.schema['enum'].each {|val|
      if val.is_a?(NilClass)
        message += " null,"
      elsif val.is_a?(Array)
        message += " (array),"
      elsif val.is_a?(Hash)
        message += " (object),"
      else
        message += " #{val.to_s},"
      end
    }
    message.chop!
    raise ValidationError.new(message, fragments, current_schema)
  end
end

#validate_extends(current_schema, data, fragments) ⇒ Object

Validate extensions of other schemas



441
442
443
444
445
446
447
448
# File 'lib/json-schema/validator.rb', line 441

def validate_extends(current_schema, data, fragments)
  schemas = current_schema.schema['extends']
  schemas = [schemas] if !schemas.is_a?(Array)
  schemas.each do |s|
    schema = JSON::Schema.new(s,current_schema.uri)
    validate_schema(schema, data, fragments)
  end
end

#validate_items(current_schema, data, fragments) ⇒ Object

Validate items in an array match a schema or a set of schemas



374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
# File 'lib/json-schema/validator.rb', line 374

def validate_items(current_schema, data, fragments)
  if data.is_a?(Array)
     if current_schema.schema['items'].is_a?(Hash)
       data.each_with_index do |item,i|
         schema = JSON::Schema.new(current_schema.schema['items'],current_schema.uri)
         fragments << i.to_s
         validate_schema(schema,item,fragments)
         fragments.pop
       end
     elsif current_schema.schema['items'].is_a?(Array)
       current_schema.schema['items'].each_with_index do |item_schema,i|
         schema = JSON::Schema.new(item_schema,current_schema.uri)
         fragments << i.to_s
         validate_schema(schema,data[i],fragments)
         fragments.pop
       end
     end
  end
end

#validate_maximum(current_schema, data, fragments) ⇒ Object

Validate the maximum value of a number



187
188
189
190
191
192
193
194
195
# File 'lib/json-schema/validator.rb', line 187

def validate_maximum(current_schema, data, fragments)
  if data.is_a?(Numeric)
    if (current_schema.schema['exclusiveMaximum'] ? data >= current_schema.schema['maximum'] : data > current_schema.schema['maximum'])
      message = "The property '#{build_fragment(fragments)}' did not have a maximum value of #{current_schema.schema['maximum']}, "
      message += current_schema.schema['exclusiveMaximum'] ? 'exclusively' : 'inclusively'
      raise ValidationError.new(message, fragments, current_schema)
    end
  end
end

#validate_maxItems(current_schema, data, fragments) ⇒ Object

Validate the maximum number of items in an array



208
209
210
211
212
213
# File 'lib/json-schema/validator.rb', line 208

def validate_maxItems(current_schema, data, fragments)
  if data.is_a?(Array) && (data.nitems > current_schema.schema['maxItems'])
    message = "The property '#{build_fragment(fragments)}' did not contain a minimum number of items #{current_schema.schema['minItems']}"
    raise ValidationError.new(message, fragments, current_schema)
  end
end

#validate_maxLength(current_schema, data, fragments) ⇒ Object

Validate a string is at maximum of a certain length



253
254
255
256
257
258
259
260
# File 'lib/json-schema/validator.rb', line 253

def validate_maxLength(current_schema, data, fragments)
  if data.is_a?(String)
    if data.length > current_schema.schema['maxLength']
      message = "The property '#{build_fragment(fragments)}' was not of a maximum string length of #{current_schema.schema['maxLength']}"
      raise ValidationError.new(message, fragments, current_schema)
    end
  end
end

#validate_minimum(current_schema, data, fragments) ⇒ Object

Validate the minimum value of a number



175
176
177
178
179
180
181
182
183
# File 'lib/json-schema/validator.rb', line 175

def validate_minimum(current_schema, data, fragments)
  if data.is_a?(Numeric)
    if (current_schema.schema['exclusiveMinimum'] ? data <= current_schema.schema['minimum'] : data < current_schema.schema['minimum'])
      message = "The property '#{build_fragment(fragments)}' did not have a minimum value of #{current_schema.schema['minimum']}, "
      message += current_schema.schema['exclusiveMinimum'] ? 'exclusively' : 'inclusively'
      raise ValidationError.new(message, fragments, current_schema)
    end
  end
end

#validate_minItems(current_schema, data, fragments) ⇒ Object

Validate the minimum number of items in an array



199
200
201
202
203
204
# File 'lib/json-schema/validator.rb', line 199

def validate_minItems(current_schema, data, fragments)
  if data.is_a?(Array) && (data.nitems < current_schema.schema['minItems'])
    message = "The property '#{build_fragment(fragments)}' did not contain a minimum number of items #{current_schema.schema['minItems']}"
    raise ValidationError.new(message, fragments, current_schema)
  end
end

#validate_minLength(current_schema, data, fragments) ⇒ Object

Validate a string is at least of a certain length



242
243
244
245
246
247
248
249
# File 'lib/json-schema/validator.rb', line 242

def validate_minLength(current_schema, data, fragments)
  if data.is_a?(String)
    if data.length < current_schema.schema['minLength']
      message = "The property '#{build_fragment(fragments)}' was not of a minimum string length of #{current_schema.schema['minLength']}"
      raise ValidationError.new(message, fragments, current_schema)
    end
  end
end

#validate_pattern(current_schema, data, fragments) ⇒ Object

Validate a string matches a regex pattern



230
231
232
233
234
235
236
237
238
# File 'lib/json-schema/validator.rb', line 230

def validate_pattern(current_schema, data, fragments)
  if data.is_a?(String)
    r = Regexp.new(current_schema.schema['pattern'])
    if (r.match(data)).nil?
      message = "The property '#{build_fragment(fragments)}' did not match the regex '#{current_schema.schema['pattern']}'"
      raise ValidationError.new(message, fragments, current_schema)
    end
  end
end

#validate_patternProperties(current_schema, data, fragments) ⇒ Object

Validate properties of an object against a schema when the property name matches a specific regex



318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
# File 'lib/json-schema/validator.rb', line 318

def validate_patternProperties(current_schema, data, fragments)
  if data.is_a?(Hash)
    current_schema.schema['patternProperties'].each do |property,property_schema|
      r = Regexp.new(property)
      
      # Check each key in the data hash to see if it matches the regex
      data.each do |key,value|
        if r.match(key)
          schema = JSON::Schema.new(property_schema,current_schema.uri)
          fragments << key
          validate_schema(schema, data[key], fragments)
          fragments.pop
        end
      end
    end
  end
end

#validate_properties(current_schema, data, fragments) ⇒ Object

Validate a set of properties of an object



298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
# File 'lib/json-schema/validator.rb', line 298

def validate_properties(current_schema, data, fragments)
  if data.is_a?(Hash)
    current_schema.schema['properties'].each do |property,property_schema|
      if (property_schema['required'] && !data.has_key?(property))
        message = "The property '#{build_fragment(fragments)}' did not contain a required property of '#{property}'"
        raise ValidationError.new(message, fragments, current_schema)
      end
      
      if data.has_key?(property)
        schema = JSON::Schema.new(property_schema,current_schema.uri)
        fragments << property
        validate_schema(schema, data[property], fragments)
        fragments.pop
      end
    end
  end
end

#validate_ref(current_schema, data, fragments) ⇒ Object

Validate schema references



452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
# File 'lib/json-schema/validator.rb', line 452

def validate_ref(current_schema, data, fragments)
  temp_uri = URI.parse(current_schema.schema['$ref'])
  if temp_uri.relative?
    temp_uri = current_schema.uri.clone
    # Check for absolute path
    path = current_schema.schema['$ref'].split("#")[0]
    if path[0,1] == "/"
      temp_uri.path = Pathname.new(path).cleanpath
    else
      temp_uri.path = (Pathname.new(current_schema.uri.path).parent + path).cleanpath
    end
    temp_uri.fragment = current_schema.schema['$ref'].split("#")[1]
  end
  temp_uri.fragment = "" if temp_uri.fragment.nil?
  
  # Grab the parent schema from the schema list
  schema_key = temp_uri.to_s.split("#")[0]
  ref_schema = Validator.schemas[schema_key]
  
  if ref_schema
    # Perform fragment resolution to retrieve the appropriate level for the schema
    target_schema = ref_schema.schema
    fragments = temp_uri.fragment.split("/")
    fragments.each do |fragment|
      if fragment && fragment != ''
        if target_schema.is_a?(Array)
          target_schema = target_schema[fragment.to_i]
        else
          target_schema = target_schema[fragment]
        end
      end
    end
    
    # We have the schema finally, build it and validate!
    schema = JSON::Schema.new(target_schema,temp_uri)
    validate_schema(schema, data, fragments)
  end
end

#validate_schema(current_schema, data, fragments) ⇒ Object

Validate the current schema



88
89
90
91
92
93
94
95
96
97
# File 'lib/json-schema/validator.rb', line 88

def validate_schema(current_schema, data, fragments)
      
  ValidationMethods.each do |method|
    if !current_schema.schema[method].nil?
      self.send(("validate_" + method.sub('$','')).to_sym, current_schema, data, fragments)
    end
  end
  
  data
end

#validate_type(current_schema, data, fragments, disallow = false) ⇒ Object

Validate the type



101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
# File 'lib/json-schema/validator.rb', line 101

def validate_type(current_schema, data, fragments, disallow=false)
  union = true
  
  if disallow
    types = current_schema.schema['disallow']
  else
    types = current_schema.schema['type']
  end
  
  if !types.is_a?(Array)
    types = [types]
    union = false
  end
  valid = false
  
  types.each do |type|
    if type.is_a?(String)
      case type
      when "string"
        valid = data.is_a?(String)
      when "number"
        valid = data.is_a?(Numeric)
      when "integer"
        valid = data.is_a?(Integer)
      when "boolean"
        valid = (data.is_a?(TrueClass) || data.is_a?(FalseClass))
      when "object"
        valid = data.is_a?(Hash)
      when "array"
        valid = data.is_a?(Array)
      when "null"
        valid = data.is_a?(NilClass)
      when "any"
        valid = true
      else
        valid = true
      end
    elsif type.is_a?(Hash) && union
      # Validate as a schema
      schema = JSON::Schema.new(type,current_schema.uri)
      begin
        validate_schema(schema,data,fragments)
        valid = true
      rescue ValidationError
        # We don't care that these schemas don't validate - we only care that one validated
      end
    end

    break if valid
  end
  
  if (disallow)
    if valid
      message = "The property '#{build_fragment(fragments)}' matched one or more of the following types:"
      types.each {|type| message += type.is_a?(String) ? " #{type}," : " (schema)," }
      message.chop!
      raise ValidationError.new(message, fragments, current_schema)
    end
  elsif !valid
    message = "The property '#{build_fragment(fragments)}' did not match one or more of the following types:"
    types.each {|type| message += type.is_a?(String) ? " #{type}," : " (schema)," }
    message.chop!
    raise ValidationError.new(message, fragments, current_schema)
  end
end

#validate_uniqueItems(current_schema, data, fragments) ⇒ Object

Validate the uniqueness of elements in an array



217
218
219
220
221
222
223
224
225
226
# File 'lib/json-schema/validator.rb', line 217

def validate_uniqueItems(current_schema, data, fragments)
  if data.is_a?(Array)
    d = data.clone
    dupes = d.uniq!
    if dupes
      message = "The property '#{build_fragment(fragments)}' contained duplicated array values"
      raise ValidationError.new(message, fragments, current_schema)
    end
  end
end