1 /*
2 * Copyright (c) 2024-2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "file_utils.h"
17
18 #include <fstream>
19
20 #include "ans_log_wrapper.h"
21 #ifdef CONFIG_POLICY_ENABLE
22 #include "config_policy_utils.h"
23 #endif
24 #include "securec.h"
25
26 namespace OHOS {
27 namespace Notification {
GetJsonByFilePath(const char * filePath,std::vector<nlohmann::json> & roots)28 bool FileUtils::GetJsonByFilePath(const char *filePath, std::vector<nlohmann::json> &roots)
29 {
30 ANS_LOGD("Get json value by file path.");
31 if (filePath == nullptr) {
32 ANS_LOGE("GetJsonByFilePath fail as filePath is null.");
33 return false;
34 }
35 bool ret = false;
36 nlohmann::json localRoot;
37 #ifdef CONFIG_POLICY_ENABLE
38 CfgFiles *cfgFiles = GetCfgFiles(filePath);
39 if (cfgFiles == nullptr) {
40 ANS_LOGE("Not found filePath:%{public}s.", filePath);
41 return false;
42 }
43
44 for (int32_t i = 0; i <= MAX_CFG_POLICY_DIRS_CNT - 1; i++) {
45 if (cfgFiles->paths[i] && *(cfgFiles->paths[i]) != '\0' && GetJsonFromFile(cfgFiles->paths[i], localRoot)) {
46 ANS_LOGD("Notification config file path:%{public}s.", cfgFiles->paths[i]);
47 roots.push_back(localRoot);
48 ret = true;
49 }
50 }
51 FreeCfgFiles(cfgFiles);
52 #else
53 ANS_LOGD("Use default notification config file path:%{public}s.", filePath);
54 ret = GetJsonFromFile(filePath, localRoot);
55 if (ret) {
56 roots.push_back(localRoot);
57 }
58 #endif
59 return ret;
60 }
61
GetJsonFromFile(const char * path,nlohmann::json & root)62 bool FileUtils::GetJsonFromFile(const char *path, nlohmann::json &root)
63 {
64 std::ifstream file(path);
65 root = nlohmann::json::parse(file);
66 if (root.is_null() || root.empty() || !root.is_object()) {
67 ANS_LOGE("GetJsonFromFile fail as invalid root.");
68 return false;
69 }
70 return true;
71 }
72 } // namespace Notification
73 } // namespace OHOS
74