Class: JSON::Validator

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

Defined Under Namespace

Classes: ErrorRecorder

Constant Summary collapse

@@schemas =
{}
@@cache_schemas =
true
@@default_opts =
{
  list: false,
  version: nil,
  validate_schema: false,
  record_errors: false,
  errors_as_objects: false,
  insert_defaults: false,
  clear_cache: false,
  strict: false,
  allPropertiesRequired: false,
  noAdditionalProperties: false,
  parse_data: true,
  parse_integer: true,
}
@@validators =
{}
@@default_validator =
nil
@@available_json_backends =
[]
@@json_backend =
nil
@@serializer =
nil
@@use_multi_json =
defined?(MultiJson) ? true : false
@@multi_json_warned =
false
@@mutex =
Mutex.new

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Validator.



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/json-schema/validator.rb', line 45

def initialize(schema_data, opts = {})
  @options = @@default_opts.clone.merge(opts)

  configured_validator = self.class.validator_for_name(@options[:version])
  @options[:schema_reader] ||= self.class.schema_reader

  @validation_options = @options[:record_errors] ? { record_errors: true } : {}
  @validation_options[:insert_defaults] = true if @options[:insert_defaults]
  if @options[:strict] == true
    @validation_options[:allPropertiesRequired] = true
    @validation_options[:noAdditionalProperties] = true
  else
    @validation_options[:allPropertiesRequired] = true if @options[:allPropertiesRequired]
    @validation_options[:noAdditionalProperties] = true if @options[:noAdditionalProperties]
  end
  @validation_options[:clear_cache] = true if !@@cache_schemas || @options[:clear_cache]

  @@mutex.synchronize { @base_schema = initialize_schema(schema_data, configured_validator) }
  @@mutex.synchronize { build_schemas(@base_schema) }

  # validate the schema, if requested
  if @options[:validate_schema]
    # Don't clear the cache during metaschema validation!
    meta_validator = self.class.new(@base_schema.validator.metaschema, { clear_cache: false })
    meta_validator.validate(@base_schema.schema)
  end

  # If the :fragment option is set, try and validate against the fragment
  if opts[:fragment]
    @base_schema = schema_from_fragment(@base_schema, opts[:fragment])
  end
end

Class Method Details

.add_schema(schema) ⇒ Object



323
324
325
# File 'lib/json-schema/validator.rb', line 323

def add_schema(schema)
  @@schemas[schema_key_for(schema.uri)] ||= schema
end

.cache_schemas=(val) ⇒ Object



342
343
344
345
# File 'lib/json-schema/validator.rb', line 342

def cache_schemas=(val)
  warn '[DEPRECATION NOTICE] Schema caching is now a validation option. Schemas will still be cached if this is set to true, but this method will be removed in version >= 3. Please use the :clear_cache validation option instead.'
  @@cache_schemas = val == true
end

.clear_cacheObject



315
316
317
# File 'lib/json-schema/validator.rb', line 315

def clear_cache
  @@schemas = {}
end

.default_validatorObject



351
352
353
# File 'lib/json-schema/validator.rb', line 351

def default_validator
  @@default_validator
end

.deregister_format_validator(format, versions = (@@validators.flat_map { |_k, v| v.names.first } + [nil])) ⇒ Object



402
403
404
405
406
407
# File 'lib/json-schema/validator.rb', line 402

def deregister_format_validator(format, versions = (@@validators.flat_map { |_k, v| v.names.first } + [nil]))
  versions.each do |version|
    validator = validator_for_name(version)
    validator.formats[format.to_s] = validator.default_formats[format.to_s]
  end
end

.ensure_ruby_json_backends!Object



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
525
526
527
528
529
530
531
532
# File 'lib/json-schema/validator.rb', line 500

