From dc2a7f054b6ace2e9702651ba27e575d01540fdc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=90=E6=9C=AA=E6=9D=A5?= Date: Fri, 29 Nov 2024 16:55:51 +0800 Subject: [PATCH] =?UTF-8?q?json=E6=9B=BF=E6=8D=A2=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E5=BA=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 徐未来 --- bundle.json | 2 +- services/BUILD.gn | 10 +- services/time_system_ability.cpp | 171 +++++---- services/time_system_ability.h | 4 +- .../{timer_database.h => cjson_helper.h} | 63 ++-- services/timer/src/cjson_helper.cpp | 344 ++++++++++++++++++ services/timer/src/timer_database.cpp | 288 --------------- services/timer/src/timer_manager.cpp | 94 +---- .../timetesttimer_fuzzer/BUILD.gn | 1 + test/fuzztest/timeservice_fuzzer/BUILD.gn | 3 +- test/unittest/service_test/BUILD.gn | 9 +- .../service_test/src/time_client_test.cpp | 1 - .../service_test/src/time_service_test.cpp | 283 +++++++++----- 13 files changed, 685 insertions(+), 588 deletions(-) rename services/timer/include/{timer_database.h => cjson_helper.h} (33%) create mode 100644 services/timer/src/cjson_helper.cpp delete mode 100644 services/timer/src/timer_database.cpp diff --git a/bundle.json b/bundle.json index ac178053..ce87b5eb 100644 --- a/bundle.json +++ b/bundle.json @@ -30,12 +30,12 @@ "napi", "samgr", "common_event_service", + "cJSON", "os_account", "ipc", "netmanager_base", "ability_base", "ability_runtime", - "relational_store", "hilog", "hicollie", "safwk", diff --git a/services/BUILD.gn b/services/BUILD.gn index 9c7a4113..c1343395 100755 --- a/services/BUILD.gn +++ b/services/BUILD.gn @@ -57,8 +57,8 @@ ohos_shared_library("time_system_ability") { "time/src/time_zone_info.cpp", "time/src/timer_notify_callback.cpp", "timer/src/batch.cpp", + "timer/src/cjson_helper.cpp", "timer/src/package_subscriber.cpp", - "timer/src/timer_database.cpp", "timer/src/timer_handler.cpp", "timer/src/timer_info.cpp", "timer/src/timer_manager.cpp", @@ -72,6 +72,7 @@ ohos_shared_library("time_system_ability") { "ability_runtime:wantagent_innerkits", "access_token:libaccesstoken_sdk", "access_token:libtokenid_sdk", + "cJSON:cjson", "c_utils:utils", "common_event_service:cesfwk_innerkits", "hilog:libhilog", @@ -81,8 +82,6 @@ ohos_shared_library("time_system_ability") { "ipc:ipc_single", "netmanager_base:net_conn_manager_if", "os_account:os_account_innerkits", - "relational_store:native_dataability", - "relational_store:native_rdb", "safwk:system_ability_fwk", "samgr:samgr_proxy", ] @@ -135,8 +134,8 @@ ohos_static_library("time_system_ability_static") { "time/src/time_zone_info.cpp", "time/src/timer_notify_callback.cpp", "timer/src/batch.cpp", + "timer/src/cjson_helper.cpp", "timer/src/package_subscriber.cpp", - "timer/src/timer_database.cpp", "timer/src/timer_handler.cpp", "timer/src/timer_info.cpp", "timer/src/timer_manager.cpp", @@ -150,6 +149,7 @@ ohos_static_library("time_system_ability_static") { "ability_runtime:wantagent_innerkits", "access_token:libaccesstoken_sdk", "access_token:libtokenid_sdk", + "cJSON:cjson", "c_utils:utils", "common_event_service:cesfwk_innerkits", "hilog:libhilog", @@ -158,8 +158,6 @@ ohos_static_library("time_system_ability_static") { "ipc:ipc_single", "netmanager_base:net_conn_manager_if", "os_account:os_account_innerkits", - "relational_store:native_dataability", - "relational_store:native_rdb", "safwk:system_ability_fwk", "samgr:samgr_proxy", ] diff --git a/services/time_system_ability.cpp b/services/time_system_ability.cpp index 251364df..53245e33 100644 --- a/services/time_system_ability.cpp +++ b/services/time_system_ability.cpp @@ -37,7 +37,6 @@ #include "timer_notify_callback.h" #include "timer_manager_interface.h" #include "timer_proxy.h" -#include "timer_database.h" #include "time_file_utils.h" #include "common_event_manager.h" #include "common_event_support.h" @@ -192,7 +191,7 @@ void TimeSystemAbility::OnStart() std::string bootCompleted = system::GetParameter(BOOTEVENT_PARAMETER, ""); TIME_HILOGI(TIME_MODULE_SERVICE, "bootCompleted: %{public}s", bootCompleted.c_str()); if (bootCompleted != "true") { - TimeDatabase::GetInstance().ClearDropOnReboot(); + CjsonHelper::GetInstance().Clear(DROP_ON_REBOOT); } AddSystemAbilityListener(ABILITY_MGR_SERVICE_ID); AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID); @@ -964,7 +963,7 @@ void TimeSystemAbility::TimePowerStateListener::OnSyncShutdown() // Clears `drop_on_reboot` table. TIME_HILOGI(TIME_MODULE_SERVICE, "OnSyncShutdown"); TimeSystemAbility::GetInstance()->SetAutoReboot(); - TimeDatabase::GetInstance().ClearDropOnReboot(); + CjsonHelper::GetInstance().Clear(DROP_ON_REBOOT); } void TimeSystemAbility::RegisterPowerStateListener() @@ -982,101 +981,136 @@ void TimeSystemAbility::RegisterPowerStateListener() bool TimeSystemAbility::RecoverTimer() { - auto database = TimeDatabase::GetInstance(); - OHOS::NativeRdb::RdbPredicates holdRdbPredicates(HOLD_ON_REBOOT); - auto holdResultSet = database.Query(holdRdbPredicates, ALL_DATA); - if (holdResultSet == nullptr || holdResultSet->GoToFirstRow() != OHOS::NativeRdb::E_OK) { - TIME_HILOGI(TIME_MODULE_SERVICE, "hold result set is nullptr or go to first row failed"); + cJSON* holdDb = NULL; + auto holdResult = CjsonHelper::GetInstance().QueryTable(HOLD_ON_REBOOT, holdDb); + if (holdResult == NULL) { + TIME_HILOGI(TIME_MODULE_SERVICE, "HOLD_ON_REBOOT get table failed"); } else { - int count; - holdResultSet->GetRowCount(count); + int count = cJSON_GetArraySize(holdResult); TIME_HILOGI(TIME_MODULE_SERVICE, "hold result rows count: %{public}d", count); - RecoverTimerInner(holdResultSet, true); - } - if (holdResultSet != nullptr) { - holdResultSet->Close(); + RecoverTimerInner(holdResult, true); } + cJSON_Delete(holdDb); - OHOS::NativeRdb::RdbPredicates dropRdbPredicates(DROP_ON_REBOOT); - auto dropResultSet = database.Query(dropRdbPredicates, ALL_DATA); - if (dropResultSet == nullptr || dropResultSet->GoToFirstRow() != OHOS::NativeRdb::E_OK) { - TIME_HILOGI(TIME_MODULE_SERVICE, "drop result set is nullptr or go to first row failed"); + cJSON* dropDb = NULL; + auto dropResult = CjsonHelper::GetInstance().QueryTable(DROP_ON_REBOOT, dropDb); + if (dropResult == NULL) { + TIME_HILOGI(TIME_MODULE_SERVICE, "DROP_ON_REBOOT get table failed"); } else { - int count; - dropResultSet->GetRowCount(count); + int count = cJSON_GetArraySize(dropResult); TIME_HILOGI(TIME_MODULE_SERVICE, "drop result rows count: %{public}d", count); - RecoverTimerInner(dropResultSet, false); - } - if (dropResultSet != nullptr) { - dropResultSet->Close(); + RecoverTimerInner(dropResult, false); } + cJSON_Delete(dropDb); return true; } -void TimeSystemAbility::RecoverTimerInner(std::shared_ptr resultSet, bool autoRestore) +std::shared_ptr GetEntry(cJSON* obj, bool autoRestore) +{ + auto item = cJSON_GetObjectItem(obj, "timerId"); + if (item == NULL) return nullptr; + int64_t tmp; + if (!CjsonHelper::GetInstance().StrToI64(item->valuestring, tmp)) return nullptr; + auto timerId = static_cast(tmp); + item = cJSON_GetObjectItem(obj, "type"); + if (item == NULL) { + return nullptr; + } + int type = item->valueint; + item = cJSON_GetObjectItem(obj, "windowLength"); + if (item == NULL) { + return nullptr; + } + uint64_t windowLength = static_cast(item->valueint); + item = cJSON_GetObjectItem(obj, "interval"); + if (item == NULL) { + return nullptr; + } + uint64_t interval = static_cast(item->valueint); + item = cJSON_GetObjectItem(obj, "flag"); + if (item == NULL) { + return nullptr; + } + int flag = item->valueint; + item = cJSON_GetObjectItem(obj, "wantAgent"); + if (item == NULL) { + return nullptr; + } + auto wantAgent = OHOS::AbilityRuntime::WantAgent::WantAgentHelper::FromString(item->valuestring); + item = cJSON_GetObjectItem(obj, "uid"); + if (item == NULL) { + return nullptr; + } + int uid = item->valueint; + item = cJSON_GetObjectItem(obj, "pid"); + if (item == NULL) { + return nullptr; + } + int pid = item->valueint; + item = cJSON_GetObjectItem(obj, "bundleName"); + if (item == NULL) { + return nullptr; + } + auto bundleName = item->valuestring; + return std::make_shared(TimerEntry {timerId, type, windowLength, interval, flag, autoRestore, + nullptr, wantAgent, uid, pid, bundleName}); +} + +void TimeSystemAbility::RecoverTimerInner(cJSON* resultSet, bool autoRestore) { auto timerManager = TimerManager::GetInstance(); if (timerManager == nullptr) { return; } - do { - auto timerId = static_cast(GetLong(resultSet, 0)); - auto timerInfo = std::make_shared(TimerEntry { - // Line 0 is 'timerId' - timerId, - // Line 1 is 'type' - GetInt(resultSet, 1), - // Line 3 is 'windowLength' - static_cast(GetLong(resultSet, 3)), - // Line 4 is 'interval' - static_cast(GetLong(resultSet, 4)), - // Line 2 is 'flag' - GetInt(resultSet, 2), - // autoRestore depends on the table type - autoRestore, - // Callback can't recover. - nullptr, - // Line 7 is 'wantAgent' - OHOS::AbilityRuntime::WantAgent::WantAgentHelper::FromString(GetString(resultSet, 7)), - // Line 5 is 'uid' - GetInt(resultSet, 5), - // Line 10 is 'pid' - GetInt(resultSet, 10), - // Line 6 is 'bundleName' - GetString(resultSet, 6) - }); + int size = cJSON_GetArraySize(resultSet); + for (int i = 0; i < size; ++i) { + // Get data row + cJSON* obj = cJSON_GetArrayItem(resultSet, i); + auto timerInfo = GetEntry(obj, autoRestore); + if (timerInfo == nullptr) { + continue; + } if (timerInfo->wantAgent == nullptr) { TIME_HILOGE(TIME_MODULE_SERVICE, "wantAgent is nullptr, uid=%{public}d, id=%{public}" PRId64 "", timerInfo->uid, timerInfo->id); continue; } - timerManager->ReCreateTimer(timerId, timerInfo); - // Line 8 is 'state' - auto state = static_cast(GetInt(resultSet, 8)); + timerManager->ReCreateTimer(timerInfo->id, timerInfo); + // 'state' + auto item = cJSON_GetObjectItem(obj, "state"); + if (item == NULL) { + continue; + } + auto state = static_cast(item->valueint); if (state == 1) { - // Line 9 is 'triggerTime' - auto triggerTime = static_cast(GetLong(resultSet, 9)); - timerManager->StartTimer(timerId, triggerTime); + // 'triggerTime' + item = cJSON_GetObjectItem(obj, "triggerTime"); + if (item == NULL) { + continue; + } + int64_t triggerTime; + if (!CjsonHelper::GetInstance().StrToI64(item->valuestring, triggerTime)) { + continue; + } + timerManager->StartTimer(timerInfo->id, static_cast(triggerTime)); } - } while (resultSet->GoToNextRow() == OHOS::NativeRdb::E_OK); + } } void TimeSystemAbility::SetAutoReboot() { - auto database = TimeDatabase::GetInstance(); - OHOS::NativeRdb::RdbPredicates holdRdbPredicates(HOLD_ON_REBOOT); - holdRdbPredicates.EqualTo("state", 1)->OrderByAsc("triggerTime"); - auto resultSet = database.Query(holdRdbPredicates, { "bundleName", "triggerTime" }); - if (resultSet == nullptr) { + auto resultSet = CjsonHelper::GetInstance().QueryAutoReboot(); + auto size = resultSet.size(); + if (size == 0) { TIME_HILOGI(TIME_MODULE_SERVICE, "no need to set RTC"); return; } int64_t currentTime = 0; TimeSystemAbility::GetInstance()->GetWallTimeMs(currentTime); auto bundleList = TimeFileUtils::GetParameterList(SCHEDULED_POWER_ON_APPS); - do { - auto bundleName = GetString(resultSet, 0); - uint64_t triggerTime = static_cast(GetLong(resultSet, 1)); + for (uint32_t i = 0; i < size; ++i) { + auto bundleName = resultSet[i].first; + uint64_t triggerTime = static_cast(resultSet[i].second); if (triggerTime < static_cast(currentTime)) { TIME_HILOGI(TIME_MODULE_SERVICE, "triggerTime: %{public}" PRIu64" currentTime: %{public}" PRId64"", triggerTime, currentTime); @@ -1086,7 +1120,6 @@ void TimeSystemAbility::SetAutoReboot() int tmfd = timerfd_create(CLOCK_POWEROFF_ALARM, TFD_NONBLOCK); if (tmfd < 0) { TIME_HILOGE(TIME_MODULE_SERVICE, "timerfd_create error: %{public}s", strerror(errno)); - resultSet->Close(); return; } if (static_cast(currentTime) + TWO_MINUTES_TO_MILLI > triggerTime) { @@ -1106,11 +1139,9 @@ void TimeSystemAbility::SetAutoReboot() TIME_HILOGE(TIME_MODULE_SERVICE, "timerfd_settime error: %{public}s", strerror(errno)); close(tmfd); } - resultSet->Close(); return; } - } while (resultSet->GoToNextRow() == OHOS::NativeRdb::E_OK); - resultSet->Close(); + } } } // namespace MiscServices } // namespace OHOS \ No newline at end of file diff --git a/services/time_system_ability.h b/services/time_system_ability.h index 2cd8b293..8a706284 100644 --- a/services/time_system_ability.h +++ b/services/time_system_ability.h @@ -30,7 +30,7 @@ #include "timer_manager.h" #include "shutdown/sync_shutdown_callback_stub.h" #include "shutdown/shutdown_client.h" -#include "rdb_helper.h" +#include "cjson_helper.h" namespace OHOS { namespace MiscServices { @@ -114,7 +114,7 @@ private: void RegisterPackageRemovedSubscriber(); void RegisterOsAccountSubscriber(); bool IsValidTime(int64_t time); - void RecoverTimerInner(std::shared_ptr resultSet, bool autoRestore); + void RecoverTimerInner(cJSON* resultSet, bool autoRestore); void SetAutoReboot(); ServiceRunningState state_; diff --git a/services/timer/include/timer_database.h b/services/timer/include/cjson_helper.h similarity index 33% rename from services/timer/include/timer_database.h rename to services/timer/include/cjson_helper.h index a5fe25ce..4bcfc1aa 100644 --- a/services/timer/include/timer_database.h +++ b/services/timer/include/cjson_helper.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023 Huawei Device Co., Ltd. + * Copyright (C) 2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,53 +13,44 @@ * limitations under the License. */ -#ifndef TIMER_DATABASE_H -#define TIMER_DATABASE_H +#ifndef TIMER_CJSON_HELPER_H +#define TIMER_CJSON_HELPER_H -#include "rdb_helper.h" -#include "rdb_predicates.h" -#include "rdb_store.h" +#include +#include +#include +#include +#include + +#include +#include "time_hilog.h" +#include "timer_manager_interface.h" namespace OHOS { namespace MiscServices { -constexpr const char *DB_NAME = "/data/service/el1/public/database/time/time.db"; -constexpr int DATABASE_OPEN_VERSION = 1; -constexpr int DATABASE_OPEN_VERSION_2 = 2; -constexpr int CHECK_VERSION_FAILED = -1; -constexpr int API12_5_0_RELEASE = 50; -constexpr int INVALID_VERSION = -50; constexpr int64_t MILLISECOND_TO_NANO = 1000000; constexpr int CLOCK_POWEROFF_ALARM = 12; constexpr const char *HOLD_ON_REBOOT = "hold_on_reboot"; constexpr const char *DROP_ON_REBOOT = "drop_on_reboot"; -int GetInt(std::shared_ptr resultSet, int line); -int64_t GetLong(std::shared_ptr resultSet, int line); -std::string GetString(std::shared_ptr resultSet, int line); - -class TimeDatabase { +class CjsonHelper { public: - TimeDatabase(); - static TimeDatabase &GetInstance(); - bool Insert(const std::string &table, const OHOS::NativeRdb::ValuesBucket &insertValues); - bool Update(const OHOS::NativeRdb::ValuesBucket values, const OHOS::NativeRdb::AbsRdbPredicates &predicates); - std::shared_ptr Query( - const OHOS::NativeRdb::AbsRdbPredicates &predicates, const std::vector &columns); - bool Delete(const OHOS::NativeRdb::AbsRdbPredicates &predicates); - void ClearDropOnReboot(); + std::string QueryWant(std::string tableName, uint64_t timerId); + cJSON* QueryTable(std::string tableName, cJSON* db); + std::vector> QueryAutoReboot(); + bool Insert(std::string tableName, std::shared_ptr timerInfo); + bool UpdateTrigger(std::string tableName, int64_t timerId, int64_t triggerTime); + bool UpdateState(std::string tableName, int64_t timerId); + bool Delete(std::string tableName, int64_t timerId); + void Clear(std::string tableName); + bool StrToI64(std::string str, int64_t& value); + static CjsonHelper &GetInstance(); private: - bool RecoverDataBase(); - std::shared_ptr store_; -}; - -class TimeDBOpenCallback : public OHOS::NativeRdb::RdbOpenCallback { -public: - int OnCreate(OHOS::NativeRdb::RdbStore &rdbStore) override; - int OnOpen(OHOS::NativeRdb::RdbStore &rdbStore) override; - int OnUpgrade(OHOS::NativeRdb::RdbStore &rdbStore, int oldVersion, int newVersion) override; - int OnDowngrade(OHOS::NativeRdb::RdbStore &rdbStore, int currentVersion, int targetVersion) override; + CjsonHelper(); + void SaveJson(cJSON* data); + std::mutex mutex_; }; } // namespace MiscServices } // namespace OHOS -#endif // TIMER_DATABASE_H \ No newline at end of file +#endif //TIMER_CJSON_HELPER_H diff --git a/services/timer/src/cjson_helper.cpp b/services/timer/src/cjson_helper.cpp new file mode 100644 index 00000000..cd6c00ad --- /dev/null +++ b/services/timer/src/cjson_helper.cpp @@ -0,0 +1,344 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include "cjson_helper.h" +#include "want_agent_helper.h" + +namespace OHOS { +namespace MiscServices { +namespace { +const char* DB_PATH = "/data/service/el1/public/database/time/time.json"; +} + +CjsonHelper &CjsonHelper::GetInstance() +{ + static CjsonHelper cjsonHelper; + return cjsonHelper; +} + +CjsonHelper::CjsonHelper() +{ + std::ifstream file(DB_PATH); + if (file.is_open()) { + file.close(); + return; + } + + std::ofstream newFile(DB_PATH); + if (!newFile.is_open()) { + TIME_HILOGE(TIME_MODULE_SERVICE, "Create new file fail"); + return; + } + cJSON* root = cJSON_CreateObject(); + cJSON* holdTable = cJSON_CreateArray(); + cJSON* dropTable = cJSON_CreateArray(); + cJSON_AddItemToObject(root, HOLD_ON_REBOOT, holdTable); + cJSON_AddItemToObject(root, DROP_ON_REBOOT, dropTable); + newFile << cJSON_Print(root); + cJSON_Delete(root); + newFile.close(); +} + +std::string CjsonHelper::QueryWant(std::string tableName, uint64_t timerId) +{ + std::string data = ""; + cJSON* db = NULL; + cJSON* table = QueryTable(tableName, db); + if (table == NULL) { + TIME_HILOGE(TIME_MODULE_SERVICE, "QueryTable fail!"); + cJSON_Delete(db); + return data; + } + + int size = cJSON_GetArraySize(table); + for (int i = 0; i < size; ++i) { + cJSON* obj = cJSON_GetArrayItem(table, i); + + auto item = cJSON_GetObjectItem(obj, "timerId"); + if (item == NULL) { + continue; + } + if (item->valuestring == std::to_string(timerId)) { + item = cJSON_GetObjectItem(obj, "wantAgent"); + if (item != NULL) { + data = item->valuestring; + } + break; + } + } + cJSON_Delete(db); + return data; +} + +// must cJSON_Delete(db) after use, avoid memory leak. +cJSON* CjsonHelper::QueryTable(std::string tableName, cJSON* db) +{ + cJSON* data = NULL; + std::lock_guard lock(mutex_); + + std::ifstream file(DB_PATH); + if (!file.good()) { + TIME_HILOGE(TIME_MODULE_SERVICE, "open json file fail!"); + return data; + } + std::string fileContent((std::istreambuf_iterator(file)), std::istreambuf_iterator()); + db = cJSON_Parse(fileContent.c_str()); + cJSON* table = cJSON_GetObjectItem(db, tableName.c_str()); + if (table == NULL) { + TIME_HILOGE(TIME_MODULE_SERVICE, "%{public}s get fail!", tableName.c_str()); + return data; + } + + data = table; + return data; +} + +bool CjsonHelper::StrToI64(std::string str, int64_t& value) +{ + auto [ptr, ec] = std::from_chars(str.data(), str.data() + str.size(), value); + return ec == std::errc{} && ptr == str.data() + str.size(); +} + +bool Compare(const std::pair& a, const std::pair& b) +{ + return a.second < b.second; +} + +std::vector> CjsonHelper::QueryAutoReboot() +{ + std::vector> result; + cJSON* db = NULL; + cJSON* table = QueryTable(HOLD_ON_REBOOT, db); + if (table == NULL) { + TIME_HILOGE(TIME_MODULE_SERVICE, "QueryTable fail!"); + cJSON_Delete(db); + return result; + } + int size = cJSON_GetArraySize(table); + for (int i = 0; i < size; ++i) { + cJSON* obj = cJSON_GetArrayItem(table, i); + + auto state = cJSON_GetObjectItem(obj, "state"); + if (state == NULL) { + continue; + } + if (state->valueint == 1) { + auto item = cJSON_GetObjectItem(obj, "bundleName"); + if (item == NULL) { + continue; + } + std::string bundleName = item->valuestring; + + item = cJSON_GetObjectItem(obj, "triggerTime"); + if (item == NULL) { + continue; + } + int64_t triggerTime; + if (!StrToI64(item->valuestring, triggerTime)) { + continue; + } + std::pair pair(bundleName, triggerTime); + result.push_back(pair); + } + } + cJSON_Delete(db); + std::sort(result.begin(), result.end(), Compare); + return result; +} + +bool CjsonHelper::Insert(std::string tableName, std::shared_ptr timerInfo) +{ + cJSON* newLine = cJSON_CreateObject(); + + cJSON_AddStringToObject(newLine, "timerId", std::to_string(timerInfo->id).c_str()); + cJSON_AddNumberToObject(newLine, "type", timerInfo->type); + cJSON_AddNumberToObject(newLine, "flag", timerInfo->flag); + cJSON_AddNumberToObject(newLine, "windowLength", timerInfo->windowLength); + cJSON_AddNumberToObject(newLine, "interval", timerInfo->interval); + cJSON_AddNumberToObject(newLine, "uid", timerInfo->uid); + cJSON_AddNumberToObject(newLine, "pid", timerInfo->pid); + cJSON_AddStringToObject(newLine, "bundleName", timerInfo->bundleName.c_str()); + cJSON_AddStringToObject(newLine, "wantAgent", + OHOS::AbilityRuntime::WantAgent::WantAgentHelper::ToString(timerInfo->wantAgent).c_str()); + cJSON_AddNumberToObject(newLine, "state", 0); + cJSON_AddStringToObject(newLine, "triggerTime", "0"); + + std::lock_guard lock(mutex_); + std::ifstream file(DB_PATH); + if (!file.good()) { + TIME_HILOGE(TIME_MODULE_SERVICE, "open json file fail!"); + return false; + } + std::string fileContent((std::istreambuf_iterator(file)), std::istreambuf_iterator()); + cJSON* db = cJSON_Parse(fileContent.c_str()); + cJSON* table = cJSON_GetObjectItem(db, tableName.c_str()); + if (table == NULL) { + TIME_HILOGE(TIME_MODULE_SERVICE, "%{public}s get fail!", tableName.c_str()); + cJSON_Delete(db); + return false; + } + cJSON_AddItemToArray(table, newLine); + SaveJson(db); + cJSON_Delete(db); + return true; +} + +bool CjsonHelper::UpdateTrigger(std::string tableName, int64_t timerId, int64_t triggerTime) +{ + std::lock_guard lock(mutex_); + + std::ifstream file(DB_PATH); + if (!file.good()) { + TIME_HILOGE(TIME_MODULE_SERVICE, "open json file fail!"); + return false; + } + std::string fileContent((std::istreambuf_iterator(file)), std::istreambuf_iterator()); + cJSON* db = cJSON_Parse(fileContent.c_str()); + cJSON* table = cJSON_GetObjectItem(db, tableName.c_str()); + if (table == NULL) { + TIME_HILOGE(TIME_MODULE_SERVICE, "%{public}s get fail!", tableName.c_str()); + cJSON_Delete(db); + return false; + } + + int size = cJSON_GetArraySize(table); + for (int i = 0; i < size; ++i) { + cJSON* obj = cJSON_GetArrayItem(table, i); + + auto timerIdObj = cJSON_GetObjectItem(obj, "timerId"); + if (timerIdObj == NULL) { + continue; + } + if (timerIdObj->valuestring == std::to_string(timerId)) { + cJSON_ReplaceItemInObject(obj, "state", cJSON_CreateNumber(1)); + cJSON_ReplaceItemInObject(obj, "triggerTime", cJSON_CreateString(std::to_string(triggerTime).c_str())); + SaveJson(db); + break; + } + } + cJSON_Delete(db); + return true; +} + +bool CjsonHelper::UpdateState(std::string tableName, int64_t timerId) +{ + std::lock_guard lock(mutex_); + + std::ifstream file(DB_PATH); + if (!file.good()) { + TIME_HILOGE(TIME_MODULE_SERVICE, "open json file fail!"); + return false; + } + std::string fileContent((std::istreambuf_iterator(file)), std::istreambuf_iterator()); + cJSON* db = cJSON_Parse(fileContent.c_str()); + cJSON* table = cJSON_GetObjectItem(db, tableName.c_str()); + if (table == NULL) { + TIME_HILOGE(TIME_MODULE_SERVICE, "%{public}s get fail!", tableName.c_str()); + cJSON_Delete(db); + return false; + } + + int size = cJSON_GetArraySize(table); + for (int i = 0; i < size; ++i) { + cJSON* obj = cJSON_GetArrayItem(table, i); + + auto timerIdObj = cJSON_GetObjectItem(obj, "timerId"); + auto stateObj = cJSON_GetObjectItem(obj, "state"); + if (timerIdObj == NULL || stateObj == NULL) { + continue; + } + if (timerIdObj->valuestring == std::to_string(timerId) && stateObj->valueint == 1) { + cJSON_ReplaceItemInObject(obj, "state", cJSON_CreateNumber(0)); + SaveJson(db); + break; + } + } + cJSON_Delete(db); + return true; +} + +bool CjsonHelper::Delete(std::string tableName, int64_t timerId) +{ + std::lock_guard lock(mutex_); + + std::ifstream file(DB_PATH); + if (!file.good()) { + TIME_HILOGE(TIME_MODULE_SERVICE, "open json file fail!"); + return false; + } + std::string fileContent((std::istreambuf_iterator(file)), std::istreambuf_iterator()); + cJSON* db = cJSON_Parse(fileContent.c_str()); + cJSON* table = cJSON_GetObjectItem(db, tableName.c_str()); + if (table == NULL) { + TIME_HILOGE(TIME_MODULE_SERVICE, "%{public}s get fail!", tableName.c_str()); + cJSON_Delete(db); + return false; + } + + int size = cJSON_GetArraySize(table); + for (int i = 0; i < size; ++i) { + cJSON* obj = cJSON_GetArrayItem(table, i); + + auto timerIdObj = cJSON_GetObjectItem(obj, "timerId"); + if (timerIdObj == NULL) { + continue; + } + if (timerIdObj->valuestring == std::to_string(timerId)) { + cJSON_DeleteItemFromArray(table, i); + SaveJson(db); + break; + } + } + cJSON_Delete(db); + return true; +} + +void CjsonHelper::Clear(std::string tableName) +{ + std::lock_guard lock(mutex_); + + std::ifstream file(DB_PATH); + if (!file.good()) { + TIME_HILOGE(TIME_MODULE_SERVICE, "open json file fail!"); + return; + } + std::string fileContent((std::istreambuf_iterator(file)), std::istreambuf_iterator()); + cJSON* db = cJSON_Parse(fileContent.c_str()); + cJSON* table = cJSON_GetObjectItem(db, tableName.c_str()); + if (table == NULL) { + TIME_HILOGE(TIME_MODULE_SERVICE, "%{public}s get json fail!", tableName.c_str()); + cJSON_Delete(db); + return; + } + + int size = cJSON_GetArraySize(table); + for (int i = size - 1; i >= 0; --i) { + cJSON_DeleteItemFromArray(table, i); + } + SaveJson(db); + cJSON_Delete(db); +} + +void CjsonHelper::SaveJson(cJSON* data) +{ + std::ofstream outFile(DB_PATH); + outFile << cJSON_Print(data); + outFile.close(); +} +} +} diff --git a/services/timer/src/timer_database.cpp b/services/timer/src/timer_database.cpp deleted file mode 100644 index 411cd6dc..00000000 --- a/services/timer/src/timer_database.cpp +++ /dev/null @@ -1,288 +0,0 @@ -/* - * Copyright (c) 2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "timer_database.h" -#include "time_hilog.h" -#include "time_common.h" - -namespace OHOS { -namespace MiscServices { -constexpr const char *CREATE_TIME_TIMER_HOLD_ON_REBOOT = "CREATE TABLE IF NOT EXISTS hold_on_reboot " - "(timerId INTEGER PRIMARY KEY, " - "type INTEGER, " - "flag INTEGER, " - "windowLength INTEGER, " - "interval INTEGER, " - "uid INTEGER, " - "bundleName TEXT, " - "wantAgent TEXT, " - "state INTEGER, " - "triggerTime INTEGER, " - "pid INTEGER)"; - -constexpr const char *CREATE_TIME_TIMER_DROP_ON_REBOOT = "CREATE TABLE IF NOT EXISTS drop_on_reboot " - "(timerId INTEGER PRIMARY KEY, " - "type INTEGER, " - "flag INTEGER, " - "windowLength INTEGER, " - "interval INTEGER, " - "uid INTEGER, " - "bundleName TEXT, " - "wantAgent TEXT, " - "state INTEGER, " - "triggerTime INTEGER, " - "pid INTEGER)"; - -constexpr const char *HOLD_ON_REBOOT_ADD_COLUMN = "ALTER TABLE hold_on_reboot ADD COLUMN pid INTEGER"; - -constexpr const char *DROP_ON_REBOOT_ADD_COLUMN = "ALTER TABLE drop_on_reboot ADD COLUMN pid INTEGER"; - -TimeDatabase::TimeDatabase() -{ - int errCode = OHOS::NativeRdb::E_OK; - OHOS::NativeRdb::RdbStoreConfig config(DB_NAME); - config.SetSecurityLevel(NativeRdb::SecurityLevel::S1); - config.SetEncryptStatus(false); - config.SetReadConSize(1); - TimeDBOpenCallback timeDBOpenCallback; - store_ = OHOS::NativeRdb::RdbHelper::GetRdbStore(config, DATABASE_OPEN_VERSION_2, timeDBOpenCallback, errCode); - TIME_HILOGI(TIME_MODULE_SERVICE, "Gets time database, ret: %{public}d", errCode); - if (errCode == OHOS::NativeRdb::E_SQLITE_CORRUPT) { - auto ret = OHOS::NativeRdb::RdbHelper::DeleteRdbStore(config); - if (ret != OHOS::NativeRdb::E_OK) { - TIME_HILOGE(TIME_MODULE_SERVICE, "delete corrupt database failed, ret: %{public}d", ret); - return; - } - store_ = OHOS::NativeRdb::RdbHelper::GetRdbStore(config, DATABASE_OPEN_VERSION_2, timeDBOpenCallback, errCode); - } -} - -TimeDatabase &TimeDatabase::GetInstance() -{ - static TimeDatabase timeDatabase; - return timeDatabase; -} - -bool TimeDatabase::RecoverDataBase() -{ - OHOS::NativeRdb::RdbStoreConfig config(DB_NAME); - config.SetSecurityLevel(NativeRdb::SecurityLevel::S1); - config.SetEncryptStatus(false); - config.SetReadConSize(1); - auto ret = OHOS::NativeRdb::RdbHelper::DeleteRdbStore(config); - if (ret != OHOS::NativeRdb::E_OK) { - TIME_HILOGE(TIME_MODULE_SERVICE, "delete corrupt database failed, ret: %{public}d", ret); - return false; - } - TimeDBOpenCallback timeDbOpenCallback; - int errCode; - store_ = OHOS::NativeRdb::RdbHelper::GetRdbStore(config, DATABASE_OPEN_VERSION_2, timeDbOpenCallback, errCode); - return true; -} - -int GetInt(std::shared_ptr resultSet, int line) -{ - int value = 0; - resultSet->GetInt(line, value); - return value; -} - -int64_t GetLong(std::shared_ptr resultSet, int line) -{ - int64_t value = 0; - resultSet->GetLong(line, value); - return value; -} - -std::string GetString(std::shared_ptr resultSet, int line) -{ - std::string value = ""; - resultSet->GetString(line, value); - return value; -} - -bool TimeDatabase::Insert(const std::string &table, const OHOS::NativeRdb::ValuesBucket &insertValues) -{ - if (store_ == nullptr) { - TIME_HILOGE(TIME_MODULE_SERVICE, "store_ is nullptr"); - return false; - } - - int64_t outRowId = 0; - int ret = store_->Insert(outRowId, table, insertValues); - if (ret != OHOS::NativeRdb::E_OK) { - TIME_HILOGE(TIME_MODULE_SERVICE, "insert values failed, ret: %{public}d", ret); - if (ret != OHOS::NativeRdb::E_SQLITE_CORRUPT) { - return false; - } - if (!RecoverDataBase()) { - return false; - } - ret = store_->Insert(outRowId, table, insertValues); - if (ret != OHOS::NativeRdb::E_OK) { - TIME_HILOGE(TIME_MODULE_SERVICE, "Insert values after RecoverDataBase failed, ret: %{public}d", ret); - } - } - return true; -} - -bool TimeDatabase::Update( - const OHOS::NativeRdb::ValuesBucket values, const OHOS::NativeRdb::AbsRdbPredicates &predicates) -{ - if (store_ == nullptr) { - TIME_HILOGE(TIME_MODULE_SERVICE, "store_ is nullptr"); - return false; - } - - int changedRows = 0; - int ret = store_->Update(changedRows, values, predicates); - if (ret != OHOS::NativeRdb::E_OK) { - TIME_HILOGE(TIME_MODULE_SERVICE, "update values failed, ret: %{public}d", ret); - if (ret != OHOS::NativeRdb::E_SQLITE_CORRUPT) { - return false; - } - if (!RecoverDataBase()) { - return false; - } - ret = store_->Update(changedRows, values, predicates); - if (ret != OHOS::NativeRdb::E_OK) { - TIME_HILOGE(TIME_MODULE_SERVICE, "Update values after RecoverDataBase failed, ret: %{public}d", ret); - } - } - return true; -} - -std::shared_ptr TimeDatabase::Query( - const OHOS::NativeRdb::AbsRdbPredicates &predicates, const std::vector &columns) -{ - if (store_ == nullptr) { - TIME_HILOGE(TIME_MODULE_SERVICE, "store_ is nullptr"); - return nullptr; - } - auto result = store_->Query(predicates, columns); - int count; - if (result->GetRowCount(count) == OHOS::NativeRdb::E_SQLITE_CORRUPT) { - RecoverDataBase(); - return nullptr; - } - return result; -} - -bool TimeDatabase::Delete(const OHOS::NativeRdb::AbsRdbPredicates &predicates) -{ - if (store_ == nullptr) { - TIME_HILOGE(TIME_MODULE_SERVICE, "store_ is nullptr"); - return false; - } - - int deletedRows = 0; - int ret = store_->Delete(deletedRows, predicates); - if (ret != OHOS::NativeRdb::E_OK) { - TIME_HILOGE(TIME_MODULE_SERVICE, "delete values failed, ret: %{public}d", ret); - if (ret != OHOS::NativeRdb::E_SQLITE_CORRUPT) { - return false; - } - if (!RecoverDataBase()) { - return false; - } - ret = store_->Delete(deletedRows, predicates); - if (ret != OHOS::NativeRdb::E_OK) { - TIME_HILOGE(TIME_MODULE_SERVICE, "Delete values after RecoverDataBase failed, ret: %{public}d", ret); - } - } - return true; -} - -void TimeDatabase::ClearDropOnReboot() -{ - TIME_HILOGI(TIME_MODULE_SERVICE, "Clears drop_on_reboot table"); - if (store_ == nullptr) { - TIME_HILOGE(TIME_MODULE_SERVICE, "store_ is nullptr"); - return; - } - int ret = store_->ExecuteSql("DELETE FROM drop_on_reboot"); - if (ret != OHOS::NativeRdb::E_OK) { - TIME_HILOGE(TIME_MODULE_SERVICE, "Clears drop_on_reboot table failed"); - if (ret != OHOS::NativeRdb::E_SQLITE_CORRUPT) { - return; - } - if (!RecoverDataBase()) { - return; - } - ret = store_->ExecuteSql("DELETE FROM drop_on_reboot"); - if (ret != OHOS::NativeRdb::E_OK) { - TIME_HILOGE(TIME_MODULE_SERVICE, "Clears after RecoverDataBase failed, ret: %{public}d", ret); - } - } -} - -int TimeDBCreateTables(OHOS::NativeRdb::RdbStore &store) -{ - TIME_HILOGI(TIME_MODULE_SERVICE, "Creates hold_on_reboot table"); - // Creates hold_on_reboot table. - int ret = store.ExecuteSql(CREATE_TIME_TIMER_HOLD_ON_REBOOT); - if (ret != OHOS::NativeRdb::E_OK) { - TIME_HILOGE(TIME_MODULE_SERVICE, "Creates hold_on_reboot table failed, ret: %{public}d", ret); - return ret; - } - - TIME_HILOGI(TIME_MODULE_SERVICE, "Creates drop_on_reboot table"); - // Creates drop_on_reboot table. - ret = store.ExecuteSql(CREATE_TIME_TIMER_DROP_ON_REBOOT); - if (ret != OHOS::NativeRdb::E_OK) { - TIME_HILOGE(TIME_MODULE_SERVICE, "Creates drop_on_reboot table failed, ret: %{public}d", ret); - return ret; - } - return ret; -} - -int TimeDBOpenCallback::OnCreate(OHOS::NativeRdb::RdbStore &store) -{ - TIME_HILOGI(TIME_MODULE_SERVICE, "OnCreate"); - auto initRet = TimeDBCreateTables(store); - if (initRet != OHOS::NativeRdb::E_OK) { - TIME_HILOGE(TIME_MODULE_SERVICE, "Init database failed: %{public}d", initRet); - return initRet; - } - return OHOS::NativeRdb::E_OK; -} - -int TimeDBOpenCallback::OnOpen(OHOS::NativeRdb::RdbStore &store) -{ - return OHOS::NativeRdb::E_OK; -} - -int TimeDBOpenCallback::OnUpgrade(OHOS::NativeRdb::RdbStore &store, int oldVersion, int newVersion) -{ - if (oldVersion == DATABASE_OPEN_VERSION && newVersion == DATABASE_OPEN_VERSION_2) { - int ret = store.ExecuteSql(HOLD_ON_REBOOT_ADD_COLUMN); - if (ret != OHOS::NativeRdb::E_OK) { - TIME_HILOGE(TIME_MODULE_SERVICE, "hold_on_reboot add column failed, ret: %{public}d", ret); - return ret; - } - ret = store.ExecuteSql(DROP_ON_REBOOT_ADD_COLUMN); - if (ret != OHOS::NativeRdb::E_OK) { - TIME_HILOGE(TIME_MODULE_SERVICE, "drop_on_reboot add column failed, ret: %{public}d", ret); - return ret; - } - } - return OHOS::NativeRdb::E_OK; -} - -int TimeDBOpenCallback::OnDowngrade(OHOS::NativeRdb::RdbStore &store, int oldVersion, int newVersion) -{ - return OHOS::NativeRdb::E_OK; -} -} -} \ No newline at end of file diff --git a/services/timer/src/timer_manager.cpp b/services/timer/src/timer_manager.cpp index 1a8d7537..53cfcdb7 100644 --- a/services/timer/src/timer_manager.cpp +++ b/services/timer/src/timer_manager.cpp @@ -23,11 +23,6 @@ #include #include "system_ability_definition.h" -#include "rdb_errno.h" -#include "rdb_helper.h" -#include "rdb_open_callback.h" -#include "rdb_predicates.h" -#include "rdb_store.h" #ifdef DEVICE_STANDBY_ENABLE #include "allow_type.h" #include "standby_service_client.h" @@ -37,9 +32,9 @@ #include "time_permission.h" #include "timer_proxy.h" #include "time_sysevent.h" -#include "timer_database.h" #include "os_account.h" #include "os_account_manager.h" +#include "cjson_helper.h" #ifdef POWER_MANAGER_ENABLE #include "time_system_ability.h" #endif @@ -133,24 +128,6 @@ TimerManager* TimerManager::GetInstance() return instance_; } -OHOS::NativeRdb::ValuesBucket GetInsertValues(std::shared_ptr timerInfo, TimerPara ¶s) -{ - OHOS::NativeRdb::ValuesBucket insertValues; - insertValues.PutLong("timerId", timerInfo->id); - insertValues.PutInt("type", paras.timerType); - insertValues.PutInt("flag", paras.flag); - insertValues.PutLong("windowLength", paras.windowLength); - insertValues.PutLong("interval", paras.interval); - insertValues.PutInt("uid", timerInfo->uid); - insertValues.PutString("bundleName", timerInfo->bundleName); - insertValues.PutString("wantAgent", - OHOS::AbilityRuntime::WantAgent::WantAgentHelper::ToString(timerInfo->wantAgent)); - insertValues.PutInt("state", 0); - insertValues.PutLong("triggerTime", 0); - insertValues.PutInt("pid", timerInfo->pid); - return insertValues; -} - int32_t TimerManager::CreateTimer(TimerPara ¶s, std::function callback, std::shared_ptr wantAgent, @@ -193,11 +170,9 @@ int32_t TimerManager::CreateTimer(TimerPara ¶s, if (type == NOT_STORE) { return E_TIME_OK; } else if (CheckNeedRecoverOnReboot(bundleName, paras.timerType, paras.autoRestore)) { - TimeDatabase::GetInstance().Insert(std::string(HOLD_ON_REBOOT), - GetInsertValues(timerInfo, paras)); + CjsonHelper::GetInstance().Insert(std::string(HOLD_ON_REBOOT), timerInfo); } else { - TimeDatabase::GetInstance().Insert(std::string(DROP_ON_REBOOT), - GetInsertValues(timerInfo, paras)); + CjsonHelper::GetInstance().Insert(std::string(DROP_ON_REBOOT), timerInfo); } return E_TIME_OK; } @@ -238,12 +213,9 @@ int32_t TimerManager::StartTimer(uint64_t timerId, uint64_t triggerTime) auto tableName = (CheckNeedRecoverOnReboot(timerInfo->bundleName, timerInfo->type, timerInfo->autoRestore) ? HOLD_ON_REBOOT : DROP_ON_REBOOT); - OHOS::NativeRdb::ValuesBucket values; - values.PutInt("state", 1); - values.PutLong("triggerTime", static_cast(triggerTime)); - OHOS::NativeRdb::RdbPredicates rdbPredicates(tableName); - rdbPredicates.EqualTo("state", 0)->And()->EqualTo("timerId", static_cast(timerId)); - TimeDatabase::GetInstance().Update(values, rdbPredicates); + CjsonHelper::GetInstance().UpdateTrigger(tableName, + static_cast(timerId), + static_cast(triggerTime)); return E_TIME_OK; } @@ -346,26 +318,16 @@ int32_t TimerManager::StopTimerInner(uint64_t timerNumber, bool needDestroy) } } if (needRecoverOnReboot) { - OHOS::NativeRdb::ValuesBucket values; - values.PutInt("state", 0); - OHOS::NativeRdb::RdbPredicates rdbPredicates(HOLD_ON_REBOOT); - rdbPredicates.EqualTo("state", 1)->And()->EqualTo("timerId", static_cast(timerNumber)); - TimeDatabase::GetInstance().Update(values, rdbPredicates); if (needDestroy) { - OHOS::NativeRdb::RdbPredicates rdbPredicatesDelete(HOLD_ON_REBOOT); - rdbPredicatesDelete.EqualTo("timerId", static_cast(timerNumber)); - TimeDatabase::GetInstance().Delete(rdbPredicatesDelete); + CjsonHelper::GetInstance().Delete(HOLD_ON_REBOOT, static_cast(timerNumber)); + } else { + CjsonHelper::GetInstance().UpdateState(HOLD_ON_REBOOT, static_cast(timerNumber)); } } else { - OHOS::NativeRdb::ValuesBucket values; - values.PutInt("state", 0); - OHOS::NativeRdb::RdbPredicates rdbPredicates(DROP_ON_REBOOT); - rdbPredicates.EqualTo("state", 1)->And()->EqualTo("timerId", static_cast(timerNumber)); - TimeDatabase::GetInstance().Update(values, rdbPredicates); if (needDestroy) { - OHOS::NativeRdb::RdbPredicates rdbPredicatesDelete(DROP_ON_REBOOT); - rdbPredicatesDelete.EqualTo("timerId", static_cast(timerNumber)); - TimeDatabase::GetInstance().Delete(rdbPredicatesDelete); + CjsonHelper::GetInstance().Delete(DROP_ON_REBOOT, static_cast(timerNumber)); + } else { + CjsonHelper::GetInstance().UpdateState(DROP_ON_REBOOT, static_cast(timerNumber)); } } return E_TIME_OK; @@ -933,21 +895,9 @@ void TimerManager::DeliverTimersLocked(const std::vectorbundleName, timer->type, timer->autoRestore)) { - OHOS::NativeRdb::ValuesBucket values; - values.PutInt("state", 0); - OHOS::NativeRdb::RdbPredicates rdbPredicates(HOLD_ON_REBOOT); - rdbPredicates.EqualTo("state", 1) - ->And() - ->EqualTo("timerId", static_cast(timer->id)); - TimeDatabase::GetInstance().Update(values, rdbPredicates); + CjsonHelper::GetInstance().UpdateState(HOLD_ON_REBOOT, static_cast(timer->id)); } else { - OHOS::NativeRdb::ValuesBucket values; - values.PutInt("state", 0); - OHOS::NativeRdb::RdbPredicates rdbPredicates(DROP_ON_REBOOT); - rdbPredicates.EqualTo("state", 1) - ->And() - ->EqualTo("timerId", static_cast(timer->id)); - TimeDatabase::GetInstance().Update(values, rdbPredicates); + CjsonHelper::GetInstance().UpdateState(DROP_ON_REBOOT, static_cast(timer->id)); } } if (((timer->flags & static_cast(IS_DISPOSABLE)) > 0) && @@ -973,20 +923,12 @@ bool TimerManager::NotifyWantAgent(const std::shared_ptr &timer) default: break; } - auto database = TimeDatabase::GetInstance(); - OHOS::NativeRdb::RdbPredicates holdRdbPredicates(HOLD_ON_REBOOT); - holdRdbPredicates.EqualTo("timerId", static_cast(timer->id)); - auto holdResultSet = database.Query(holdRdbPredicates, ALL_DATA); - if (holdResultSet == nullptr || holdResultSet->GoToFirstRow() != OHOS::NativeRdb::E_OK) { - TIME_HILOGE(TIME_MODULE_SERVICE, "db query failed nullptr"); - if (holdResultSet != nullptr) { - holdResultSet->Close(); - } + auto wantStr = CjsonHelper::GetInstance().QueryWant(HOLD_ON_REBOOT, timer->id); + if (wantStr == "") { + TIME_HILOGE(TIME_MODULE_SERVICE, "db query failed"); return false; } - // Line 7 is 'wantAgent' - wantAgent = OHOS::AbilityRuntime::WantAgent::WantAgentHelper::FromString(GetString(holdResultSet, 7)); - holdResultSet->Close(); + wantAgent = OHOS::AbilityRuntime::WantAgent::WantAgentHelper::FromString(wantStr); switch (CheckUserIdForNotify(timer)) { case E_TIME_ACCOUNT_NOT_MATCH: TIME_HILOGI(TIME_MODULE_SERVICE, "user sw after FS, id=%{public}" PRId64 "", timer->id); diff --git a/test/fuzztest/timemanager_fuzzer/timetesttimer_fuzzer/BUILD.gn b/test/fuzztest/timemanager_fuzzer/timetesttimer_fuzzer/BUILD.gn index fcdfc48b..bc24d6db 100644 --- a/test/fuzztest/timemanager_fuzzer/timetesttimer_fuzzer/BUILD.gn +++ b/test/fuzztest/timemanager_fuzzer/timetesttimer_fuzzer/BUILD.gn @@ -44,6 +44,7 @@ ohos_fuzztest("TimeTestTimerFuzzTest") { "access_token:libnativetoken", "access_token:libtoken_setproc", "bundle_framework:appexecfwk_core", + "cJSON:cjson", "c_utils:utils", "common_event_service:cesfwk_innerkits", "hilog:libhilog", diff --git a/test/fuzztest/timeservice_fuzzer/BUILD.gn b/test/fuzztest/timeservice_fuzzer/BUILD.gn index e736d8c9..b24ceead 100644 --- a/test/fuzztest/timeservice_fuzzer/BUILD.gn +++ b/test/fuzztest/timeservice_fuzzer/BUILD.gn @@ -133,14 +133,13 @@ foreach(item, time_fuzztests) { "access_token:libnativetoken", "access_token:libtoken_setproc", "bundle_framework:appexecfwk_core", + "cJSON:cjson", "c_utils:utils", "common_event_service:cesfwk_innerkits", "hilog:libhilog", "init:libbegetutil", "ipc:ipc_single", "power_manager:powermgr_client", - "relational_store:native_dataability", - "relational_store:native_rdb", "safwk:system_ability_fwk", "samgr:samgr_proxy", ] diff --git a/test/unittest/service_test/BUILD.gn b/test/unittest/service_test/BUILD.gn index fb5b3503..8b2e4a69 100644 --- a/test/unittest/service_test/BUILD.gn +++ b/test/unittest/service_test/BUILD.gn @@ -59,6 +59,7 @@ ohos_unittest("TimeServiceTest") { "access_token:libaccesstoken_sdk", "access_token:libnativetoken", "access_token:libtoken_setproc", + "cJSON:cjson", "c_utils:utils", "common_event_service:cesfwk_innerkits", "hilog:libhilog", @@ -66,8 +67,6 @@ ohos_unittest("TimeServiceTest") { "ipc:ipc_single", "jsoncpp:jsoncpp", "power_manager:powermgr_client", - "relational_store:native_dataability", - "relational_store:native_rdb", "safwk:system_ability_fwk", "samgr:samgr_proxy", ] @@ -98,13 +97,12 @@ ohos_unittest("TimeClientTest") { "access_token:libaccesstoken_sdk", "access_token:libnativetoken", "access_token:libtoken_setproc", + "cJSON:cjson", "c_utils:utils", "hilog:libhilog", "init:libbegetutil", "ipc:ipc_single", "power_manager:powermgr_client", - "relational_store:native_dataability", - "relational_store:native_rdb", "safwk:system_ability_fwk", "samgr:samgr_proxy", ] @@ -136,13 +134,12 @@ ohos_unittest("TimeDfxTest") { "access_token:libnativetoken", "access_token:libtoken_setproc", "bundle_framework:appexecfwk_core", + "cJSON:cjson", "c_utils:utils", "hilog:libhilog", "init:libbegetutil", "ipc:ipc_single", "power_manager:powermgr_client", - "relational_store:native_dataability", - "relational_store:native_rdb", "safwk:system_ability_fwk", "samgr:samgr_proxy", ] diff --git a/test/unittest/service_test/src/time_client_test.cpp b/test/unittest/service_test/src/time_client_test.cpp index a8880d34..f5c7f6a6 100644 --- a/test/unittest/service_test/src/time_client_test.cpp +++ b/test/unittest/service_test/src/time_client_test.cpp @@ -34,7 +34,6 @@ #define private public #include "time_system_ability.h" #include "time_service_client.h" -#include "timer_database.h" namespace { using namespace testing::ext; diff --git a/test/unittest/service_test/src/time_service_test.cpp b/test/unittest/service_test/src/time_service_test.cpp index 13f39d77..1ebd52b4 100644 --- a/test/unittest/service_test/src/time_service_test.cpp +++ b/test/unittest/service_test/src/time_service_test.cpp @@ -32,6 +32,7 @@ #include "time_common.h" #include "power_subscriber.h" #include "ntp_update_time.h" +#include "cjson_helper.h" #define private public #define protected public @@ -40,7 +41,6 @@ #include "time_system_ability.h" #include "ntp_trusted_time.h" #include "time_tick_notify.h" -#include "timer_database.h" #include "timer_proxy.h" #include "timer_notify_callback.h" @@ -230,6 +230,31 @@ void WaitForAlarm(std::atomic * data, int interval) } } +/** + * @brief Check timeId in json table + * @param tableName the tableName + * @param timerId the timerId need check + */ +bool CheckInJson(std::string tableName, uint64_t timerId) +{ + bool flag = false; + cJSON* db1 = NULL; + cJSON* data1 = CjsonHelper::GetInstance().QueryTable(tableName, db1); + if (data1 != NULL) { + int size = cJSON_GetArraySize(data1); + for (int i = 0; i < size; ++i) { + cJSON* obj = cJSON_GetArrayItem(data1, i); + + if (cJSON_GetObjectItem(obj, "timerId")->valuestring == std::to_string(timerId)) { + flag = true; + break; + } + } + } + cJSON_Delete(db1); + return flag; +} + /** * @tc.name: ProxyTimer001. * @tc.desc: proxy timer. @@ -1216,34 +1241,22 @@ HWTEST_F(TimeServiceTest, TimerManager004, TestSize.Level0) HWTEST_F(TimeServiceTest, TimerManager005, TestSize.Level0) { TimerManager::GetInstance()->NotifyWantAgentRetry(nullptr); - + auto duration = std::chrono::milliseconds::zero(); auto timePoint = std::chrono::steady_clock::now(); auto timerInfo = std::make_shared(TIMER_ID, 0, duration, timePoint, duration, timePoint, duration, nullptr, nullptr, 0, false, 0, 0, ""); auto res = TimerManager::GetInstance()->NotifyWantAgent(timerInfo); EXPECT_FALSE(res); - - OHOS::NativeRdb::ValuesBucket insertValues; - insertValues.PutLong("timerId", TIMER_ID); - insertValues.PutInt("type", 0); - insertValues.PutInt("flag", 0); - insertValues.PutLong("windowLength", 0); - insertValues.PutLong("interval", 0); - insertValues.PutInt("uid", 0); - insertValues.PutString("bundleName", ""); - std::shared_ptr wantAgent = nullptr; - insertValues.PutString("wantAgent", OHOS::AbilityRuntime::WantAgent::WantAgentHelper::ToString(wantAgent)); - insertValues.PutInt("state", 0); - insertValues.PutLong("triggerTime", static_cast(std::numeric_limits::max())); - TimeDatabase::GetInstance().Insert(HOLD_ON_REBOOT, insertValues); + + auto entry = std::make_shared( + TimerEntry{TIMER_ID, 0, 0, 0, 0, false, nullptr, nullptr, 0, 0, "bundleName"}); + CjsonHelper::GetInstance().Insert(HOLD_ON_REBOOT, entry); res = TimerManager::GetInstance()->NotifyWantAgent(timerInfo); EXPECT_FALSE(res); - OHOS::NativeRdb::RdbPredicates rdbPredicatesDelete(HOLD_ON_REBOOT); - rdbPredicatesDelete.EqualTo("timerId", static_cast(TIMER_ID)); - TimeDatabase::GetInstance().Delete(rdbPredicatesDelete); + CjsonHelper::GetInstance().Delete(HOLD_ON_REBOOT, TIMER_ID); } /** @@ -1514,33 +1527,13 @@ HWTEST_F(TimeServiceTest, SystemAbility002, TestSize.Level0) map.erase(it); } - OHOS::NativeRdb::ValuesBucket insertValues1; - insertValues1.PutLong("timerId", timerId1); - insertValues1.PutInt("type", 0); - insertValues1.PutInt("flag", 0); - insertValues1.PutLong("windowLength", 0); - insertValues1.PutLong("interval", 0); - insertValues1.PutInt("uid", 0); - insertValues1.PutString("bundleName", ""); - std::shared_ptr wantAgent = nullptr; - insertValues1.PutString("wantAgent", OHOS::AbilityRuntime::WantAgent::WantAgentHelper::ToString(wantAgent)); - insertValues1.PutInt("state", 0); - insertValues1.PutLong("triggerTime", static_cast(std::numeric_limits::max())); - TimeDatabase::GetInstance().Insert(HOLD_ON_REBOOT, insertValues1); - - OHOS::NativeRdb::ValuesBucket insertValues2; - insertValues2.PutLong("timerId", timerId2); - insertValues2.PutInt("type", 0); - insertValues2.PutInt("flag", 0); - insertValues2.PutLong("windowLength", 0); - insertValues2.PutLong("interval", 0); - insertValues2.PutInt("uid", 0); - insertValues2.PutString("bundleName", ""); - wantAgent = std::shared_ptr(); - insertValues2.PutString("wantAgent", OHOS::AbilityRuntime::WantAgent::WantAgentHelper::ToString(wantAgent)); - insertValues2.PutInt("state", 0); - insertValues2.PutLong("triggerTime", static_cast(std::numeric_limits::max())); - TimeDatabase::GetInstance().Insert(DROP_ON_REBOOT, insertValues2); + auto entry1 = std::make_shared( + TimerEntry{timerId1, 0, 0, 0, 0, true, nullptr, nullptr, 0, 0, "bundleName1"}); + CjsonHelper::GetInstance().Insert(HOLD_ON_REBOOT, entry1); + + auto entry2 = std::make_shared( + TimerEntry{timerId2, 0, 0, 0, 0, false, nullptr, nullptr, 0, 0, "bundleName1"}); + CjsonHelper::GetInstance().Insert(DROP_ON_REBOOT, entry2); TimeSystemAbility::GetInstance()->RecoverTimer(); @@ -1549,13 +1542,8 @@ HWTEST_F(TimeServiceTest, SystemAbility002, TestSize.Level0) it = map.find(timerId2); EXPECT_EQ(it, map.end()); - OHOS::NativeRdb::RdbPredicates rdbPredicatesDelete1(HOLD_ON_REBOOT); - rdbPredicatesDelete1.EqualTo("timerId", static_cast(timerId1)); - TimeDatabase::GetInstance().Delete(rdbPredicatesDelete1); - - OHOS::NativeRdb::RdbPredicates rdbPredicatesDelete2(DROP_ON_REBOOT); - rdbPredicatesDelete2.EqualTo("timerId", static_cast(timerId2)); - TimeDatabase::GetInstance().Delete(rdbPredicatesDelete2); + CjsonHelper::GetInstance().Delete(HOLD_ON_REBOOT, static_cast(timerId1)); + CjsonHelper::GetInstance().Delete(DROP_ON_REBOOT, static_cast(timerId2)); } /** @@ -1568,26 +1556,17 @@ HWTEST_F(TimeServiceTest, SystemAbility003, TestSize.Level0) uint64_t timerId1 = TIMER_ID; TimeSystemAbility::GetInstance()->SetAutoReboot(); - - OHOS::NativeRdb::ValuesBucket insertValues1; - insertValues1.PutLong("timerId", timerId1); - insertValues1.PutInt("type", 0); - insertValues1.PutInt("flag", 0); - insertValues1.PutLong("windowLength", 0); - insertValues1.PutLong("interval", 0); - insertValues1.PutInt("uid", 0); - insertValues1.PutString("bundleName", "anything"); - insertValues1.PutString("wantAgent", ""); - insertValues1.PutInt("state", 1); - insertValues1.PutLong("triggerTime", static_cast(0)); - auto res = TimeDatabase::GetInstance().Insert(HOLD_ON_REBOOT, insertValues1); + + auto entry1 = std::make_shared( + TimerEntry{timerId1, 0, 0, 0, 0, true, nullptr, nullptr, 0, 0, "anything"}); + auto res = CjsonHelper::GetInstance().Insert(HOLD_ON_REBOOT, entry1); + EXPECT_EQ(res, true); + res = CjsonHelper::GetInstance().UpdateTrigger(HOLD_ON_REBOOT, timerId1, 0); EXPECT_EQ(res, true); TimeSystemAbility::GetInstance()->SetAutoReboot(); - OHOS::NativeRdb::RdbPredicates rdbPredicatesDelete1(HOLD_ON_REBOOT); - rdbPredicatesDelete1.EqualTo("timerId", static_cast(timerId1)); - TimeDatabase::GetInstance().Delete(rdbPredicatesDelete1); + CjsonHelper::GetInstance().Delete(HOLD_ON_REBOOT, static_cast(timerId1)); } /** @@ -1602,59 +1581,163 @@ HWTEST_F(TimeServiceTest, SystemAbility004, TestSize.Level0) } /** -* @tc.name: TimeDatabase001. -* @tc.desc: test TimeDatabase Insert. +* @tc.name: TimerInfo001. +* @tc.desc: test UpdateWhenElapsedFromNow. * @tc.type: FUNC */ -HWTEST_F(TimeServiceTest, TimeDatabase001, TestSize.Level0) +HWTEST_F(TimeServiceTest, TimerInfo001, TestSize.Level0) { - OHOS::NativeRdb::ValuesBucket insertValues; - insertValues.PutLong("something", 0); - auto res = TimeDatabase::GetInstance().Insert(DROP_ON_REBOOT, insertValues); + auto duration = std::chrono::milliseconds::zero(); + auto timePoint = std::chrono::steady_clock::now(); + auto timerInfo = TimerInfo(0, 0, duration, timePoint, duration, timePoint, duration, nullptr, + nullptr, 0, false, 0, 0, ""); + auto res = timerInfo.UpdateWhenElapsedFromNow(timePoint, duration); EXPECT_FALSE(res); } /** -* @tc.name: TimeDatabase002. -* @tc.desc: test TimeDatabase Update. +* @tc.name: Cjson001. +* @tc.desc: cjson. * @tc.type: FUNC */ -HWTEST_F(TimeServiceTest, TimeDatabase002, TestSize.Level0) +HWTEST_F(TimeServiceTest, Cjson001, TestSize.Level0) { - OHOS::NativeRdb::ValuesBucket values; - values.PutInt("something", 1); - OHOS::NativeRdb::RdbPredicates rdbPredicates(DROP_ON_REBOOT); - rdbPredicates.EqualTo("something", 0)->And()->EqualTo("something", static_cast(0)); - auto res = TimeDatabase::GetInstance().Update(values, rdbPredicates); - EXPECT_FALSE(res); + auto timerId2 = TIMER_ID + 1; + + auto entry1 = std::make_shared( + TimerEntry{TIMER_ID, 1, 1, 1, 1, false, nullptr, nullptr, 1, 1, "bundleName1"}); + auto ret = CjsonHelper::GetInstance().Insert(std::string(DROP_ON_REBOOT), entry1); + EXPECT_TRUE(ret); + auto entry2 = std::make_shared( + TimerEntry{timerId2, 2, 2, 2, 2, true, nullptr, nullptr, 2, 2, "bundleName2"}); + ret = CjsonHelper::GetInstance().Insert(std::string(HOLD_ON_REBOOT), entry2); + EXPECT_TRUE(ret); + + EXPECT_TRUE(CheckInJson(DROP_ON_REBOOT, TIMER_ID)); + EXPECT_TRUE(CheckInJson(HOLD_ON_REBOOT, timerId2)); + + CjsonHelper::GetInstance().Delete(std::string(DROP_ON_REBOOT), TIMER_ID); + CjsonHelper::GetInstance().Delete(std::string(HOLD_ON_REBOOT), timerId2); + + EXPECT_FALSE(CheckInJson(DROP_ON_REBOOT, TIMER_ID)); + EXPECT_FALSE(CheckInJson(HOLD_ON_REBOOT, timerId2)); } /** -* @tc.name: TimeDatabase003. -* @tc.desc: test TimeDatabase Delete. +* @tc.name: Cjson002. +* @tc.desc: cjson. * @tc.type: FUNC */ -HWTEST_F(TimeServiceTest, TimeDatabase003, TestSize.Level0) +HWTEST_F(TimeServiceTest, Cjson002, TestSize.Level0) { - OHOS::NativeRdb::RdbPredicates rdbPredicatesDelete(DROP_ON_REBOOT); - rdbPredicatesDelete.EqualTo("something", static_cast(0)); - auto res = TimeDatabase::GetInstance().Delete(rdbPredicatesDelete); - EXPECT_FALSE(res); + auto timerId2 = TIMER_ID + 1; + + auto entry1 = std::make_shared( + TimerEntry{TIMER_ID, 1, 1, 1, 1, false, nullptr, nullptr, 1, 1, "bundleName1"}); + auto ret = CjsonHelper::GetInstance().Insert(std::string(DROP_ON_REBOOT), entry1); + EXPECT_TRUE(ret); + auto entry2 = std::make_shared( + TimerEntry{timerId2, 2, 2, 2, 2, true, nullptr, nullptr, 2, 2, "bundleName2"}); + ret = CjsonHelper::GetInstance().Insert(std::string(HOLD_ON_REBOOT), entry2); + EXPECT_TRUE(ret); + + EXPECT_TRUE(CheckInJson(DROP_ON_REBOOT, TIMER_ID)); + EXPECT_TRUE(CheckInJson(HOLD_ON_REBOOT, timerId2)); + + CjsonHelper::GetInstance().Clear(std::string(DROP_ON_REBOOT)); + CjsonHelper::GetInstance().Clear(std::string(HOLD_ON_REBOOT)); + + EXPECT_FALSE(CheckInJson(DROP_ON_REBOOT, TIMER_ID)); + EXPECT_FALSE(CheckInJson(HOLD_ON_REBOOT, timerId2)); } /** -* @tc.name: TimerInfo001. -* @tc.desc: test UpdateWhenElapsedFromNow. +* @tc.name: Cjson003. +* @tc.desc: cjson. * @tc.type: FUNC */ -HWTEST_F(TimeServiceTest, TimerInfo001, TestSize.Level0) +HWTEST_F(TimeServiceTest, Cjson003, TestSize.Level0) { - auto duration = std::chrono::milliseconds::zero(); - auto timePoint = std::chrono::steady_clock::now(); - auto timerInfo = TimerInfo(0, 0, duration, timePoint, duration, timePoint, duration, nullptr, - nullptr, 0, false, 0, 0, ""); - auto res = timerInfo.UpdateWhenElapsedFromNow(timePoint, duration); - EXPECT_FALSE(res); + auto triggerTime = 200; + auto entry1 = std::make_shared( + TimerEntry{TIMER_ID, 1, 1, 1, 1, false, nullptr, nullptr, 1, 1, "bundleName1"}); + CjsonHelper::GetInstance().Insert(std::string(DROP_ON_REBOOT), entry1); + + CjsonHelper::GetInstance().UpdateTrigger(std::string(DROP_ON_REBOOT), TIMER_ID, triggerTime); + + bool flag = false; + cJSON* db1 = NULL; + cJSON* data1 = CjsonHelper::GetInstance().QueryTable(DROP_ON_REBOOT, db1); + if (data1 != NULL) { + int size = cJSON_GetArraySize(data1); + for (int i = 0; i < size; ++i) { + cJSON* obj = cJSON_GetArrayItem(data1, i); + + if (cJSON_GetObjectItem(obj, "timerId")->valuestring == std::to_string(TIMER_ID)) { + auto state = cJSON_GetObjectItem(obj, "state")->valueint; + EXPECT_EQ(state, 1); + string triggerTimeStr = cJSON_GetObjectItem(obj, "triggerTime")->valuestring; + EXPECT_EQ(triggerTimeStr, std::to_string(triggerTime)); + flag = true; + break; + } + } + } + cJSON_Delete(db1); + EXPECT_TRUE(flag); + CjsonHelper::GetInstance().UpdateState(std::string(DROP_ON_REBOOT), TIMER_ID); + flag = false; + db1 = NULL; + data1 = CjsonHelper::GetInstance().QueryTable(DROP_ON_REBOOT, db1); + if (data1 != NULL) { + int size = cJSON_GetArraySize(data1); + for (int i = 0; i < size; ++i) { + cJSON* obj = cJSON_GetArrayItem(data1, i); + + if (cJSON_GetObjectItem(obj, "timerId")->valuestring == std::to_string(TIMER_ID)) { + auto state = cJSON_GetObjectItem(obj, "state")->valueint; + EXPECT_EQ(state, 0); + flag = true; + break; + } + } + } + cJSON_Delete(db1); + EXPECT_TRUE(flag); + + CjsonHelper::GetInstance().Delete(std::string(DROP_ON_REBOOT), TIMER_ID); +} + + +/** +* @tc.name: Cjson004. +* @tc.desc: cjson. +* @tc.type: FUNC +*/ +HWTEST_F(TimeServiceTest, Cjson004, TestSize.Level0) +{ + auto entry1 = std::make_shared( + TimerEntry{TIMER_ID, 1, 1, 1, 1, false, nullptr, nullptr, 1, 1, "bundleName1"}); + CjsonHelper::GetInstance().Insert(std::string(DROP_ON_REBOOT), entry1); + std::string want1 = CjsonHelper::GetInstance().QueryWant(std::string(DROP_ON_REBOOT), TIMER_ID); + EXPECT_EQ(want1, ""); + CjsonHelper::GetInstance().Delete(std::string(DROP_ON_REBOOT), TIMER_ID); +} + +/** +* @tc.name: Cjson005. +* @tc.desc: cjson. +* @tc.type: FUNC +*/ +HWTEST_F(TimeServiceTest, Cjson005, TestSize.Level0) +{ + auto entry1 = std::make_shared( + TimerEntry{TIMER_ID, 1, 1, 1, 1, true, nullptr, nullptr, 1, 1, "bundleName1"}); + CjsonHelper::GetInstance().Insert(std::string(HOLD_ON_REBOOT), entry1); + CjsonHelper::GetInstance().UpdateTrigger(std::string(HOLD_ON_REBOOT), TIMER_ID, 200); + auto data = CjsonHelper::GetInstance().QueryAutoReboot(); + EXPECT_TRUE(data.size() > 0); + CjsonHelper::GetInstance().Delete(std::string(HOLD_ON_REBOOT), TIMER_ID); } /** -- Gitee