blob: 91bb30962611e3f74d31602e4459fff660150b1e [file] [log] [blame]
Matt Spinler852db672019-03-06 13:46:14 -06001#include "association_manager.hpp"
2
Matt Spinler99e66a02019-03-06 14:11:22 -06003#include <filesystem>
4#include <fstream>
5#include <nlohmann/json.hpp>
6#include <phosphor-logging/log.hpp>
7
Matt Spinler852db672019-03-06 13:46:14 -06008namespace phosphor
9{
10namespace inventory
11{
12namespace manager
13{
14namespace associations
15{
Matt Spinler99e66a02019-03-06 14:11:22 -060016using namespace phosphor::logging;
17using sdbusplus::exception::SdBusError;
Matt Spinler852db672019-03-06 13:46:14 -060018
19Manager::Manager(sdbusplus::bus::bus& bus, const std::string& jsonPath) :
20 _bus(bus), _jsonFile(jsonPath)
21{
Matt Spinler99e66a02019-03-06 14:11:22 -060022 load();
23}
24
25/**
26 * @brief Throws an exception if 'num' is zero. Used for JSON
27 * sanity checking.
28 *
29 * @param[in] num - the number to check
30 */
31void throwIfZero(int num)
32{
33 if (!num)
34 {
35 throw std::invalid_argument("Invalid empty field in JSON");
36 }
37}
38
39void Manager::load()
40{
41 // Load the contents of _jsonFile into _associations and throw
42 // an exception on any problem.
43
44 std::ifstream file{_jsonFile};
45
46 auto json = nlohmann::json::parse(file, nullptr, true);
47
48 const std::string root{INVENTORY_ROOT};
49
50 for (const auto& jsonAssoc : json)
51 {
52 // Only add the slash if necessary
53 std::string path = jsonAssoc.at("path");
54 throwIfZero(path.size());
55 if (path.front() != '/')
56 {
57 path = root + "/" + path;
58 }
59 else
60 {
61 path = root + path;
62 }
63
64 auto& assocEndpoints = _associations[path];
65
66 for (const auto& endpoint : jsonAssoc.at("endpoints"))
67 {
68 std::string ftype = endpoint.at("types").at("fType");
69 std::string rtype = endpoint.at("types").at("rType");
70 throwIfZero(ftype.size());
71 throwIfZero(rtype.size());
72 Types types{std::move(ftype), std::move(rtype)};
73
74 Paths paths = endpoint.at("paths");
75 throwIfZero(paths.size());
76 assocEndpoints.emplace_back(std::move(types), std::move(paths));
77 }
78 }
Matt Spinler852db672019-03-06 13:46:14 -060079}
80
81void Manager::createAssociations(const std::string& objectPath)
82{
83 // TODO
84}
85} // namespace associations
86} // namespace manager
87} // namespace inventory
88} // namespace phosphor