1 /*
2  * Copyright (c) 2021-2022 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 "uri_utils.h"
17 #include "common.h"
18 #include "hilog_wrapper.h"
19 
20 namespace OHOS {
21 namespace Contacts {
UriUtils(void)22 UriUtils::UriUtils(void)
23 {
24 }
25 
~UriUtils()26 UriUtils::~UriUtils()
27 {
28 }
29 
getQueryParameter(OHOS::Uri &uri)30 std::map<std::string, std::string> UriUtils::getQueryParameter(OHOS::Uri &uri)
31 {
32     std::map<std::string, std::string> mapQuery;
33     std::string query = uri.GetQuery();
34     if (query.empty()) {
35         return mapQuery;
36     }
37     std::vector<std::string> tempVector = split(query, "&");
38     unsigned int size = tempVector.size();
39     for (unsigned int i = 0; i < size; i++) {
40         std::vector<std::string> childTempVector = split(tempVector[i], "=");
41         size_t childSize = childTempVector.size();
42         if (childSize != REQUEST_PARAMS_NUM) {
43             HILOG_ERROR("UriUtils uriParse getQueryParameter query parameter error");
44             break;
45         }
46         std::string key = childTempVector[0];
47         std::string value = childTempVector[1];
48         mapQuery.insert(std::make_pair(key, value));
49     }
50     return mapQuery;
51 }
52 
split(const std::string &str, const std::string &split)53 std::vector<std::string> UriUtils::split(const std::string &str, const std::string &split)
54 {
55     char *saveChar = nullptr;
56     char *token = strtok_r(const_cast<char *>(str.c_str()), split.c_str(), &saveChar);
57     std::vector<std::string> result;
58     while (token != nullptr) {
59         result.emplace_back(token);
60         token = strtok_r(nullptr, split.c_str(), &saveChar);
61     }
62     return result;
63 }
64 
UriParse(OHOS::Uri &uri, std::map<std::string, int> &keyMap)65 int UriUtils::UriParse(OHOS::Uri &uri, std::map<std::string, int> &keyMap)
66 {
67     std::string path = uri.GetPath();
68     if (path.empty()) {
69         return OPERATION_ERROR;
70     }
71     std::map<std::string, int>::iterator iterator = keyMap.find(path);
72     if (iterator != keyMap.end()) {
73         return iterator->second;
74     }
75     return OPERATION_ERROR;
76 }
77 } // namespace Contacts
78 } // namespace OHOS