a1d7dcee19bf8aa429dad7eedd701a726f5486c0
[archive/platform/core/system/libConfig.git] / src / config / manager.hpp
1 /*
2  *  Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  *  Contact: Piotr Bartosiewicz (p.bartosiewi@partner.samsung.com)
5  *
6  *  Licensed under the Apache License, Version 2.0 (the "License");
7  *  you may not use this file except in compliance with the License.
8  *  You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License
17  */
18
19 /**
20  * @file
21  * @author  Piotr Bartosiewicz (p.bartosiewi@partner.samsung.com)
22  * @brief   Configuration management functions
23  */
24
25 #ifndef CONFIG_MANAGER_HPP
26 #define CONFIG_MANAGER_HPP
27
28 #include "config/to-json-visitor.hpp"
29 #include "config/from-json-visitor.hpp"
30 #include "config/is-visitable.hpp"
31 #include "config/fs-utils.hpp"
32
33
34 namespace config {
35
36 template <class Config>
37 void loadFromString(const std::string& jsonString, Config& config)
38 {
39     static_assert(isVisitable<Config>::value, "Use CONFIG_REGISTER macro");
40
41     FromJsonVisitor visitor(jsonString);
42     config.accept(visitor);
43 }
44
45 template <class Config>
46 std::string saveToString(const Config& config)
47 {
48     static_assert(isVisitable<Config>::value, "Use CONFIG_REGISTER macro");
49
50     ToJsonVisitor visitor;
51     config.accept(visitor);
52     return visitor.toString();
53 }
54
55 template <class Config>
56 void loadFromFile(const std::string& filename, Config& config)
57 {
58     std::string content;
59     if (!fsutils::readFileContent(filename, content)) {
60         throw ConfigException("Could not load " + filename);
61     }
62     try {
63         loadFromString(content, config);
64     } catch (ConfigException& e) {
65         throw ConfigException("Error in " + filename + ": " + e.what());
66     }
67 }
68
69 template <class Config>
70 void saveToFile(const std::string& filename, const Config& config)
71 {
72     const std::string content = saveToString(config);
73     if (!fsutils::saveFileContent(filename, content)) {
74         throw ConfigException("Could not save " + filename);
75     }
76 }
77
78 } // namespace config
79
80 #endif // CONFIG_MANAGER_HPP