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 "hap_resource_manager.h"
17 #include "hilog_wrapper.h"
18 
19 namespace OHOS {
20 namespace Global {
21 namespace Resource {
22 std::shared_ptr<HapResourceManager> HapResourceManager::instance_ = nullptr;
23 std::recursive_mutex HapResourceManager::mutex_;
24 
GetInstance()25 std::shared_ptr<HapResourceManager> HapResourceManager::GetInstance()
26 {
27     if (instance_ == nullptr) {
28         std::lock_guard<std::recursive_mutex> lock(mutex_);
29         if (instance_ == nullptr) {
30             instance_ = std::make_shared<HapResourceManager>();
31         }
32     }
33     return instance_;
34 }
35 
PutAndGetResource(const std::string &path, std::shared_ptr<HapResource> pResource)36 std::shared_ptr<HapResource> HapResourceManager::PutAndGetResource(const std::string &path,
37     std::shared_ptr<HapResource> pResource)
38 {
39     std::unique_lock<std::shared_mutex> lock(mutexRw_);
40     auto iter = hapResourceMap_.find(path);
41     if (iter != hapResourceMap_.end()) {
42         auto res = iter->second.lock();
43         if (res) {
44             return res;
45         }
46     }
47     hapResourceMap_[path] = pResource;
48     return pResource;
49 }
50 
PutPatchResource(const std::string &path, const std::string &patchPath)51 bool HapResourceManager::PutPatchResource(const std::string &path, const std::string &patchPath)
52 {
53     std::unique_lock<std::shared_mutex> lock(mutexRw_);
54     if (hapResourceMap_.find(path) != hapResourceMap_.end()) {
55         std::shared_ptr<HapResource> hapResource = hapResourceMap_[path].lock();
56         if (hapResource) {
57             hapResource->SetPatchPath(patchPath);
58             hapResource->SetIsPatch(true);
59             return true;
60         }
61     }
62     return false;
63 }
64 
GetHapResource(const std::string &path)65 std::shared_ptr<HapResource> HapResourceManager::GetHapResource(const std::string &path)
66 {
67     std::shared_lock<std::shared_mutex> lock(mutexRw_);
68     auto iter = hapResourceMap_.find(path);
69     if (iter != hapResourceMap_.end()) {
70         return iter->second.lock();
71     }
72     return nullptr;
73 }
74 } // namespace Resource
75 } // namespace Global
76 } // namespace OHOS