28std::shared_ptr<const valijson::Schema> loadSchema(
const QString& schemaResourcePath, QString& errorString)
31 static QHash<QString, std::shared_ptr<const valijson::Schema>> schemaCache;
33 if (
const auto cached = schemaCache.value(schemaResourcePath)) {
37 QFile schemaFile(schemaResourcePath);
38 if (!schemaFile.open(QIODevice::ReadOnly)) {
39 errorString = QStringLiteral(
"Failed to open schema resource: %1").arg(schemaResourcePath);
43 QJsonParseError parseError;
44 const QJsonDocument schemaDoc = QJsonDocument::fromJson(schemaFile.readAll(), &parseError);
45 if (parseError.error != QJsonParseError::NoError) {
46 errorString = QStringLiteral(
"Failed to parse schema %1: %2").arg(schemaResourcePath, parseError.errorString());
52 QJsonObject schemaObj = schemaDoc.object();
53 QJsonObject schemaProps = schemaObj.value(QStringLiteral(
"properties")).toObject();
54 if (schemaProps.contains(QStringLiteral(
"version"))) {
55 QJsonObject versionSchema = schemaProps.value(QStringLiteral(
"version")).toObject();
56 versionSchema.remove(QStringLiteral(
"minimum"));
57 versionSchema.remove(QStringLiteral(
"maximum"));
58 schemaProps[QStringLiteral(
"version")] = versionSchema;
59 schemaObj[QStringLiteral(
"properties")] = schemaProps;
62 auto schema = std::make_shared<valijson::Schema>();
64 valijson::SchemaParser parser;
65 const valijson::adapters::QtJsonAdapter schemaAdapter(schemaObj);
66 parser.populateSchema(schemaAdapter, *schema);
67 }
catch (
const std::exception& e) {
69 QStringLiteral(
"Failed to load schema %1: %2").arg(schemaResourcePath, QString::fromUtf8(e.what()));
73 schemaCache.insert(schemaResourcePath, schema);
79bool validate(
const QJsonDocument& doc,
const QString& schemaResourcePath, QString& errorString)
83 const QJsonValue root = doc.isArray() ? QJsonValue(doc.array()) : QJsonValue(doc.object());
87 static QSet<QByteArray> validatedDocuments;
88 QCryptographicHash digest(QCryptographicHash::Sha256);
89 digest.addData(schemaResourcePath.toUtf8());
90 digest.addData(QByteArrayView(
"\0", 1));
91 digest.addData(QCborValue::fromJsonValue(root).toCbor());
92 const QByteArray documentKey = digest.result();
93 if (validatedDocuments.contains(documentKey)) {
97 const auto schema = loadSchema(schemaResourcePath, errorString);
102 valijson::Validator validator;
103 valijson::ValidationResults results;
104 const valijson::adapters::QtJsonAdapter docAdapter(root);
106 if (validator.validate(*schema, docAdapter, &results)) {
107 validatedDocuments.insert(documentKey);
111 QStringList failures;
112 valijson::ValidationResults::Error error;
113 while (results.popError(error)) {
114 failures.append(QStringLiteral(
"%1: %2").arg(QString::fromStdString(error.jsonPointer),
115 QString::fromStdString(error.description)));
117 errorString = failures.join(QStringLiteral(
"; "));