Class: JSON::Validator

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

Constant Summary collapse

@@schemas =
{}
@@cache_schemas =
false
@@default_opts =
{
  :list => false,
  :version => nil,
  :validate_schema => false,
  :record_errors => false,
  :errors_as_objects => false,
  :insert_defaults => false,
  :clear_cache => true,
  :strict => false
}
@@validators =
{}
@@default_validator =
nil
@@available_json_backends =
[]
@@json_backend =
'yajl'
@@serializer =
lambda{|o| YAML.dump(o) }
@@mutex =
Mutex.new

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Validator.



36
37
38
39
40
41
42
43
44
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
# File 'lib/json-schema/validator.rb', line 36

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

  validator = JSON::Validator.validator_for_name(@options[:version])
  @options[:version] = validator

  @validation_options = @options[:record_errors] ? {:record_errors => true} : {}
  @validation_options[:insert_defaults] = true if @options[:insert_defaults]
  @validation_options[:strict] = true if @options[:strict] == true

  @@mutex.synchronize { @base_schema = initialize_schema(schema_data) }
  @data = initialize_data(data)
  @@mutex.synchronize { build_schemas(@base_schema) }

  # validate the schema, if requested
  if @options[:validate_schema]
    begin
      if @base_schema.schema["$schema"]
        base_validator = JSON::Validator.validator_for_name(@base_schema.schema["$schema"])
      end
      metaschema = base_validator ? base_validator.metaschema : validator.metaschema
      # Don't clear the cache during metaschema validation!
      meta_validator = JSON::Validator.new(metaschema, @base_schema.schema, {:clear_cache => false})
      meta_validator.validate
    rescue JSON::Schema::ValidationError, JSON::Schema::SchemaError
      raise $!
    end
  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



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

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

.cache_schemas=(val) ⇒ Object



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

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 ? true : false
end

.clear_cacheObject



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

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

.default_validatorObject



335
336
337
# File 'lib/json-schema/validator.rb', line 335

def default_validator
  @@default_validator
end

.deregister_format_validator(format, versions = ["draft1", "draft2", "draft3", "draft4"]) ⇒ Object



377
378
379
380
381
# File 'lib/json-schema/validator.rb', line 377

def deregister_format_validator(format, versions = ["draft1", "draft2", "draft3", "draft4"])
  validators_for_names(versions).each do |validator|
    validator.formats[format.to_s] = validator.default_formats[format.to_s]
  end
end

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



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

def fully_validate(schema, data, opts={})
  opts[:record_errors] = true
  validator = JSON::Validator.new(schema, data, opts)
  validator.validate
end

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



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

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

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



300
301
302
303
304
# File 'lib/json-schema/validator.rb', line 300

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

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



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

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

.json_backendObject



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

def json_backend
  if defined?(MultiJson)
    MultiJson.respond_to?(:adapter) ? MultiJson.adapter : MultiJson.engine
  else
    @@json_backend
  end
end

.json_backend=(backend) ⇒ Object



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

def json_backend=(backend)
  if defined?(MultiJson)
    backend = backend == 'json' ? 'json_gem' : backend
    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.new("The JSON backend '#{backend}' could not be found.")
    end
  end
end

.parse(s) ⇒ Object



411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
# File 'lib/json-schema/validator.rb', line 411

def parse(s)
  if defined?(MultiJson)
    MultiJson.respond_to?(:adapter) ? MultiJson.load(s) : MultiJson.decode(s)
  else
    case @@json_backend.to_s
    when 'json'
      JSON.parse(s)
    when 'yajl'
      json = StringIO.new(s)
      parser = Yajl::Parser.new
      parser.parse(json) or raise JSON::Schema::JsonParseError.new("The JSON could not be parsed by yajl")
    else
      raise JSON::Schema::JsonParseError.new("No supported JSON parsers found. The following parsers are suported:\n * yajl-ruby\n * json")
    end
  end
end

.register_default_validator(v) ⇒ Object



366
367
368
# File 'lib/json-schema/validator.rb', line 366

def register_default_validator(v)
  @@default_validator = v
end

.register_format_validator(format, validation_proc, versions = ["draft1", "draft2", "draft3", "draft4"]) ⇒ Object



370
371
372
373
374
375
# File 'lib/json-schema/validator.rb', line 370

def register_format_validator(format, validation_proc, versions = ["draft1", "draft2", "draft3", "draft4"])
  custom_format_validator = JSON::Schema::CustomFormat.new(validation_proc)
  validators_for_names(versions).each do |validator|
    validator.formats[format.to_s] = custom_format_validator
  end
end

.register_validator(v) ⇒ Object



362
363
364
# File 'lib/json-schema/validator.rb', line 362

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

.restore_default_formats(versions = ["draft1", "draft2", "draft3", "draft4"]) ⇒ Object



383
384
385
386
387
# File 'lib/json-schema/validator.rb', line 383

def restore_default_formats(versions = ["draft1", "draft2", "draft3", "draft4"])
  validators_for_names(versions).each do |validator|
    validator.formats = validator.default_formats.clone
  end
end

.schemasObject



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

def schemas
  @@schemas
end

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



261
262
263
264
265
266
267
268
269
# File 'lib/json-schema/validator.rb', line 261

def validate(schema, data,opts={})
  begin
    validator = JSON::Validator.new(schema, data, opts)
    validator.validate
    return true
  rescue JSON::Schema::ValidationError, JSON::Schema::SchemaError
    return false
  end
