Module: JSON_check

Defined in:
lib/json_check.rb

Constant Summary collapse

@@classes =
[
        'Integer',
        'Float',
        'String',
        'Boolean',
        'URL',
        'Array',
        'Hash',
        'NULL'
]
@@permissible_params =
{
        'Integer' => ['null', 'required', 'enum', 'compare'],
        'Float' => ['null', 'required', 'enum', 'compare', 'integer'],
        'String' => ['null', 'required', 'enum', 'mask'],
        'Boolean' => ['null', 'required', 'enum'],
        'URL'  => ['null', 'required', 'mask', 'empty'],
        'Array' => ['null', 'required', 'empty', 'pattern', 'patterns'],
        'Hash' => ['null', 'required', 'pattern', 'patterns', 'dynamic_key'],
        'NULL' => ['required']
}
@@permissible_values =
{
        'null' => [true, false],
        'required' => [true, false],
        'enum' => Array,
        'mask' => String,
        'pattern' => Hash,
        'patterns' => Array,
        'empty' => [true, false],
        'dynamic_key' => [true, false],
        'compare' => /^(!=|<=|>=|==|<|>)(-?\d+\.\d+|-?\d+)( (or|and) (!=|<=|>=|==|<|>)(-?\d+\.\d+|-?\d+))?$/
}
@@valid_enum_classes =
{
        'Integer' => [Fixnum, Float],
        'Float' => [Fixnum, Float],
        'Boolean' => [FalseClass, TrueClass],
        'String' => [String]
}
@@classes_of_types =
{
        'Integer' => [Fixnum],
        'Float' => [Fixnum, Float],
        'Boolean' => [FalseClass, TrueClass],
        'String' => [String],
        'URL' => [String],
        'Hash' => [Hash],
        'Array' => [Array],
        'NULL' => [NilClass]
}

Class Method Summary collapse

Class Method Details

.add(data, comma, message = nil) ⇒ Object



494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
# File 'lib/json_check.rb', line 494

def self.add data, comma, message = nil
   for_print = JSON.pretty_generate(data)
   for_print.gsub! /^(\{\n|\[\n|\}|\])/, ""
   for_print.gsub! /^[ ]{2}/, "    "*@@print_level
   for_print.gsub! /[ ]{2}/, "    "
   if message
     lines = for_print.split("\n")
     max_length = lines.max_by(&:length).length
     if lines.size > 1
       if comma
         last_line = lines.pop
         lines.push last_line+","
       end
       lines.collect! do |line|
         line+" "*(max_length-line.length+1)+"    #"
       end
       @@log += lines.join("\n") + "    <= #{message}\n"
     else
       @@log += lines.join("\n") + (comma ? "," : "") + "    <= #{message}\n"
     end
   else
     @@log += for_print.chomp + (comma ? ",\n" : "\n")
   end
end

.array(json, ptn, comma, key = nil) ⇒ Object



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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
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
# File 'lib/json_check.rb', line 322