def ensure_ruby_json_backends!
  if !@@available_json_backends.empty? || !@@serializer.nil?
    return
  end

  if Gem::Specification.find_all_by_name('json').any?
    require 'json'
    @@available_json_backends << 'json'
    @@json_backend = 'json'
  else
    # Try force-loading json for rubies > 1.9.2
    begin
      require 'json'
      @@available_json_backends << 'json'
      @@json_backend = 'json'
    rescue LoadError
    end
  end

  if Gem::Specification.find_all_by_name('yajl-ruby').any?
    require 'yajl'
    @@available_json_backends << 'yajl'
    @@json_backend = 'yajl'
  end

  @@serializer = if @@json_backend == 'yajl'
                   ->(o) { Yajl::Encoder.encode(o) }
                 elsif @@json_backend == 'json'
                   ->(o) { JSON.dump(o) }
                 else
                   ->(o) { YAML.dump(o) }
                 end
end

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



289
290
291
# File 'lib/json-schema/validator.rb', line 289

def fully_validate(schema, data, opts = {})
  validate!(schema, data, opts.merge(record_errors: true))
end

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



299
300
301
# File 'lib/json-schema/validator.rb', line 299

def fully_validate_json(schema, data, opts = {})
  fully_validate(schema, data, opts.merge(json: true))
end

.fully_validate_schema(schema, opts = {}) ⇒ Object



293
294
295
296
297
# File 'lib/json-schema/validator.rb', line 293

def fully_validate_schema(schema, opts = {})
  data = schema
  schema = validator_for_name(opts[:version]).metaschema
  fully_validate(schema, data, opts)
end

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



303
304
305
# File 'lib/json-schema/validator.rb', line 303

def fully_validate_uri(schema, data, opts = {})
  fully_validate(schema, data, opts.merge(uri: true))
end

.json_backendObject



427
428
429
430
431
432
433
434
# File 'lib/json-schema/validator.rb', line 427

def json_backend
  if use_multi_json?
    multi_json_deprecation_warning!
    MultiJson.respond_to?(:adapter) ? MultiJson.adapter : MultiJson.engine
  else
    @@json_backend
  end
end

.json_backend=(backend) ⇒ Object



436
437
438
439
440
441
442
443
444
445
446
447
448
449
# File 'lib/json-schema/validator.rb', line 436

def json_backend=(backend)
  if use_multi_json?
    multi_json_deprecation_warning!
    backend = 'json_gem' if backend == 'json'
    MultiJson.respond_to?(:use) ? MultiJson.use(backend) : MultiJson.engine = backend
  else
    backend = backend.to_s
    if @@available_json_backends.include?(backend)
      @@json_backend = backend
    else
      raise JSON::Schema::JsonParseError, "The JSON backend '#{backend}' could not be found."
    end
  end
end

.merge_missing_values(source, destination) ⇒ Object



481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
# File 'lib/json-schema/validator.rb', line 481

def merge_missing_values(source, destination)
  case destination
  when Hash
    source.each do |key, source_value|
      destination_value = destination[key] || destination[key.to_sym]
      if destination_value.nil?
        destination[key] = source_value
      else
        merge_missing_values(source_value, destination_value)
      end
    end
  when Array
    source.each_with_index do |source_value, i|
      destination_value = destination[i]
      merge_missing_values(source_value, destination_value)
    end
  end
end

.multi_json_deprecation_warning!Object



534
535
536
537
538
539
540
# File 'lib/json-schema/validator.rb', line 534

def multi_json_deprecation_warning!
  unless @@multi_json_warned
    @@multi_json_warned = true
    warn '[DEPRECATION NOTICE] json-schema support for MultiJSON is deprecated and will be removed in a future version. ' \
         'To stop using MultiJSON, add `JSON::Validator.use_multi_json = false` to your application\'s initialization code.'
  end
end

.parse(s) ⇒ Object



451
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
# File 'lib/json-schema/validator.rb', line 451

