JsonHelper.cc 10 KB
Newer Older
1 2 3 4 5 6 7 8
/****************************************************************************
 *
 *   (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
 *
 * QGroundControl is licensed according to the terms in the file
 * COPYING.md in the root of the source code directory.
 *
 ****************************************************************************/
Don Gagne's avatar
Don Gagne committed
9 10 11 12 13


#include "JsonHelper.h"

#include <QJsonArray>
14
#include <QJsonParseError>
15 16 17
#include <QObject>
#include <QRegularExpression>
#include <QRegularExpressionMatch>
Don Gagne's avatar
Don Gagne committed
18

19 20 21 22 23 24
const char* JsonHelper::_enumStringsJsonKey =       "enumStrings";
const char* JsonHelper::_enumValuesJsonKey =        "enumValues";
const char* JsonHelper::jsonVersionKey =            "version";
const char* JsonHelper::jsonGroundStationKey =      "groundStation";
const char* JsonHelper::jsonGroundStationValue =    "QGroundControl";
const char* JsonHelper::jsonFileTypeKey =           "fileType";
Don Gagne's avatar
Don Gagne committed
25

Don Gagne's avatar
Don Gagne committed
26 27 28 29 30 31 32 33 34 35 36 37 38 39
bool JsonHelper::validateRequiredKeys(const QJsonObject& jsonObject, const QStringList& keys, QString& errorString)
{
    QString missingKeys;

    foreach(const QString& key, keys) {
        if (!jsonObject.contains(key)) {
            if (!missingKeys.isEmpty()) {
                missingKeys += QStringLiteral(", ");
            }
            missingKeys += key;
        }
    }

    if (missingKeys.count() != 0) {
40
        errorString = QObject::tr("The following required keys are missing: %1").arg(missingKeys);
Don Gagne's avatar
Don Gagne committed
41 42 43 44 45 46
        return false;
    }

    return true;
}

47 48 49 50
bool JsonHelper::loadGeoCoordinate(const QJsonValue&    jsonValue,
                                   bool                 altitudeRequired,
                                   QGeoCoordinate&      coordinate,
                                   QString&             errorString)
Don Gagne's avatar
Don Gagne committed
51 52
{
    if (!jsonValue.isArray()) {
53
        errorString = QObject::tr("value for coordinate is not array");
Don Gagne's avatar
Don Gagne committed
54 55 56 57 58 59
        return false;
    }

    QJsonArray coordinateArray = jsonValue.toArray();
    int requiredCount = altitudeRequired ? 3 : 2;
    if (coordinateArray.count() != requiredCount) {
60
        errorString = QObject::tr("Coordinate array must contain %1 values").arg(requiredCount);
Don Gagne's avatar
Don Gagne committed
61 62 63
        return false;
    }

Don Gagne's avatar
Don Gagne committed
64 65
    foreach(const QJsonValue& jsonValue, coordinateArray) {
        if (jsonValue.type() != QJsonValue::Double) {
66
            errorString = QObject::tr("Coordinate array may only contain double values, found: %1").arg(jsonValue.type());
Don Gagne's avatar
Don Gagne committed
67 68 69 70
            return false;
        }
    }

Don Gagne's avatar
Don Gagne committed
71 72 73 74 75 76
    coordinate = QGeoCoordinate(coordinateArray[0].toDouble(), coordinateArray[1].toDouble());
    if (altitudeRequired) {
        coordinate.setAltitude(coordinateArray[2].toDouble());
    }

    if (!coordinate.isValid()) {
77
        errorString = QObject::tr("Coordinate is invalid: %1").arg(coordinate.toString());
Don Gagne's avatar
Don Gagne committed
78 79 80 81 82
        return false;
    }

    return true;
}
Don Gagne's avatar
Don Gagne committed
83

84 85 86
void JsonHelper::saveGeoCoordinate(const QGeoCoordinate&    coordinate,
                                   bool                     writeAltitude,
                                   QJsonValue&              jsonValue)