def self.array json, ptn, comma, key=nil 
  last = json.size
  ptn_list = ptn if ptn.class == Array
  num = 1
  if !ptn_list.nil? and ptn_list.size > json.size
    add([json], num != last, "This array does not match the pattern")
    change_status
    failure = true
    return
  end
  @@log += '        '*@@print_level+"#{key.nil? ? '' : wrap(key)+":"}[\n"
  @@print_level += 1
  json.each do |value|
    failure = false
    ptn = ptn_list[num-1] if ptn_list
    if ptn.nil?
      add([value], num != last, "This value is not included in the list of patterns")
      change_status
      failure = true
      num += 1
      next
    end
    case ptn['type']
    when 'Integer'
      unless check_int value, ptn['null']
        add([value], num != last, "It must be Integer")
        failure = true
        change_status
      end
    when 'Float'
      unless check_float value, ptn['null'], ptn['integer']
        add([value], num != last, "It must be Float")
        failure = true
        change_status
      end
    when 'String'
      unless check_str value, ptn['null']
        add([value], num != last, "It must be String")
        failure = true
        change_status
      end
    when 'Boolean'
      unless check_bool value, ptn['null']
        add([value], num != last, "It must be Boolean")
        failure = true
        change_status
      end
    when 'URL'
      unless check_url value, ptn['null'], ptn['empty']
        add([value], num != last, "It must be URL")
        failure = true
        change_status
      end
      unless failure or value == ''
        status = 0
        attempt = 0
        while status != 200 and attempt < 8
          status = url_status(value)
          attempt += 1
        end
        unless status == 200
          failure = true
          change_status
          if status.class == String
            add([value], num != last, "Error: #{status}")
          elsif status == -1
            add([value], num != last, "Too many redirect!")
          else
            add([value], num != last, "Status: #{status}")
          end
        end
      end 
    when 'Array'
      unless check_array value, ptn['null']
        add([value], num != last, "It must be Array")
        failure = true
        change_status
      end 
      if ptn.has_key?('empty') and ptn['empty'] == false
        if value.empty?
          change_status
          failure = true
          add([[]], num != last, "This array must not be empty")
        end
      end
      unless failure 
        array value, (ptn.has_key?('pattern') ? ptn['pattern'] : ptn['patterns']), num != last
      end
      num += 1
      next
    when 'Hash'
      unless check_hash value, ptn['null']
        add([value], num != last, "It must be Hash")
        failure = true
        change_status
      end
      unless failure
        @@log += '        '*@@print_level+"{\n"
        @@print_level += 1
        if ptn.has_key?('patterns')
          hash value, associate(ptn['patterns'], value)
        else       
          hash value, ptn['pattern'], ptn['dynamic_key']
        end
        unless ptn['dynamic_key']
          if ptn.has_key?('patterns')
            missing_keys value, associate(ptn['patterns'], value)
          else
            missing_keys value, ptn['pattern']
          end
        end
        @@print_level -= 1 
        @@log += '        '*@@print_level+"}#{num != last ? "," : ""}\n"
      end
      num += 1
      next 
    end 

    #addition checks
    unless failure
      if ptn.has_key? 'enum'
        unless enum value, ptn['enum']
          add([value], num != last, "This value is not included in the list #{ptn['enum'].to_s}")
          change_status
        else
          add([value], num != last)
        end
      elsif ptn.has_key? 'compare'
        if value.nil?
          num += 1
          next
        end
        unless compare value, ptn['compare']
          add([value], num != last, "This value does not satisfy the condition #{ptn['compare']}")
          change_status
        else
          add([value], num != last)
        end
      elsif ptn.has_key? 'mask'
         next if value.nil?
         unless mask value, ptn['mask']
           add([value], num != last, "This value does not satisfy the regular expression \\#{ptn['mask']}\\")
           change_status
         else
           add([value], num != last)
         end
      else
        add([value], num != last)
      end
    end
    num += 1
  end
  @@print_level -= 1 
  @@log += '        '*@@print_level+"]#{comma ? ',' : ''}\n"
end

.associate(patterns, json) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/json_check.rb', line 61

def self.associate patterns, json
  matches = []
  count = 0
  patterns.each do |ptn|
    ptn.each do |key, value|
      if json.has_key?(key) and (@@classes_of_types[value['type']].include?(json[key].class) or (json[key].class == NilClass and value.has_key?('null')    and value['null'] == true))
        count += 1     
      end
    end
    matches << count
    count = 0
  end
  return patterns[matches.rindex(matches.max)]
end

.change_statusObject



76
77
78
# File 'lib/json_check.rb', line 76

def self.change_status
  @@status = false
end

.check_array(arg, null) ⇒ Object



562
563
564
565
# File 'lib/json_check.rb', line 562

def self.check_array arg, null
  return true if null && arg.class == NilClass
  arg.class == Array
end

.check_bool(arg, null) ⇒ Object



539
540
541
542
# File 'lib/json_check.rb', line 539

def self.check_bool arg, null
  return true if null && arg.class == NilClass
  return (arg.class == TrueClass or arg.class == FalseClass)
end

.check_float(arg, null, integer) ⇒ Object



524
525
526
527
528
# File 'lib/json_check.rb', line 524

def self.check_float arg, null, integer
  return true if null && arg.class == NilClass
  return true if integer && arg.class == Fixnum
  return arg.class == Float
end

.check_hash(arg, null) ⇒ Object



567
568
569
570
# File 'lib/json_check.rb', line 567

def self.check_hash arg, null
  return true if null && arg.class == NilClass
  arg.class == Hash
end

.check_int(arg, null) ⇒ Object



519
520
521
522
# File 'lib/json_check.rb', line 519

def self.check_int arg, null
  return true if null && arg.class == NilClass
  return arg.class == Fixnum 
end

.check_null(arg) ⇒ Object



530
531
532
# File 'lib/json_check.rb', line 530

def self.check_null arg
  arg.class == NilClass
end

.check_pattern(ptn, subkey = nil) ⇒ Object



