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.



55
56
57
58
59
60
# File 'lib/json-schema/validator.rb', line 55

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



623
624
625
# File 'lib/json-schema/validator.rb', line 623

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

.cache_schemas=(val) ⇒ Object



627
628
629
# File 'lib/json-schema/validator.rb', line 627

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

.clear_cacheObject



615
616
617
# File 'lib/json-schema/validator.rb', line 615

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

.schemasObject



619
620
621
# File 'lib/json-schema/validator.rb', line 619

def schemas
  @@schemas
end

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



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

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

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



610
611
612
613
# File 'lib/json-schema/validator.rb', line 610

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

Instance Method Details

#build_fragment(fragments) ⇒ Object



505
506
507
# File 'lib/json-schema/validator.rb', line 505

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

#build_schemas(parent_schema) ⇒ Object

Build all schemas with IDs, mapping out the namespace



548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
# File 'lib/json-schema/validator.rb', line 548

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



590
591
592
593
594
595
596
597
598
599
600
601
# File 'lib/json-schema/validator.rb', line 590

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



510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
# File 'lib/json-schema/validator.rb', line 510

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]
    
    # This is a self reference and thus the schema does not need to be re-loaded
    if path.nil? || path == ''
      return
    end
    
    if path && path[0,1] == '/'
      uri.path = Pathname.new(path).cleanpath.to_s
    else
      uri.path = (Pathname.new(parent_schema.uri.path).parent + path).cleanpath.to_s
    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



64
65
66
67
68
69
70
71
72
73
# File 'lib/json-schema/validator.rb', line 64

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



79
80
81
82
83
84
85
86
87
88
# File 'lib/json-schema/validator.rb', line 79

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



400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
# File 'lib/json-schema/validator.rb', line 400

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



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
371
372
373
374
# File 'lib/json-schema/validator.rb', line 342

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



420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
# File 'lib/json-schema/validator.rb', line 420

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



173
174
175
# File 'lib/json-schema/validator.rb', line 173

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



268
269
270
271
272
273
274
275
276
277
# File 'lib/json-schema/validator.rb', line 268

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



281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
# File 'lib/json-schema/validator.rb', line 281

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



445
446
447
448
449
450
451
452
# File 'lib/json-schema/validator.rb', line 445

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



378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
# File 'lib/json-schema/validator.rb', line 378

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



191
192
193
194
195
196
197
198
199
# File 'lib/json-schema/validator.rb', line 191

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



212
213
214
215
216
217
# File 'lib/json-schema/validator.rb', line 212

def validate_maxItems(current_schema, data, fragments)
  if data.is_a?(Array) && (data.compact.size > 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



257
258
259
260
261
262
263
264
# File 'lib/json-schema/validator.rb', line 257

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



179
180
181
182
183
184
185
186
187
# File 'lib/json-schema/validator.rb', line 179

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



203
204
205
206
207
208
# File 'lib/json-schema/validator.rb', line 203

def validate_minItems(current_schema, data, fragments)
  if data.is_a?(Array) && (data.compact.size < 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



246
247
248
249
250
251
252
253
# File 'lib/json-schema/validator.rb', line 246

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



234
235
236
237
238
239
240
241
242
# File 'lib/json-schema/validator.rb', line 234

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



322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
# File 'lib/json-schema/validator.rb', line 322

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



302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
# File 'lib/json-schema/validator.rb', line 302

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



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
490
491
492
493
494
495
496
497
498
499
500
501
502
# File 'lib/json-schema/validator.rb', line 456

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.nil? || path == ''
      temp_uri.path = current_schema.uri.path
    elsif path[0,1] == "/"
      temp_uri.path = Pathname.new(path).cleanpath.to_s
    else
      temp_uri.path = (Pathname.new(current_schema.uri.path).parent + path).cleanpath.to_s
    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("/")
    fragment_path = ''
    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
        fragment_path = fragment_path + "/#{fragment}"
        if target_schema.nil?
          raise SchemaError.new("The fragment '#{fragment_path}' does not exist on schema #{ref_schema.uri.to_s}")
        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)
  else
    raise ValidationError.new("The referenced schema '#{temp_uri.to_s}' cannot be found", fragments, current_schema)
  end
end

#validate_schema(current_schema, data, fragments) ⇒ Object

Validate the current schema



92
93
94
95
96
97
98
99
100
101
# File 'lib/json-schema/validator.rb', line 92

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



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
166
167
168
169
# File 'lib/json-schema/validator.rb', line 105

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



221
222
223
224
225
226
227
228
229
230
# File 'lib/json-schema/validator.rb', line 221

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