forked from AMSC-24-25/20-fft-20-fft
-
Notifications
You must be signed in to change notification settings - Fork 0
/
json-configuration-loader.cpp
47 lines (43 loc) · 1.74 KB
/
json-configuration-loader.cpp
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
/**
* JSONConfigurationLoader class implementation.
*/
#include <fstream>
#include <config-loader/json-configuration-loader.hpp>
#include <config-loader/json-field-handler.hpp>
using json = nlohmann::json;
const JsonFieldHandler &JSONConfigurationLoader::getConfigurationData() const {
if (configurationData.has_value()) {
return configurationData.value();
}
throw std::runtime_error("No JSON configuration data loaded.");
}
void JSONConfigurationLoader::loadConfigurationFromFile(const std::string &filePath) {
// assert that the file have a .json extension
if (!filePath.ends_with(".json")) {
throw std::runtime_error("File is not a JSON file: " + filePath);
}
// get the file stream
std::ifstream fileStream(filePath);
// check if the file stream is open
if (!fileStream.is_open()) {
throw std::runtime_error("Failed to open file: " + filePath);
}
// check if the file is empty
if (fileStream.peek() == std::ifstream::traits_type::eof()) {
throw std::runtime_error("File is empty: " + filePath);
}
// if all checks pass, load the configuration data
nlohmann::json jsonConfigurationData;
try {
fileStream >> jsonConfigurationData;
} catch (const nlohmann::json::parse_error &e) {
throw std::runtime_error("Failed to parse JSON file: " + filePath + "; Parse error: " + e.what());
}
// create the field handler object
configurationData = JsonFieldHandler(jsonConfigurationData);
// close the file stream
fileStream.close();
// print the actual configuration data;
printf("The configuration data has been loaded from the file: %s.\n%s\n\n",
filePath.c_str(), configurationData->getConfigurationLoaded().dump(4).c_str());
}