656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
# File 'lib/json_check.rb', line 656

def self.check_pattern ptn, subkey = nil
  raise "Invalid pattert" if ptn.keys.size == 0
  ptn.each do |key, value|
    if value.class != Hash
      raise "Invalid pattern"
    end
    unless value.has_key? 'type'
      raise "Type is not decleared for #{wrap(subkey.to_s+key)}" # тип должен быть указан для всех ключей
    end
    unless @@classes.include? value['type']
      raise "Invalid type value #{wrap(value['type'])} for #{wrap(subkey.to_s+key)}" # тип должен быть валидным
    end
    keys = value.keys - ['type'] - @@permissible_params[value['type']]
    raise "Invalid key(s) \"#{keys.join('", "')}\" for #{wrap(subkey.to_s+key)}" unless keys.empty?
    raise "Pattern is not decleared for \"#{subkey.to_s+key}\"" if ['Hash', 'Array'].include?(value['type']) and !(value.has_key?('pattern') or value.has_key?('patterns'))
    keys = value.keys - ['type']
    keys.each do |i|
      mask = @@permissible_values[i]
      failure = false
      case mask.class.to_s
      when 'Array'
        failure = true unless mask.include?(value[i]) 
      when 'Class'
        failure = true unless mask == value[i].class
        if i == 'enum' and !failure
          raise "Empty enum array for #{wrap(subkey.to_s+key)}" if value[i].size == 0
          value[i].each do |elem|
            raise "Invalid value #{wrap(elem)} in enum for #{wrap(subkey.to_s+key)}" unless (@@valid_enum_classes[value['type']]+((value.has_key?("null") and value['null'] == true) ? [NilClass] : [])).include?(elem.class)
          end
        end
        if i == 'pattern' and !failure
          if value['type'] == 'Hash'
            check_pattern value['pattern'], "#{subkey ? subkey.to_s+" > " : ""}#{key} > "
            if value.has_key?('dynamic_key') and value['dynamic_key']
              raise "Hash with dynamic_key=true must has one key in pattern" if value['pattern'].keys.size != 1
              raise "Invalid dynamic key value #{value['pattern'].keys[0]}" unless value['pattern'].keys[0].class == String  and check_regex value['pattern'].keys[0]
            end
          else
            check_pattern({"[:pattern:]" => value['pattern']}, "#{subkey ? subkey.to_s+" > " : ""}#{key} > ")
          end 
        end
        if i == 'mask'
          raise "Invalid value #{wrap(value['mask'])} of mask for #{wrap(subkey.to_s+key)}" unless check_regex value['mask']
        end
      when 'Regexp'
        failure = true unless (value[i].class == String and mask === value[i])
      end
      raise "Invalid  value #{wrap(value[i])} of \"#{i}\" for \"#{subkey.to_s+key}\"" if failure
    end
  end 
end

.check_regex(val) ⇒ Object



712
713
714
715
716
717
718
719
# File 'lib/json_check.rb', line 712

def self.check_regex val
  begin
    Regexp.new val
  rescue
    return false    
  end
  return true
end

.check_str(arg, null) ⇒ Object



534
535
536
537
# File 'lib/json_check.rb', line 534

def self.check_str arg, null
  return true if null && arg.class == NilClass
  return  arg.class == String
end

.check_url(arg, null, empty) ⇒ Object



544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
# File 'lib/json_check.rb', line 544

def self.check_url arg, null, empty
  return true if empty && arg.class == String && arg == ''
  return true if null && arg.class == NilClass
  return false unless arg.class == String
  attempt = 0
  begin
      Timeout::timeout(2) { return false unless (/^((https?|ftp):\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})(\S*)*\/?$/ === arg.strip) }
  rescue
      attempt += 1
      if attempt <=3
              retry
      else
              return false
      end
  end
  return true
end

.collate(json, pattern, log_level = 0) ⇒ Object



88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
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
# File 'lib/json_check.rb', line 88