def parse(s)
  if use_multi_json?
    multi_json_deprecation_warning!
    begin
      MultiJson.respond_to?(:adapter) ? MultiJson.load(s) : MultiJson.decode(s)
    rescue MultiJson::ParseError => e
      raise JSON::Schema::JsonParseError, e.message
    end
  else
    case @@json_backend.to_s
    when 'json'
      begin
        JSON.parse(s, quirks_mode: true)
      rescue JSON::ParserError => e
        raise JSON::Schema::JsonParseError, e.message
      end
    when 'yajl'
      begin
        json = StringIO.new(s)
        parser = Yajl::Parser.new
        parser.parse(json) or raise(JSON::Schema::JsonParseError, 'The JSON could not be parsed by yajl')
      rescue Yajl::ParseError => e
        raise JSON::Schema::JsonParseError, e.message
      end
    else
      raise JSON::Schema::JsonParseError, "No supported JSON parsers found. The following parsers are suported:\n * yajl-ruby\n * json"
    end
  end
end

.register_default_validator(v) ⇒ Object



390
391
392
# File 'lib/json-schema/validator.rb', line 390

def register_default_validator(v)
  @@default_validator = v
end

.register_format_validator(format, validation_proc, versions = (@@validators.flat_map { |_k, v| v.names.first } + [nil])) ⇒ Object



394
395
396
397
398
399
400
# File 'lib/json-schema/validator.rb', line 394

def register_format_validator(format, validation_proc, versions = (@@validators.flat_map { |_k, v| v.names.first } + [nil]))
  custom_format_validator = JSON::Schema::CustomFormat.new(validation_proc)
  versions.each do |version|
    validator = validator_for_name(version)
    validator.formats[format.to_s] = custom_format_validator
  end
end

.register_validator(v) ⇒ Object



386
387
388
# File 'lib/json-schema/validator.rb', line 386

def register_validator(v)
  @@validators["#{v.uri.scheme}://#{v.uri.host}#{v.uri.path}"] = v
end

.restore_default_formats(versions = (@@validators.flat_map { |_k, v| v.names.first } + [nil])) ⇒ Object



409
410
411
412
413
414
# File 'lib/json-schema/validator.rb', line 409

def restore_default_formats(versions = (@@validators.flat_map { |_k, v| v.names.first } + [nil]))
  versions.each do |version|
    validator = validator_for_name(version)
    validator.formats = validator.default_formats.clone
  end
end

.schema_for_uri(uri) ⇒ Object



327
328
329
330
331
# File 'lib/json-schema/validator.rb', line 327

def schema_for_uri(uri)
  # We only store normalized uris terminated with fragment #, so we can try whether
  # normalization can be skipped
  @@schemas[uri] || @@schemas[schema_key_for(uri)]
end

.schema_key_for(uri) ⇒ Object



337
338
339
340
# File 'lib/json-schema/validator.rb', line 337

def schema_key_for(uri)
  key = Util::URI.normalized_uri(uri).to_s
  key.end_with?('#') ? key : "#{key}#"
end

.schema_loaded?(schema_uri) ⇒ Boolean

Returns:

  • (Boolean)


333
334
335
# File 'lib/json-schema/validator.rb', line 333

def schema_loaded?(schema_uri)
  !schema_for_uri(schema_uri).nil?
end

.schema_readerObject



307
308
309
# File 'lib/json-schema/validator.rb', line 307

def schema_reader
  @@schema_reader ||= JSON::Schema::Reader.new
end

.schema_reader=(reader) ⇒ Object



311
312
313
# File 'lib/json-schema/validator.rb', line 311

def schema_reader=(reader)
  @@schema_reader = reader
end

.schemasObject



319
320
321
# File 'lib/json-schema/validator.rb', line 319

def schemas
  @@schemas
end

.use_multi_json=(value) ⇒ Object



420
421
422
423
424
425
# File 'lib/json-schema/validator.rb', line 420

def use_multi_json=(value)
  @@use_multi_json = value ? true : false
  if use_multi_json? == false
    ensure_ruby_json_backends!
  end
end

.use_multi_json?Boolean

Returns:

  • (Boolean)


416
417
418
# File 'lib/json-schema/validator.rb', line 416

def use_multi_json?
  @@use_multi_json
end

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



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

def validate(schema, data, opts = {})
  validate!(schema, data, opts)
