Matthew Barth | fd05d64 | 2019-11-14 15:01:57 -0600 | [diff] [blame] | 1 | /** |
| 2 | * Copyright © 2019 IBM Corporation |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | #include <string> |
Matthew Barth | 0961fae | 2019-11-15 09:00:27 -0600 | [diff] [blame^] | 17 | #include <filesystem> |
| 18 | #include <fstream> |
| 19 | #include <nlohmann/json.hpp> |
| 20 | #include <phosphor-logging/log.hpp> |
Matthew Barth | fd05d64 | 2019-11-14 15:01:57 -0600 | [diff] [blame] | 21 | |
| 22 | #include "json_config.hpp" |
| 23 | |
| 24 | namespace phosphor |
| 25 | { |
| 26 | namespace fan |
| 27 | { |
| 28 | namespace presence |
| 29 | { |
| 30 | |
Matthew Barth | 0961fae | 2019-11-15 09:00:27 -0600 | [diff] [blame^] | 31 | using json = nlohmann::json; |
| 32 | namespace fs = std::filesystem; |
| 33 | using namespace phosphor::logging; |
| 34 | |
Matthew Barth | fd05d64 | 2019-11-14 15:01:57 -0600 | [diff] [blame] | 35 | policies JsonConfig::_policies; |
| 36 | |
| 37 | JsonConfig::JsonConfig(const std::string& jsonFile) |
| 38 | { |
Matthew Barth | 0961fae | 2019-11-15 09:00:27 -0600 | [diff] [blame^] | 39 | fs::path confFile{jsonFile}; |
| 40 | std::ifstream file; |
| 41 | json jsonConf; |
Matthew Barth | fd05d64 | 2019-11-14 15:01:57 -0600 | [diff] [blame] | 42 | |
Matthew Barth | 0961fae | 2019-11-15 09:00:27 -0600 | [diff] [blame^] | 43 | if (fs::exists(confFile)) |
| 44 | { |
| 45 | file.open(confFile); |
| 46 | try |
| 47 | { |
| 48 | jsonConf = json::parse(file); |
| 49 | } |
| 50 | catch (std::exception& e) |
| 51 | { |
| 52 | log<level::ERR>("Failed to parse JSON config file", |
| 53 | entry("JSON_FILE=%s", jsonFile.c_str()), |
| 54 | entry("JSON_ERROR=%s", e.what())); |
| 55 | throw std::runtime_error("Failed to parse JSON config file"); |
| 56 | } |
| 57 | } |
| 58 | else |
| 59 | { |
| 60 | log<level::ERR>("Unable to open JSON config file", |
| 61 | entry("JSON_FILE=%s", jsonFile.c_str())); |
| 62 | throw std::runtime_error("Unable to open JSON config file"); |
| 63 | } |
Matthew Barth | fd05d64 | 2019-11-14 15:01:57 -0600 | [diff] [blame] | 64 | } |
| 65 | |
| 66 | const policies& JsonConfig::get() |
| 67 | { |
| 68 | return _policies; |
| 69 | } |
| 70 | |
| 71 | } // namespace presence |
| 72 | } // namespace fan |
| 73 | } // namespace phosphor |