def self.collate json, pattern, log_level = 0
  unless [0, 1].include? log_level
    raise 'Invalid log_level parameter!'
  end
  init
  @@log_level = log_level
  begin
    json = JSON.parse(json)
  rescue
    raise 'Invalid JSON format of input data'
  end
  begin
    ptn = JSON.parse(pattern)
  rescue
    raise 'Invalid JSON format of pattern'
  end
  if ptn.class == Array
    raise 'Invalid pattern' unless [1,2].include? ptn.size
    raise 'Invalid pattern' if ptn.size == 2 and ![true, false, 'dynamic_key'].include? ptn[1]
    check_pattern({"[:pattern:]" => ptn[0]})
  else
    check_pattern ptn
  end
  if ptn.class == Array

    raise 'JSON not match the pattern!' if json.class != Array

    if ptn[1] == false and json.size == 0
      @@log += "[\n\n]    <= This array must be not empty"
      change_status 
    else
      array json, ptn[0], false   
    end
  else
    pattern_keys = []
    ptn.keys.each do |key|
      unless ptn[key].has_key?('required') and ptn[key]['required'] == false
        pattern_keys << key
      end
    end
    
    json_keys = json.keys

    if pattern_keys-json_keys == pattern_keys and !pattern_keys.empty?
      raise 'JSON not match the pattern!'
    end
    
    @@log += "{\n"
    @@print_level += 1

    hash json, ptn
    missing_keys json, ptn

    @@print_level -= 1 
    @@log += "}"
  end
  unless @@status
    raise "\n#{@@log}"
  else
    return true
  end
end

.compare(value, conditions) ⇒ Object



572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
# File 'lib/json_check.rb', line 572

def self.compare value, conditions 
  unless conditions.include?('or') or conditions.include?('and') 
    return compare_action value, conditions 
  else
    result = false
    or_parts = conditions.split(' or ')
    or_parts.each do |part|
      and_parts = part.split(' and ')
      subresult = true
      while and_parts.size != 0
        condition = and_parts.shift
        subresult &&= compare_action(value, condition)
      end
      result ||= subresult
    end
    return result
  end
end

.compare_action(value, condition) ⇒ Object



591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
# File 'lib/json_check.rb', line 591

def self.compare_action value, condition
  params = (/(!=|<=|>=|==|<|>)(-?\d+\.\d+|-?\d+)/.match condition).to_a
  case params[1]
  when '!='
    value != params[2].to_f
  when '<='
    value <= params[2].to_f
  when '>='
    value >= params[2].to_f
  when '=='
    value == params[2].to_f
  when '>'
    value > params[2].to_f
  when '<'
    value < params[2].to_f
  end
end

.enum(value, list_of_values) ⇒ Object



609
610
611
# File 'lib/json_check.rb', line 609

def self.enum value, list_of_values
  list_of_values.include? value
end

.hash(json, ptn, dynamic_key = nil) ⇒ Object



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
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
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
270
271
272
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
# File 'lib/json_check.rb', line 151

