summaryrefslogtreecommitdiffstats
path: root/build/buildjson.cpp
blob: a5ae502b1608bc37313db6b88b32bc711ac5f40f (plain)
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
#include "build/buildjson.hpp"

#include "errors/exception.hpp"

#include <fstream>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

void validateJson(const json& data)
{
    if (data.count("sensors") != 1)
    {
        throw ConfigurationException(
            "KeyError: 'sensors' not found (or found repeatedly)");
    }

    if (data["sensors"].size() == 0)
    {
        throw ConfigurationException(
            "Invalid Configuration: At least one sensor required");
    }

    if (data.count("zones") != 1)
    {
        throw ConfigurationException(
            "KeyError: 'zones' not found (or found repeatedly)");
    }

    for (const auto& zone : data["zones"])
    {
        if (zone.count("pids") != 1)
        {
            throw ConfigurationException(
                "KeyError: should only have one 'pids' key per zone.");
        }

        if (zone["pids"].size() == 0)
        {
            throw ConfigurationException(
                "Invalid Configuration: must be at least one pid per zone.");
        }
    }
}

json parseValidateJson(const std::string& path)
{
    std::ifstream jsonFile(path);
    if (!jsonFile.is_open())
    {
        throw ConfigurationException("Unable to open json file");
    }

    auto data = json::parse(jsonFile, nullptr, false);
    if (data.is_discarded())
    {
        throw ConfigurationException("Invalid json - parse failed");
    }

    /* Check the data. */
    validateJson(data);

    return data;
}
OpenPOWER on IntegriCloud