87 88 89 90 91 92 93 94 95 96 97 98
{
    QJsonArray coordinateArray;

    coordinateArray << coordinate.latitude() << coordinate.longitude();
    if (writeAltitude) {
        coordinateArray << coordinate.altitude();
    }

    jsonValue = QJsonValue(coordinateArray);
}

bool JsonHelper::validateKeyTypes(const QJsonObject& jsonObject, const QStringList& keys, const QList<QJsonValue::Type>& types, QString& errorString)
Don Gagne's avatar
Don Gagne committed
99 100 101 102
{
    for (int i=0; i<keys.count(); i++) {
        if (jsonObject.contains(keys[i])) {
            if (jsonObject.value(keys[i]).type() != types[i]) {
103
                errorString  = QObject::tr("Incorrect type key:type:expected %1 %2 %3").arg(keys[i]).arg(jsonObject.value(keys[i]).type()).arg(types[i]);
Don Gagne's avatar
Don Gagne committed
104 105 106 107 108 109 110 111
                return false;
            }
        }
    }

    return true;
}

112
bool JsonHelper::parseEnum(const QJsonObject& jsonObject, QStringList& enumStrings, QStringList& enumValues, QString& errorString)
Don Gagne's avatar
Don Gagne committed
113 114 115 116 117
{
    enumStrings = jsonObject.value(_enumStringsJsonKey).toString().split(",", QString::SkipEmptyParts);
    enumValues = jsonObject.value(_enumValuesJsonKey).toString().split(",", QString::SkipEmptyParts);

    if (enumStrings.count() != enumValues.count()) {
118
        errorString = QObject::tr("enum strings/values count mismatch strings:values %1:%2").arg(enumStrings.count()).arg(enumValues.count());
Don Gagne's avatar
Don Gagne committed
119 120 121 122 123
        return false;
    }

    return true;
}
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140

bool JsonHelper::isJsonFile(const QByteArray& bytes, QJsonDocument& jsonDoc)
{
    QJsonParseError error;

    jsonDoc = QJsonDocument::fromJson(bytes, &error);

    if (error.error == QJsonParseError::NoError) {
        return true;
    }

    if (error.error == QJsonParseError::MissingObject && error.offset == 0) {
        return false;
    }

    return true;
}
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

bool JsonHelper::validateQGCJsonFile(const QJsonObject& jsonObject,
                                     const QString&     expectedFileType,
                                     int                supportedMajorVersion,
                                     int                supportedMinorVersion,
                                     int&               fileMajorVersion,
                                     int&               fileMinorVersion,
                                     QString&           errorString)
{
    // Check for required keys
    QStringList requiredKeys = { jsonVersionKey, jsonFileTypeKey };
    if (!validateRequiredKeys(jsonObject, requiredKeys, errorString)) {
        return false;
    }

    // Validate base key types
    QList<QJsonValue::Type> typeList = { QJsonValue::String, QJsonValue::String };
    if (!validateKeyTypes(jsonObject, requiredKeys, typeList, errorString)) {
        return false;
    }

    // Make sure file type is correct
    QString fileTypeValue = jsonObject[jsonFileTypeKey].toString();
    if (fileTypeValue != expectedFileType) {
        errorString = QObject::tr("Incorrect file type key expected:%1 actual:%2").arg(expectedFileType).arg(fileTypeValue);
        return false;
    }

    // Parse and validate version

    QString incorrectVersionFormatErrorString = QObject::tr("Incorrectly formatted version value");
    QRegularExpression versionRegExp("(\\d+).(\\d+)");
    QRegularExpressionMatch match = versionRegExp.match(jsonObject[jsonVersionKey].toString());
    if (!match.hasMatch()) {
        errorString = incorrectVersionFormatErrorString;
        return false;
    }
    QStringList versionParts = match.capturedTexts();
    if (versionParts.count() != 3) {
        errorString = incorrectVersionFormatErrorString;
        return false;
    }

    fileMajorVersion = versionParts[0].toInt();
    fileMinorVersion = versionParts[0].toInt();
    if (fileMajorVersion > supportedMajorVersion || (fileMajorVersion == supportedMajorVersion && fileMinorVersion > supportedMinorVersion)) {
        errorString = QObject::tr("File version (%1.%2) is larger than current supported version (%3.%4)").arg(fileMajorVersion).arg(fileMinorVersion).arg(supportedMajorVersion).arg(supportedMinorVersion);
        return false;
    }

    return true;
}

