File: custom_schema.cpp

package info (click to toggle)
valijson 1.0.3%2Brepack-2
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 2,756 kB
  • sloc: cpp: 19,769; sh: 134; makefile: 24
file content (222 lines) | stat: -rw-r--r-- 7,298 bytes parent folder | download | duplicates (3)
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
/**
 * @file
 *
 * @brief Demonstrates validation against a manually constructed schema.
 *
 * This example demonstrates the construction and composition of a Schema object
 * using manually created Constraint objects. The following Constraint classes
 * are used:
 *  - EnumConstraint
 *  - MaxLengthConstraint
 *  - MinimumConstraint
 *  - MinLengthConstraint
 *  - PropertiesConstraint
 *  - RequiredConstraint
 *  - TypeConstraint
 *
 * The MinimumConstraint class provides support for the exclusiveMinimum and
 * minimum keywords in JSON Schema. And the PropertiesConstraint class provides
 * support for the properties, patternProperties, and additionalProperties
 * keywords.
 *
 * This is the JSON Schema representation of the Schema that will be created:
 *
 *  {
 *    "properties": {
 *      "category": {
 *        "enum": [
 *          "album",
 *          "book",
 *          "other",
 *          "video"
 *        ]
 *      },
 *      "description": {
 *        "type": "string"
 *      },
 *      "price": {
 *        "exclusiveMinimum": true,
 *        "minimum": 0.0,
 *        "type": "number"
 *      },
 *      "title": {
 *        "maxLength": 200,
 *        "minLength": 1,
 *        "type": "string"
 *      }
 *    },
 *    "required": [
 *      "category",
 *      "price",
 *      "title"
 *    ],
 *    "type": "object"
 *  }
 *
 */

#include <fstream>
#include <iostream>
#include <stdexcept>

#include <valijson/adapters/rapidjson_adapter.hpp>
#include <valijson/constraints/concrete_constraints.hpp>
#include <valijson/utils/rapidjson_utils.hpp>
#include <valijson/schema.hpp>
#include <valijson/validation_results.hpp>
#include <valijson/validator.hpp>

using std::cerr;
using std::endl;

using valijson::Schema;
using valijson::Subschema;
using valijson::Validator;
using valijson::ValidationResults;
using valijson::adapters::RapidJsonAdapter;
using valijson::adapters::RapidJsonFrozenValue;
using valijson::constraints::EnumConstraint;
using valijson::constraints::MaxLengthConstraint;
using valijson::constraints::MinimumConstraint;
using valijson::constraints::MinLengthConstraint;
using valijson::constraints::PropertiesConstraint;
using valijson::constraints::RequiredConstraint;
using valijson::constraints::TypeConstraint;

void addPropertiesConstraint(Schema &schema)
{

    PropertiesConstraint propertiesConstraint;

    {
        // Prepare an enum constraint requires a document to be equal to at
        // least one of a set of possible values
        EnumConstraint constraint;
        constraint.addValue(RapidJsonFrozenValue("album"));
        constraint.addValue(RapidJsonFrozenValue("book"));
        constraint.addValue(RapidJsonFrozenValue("other"));
        constraint.addValue(RapidJsonFrozenValue("video"));

        // Create a subschema, owned by the root schema, with a constraint
        const Subschema *subschema = schema.createSubschema();
        schema.addConstraintToSubschema(constraint, subschema);

        // Include subschema in properties constraint
        propertiesConstraint.addPropertySubschema("category", subschema);
    }

    {
        // Create a child schema for the 'description' property that requires
        // a string, but does not enforce any length constraints.
        const Subschema *subschema = schema.createSubschema();
        TypeConstraint typeConstraint;
        typeConstraint.addNamedType(TypeConstraint::kString);
        schema.addConstraintToSubschema(typeConstraint, subschema);

        // Include subschema in properties constraint
        propertiesConstraint.addPropertySubschema("description", subschema);
    }

    {
        // Create a child schema for the 'price' property, that requires a
        // number with a value greater than zero.
        const Subschema *subschema = schema.createSubschema();
        MinimumConstraint minimumConstraint;
        minimumConstraint.setMinimum(0.0);
        minimumConstraint.setExclusiveMinimum(true);
        schema.addConstraintToSubschema(minimumConstraint, subschema);
        TypeConstraint typeConstraint;
        typeConstraint.addNamedType(TypeConstraint::kNumber);
        schema.addConstraintToSubschema(typeConstraint, subschema);

        // Include subschema in properties constraint
        propertiesConstraint.addPropertySubschema("price", subschema);
    }

    {
        // Create a child schema for the 'title' property that requires a string
        // that is between 1 and 200 characters in length.
        const Subschema *subschema = schema.createSubschema();
        MaxLengthConstraint maxLengthConstraint;
        maxLengthConstraint.setMaxLength(200);
        schema.addConstraintToSubschema(maxLengthConstraint, subschema);
        MinLengthConstraint minLengthConstraint;
        minLengthConstraint.setMinLength(0);
        schema.addConstraintToSubschema(minLengthConstraint, subschema);
        TypeConstraint typeConstraint;
        typeConstraint.addNamedType(TypeConstraint::kString);
        schema.addConstraintToSubschema(typeConstraint, subschema);

        // Include subschema in properties constraint
        propertiesConstraint.addPropertySubschema("title", subschema);
    }

    // Add a PropertiesConstraint to the root schema
    schema.addConstraint(propertiesConstraint);
}

void addRequiredConstraint(Schema &schema)
{
    // Add a RequiredConstraint to the schema, specifying that the category,
    // price, and title properties must be present.
    RequiredConstraint constraint;
    constraint.addRequiredProperty("category");
    constraint.addRequiredProperty("price");
    constraint.addRequiredProperty("title");
    schema.addConstraint(constraint);
}

void addTypeConstraint(Schema &schema)
{
    // Add a TypeConstraint to the schema, specifying that the root of the
    // document must be an object.
    TypeConstraint typeConstraint;
    typeConstraint.addNamedType(TypeConstraint::kObject);
    schema.addConstraint(typeConstraint);
}

int main(int argc, char *argv[])
{
    if (argc != 2) {
        cerr << "Usage:" << endl;
        cerr << "  ./custom_schema <document>" << endl;
        cerr << endl;
        return 1;
    }

    // Load the document that is to be validated
    rapidjson::Document targetDocument;
    if (!valijson::utils::loadDocument(argv[1], targetDocument)) {
        cerr << "Failed to load target document." << endl;
        return 1;
    }

    // Populate a schema
    Schema schema;
    addPropertiesConstraint(schema);
    addRequiredConstraint(schema);
    addTypeConstraint(schema);

    // Perform validation
    Validator validator;
    ValidationResults results;
    RapidJsonAdapter targetDocumentAdapter(targetDocument);
    if (!validator.validate(schema, targetDocumentAdapter, &results)) {
        std::cerr << "Validation failed." << endl;
        ValidationResults::Error error;
        unsigned int errorNum = 1;
        while (results.popError(error)) {
            cerr << "Error #" << errorNum << std::endl;
            cerr << "  ";
            for (const std::string &contextElement : error.context) {
                cerr << contextElement << " ";
            }
            cerr << endl;
            cerr << "    - " << error.description << endl;
            ++errorNum;
        }
        return 1;
    }

    return 0;
}