-
Notifications
You must be signed in to change notification settings - Fork 83
/
Copy pathjson-validator.cpp
1472 lines (1233 loc) · 43.4 KB
/
json-validator.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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
71
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
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
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
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
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
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
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
655
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
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* JSON schema validator for JSON for modern C++
*
* Copyright (c) 2016-2019 Patrick Boettcher <[email protected]>.
*
* SPDX-License-Identifier: MIT
*
*/
#include <nlohmann/json-schema.hpp>
#include "json-patch.hpp"
#include <deque>
#include <memory>
#include <set>
#include <sstream>
#include <string>
using nlohmann::json;
using nlohmann::json_patch;
using nlohmann::json_uri;
using nlohmann::json_schema::root_schema;
using namespace nlohmann::json_schema;
#ifdef JSON_SCHEMA_BOOST_REGEX
# include <boost/regex.hpp>
# define REGEX_NAMESPACE boost
#elif defined(JSON_SCHEMA_NO_REGEX)
# define NO_STD_REGEX
#else
# include <regex>
# define REGEX_NAMESPACE std
#endif
namespace
{
class schema
{
protected:
root_schema *root_;
json default_value_ = nullptr;
protected:
virtual std::shared_ptr<schema> make_for_default_(
std::shared_ptr<::schema> & /* sch */,
root_schema * /* root */,
std::vector<nlohmann::json_uri> & /* uris */,
nlohmann::json & /* default_value */) const
{
return nullptr;
};
public:
virtual ~schema() = default;
schema(root_schema *root)
: root_(root) {}
virtual void validate(const json::json_pointer &ptr, const json &instance, json_patch &patch, error_handler &e) const = 0;
virtual const json &default_value(const json::json_pointer &, const json &, error_handler &) const
{
return default_value_;
}
void set_default_value(const json &v) { default_value_ = v; }
static std::shared_ptr<schema> make(json &schema,
root_schema *root,
const std::vector<std::string> &key,
std::vector<nlohmann::json_uri> uris);
};
class schema_ref : public schema
{
const std::string id_;
std::weak_ptr<schema> target_;
std::shared_ptr<schema> target_strong_; // for references to references keep also the shared_ptr because
// no one else might use it after resolving
void validate(const json::json_pointer &ptr, const json &instance, json_patch &patch, error_handler &e) const final
{
auto target = target_.lock();
if (target)
target->validate(ptr, instance, patch, e);
else
e.error(ptr, instance, "unresolved or freed schema-reference " + id_);
}
const json &default_value(const json::json_pointer &ptr, const json &instance, error_handler &e) const override final
{
if (!default_value_.is_null())
return default_value_;
auto target = target_.lock();
if (target)
return target->default_value(ptr, instance, e);
e.error(ptr, instance, "unresolved or freed schema-reference " + id_);
return default_value_;
}
protected:
virtual std::shared_ptr<schema> make_for_default_(
std::shared_ptr<::schema> &sch,
root_schema *root,
std::vector<nlohmann::json_uri> &uris,
nlohmann::json &default_value) const override
{
// create a new reference schema using the original reference (which will be resolved later)
// to store this overloaded default value #209
auto result = std::make_shared<schema_ref>(uris[0].to_string(), root);
result->set_target(sch, true);
result->set_default_value(default_value);
return result;
};
public:
schema_ref(const std::string &id, root_schema *root)
: schema(root), id_(id) {}
const std::string &id() const { return id_; }
void set_target(const std::shared_ptr<schema> &target, bool strong = false)
{
target_ = target;
if (strong)
target_strong_ = target;
}
};
} // namespace
namespace nlohmann
{
namespace json_schema
{
class root_schema
{
schema_loader loader_;
format_checker format_check_;
content_checker content_check_;
std::shared_ptr<schema> root_;
struct schema_file {
std::map<std::string, std::shared_ptr<schema>> schemas;
std::map<std::string, std::shared_ptr<schema_ref>> unresolved; // contains all unresolved references from any other file seen during parsing
json unknown_keywords;
};
// location as key
std::map<std::string, schema_file> files_;
schema_file &get_or_create_file(const std::string &loc)
{
auto file = files_.lower_bound(loc);
if (file != files_.end() && !(files_.key_comp()(loc, file->first)))
return file->second;
else
return files_.insert(file, {loc, {}})->second;
}
public:
root_schema(schema_loader &&loader,
format_checker &&format,
content_checker &&content)
: loader_(std::move(loader)),
format_check_(std::move(format)),
content_check_(std::move(content))
{
}
format_checker &format_check() { return format_check_; }
content_checker &content_check() { return content_check_; }
void insert(const json_uri &uri, const std::shared_ptr<schema> &s)
{
auto &file = get_or_create_file(uri.location());
auto sch = file.schemas.lower_bound(uri.fragment());
if (sch != file.schemas.end() && !(file.schemas.key_comp()(uri.fragment(), sch->first))) {
throw std::invalid_argument("schema with " + uri.to_string() + " already inserted");
return;
}
file.schemas.insert({uri.fragment(), s});
// was someone referencing this newly inserted schema?
auto unresolved = file.unresolved.find(uri.fragment());
if (unresolved != file.unresolved.end()) {
unresolved->second->set_target(s);
file.unresolved.erase(unresolved);
}
}
void insert_unknown_keyword(const json_uri &uri, const std::string &key, json &value)
{
auto &file = get_or_create_file(uri.location());
auto new_uri = uri.append(key);
auto fragment = new_uri.pointer();
// is there a reference looking for this unknown-keyword, which is thus no longer a unknown keyword but a schema
auto unresolved = file.unresolved.find(fragment.to_string());
if (unresolved != file.unresolved.end())
schema::make(value, this, {}, {{new_uri}});
else { // no, nothing ref'd it, keep for later
// need to create an object for each reference-token in the
// JSON-Pointer When not existing, a stringified integer reference
// token (e.g. "123") in the middle of the pointer will be
// interpreted a an array-index and an array will be created.
// json_pointer's reference_tokens is private - get them
std::deque<std::string> ref_tokens;
auto uri_pointer = uri.pointer();
while (!uri_pointer.empty()) {
ref_tokens.push_front(uri_pointer.back());
uri_pointer.pop_back();
}
// for each token create an object, if not already existing
auto unk_kw = &file.unknown_keywords;
for (auto &rt : ref_tokens) {
auto existing_object = unk_kw->find(rt);
if (existing_object == unk_kw->end())
(*unk_kw)[rt] = json::object();
unk_kw = &(*unk_kw)[rt];
}
(*unk_kw)[key] = value;
}
// recursively add possible subschemas of unknown keywords
if (value.type() == json::value_t::object)
for (auto &subsch : value.items())
insert_unknown_keyword(new_uri, subsch.key(), subsch.value());
}
std::shared_ptr<schema> get_or_create_ref(const json_uri &uri)
{
auto &file = get_or_create_file(uri.location());
// existing schema
auto sch = file.schemas.find(uri.fragment());
if (sch != file.schemas.end())
return sch->second;
// referencing an unknown keyword, turn it into schema
//
// an unknown keyword can only be referenced by a json-pointer,
// not by a plain name fragment
if (uri.pointer().to_string() != "") {
try {
auto &subschema = file.unknown_keywords.at(uri.pointer()); // null is returned if not existing
auto s = schema::make(subschema, this, {}, {{uri}}); // A JSON Schema MUST be an object or a boolean.
if (s) { // nullptr if invalid schema, e.g. null
file.unknown_keywords.erase(uri.fragment());
return s;
}
} catch (nlohmann::detail::out_of_range &) { // at() did not find it
}
}
// get or create a schema_ref
auto r = file.unresolved.lower_bound(uri.fragment());
if (r != file.unresolved.end() && !(file.unresolved.key_comp()(uri.fragment(), r->first))) {
return r->second; // unresolved, already seen previously - use existing reference
} else {
return file.unresolved.insert(r,
{uri.fragment(), std::make_shared<schema_ref>(uri.to_string(), this)})
->second; // unresolved, create reference
}
}
void set_root_schema(json sch)
{
files_.clear();
root_ = schema::make(sch, this, {}, {{"#"}});
// load all files which have not yet been loaded
do {
bool new_schema_loaded = false;
// files_ is modified during parsing, iterators are invalidated
std::vector<std::string> locations;
for (auto &file : files_)
locations.push_back(file.first);
for (auto &loc : locations) {
if (files_[loc].schemas.size() == 0) { // nothing has been loaded for this file
if (loader_) {
json loaded_schema;
loader_(loc, loaded_schema);
schema::make(loaded_schema, this, {}, {{loc}});
new_schema_loaded = true;
} else {
throw std::invalid_argument("external schema reference '" + loc + "' needs loading, but no loader callback given");
}
}
}
if (!new_schema_loaded) // if no new schema loaded, no need to try again
break;
} while (1);
for (const auto &file : files_) {
if (file.second.unresolved.size() != 0) {
// Build a representation of the undefined
// references as a list of comma-separated strings.
auto n_urefs = file.second.unresolved.size();
std::string urefs = "[";
decltype(n_urefs) counter = 0;
for (const auto &p : file.second.unresolved) {
urefs += p.first;
if (counter != n_urefs - 1u) {
urefs += ", ";
}
++counter;
}
urefs += "]";
throw std::invalid_argument("after all files have been parsed, '" +
(file.first == "" ? "<root>" : file.first) +
"' has still the following undefined references: " + urefs);
}
}
}
void validate(const json::json_pointer &ptr,
const json &instance,
json_patch &patch,
error_handler &e,
const json_uri &initial) const
{
if (!root_) {
e.error(ptr, "", "no root schema has yet been set for validating an instance");
return;
}
auto file_entry = files_.find(initial.location());
if (file_entry == files_.end()) {
e.error(ptr, "", "no file found serving requested root-URI. " + initial.location());
return;
}
auto &file = file_entry->second;
auto sch = file.schemas.find(initial.fragment());
if (sch == file.schemas.end()) {
e.error(ptr, "", "no schema find for request initial URI: " + initial.to_string());
return;
}
sch->second->validate(ptr, instance, patch, e);
}
};
} // namespace json_schema
} // namespace nlohmann
namespace
{
class first_error_handler : public error_handler
{
public:
bool error_{false};
json::json_pointer ptr_;
json instance_;
std::string message_;
void error(const json::json_pointer &ptr, const json &instance, const std::string &message) override
{
if (*this)
return;
error_ = true;
ptr_ = ptr;
instance_ = instance;
message_ = message;
}
operator bool() const { return error_; }
};
class logical_not : public schema
{
std::shared_ptr<schema> subschema_;
void validate(const json::json_pointer &ptr, const json &instance, json_patch &patch, error_handler &e) const final
{
first_error_handler esub;
subschema_->validate(ptr, instance, patch, esub);
if (!esub)
e.error(ptr, instance, "the subschema has succeeded, but it is required to not validate");
}
const json &default_value(const json::json_pointer &ptr, const json &instance, error_handler &e) const override
{
return subschema_->default_value(ptr, instance, e);
}
public:
logical_not(json &sch,
root_schema *root,
const std::vector<nlohmann::json_uri> &uris)
: schema(root)
{
subschema_ = schema::make(sch, root, {"not"}, uris);
}
};
enum logical_combination_types {
allOf,
anyOf,
oneOf
};
template <enum logical_combination_types combine_logic>
class logical_combination : public schema
{
std::vector<std::shared_ptr<schema>> subschemata_;
void validate(const json::json_pointer &ptr, const json &instance, json_patch &patch, error_handler &e) const final
{
size_t count = 0;
for (auto &s : subschemata_) {
first_error_handler esub;
auto oldPatchSize = patch.get_json().size();
s->validate(ptr, instance, patch, esub);
if (!esub)
count++;
else
patch.get_json().get_ref<nlohmann::json::array_t &>().resize(oldPatchSize);
if (is_validate_complete(instance, ptr, e, esub, count))
return;
}
// could accumulate esub details for anyOf and oneOf, but not clear how to select which subschema failure to report
// or how to report multiple such failures
if (count == 0)
e.error(ptr, instance, "no subschema has succeeded, but one of them is required to validate");
}
// specialized for each of the logical_combination_types
static const std::string key;
static bool is_validate_complete(const json &, const json::json_pointer &, error_handler &, const first_error_handler &, size_t);
public:
logical_combination(json &sch,
root_schema *root,
const std::vector<nlohmann::json_uri> &uris)
: schema(root)
{
size_t c = 0;
for (auto &subschema : sch)
subschemata_.push_back(schema::make(subschema, root, {key, std::to_string(c++)}, uris));
// value of allOf, anyOf, and oneOf "MUST be a non-empty array"
// TODO error/throw? when subschemata_.empty()
}
};
template <>
const std::string logical_combination<allOf>::key = "allOf";
template <>
const std::string logical_combination<anyOf>::key = "anyOf";
template <>
const std::string logical_combination<oneOf>::key = "oneOf";
template <>
bool logical_combination<allOf>::is_validate_complete(const json &, const json::json_pointer &, error_handler &e, const first_error_handler &esub, size_t)
{
if (esub)
e.error(esub.ptr_, esub.instance_, "at least one subschema has failed, but all of them are required to validate - " + esub.message_);
return esub;
}
template <>
bool logical_combination<anyOf>::is_validate_complete(const json &, const json::json_pointer &, error_handler &, const first_error_handler &, size_t count)
{
return count == 1;
}
template <>
bool logical_combination<oneOf>::is_validate_complete(const json &instance, const json::json_pointer &ptr, error_handler &e, const first_error_handler &, size_t count)
{
if (count > 1)
e.error(ptr, instance, "more than one subschema has succeeded, but exactly one of them is required to validate");
return count > 1;
}
class type_schema : public schema
{
std::vector<std::shared_ptr<schema>> type_;
std::pair<bool, json> enum_, const_;
std::vector<std::shared_ptr<schema>> logic_;
static std::shared_ptr<schema> make(json &schema,
json::value_t type,
root_schema *,
const std::vector<nlohmann::json_uri> &,
std::set<std::string> &);
std::shared_ptr<schema> if_, then_, else_;
void validate(const json::json_pointer &ptr, const json &instance, json_patch &patch, error_handler &e) const override final
{
// depending on the type of instance run the type specific validator - if present
auto type = type_[static_cast<uint8_t>(instance.type())];
if (type)
type->validate(ptr, instance, patch, e);
else
e.error(ptr, instance, "unexpected instance type");
if (enum_.first) {
bool seen_in_enum = false;
for (auto &v : enum_.second)
if (instance == v) {
seen_in_enum = true;
break;
}
if (!seen_in_enum)
e.error(ptr, instance, "instance not found in required enum");
}
if (const_.first &&
const_.second != instance)
e.error(ptr, instance, "instance not const");
for (auto l : logic_)
l->validate(ptr, instance, patch, e);
if (if_) {
first_error_handler err;
if_->validate(ptr, instance, patch, err);
if (!err) {
if (then_)
then_->validate(ptr, instance, patch, e);
} else {
if (else_)
else_->validate(ptr, instance, patch, e);
}
}
if (instance.is_null()) {
patch.add(nlohmann::json::json_pointer{}, default_value_);
}
}
protected:
virtual std::shared_ptr<schema> make_for_default_(
std::shared_ptr<::schema> & /* sch */,
root_schema * /* root */,
std::vector<nlohmann::json_uri> & /* uris */,
nlohmann::json &default_value) const override
{
auto result = std::make_shared<type_schema>(*this);
result->set_default_value(default_value);
return result;
};
public:
type_schema(json &sch,
root_schema *root,
const std::vector<nlohmann::json_uri> &uris)
: schema(root), type_(static_cast<uint8_t>(json::value_t::discarded) + 1)
{
// association between JSON-schema-type and NLohmann-types
static const std::vector<std::pair<std::string, json::value_t>> schema_types = {
{"null", json::value_t::null},
{"object", json::value_t::object},
{"array", json::value_t::array},
{"string", json::value_t::string},
{"boolean", json::value_t::boolean},
{"integer", json::value_t::number_integer},
{"number", json::value_t::number_float},
};
std::set<std::string> known_keywords;
auto attr = sch.find("type");
if (attr == sch.end()) // no type field means all sub-types possible
for (auto &t : schema_types)
type_[static_cast<uint8_t>(t.second)] = type_schema::make(sch, t.second, root, uris, known_keywords);
else {
switch (attr.value().type()) { // "type": "type"
case json::value_t::string: {
auto schema_type = attr.value().get<std::string>();
for (auto &t : schema_types)
if (t.first == schema_type)
type_[static_cast<uint8_t>(t.second)] = type_schema::make(sch, t.second, root, uris, known_keywords);
} break;
case json::value_t::array: // "type": ["type1", "type2"]
for (auto &array_value : attr.value()) {
auto schema_type = array_value.get<std::string>();
for (auto &t : schema_types)
if (t.first == schema_type)
type_[static_cast<uint8_t>(t.second)] = type_schema::make(sch, t.second, root, uris, known_keywords);
}
break;
default:
break;
}
sch.erase(attr);
}
attr = sch.find("default");
if (attr != sch.end()) {
set_default_value(attr.value());
sch.erase(attr);
}
for (auto &key : known_keywords)
sch.erase(key);
// with nlohmann::json float instance (but number in schema-definition) can be seen as unsigned or integer -
// reuse the number-validator for integer values as well, if they have not been specified explicitly
if (type_[static_cast<uint8_t>(json::value_t::number_float)] && !type_[static_cast<uint8_t>(json::value_t::number_integer)])
type_[static_cast<uint8_t>(json::value_t::number_integer)] = type_[static_cast<uint8_t>(json::value_t::number_float)];
// #54: JSON-schema does not differentiate between unsigned and signed integer - nlohmann::json does
// we stick with JSON-schema: use the integer-validator if instance-value is unsigned
type_[static_cast<uint8_t>(json::value_t::number_unsigned)] = type_[static_cast<uint8_t>(json::value_t::number_integer)];
// special for binary types
if (type_[static_cast<uint8_t>(json::value_t::string)]) {
type_[static_cast<uint8_t>(json::value_t::binary)] = type_[static_cast<uint8_t>(json::value_t::string)];
}
attr = sch.find("enum");
if (attr != sch.end()) {
enum_ = {true, attr.value()};
sch.erase(attr);
}
attr = sch.find("const");
if (attr != sch.end()) {
const_ = {true, attr.value()};
sch.erase(attr);
}
attr = sch.find("not");
if (attr != sch.end()) {
logic_.push_back(std::make_shared<logical_not>(attr.value(), root, uris));
sch.erase(attr);
}
attr = sch.find("allOf");
if (attr != sch.end()) {
logic_.push_back(std::make_shared<logical_combination<allOf>>(attr.value(), root, uris));
sch.erase(attr);
}
attr = sch.find("anyOf");
if (attr != sch.end()) {
logic_.push_back(std::make_shared<logical_combination<anyOf>>(attr.value(), root, uris));
sch.erase(attr);
}
attr = sch.find("oneOf");
if (attr != sch.end()) {
logic_.push_back(std::make_shared<logical_combination<oneOf>>(attr.value(), root, uris));
sch.erase(attr);
}
attr = sch.find("if");
if (attr != sch.end()) {
auto attr_then = sch.find("then");
auto attr_else = sch.find("else");
if (attr_then != sch.end() || attr_else != sch.end()) {
if_ = schema::make(attr.value(), root, {"if"}, uris);
if (attr_then != sch.end()) {
then_ = schema::make(attr_then.value(), root, {"then"}, uris);
sch.erase(attr_then);
}
if (attr_else != sch.end()) {
else_ = schema::make(attr_else.value(), root, {"else"}, uris);
sch.erase(attr_else);
}
}
sch.erase(attr);
}
}
};
class string : public schema
{
std::pair<bool, size_t> maxLength_{false, 0};
std::pair<bool, size_t> minLength_{false, 0};
#ifndef NO_STD_REGEX
std::pair<bool, REGEX_NAMESPACE::regex> pattern_{false, REGEX_NAMESPACE::regex()};
std::string patternString_;
#endif
std::pair<bool, std::string> format_;
std::tuple<bool, std::string, std::string> content_{false, "", ""};
std::size_t utf8_length(const std::string &s) const
{
size_t len = 0;
for (auto c : s)
if ((c & 0xc0) != 0x80)
len++;
return len;
}
void validate(const json::json_pointer &ptr, const json &instance, json_patch &, error_handler &e) const override
{
if (minLength_.first) {
if (utf8_length(instance.get<std::string>()) < minLength_.second) {
std::ostringstream s;
s << "instance is too short as per minLength:" << minLength_.second;
e.error(ptr, instance, s.str());
}
}
if (maxLength_.first) {
if (utf8_length(instance.get<std::string>()) > maxLength_.second) {
std::ostringstream s;
s << "instance is too long as per maxLength: " << maxLength_.second;
e.error(ptr, instance, s.str());
}
}
if (std::get<0>(content_)) {
if (root_->content_check() == nullptr)
e.error(ptr, instance, std::string("a content checker was not provided but a contentEncoding or contentMediaType for this string have been present: '") + std::get<1>(content_) + "' '" + std::get<2>(content_) + "'");
else {
try {
root_->content_check()(std::get<1>(content_), std::get<2>(content_), instance);
} catch (const std::exception &ex) {
e.error(ptr, instance, std::string("content-checking failed: ") + ex.what());
}
}
} else if (instance.type() == json::value_t::binary) {
e.error(ptr, instance, "expected string, but get binary data");
}
if (instance.type() != json::value_t::string) {
return; // next checks only for strings
}
#ifndef NO_STD_REGEX
if (pattern_.first &&
!REGEX_NAMESPACE::regex_search(instance.get<std::string>(), pattern_.second))
e.error(ptr, instance, "instance does not match regex pattern: " + patternString_);
#endif
if (format_.first) {
if (root_->format_check() == nullptr)
e.error(ptr, instance, std::string("a format checker was not provided but a format keyword for this string is present: ") + format_.second);
else {
try {
root_->format_check()(format_.second, instance.get<std::string>());
} catch (const std::exception &ex) {
e.error(ptr, instance, std::string("format-checking failed: ") + ex.what());
}
}
}
}
public:
string(json &sch, root_schema *root)
: schema(root)
{
auto attr = sch.find("maxLength");
if (attr != sch.end()) {
maxLength_ = {true, attr.value().get<size_t>()};
sch.erase(attr);
}
attr = sch.find("minLength");
if (attr != sch.end()) {
minLength_ = {true, attr.value().get<size_t>()};
sch.erase(attr);
}
attr = sch.find("contentEncoding");
if (attr != sch.end()) {
std::get<0>(content_) = true;
std::get<1>(content_) = attr.value().get<std::string>();
// special case for nlohmann::json-binary-types
//
// https://github.com/pboettch/json-schema-validator/pull/114
//
// We cannot use explicitly in a schema: {"type": "binary"} or
// "type": ["binary", "number"] we have to be implicit. For a
// schema where "contentEncoding" is set to "binary", an instance
// of type json::value_t::binary is accepted. If a
// contentEncoding-callback has to be provided and is called
// accordingly. For encoding=binary, no other type validations are done
sch.erase(attr);
}
attr = sch.find("contentMediaType");
if (attr != sch.end()) {
std::get<0>(content_) = true;
std::get<2>(content_) = attr.value().get<std::string>();
sch.erase(attr);
}
if (std::get<0>(content_) == true && root_->content_check() == nullptr) {
throw std::invalid_argument{"schema contains contentEncoding/contentMediaType but content checker was not set"};
}
#ifndef NO_STD_REGEX
attr = sch.find("pattern");
if (attr != sch.end()) {
patternString_ = attr.value().get<std::string>();
pattern_ = {true, REGEX_NAMESPACE::regex(attr.value().get<std::string>(),
REGEX_NAMESPACE::regex::ECMAScript)};
sch.erase(attr);
}
#endif
attr = sch.find("format");
if (attr != sch.end()) {
if (root_->format_check() == nullptr)
throw std::invalid_argument{"a format checker was not provided but a format keyword for this string is present: " + format_.second};
format_ = {true, attr.value().get<std::string>()};
sch.erase(attr);
}
}
};
template <typename T>
class numeric : public schema
{
std::pair<bool, T> maximum_{false, 0};
std::pair<bool, T> minimum_{false, 0};
bool exclusiveMaximum_ = false;
bool exclusiveMinimum_ = false;
std::pair<bool, json::number_float_t> multipleOf_{false, 0};
// multipleOf - if the remainder of the division is 0 -> OK
bool violates_multiple_of(T x) const
{
double res = std::remainder(x, multipleOf_.second);
double multiple = std::fabs(x / multipleOf_.second);
if (multiple > 1) {
res = res / multiple;
}
double eps = std::nextafter(x, 0) - static_cast<double>(x);
return std::fabs(res) > std::fabs(eps);
}
void validate(const json::json_pointer &ptr, const json &instance, json_patch &, error_handler &e) const override
{
T value = instance; // conversion of json to value_type
if (multipleOf_.first && value != 0) // zero is multiple of everything
if (violates_multiple_of(value))
e.error(ptr, instance, "instance is not a multiple of " + std::to_string(multipleOf_.second));
if (maximum_.first) {
if (exclusiveMaximum_ && value >= maximum_.second)
e.error(ptr, instance, "instance exceeds or equals maximum of " + std::to_string(maximum_.second));
else if (value > maximum_.second)
e.error(ptr, instance, "instance exceeds maximum of " + std::to_string(maximum_.second));
}
if (minimum_.first) {
if (exclusiveMinimum_ && value <= minimum_.second)
e.error(ptr, instance, "instance is below or equals minimum of " + std::to_string(minimum_.second));
else if (value < minimum_.second)
e.error(ptr, instance, "instance is below minimum of " + std::to_string(minimum_.second));
}
}
public:
numeric(const json &sch, root_schema *root, std::set<std::string> &kw)
: schema(root)
{
auto attr = sch.find("maximum");
if (attr != sch.end()) {
maximum_ = {true, attr.value().get<T>()};
kw.insert("maximum");
}
attr = sch.find("minimum");
if (attr != sch.end()) {
minimum_ = {true, attr.value().get<T>()};
kw.insert("minimum");
}
attr = sch.find("exclusiveMaximum");
if (attr != sch.end()) {
exclusiveMaximum_ = true;
maximum_ = {true, attr.value().get<T>()};
kw.insert("exclusiveMaximum");
}
attr = sch.find("exclusiveMinimum");
if (attr != sch.end()) {
exclusiveMinimum_ = true;
minimum_ = {true, attr.value().get<T>()};
kw.insert("exclusiveMinimum");
}
attr = sch.find("multipleOf");
if (attr != sch.end()) {
multipleOf_ = {true, attr.value().get<json::number_float_t>()};
kw.insert("multipleOf");
}
}
};
class null : public schema
{
void validate(const json::json_pointer &ptr, const json &instance, json_patch &, error_handler &e) const override
{
if (!instance.is_null())
e.error(ptr, instance, "expected to be null");
}
public:
null(json &, root_schema *root)
: schema(root) {}
};
class boolean_type : public schema
{
void validate(const json::json_pointer &, const json &, json_patch &, error_handler &) const override {}
public:
boolean_type(json &, root_schema *root)
: schema(root) {}
};
class boolean : public schema
{
bool true_;
void validate(const json::json_pointer &ptr, const json &instance, json_patch &, error_handler &e) const override
{
if (!true_) { // false schema
// empty array
// switch (instance.type()) {
// case json::value_t::array:
// if (instance.size() != 0) // valid false-schema
// e.error(ptr, instance, "false-schema required empty array");
// return;
//}
e.error(ptr, instance, "instance invalid as per false-schema");
}
}
public:
boolean(json &sch, root_schema *root)
: schema(root), true_(sch) {}
};
class required : public schema
{
const std::vector<std::string> required_;
void validate(const json::json_pointer &ptr, const json &instance, json_patch &, error_handler &e) const override final
{
for (auto &r : required_)
if (instance.find(r) == instance.end())
e.error(ptr, instance, "required property '" + r + "' not found in object as a dependency");
}
public:
required(const std::vector<std::string> &r, root_schema *root)
: schema(root), required_(r) {}
};
class object : public schema
{
std::pair<bool, size_t> maxProperties_{false, 0};