bool JsonHelper::loadGeoCoordinateArray(const QJsonValue&   jsonValue,
                                        bool                altitudeRequired,
                                        QVariantList&       rgVarPoints,
                                        QString&            errorString)
{
    if (!jsonValue.isArray()) {
        errorString = QObject::tr("value for coordinate array is not array");
        return false;
    }
    QJsonArray rgJsonPoints = jsonValue.toArray();

    rgVarPoints.clear();
    for (int i=0; i<rgJsonPoints.count(); i++) {
        QGeoCoordinate coordinate;

        if (!JsonHelper::loadGeoCoordinate(rgJsonPoints[i], altitudeRequired, coordinate, errorString)) {
            return false;
        }
        rgVarPoints.append(QVariant::fromValue(coordinate));
    }

    return true;
}

bool JsonHelper::loadGeoCoordinateArray(const QJsonValue&       jsonValue,
                                        bool                    altitudeRequired,
                                        QList<QGeoCoordinate>&  rgPoints,
                                        QString&                errorString)
{
    QVariantList rgVarPoints;

    if (!loadGeoCoordinateArray(jsonValue, altitudeRequired, rgVarPoints, errorString)) {
        return false;
    }

    rgPoints.clear();
    for (int i=0; i<rgVarPoints.count(); i++) {
        rgPoints.append(rgVarPoints[i].value<QGeoCoordinate>());
    }

    return true;
}

void JsonHelper::saveGeoCoordinateArray(const QVariantList& rgVarPoints,
                                        bool                writeAltitude,
                                        QJsonValue&         jsonValue)
{
    QJsonArray rgJsonPoints;

    // Add all points to the array
    for (int i=0; i<rgVarPoints.count(); i++) {
        QJsonValue jsonPoint;

        JsonHelper::saveGeoCoordinate(rgVarPoints[i].value<QGeoCoordinate>(), writeAltitude, jsonPoint);
        rgJsonPoints.append(jsonPoint);
    }

    jsonValue = rgJsonPoints;
}

void JsonHelper::saveGeoCoordinateArray(const QList<QGeoCoordinate>&    rgPoints,
                                        bool                            writeAltitude,
                                        QJsonValue&                     jsonValue)
{
    QVariantList rgVarPoints;

    for (int i=0; i<rgPoints.count(); i++) {
        rgVarPoints.append(QVariant::fromValue(rgPoints[i]));
    }
    return saveGeoCoordinateArray(rgVarPoints, writeAltitude, jsonValue);
}
Don Gagne's avatar
Don Gagne committed
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286

bool JsonHelper::validateKeys(const QJsonObject& jsonObject, const QList<JsonHelper::KeyValidateInfo>& keyInfo, QString& errorString)
{
    QStringList             keyList;
    QList<QJsonValue::Type> typeList;

    for (int i=0; i<keyInfo.count(); i++) {
        if (keyInfo[i].required) {
            keyList.append(keyInfo[i].key);
        }
    }
    if (!validateRequiredKeys(jsonObject, keyList, errorString)) {
        return false;
    }

    keyList.clear();
    for (int i=0; i<keyInfo.count(); i++) {
        keyList.append(keyInfo[i].key);
        typeList.append(keyInfo[i].type);
    }
    return validateKeyTypes(jsonObject, keyList, typeList, errorString);
}