1 #include "association_manager.hpp" 2 3 #include <filesystem> 4 #include <fstream> 5 #include <nlohmann/json.hpp> 6 #include <phosphor-logging/log.hpp> 7 8 namespace phosphor 9 { 10 namespace inventory 11 { 12 namespace manager 13 { 14 namespace associations 15 { 16 using namespace phosphor::logging; 17 using sdbusplus::exception::SdBusError; 18 19 Manager::Manager(sdbusplus::bus::bus& bus, const std::string& jsonPath) : 20 _bus(bus), _jsonFile(jsonPath) 21 { 22 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 */ 31 void throwIfZero(int num) 32 { 33 if (!num) 34 { 35 throw std::invalid_argument("Invalid empty field in JSON"); 36 } 37 } 38 39 void 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 } 79 } 80 81 void Manager::createAssociations(const std::string& objectPath) 82 { 83 // TODO 84 } 85 } // namespace associations 86 } // namespace manager 87 } // namespace inventory 88 } // namespace phosphor 89