end

.validate!(schema, data, opts = {}) ⇒ Object Also known as: validate2



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

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

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



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

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

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



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

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

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



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

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

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



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

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

.validator_for_name(schema_name) ⇒ Object



350
351
352
353
354
355
356
357
358
# File 'lib/json-schema/validator.rb', line 350

def validator_for_name(schema_name)
  return default_validator unless schema_name
  validator = validators_for_names([schema_name]).first
  if validator.nil?
    raise JSON::Schema::SchemaError.new("The requested JSON schema version is not supported")
  else
    validator
  end
end

.validator_for_uri(schema_uri) ⇒ Object Also known as: validator_for



339
340
341
342
343
344
345
346
347
348
# File 'lib/json-schema/validator.rb', line 339

def validator_for_uri(schema_uri)
  return default_validator unless schema_uri
  u = URI.parse(schema_uri)
  validator = validators["#{u.scheme}://#{u.host}#{u.path}"]
  if validator.nil?
    raise JSON::Schema::SchemaError.new("Schema not found: #{schema_uri}")
  else
    validator
  end
end

.validatorsObject



331
332
333
# File 'lib/json-schema/validator.rb', line 331

def validators
  @@validators
end

Instance Method Details

#build_schemas(parent_schema) ⇒ Object

Build all schemas with IDs, mapping out the namespace



158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
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
# File 'lib/json-schema/validator.rb', line 158

def build_schemas(parent_schema)
  # Build ref schemas if they exist
  if parent_schema.schema["$ref"]
    load_ref_schema(parent_schema, parent_schema.schema["$ref"])
  end
  if parent_schema.schema["extends"]
    if parent_schema.schema["extends"].is_a?(String)
      load_ref_schema(parent_schema, parent_schema.schema["extends"])
    elsif parent_schema.schema["extends"].is_a?(Array)
      parent_schema.schema["extends"].each do |type|
        handle_schema(parent_schema, type)
      end
    end
  end

  # handle validations that always contain schemas
  ["allOf", "anyOf", "oneOf", "not"].each do |key|
    if parent_schema.schema.has_key?(key)
      validations = parent_schema.schema[key]
      validations = [validations] unless validations.is_a?(Array)
      validations.each {|v| handle_schema(parent_schema, v) }
    end
  end

  # 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

  # "definitions" are schemas in V4
  if parent_schema.schema["definitions"]
    parent_schema.schema["definitions"].each do |k,v|
      handle_schema(parent_schema, v)
    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
  if parent_schema.schema["patternProperties"]
    parent_schema.schema["patternProperties"].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

  # Convert enum to a ArraySet
  if parent_schema.schema["enum"] && parent_schema.schema["enum"].is_a?(Array)
    parent_schema.schema["enum"] = ArraySet.new(parent_schema.schema["enum"])
  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



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

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

#load_ref_schema(parent_schema, ref) ⇒ Object



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

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 = parent_schema.uri.merge(path)
    end
    uri.fragment = ''
  end

  if Validator.schemas[uri.to_s].nil?
    schema = JSON::Schema.new(JSON::Validator.parse(open(uri.to_s).read), uri, @options[:version])
    Validator.add_schema(schema)
    build_schemas(schema)
  end
end

#schema_from_fragment(base_schema, fragment) ⇒ Object



72
73
74
75
76
77
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
# File 'lib/json-schema/validator.rb', line 72

def schema_from_fragment(base_schema, fragment)
  schema_uri = base_schema.uri
  fragments = fragment.split("/")

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

  fragments.each do |f|
    if base_schema.is_a?(JSON::Schema) #test if fragment is a JSON:Schema instance
      if !base_schema.schema.has_key?(f)
        raise JSON::Schema::SchemaError.new("Invalid fragment resolution for :fragment option")
      end
      base_schema = base_schema.schema[f]
    elsif base_schema.is_a?(Hash)
      if !base_schema.has_key?(f)
        raise JSON::Schema::SchemaError.new("Invalid fragment resolution for :fragment option")
      end
      base_schema = JSON::Schema.new(base_schema[f],schema_uri,@options[:version])
    elsif base_schema.is_a?(Array)
      if base_schema[f.to_i].nil?
        raise JSON::Schema::SchemaError.new("Invalid fragment resolution for :fragment option")
      end
      base_schema = JSON::Schema.new(base_schema[f.to_i],schema_uri,@options[:version])
    else
      raise JSON::Schema::SchemaError.new("Invalid schema encountered when resolving :fragment option")
    end
  end
  if @options[:list] #check if the schema is validating a list
    base_schema.schema = schema_to_list(base_schema.schema)
  end
  base_schema
end

#validateObject

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



108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/json-schema/validator.rb', line 108

def validate()
  begin
    @base_schema.validate(@data,[],self,@validation_options)
    if @validation_options[:clear_cache] == true
      Validator.clear_cache
    end
    if @options[:errors_as_objects]
      return @errors.map{|e| e.to_hash}
    else
      return @errors.map{|e| e.to_string}
    end
  rescue JSON::Schema::ValidationError
    if @validation_options[:clear_cache] == true
      Validator.clear_cache
    end
    raise $!
  end
end

#validation_error(error) ⇒ Object



251
252
253
# File 'lib/json-schema/validator.rb', line 251

def validation_error(error)
  @errors.push(error)
end

#validation_errorsObject



255
256
257
# File 'lib/json-schema/validator.rb', line 255

def validation_errors
  @errors
end