rescue JSON::Schema::ValidationError, JSON::Schema::SchemaError
  false
end

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



271
272
273
274
# File 'lib/json-schema/validator.rb', line 271

def validate!(schema, data, opts = {})
  validator = new(schema, opts)
  validator.validate(data)
end

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



276
277
278
279
# File 'lib/json-schema/validator.rb', line 276

def validate2(schema, data, opts = {})
  warn '[DEPRECATION NOTICE] JSON::Validator#validate2 has been replaced by JSON::Validator#validate! and will be removed in version >= 3. Please use the #validate! method instead.'
  validate!(schema, data, opts)
end

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



263
264
265
# File 'lib/json-schema/validator.rb', line 263

def validate_json(schema, data, opts = {})
  validate(schema, data, opts.merge(json: true))
end

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



281
282
283
# File 'lib/json-schema/validator.rb', line 281

def validate_json!(schema, data, opts = {})
  validate!(schema, data, opts.merge(json: true))
end

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



267
268
269
# File 'lib/json-schema/validator.rb', line 267

def validate_uri(schema, data, opts = {})
  validate(schema, data, opts.merge(uri: true))
end

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



285
286
287
# File 'lib/json-schema/validator.rb', line 285

def validate_uri!(schema, data, opts = {})
  validate!(schema, data, opts.merge(uri: true))
end

.validator_for(schema_uri) ⇒ Object



381
382
383
384
# File 'lib/json-schema/validator.rb', line 381

def validator_for(schema_uri)
  warn '[DEPRECATION NOTICE] JSON::Validator#validator_for has been replaced by JSON::Validator#validator_for_uri and will be removed in version >= 3. Please use the #validator_for_uri method instead.'
  validator_for_uri(schema_uri)
end

.validator_for_name(schema_name, raise_not_found = true) ⇒ Object



367
368
369
370
371
372
373
374
375
376
377
378
379
# File 'lib/json-schema/validator.rb', line 367

def validator_for_name(schema_name, raise_not_found = true)
  return default_validator unless schema_name

  schema_name = schema_name.to_s
  validator = validators.values.detect do |v|
    Array(v.names).include?(schema_name)
  end
  if validator.nil? && raise_not_found
    raise JSON::Schema::SchemaError, 'The requested JSON schema version is not supported'
  else
    validator
  end
end

.validator_for_uri(schema_uri, raise_not_found = true) ⇒ Object



355
356
357
358
359
360
361
362
363
364
365
# File 'lib/json-schema/validator.rb', line 355

def validator_for_uri(schema_uri, raise_not_found = true)
  return default_validator unless schema_uri

  u = JSON::Util::URI.parse(schema_uri)
  validator = validators["#{u.scheme}://#{u.host}#{u.path}"]
  if validator.nil? && raise_not_found
    raise JSON::Schema::SchemaError, "Schema not found: #{schema_uri}"
  else
    validator
  end
end

.validatorsObject



347
348
349
# File 'lib/json-schema/validator.rb', line 347

def validators
  @@validators
end

Instance Method Details

#build_schemas(parent_schema) ⇒ Object

Build all schemas with IDs, mapping out the namespace



174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
# File 'lib/json-schema/validator.rb', line 174