def self.hash json, ptn, dynamic_key = nil
    last = json.keys.size
    num = 1 
    json.each do |key, value|
      unless ptn.has_key?(key) or dynamic_key
          add({key => value}, num != last, "Undefined key!")
          change_status
      else
        if dynamic_key
          regex =  Regexp.new ptn.keys[0]
          unless regex === key
            add({key => value}, num != last, "This key does not satisfy the regular expression /#{ptn.keys[0]}/")
            change_status
            num += 1
            next
          end
          c_p = ptn.values[0]
        else
          c_p = ptn[key] #current pattern
        end
        failure = false
        case c_p['type']
        when 'Integer'
          unless check_int value, c_p["null"]
            add({key=>value}, num != last, "It must be Integer")
            failure = true
            change_status
          end
        when 'Float'
          unless check_float value, c_p['null'], c_p['integer']
            add({key=>value}, num != last, "It must be Float")
            failure = true
            change_status
          end
        when 'NULL'
          if check_null value
            add({key => value}, num != last)
          else
            add({key=>value}, num != last, "It must be null")
            change_status
          end
          num += 1
          next
        when 'String'
          unless check_str value, c_p["null"]
            add({key=>value}, num != last, "It must be String")
            failure = true
            change_status
          end
        when 'Boolean'
          unless check_bool value, c_p["null"]
            add({key=>value}, num != last, "It must be Boolean")
            failure = true
            change_status
          end
        when 'URL'
          unless check_url value, c_p["null"], c_p["empty"]
            add({key=>value}, num != last, "It must be URL")
            failure = true
            change_status
          end
          unless failure or value.nil? or value == ''
     status = 0
            attempt = 0
            while status != 200 and attempt < 8
              status = url_status(value)
              attempt += 1
            end
            unless status == 200
              failure = true
              change_status
              if status.class == String
                add({key=>value}, num != last, "Error: #{status}")
              elsif status == -1
                add({key=>value}, num != last, "Too many redirect!")
              else
                add({key=>value}, num != last, "Status: #{status}")
              end
            end
          end 
        when 'Array'
          unless check_array value, c_p["null"]
            add({key=>value}, num != last, "It must be Array")
            failure = true
            change_status
          end
          if value.nil? and !failure
            add({key => value}, num != last)
            num += 1
            next
          end
          if c_p.has_key?('empty') and c_p['empty'] == false
            if value.empty?
              change_status
              failure = true
              add({key=>value}, num != last, "This array must not be empty")
            end
          end
          unless failure
            array value, (c_p.has_key?('pattern') ? c_p['pattern'] : c_p['patterns']), num != last, key
          end
          num += 1
          next
        when 'Hash'
          unless check_hash value, c_p["null"]
            add({key=>value}, num != last, "It must be Hash")
            failure = true
            change_status
          end
          if value.nil? and !failure
            add({key => value}, num != last)
            num += 1
            next
          end
          unless failure
            @@log += '        '*@@print_level+"\"#{key}\":{\n"
            @@print_level += 1
            if c_p.has_key?('patterns')
              hash value, associate(c_p['patterns'], value)
            else
              hash value, c_p['pattern'], c_p['dynamic_key']
            end
            unless c_p['dynamic_key']
              if c_p.has_key?('patterns')
                missing_keys value, associate(c_p['patterns'], value)
              else
                missing_keys value, c_p['pattern']   
              end
            end
            @@print_level -= 1 
            @@log += '        '*@@print_level+"}#{num != last ? "," : ""}\n"
          end
          num += 1
          next 
        end 

        #addition checks
        unless failure
          if c_p.has_key? 'enum'
            unless enum value, c_p['enum']
              add({key=>value}, num != last, "This value is not included in the list #{c_p['enum'].to_s}")
              change_status
            else
              add({key => value}, num != last)
            end
          elsif c_p.has_key? 'compare'
            next if value.nil?
            unless compare value, c_p['compare']
              add({key=>value}, num != last, "This value does not satisfy the condition #{c_p['compare']}")
              change_status
            else
              add({key => value}, num != last)
            end
          elsif c_p.has_key? 'mask'
             next if value.nil?
             unless mask value, c_p['mask']
               add({key => value}, num != last, "This value does not satisfy the regular expression \\#{c_p['mask']}\\")
               change_status
             else
               add({key => value}, num != last)
             end
          else
            add({key => value}, num != last)
          end
        end

      end
      num += 1
    end
end

.initObject



80
81
82
83
84
85
86
# File 'lib/json_check.rb', line 80

def self.init
  @@log = ""
  @@print_level = 0
  @@redirect_level = 0
  @@log_level = 0
  @@status = true
end

.mask(value, regex) ⇒ Object



613
614
615
616
# File 'lib/json_check.rb', line 613

def self.mask value, regex
  mask = Regexp.new regex
  return mask === value
end

.missing_keys(json, ptn) ⇒ Object



478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
# File 'lib/json_check.rb', line 478

def self.missing_keys json, ptn
  keys = []
  ptn.each_key do |key|
    unless ptn[key].has_key?('required') and ptn[key]['required'] == false
      keys << key
    end
  end
  keys = keys - json.keys
  if keys.size>0
    change_status
    keys.each do |key|
      add({key => 'This key is declared, but not found!'}, true, "Key is missing!")
    end 
  end
end

.resetObject



618
619
620
# File 'lib/json_check.rb', line 618

def self.reset
  @@redirect_level = 0
end

.url_status(url) ⇒ Object



622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
# File 'lib/json_check.rb', line 622

def self.url_status url
  begin
    link = URI.parse(url)
    resp = Net::HTTP.start(link.host, link.port){|http| 
                                       http.read_timeout = 60
                                       http.head(link)
                                     }
    http_status = resp.code.to_i
    case http_status
    when 200
      reset
      return 200
    when 302, 301
       @@redirect_level += 1
       if @@redirect_level > 10
         reset
         return -1
       end
       tmp_url = resp['location']
       tmp_link = URI.parse(tmp_url)
       if tmp_link.host == nil
         tmp_url = link.scheme+'://'+link.host+tmp_url
       end
       return url_status tmp_url
    else
      reset
      return http_status
    end
  rescue Exception => e
    reset
    return e.to_s
  end
end

.wrap(val) ⇒ Object



708
709
710
# File 'lib/json_check.rb', line 708

def self.wrap val
  val.nil? ? 'null' : (val.class == String ? '"'+val+'"': val.to_s )
end