1 /*
2  * Copyright (c) 2023 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 #ifndef OHOS_SYSTEM_ABILITY_MANAGER_DEVICE_TIMED_COLLECT_TOOL_H
17 #define OHOS_SYSTEM_ABILITY_MANAGER_DEVICE_TIMED_COLLECT_TOOL_H
18 
19 #include <map>
20 #include <time.h>
21 
22 #include "preferences.h"
23 namespace OHOS {
24 class PreferencesUtil {
25 public:
26     static std::shared_ptr<PreferencesUtil> GetInstance();
27     PreferencesUtil() = default;
28     ~PreferencesUtil() = default;
29 
30     bool SaveLong(const std::string& key, int64_t value);
31     bool SaveString(const std::string& key, std::string value);
32 
33     int64_t ObtainLong(const std::string& key, int64_t defValue);
34     std::string ObtainString(const std::string& key, std::string defValue);
35     std::map<std::string, NativePreferences::PreferencesValue> ObtainAll();
36 
37     bool IsExist(const std::string& key);
38     bool Remove(const std::string &key);
39 private:
40     bool GetPreference();
41     bool RefreshSync();
42 
43     template <typename T>
44     bool Save(const std::string& key, const T& defValue);
45 
46     bool SaveInner(
47         std::shared_ptr<NativePreferences::Preferences> ptr, const std::string& key, const int64_t& value);
48     bool SaveInner(
49         std::shared_ptr<NativePreferences::Preferences> ptr, const std::string& key, const std::string& value);
50 
51     template <typename T>
52     T Obtain(const std::string& key, const T& defValue);
53 
54     int64_t ObtainInner(
55         std::shared_ptr<NativePreferences::Preferences> ptr, const std::string& key, const int64_t& defValue);
56     std::string ObtainInner(
57         std::shared_ptr<NativePreferences::Preferences> ptr, const std::string& key, const std::string& defValue);
58     std::shared_ptr<NativePreferences::Preferences> ptr_ = nullptr;
59 };
60 
61 class TimeUtils {
62 public:
GetTimestamp()63     static int64_t GetTimestamp()
64     {
65         time_t currentTime = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
66         return static_cast<int64_t>(currentTime);
67     }
68 };
69 } // namespace OHOS
70 #endif // OHOS_SYSTEM_ABILITY_MANAGER_DEVICE_TIMED_COLLECT_TOOL_H