1 /*
2  * Copyright (c) 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 "base/utils/utils.h"
17 #include "storage_impl.h"
18 
19 namespace OHOS::Ace {
GetPreference(const std::string & fileName)20 std::shared_ptr<NativePreferences::Preferences> StorageImpl::GetPreference(const std::string& fileName)
21 {
22     auto it = preferences_.find(fileName);
23     if (it != preferences_.end()) {
24         return it->second;
25     }
26     auto pref = NativePreferences::PreferencesHelper::GetPreferences(fileName, errCode_);
27     preferences_.insert(std::make_pair(fileName, pref));
28     return pref;
29 }
30 
SetString(const std::string & key,const std::string & value)31 void StorageImpl::SetString(const std::string& key, const std::string& value)
32 {
33     std::shared_ptr<NativePreferences::Preferences> pref = GetPreference(fileName_);
34     CHECK_NULL_VOID(pref);
35     TAG_LOGD(AceLogTag::ACE_STATE_MGMT, "Set preference with key %{public}s, value %{public}s",
36         key.c_str(), value.c_str());
37     pref->PutString(key, value);
38     pref->Flush();
39 }
40 
GetString(const std::string & key)41 std::string StorageImpl::GetString(const std::string& key)
42 {
43     std::shared_ptr<NativePreferences::Preferences> pref = GetPreference(fileName_);
44     CHECK_NULL_RETURN(pref, "");
45     LOGD("Get preference with key %{public}s", key.c_str());
46     return pref->GetString(key, "");
47 }
48 
Clear()49 void StorageImpl::Clear()
50 {
51     std::shared_ptr<NativePreferences::Preferences> pref = GetPreference(fileName_);
52     CHECK_NULL_VOID(pref);
53     pref->Clear();
54     LOGD("StorageImpl: Clear preferences");
55     NativePreferences::PreferencesHelper::DeletePreferences(fileName_);
56     preferences_.erase(fileName_);
57 }
58 
Delete(const std::string & key)59 void StorageImpl::Delete(const std::string& key)
60 {
61     std::shared_ptr<NativePreferences::Preferences> pref = GetPreference(fileName_);
62     CHECK_NULL_VOID(pref);
63     LOGD("StorageImpl: Delete preference with key %{public}s", key.c_str());
64     pref->Delete(key);
65     pref->FlushSync();
66 }
67 
GetStorage() const68 RefPtr<Storage> StorageProxyImpl::GetStorage() const
69 {
70     return AceType::MakeRefPtr<StorageImpl>();
71 }
72 } // namespace OHOS::Ace