Debian Codegraph @

LspCpp/third_party/rapidjson/example/schemavalidator/schemavalidator.cpp

raw
1 // Schema Validator example
2
3 // The example validates JSON text from stdin with a JSON schema specified in the argument.
4
5 #define RAPIDJSON_HAS_STDSTRING 1
6
7 #include "rapidjson/error/en.h"
8 #include "rapidjson/filereadstream.h"
9 #include "rapidjson/schema.h"
10 #include "rapidjson/stringbuffer.h"
11 #include "rapidjson/prettywriter.h"
12 #include <string>
13 #include <iostream>
14 #include <sstream>
15
16 using namespace rapidjson;
17
18 typedef GenericValue<UTF8<>, CrtAllocator > ValueType;
19
20 // Forward ref
21 static void CreateErrorMessages(const ValueType& errors, size_t depth, const char* context);
22
23 // Convert GenericValue to std::string
24 static std::string GetString(const ValueType& val) {
25 std::ostringstream s;
26 if (val.IsString())
27 s << val.GetString();
28 else if (val.IsDouble())
29 s << val.GetDouble();
30 else if (val.IsUint())
31 s << val.GetUint();
32 else if (val.IsInt())
33 s << val.GetInt();
34 else if (val.IsUint64())
35 s << val.GetUint64();
36 else if (val.IsInt64())
37 s << val.GetInt64();
38 else if (val.IsBool() && val.GetBool())
39 s << "true";
40 else if (val.IsBool())
41 s << "false";
42 else if (val.IsFloat())
43 s << val.GetFloat();
44 return s.str();
45 }
46
47 // Create the error message for a named error
48 // The error object can either be empty or contain at least member properties:
49 // {"errorCode": <code>, "instanceRef": "<pointer>", "schemaRef": "<pointer>" }
50 // Additional properties may be present for use as inserts.
51 // An "errors" property may be present if there are child errors.
52 static void HandleError(const char* errorName, const ValueType& error, size_t depth, const char* context) {
53 if (!error.ObjectEmpty()) {
54 // Get error code and look up error message text (English)
55 int code = error["errorCode"].GetInt();
56 std::string message(GetValidateError_En(static_cast<ValidateErrorCode>(code)));
57 // For each member property in the error, see if its name exists as an insert in the error message and if so replace with the stringified property value
58 // So for example - "Number '%actual' is not a multiple of the 'multipleOf' value '%expected'." - we would expect "actual" and "expected" members.
59 for (ValueType::ConstMemberIterator insertsItr = error.MemberBegin();
60 insertsItr != error.MemberEnd(); ++insertsItr) {
61 std::string insertName("%");
62 insertName += insertsItr->name.GetString(); // eg "%actual"
63 size_t insertPos = message.find(insertName);
64 if (insertPos != std::string::npos) {
65 std::string insertString("");
66 const ValueType &insert = insertsItr->value;
67 if (insert.IsArray()) {
68 // Member is an array so create comma-separated list of items for the insert string
69 for (ValueType::ConstValueIterator itemsItr = insert.Begin(); itemsItr != insert.End(); ++itemsItr) {
70 if (itemsItr != insert.Begin()) insertString += ",";
71 insertString += GetString(*itemsItr);
72 }
73 } else {
74 insertString += GetString(insert);
75 }
76 message.replace(insertPos, insertName.length(), insertString);
77 }
78 }
79 // Output error message, references, context
80 std::string indent(depth * 2, ' ');
81 std::cout << indent << "Error Name: " << errorName << std::endl;
82 std::cout << indent << "Message: " << message.c_str() << std::endl;
83 std::cout << indent << "Instance: " << error["instanceRef"].GetString() << std::endl;
84 std::cout << indent << "Schema: " << error["schemaRef"].GetString() << std::endl;
85 if (depth > 0) std::cout << indent << "Context: " << context << std::endl;
86 std::cout << std::endl;
87
88 // If child errors exist, apply the process recursively to each error structure.
89 // This occurs for "oneOf", "allOf", "anyOf" and "dependencies" errors, so pass the error name as context.
90 if (error.HasMember("errors")) {
91 depth++;
92 const ValueType &childErrors = error["errors"];
93 if (childErrors.IsArray()) {
94 // Array - each item is an error structure - example
95 // "anyOf": {"errorCode": ..., "errors":[{"pattern": {"errorCode\": ...\"}}, {"pattern": {"errorCode\": ...}}]
96 for (ValueType::ConstValueIterator errorsItr = childErrors.Begin();
97 errorsItr != childErrors.End(); ++errorsItr) {
98 CreateErrorMessages(*errorsItr, depth, errorName);
99 }
100 } else if (childErrors.IsObject()) {
101 // Object - each member is an error structure - example
102 // "dependencies": {"errorCode": ..., "errors": {"address": {"required": {"errorCode": ...}}, "name": {"required": {"errorCode": ...}}}
103 for (ValueType::ConstMemberIterator propsItr = childErrors.MemberBegin();
104 propsItr != childErrors.MemberEnd(); ++propsItr) {
105 CreateErrorMessages(propsItr->value, depth, errorName);
106 }
107 }
108 }
109 }
110 }
111
112 // Create error message for all errors in an error structure
113 // Context is used to indicate whether the error structure has a parent 'dependencies', 'allOf', 'anyOf' or 'oneOf' error
114 static void CreateErrorMessages(const ValueType& errors, size_t depth = 0, const char* context = 0) {
115 // Each member property contains one or more errors of a given type
116 for (ValueType::ConstMemberIterator errorTypeItr = errors.MemberBegin(); errorTypeItr != errors.MemberEnd(); ++errorTypeItr) {
117 const char* errorName = errorTypeItr->name.GetString();
118 const ValueType& errorContent = errorTypeItr->value;
119 if (errorContent.IsArray()) {
120 // Member is an array where each item is an error - eg "type": [{"errorCode": ...}, {"errorCode": ...}]
121 for (ValueType::ConstValueIterator contentItr = errorContent.Begin(); contentItr != errorContent.End(); ++contentItr) {
122 HandleError(errorName, *contentItr, depth, context);
123 }
124 } else if (errorContent.IsObject()) {
125 // Member is an object which is a single error - eg "type": {"errorCode": ... }
126 HandleError(errorName, errorContent, depth, context);
127 }
128 }
129 }
130
131 int main(int argc, char *argv[]) {
132 if (argc != 2) {
133 fprintf(stderr, "Usage: schemavalidator schema.json < input.json\n");
134 return EXIT_FAILURE;
135 }
136
137 // Read a JSON schema from file into Document
138 Document d;
139 char buffer[4096];
140
141 {
142 FILE *fp = fopen(argv[1], "r");
143 if (!fp) {
144 printf("Schema file '%s' not found\n", argv[1]);
145 return -1;
146 }
147 FileReadStream fs(fp, buffer, sizeof(buffer));
148 d.ParseStream(fs);
149 if (d.HasParseError()) {
150 fprintf(stderr, "Schema file '%s' is not a valid JSON\n", argv[1]);
151 fprintf(stderr, "Error(offset %u): %s\n",
152 static_cast<unsigned>(d.GetErrorOffset()),
153 GetParseError_En(d.GetParseError()));
154 fclose(fp);
155 return EXIT_FAILURE;
156 }
157 fclose(fp);
158 }
159
160 // Then convert the Document into SchemaDocument
161 SchemaDocument sd(d);
162
163 // Use reader to parse the JSON in stdin, and forward SAX events to validator
164 SchemaValidator validator(sd);
165 Reader reader;
166 FileReadStream is(stdin, buffer, sizeof(buffer));
167 if (!reader.Parse(is, validator) && reader.GetParseErrorCode() != kParseErrorTermination) {
168 // Schema validator error would cause kParseErrorTermination, which will handle it in next step.
169 fprintf(stderr, "Input is not a valid JSON\n");
170 fprintf(stderr, "Error(offset %u): %s\n",
171 static_cast<unsigned>(reader.GetErrorOffset()),
172 GetParseError_En(reader.GetParseErrorCode()));
173 }
174
175 // Check the validation result
176 if (validator.IsValid()) {
177 printf("Input JSON is valid.\n");
178 return EXIT_SUCCESS;
179 }
180 else {
181 printf("Input JSON is invalid.\n");
182 StringBuffer sb;
183 validator.GetInvalidSchemaPointer().StringifyUriFragment(sb);
184 fprintf(stderr, "Invalid schema: %s\n", sb.GetString());
185 fprintf(stderr, "Invalid keyword: %s\n", validator.GetInvalidSchemaKeyword());
186 fprintf(stderr, "Invalid code: %d\n", validator.GetInvalidSchemaCode());
187 fprintf(stderr, "Invalid message: %s\n", GetValidateError_En(validator.GetInvalidSchemaCode()));
188 sb.Clear();
189 validator.GetInvalidDocumentPointer().StringifyUriFragment(sb);
190 fprintf(stderr, "Invalid document: %s\n", sb.GetString());
191 // Detailed violation report is available as a JSON value
192 sb.Clear();
193 PrettyWriter<StringBuffer> w(sb);
194 validator.GetError().Accept(w);
195 fprintf(stderr, "Error report:\n%s\n", sb.GetString());
196 CreateErrorMessages(validator.GetError());
197 return EXIT_FAILURE;
198 }
199 }