def build_schemas(parent_schema)
  schema = parent_schema.schema

  # Build ref schemas if they exist
  if schema['$ref']
    load_ref_schema(parent_schema, schema['$ref'])
  end

  case schema['extends']
  when String
    load_ref_schema(parent_schema, schema['extends'])
  when Array
    schema['extends'].each do |type|
      handle_schema(parent_schema, type)
    end
  end

  # Check for schemas in union types
  %w[type disallow].each do |key|
    next unless schema[key].is_a?(Array)

    schema[key].each do |type|
      if type.is_a?(Hash)
        handle_schema(parent_schema, type)
      end
    end
  end

  # Schema properties whose values are objects, the values of which
  # are themselves schemas.
  %w[definitions properties patternProperties].each do |key|
    next unless value = schema[key]

    value.each do |_k, inner_schema|
      handle_schema(parent_schema, inner_schema)
    end
  end

  # Schema properties whose values are themselves schemas.
  %w[additionalProperties additionalItems dependencies extends].each do |key|
    next unless schema[key].is_a?(Hash)

    handle_schema(parent_schema, schema[key])
  end

  # Schema properties whose values may be an array of schemas.
  %w[allOf anyOf oneOf not].each do |key|
    next unless value = schema[key]

    Array(value).each do |inner_schema|
      handle_schema(parent_schema, inner_schema)
    end
  end

  # Items are always schemas
  if schema['items']
    items = schema['items'].clone
    items = [items] unless items.is_a?(Array)

    items.each do |item|
      handle_schema(parent_schema, item)
    end
  end

  # Convert enum to a ArraySet
  if schema['enum'].is_a?(Array)
    schema['enum'] = ArraySet.new(schema['enum'])
  end
end

#handle_schema(parent_schema, obj) ⇒ Object

Either load a reference schema or create a new schema



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

def handle_schema(parent_schema, obj)
  if obj.is_a?(Hash)
    schema_uri = parent_schema.uri.dup
    schema = JSON::Schema.new(obj, schema_uri, parent_schema.validator)
    if obj['id']
      self.class.add_schema(schema)
    end
    build_schemas(schema)
  end
end

#load_ref_schema(parent_schema, ref) ⇒ Object



161
162
163
164
165
166
167
168
169
170
171
# File 'lib/json-schema/validator.rb', line 161

def load_ref_schema(parent_schema, ref)
  schema_uri = JSON::Util::URI.absolutize_ref(ref, parent_schema.uri)
  return true if self.class.schema_loaded?(schema_uri)

  validator = self.class.validator_for_uri(schema_uri, false)
  schema_uri = JSON::Util::URI.file_uri(validator.metaschema) if validator

  schema = @options[:schema_reader].read(schema_uri)
  self.class.add_schema(schema)
  build_schemas(schema)
end

#schema_from_fragment(base_schema, fragment) ⇒ Object



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/json-schema/validator.rb', line 78

def schema_from_fragment(base_schema, fragment)
  schema_uri = base_schema.uri
  fragments = fragment.split('/').map { |f| f.gsub('~0', '~').gsub('~1', '/') }

  # ensure the first element was a hash, per the fragment spec
  if fragments.shift != '#'
    raise JSON::Schema::SchemaError, 'Invalid fragment syntax in :fragment option'
  end

  schema_fragment = base_schema.schema
  fragments.each do |f|
    case schema_fragment
    when Hash
      schema_fragment = schema_fragment[f]
    when Array
      schema_fragment = schema_fragment[f.to_i]
    end
  end

  unless schema_fragment.is_a?(Hash)
    raise JSON::Schema::SchemaError, 'Invalid fragment resolution for :fragment option'
  end

  schema = JSON::Schema.new(schema_fragment, schema_uri, base_schema.validator)

  if @options[:list]
    schema.to_array_schema
  elsif schema.is_a?(Hash)
    JSON::Schema.new(schema, schema_uri, @options[:version])
  else
    schema
  end
end

#validate(data) ⇒ Object

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



137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/json-schema/validator.rb', line 137

def validate(data)
  original_data = data
  data = initialize_data(data)
  error_recorder = with_errors
  @base_schema.validate(data, [], error_recorder, @validation_options)

  if @options[:record_errors]
    if @options[:errors_as_objects]
      error_recorder.validation_errors.map { |e| e.to_hash }
    else
      error_recorder.validation_errors.map { |e| e.to_string }
    end
  else
    true
  end
ensure
  if @validation_options[:clear_cache] == true
    self.class.clear_cache
  end
  if @validation_options[:insert_defaults]
    self.class.merge_missing_values(data, original_data)
  end
end

#with_errorsObject



132
133
134
# File 'lib/json-schema/validator.rb', line 132

def with_errors
  ErrorRecorder.new(self)
end