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
}
@@validators =
{}
@@default_validator =
nil
@@available_json_backends =
[]
@@json_backend =
'yajl'
@@errors =
[]
@@serializer =
lambda{|o| Marshal.dump(o) }

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Validator.



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

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

  # I'm not a fan of this, but it's quick and dirty to get it working for now
  version_string = "draft-03"
  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} : {}
  
  # validate the schema, if requested
  if @options[:validate_schema]
    begin
      meta_validator = JSON::Validator.new(self.class.metaschema_for(version_string), schema_data)
      meta_validator.validate
    rescue JSON::Schema::ValidationError, JSON::Schema::SchemaError
      raise $!
    end
  end
  
  @base_schema = initialize_schema(schema_data)
  @data = initialize_data(data)
  build_schemas(@base_schema)
end

Class Method Details

.add_schema(schema) ⇒ Object



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

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

.cache_schemas=(val) ⇒ Object



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

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

.clear_cacheObject



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

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

.clear_errorsObject



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

def clear_errors
  @@errors = []
end

.default_validatorObject



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

def default_validator
  @@default_validator
end

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



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

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

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



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

def fully_validate_schema(schema, opts={})
  data = schema
  schema = metaschema_for(version_string_for(opts[:version]))
  fully_validate(schema, data, opts)
end

.json_backendObject



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

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

.json_backend=(backend) ⇒ Object



334
335
336
337
338
339
340
341
342
343
344
345
346
# File 'lib/json-schema/validator.rb', line 334

def json_backend=(backend)
  if defined?(MultiJson)
    backend = backend == 'json' ? 'json_gem' : 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



111
112
113
# File 'lib/json-schema/validator.rb', line 111

def self.metaschema_for(version_string)
  File.join(Pathname.new(File.dirname(__FILE__)).parent.parent, "resources", "#{version_string}.json").to_s
end

.parse(s) ⇒ Object



348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
# File 'lib/json-schema/validator.rb', line 348

def parse(s)
  if defined?(MultiJson)
    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



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

def register_default_validator(v)
  @@default_validator = v
end

.register_validator(v) ⇒ Object



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

def register_validator(v)
  @@validators[v.to_s] = v
end

.schemasObject



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

def schemas
  @@schemas
end

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



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

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



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

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

.validation_error(error) ⇒ Object



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

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

.validatorsObject



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

def validators
  @@validators
end

.version_string_for(version) ⇒ Object



96
97
98
99
100
101
102
103
104
105
106
107
108
109
# File 'lib/json-schema/validator.rb', line 96

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-03" unless version
  case version.to_s
  when "draft3"
    "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



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

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

  # 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



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

def handle_schema(parent_schema, obj)
  schema_uri = parent_schema.uri.clone
  schema = JSON::Schema.new(obj,schema_uri,@options[:version])
  if obj['id']
    Validator.add_schema(schema)
  end
  build_schemas(schema)
end

#load_ref_schema(parent_schema, ref) ⇒ Object



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

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

#validateObject

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



146
147
148
149
150
151
152
153
154
155
156
# File 'lib/json-schema/validator.rb', line 146

def validate()
  begin
    Validator.clear_errors
    @base_schema.validate(@data,[],@validation_options)
    Validator.clear_cache
    @@errors
  rescue JSON::Schema::ValidationError
    Validator.clear_cache
    raise $!
  end
end