Class: JSON::Validator
- Inherits:
-
Object
- Object
- JSON::Validator
- 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 }
- @@validators =
{}
- @@default_validator =
nil
- @@available_json_backends =
[]
- @@json_backend =
'yajl'
- @@serializer =
lambda{|o| YAML.dump(o) }
- @@mutex =
Mutex.new
Class Method Summary collapse
- .add_schema(schema) ⇒ Object
- .cache_schemas=(val) ⇒ Object
- .clear_cache ⇒ Object
- .default_validator ⇒ Object
- .fully_validate(schema, data, opts = {}) ⇒ Object
- .fully_validate_json(schema, data, opts = {}) ⇒ Object
- .fully_validate_schema(schema, opts = {}) ⇒ Object
- .fully_validate_uri(schema, data, opts = {}) ⇒ Object
- .json_backend ⇒ Object
- .json_backend=(backend) ⇒ Object
- .metaschema_for(version_string) ⇒ Object
- .parse(s) ⇒ Object
- .register_default_validator(v) ⇒ Object
- .register_validator(v) ⇒ Object
- .schemas ⇒ Object
- .validate(schema, data, opts = {}) ⇒ Object
- .validate!(schema, data, opts = {}) ⇒ Object (also: validate2)
- .validate_json(schema, data, opts = {}) ⇒ Object
- .validate_json!(schema, data, opts = {}) ⇒ Object
- .validate_uri(schema, data, opts = {}) ⇒ Object
- .validate_uri!(schema, data, opts = {}) ⇒ Object
- .validators ⇒ Object
- .version_string_for(version) ⇒ Object
Instance Method Summary collapse
-
#build_schemas(parent_schema) ⇒ Object
Build all schemas with IDs, mapping out the namespace.
-
#handle_schema(parent_schema, obj) ⇒ Object
Either load a reference schema or create a new schema.
-
#initialize(schema_data, data, opts = {}) ⇒ Validator
constructor
A new instance of Validator.
- #load_ref_schema(parent_schema, ref) ⇒ Object
- #schema_from_fragment(base_schema, fragment) ⇒ Object
-
#validate ⇒ Object
Run a simple true/false validation of data against a schema.
- #validation_error(error) ⇒ Object
- #validation_errors ⇒ Object
Constructor Details
#initialize(schema_data, data, opts = {}) ⇒ Validator
Returns a new instance of Validator.
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 170 171 172 173 174 175 176 177 178 179 180 181 182 |
# File 'lib/json-schema/validator.rb', line 145 def initialize(schema_data, data, opts={}) @options = @@default_opts.clone.merge(opts) @errors = [] # I'm not a fan of this, but it's quick and dirty to get it working for now version_string = "draft-04" if @options[:version] version_string = @options[:version] = self.class.version_string_for(@options[:version]) u = URI.parse("http://json-schema.org/#{@options[:version]}/schema#") validator = JSON::Validator.validators["#{u.scheme}://#{u.host}#{u.path}"] @options[:version] = validator end @validation_options = @options[:record_errors] ? {:record_errors => true} : {} @validation_options[:insert_defaults] = true if @options[:insert_defaults] @@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"] version_string = @options[:version] = self.class.version_string_for(@base_schema.schema["$schema"]) end = JSON::Validator.new(self.class.(version_string), @base_schema.schema) .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
441 442 443 |
# File 'lib/json-schema/validator.rb', line 441 def add_schema(schema) @@schemas[schema.uri.to_s] = schema if @@schemas[schema.uri.to_s].nil? end |
.cache_schemas=(val) ⇒ Object
445 446 447 |
# File 'lib/json-schema/validator.rb', line 445 def cache_schemas=(val) @@cache_schemas = val == true ? true : false end |
.clear_cache ⇒ Object
433 434 435 |
# File 'lib/json-schema/validator.rb', line 433 def clear_cache @@schemas = {} if @@cache_schemas == false end |
.default_validator ⇒ Object
453 454 455 |
# File 'lib/json-schema/validator.rb', line 453 def default_validator @@default_validator end |
.fully_validate(schema, data, opts = {}) ⇒ Object
413 414 415 416 417 |
# File 'lib/json-schema/validator.rb', line 413 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
425 426 427 |
# File 'lib/json-schema/validator.rb', line 425 def fully_validate_json(schema, data, opts={}) fully_validate(schema, data, opts.merge(:json => true)) end |
.fully_validate_schema(schema, opts = {}) ⇒ Object
419 420 421 422 423 |
# File 'lib/json-schema/validator.rb', line 419 def fully_validate_schema(schema, opts={}) data = schema schema = (version_string_for(opts[:version])) fully_validate(schema, data, opts) end |
.fully_validate_uri(schema, data, opts = {}) ⇒ Object
429 430 431 |
# File 'lib/json-schema/validator.rb', line 429 def fully_validate_uri(schema, data, opts={}) fully_validate(schema, data, opts.merge(:uri => true)) end |
.json_backend ⇒ Object
465 466 467 468 469 470 471 |
# File 'lib/json-schema/validator.rb', line 465 def json_backend if defined?(MultiJson) MultiJson.respond_to?(:adapter) ? MultiJson.adapter : MultiJson.engine else @@json_backend end end |
.json_backend=(backend) ⇒ Object
473 474 475 476 477 478 479 480 481 482 483 484 485 |
# File 'lib/json-schema/validator.rb', line 473 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 |
.metaschema_for(version_string) ⇒ Object
141 142 143 |
# File 'lib/json-schema/validator.rb', line 141 def self.(version_string) File.join(Pathname.new(File.dirname(__FILE__)).parent.parent, "resources", "#{version_string}.json").to_s end |
.parse(s) ⇒ Object
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 |
# File 'lib/json-schema/validator.rb', line 487 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) 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
461 462 463 |
# File 'lib/json-schema/validator.rb', line 461 def register_default_validator(v) @@default_validator = v end |
.register_validator(v) ⇒ Object
457 458 459 |
# File 'lib/json-schema/validator.rb', line 457 def register_validator(v) @@validators[v.to_s] = v end |
.schemas ⇒ Object
437 438 439 |
# File 'lib/json-schema/validator.rb', line 437 def schemas @@schemas end |
.validate(schema, data, opts = {}) ⇒ Object
380 381 382 383 384 385 386 387 388 |
# File 'lib/json-schema/validator.rb', line 380 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
398 399 400 401 402 |
# File 'lib/json-schema/validator.rb', line 398 def validate!(schema, data,opts={}) validator = JSON::Validator.new(schema, data, opts) validator.validate return true end |
.validate_json(schema, data, opts = {}) ⇒ Object
390 391 392 |
# File 'lib/json-schema/validator.rb', line 390 def validate_json(schema, data, opts={}) validate(schema, data, opts.merge(:json => true)) end |
.validate_json!(schema, data, opts = {}) ⇒ Object
405 406 407 |
# File 'lib/json-schema/validator.rb', line 405 def validate_json!(schema, data, opts={}) validate!(schema, data, opts.merge(:json => true)) end |
.validate_uri(schema, data, opts = {}) ⇒ Object
394 395 396 |
# File 'lib/json-schema/validator.rb', line 394 def validate_uri(schema, data, opts={}) validate(schema, data, opts.merge(:uri => true)) end |
.validate_uri!(schema, data, opts = {}) ⇒ Object
409 410 411 |
# File 'lib/json-schema/validator.rb', line 409 def validate_uri!(schema, data, opts={}) validate!(schema, data, opts.merge(:uri => true)) end |
.validators ⇒ Object
449 450 451 |
# File 'lib/json-schema/validator.rb', line 449 def validators @@validators end |
.version_string_for(version) ⇒ Object
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 |
# File 'lib/json-schema/validator.rb', line 124 def self.version_string_for(version) # I'm not a fan of this, but it's quick and dirty to get it working for now return "draft-04" unless version case version.to_s when "draft4", "http://json-schema.org/draft-04/schema#" "draft-04" when "draft3", "http://json-schema.org/draft-03/schema#" "draft-03" when "draft2" "draft-02" when "draft1" "draft-01" else raise JSON::Schema::SchemaError.new("The requested JSON schema version is not supported") end end |
Instance Method Details
#build_schemas(parent_schema) ⇒ Object
Build all schemas with IDs, mapping out the namespace
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 |
# File 'lib/json-schema/validator.rb', line 273 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 hash if parent_schema.schema["enum"] && parent_schema.schema["enum"].is_a?(Array) enum_hash = {} parent_schema.schema["enum"].each do |item| enum_hash[item] = true end parent_schema.schema["enum"] = enum_hash 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
359 360 361 362 363 364 365 366 367 368 |
# File 'lib/json-schema/validator.rb', line 359 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
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 |
# File 'lib/json-schema/validator.rb', line 235 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? begin schema = JSON::Schema.new(JSON::Validator.parse(open(uri.to_s).read), uri, @options[:version]) 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 Exception # 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 |
#schema_from_fragment(base_schema, fragment) ⇒ Object
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 |
# File 'lib/json-schema/validator.rb', line 184 def schema_from_fragment(base_schema, fragment) 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 = initialize_schema(base_schema[f]) #need to return a Schema instance for validation to work 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 = initialize_schema(base_schema[f.to_i]) 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 |
#validate ⇒ Object
Run a simple true/false validation of data against a schema
219 220 221 222 223 224 225 226 227 228 229 230 231 232 |
# File 'lib/json-schema/validator.rb', line 219 def validate() begin @base_schema.validate(@data,[],self,@validation_options) Validator.clear_cache 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 Validator.clear_cache raise $! end end |
#validation_error(error) ⇒ Object
370 371 372 |
# File 'lib/json-schema/validator.rb', line 370 def validation_error(error) @errors.push(error) end |
#validation_errors ⇒ Object
374 375 376 |
# File 'lib/json-schema/validator.rb', line 374 def validation_errors @errors end |