diff --git a/OAT.xml b/OAT.xml index 141c974629a4f597457ba8c40d35817195d2f17d..96b39662a64dc3b78a7dd784ee9ea8bb2effc280 100644 --- a/OAT.xml +++ b/OAT.xml @@ -62,8 +62,7 @@ Note:If the text contains special characters, please escape them according to th - - + diff --git a/frameworks/kits/ability/ability_runtime/test/mock/AMS/mock_serviceability_manager_service.h b/frameworks/kits/ability/ability_runtime/test/mock/AMS/mock_serviceability_manager_service.h index 64a58e4af28053ea5d50d7749bb0d70aca268f73..fb6a3059f83231995beaae402548ef8beaa4540a 100644 --- a/frameworks/kits/ability/ability_runtime/test/mock/AMS/mock_serviceability_manager_service.h +++ b/frameworks/kits/ability/ability_runtime/test/mock/AMS/mock_serviceability_manager_service.h @@ -117,7 +117,7 @@ public: MOCK_METHOD1(GetPendinTerminateAbilityTestgRequestWant, void(int id)); MOCK_METHOD1(GetSystemMemoryAttr, void(AppExecFwk::SystemMemoryAttr &memoryInfo)); MOCK_METHOD3(StartContinuation, int(const Want &want, const sptr &abilityToken, int32_t status)); - MOCK_METHOD2(NotifyContinuationResult, int(int32_t missionId, int32_t result)); + MOCK_METHOD2(NotifyContinuationResult, int(int32_t missionId, const int32_t result)); MOCK_METHOD1(LockMissionForCleanup, int(int32_t missionId)); MOCK_METHOD1(UnlockMissionForCleanup, int(int32_t missionId)); @@ -134,7 +134,6 @@ public: MOCK_METHOD1(CleanMission, int(int32_t missionId)); MOCK_METHOD0(CleanAllMissions, int()); MOCK_METHOD1(MoveMissionToFront, int(int32_t missionId)); - MOCK_METHOD2(MoveMissionToFront, int(int32_t missionId, const StartOptions &startOptions)); MOCK_METHOD2(GetWantSenderInfo, int(const sptr &target, std::shared_ptr &info)); diff --git a/frameworks/kits/ability/native/BUILD.gn b/frameworks/kits/ability/native/BUILD.gn index 3bfc269332c0bb3e5bb209f88bc9c9886d4af406..6473ae59308887c8615615c408608d211d178e7b 100644 --- a/frameworks/kits/ability/native/BUILD.gn +++ b/frameworks/kits/ability/native/BUILD.gn @@ -76,7 +76,6 @@ config("ability_public_config") { "//third_party/libuv/include", "//foundation/aafwk/standard/frameworks/kits/appkit/native/ability_runtime/context", "//foundation/aafwk/standard/interfaces/innerkits/base/include/ohos/aafwk/base", - "//foundation/aafwk/standard/frameworks/kits/ability/native/include", "//foundation/aafwk/standard/frameworks/kits/ability/native/include/continuation/remote_register_service", "//foundation/aafwk/standard/frameworks/kits/ability/native/include/continuation/distributed", "//foundation/aafwk/standard/frameworks/kits/ability/native/include/distributed_ability_runtime", @@ -125,7 +124,6 @@ ohos_shared_library("abilitykit_native") { "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/common/include", "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/napi_dataability/include", "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/napi_resultset/include", - "//foundation/distributeddatamgr/objectstore/interfaces/innerkits/", "//base/global/i18n_standard/frameworks/intl/include", ] @@ -234,7 +232,6 @@ ohos_shared_library("abilitykit_native") { configs = [ ":ability_config" ] public_configs = [ ":ability_public_config", - "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits_public_config", "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime:ability_context_public_config", ] @@ -242,7 +239,6 @@ ohos_shared_library("abilitykit_native") { ":static_subscriber_ipc", "${INNERKITS_PATH}/base:base", "${INNERKITS_PATH}/want:want", - "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", "//foundation/aafwk/standard/common/task_dispatcher:task_dispatcher", "//foundation/aafwk/standard/frameworks/kits/ability/ability_runtime:ability_context_native", @@ -257,7 +253,6 @@ ohos_shared_library("abilitykit_native") { "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//foundation/multimodalinput/input/frameworks/proxy:libmmi-common", - "//foundation/resourceschedule/background_task_mgr/interfaces/innerkits:bgtaskmgr_innerkits", "//third_party/icu/icu4c:shared_icuuc", ] @@ -269,7 +264,6 @@ ohos_shared_library("abilitykit_native") { "access_token:libaccesstoken_sdk", "bytrace_standard:bytrace_core", "ces_standard:cesfwk_innerkits", - "distributeddataobject:distributeddataobject_impl", "form_runtime:fmskit_native", "form_runtime:form_manager", "ipc:ipc_core", diff --git a/frameworks/kits/ability/native/include/ability.h b/frameworks/kits/ability/native/include/ability.h index b43960bd9f453c32481e04de3b16671937f44a93..55b6f88512d06c6b7b8b07a5a346a41e34ac2a8b 100755 --- a/frameworks/kits/ability/native/include/ability.h +++ b/frameworks/kits/ability/native/include/ability.h @@ -44,7 +44,6 @@ #include "iremote_object.h" #include "pac_map.h" #include "want.h" -#include "want_agent.h" #include "window_option.h" #include "window_scene.h" #include "wm_common.h" @@ -672,14 +671,6 @@ public: */ virtual void Dump(const std::string &extra); - /** - * @brief dump ability info - * - * @param params dump params that indicate different dump targets - * @param info dump ability info - */ - virtual void Dump(const std::vector ¶ms, std::vector &info); - /** * @brief Keeps this Service ability in the background and displays a notification bar. * To use this method, you need to request the ohos.permission.KEEP_BACKGROUND_RUNNING permission from the system. @@ -1015,21 +1006,6 @@ public: */ bool DeleteForm(const int64_t formId); - /** - * @brief Keep this Service ability in the background and displays a notification bar. - * - * @param wantAgent Indicates which ability to start when user click the notification bar. - * @return the method result code, 0 means succeed - */ - virtual int StartBackgroundRunning(const Notification::WantAgent::WantAgent &wantAgent) final; - - /** - * @brief Cancel background running of this ability to free up system memory. - * - * @return the method result code, 0 means succeed - */ - virtual int StopBackgroundRunning() final; - /** * @brief The form callback. */ @@ -1461,13 +1437,6 @@ protected: */ bool IsRestoredInContinuation() const; - /** - * @brief wait for distributed object to complete sync - * - * @param want the want param. - */ - void WaitingDistributedObjectSyncComplete(const Want& want); - /** * @brief Notify continuation * diff --git a/frameworks/kits/ability/native/include/ability_impl.h b/frameworks/kits/ability/native/include/ability_impl.h index c5ee7da16074c8a1a2cbfcf658f9b819474cd50c..cf2afeb8a7be214080708c16877ed46f0aef3014 100755 --- a/frameworks/kits/ability/native/include/ability_impl.h +++ b/frameworks/kits/ability/native/include/ability_impl.h @@ -349,7 +349,7 @@ public: * * @return */ - virtual void NotifyContinuationResult(int32_t result); + virtual void NotifyContinuationResult(const int32_t result); bool IsStageBasedModel() const; diff --git a/frameworks/kits/ability/native/include/ability_thread.h b/frameworks/kits/ability/native/include/ability_thread.h index 6ad054d18b45ab4b8c3d975ccbacb96d7aec9345..2b870321f205bc52bf9e4ba1571d8da954edc34a 100644 --- a/frameworks/kits/ability/native/include/ability_thread.h +++ b/frameworks/kits/ability/native/include/ability_thread.h @@ -313,7 +313,7 @@ public: * * @param result: Continuation result */ - void NotifyContinuationResult(int32_t result); + void NotifyContinuationResult(const int32_t result); /** * @brief Converts the given uri that refer to the Data ability into a normalized URI. A normalized URI can be used @@ -400,7 +400,7 @@ public: * * @param runnerInfo ability runner info. */ - void DumpAbilityInfo(const std::vector ¶ms, std::vector &info); + void DumpAbilityInfo(std::vector &info); sptr CallRequest(); diff --git a/frameworks/kits/ability/native/include/datashare_helper.h b/frameworks/kits/ability/native/include/datashare_helper.h index 29f15ba6204ae3db567c35b5a7cca94538170eec..39cb1935acea396869e28e72de8bf2f7f1732525 100644 --- a/frameworks/kits/ability/native/include/datashare_helper.h +++ b/frameworks/kits/ability/native/include/datashare_helper.h @@ -264,6 +264,7 @@ private: std::shared_ptr uri_ = nullptr; sptr dataShareProxy_ = nullptr; bool isSystemCaller_ = false; + std::mutex lock_; static std::mutex oplock_; sptr callerDeathRecipient_ = nullptr; std::map, sptr> registerMap_; diff --git a/frameworks/kits/ability/native/include/distributed_ability_runtime/distributed_client.h b/frameworks/kits/ability/native/include/distributed_ability_runtime/distributed_client.h index f931e17ee99613f02c29201f15f589ac75c14b86..a8a75b9274d14a0ab816832619682586dfe2e29a 100644 --- a/frameworks/kits/ability/native/include/distributed_ability_runtime/distributed_client.h +++ b/frameworks/kits/ability/native/include/distributed_ability_runtime/distributed_client.h @@ -31,15 +31,14 @@ class DistributedClient { public: DistributedClient() = default; virtual ~DistributedClient() = default; - int32_t StartRemoteAbility(const OHOS::AAFwk::Want& want, int32_t callerUid, int32_t requestCode, - uint32_t accessToken); + int32_t StartRemoteAbility(const OHOS::AAFwk::Want& want, int32_t callerUid, int32_t requestCode); int32_t ContinueMission(const std::string& srcDeviceId, const std::string& dstDeviceId, int32_t missionId, const sptr& callback, const OHOS::AAFwk::WantParams& wantParams); int32_t StartContinuation(const OHOS::AAFwk::Want& want, int32_t missionId, int32_t callerUid, - int32_t status, uint32_t accessToken); + int32_t status); int32_t NotifyCompleteContinuation(const std::u16string &devId, int32_t sessionId, bool isSuccess); - int32_t ConnectRemoteAbility(const OHOS::AAFwk::Want& want, const sptr& connect, - int32_t callerUid, int32_t callerPid, uint32_t accessToken); + int32_t ConnectRemoteAbility(const OHOS::AAFwk::Want& want, + const sptr& connect, int32_t callerUid, int32_t callerPid); int32_t DisconnectRemoteAbility(const sptr& connect); int32_t StartSyncRemoteMissions(const std::string& devId, bool fixConflict, int64_t tag); int32_t StopSyncRemoteMissions(const std::string& devId); diff --git a/frameworks/kits/ability/native/include/iability_callback.h b/frameworks/kits/ability/native/include/iability_callback.h index 7a4f8195fb735b16484c707afbdf86c200710baf..a62753795d5072be4f603e408ca9f91fb6c4a1fc 100644 --- a/frameworks/kits/ability/native/include/iability_callback.h +++ b/frameworks/kits/ability/native/include/iability_callback.h @@ -20,9 +20,6 @@ namespace OHOS { namespace AppExecFwk { class IAbilityCallback { public: - IAbilityCallback() = default; - virtual ~IAbilityCallback() = default; - /** * @brief Called back at ability context. */ diff --git a/frameworks/kits/ability/native/src/ability.cpp b/frameworks/kits/ability/native/src/ability.cpp index bb233168059572d73a527a0f156a8de053f60854..54ce04dd2027150cccb628e9cbfb4bff8921e0b3 100755 --- a/frameworks/kits/ability/native/src/ability.cpp +++ b/frameworks/kits/ability/native/src/ability.cpp @@ -24,20 +24,17 @@ #include "ability_runtime/js_ability.h" #include "abs_shared_result_set.h" #include "app_log_wrapper.h" -#include "background_task_mgr_helper.h" #include "bytrace.h" #include "connection_manager.h" #include "context_impl.h" #include "continuation_manager.h" #include "continuation_register_manager.h" #include "continuation_register_manager_proxy.h" -#include "continuous_task_param.h" #include "data_ability_operation.h" #include "data_ability_predicates.h" #include "data_ability_result.h" #include "data_uri_utils.h" #include "display_type.h" -#include "distributed_objectstore.h" #include "form_host_client.h" #include "form_mgr.h" #include "form_provider_client.h" @@ -81,7 +78,6 @@ static std::mutex formLock; constexpr int64_t SEC_TO_MILLISEC = 1000; constexpr int64_t MILLISEC_TO_NANOSEC = 1000000; -constexpr int32_t DISTRIBUTED_OBJECT_TIMEOUT = 3000; Ability* Ability::Create(const std::unique_ptr& runtime) { @@ -279,7 +275,6 @@ void Ability::Destroy() APP_LOGI("%{public}s begin.", __func__); // Release the scene. if (scene_ != nullptr) { - scene_->GoDestroy(); scene_ = nullptr; onSceneDestroyed(); } @@ -418,43 +413,8 @@ bool Ability::IsRestoredInContinuation() const return false; } -void Ability::WaitingDistributedObjectSyncComplete(const Want& want) -{ - int sessionId = want.GetIntParam(DMS_SESSION_ID, DEFAULT_DMS_SESSION_ID); - std::string originDeviceId = want.GetStringParam(DMS_ORIGIN_DEVICE_ID); - - APP_LOGI("continuation WaitingDistributedObjectSyncComplete begin"); - auto timeout = [self = shared_from_this(), sessionId, originDeviceId]() { - APP_LOGI("DistributedObject sync timeout"); - self->continuationManager_->NotifyCompleteContinuation( - originDeviceId, sessionId, false, nullptr); - }; - - // std::shared_ptr handler = handler_; - auto callback = [self = shared_from_this(), sessionId, originDeviceId]() { - APP_LOGI("DistributedObject sync complete"); - if (self->handler_ != nullptr) { - self->handler_->RemoveTask("Waiting_Sync_Timeout"); - } - self->continuationManager_->NotifyCompleteContinuation( - originDeviceId, sessionId, true, nullptr); - }; - - std::string &bundleName = abilityInfo_->bundleName; - APP_LOGI("continuation TriggerRestore begin"); - ObjectStore::DistributedObjectStore::GetInstance(bundleName)->TriggerRestore(callback); - APP_LOGI("continuation TriggerRestore end"); - - if (handler_ != nullptr) { - APP_LOGI("continuation set timeout begin"); - handler_->PostTask(timeout, "Waiting_Sync_Timeout", DISTRIBUTED_OBJECT_TIMEOUT); - APP_LOGI("continuation set timeout end"); - } -} - void Ability::NotityContinuationResult(const Want& want, bool success) { - APP_LOGI("NotityContinuationResult begin"); std::weak_ptr ReplicaHandler = continuationHandler_; reverseContinuationSchedulerReplica_ = sptr( new (std::nothrow) ReverseContinuationSchedulerReplica(handler_, ReplicaHandler)); @@ -1262,15 +1222,6 @@ void Ability::Dump(const std::string &extra) } } -/** - * @brief dump ability info - * - * @param params dump params that indicate different dump targets - * @param info dump ability info -*/ -void Ability::Dump(const std::vector ¶ms, std::vector &info) -{} - /** * @brief Keeps this Service ability in the background and displays a notification bar. * To use this method, you need to request the ohos.permission.KEEP_BACKGROUND_RUNNING permission from the system. @@ -1994,30 +1945,6 @@ bool Ability::DeleteForm(const int64_t formId) return DeleteForm(formId, DELETE_FORM); } -/** - * @brief Keep this Service ability in the background and displays a notification bar. - * - * @param wantAgent Indicates which ability to start when user click the notification bar. - * @return the method result code, 0 means succeed - */ -int Ability::StartBackgroundRunning(const Notification::WantAgent::WantAgent &wantAgent) -{ - uint32_t defaultBgMode = 0; - BackgroundTaskMgr::ContinuousTaskParam taskParam = BackgroundTaskMgr::ContinuousTaskParam(false, defaultBgMode, - std::make_shared(wantAgent), abilityInfo_->name, GetToken()); - return BackgroundTaskMgr::BackgroundTaskMgrHelper::RequestStartBackgroundRunning(taskParam); -} - -/** - * @brief Cancel background running of this ability to free up system memory. - * - * @return the method result code, 0 means succeed - */ -int Ability::StopBackgroundRunning() -{ - return BackgroundTaskMgr::BackgroundTaskMgrHelper::RequestStopBackgroundRunning(abilityInfo_->name, GetToken()); -} - /** * @brief Cast temp form with formId. * @@ -3345,13 +3272,6 @@ void Ability::DoOnForeground(const Want& want) if (abilityWindow_ != nullptr) { APP_LOGI("%{public}s begin abilityWindow_->OnPostAbilityForeground, sceneFlag:%{public}d.", __func__, sceneFlag_); - auto window = abilityWindow_->GetWindow(); - if (window != nullptr && want.HasParameter(Want::PARAM_RESV_WINDOW_MODE)) { - auto windowMode = want.GetIntParam(Want::PARAM_RESV_WINDOW_MODE, - AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_UNDEFINED); - window->SetWindowMode(static_cast(windowMode)); - APP_LOGI("set window mode = %{public}d.", windowMode); - } abilityWindow_->OnPostAbilityForeground(sceneFlag_); APP_LOGI("%{public}s end abilityWindow_->OnPostAbilityForeground.", __func__); } else { diff --git a/frameworks/kits/ability/native/src/ability_impl.cpp b/frameworks/kits/ability/native/src/ability_impl.cpp index e4aed208c0b86bafd483c7795b99c2151532e007..a57bfb9b105a507c8b8ad7c0deb012704f790d6a 100755 --- a/frameworks/kits/ability/native/src/ability_impl.cpp +++ b/frameworks/kits/ability/native/src/ability_impl.cpp @@ -918,7 +918,7 @@ void AbilityImpl::ContinueAbility(const std::string& deviceId) ability_->ContinueAbilityWithStack(deviceId); } -void AbilityImpl::NotifyContinuationResult(int32_t result) +void AbilityImpl::NotifyContinuationResult(const int32_t result) { if (ability_ == nullptr) { APP_LOGE("AbilityImpl::NotifyContinuationResult ability_ is nullptr"); diff --git a/frameworks/kits/ability/native/src/ability_runtime/js_ability.cpp b/frameworks/kits/ability/native/src/ability_runtime/js_ability.cpp index 46ad247b289b5d972ef53bb86a0de7dbcd48c879..a5563e07cd4b44bbd7d94b58cd97b8226cb2dc36 100755 --- a/frameworks/kits/ability/native/src/ability_runtime/js_ability.cpp +++ b/frameworks/kits/ability/native/src/ability_runtime/js_ability.cpp @@ -455,18 +455,10 @@ void JsAbility::DoOnForeground(const Want &want) HILOG_ERROR("restore: content storage is nullptr"); } OnSceneRestored(); - WaitingDistributedObjectSyncComplete(want); + NotityContinuationResult(want, true); } else { OnSceneCreated(); } - } else { - auto window = scene_->GetMainWindow(); - if (window != nullptr && want.HasParameter(Want::PARAM_RESV_WINDOW_MODE)) { - auto windowMode = want.GetIntParam(Want::PARAM_RESV_WINDOW_MODE, - AAFwk::AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_UNDEFINED); - window->SetWindowMode(static_cast(windowMode)); - HILOG_INFO("set window mode = %{public}d.", windowMode); - } } HILOG_INFO("%{public}s begin scene_->GoForeground, sceneFlag_:%{public}d.", __func__, Ability::sceneFlag_); scene_->GoForeground(Ability::sceneFlag_); diff --git a/frameworks/kits/ability/native/src/ability_thread.cpp b/frameworks/kits/ability/native/src/ability_thread.cpp index 9b980402d57eab7ace70b5937bd9519ef40a7ed8..ef238eaad0ae519a171255214fd23e9343d5316d 100644 --- a/frameworks/kits/ability/native/src/ability_thread.cpp +++ b/frameworks/kits/ability/native/src/ability_thread.cpp @@ -1212,7 +1212,7 @@ void AbilityThread::ContinueAbility(const std::string& deviceId) abilityImpl_->ContinueAbility(deviceId); } -void AbilityThread::NotifyContinuationResult(int32_t result) +void AbilityThread::NotifyContinuationResult(const int32_t result) { APP_LOGI("NotifyContinuationResult, result:%{public}d", result); if (abilityImpl_ == nullptr) { @@ -1559,23 +1559,9 @@ std::shared_ptr AbilityThread::BuildAbilityConte return abilityContextImpl; } -void AbilityThread::DumpAbilityInfo(const std::vector ¶ms, std::vector &info) +void AbilityThread::DumpAbilityInfo(std::vector &info) { APP_LOGI("%{public}s begin.", __func__); - if (!params.empty()) { - if (abilityImpl_->IsStageBasedModel()) { - auto window = currentAbility_->GetWindow(); - if (window == nullptr) { - APP_LOGE("DumpAbilityInfo window == nullptr"); - return; - } - window->DumpInfo(params, info); - } else { - currentAbility_->Dump(params, info); - } - - return; - } std::string dumpInfo = " event:"; info.push_back(dumpInfo); diff --git a/frameworks/kits/ability/native/src/continuation/distributed/continuation_manager.cpp b/frameworks/kits/ability/native/src/continuation/distributed/continuation_manager.cpp index 92d95f336f54d4eb0808697cd104683c8b7cb16a..cb26a3056faad3fca07eabb702b6b31b870e919a 100644 --- a/frameworks/kits/ability/native/src/continuation/distributed/continuation_manager.cpp +++ b/frameworks/kits/ability/native/src/continuation/distributed/continuation_manager.cpp @@ -21,7 +21,6 @@ #include "app_log_wrapper.h" #include "continuation_handler.h" #include "distributed_client.h" -#include "distributed_objectstore.h" #include "operation_builder.h" #include "string_ex.h" #include "string_wrapper.h" @@ -163,9 +162,6 @@ int32_t ContinuationManager::OnContinueAndGetContent(WantParams &wantParams) APP_LOGE("OnContinue failed."); return CONTINUE_ON_CONTINUE_FAILED; } - auto abilityInfo = abilityInfo_.lock(); - std::string &bundleName = abilityInfo->bundleName; - ObjectStore::DistributedObjectStore::GetInstance(bundleName)->TriggerSync(); status = GetContentInfo(wantParams); if (!status) { diff --git a/frameworks/kits/ability/native/src/datashare_helper.cpp b/frameworks/kits/ability/native/src/datashare_helper.cpp index 5635726b05fea9b0226d738be5b13e677884aece..db011ced34f4b0abab034ba8c220b3f4672e2258 100644 --- a/frameworks/kits/ability/native/src/datashare_helper.cpp +++ b/frameworks/kits/ability/native/src/datashare_helper.cpp @@ -30,7 +30,6 @@ namespace OHOS { namespace AppExecFwk { namespace { const std::string SCHEME_DATASHARE = "datashare"; -constexpr int INVALID_VALUE = -1; } // namespace std::mutex DataShareHelper::oplock_; @@ -92,6 +91,7 @@ void DataShareHelper::AddDataShareDeathRecipient(const sptr &toke void DataShareHelper::OnSchedulerDied(const wptr &remote) { APP_LOGI("'%{public}s start':", __func__); + std::lock_guard guard(lock_); auto object = remote.promote(); object = nullptr; dataShareProxy_ = nullptr; @@ -147,19 +147,19 @@ std::shared_ptr DataShareHelper::Creator( std::shared_ptr DataShareHelper::Creator( const std::shared_ptr &context, const AAFwk::Want &want, const std::shared_ptr &uri) { - APP_LOGI("DataShareHelper::Creator with context, want and uri called start."); + APP_LOGI("DataShareHelper::Creator with context uri called start."); if (context == nullptr) { - APP_LOGE("DataShareHelper::Creator failed, context == nullptr"); + APP_LOGE("DataShareHelper::Creator (context, uri) failed, context == nullptr"); return nullptr; } if (uri == nullptr) { - APP_LOGE("DataShareHelper::Creator failed, uri == nullptr"); + APP_LOGE("DataShareHelper::Creator (context, uri) failed, uri == nullptr"); return nullptr; } if (uri->GetScheme() != SCHEME_DATASHARE) { - APP_LOGE("DataShareHelper::Creator failed, the Scheme is not datashare, Scheme: %{public}s", + APP_LOGE("DataShareHelper::Creator (context, uri) failed, the Scheme is not datashare, Scheme: %{public}s", uri->GetScheme().c_str()); return nullptr; } @@ -179,11 +179,11 @@ std::shared_ptr DataShareHelper::Creator( DataShareHelper *ptrDataShareHelper = new (std::nothrow) DataShareHelper(context, want, uri, dataShareProxy); if (ptrDataShareHelper == nullptr) { - APP_LOGE("DataShareHelper::Creator failed, create DataShareHelper failed"); + APP_LOGE("DataShareHelper::Creator (context, uri) failed, create DataShareHelper failed"); return nullptr; } - APP_LOGI("DataShareHelper::Creator with context, want and uri called end."); + APP_LOGI("DataShareHelper::Creator with context uri called end."); return std::shared_ptr(ptrDataShareHelper); } @@ -202,19 +202,19 @@ std::shared_ptr DataShareHelper::Creator( const std::shared_ptr &context, const AAFwk::Want &want, const std::shared_ptr &uri) { - APP_LOGI("DataShareHelper::Creator with runtime context, want and uri called start."); + APP_LOGI("DataShareHelper::Creator with context uri called start."); if (context == nullptr) { - APP_LOGE("DataShareHelper::Creator failed, context == nullptr"); + APP_LOGE("DataShareHelper::Creator (context, uri) failed, context == nullptr"); return nullptr; } if (uri == nullptr) { - APP_LOGE("DataShareHelper::Creator failed, uri == nullptr"); + APP_LOGE("DataShareHelper::Creator (context, uri) failed, uri == nullptr"); return nullptr; } if (uri->GetScheme() != SCHEME_DATASHARE) { - APP_LOGE("DataShareHelper::Creator failed, the Scheme is not datashare, Scheme: %{public}s", + APP_LOGE("DataShareHelper::Creator (context, uri) failed, the Scheme is not datashare, Scheme: %{public}s", uri->GetScheme().c_str()); return nullptr; } @@ -234,11 +234,11 @@ std::shared_ptr DataShareHelper::Creator( DataShareHelper *ptrDataShareHelper = new (std::nothrow) DataShareHelper(context, want, uri, dataShareProxy); if (ptrDataShareHelper == nullptr) { - APP_LOGE("DataShareHelper::Creator failed, create DataShareHelper failed"); + APP_LOGE("DataShareHelper::Creator (context, uri) failed, create DataShareHelper failed"); return nullptr; } - APP_LOGI("DataShareHelper::Creator with runtime context, want and uri called end."); + APP_LOGI("DataShareHelper::Creator with context uri called end."); return std::shared_ptr(ptrDataShareHelper); } @@ -251,6 +251,7 @@ std::shared_ptr DataShareHelper::Creator( bool DataShareHelper::Release() { APP_LOGI("DataShareHelper::Release start."); + std::lock_guard guard(lock_); if (uri_ == nullptr) { APP_LOGE("DataShareHelper::Release failed, uri_ is nullptr"); return false; @@ -278,6 +279,7 @@ bool DataShareHelper::Release() std::vector DataShareHelper::GetFileTypes(Uri &uri, const std::string &mimeTypeFilter) { APP_LOGI("DataShareHelper::GetFileTypes start."); + std::lock_guard guard(lock_); std::vector matchedMIMEs; if (!CheckUriParam(uri)) { APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); @@ -294,8 +296,6 @@ std::vector DataShareHelper::GetFileTypes(Uri &uri, const std::stri if (isSystemCaller_ && dataShareProxy_) { AddDataShareDeathRecipient(dataShareProxy_->AsObject()); } - } else { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); } if (dataShareProxy_ == nullptr) { @@ -333,7 +333,8 @@ std::vector DataShareHelper::GetFileTypes(Uri &uri, const std::stri int DataShareHelper::OpenFile(Uri &uri, const std::string &mode) { APP_LOGI("DataShareHelper::OpenFile start."); - int fd = INVALID_VALUE; + std::lock_guard guard(lock_); + int fd = -1; if (!CheckUriParam(uri)) { APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); return fd; @@ -349,8 +350,6 @@ int DataShareHelper::OpenFile(Uri &uri, const std::string &mode) if (isSystemCaller_ && dataShareProxy_) { AddDataShareDeathRecipient(dataShareProxy_->AsObject()); } - } else { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); } if (dataShareProxy_ == nullptr) { @@ -388,7 +387,8 @@ int DataShareHelper::OpenFile(Uri &uri, const std::string &mode) int DataShareHelper::OpenRawFile(Uri &uri, const std::string &mode) { APP_LOGI("DataShareHelper::OpenRawFile start."); - int fd = INVALID_VALUE; + std::lock_guard guard(lock_); + int fd = -1; if (!CheckUriParam(uri)) { APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); return fd; @@ -404,8 +404,6 @@ int DataShareHelper::OpenRawFile(Uri &uri, const std::string &mode) if (isSystemCaller_ && dataShareProxy_) { AddDataShareDeathRecipient(dataShareProxy_->AsObject()); } - } else { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); } if (dataShareProxy_ == nullptr) { @@ -439,7 +437,8 @@ int DataShareHelper::OpenRawFile(Uri &uri, const std::string &mode) int DataShareHelper::Insert(Uri &uri, const NativeRdb::ValuesBucket &value) { APP_LOGI("DataShareHelper::Insert start."); - int index = INVALID_VALUE; + std::lock_guard guard(lock_); + int index = -1; if (!CheckUriParam(uri)) { APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); return index; @@ -455,8 +454,6 @@ int DataShareHelper::Insert(Uri &uri, const NativeRdb::ValuesBucket &value) if (isSystemCaller_ && dataShareProxy_) { AddDataShareDeathRecipient(dataShareProxy_->AsObject()); } - } else { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); } if (dataShareProxy_ == nullptr) { @@ -492,7 +489,8 @@ int DataShareHelper::Update( Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) { APP_LOGI("DataShareHelper::Update start."); - int index = INVALID_VALUE; + std::lock_guard guard(lock_); + int index = -1; if (!CheckUriParam(uri)) { APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); return index; @@ -508,8 +506,6 @@ int DataShareHelper::Update( if (isSystemCaller_ && dataShareProxy_) { AddDataShareDeathRecipient(dataShareProxy_->AsObject()); } - } else { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); } if (dataShareProxy_ == nullptr) { @@ -543,7 +539,8 @@ int DataShareHelper::Update( int DataShareHelper::Delete(Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) { APP_LOGI("DataShareHelper::Delete start."); - int index = INVALID_VALUE; + std::lock_guard guard(lock_); + int index = -1; if (!CheckUriParam(uri)) { APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); return index; @@ -559,8 +556,6 @@ int DataShareHelper::Delete(Uri &uri, const NativeRdb::DataAbilityPredicates &pr if (isSystemCaller_ && dataShareProxy_) { AddDataShareDeathRecipient(dataShareProxy_->AsObject()); } - } else { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); } if (dataShareProxy_ == nullptr) { @@ -596,6 +591,7 @@ std::shared_ptr DataShareHelper::Query( Uri &uri, std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) { APP_LOGI("DataShareHelper::Query start."); + std::lock_guard guard(lock_); std::shared_ptr resultset = nullptr; if (!CheckUriParam(uri)) { @@ -613,8 +609,6 @@ std::shared_ptr DataShareHelper::Query( if (isSystemCaller_ && dataShareProxy_) { AddDataShareDeathRecipient(dataShareProxy_->AsObject()); } - } else { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); } if (dataShareProxy_ == nullptr) { @@ -648,6 +642,7 @@ std::shared_ptr DataShareHelper::Query( std::string DataShareHelper::GetType(Uri &uri) { APP_LOGI("DataShareHelper::GetType start."); + std::lock_guard guard(lock_); std::string type; if (!CheckUriParam(uri)) { APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); @@ -664,8 +659,6 @@ std::string DataShareHelper::GetType(Uri &uri) if (isSystemCaller_ && dataShareProxy_) { AddDataShareDeathRecipient(dataShareProxy_->AsObject()); } - } else { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); } if (dataShareProxy_ == nullptr) { @@ -699,7 +692,8 @@ std::string DataShareHelper::GetType(Uri &uri) int DataShareHelper::BatchInsert(Uri &uri, const std::vector &values) { APP_LOGI("DataShareHelper::BatchInsert start."); - int ret = INVALID_VALUE; + std::lock_guard guard(lock_); + int ret = -1; if (!CheckUriParam(uri)) { APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); return ret; @@ -715,8 +709,6 @@ int DataShareHelper::BatchInsert(Uri &uri, const std::vectorAsObject()); } - } else { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); } if (dataShareProxy_ == nullptr) { @@ -922,8 +914,6 @@ void DataShareHelper::NotifyChange(const Uri &uri) dataShareConnection_->ConnectDataShareExtAbility(want_, token_); } dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); - } else { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); } if (dataShareProxy_ == nullptr) { @@ -957,6 +947,7 @@ void DataShareHelper::NotifyChange(const Uri &uri) Uri DataShareHelper::NormalizeUri(Uri &uri) { APP_LOGI("DataShareHelper::NormalizeUri start."); + std::lock_guard guard(lock_); Uri urivalue(""); if (!CheckUriParam(uri)) { APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); @@ -973,8 +964,6 @@ Uri DataShareHelper::NormalizeUri(Uri &uri) if (isSystemCaller_ && dataShareProxy_) { AddDataShareDeathRecipient(dataShareProxy_->AsObject()); } - } else { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); } if (dataShareProxy_ == nullptr) { @@ -1010,6 +999,7 @@ Uri DataShareHelper::NormalizeUri(Uri &uri) Uri DataShareHelper::DenormalizeUri(Uri &uri) { APP_LOGI("DataShareHelper::DenormalizeUri start."); + std::lock_guard guard(lock_); Uri urivalue(""); if (!CheckUriParam(uri)) { APP_LOGE("%{public}s called. CheckUriParam uri failed", __func__); @@ -1026,8 +1016,6 @@ Uri DataShareHelper::DenormalizeUri(Uri &uri) if (isSystemCaller_ && dataShareProxy_) { AddDataShareDeathRecipient(dataShareProxy_->AsObject()); } - } else { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); } if (dataShareProxy_ == nullptr) { @@ -1085,8 +1073,6 @@ std::vector> DataShareHelper::ExecuteBatch( APP_LOGE("DataShareHelper::ExecuteBatch failed dataShareProxy_ == nullptr"); return results; } - } else { - dataShareProxy_ = dataShareConnection_->GetDataShareProxy(); } if (dataShareProxy_ == nullptr) { diff --git a/frameworks/kits/ability/native/src/distributed_ability_runtime/distributed_client.cpp b/frameworks/kits/ability/native/src/distributed_ability_runtime/distributed_client.cpp index 9255c711399672cfbddc0d885b9dfd8f81b52799..b7ef1ed1473c66efb54d242e67ac5bc02ef2e037 100644 --- a/frameworks/kits/ability/native/src/distributed_ability_runtime/distributed_client.cpp +++ b/frameworks/kits/ability/native/src/distributed_ability_runtime/distributed_client.cpp @@ -37,7 +37,7 @@ sptr DistributedClient::GetDmsProxy() } int32_t DistributedClient::StartRemoteAbility(const OHOS::AAFwk::Want& want, - int32_t callerUid, int32_t requestCode, uint32_t accessToken) + int32_t callerUid, int32_t requestCode) { HILOG_INFO("called"); sptr remote = GetDmsProxy(); @@ -51,13 +51,12 @@ int32_t DistributedClient::StartRemoteAbility(const OHOS::AAFwk::Want& want, PARCEL_WRITE_HELPER(data, Parcelable, &want); PARCEL_WRITE_HELPER(data, Int32, callerUid); PARCEL_WRITE_HELPER(data, Int32, requestCode); - PARCEL_WRITE_HELPER(data, Uint32, accessToken); MessageParcel reply; PARCEL_TRANSACT_SYNC_RET_INT(remote, START_REMOTE_ABILITY, data, reply); } -int32_t DistributedClient::ConnectRemoteAbility(const OHOS::AAFwk::Want& want, const sptr& connect, - int32_t callerUid, int32_t callerPid, uint32_t accessToken) +int32_t DistributedClient::ConnectRemoteAbility(const OHOS::AAFwk::Want& want, + const sptr& connect, int32_t callerUid, int32_t callerPid) { HILOG_INFO("called"); if (connect == nullptr) { @@ -78,7 +77,6 @@ int32_t DistributedClient::ConnectRemoteAbility(const OHOS::AAFwk::Want& want, c PARCEL_WRITE_HELPER(data, RemoteObject, connect); PARCEL_WRITE_HELPER(data, Int32, callerUid); PARCEL_WRITE_HELPER(data, Int32, callerPid); - PARCEL_WRITE_HELPER(data, Uint32, accessToken); MessageParcel reply; PARCEL_TRANSACT_SYNC_RET_INT(remote, CONNECT_REMOTE_ABILITY, data, reply); } @@ -132,7 +130,7 @@ int32_t DistributedClient::ContinueMission(const std::string& srcDeviceId, const } int32_t DistributedClient::StartContinuation(const OHOS::AAFwk::Want& want, int32_t missionId, int32_t callerUid, - int32_t status, uint32_t accessToken) + int32_t status) { HILOG_INFO("called"); sptr remote = GetDmsProxy(); @@ -148,7 +146,6 @@ int32_t DistributedClient::StartContinuation(const OHOS::AAFwk::Want& want, int3 PARCEL_WRITE_HELPER(data, Int32, missionId); PARCEL_WRITE_HELPER(data, Int32, callerUid); PARCEL_WRITE_HELPER(data, Int32, status); - PARCEL_WRITE_HELPER(data, Uint32, accessToken); MessageParcel reply; PARCEL_TRANSACT_SYNC_RET_INT(remote, START_CONTINUATION, data, reply); } diff --git a/frameworks/kits/ability/native/src/js_datashare_ext_ability.cpp b/frameworks/kits/ability/native/src/js_datashare_ext_ability.cpp index 58c8add6c898167a2098bb82484df27771274958..dde8bac32b0831fc891daadaf334171fd29ec4d9 100644 --- a/frameworks/kits/ability/native/src/js_datashare_ext_ability.cpp +++ b/frameworks/kits/ability/native/src/js_datashare_ext_ability.cpp @@ -213,7 +213,7 @@ NativeValue* JsDataShareExtAbility::CallObjectMethod(const char* name, NativeVal return nullptr; } HILOG_INFO("JsDataShareExtAbility::CallFunction(%{public}s), success", name); - return handleScope.Escape(nativeEngine.CallFunction(value, method, argv, argc)); + return nativeEngine.CallFunction(value, method, argv, argc); } void JsDataShareExtAbility::GetSrcPath(std::string &srcPath) @@ -338,10 +338,6 @@ int JsDataShareExtAbility::Insert(const Uri &uri, const NativeRdb::ValuesBucket napi_value napiUri = nullptr; napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri); napi_value napiValue = rdbValueBucketNewInstance_(env, const_cast(value)); - if (napiValue == nullptr) { - HILOG_ERROR("%{public}s failed to make new instance of rdbValueBucket.", __func__); - return ret; - } NativeValue* nativeUri = reinterpret_cast(napiUri); NativeValue* nativeValue = reinterpret_cast(napiValue); @@ -381,18 +377,10 @@ int JsDataShareExtAbility::Update(const Uri &uri, const NativeRdb::ValuesBucket napi_value napiUri = nullptr; napi_create_string_utf8(env, uri.ToString().c_str(), NAPI_AUTO_LENGTH, &napiUri); napi_value napiValue = rdbValueBucketNewInstance_(env, const_cast(value)); - if (napiValue == nullptr) { - HILOG_ERROR("%{public}s failed to make new instance of rdbValueBucket.", __func__); - return ret; - } OHOS::NativeRdb::DataAbilityPredicates* predicatesPtr = new OHOS::NativeRdb::DataAbilityPredicates(); *predicatesPtr = predicates; napi_value napiPredicates = dataAbilityPredicatesNewInstance_(env, predicatesPtr); - if (napiPredicates == nullptr) { - HILOG_ERROR("%{public}s failed to make new instance of dataAbilityPredicates.", __func__); - return ret; - } NativeValue* nativeUri = reinterpret_cast(napiUri); NativeValue* nativeValue = reinterpret_cast(napiValue); @@ -431,10 +419,6 @@ int JsDataShareExtAbility::Delete(const Uri &uri, const NativeRdb::DataAbilityPr OHOS::NativeRdb::DataAbilityPredicates* predicatesPtr = new OHOS::NativeRdb::DataAbilityPredicates(); *predicatesPtr = predicates; napi_value napiPredicates = dataAbilityPredicatesNewInstance_(env, predicatesPtr); - if (napiPredicates == nullptr) { - HILOG_ERROR("%{public}s failed to make new instance of dataAbilityPredicates.", __func__); - return ret; - } NativeValue* nativeUri = reinterpret_cast(napiUri); NativeValue* nativePredicates = reinterpret_cast(napiPredicates); @@ -487,10 +471,6 @@ std::shared_ptr JsDataShareExtAbility::Query(cons OHOS::NativeRdb::DataAbilityPredicates* predicatesPtr = new OHOS::NativeRdb::DataAbilityPredicates(); *predicatesPtr = predicates; napi_value napiPredicates = dataAbilityPredicatesNewInstance_(env, predicatesPtr); - if (napiPredicates == nullptr) { - HILOG_ERROR("%{public}s failed to make new instance of dataAbilityPredicates.", __func__); - return ret; - } NativeValue* nativeUri = reinterpret_cast(napiUri); NativeValue* nativeColumns = reinterpret_cast(napiColumns); @@ -502,11 +482,6 @@ std::shared_ptr JsDataShareExtAbility::Query(cons return ret; } - if (rdbResultSetProxyGetNativeObject_ == nullptr) { - HILOG_ERROR("%{public}s rdbResultSetProxyGetNativeObject_ is null.", __func__); - return ret; - } - auto nativeObject = rdbResultSetProxyGetNativeObject_(env, reinterpret_cast(nativeResult)); if (nativeObject == nullptr) { HILOG_ERROR("JsiPaEngine AbsSharedResultSet from JS to Native failed"); @@ -570,10 +545,6 @@ int JsDataShareExtAbility::BatchInsert(const Uri &uri, const std::vector(value)); - if (result == nullptr) { - HILOG_ERROR("%{public}s failed to make new instance of rdbValueBucket.", __func__); - return ret; - } napi_set_element(env, napiValues, index++, result); } @@ -670,13 +641,10 @@ std::vector> JsDataShareExtAbilit bool JsDataShareExtAbility::CheckCallingPermission(const std::string &permission) { - HILOG_INFO("%{public}s begin, permission:%{public}s", __func__, permission.c_str()); if (!permission.empty() && AccessTokenKit::VerifyAccessToken(IPCSkeleton::GetCallingTokenID(), permission) != AppExecFwk::Constants::PERMISSION_GRANTED) { - HILOG_ERROR("%{public}s permission not granted.", __func__); return false; } - HILOG_INFO("%{public}s end.", __func__); return true; } } // namespace AbilityRuntime diff --git a/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_client.h b/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_client.h index c5d85822a23191da8bff21adcca6d7afb56c9b84..3c1fda6d1d2cf024ffd8e193479025671469f4a6 100755 --- a/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_client.h +++ b/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_client.h @@ -125,9 +125,9 @@ public: { return std::vector>(); }; - virtual void NotifyContinuationResult(int32_t result) {}; + virtual void NotifyContinuationResult(const int32_t result) {}; virtual void ContinueAbility(const std::string& deviceId) {}; - virtual void DumpAbilityInfo(const std::vector ¶ms, std::vector &info) {}; + virtual void DumpAbilityInfo(std::vector &info) {}; virtual sptr CallRequest() { return sptr(nullptr); @@ -135,4 +135,4 @@ public: }; } // namespace AppExecFwk } // namespace OHOS -#endif // FOUNDATION_APPEXECFWK_OHOS_ABILITY_NATIVE_MOCK_ABILITY_MANAGER_CLIENT_H +#endif // FOUNDATION_APPEXECFWK_OHOS_ABILITY_NATIVE_MOCK_ABILITY_MANAGER_CLIENT_H \ No newline at end of file diff --git a/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_service.h b/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_service.h index 5b09920189075f3c66b0f02e3d65cd0de8ebe1e0..f828cef1da661c0fa4e7c870ea9fa2f8dd643a9a 100644 --- a/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_service.h +++ b/frameworks/kits/ability/native/test/mock/include/mock_ability_manager_service.h @@ -137,7 +137,7 @@ public: MOCK_METHOD1(GetPendinTerminateAbilityTestgRequestWant, void(int id)); MOCK_METHOD1(GetSystemMemoryAttr, void(AppExecFwk::SystemMemoryAttr &memoryInfo)); MOCK_METHOD3(StartContinuation, int(const Want &want, const sptr &abilityToken, int32_t status)); - MOCK_METHOD2(NotifyContinuationResult, int(int32_t missionId, int32_t result)); + MOCK_METHOD2(NotifyContinuationResult, int(int32_t missionId, const int32_t result)); MOCK_METHOD5(ContinueMission, int(const std::string &srcDeviceId, const std::string &dstDeviceId, int32_t missionId, const sptr &callBack, AAFwk::WantParams &wantParams)); MOCK_METHOD2(ContinueAbility, int(const std::string &deviceId, int32_t missionId)); @@ -154,7 +154,6 @@ public: MOCK_METHOD0(CleanAllMissions, int()); MOCK_METHOD2(SetMissionLabel, int(const sptr &token, const std::string &label)); MOCK_METHOD1(MoveMissionToFront, int(int32_t missionId)); - MOCK_METHOD2(MoveMissionToFront, int(int32_t missionId, const StartOptions &startOptions)); MOCK_METHOD1(GetAbilityRunningInfos, int(std::vector &info)); MOCK_METHOD2(GetExtensionRunningInfos, int(int upperLimit, std::vector &info)); diff --git a/frameworks/kits/ability/native/test/mock/include/mock_ability_scheduler_for_observer.h b/frameworks/kits/ability/native/test/mock/include/mock_ability_scheduler_for_observer.h index b5c7d3e35c29fbf24cb2e0c6472ff8b2ec78dc7a..a638facadc4d357173aa3f0ea53da3967a595c11 100755 --- a/frameworks/kits/ability/native/test/mock/include/mock_ability_scheduler_for_observer.h +++ b/frameworks/kits/ability/native/test/mock/include/mock_ability_scheduler_for_observer.h @@ -58,9 +58,9 @@ public: MOCK_METHOD2(ScheduleUnregisterObserver, bool(const Uri &uri, const sptr &dataObserver)); MOCK_METHOD1(ScheduleNotifyChange, bool(const Uri &uri)); MOCK_METHOD1(ExecuteBatch, std::vector>(const std::vector> &operation)); - MOCK_METHOD1(NotifyContinuationResult, void(int32_t result)); + MOCK_METHOD1(NotifyContinuationResult, void(const int32_t result)); MOCK_METHOD1(ContinueAbility, void(const std::string& deviceId)); - MOCK_METHOD2(DumpAbilityInfo, void(const std::vector ¶ms, std::vector &info)); + MOCK_METHOD1(DumpAbilityInfo, void(std::vector &info)); virtual sptr CallRequest() { @@ -71,4 +71,4 @@ public: } // namespace AppExecFwk } // namespace OHOS -#endif /* OHOS_APPEXECFWK_MOCK_ABILITY_SCHEDULER_FOR_OBESERVER_H */ +#endif /* OHOS_APPEXECFWK_MOCK_ABILITY_SCHEDULER_FOR_OBESERVER_H */ \ No newline at end of file diff --git a/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager.cpp b/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager.cpp index cc5a68fc2514c2de026af7017b6360e7f217d29f..0716fe7de162a307d4187a554ace4e357831ccc6 100644 --- a/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager.cpp +++ b/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager.cpp @@ -153,6 +153,11 @@ bool BundleMgrProxy::IsSafeMode() { return true; } +bool BundleMgrProxy::CleanBundleCacheFiles( + const std::string &bundleName, const sptr &cleanCacheCallback) +{ + return true; +} bool BundleMgrProxy::CleanBundleDataFiles(const std::string &bundleName, const int userId) { return true; @@ -178,10 +183,18 @@ bool BundleMgrProxy::IsApplicationEnabled(const std::string &bundleName) { return true; } +bool BundleMgrProxy::SetApplicationEnabled(const std::string &bundleName, bool isEnable) +{ + return true; +} bool BundleMgrProxy::IsAbilityEnabled(const AbilityInfo &abilityInfo) { return true; } +bool BundleMgrProxy::SetAbilityEnabled(const AbilityInfo &abilityInfo, bool isEnabled) +{ + return true; +} std::string BundleMgrProxy::GetAbilityIcon(const std::string &bundleName, const std::string &className) { return ""; @@ -386,6 +399,11 @@ bool BundleMgrService::IsSafeMode() { return true; } +bool BundleMgrService::CleanBundleCacheFiles( + const std::string &bundleName, const sptr &cleanCacheCallback) +{ + return true; +} bool BundleMgrService::CleanBundleDataFiles(const std::string &bundleName, const int userId) { return true; @@ -411,10 +429,18 @@ bool BundleMgrService::IsApplicationEnabled(const std::string &bundleName) { return true; } +bool BundleMgrService::SetApplicationEnabled(const std::string &bundleName, bool isEnable) +{ + return true; +} bool BundleMgrService::IsAbilityEnabled(const AbilityInfo &abilityInfo) { return true; } +bool BundleMgrService::SetAbilityEnabled(const AbilityInfo &abilityInfo, bool isEnabled) +{ + return true; +} std::string BundleMgrService::GetAbilityIcon(const std::string &bundleName, const std::string &className) { return ""; diff --git a/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager.h b/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager.h index aa70e0a23918ce0d9290e7607568fdf4626ffdce..03c958a02c9418b152e5daafdb902cf1577c80eb 100644 --- a/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager.h +++ b/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager.h @@ -79,6 +79,8 @@ public: virtual bool HasSystemCapability(const std::string &capName) override; virtual bool GetSystemAvailableCapabilities(std::vector &systemCaps) override; virtual bool IsSafeMode() override; + virtual bool CleanBundleCacheFiles( + const std::string &bundleName, const sptr &cleanCacheCallback) override; virtual bool CleanBundleDataFiles(const std::string &bundleName, const int userId) override; virtual bool RegisterBundleStatusCallback(const sptr &bundleStatusCallback) override; virtual bool ClearBundleStatusCallback(const sptr &bundleStatusCallback) override; @@ -86,7 +88,9 @@ public: virtual bool DumpInfos( const DumpFlag flag, const std::string &bundleName, int32_t userId, std::string &result) override; virtual bool IsApplicationEnabled(const std::string &bundleName) override; + virtual bool SetApplicationEnabled(const std::string &bundleName, bool isEnable) override; virtual bool IsAbilityEnabled(const AbilityInfo &abilityInfo) override; + virtual bool SetAbilityEnabled(const AbilityInfo &abilityInfo, bool isEnabled) override; virtual std::string GetAbilityIcon(const std::string &bundleName, const std::string &className) override; virtual bool CanRequestPermission( const std::string &bundleName, const std::string &permissionName, const int userId) override; @@ -162,6 +166,8 @@ public: virtual bool HasSystemCapability(const std::string &capName) override; virtual bool GetSystemAvailableCapabilities(std::vector &systemCaps) override; virtual bool IsSafeMode() override; + virtual bool CleanBundleCacheFiles( + const std::string &bundleName, const sptr &cleanCacheCallback) override; virtual bool CleanBundleDataFiles(const std::string &bundleName, const int userId) override; virtual bool RegisterBundleStatusCallback(const sptr &bundleStatusCallback) override; virtual bool ClearBundleStatusCallback(const sptr &bundleStatusCallback) override; @@ -169,7 +175,9 @@ public: virtual bool DumpInfos( const DumpFlag flag, const std::string &bundleName, int32_t userId, std::string &result) override; virtual bool IsApplicationEnabled(const std::string &bundleName) override; + virtual bool SetApplicationEnabled(const std::string &bundleName, bool isEnable) override; virtual bool IsAbilityEnabled(const AbilityInfo &abilityInfo) override; + virtual bool SetAbilityEnabled(const AbilityInfo &abilityInfo, bool isEnabled) override; virtual std::string GetAbilityIcon(const std::string &bundleName, const std::string &className) override; virtual bool CanRequestPermission( const std::string &bundleName, const std::string &permissionName, const int userId) override; diff --git a/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager_form.h b/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager_form.h index 3ef1c1037f58a3f98fdfcfe4b8dbe9d61a99ab56..28704c66b9e271d22d7d9b00ff2fecec13752d47 100644 --- a/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager_form.h +++ b/frameworks/kits/ability/native/test/mock/include/mock_bundle_manager_form.h @@ -146,6 +146,12 @@ public: { return true; } + // clears cache data of a specified application. + virtual bool CleanBundleCacheFiles( + const std::string &bundleName, const sptr &cleanCacheCallback) override + { + return true; + } virtual bool CleanBundleDataFiles(const std::string &bundleName, const int userId) override { return true; @@ -209,6 +215,10 @@ public: { return true; } + virtual bool SetApplicationEnabled(const std::string &bundleName, bool isEnable) override + { + return true; + } virtual bool GetBundleInfo( const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo, int32_t userId) override; @@ -239,6 +249,7 @@ public: bool(const std::string &bundleName, const std::string &permission, const int userId)); MOCK_METHOD2(GetNameForUid, bool(const int uid, std::string &name)); MOCK_METHOD2(GetBundlesForUid, bool(const int uid, std::vector &)); + MOCK_METHOD2(SetAbilityEnabled, bool(const AbilityInfo &, bool)); MOCK_METHOD1(IsAbilityEnabled, bool(const AbilityInfo &)); MOCK_METHOD2(GetAbilityIcon, std::string(const std::string &bundleName, const std::string &className)); MOCK_METHOD1(RegisterAllPermissionsChanged, bool(const sptr &callback)); @@ -333,6 +344,12 @@ public: { return true; }; + // clears cache data of a specified application. + virtual bool CleanBundleCacheFiles( + const std::string &bundleName, const sptr &cleanCacheCallback) override + { + return true; + }; virtual bool RegisterBundleStatusCallback(const sptr &bundleStatusCallback) override { @@ -372,6 +389,10 @@ public: return true; }; + virtual bool SetApplicationEnabled(const std::string &bundleName, bool isEnable) override + { + return true; + }; /** * @brief Obtains information about the shortcuts of the application. diff --git a/frameworks/kits/appkit/native/ability_runtime/form_extension_context.cpp b/frameworks/kits/appkit/native/ability_runtime/form_extension_context.cpp index 7e8e1ae7a34097d79f9dd0b6fb150b8fbae30cf4..c6f080e518b8292a2fc604be38b4f96e98132abc 100644 --- a/frameworks/kits/appkit/native/ability_runtime/form_extension_context.cpp +++ b/frameworks/kits/appkit/native/ability_runtime/form_extension_context.cpp @@ -55,7 +55,7 @@ ErrCode FormExtensionContext::StartAbility(const AAFwk::Want &want) const ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want, token_, -1); HILOG_DEBUG("%{public}s. End calling StartAbility. ret=%{public}d", __func__, err); if (err != ERR_OK) { - HILOG_ERROR("FormExtensionContext::StartAbility is failed %{public}d", err); + HILOG_ERROR("ServiceContext::StartAbility is failed %{public}d", err); } return err; } @@ -66,7 +66,7 @@ ErrCode FormExtensionContext::StartAbility(const AAFwk::Want &want, const AAFwk: ErrCode err = AAFwk::AbilityManagerClient::GetInstance()->StartAbility(want, startOptions, token_, -1); HILOG_DEBUG("%{public}s. End calling StartAbility. ret=%{public}d", __func__, err); if (err != ERR_OK) { - HILOG_ERROR("FormExtensionContext::StartAbility is failed %{public}d", err); + HILOG_ERROR("ServiceContext::StartAbility is failed %{public}d", err); } return err; } @@ -75,7 +75,7 @@ AppExecFwk::AbilityType FormExtensionContext::GetAbilityInfoType() const { std::shared_ptr info = GetAbilityInfo(); if (info == nullptr) { - HILOG_ERROR("FormExtensionContext::GetAbilityInfoType info == nullptr"); + HILOG_ERROR("ServiceContext::GetAbilityInfoType info == nullptr"); return AppExecFwk::AbilityType::UNKNOWN; } diff --git a/frameworks/kits/appkit/native/app/include/main_thread.h b/frameworks/kits/appkit/native/app/include/main_thread.h index 28e6e32b6529b78c4c821cbd3ffc4325ebab2039..4520c6a637fdcbaf43f7577afd95ac0aea34c1e5 100644 --- a/frameworks/kits/appkit/native/app/include/main_thread.h +++ b/frameworks/kits/appkit/native/app/include/main_thread.h @@ -392,10 +392,8 @@ private: * * @brief Task in event handler timeout detected. * - * @param runner the runner belong to the mainthread. - * */ - void TaskTimeoutDetected(const std::shared_ptr& runner); + void TaskTimeoutDetected(); /** * diff --git a/frameworks/kits/appkit/native/app/src/main_thread.cpp b/frameworks/kits/appkit/native/app/src/main_thread.cpp index 9e9c75694653c2ce561534729b22e44053c997f8..868b04c2eb8a613ff5c61fb57f7b1cee244c26c6 100644 --- a/frameworks/kits/appkit/native/app/src/main_thread.cpp +++ b/frameworks/kits/appkit/native/app/src/main_thread.cpp @@ -1294,7 +1294,7 @@ void MainThread::HandleConfigurationUpdated(const Configuration &config) APP_LOGI("MainThread::HandleConfigurationUpdated called end."); } -void MainThread::TaskTimeoutDetected(const std::shared_ptr &runner) +void MainThread::TaskTimeoutDetected() { BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); APP_LOGI("MainThread::TaskTimeoutDetected called start."); @@ -1303,14 +1303,14 @@ void MainThread::TaskTimeoutDetected(const std::shared_ptr &runner) APP_LOGI("MainThread::TaskTimeoutDetected delivery timeout"); }; auto distributeTimeoutCallback = []() { - APP_LOGI("MainThread::TaskTimeoutDetected distribute timeout"); + APP_LOGI("MainThread::TaskTimeoutDetected delivery timeout"); }; - if (runner !=nullptr && mainHandler_ != nullptr) { - runner->SetDeliveryTimeout(DELIVERY_TIME); + if (mainHandler_ != nullptr) { + mainHandler_->SetDeliveryTimeout(DELIVERY_TIME); mainHandler_->SetDeliveryTimeoutCallback(deliveryTimeoutCallback); - runner->SetDistributeTimeout(DISTRIBUTE_TIME); + mainHandler_->SetDistributeTimeout(DISTRIBUTE_TIME); mainHandler_->SetDistributeTimeoutCallback(distributeTimeoutCallback); } APP_LOGI("MainThread::TaskTimeoutDetected called end."); @@ -1341,7 +1341,7 @@ void MainThread::Init(const std::shared_ptr &runner, const std::sha if (!watchDogHandler_->PostTask(taskWatchDog)) { APP_LOGE("MainThread::Init WatchDog postTask task failed"); } - TaskTimeoutDetected(runner); + TaskTimeoutDetected(); /* watchDogHandler_->Init(mainHandler_, watchDogHandler_); APP_LOGI("MainThread:Init before CreateRunner."); diff --git a/frameworks/kits/appkit/native/test/mock/include/mock_ability_manager_client_interface1.h b/frameworks/kits/appkit/native/test/mock/include/mock_ability_manager_client_interface1.h index a82f685e6a34109f42fdfa7c0b1b121f1ddcd445..d1a6b166fa04afa3fcf4f034809301a1b9ec6134 100644 --- a/frameworks/kits/appkit/native/test/mock/include/mock_ability_manager_client_interface1.h +++ b/frameworks/kits/appkit/native/test/mock/include/mock_ability_manager_client_interface1.h @@ -196,6 +196,11 @@ public: { return true; }; + virtual bool CleanBundleCacheFiles( + const std::string &bundleName, const sptr &cleanCacheCallback) + { + return true; + }; virtual bool CleanBundleDataFiles(const std::string &bundleName, const int userId = 0) { return true; @@ -221,10 +226,18 @@ public: { return true; }; + virtual bool SetApplicationEnabled(const std::string &bundleName, bool isEnable) + { + return true; + }; virtual bool IsAbilityEnabled(const AbilityInfo &abilityInfo) { return true; }; + virtual bool SetAbilityEnabled(const AbilityInfo &abilityInfo, bool isEnabled) + { + return true; + }; virtual std::string GetAbilityIcon(const std::string &bundleName, const std::string &className) { return std::string(""); diff --git a/frameworks/kits/appkit/native/test/unittest/context_container_test.cpp b/frameworks/kits/appkit/native/test/unittest/context_container_test.cpp index a4b2e5a9028f78eb19b720dddcf4bafb0fe58ea7..c9a1cda312b5d30edeccde4783b9f0306889108f 100644 --- a/frameworks/kits/appkit/native/test/unittest/context_container_test.cpp +++ b/frameworks/kits/appkit/native/test/unittest/context_container_test.cpp @@ -52,18 +52,18 @@ void ContextContainerTest::TearDownTestCase(void) void ContextContainerTest::SetUp(void) { + OHOS::sptr bundleObject = new (std::nothrow) BundleMgrService(); + + OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility( + OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, bundleObject); OHOS::DelayedSingleton::GetInstance()->RegisterSystemAbility( - OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, new BundleMgrService()); + OHOS::ABILITY_MGR_SERVICE_ID, bundleObject); context_ = std::make_shared(); contextDeal_ = std::make_shared(); } void ContextContainerTest::TearDown(void) -{ - OHOS::DelayedSingleton::DestroyInstance(); - context_ = nullptr; - contextDeal_ = nullptr; -} +{} /** * @tc.number: AppExecFwk_ContextContainer_GetBundleName_0100 diff --git a/frameworks/kits/appkit/test/Mock/include/mock_ability_mgr_service.h b/frameworks/kits/appkit/test/Mock/include/mock_ability_mgr_service.h index c776ffb53d14ad541ee7e3ff6b21f128b8b80689..f53ce738e032cb1419c6ee36a623a62e308f3338 100644 --- a/frameworks/kits/appkit/test/Mock/include/mock_ability_mgr_service.h +++ b/frameworks/kits/appkit/test/Mock/include/mock_ability_mgr_service.h @@ -73,7 +73,6 @@ public: MOCK_METHOD1(CleanMission, int(int32_t missionId)); MOCK_METHOD0(CleanAllMissions, int()); MOCK_METHOD1(MoveMissionToFront, int(int32_t missionId)); - MOCK_METHOD2(MoveMissionToFront, int(int32_t missionId, const StartOptions &startOptions)); MOCK_METHOD1(GetAbilityRunningInfos, int(std::vector &info)); MOCK_METHOD2(GetExtensionRunningInfos, int(int upperLimit, std::vector &info)); @@ -109,6 +108,7 @@ private: bool DumpStateCalled_ = false; Semaphore sem_; }; + } // namespace AAFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_KITS_APPKIT_TEST_MOCK_ABILITY_MGR_SERVICE_H \ No newline at end of file diff --git a/frameworks/kits/appkit/test/Mock/include/mock_bundle_mgr_service.h b/frameworks/kits/appkit/test/Mock/include/mock_bundle_mgr_service.h index 3154fb4edcebf07f909d5272b63b630eab2f0547..f7a06c00d72fee5393a977776aab46203c7f1376 100644 --- a/frameworks/kits/appkit/test/Mock/include/mock_bundle_mgr_service.h +++ b/frameworks/kits/appkit/test/Mock/include/mock_bundle_mgr_service.h @@ -87,6 +87,8 @@ public: MOCK_METHOD1(HasSystemCapability, bool(const std::string &capName)); MOCK_METHOD1(GetSystemAvailableCapabilities, bool(std::vector &systemCaps)); MOCK_METHOD0(IsSafeMode, bool()); + MOCK_METHOD2(CleanBundleCacheFiles, + bool(const std::string &bundleName, const sptr &cleanCacheCallback)); MOCK_METHOD2(CleanBundleDataFiles, bool(const std::string &bundleName, const int userId)); MOCK_METHOD1(RegisterBundleStatusCallback, bool(const sptr &bundleStatusCallback)); MOCK_METHOD1(ClearBundleStatusCallback, bool(const sptr &bundleStatusCallback)); @@ -98,6 +100,7 @@ public: } MOCK_METHOD0(GetBundleInstaller, sptr()); MOCK_METHOD1(GetBundleInstaller, bool(const std::string &)); + MOCK_METHOD2(SetApplicationEnabled, bool(const std::string &, bool)); MOCK_METHOD1(IsApplicationEnabled, bool(const std::string &)); virtual bool CanRequestPermission( @@ -112,6 +115,7 @@ public: } MOCK_METHOD2(GetNameForUid, bool(const int uid, std::string &name)); MOCK_METHOD2(GetBundlesForUid, bool(const int uid, std::vector &)); + MOCK_METHOD2(SetAbilityEnabled, bool(const AbilityInfo &, bool)); MOCK_METHOD1(IsAbilityEnabled, bool(const AbilityInfo &)); MOCK_METHOD2(GetAbilityIcon, std::string(const std::string &bundleName, const std::string &className)); MOCK_METHOD1(RegisterAllPermissionsChanged, bool(const sptr &callback)); diff --git a/frameworks/kits/test/mock/AMS/mock_ability_manager_service.h b/frameworks/kits/test/mock/AMS/mock_ability_manager_service.h index d44cbd503d610ae9a1b1df78a99466542b8d8625..08e6ee1ace67e73282896984c89290b71d4badb0 100644 --- a/frameworks/kits/test/mock/AMS/mock_ability_manager_service.h +++ b/frameworks/kits/test/mock/AMS/mock_ability_manager_service.h @@ -114,7 +114,7 @@ public: MOCK_METHOD1(SetMissionStackSetting, int(const StackSetting &stackSetting)); MOCK_METHOD1(GetPendinTerminateAbilityTestgRequestWant, void(int id)); MOCK_METHOD3(StartContinuation, int(const Want &want, const sptr &abilityToken, int32_t status)); - MOCK_METHOD2(NotifyContinuationResult, int(int32_t missionId, int32_t result)); + MOCK_METHOD2(NotifyContinuationResult, int(int32_t missionId, const int32_t result)); MOCK_METHOD5(ContinueMission, int(const std::string &srcDeviceId, const std::string &dstDeviceId, int32_t missionId, const sptr &callBack, AAFwk::WantParams &wantParams)); MOCK_METHOD2(ContinueAbility, int(const std::string &deviceId, int32_t missionId)); @@ -130,7 +130,6 @@ public: MOCK_METHOD1(CleanMission, int(int32_t missionId)); MOCK_METHOD0(CleanAllMissions, int()); MOCK_METHOD1(MoveMissionToFront, int(int32_t missionId)); - MOCK_METHOD2(MoveMissionToFront, int(int32_t missionId, const StartOptions &startOptions)); MOCK_METHOD2(SetMissionLabel, int(const sptr &token, const std::string &label)); MOCK_METHOD2(GetWantSenderInfo, int(const sptr &target, std::shared_ptr &info)); diff --git a/frameworks/kits/test/mock/AMS/mock_serviceability_manager_service.h b/frameworks/kits/test/mock/AMS/mock_serviceability_manager_service.h index 32f421dde290579f7c87172c52e207a9924a1da7..cca6d5b4c931def3db70089ac07e43f9d0b98e21 100644 --- a/frameworks/kits/test/mock/AMS/mock_serviceability_manager_service.h +++ b/frameworks/kits/test/mock/AMS/mock_serviceability_manager_service.h @@ -113,7 +113,7 @@ public: MOCK_METHOD1(GetPendinTerminateAbilityTestgRequestWant, void(int id)); MOCK_METHOD1(GetSystemMemoryAttr, void(AppExecFwk::SystemMemoryAttr &memoryInfo)); MOCK_METHOD3(StartContinuation, int(const Want &want, const sptr &abilityToken, int32_t status)); - MOCK_METHOD2(NotifyContinuationResult, int(int32_t missionId, int32_t result)); + MOCK_METHOD2(NotifyContinuationResult, int(int32_t missionId, const int32_t result)); MOCK_METHOD5(ContinueMission, int(const std::string &srcDeviceId, const std::string &dstDeviceId, int32_t missionId, const sptr &callBack, AAFwk::WantParams &wantParams)); MOCK_METHOD2(ContinueAbility, int(const std::string &deviceId, int32_t missionId)); @@ -129,7 +129,6 @@ public: MOCK_METHOD1(CleanMission, int(int32_t missionId)); MOCK_METHOD0(CleanAllMissions, int()); MOCK_METHOD1(MoveMissionToFront, int(int32_t missionId)); - MOCK_METHOD2(MoveMissionToFront, int(int32_t missionId, const StartOptions &startOptions)); MOCK_METHOD2(SetMissionLabel, int(const sptr &token, const std::string &label)); MOCK_METHOD2(GetWantSenderInfo, int(const sptr &target, std::shared_ptr &info)); diff --git a/interfaces/innerkits/ability_manager/include/ability_manager_client.h b/interfaces/innerkits/ability_manager/include/ability_manager_client.h index a1276abb2179e7d4647870e6eba0df1c7d694fc2..2fb5972561443b51ff62565ccffacaff28915f65 100644 --- a/interfaces/innerkits/ability_manager/include/ability_manager_client.h +++ b/interfaces/innerkits/ability_manager/include/ability_manager_client.h @@ -609,13 +609,11 @@ public: /** * @brief Move a mission to front. * @param missionId Id of target mission. - * @param startOptions Special startOptions for target mission. * * @return Returns ERR_OK on success, others on failure. */ ErrCode MoveMissionToFront(int32_t missionId); - ErrCode MoveMissionToFront(int32_t missionId, const StartOptions &startOptions); - + /** * Start Ability, connect session with common ability. * @@ -751,16 +749,7 @@ public: * @return Returns ERR_OK on success, others on failure. */ ErrCode DoAbilityBackground(const sptr &token, uint32_t flag); - - /** - * Set ability controller. - * - * @param abilityController, The ability controller. - * @return Returns ERR_OK on success, others on failure. - */ - virtual int SetAbilityController(const sptr &abilityController, - bool imAStabilityTest); - + private: static std::mutex mutex_; static std::shared_ptr instance_; diff --git a/interfaces/innerkits/ability_manager/include/ability_manager_interface.h b/interfaces/innerkits/ability_manager/include/ability_manager_interface.h index f38d68f96f992031423d6caa95d9f091153d926d..b741244ada4b7995ad4c4c0e89b967498a41a0e7 100644 --- a/interfaces/innerkits/ability_manager/include/ability_manager_interface.h +++ b/interfaces/innerkits/ability_manager/include/ability_manager_interface.h @@ -544,7 +544,7 @@ public: virtual void NotifyCompleteContinuation(const std::string &deviceId, int32_t sessionId, bool isSuccess) = 0; - virtual int NotifyContinuationResult(int32_t missionId, int32_t result) = 0; + virtual int NotifyContinuationResult(int32_t missionId, const int32_t result) = 0; virtual int LockMissionForCleanup(int32_t missionId) = 0; @@ -566,9 +566,7 @@ public: virtual int CleanAllMissions() = 0; virtual int MoveMissionToFront(int32_t missionId) = 0; - - virtual int MoveMissionToFront(int32_t missionId, const StartOptions &startOptions) = 0; - + /** * Start Ability, connect session with common ability. * @@ -671,7 +669,7 @@ public: * @return Returns ERR_OK on success, others on failure. */ virtual int DelegatorDoAbilityBackground(const sptr &token) = 0; - + /** * Calls this interface to move the ability to the foreground. * @@ -863,9 +861,6 @@ public: // ipc id for ability background (55) DO_ABILITY_BACKGROUND, - // ipc id for move mission to front by options (56) - MOVE_MISSION_TO_FRONT_BY_OPTIONS, - // ipc id 1001-2000 for DMS // ipc id for starting ability (1001) START_ABILITY = 1001, diff --git a/interfaces/innerkits/ability_manager/include/ability_scheduler_interface.h b/interfaces/innerkits/ability_manager/include/ability_scheduler_interface.h index c56581a4cf5e4d3ae856459ecbcba22f53354789..42db89b98546233e1ad4184f4b98510930be77cb 100644 --- a/interfaces/innerkits/ability_manager/include/ability_scheduler_interface.h +++ b/interfaces/innerkits/ability_manager/include/ability_scheduler_interface.h @@ -273,9 +273,9 @@ public: virtual std::vector> ExecuteBatch( const std::vector> &operations) = 0; virtual void ContinueAbility(const std::string& deviceId) = 0; - virtual void NotifyContinuationResult(int32_t result) = 0; + virtual void NotifyContinuationResult(const int32_t result) = 0; - virtual void DumpAbilityInfo(const std::vector ¶ms, std::vector &info) = 0; + virtual void DumpAbilityInfo(std::vector& info) = 0; virtual sptr CallRequest() = 0; diff --git a/interfaces/innerkits/ability_manager/include/start_options.h b/interfaces/innerkits/ability_manager/include/start_options.h index ed8bc0f6e706c1e3c8393ec73cd162cd0b999be1..82fe7cd47f70d11565949bff267bab297c8fa8a7 100644 --- a/interfaces/innerkits/ability_manager/include/start_options.h +++ b/interfaces/innerkits/ability_manager/include/start_options.h @@ -22,16 +22,11 @@ #include "parcel.h" namespace OHOS { namespace AAFwk { -class StartOptions final : public Parcelable, public std::enable_shared_from_this { +class StartOptions : public Parcelable { public: static const std::string STRING_DISPLAY_ID; const int32_t DEFAULT_DISPLAY_ID {0}; - StartOptions() = default; - ~StartOptions() = default; - StartOptions(const StartOptions &other); - StartOptions &operator=(const StartOptions &other); - bool ReadFromParcel(Parcel &parcel); virtual bool Marshalling(Parcel &parcel) const override; static StartOptions *Unmarshalling(Parcel &parcel); diff --git a/interfaces/kits/js/@ohos.ability.particleAbility.d.ts b/interfaces/kits/js/@ohos.ability.particleAbility.d.ts index a6db3d53a1cbd096a566a01c3a6541eded23ce25..44e794c32b5e290c2508cdc4bd16cbaa51bc3ace 100644 --- a/interfaces/kits/js/@ohos.ability.particleAbility.d.ts +++ b/interfaces/kits/js/@ohos.ability.particleAbility.d.ts @@ -16,7 +16,6 @@ import { AsyncCallback } from './basic'; import { StartAbilityParameter } from './ability/startAbilityParameter'; import { Want } from './ability/want'; import { ConnectOptions } from './ability/connectOptions'; -import { NotificationRequest } from './notification/notificationRequest'; /** * A Particle Ability represents an ability with service. @@ -61,30 +60,5 @@ declare namespace particleAbility { */ function disconnectAbility(connection: number, callback:AsyncCallback): void; function disconnectAbility(connection: number): Promise; - - /** - * Keep this Service ability in the background and display a notification bar. - * - * @since 7 - * @syscap SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask - * @permission ohos.permission.KEEP_BACKGROUND_RUNNING - * @param id Identifies the notification bar information. - * @param request Indicates the notificationRequest instance containing information for displaying a notification bar. - * @FAModelOnly - * @deprecated - */ - function startBackgroundRunning(id: number, request: NotificationRequest, callback: AsyncCallback): void; - function startBackgroundRunning(id: number, request: NotificationRequest): Promise; - - /** - * Cancel background running of this ability to free up system memory. - * - * @since 7 - * @syscap SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask - * @FAModelOnly - * @deprecated - */ - function cancelBackgroundRunning(callback: AsyncCallback): void; - function cancelBackgroundRunning(): Promise; } export default particleAbility; \ No newline at end of file diff --git a/interfaces/kits/js/@ohos.application.DataShareExtAbility.d.ts b/interfaces/kits/js/@ohos.application.DataShareExtAbility.d.ts index 47018ace74d282568866da0a7f48a71c8f2d7eaf..4e9c950410bf29f6b5a263a2799e4e08ce27ab9d 100644 --- a/interfaces/kits/js/@ohos.application.DataShareExtAbility.d.ts +++ b/interfaces/kits/js/@ohos.application.DataShareExtAbility.d.ts @@ -22,16 +22,17 @@ import rdb from './@ohos.data.rdb'; /** * class of datashare extension ability. * - * @since 9 - * @sysCap SystemCapability.DistributedDataMgr.DataShare.Provider + * @since 8 + * @sysCap AAFwk + * @devices phone, tablet, tv, wearable, car * @systemapi hide for inner use. */ export default class DataShareExtAbility { /** * Indicates datashare extension ability context. * - * @since 9 - * @sysCap SystemCapability.DistributedDataMgr.DataShare.Provider + * @since 8 + * @sysCap AAFwk * @systemapi hide for inner use. */ context?: ExtensionContext; @@ -39,8 +40,9 @@ export default class DataShareExtAbility { /** * Called back when a datashare extension ability is started for initialization. * - * @since 9 - * @sysCap SystemCapability.DistributedDataMgr.DataShare.Provider + * @devices phone, tablet, tv, wearable, car + * @since 8 + * @sysCap AAFwk * @param want Indicates connection information about the datashare extension ability. * @systemapi hide for inner use. * @return - @@ -50,8 +52,9 @@ export default class DataShareExtAbility { /** * Obtains the MIME type of files. This method should be implemented by a data share. * - * @since 9 - * @sysCap SystemCapability.DistributedDataMgr.DataShare.Provider + * @devices phone, tablet, tv, wearable, car + * @since 8 + * @sysCap AAFwk * @param uri Indicates the path of the files to obtain. * @param mimeTypeFilter Indicates the MIME type of the files to obtain. This parameter cannot be set to {@code * null}. @@ -60,13 +63,14 @@ export default class DataShareExtAbility { *

3. "*/jpg": Obtains files whose subtype is JPG of any main type. * @return Returns the MIME type of the matched files; returns null if there is no type that matches the Data */ - getFileTypes?(uri: string, mimeTypeFilter: string): Array; + getFileTypes?(uri: string, mimeTypeFilter:string, callback: AsyncCallback>): void; /** * Opens a file. This method should be implemented by a data share. * - * @since 9 - * @sysCap SystemCapability.DistributedDataMgr.DataShare.Provider + * @devices phone, tablet, tv, wearable, car + * @since 8 + * @sysCap AAFwk * @param uri Indicates the path of the file to open. * @param mode Indicates the open mode, which can be "r" for read-only access, "w" for write-only access (erasing * whatever data is currently in the file), "wt" for write access that truncates any existing file, @@ -74,24 +78,26 @@ export default class DataShareExtAbility { * existing data, or "rwt" for read and write access that truncates any existing file. * @return Returns the file descriptor. */ - openFile?(uri: string, mode: string): number; + openFile?(uri: string, mode: string, callback: AsyncCallback): void; /** * Inserts a data record into the database. This method should be implemented by a data share. * - * @since 9 - * @sysCap SystemCapability.DistributedDataMgr.DataShare.Provider + * @devices phone, tablet, tv, wearable, car + * @since 8 + * @sysCap AAFwk * @param uri Indicates the position where the data is to insert. * @param valueBucket Indicates the data to insert. * @return Returns the index of the newly inserted data record. */ - insert?(uri: string, valueBucket: rdb.ValuesBucket): number; + insert?(uri: string, values: rdb.ValuesBucket, callback: AsyncCallback): void; /** * Updates one or more data records in the database. This method should be implemented by a data share. * - * @since 9 - * @sysCap SystemCapability.DistributedDataMgr.DataShare.Provider + * @devices phone, tablet, tv, wearable, car + * @since 8 + * @sysCap AAFwk * @param uri Indicates the database table storing the data to update. * @param valueBucket Indicates the data to update. This parameter can be null. * @param predicates Indicates filter criteria. If this parameter is null, all data records will be updated by @@ -99,25 +105,28 @@ export default class DataShareExtAbility { * @return Returns the number of data records updated. * @return - */ - update?(uri: string, valueBucket: rdb.ValuesBucket, predicates: dataAbility.DataAbilityPredicates): number; + update?(uri: string, values: rdb.ValuesBucket, predicates: dataAbility.DataAbilityPredicates, + callback: AsyncCallback): void; /** * Deletes one or more data records. This method should be implemented by a data share. * - * @since 9 - * @sysCap SystemCapability.DistributedDataMgr.DataShare.Provider + * @devices phone, tablet, tv, wearable, car + * @since 8 + * @sysCap AAFwk * @param uri Indicates the database table storing the data to delete. * @param predicates Indicates filter criteria. If this parameter is null, all data records will be deleted by * default. * @return Returns the number of data records deleted. */ - delete?(uri: string, predicates: dataAbility.DataAbilityPredicates): number; + delete?(uri: string, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback): void; /** * Queries one or more data records in the database. This method should be implemented by a data share. * - * @since 9 - * @sysCap SystemCapability.DistributedDataMgr.DataShare.Provider + * @devices phone, tablet, tv, wearable, car + * @since 8 + * @sysCap AAFwk * @param uri Indicates the database table storing the data to query. * @param columns Indicates the columns to be queried, in array, for example, {"name","age"}. You should define * the processing logic when this parameter is null. @@ -125,54 +134,59 @@ export default class DataShareExtAbility { * default. * @return Returns the queried data. */ - query?(uri: string, columns: Array, predicates: dataAbility.DataAbilityPredicates): ResultSet; + query?(uri: string, columns: Array, predicates: dataAbility.DataAbilityPredicates, + callback: AsyncCallback): void; /** - * Obtains the MIME type matching the data specified by the URI of the data share. This method should be + * Obtains the MIME type matching the data specified by the uri of the data share. This method should be * implemented by a data share. * *

Data abilities supports general data types, including text, HTML, and JPEG.

* - * @since 9 - * @sysCap SystemCapability.DistributedDataMgr.DataShare.Provider + * @devices phone, tablet, tv, wearable, car + * @since 8 + * @sysCap AAFwk * @param uri Indicates the uri of the data. * @return Returns the MIME type that matches the data specified by {@code uri}. */ - getType?(uri: string): string; + getType?(uri: string, callback: AsyncCallback): void; /** * Inserts multiple data records into the database. This method should be implemented by a data share. * - * @since 9 - * @sysCap SystemCapability.DistributedDataMgr.DataShare.Provider + * @devices phone, tablet, tv, wearable, car + * @since 8 + * @sysCap AAFwk * @param uri Indicates the position where the data is to insert. * @param valueBuckets Indicates the data to insert. * @return Returns the number of data records inserted. */ - batchInsert?(uri: string, valueBuckets: Array): number; + batchInsert?(uri: string, values: Array, callback: AsyncCallback): void; /** - * Converts the given {@code uri} that refer to the data share into a normalized URI. A normalized URI can be + * Converts the given {@code uri} that refer to the data share into a normalized uri. A normalized uri can be * used across devices, persisted, backed up, and restored. It can refer to the same item in the data share * even if the context has changed. * - * @since 9 - * @sysCap SystemCapability.DistributedDataMgr.DataShare.Provider + * @devices phone, tablet, tv, wearable, car + * @since 8 + * @sysCap AAFwk * @param uri Indicates the uri to normalize. - * @return Returns the normalized uri if the data share supports URI normalization; + * @return Returns the normalized uri if the data share supports uri normalization; */ - normalizeUri?(uri: string): string; + normalizeUri?(uri: string, callback: AsyncCallback): void; /** * Converts the given normalized {@code uri} generated by {@link #normalizeUri(uri)} into a denormalized one. * The default implementation of this method returns the original uri passed to it. * - * @since 9 - * @sysCap SystemCapability.DistributedDataMgr.DataShare.Provider + * @devices phone, tablet, tv, wearable, car + * @since 8 + * @sysCap AAFwk * @param uri Indicates the uri to denormalize. * @return Returns the denormalized {@code uri} object if the denormalization is successful; returns the original * {@code uri} passed to this method if there is nothing to do; returns {@code null} if the data identified by * the original {@code uri} cannot be found in the current environment. */ - denormalizeUri?(uri: string): string; + denormalizeUri?(uri: string, callback: AsyncCallback): void; } \ No newline at end of file diff --git a/interfaces/kits/js/@ohos.data.dataShare.d.ts b/interfaces/kits/js/@ohos.data.dataShare.d.ts deleted file mode 100644 index 20cf3eb02d747bf9dbfe97e34a945064e86af9f2..0000000000000000000000000000000000000000 --- a/interfaces/kits/js/@ohos.data.dataShare.d.ts +++ /dev/null @@ -1,213 +0,0 @@ -/* -* Copyright (c) 2021 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. -*/ - -import { AsyncCallback, Callback } from './basic'; -import { Want } from './ability/want'; -import Context from './application/Context'; -import { ValuesBucket, ResultSet, DataSharePredicates } from './@ohos.data.rdb'; - -declare namespace dataShare { - /** - * Obtains the dataShareHelper. - * @since 9 - * @sysCap SystemCapability.DistributedDataMgr.DataShare.Consumer - * @param context Indicates the application context. - * @param want Indicates The element parameter of the service ability. - * @param uri Indicates the path of the file to open. - * @return Returns the dataShareHelper. - * @systemapi Hide this for inner system use - */ - function createDataShareHelper(context: Context, want: Want, uri: string): DataShareHelper; - - /** - * DataShareHelper - * @since 9 - * @sysCap SystemCapability.DistributedDataMgr.DataShare.Consumer - * @systemapi Hide this for inner system use - */ - interface DataShareHelper { - /** - * Opens a file in a specified remote path. - * @since 9 - * @sysCap SystemCapability.DistributedDataMgr.DataShare.Consumer - * @param uri Indicates the path of the file to open. - * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access - * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing - * file, "wa" for write-only access to append to any existing data, "rw" for read and write access on - * any existing data, or "rwt" for read and write access that truncates any existing file. - * @param callback Indicates the callback when openfile success - * @systemapi Hide this for inner system use - */ - openFile(uri: string, mode: string, callback: AsyncCallback): void; - openFile(uri: string, mode: string): Promise; - - /** - * Registers an observer to observe data specified by the given uri. - * @since 9 - * @sysCap SystemCapability.DistributedDataMgr.DataShare.Consumer - * @param type dataChange. - * @param uri Indicates the path of the data to operate. - * @param callback Indicates the callback when dataChange. - * @systemapi Hide this for inner system use - */ - on(type: 'dataChange', uri: string, callback: AsyncCallback): void; - - /** - * Deregisters an observer used for monitoring data specified by the given uri. - * @since 9 - * @sysCap SystemCapability.DistributedDataMgr.DataShare.Consumer - * @param type dataChange. - * @param uri Indicates the path of the data to operate. - * @param callback Indicates the registered callback. - * @systemapi Hide this for inner system use - */ - off(type: 'dataChange', uri: string, callback?: AsyncCallback): void; - - /** - * Inserts a single data record into the database. - * @since 9 - * @sysCap SystemCapability.DistributedDataMgr.DataShare.Consumer - * @param uri Indicates the path of the data to operate. - * @param value Indicates the data record to insert. If this parameter is null, a blank row will be inserted. - * @return Returns the index of the inserted data record. - * @systemapi Hide this for inner system use - */ - insert(URI: string, values: ValuesBucket, callback: AsyncCallback): void; - insert(URI: string, values: ValuesBucket): Promise; - - /** - * Deletes one or more data records from the database. - * @since 9 - * @sysCap SystemCapability.DistributedDataMgr.DataShare.Consumer - * @param uri Indicates the path of the data to operate. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * @return Returns the number of data records deleted. - * @systemapi Hide this for inner system use - */ - delete(URI: string, predicates: DataSharePredicates, callback: AsyncCallback): void; - delete(URI: string, predicates: DataSharePredicates): Promise; - - /** - * Queries data in the database. - * @since 9 - * @sysCap SystemCapability.DistributedDataMgr.DataShare.Consumer - * @param uri Indicates the path of data to query. - * @param columns Indicates the columns to query. If this parameter is null, all columns are queried. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * @return Returns the query result. - * @systemapi Hide this for inner system use - */ - query(URI: string, columns: Array, predicates: DataSharePredicates, callback: AsyncCallback): void; - query(URI: string, columns: Array, predicates: DataSharePredicates): Promise; - - /** - * Updates data records in the database. - * @since 9 - * @sysCap SystemCapability.DistributedDataMgr.DataShare.Consumer - * @param uri Indicates the path of data to update. - * @param value Indicates the data to update. This parameter can be null. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * @return Returns the number of data records updated. - * @systemapi Hide this for inner system use - */ - update(URI: string, values: ValuesBucket, predicates: DataSharePredicates, callback: AsyncCallback): void; - update(URI: string, values: ValuesBucket, predicates: DataSharePredicates): Promise; - - /** - * Inserts multiple data records into the database. - * @since 9 - * @sysCap SystemCapability.DistributedDataMgr.DataShare.Consumer - * @param uri Indicates the path of the data to operate. - * @param values Indicates the data records to insert. - * @return Returns the number of data records inserted. - * @systemapi Hide this for inner system use - */ - batchInsert(URI: string, values: Array, callback: AsyncCallback): void; - batchInsert(URI: string, values: Array): Promise; - - /** - * Obtains the MIME type of the date specified by the given URI. - * @since 9 - * @sysCap SystemCapability.DistributedDataMgr.DataShare.Consumer - * @param uri Indicates the path of the data to operate. - * @return Returns the MIME type that matches the data specified by uri. - * @systemapi Hide this for inner system use - */ - getType(URI: string, callback: AsyncCallback): void; - getType(URI: string): Promise; - - /** - * Obtains the MIME types of files supported. - * @since 9 - * @sysCap SystemCapability.DistributedDataMgr.DataShare.Consumer - * @param uri Indicates the path of the files to obtain. - * @param mimeTypeFilter Indicates the MIME types of the files to obtain. This parameter cannot be null. - *

1. "*/*": Obtains all types supported by Data abilities. - *

2. "image/*": Obtains files whose main type is image of any subtype. - *

3. "*/jpg": Obtains files whose subtype is JPG of any main type. - * @return Returns the matched MIME types. If there is no match, {@code null} is returned. - * @systemapi Hide this for inner system use - */ - getFileTypes(uri: string, mimeTypeFilter:string, callback: AsyncCallback>): void; - getFileTypes(uri: string, mimeTypeFilter): Promise>; - - /** - * Converts the given {@code uri} that refers to the Data ability into a normalized {@link ohos.utils.net.Uri}. - * A normalized URI can be used across devices, persisted, backed up, and restored. - *

To transfer a normalized URI from another environment to the current environment, you should call this - * method again to re-normalize the URI for the current environment or call {@link #denormalizeUri(Uri)} - * to convert it to a denormalized URI that can be used only in the current environment. - * @since 9 - * @sysCap SystemCapability.DistributedDataMgr.DataShare.Consumer - * @param uri Indicates the {@link ohos.utils.net.Uri} object to normalize. - * @return Returns the normalized {@code Uri} object if the Data ability supports URI normalization; - * returns {@code null} otherwise. - * @throws DataShareRemoteException Throws this exception if the remote process exits. - * @throws NullPointerException Throws this exception if {@code uri} is null. - * @see #denormalizeUri - * @systemapi Hide this for inner system use - */ - normalizeUri(uri: string, callback: AsyncCallback): void; - normalizeUri(uri: string): Promise; - - /** - * Converts the given normalized {@code uri} generated by {@link #normalizeUri(Uri)} into a denormalized one. - * @since 9 - * @sysCap SystemCapability.DistributedDataMgr.DataShare.Consumer - * @param uri Indicates the {@link ohos.utils.net.Uri} object to denormalize. - * @return Returns the denormalized {@code Uri} object if the denormalization is successful; returns the - * original {@code Uri} passed to this method if there is nothing to do; returns {@code null} if the data - * identified by the normalized {@code Uri} cannot be found in the current environment. - * @throws DataShareRemoteException Throws this exception if the remote process exits. - * @throws NullPointerException Throws this exception if {@code uri} is null. - * @see #normalizeUri - * @systemapi Hide this for inner system use - */ - denormalizeUri(uri: string, callback: AsyncCallback): void; - denormalizeUri(uri: string): Promise; - - /** - * Notifies the registered observers of a change to the data resource specified by Uri. - * @since 9 - * @sysCap SystemCapability.DistributedDataMgr.DataShare.Consumer - * @param uri Indicates the {@link ohos.utils.net.Uri} object to notifyChange. - * @systemapi Hide this for inner system use - */ - notifyChange(URI: string, callback: AsyncCallback): void; - notifyChange(URI: string): Promise; - } -} - -export default dataShare; diff --git a/interfaces/kits/napi/BUILD.gn b/interfaces/kits/napi/BUILD.gn index 355186047787ae6d13201d93436b33a1429c53b8..aff640ffd0f3bc5e2e014181a14f2b1a81491baf 100644 --- a/interfaces/kits/napi/BUILD.gn +++ b/interfaces/kits/napi/BUILD.gn @@ -29,7 +29,6 @@ group("napi_packages") { "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/app/test_runner:testrunner_napi", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/callee:callee_napi", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/caller:caller_napi", - "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/dataShare:datashare", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/dataUriUtils:datauriutils", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/datashare_ext_ability:datashareextability_napi", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/datashare_ext_ability_context:datashareextabilitycontext_napi", diff --git a/interfaces/kits/napi/aafwk/abilityManager/napi_ability_manager.cpp b/interfaces/kits/napi/aafwk/abilityManager/napi_ability_manager.cpp index 6f33960308b7ba5413c6b261cca5cb529a65f775..6517c51b2c4444b7d23d188988b7fdd3f16d1e3a 100644 --- a/interfaces/kits/napi/aafwk/abilityManager/napi_ability_manager.cpp +++ b/interfaces/kits/napi/aafwk/abilityManager/napi_ability_manager.cpp @@ -50,9 +50,6 @@ OHOS::sptr GetAppManagerInstance() napi_value ParseBundleName(napi_env env, std::string &bundleName, napi_value args) { - napi_valuetype valuetype = napi_valuetype::napi_null; - NAPI_CALL(env, napi_typeof(env, args, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); char buf[NapiAbilityMgr::BUFFER_LENGTH_MAX] = {0}; size_t len = 0; napi_get_value_string_utf8(env, args, buf, NapiAbilityMgr::BUFFER_LENGTH_MAX, &len); @@ -1692,6 +1689,9 @@ napi_value NAPI_KillProcessesByBundleName(napi_env env, napi_callback_info info) HILOG_INFO("argc = [%{public}zu]", argc); std::string bundleName = ""; + napi_valuetype valuetype = napi_valuetype::napi_null; + NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); ParseBundleName(env, bundleName, argv[0]); bool callBackMode = false; @@ -1813,6 +1813,9 @@ napi_value NAPI_ClearUpApplicationData(napi_env env, napi_callback_info info) HILOG_INFO("argc = [%{public}zu]", argc); std::string bundleName = ""; + napi_valuetype valuetype = napi_valuetype::napi_null; + NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); ParseBundleName(env, bundleName, argv[0]); bool callBackMode = false; diff --git a/interfaces/kits/napi/aafwk/ability_context/ability_context.js b/interfaces/kits/napi/aafwk/ability_context/ability_context.js index 0be12bee92f9d4b43a49938fa4fe3919594be7a0..c053519cd7c01bddf99987417eef145dd577b4dd 100755 --- a/interfaces/kits/napi/aafwk/ability_context/ability_context.js +++ b/interfaces/kits/napi/aafwk/ability_context/ability_context.js @@ -52,12 +52,12 @@ class AbilityContext extends Context { } } - startAbilityForResult(want, options, callback) { - return this.__context_impl__.startAbilityForResult(want, options, callback) + startAbilityForResult(want, callback) { + return this.__context_impl__.startAbilityForResult(want, callback) } - startAbilityForResultWithAccount(want, accountId, options, callback) { - return this.__context_impl__.startAbilityForResultWithAccount(want, accountId, options, callback) + startAbilityForResultWithAccount(want, accountId, callback) { + return this.__context_impl__.startAbilityForResultWithAccount(want, accountId, callback) } connectAbility(want, options) { diff --git a/interfaces/kits/napi/aafwk/app/app_manager/js_app_manager.cpp b/interfaces/kits/napi/aafwk/app/app_manager/js_app_manager.cpp index 9e864b0619ab41f277fc84869a28be429438f894..66029a291d6d02e7b4b5eceb707e8939deab09f9 100644 --- a/interfaces/kits/napi/aafwk/app/app_manager/js_app_manager.cpp +++ b/interfaces/kits/napi/aafwk/app/app_manager/js_app_manager.cpp @@ -89,6 +89,18 @@ public: return (me != nullptr) ? me->OnKillProcessWithAccount(*engine, *info) : nullptr; } + static NativeValue* KillProcessesByBundleName(NativeEngine* engine, NativeCallbackInfo* info) + { + JsAppManager* me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnkillProcess(*engine, *info) : nullptr; + } + + static NativeValue* ClearUpApplicationData(NativeEngine* engine, NativeCallbackInfo* info) + { + JsAppManager* me = CheckParamsAndGetThis(engine, info); + return (me != nullptr) ? me->OnClearUpApplicationData(*engine, *info) : nullptr; + } + private: sptr appManager_ = nullptr; sptr abilityManager_ = nullptr; @@ -270,6 +282,80 @@ private: return result; } + NativeValue* OnkillProcess(NativeEngine &engine, NativeCallbackInfo &info) + { + HILOG_INFO("%{public}s is called", __FUNCTION__); + if (info.argc == 0) { + HILOG_ERROR("Not enough params"); + return engine.CreateUndefined(); + } + + std::string bundleName; + if (!ConvertFromJsValue(engine, info.argv[0], bundleName)) { + HILOG_ERROR("get bundelName failed!"); + return engine.CreateUndefined(); + } + + HILOG_INFO("kill process [%{public}s]", bundleName.c_str()); + AsyncTask::CompleteCallback complete = [bundleName, abilityManager = abilityManager_](NativeEngine& engine, + AsyncTask& task, int32_t status) { + if (abilityManager == nullptr) { + HILOG_WARN("abilityManager nullptr"); + task.Reject(engine, CreateJsError(engine, ERROR_CODE_ONE, "abilityManager nullptr")); + return; + } + auto errcode = abilityManager->KillProcess(bundleName); + if (errcode == 0) { + task.Resolve(engine, engine.CreateUndefined()); + } else { + task.Reject(engine, CreateJsError(engine, errcode, "kill process failed.")); + } + }; + + NativeValue* lastParam = (info.argc == 1) ? nullptr : info.argv[1]; + NativeValue* result = nullptr; + AsyncTask::Schedule( + engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); + return result; + } + + NativeValue* OnClearUpApplicationData(NativeEngine &engine, NativeCallbackInfo &info) + { + HILOG_INFO("%{public}s is called", __FUNCTION__); + if (info.argc == 0) { + HILOG_ERROR("Not enough params"); + return engine.CreateUndefined(); + } + + std::string bundleName; + if (!ConvertFromJsValue(engine, info.argv[0], bundleName)) { + HILOG_ERROR("get bundelName failed!"); + return engine.CreateUndefined(); + } + + HILOG_INFO("kill process [%{public}s]", bundleName.c_str()); + AsyncTask::CompleteCallback complete = [bundleName, abilityManager = abilityManager_](NativeEngine& engine, + AsyncTask& task, int32_t status) { + if (abilityManager == nullptr) { + HILOG_WARN("abilityManager nullptr"); + task.Reject(engine, CreateJsError(engine, ERROR_CODE_ONE, "abilityManager nullptr")); + return; + } + auto errcode = abilityManager->ClearUpApplicationData(bundleName); + if (errcode == 0) { + task.Resolve(engine, engine.CreateUndefined()); + } else { + task.Reject(engine, CreateJsError(engine, errcode, "clear up application failed.")); + } + }; + + NativeValue* lastParam = (info.argc == 1) ? nullptr : info.argv[1]; + NativeValue* result = nullptr; + AsyncTask::Schedule( + engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); + return result; + } + NativeValue* OnKillProcessWithAccount(NativeEngine &engine, NativeCallbackInfo &info) { HILOG_INFO("%{public}s is called", __FUNCTION__); @@ -359,6 +445,10 @@ NativeValue* JsAppManagerInit(NativeEngine* engine, NativeValue* exportObj) JsAppManager::IsRunningInStabilityTest); BindNativeFunction(*engine, *object, "killProcessWithAccount", JsAppManager::KillProcessWithAccount); + BindNativeFunction(*engine, *object, "killProcessesByBundleName", + JsAppManager::KillProcessesByBundleName); + BindNativeFunction(*engine, *object, "clearUpApplicationData", + JsAppManager::ClearUpApplicationData); HILOG_INFO("JsAppManagerInit end"); return engine->CreateUndefined(); } diff --git a/interfaces/kits/napi/aafwk/dataShare/BUILD.gn b/interfaces/kits/napi/aafwk/dataShare/BUILD.gn deleted file mode 100644 index 2248e600e88809dd8374be7bd7b028e973e65eaf..0000000000000000000000000000000000000000 --- a/interfaces/kits/napi/aafwk/dataShare/BUILD.gn +++ /dev/null @@ -1,69 +0,0 @@ -# Copyright (c) 2021 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. - -import("//build/ohos.gni") - -ohos_shared_library("datashare") { - include_dirs = [ - "//foundation/ace/napi/interfaces/kits", - "//third_party/node/src", - "//third_party/libuv/include", - "//foundation/aafwk/standard/frameworks/kits/ability/native/include", - "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/dataShare", - "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common", - "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/napi_rdb/include", - "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/common/include", - "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/napi_dataability/include", - "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/napi_resultset/include", - ] - - sources = [ - "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/common/src/js_utils.cpp", - "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/napi_dataability/src/napi_data_ability_predicates.cpp", - "//foundation/distributeddatamgr/appdatamgr/frameworks/jskitsimpl/napi_resultset/src/napi_result_set.cpp", - "napi_datashare_helper.cpp", - "native_datashare_module.cpp", - ] - - deps = [ - "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", - "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", - "//foundation/aafwk/standard/interfaces/innerkits/base:base", - "//foundation/aafwk/standard/interfaces/innerkits/dataobs_manager:dataobs_manager", - "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common:napi_common", - "//foundation/ace/napi:ace_napi", - "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", - "//third_party/libuv:uv_static", - "//utils/native/base:utils", - ] - - external_deps = [ - "ability_base:want", - "ability_runtime:ability_manager", - "ability_runtime:app_manager", - "ability_runtime:napi_base_context", - "bundle_framework:appexecfwk_base", - "bundle_framework:appexecfwk_core", - "eventhandler:libeventhandler", - "hiviewdfx_hilog_native:libhilog", - "ipc:ipc_core", - "native_appdatamgr:native_appdatafwk", - "native_appdatamgr:native_dataability", - "native_appdatamgr:native_rdb", - ] - - relative_install_dir = "module/data" - - subsystem_name = "aafwk" - part_name = "ability_runtime" -} diff --git a/interfaces/kits/napi/aafwk/dataShare/data_share_common.h b/interfaces/kits/napi/aafwk/dataShare/data_share_common.h deleted file mode 100644 index b462002faa4063d97b4cdce433f89a989e8dca4f..0000000000000000000000000000000000000000 --- a/interfaces/kits/napi/aafwk/dataShare/data_share_common.h +++ /dev/null @@ -1,360 +0,0 @@ -/* - * Copyright (c) 2022 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. - */ - -#ifndef OHOS_APPEXECFWK_DATASHARE_COMMON_H -#define OHOS_APPEXECFWK_DATASHARE_COMMON_H -#include "ability.h" -#include "abs_shared_result_set.h" -#include "data_ability_predicates.h" -#include "napi/native_api.h" -#include "napi/native_common.h" -#include "napi/native_node_api.h" -#include "napi_common.h" -#include "napi_common_util.h" -#include "values_bucket.h" -#include "want.h" - -using Want = OHOS::AAFwk::Want; -using Ability = OHOS::AppExecFwk::Ability; -using AbilityStartSetting = OHOS::AppExecFwk::AbilityStartSetting; - -namespace OHOS { -namespace AppExecFwk { -struct CallAbilityParam { - Want want; - int requestCode = 0; - bool forResultOption = false; - std::shared_ptr setting = nullptr; -}; - -struct OnAbilityCallback { - int requestCode = 0; - int resultCode = 0; - Want resultData; - CallbackInfo cb; -}; - -struct ContinueAbilityOptionsInfo { - bool reversible = false; - std::string deviceId; -}; - -struct AsyncCallbackInfo { - CallbackInfo cbInfo; - napi_async_work asyncWork = nullptr; - napi_deferred deferred = nullptr; - Ability *ability = nullptr; - CallAbilityParam param; - CallbackInfo aceCallback; - bool native_result; - AbilityType abilityType = AbilityType::UNKNOWN; - int errCode = 0; - ContinueAbilityOptionsInfo optionInfo; -}; - -struct CBBase { - CallbackInfo cbInfo; - napi_async_work asyncWork; - napi_deferred deferred; - Ability *ability = nullptr; - AbilityType abilityType = AbilityType::UNKNOWN; - int errCode = 0; -}; - -struct AppInfo_ { - std::string name; - std::string description; - int32_t descriptionId = 0; - bool systemApp = false; - bool enabled = true; // no data - std::string label; - std::string labelId; - std::string icon; - std::string iconId; - std::string process; - int32_t supportedModes = 0; - std::vector moduleSourceDirs; - std::vector permissions; - std::vector moduleInfos; - std::string entryDir; -}; - -struct AppInfoCB { - CBBase cbBase; - AppInfo_ appInfo; -}; - -struct AppTypeCB { - CBBase cbBase; - std::string name; -}; - -struct AbilityInfo_ { - std::string bundleName; - std::string name; - std::string label; - std::string description; - std::string icon; - int32_t labelId; - int32_t descriptionId; - int32_t iconId; - std::string moduleName; - std::string process; - std::string targetAbility; // no data - int32_t backgroundModes; // no data - bool isVisible = true; - bool formEnabled = false; // no data - int32_t type = 0; - int32_t subType = 0; // no data - int32_t orientation = 0; - int32_t launchMode = 0; - std::vector permissions; - std::vector deviceTypes; - std::vector deviceCapabilities; - std::string readPermission; // no data - std::string writePermission; // no data - AppInfo_ appInfo; - int32_t formEntity; // no data - int32_t minFormHeight; // no data - int32_t defaultFormHeight; // no data - int32_t minFormWidth; // no data - int32_t defaultFormWidth; // no data - std::string uri; -}; -struct AbilityInfoCB { - CBBase cbBase; - AbilityInfo_ abilityInfo; -}; - -struct AbilityNameCB { - CBBase cbBase; - std::string name; -}; - -struct ProcessInfoCB { - CBBase cbBase; - pid_t pid = 0; - std::string processName; -}; - -struct ProcessNameCB { - CBBase cbBase; - std::string processName; -}; - -struct CallingBundleCB { - CBBase cbBase; - std::string callingBundleName; -}; - -struct GetOrCreateLocalDirCB { - CBBase cbBase; - std::string rootDir; -}; - -struct DatabaseDirCB { - CBBase cbBase; - std::string dataBaseDir; -}; - -struct PreferencesDirCB { - CBBase cbBase; - std::string preferencesDir; -}; - -struct ElementNameCB { - CBBase cbBase; - std::string deviceId; - std::string bundleName; - std::string abilityName; - std::string uri; - std::string shortName; -}; - -struct HapModuleInfo_ { - std::string name; - std::string description; - int32_t descriptionId = 0; // no data - std::string icon; - std::string label; - int32_t labelId = 0; // no data - int32_t iconId = 0; // no data - std::string backgroundImg; - int32_t supportedModes = 0; - std::vector reqCapabilities; - std::vector deviceTypes; - std::vector abilityInfos; - std::string moduleName; - std::string mainAbilityName; // no data - bool installationFree; // no data -}; - -struct HapModuleInfoCB { - CBBase cbBase; - HapModuleInfo_ hapModuleInfo; -}; - -struct DataShareHelperCB { - CBBase cbBase; - napi_ref uri = nullptr; - napi_value result = nullptr; -}; - -struct DSHelperInsertCB { - CBBase cbBase; - DataShareHelper *dataShareHelper = nullptr; - std::string uri; - NativeRdb::ValuesBucket valueBucket; - int result = 0; - int execResult; -}; - -class NAPIAbilityConnection; -struct AbilityConnectionCB { - napi_env env; - napi_ref callback[3] = {0}; // onConnect/onDisconnect/onFailed - int resultCode = 0; - ElementName elementName; - sptr connection; -}; -struct ConnectAbilityCB { - CBBase cbBase; - Want want; - sptr abilityConnection; - AbilityConnectionCB abilityConnectionCB; - int64_t id; - bool result; - int errCode = 0; -}; - -struct DSHelperNotifyChangeCB { - CBBase cbBase; - DataShareHelper *dataShareHelper = nullptr; - std::string uri; - int execResult; -}; - -class NAPIDataShareObserver; -struct DSHelperOnOffCB { - CBBase cbBase; - DataShareHelper *dataShareHelper = nullptr; - sptr observer; - std::string uri; - int result = 0; - std::vector NotifyList; - std::vector DestoryList; -}; - -struct ShowOnLockScreenCB { - CBBase cbBase; - bool isShow; -}; - -struct DSHelperGetTypeCB { - CBBase cbBase; - DataShareHelper *dataShareHelper = nullptr; - std::string uri; - std::string result = ""; - int execResult; -}; - -struct DSHelperGetFileTypesCB { - CBBase cbBase; - DataShareHelper *dataShareHelper = nullptr; - std::string uri; - std::string mimeTypeFilter; - std::vector result; - int execResult; -}; - -struct DSHelperNormalizeUriCB { - CBBase cbBase; - DataShareHelper *dataShareHelper = nullptr; - std::string uri; - std::string result = ""; - int execResult; -}; - -struct DSHelperDenormalizeUriCB { - CBBase cbBase; - DataShareHelper *dataShareHelper = nullptr; - std::string uri; - std::string result = ""; - int execResult; -}; - -struct DSHelperDeleteCB { - CBBase cbBase; - DataShareHelper *dataShareHelper = nullptr; - std::string uri; - NativeRdb::DataAbilityPredicates predicates; - int result = 0; - int execResult; -}; - -struct DSHelperQueryCB { - CBBase cbBase; - DataShareHelper *dataShareHelper = nullptr; - std::string uri; - std::vector columns; - NativeRdb::DataAbilityPredicates predicates; - std::shared_ptr result; - int execResult; -}; - -struct DSHelperUpdateCB { - CBBase cbBase; - DataShareHelper *dataShareHelper = nullptr; - std::string uri; - NativeRdb::ValuesBucket valueBucket; - NativeRdb::DataAbilityPredicates predicates; - int result = 0; - int execResult; -}; - -struct DSHelperBatchInsertCB { - CBBase cbBase; - DataShareHelper *dataShareHelper = nullptr; - std::string uri; - std::vector values; - int result = 0; - int execResult; -}; - -struct DSHelperOpenFileCB { - CBBase cbBase; - DataShareHelper *dataShareHelper = nullptr; - std::string uri; - std::string mode; - int result = 0; - int execResult; -}; - -struct DSHelperReleaseCB { - CBBase cbBase; - DataShareHelper *dataShareHelper = nullptr; - bool result = false; -}; - -struct DSHelperExecuteBatchCB { - CBBase cbBase; - std::string uri; - std::vector> operations; - DataShareHelper *dataShareHelper = nullptr; - std::vector> result; -}; -} // namespace AppExecFwk -} // namespace OHOS -#endif /* OHOS_APPEXECFWK_DATASHARE_COMMON_H */ diff --git a/interfaces/kits/napi/aafwk/dataShare/napi_datashare_helper.cpp b/interfaces/kits/napi/aafwk/dataShare/napi_datashare_helper.cpp deleted file mode 100644 index 98c264fbbfa049baa115f9168ef468fd1891ff9a..0000000000000000000000000000000000000000 --- a/interfaces/kits/napi/aafwk/dataShare/napi_datashare_helper.cpp +++ /dev/null @@ -1,3322 +0,0 @@ -/* - * Copyright (c) 2022 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 "napi_datashare_helper.h" - -#include -#include -#include - -#include "datashare_helper.h" -#include "data_ability_observer_interface.h" -#include "uri.h" - -#include "data_ability_result.h" -#include "hilog_wrapper.h" -#include "message_parcel.h" -#include "napi_base_context.h" -#include "napi_data_ability_predicates.h" -#include "napi_rdb_predicates.h" -#include "napi_result_set.h" -#include "securec.h" - -using namespace OHOS::AAFwk; -using namespace OHOS::AppExecFwk; - -namespace OHOS { -namespace AppExecFwk { -namespace { -const std::string DATASHARE_CLASS_NAME = "DataShareHelper"; -constexpr int NO_ERROR = 0; -constexpr int INVALID_PARAMETER = -1; - -std::string NapiValueToStringUtf8(napi_env env, napi_value value) -{ - std::string result = ""; - return UnwrapStringFromJS(env, value, result); -} - -bool NapiValueToArrayStringUtf8(napi_env env, napi_value param, std::vector &result) -{ - return UnwrapArrayStringFromJS(env, param, result); -} -} - -std::list> g_dataShareHelperList; -static napi_ref g_constructorRef = nullptr; - -/** - * @brief acquireDataAbilityHelper processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param dataShareHelperCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value AcquireDataShareHelperWrap(napi_env env, napi_callback_info info, DataShareHelperCB *dataShareHelperCB) -{ - HILOG_INFO("%{public}s,called", __func__); - if (dataShareHelperCB == nullptr) { - HILOG_ERROR("%{public}s,dataShareHelperCB == nullptr", __func__); - return nullptr; - } - - size_t requireArgc = ARGS_THREE; - size_t argc = ARGS_THREE; - napi_value args[ARGS_THREE] = {nullptr}; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr)); - if (argc > requireArgc) { - HILOG_ERROR("%{public}s, Wrong argument count %{public}zu.", __func__, argc); - return nullptr; - } - - napi_value result = nullptr; - napi_value cons = nullptr; - if (napi_get_reference_value(env, g_constructorRef, &cons) != napi_ok) { - return nullptr; - } - NAPI_CALL(env, napi_new_instance(env, cons, ARGS_THREE, args, &result)); - - if (!IsTypeForNapiValue(env, result, napi_object)) { - HILOG_ERROR("%{public}s, IsTypeForNapiValue isn`t object", __func__); - return nullptr; - } - - if (IsTypeForNapiValue(env, result, napi_null)) { - HILOG_ERROR("%{public}s, IsTypeForNapiValue is null", __func__); - return nullptr; - } - - if (IsTypeForNapiValue(env, result, napi_undefined)) { - HILOG_ERROR("%{public}s, IsTypeForNapiValue is undefined", __func__); - return nullptr; - } - - delete dataShareHelperCB; - dataShareHelperCB = nullptr; - HILOG_INFO("%{public}s,end", __func__); - return result; -} - -/** - * @brief AcquireDataAbilityHelper. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_AcquireDataShareHelperCommon(napi_env env, napi_callback_info info, AbilityType abilityType) -{ - HILOG_INFO("%{public}s,called", __func__); - DataShareHelperCB *dataShareHelperCB = new (std::nothrow) DataShareHelperCB; - if (dataShareHelperCB == nullptr) { - HILOG_ERROR("%{public}s, dataShareHelperCB == nullptr", __func__); - return WrapVoidToJS(env); - } - - dataShareHelperCB->cbBase.cbInfo.env = env; - dataShareHelperCB->cbBase.errCode = NAPI_ERR_NO_ERROR; - dataShareHelperCB->cbBase.abilityType = abilityType; - napi_value ret = AcquireDataShareHelperWrap(env, info, dataShareHelperCB); - if (ret == nullptr) { - HILOG_ERROR("%{public}s, ret == nullptr", __func__); - if (dataShareHelperCB != nullptr) { - delete dataShareHelperCB; - dataShareHelperCB = nullptr; - } - ret = WrapVoidToJS(env); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} - -/** - * @brief DataShareHelper NAPI method : CreateDataShareHelper. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_CreateDataShareHelper(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s, called", __func__); - return NAPI_AcquireDataShareHelperCommon(env, info, AbilityType::EXTENSION); -} - -/** - * @brief DataShareHelper NAPI module registration. - * - * @param env The environment that the Node-API call is invoked under. - * @param exports An empty object via the exports parameter as a convenience. - * - * @return The return value from Init is treated as the exports object for the module. - */ -napi_value DataShareHelperInit(napi_env env, napi_value exports) -{ - HILOG_INFO("%{public}s,called", __func__); - napi_property_descriptor properties[] = { - DECLARE_NAPI_FUNCTION("insert", NAPI_Insert), - DECLARE_NAPI_FUNCTION("notifyChange", NAPI_NotifyChange), - DECLARE_NAPI_FUNCTION("on", NAPI_Register), - DECLARE_NAPI_FUNCTION("off", NAPI_UnRegister), - DECLARE_NAPI_FUNCTION("delete", NAPI_Delete), - DECLARE_NAPI_FUNCTION("query", NAPI_Query), - DECLARE_NAPI_FUNCTION("update", NAPI_Update), - DECLARE_NAPI_FUNCTION("batchInsert", NAPI_BatchInsert), - DECLARE_NAPI_FUNCTION("openFile", NAPI_OpenFile), - DECLARE_NAPI_FUNCTION("getType", NAPI_GetType), - DECLARE_NAPI_FUNCTION("getFileTypes", NAPI_GetFileTypes), - DECLARE_NAPI_FUNCTION("normalizeUri", NAPI_NormalizeUri), - DECLARE_NAPI_FUNCTION("denormalizeUri", NAPI_DenormalizeUri), - DECLARE_NAPI_FUNCTION("release", NAPI_Release), - }; - - napi_value cons = nullptr; - NAPI_CALL(env, - napi_define_class(env, - DATASHARE_CLASS_NAME.c_str(), - NAPI_AUTO_LENGTH, - DataShareHelperConstructor, - nullptr, - sizeof(properties) / sizeof(*properties), - properties, - &cons)); - g_dataShareHelperList.clear(); - NAPI_CALL(env, napi_create_reference(env, cons, 1, &g_constructorRef)); - NAPI_CALL(env, napi_set_named_property(env, exports, DATASHARE_CLASS_NAME.c_str(), cons)); - - napi_property_descriptor export_properties[] = { - DECLARE_NAPI_FUNCTION("createDataShareHelper", NAPI_CreateDataShareHelper), - }; - NAPI_CALL(env, napi_define_properties(env, exports, sizeof(export_properties) / sizeof(export_properties[0]), - export_properties)); - return exports; -} - -napi_value DataShareHelperConstructor(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s, called", __func__); - size_t argc = ARGS_THREE; - napi_value argv[ARGS_THREE] = {nullptr}; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr)); - NAPI_ASSERT(env, argc > 0, "Wrong number of arguments"); - AAFwk::Want want; - OHOS::AppExecFwk::UnwrapWant(env, argv[PARAM1], want); - std::string strUri = NapiValueToStringUtf8(env, argv[PARAM2]); - std::shared_ptr dataShareHelper = nullptr; - bool isStageMode = false; - napi_status status = AbilityRuntime::IsStageContext(env, argv[PARAM0], isStageMode); - if (status != napi_ok || !isStageMode) { - auto ability = OHOS::AbilityRuntime::GetCurrentAbility(env); - NAPI_ASSERT(env, ability != nullptr, "DataShareHelperConstructor: failed to get native ability"); - HILOG_INFO("FA Model: ability = %{public}p strUri = %{public}s", ability, strUri.c_str()); - dataShareHelper = DataShareHelper::Creator(ability->GetContext(), want, std::make_shared(strUri)); - } else { - auto context = OHOS::AbilityRuntime::GetStageModeContext(env, argv[PARAM0]); - NAPI_ASSERT(env, context != nullptr, "DataShareHelperConstructor: failed to get native context"); - HILOG_INFO("Stage Model: context = %{public}p strUri = %{public}s", context.get(), strUri.c_str()); - dataShareHelper = DataShareHelper::Creator(context, want, std::make_shared(strUri)); - } - NAPI_ASSERT(env, dataShareHelper != nullptr, "DataShareHelperConstructor: dataShareHelper is nullptr"); - g_dataShareHelperList.emplace_back(dataShareHelper); - napi_wrap(env, thisVar, dataShareHelper.get(), [](napi_env env, void *data, void *hint) { - DataShareHelper *objectInfo = static_cast(data); - auto helper = std::find_if(registerInstances_.begin(), registerInstances_.end(), - [&objectInfo](const DSHelperOnOffCB *helper) { return helper->dataShareHelper == objectInfo; }); - if (helper != registerInstances_.end()) { - HILOG_INFO("DataShareHelper finalize_cb find helper"); - (*helper)->dataShareHelper->Release(); - delete *helper; - registerInstances_.erase(helper); - } - g_dataShareHelperList.remove_if([objectInfo](const std::shared_ptr &dataShareHelper) { - return objectInfo == dataShareHelper.get(); - }); - }, nullptr, nullptr); - HILOG_INFO("%{public}s,called end", __func__); - return thisVar; -} - -/** - * @brief DataShareHelper NAPI method : insert. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_Insert(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s, called", __func__); - DSHelperInsertCB *insertCB = new (std::nothrow) DSHelperInsertCB; - if (insertCB == nullptr) { - HILOG_ERROR("%{public}s, insertCB == nullptr.", __func__); - return WrapVoidToJS(env); - } - insertCB->cbBase.cbInfo.env = env; - insertCB->cbBase.asyncWork = nullptr; - insertCB->cbBase.deferred = nullptr; - insertCB->cbBase.ability = nullptr; - - napi_value ret = InsertWrap(env, info, insertCB); - if (ret == nullptr) { - HILOG_ERROR("%{public}s, ret == nullptr.", __func__); - if (insertCB != nullptr) { - delete insertCB; - insertCB = nullptr; - } - ret = WrapVoidToJS(env); - } - HILOG_INFO("%{public}s,called end", __func__); - return ret; -} - -/** - * @brief Insert processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param insertCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value InsertWrap(napi_env env, napi_callback_info info, DSHelperInsertCB *insertCB) -{ - HILOG_INFO("%{public}s,called", __func__); - size_t argcAsync = ARGS_THREE; - const size_t argcPromise = ARGS_TWO; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = 0; - napi_value thisVar = nullptr; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); - if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); - if (valuetype == napi_string) { - insertCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); - HILOG_INFO("%{public}s,uri=%{public}s", __func__, insertCB->uri.c_str()); - } else { - HILOG_ERROR("%{public}s, Wrong argument type.", __func__); - } - - insertCB->valueBucket.Clear(); - AnalysisValuesBucket(insertCB->valueBucket, env, args[PARAM1]); - - DataShareHelper *objectInfo = nullptr; - napi_unwrap(env, thisVar, (void **)&objectInfo); - HILOG_INFO("%{public}s,DataShareHelper objectInfo = %{public}p", __func__, objectInfo); - insertCB->dataShareHelper = objectInfo; - - if (argcAsync > argcPromise) { - ret = InsertAsync(env, args, ARGS_TWO, insertCB); - } else { - ret = InsertPromise(env, insertCB); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} - -void AnalysisValuesBucket(NativeRdb::ValuesBucket &valuesBucket, const napi_env &env, const napi_value &arg) -{ - napi_value keys = 0; - napi_get_property_names(env, arg, &keys); - uint32_t arrLen = 0; - napi_status status = napi_get_array_length(env, keys, &arrLen); - if (status != napi_ok) { - HILOG_ERROR("ValuesBucket errr"); - return; - } - HILOG_INFO("ValuesBucket num:%{public}d ", arrLen); - for (size_t i = 0; i < arrLen; ++i) { - napi_value key = 0; - status = napi_get_element(env, keys, i, &key); - std::string keyStr = UnwrapStringFromJS(env, key); - napi_value value = 0; - napi_get_property(env, arg, key, &value); - - SetValuesBucketObject(valuesBucket, env, keyStr, value); - } -} - -void SetValuesBucketObject( - NativeRdb::ValuesBucket &valuesBucket, const napi_env &env, std::string keyStr, napi_value value) -{ - napi_valuetype valueType = napi_undefined; - napi_typeof(env, value, &valueType); - if (valueType == napi_string) { - std::string valueString = UnwrapStringFromJS(env, value); - HILOG_INFO("ValueObject type:%{public}d, key:%{public}s, value:%{public}s", - valueType, - keyStr.c_str(), - valueString.c_str()); - valuesBucket.PutString(keyStr, valueString); - } else if (valueType == napi_number) { - double valueNumber = 0; - napi_get_value_double(env, value, &valueNumber); - valuesBucket.PutDouble(keyStr, valueNumber); - HILOG_INFO( - "ValueObject type:%{public}d, key:%{public}s, value:%{public}lf", valueType, keyStr.c_str(), valueNumber); - } else if (valueType == napi_boolean) { - bool valueBool = false; - napi_get_value_bool(env, value, &valueBool); - HILOG_INFO( - "ValueObject type:%{public}d, key:%{public}s, value:%{public}d", valueType, keyStr.c_str(), valueBool); - valuesBucket.PutBool(keyStr, valueBool); - } else if (valueType == napi_null) { - valuesBucket.PutNull(keyStr); - HILOG_INFO("ValueObject type:%{public}d, key:%{public}s, value:null", valueType, keyStr.c_str()); - } else if (valueType == napi_object) { - HILOG_INFO("ValueObject type:%{public}d, key:%{public}s, value:Uint8Array", valueType, keyStr.c_str()); - valuesBucket.PutBlob(keyStr, ConvertU8Vector(env, value)); - } else { - HILOG_ERROR("valuesBucket error"); - } -} -napi_value InsertAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperInsertCB *insertCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || insertCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = 0; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); - if (valuetype == napi_function) { - NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &insertCB->cbBase.cbInfo.callback)); - } - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - InsertExecuteCB, - InsertAsyncCompleteCB, - (void *)insertCB, - &insertCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, insertCB->cbBase.asyncWork)); - napi_value result = 0; - NAPI_CALL(env, napi_get_null(env, &result)); - HILOG_INFO("%{public}s, asyncCallback end", __func__); - return result; -} - -napi_value InsertPromise(napi_env env, DSHelperInsertCB *insertCB) -{ - HILOG_INFO("%{public}s, promise.", __func__); - if (insertCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - napi_deferred deferred; - napi_value promise = 0; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - insertCB->cbBase.deferred = deferred; - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - InsertExecuteCB, - InsertPromiseCompleteCB, - (void *)insertCB, - &insertCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, insertCB->cbBase.asyncWork)); - HILOG_INFO("%{public}s, promise end", __func__); - return promise; -} - -void InsertExecuteCB(napi_env env, void *data) -{ - HILOG_INFO("NAPI_Insert, worker pool thread execute."); - DSHelperInsertCB *insertCB = static_cast(data); - if (insertCB->dataShareHelper != nullptr) { - insertCB->execResult = INVALID_PARAMETER; - if (!insertCB->uri.empty()) { - OHOS::Uri uri(insertCB->uri); - insertCB->result = insertCB->dataShareHelper->Insert(uri, insertCB->valueBucket); - insertCB->execResult = NO_ERROR; - } - } else { - HILOG_ERROR("NAPI_Insert, dataShareHelper == nullptr."); - } - HILOG_INFO("NAPI_Insert, worker pool thread execute end."); -} - -void InsertAsyncCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_Insert, main event thread complete."); - DSHelperInsertCB *insertCB = static_cast(data); - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value result[ARGS_TWO] = {nullptr}; - napi_value callResult = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, insertCB->cbBase.cbInfo.callback, &callback)); - - result[PARAM0] = GetCallbackErrorValue(env, insertCB->execResult); - napi_create_int32(env, insertCB->result, &result[PARAM1]); - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); - - if (insertCB->cbBase.cbInfo.callback != nullptr) { - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, insertCB->cbBase.cbInfo.callback)); - } - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, insertCB->cbBase.asyncWork)); - delete insertCB; - insertCB = nullptr; - HILOG_INFO("NAPI_Insert, main event thread complete end."); -} - -void InsertPromiseCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_Insert, main event thread complete."); - DSHelperInsertCB *insertCB = static_cast(data); - napi_value result = nullptr; - napi_create_int32(env, insertCB->result, &result); - NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, insertCB->cbBase.deferred, result)); - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, insertCB->cbBase.asyncWork)); - delete insertCB; - insertCB = nullptr; - HILOG_INFO("NAPI_Insert, main event thread complete end."); -} - -/** - * @brief Parse the ValuesBucket parameters. - * - * @param param Indicates the want parameters saved the parse result. - * @param env The environment that the Node-API call is invoked under. - * @param args Indicates the arguments passed into the callback. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value UnwrapValuesBucket(std::string &value, napi_env env, napi_value args) -{ - HILOG_INFO("%{public}s,called", __func__); - napi_valuetype valueType = napi_undefined; - napi_typeof(env, args, &valueType); - if (valueType != napi_object) { - HILOG_ERROR("%{public}s, valueType != napi_object.", __func__); - return nullptr; - } - - std::string strValue = ""; - if (UnwrapStringByPropertyName(env, args, "value", strValue)) { - HILOG_INFO("%{public}s,strValue=%{public}s", __func__, strValue.c_str()); - value = strValue; - } else { - HILOG_ERROR("%{public}s, value == nullptr.", __func__); - return nullptr; - } - - napi_value result; - NAPI_CALL(env, napi_create_int32(env, 1, &result)); - HILOG_INFO("%{public}s,end", __func__); - return result; -} - -/** - * @brief DataShareHelper NAPI method : notifyChange. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_NotifyChange(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s,called", __func__); - DSHelperNotifyChangeCB *notifyChangeCB = new (std::nothrow) DSHelperNotifyChangeCB; - if (notifyChangeCB == nullptr) { - HILOG_ERROR("%{public}s, notifyChangeCB == nullptr.", __func__); - return WrapVoidToJS(env); - } - notifyChangeCB->cbBase.cbInfo.env = env; - notifyChangeCB->cbBase.asyncWork = nullptr; - notifyChangeCB->cbBase.deferred = nullptr; - notifyChangeCB->cbBase.ability = nullptr; - - napi_value ret = NotifyChangeWrap(env, info, notifyChangeCB); - if (ret == nullptr) { - HILOG_ERROR("%{public}s, ret == nullptr.", __func__); - if (notifyChangeCB != nullptr) { - delete notifyChangeCB; - notifyChangeCB = nullptr; - } - ret = WrapVoidToJS(env); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} - -/** - * @brief NotifyChange processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param notifyChangeCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value NotifyChangeWrap(napi_env env, napi_callback_info info, DSHelperNotifyChangeCB *notifyChangeCB) -{ - HILOG_INFO("%{public}s,called", __func__); - size_t argcAsync = ARGS_TWO; - const size_t argcPromise = ARGS_ONE; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = 0; - napi_value thisVar = nullptr; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); - if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); - if (valuetype == napi_string) { - notifyChangeCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); - HILOG_INFO("%{public}s,uri=%{public}s", __func__, notifyChangeCB->uri.c_str()); - } else { - HILOG_ERROR("%{public}s, Wrong argument type.", __func__); - } - - DataShareHelper *objectInfo = nullptr; - napi_unwrap(env, thisVar, (void **)&objectInfo); - HILOG_INFO("DataShareHelper objectInfo = %{public}p", objectInfo); - notifyChangeCB->dataShareHelper = objectInfo; - - if (argcAsync > argcPromise) { - ret = NotifyChangeAsync(env, args, argcAsync, argcPromise, notifyChangeCB); - } else { - ret = NotifyChangePromise(env, notifyChangeCB); - } - return ret; -} - -napi_value NotifyChangeAsync( - napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DSHelperNotifyChangeCB *notifyChangeCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || notifyChangeCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = 0; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); - if (valuetype == napi_function) { - NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, ¬ifyChangeCB->cbBase.cbInfo.callback)); - } - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - NotifyChangeExecuteCB, - NotifyChangeAsyncCompleteCB, - (void *)notifyChangeCB, - ¬ifyChangeCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, notifyChangeCB->cbBase.asyncWork)); - napi_value result = 0; - NAPI_CALL(env, napi_get_null(env, &result)); - return result; -} - -napi_value NotifyChangePromise(napi_env env, DSHelperNotifyChangeCB *notifyChangeCB) -{ - HILOG_INFO("%{public}s, promise.", __func__); - if (notifyChangeCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - napi_deferred deferred; - napi_value promise = 0; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - notifyChangeCB->cbBase.deferred = deferred; - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - NotifyChangeExecuteCB, - NotifyChangePromiseCompleteCB, - (void *)notifyChangeCB, - ¬ifyChangeCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, notifyChangeCB->cbBase.asyncWork)); - return promise; -} - -void NotifyChangeExecuteCB(napi_env env, void *data) -{ - HILOG_INFO("NAPI_NotifyChange, worker pool thread execute."); - DSHelperNotifyChangeCB *notifyChangeCB = static_cast(data); - if (notifyChangeCB->dataShareHelper != nullptr) { - notifyChangeCB->execResult = INVALID_PARAMETER; - if (!notifyChangeCB->uri.empty()) { - OHOS::Uri uri(notifyChangeCB->uri); - notifyChangeCB->dataShareHelper->NotifyChange(uri); - notifyChangeCB->execResult = NO_ERROR; - } else { - HILOG_ERROR("%{public}s, notifyChangeCB uri is empty.", __func__); - } - } -} - -void NotifyChangeAsyncCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_NotifyChange, main event thread complete."); - DSHelperNotifyChangeCB *notifyChangeCB = static_cast(data); - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value result[ARGS_TWO] = {nullptr}; - napi_value callResult = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, notifyChangeCB->cbBase.cbInfo.callback, &callback)); - - if (!IsTypeForNapiValue(env, callback, napi_function)) { - delete notifyChangeCB; - notifyChangeCB = nullptr; - HILOG_INFO("NAPI_NotifyChange, callback is invalid."); - return; - } - - result[PARAM0] = GetCallbackErrorValue(env, notifyChangeCB->execResult); - result[PARAM1] = WrapVoidToJS(env); - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); - - if (notifyChangeCB->cbBase.cbInfo.callback != nullptr) { - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, notifyChangeCB->cbBase.cbInfo.callback)); - } - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, notifyChangeCB->cbBase.asyncWork)); - delete notifyChangeCB; - notifyChangeCB = nullptr; -} - -void NotifyChangePromiseCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_NotifyChange, main event thread complete."); - DSHelperNotifyChangeCB *notifyChangeCB = static_cast(data); - napi_value result = nullptr; - napi_create_int32(env, 0, &result); - NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, notifyChangeCB->cbBase.deferred, result)); - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, notifyChangeCB->cbBase.asyncWork)); - delete notifyChangeCB; - notifyChangeCB = nullptr; -} - -/** - * @brief DataShareHelper NAPI method : on. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_Register(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s,called", __func__); - DSHelperOnOffCB *onCB = new (std::nothrow) DSHelperOnOffCB; - if (onCB == nullptr) { - HILOG_ERROR("%{public}s, onCB == nullptr.", __func__); - return WrapVoidToJS(env); - } - onCB->cbBase.cbInfo.env = env; - onCB->cbBase.asyncWork = nullptr; - onCB->cbBase.deferred = nullptr; - onCB->cbBase.ability = nullptr; - - napi_value ret = RegisterWrap(env, info, onCB); - if (ret == nullptr) { - HILOG_ERROR("%{public}s, ret == nullptr.", __func__); - if (onCB != nullptr) { - delete onCB; - onCB = nullptr; - } - ret = WrapVoidToJS(env); - } - HILOG_INFO("%{public}s,called end", __func__); - return ret; -} - -/** - * @brief On processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param insertCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value RegisterWrap(napi_env env, napi_callback_info info, DSHelperOnOffCB *onCB) -{ - HILOG_INFO("%{public}s,called", __func__); - size_t argcAsync = ARGS_THREE; - const size_t argcPromise = ARGS_TWO; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = 0; - napi_value thisVar = nullptr; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); - if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - onCB->result = NO_ERROR; - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); - if (valuetype == napi_string) { - std::string type = NapiValueToStringUtf8(env, args[PARAM0]); - if (type == "dataChange") { - HILOG_INFO("%{public}s, Wrong type=%{public}s", __func__, type.c_str()); - } else { - HILOG_ERROR("%{public}s, Wrong argument type is %{public}s.", __func__, type.c_str()); - onCB->result = INVALID_PARAMETER; - } - } else { - HILOG_ERROR("%{public}s, Wrong argument type.", __func__); - onCB->result = INVALID_PARAMETER; - } - - NAPI_CALL(env, napi_typeof(env, args[PARAM1], &valuetype)); - if (valuetype == napi_string) { - onCB->uri = NapiValueToStringUtf8(env, args[PARAM1]); - HILOG_INFO("%{public}s,uri=%{public}s", __func__, onCB->uri.c_str()); - } else { - HILOG_ERROR("%{public}s, Wrong argument type.", __func__); - onCB->result = INVALID_PARAMETER; - } - - DataShareHelper *objectInfo = nullptr; - napi_unwrap(env, thisVar, (void **)&objectInfo); - HILOG_INFO("DataShareHelper objectInfo = %{public}p", objectInfo); - onCB->dataShareHelper = objectInfo; - - ret = RegisterAsync(env, args, argcAsync, argcPromise, onCB); - return ret; -} - -napi_value RegisterAsync( - napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DSHelperOnOffCB *onCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || onCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = 0; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[argcPromise], &valuetype)); - if (valuetype == napi_function) { - HILOG_INFO("valuetype is napi_function"); - NAPI_CALL(env, napi_create_reference(env, args[argcPromise], 1, &onCB->cbBase.cbInfo.callback)); - } else { - HILOG_INFO("not valuetype isn't napi_function"); - onCB->result = INVALID_PARAMETER; - } - - sptr observer(new (std::nothrow) NAPIDataShareObserver()); - observer->SetEnv(env); - observer->SetCallbackRef(onCB->cbBase.cbInfo.callback); - onCB->observer = observer; - - if (onCB->result == NO_ERROR) { - registerInstances_.emplace_back(onCB); - } - - NAPI_CALL(env, - napi_create_async_work( - env, - nullptr, - resourceName, - RegisterExecuteCB, - RegisterCompleteCB, - (void *)onCB, - &onCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, onCB->cbBase.asyncWork)); - napi_value result = 0; - NAPI_CALL(env, napi_get_null(env, &result)); - return result; -} - -void RegisterExecuteCB(napi_env env, void *data) -{ - HILOG_INFO("NAPI_Register, worker pool thread execute."); - DSHelperOnOffCB *onCB = static_cast(data); - if (onCB->dataShareHelper != nullptr) { - if (onCB->result != INVALID_PARAMETER && !onCB->uri.empty() && onCB->cbBase.cbInfo.callback != nullptr) { - OHOS::Uri uri(onCB->uri); - onCB->dataShareHelper->RegisterObserver(uri, onCB->observer); - } else { - HILOG_ERROR("%{public}s, dataShareHelper uri is empty or callback is nullptr.", __func__); - } - } -} - -void RegisterCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_Register, main event thread complete."); - DSHelperOnOffCB *onCB = static_cast(data); - if (onCB == nullptr) { - HILOG_ERROR("%{public}s, input params onCB is nullptr.", __func__); - return; - } - if (onCB->result == NO_ERROR) { - return; - } - HILOG_INFO("NAPI_Register, input params onCB is invalid params, will be release"); - onCB->observer->ReleaseJSCallback(); - delete onCB; - onCB = nullptr; - HILOG_INFO("NAPI_Register, main event thread complete over an release invalid onCB."); -} - -/** - * @brief DataShareHelper NAPI method : Off. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_UnRegister(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s,called", __func__); - DSHelperOnOffCB *offCB = new (std::nothrow) DSHelperOnOffCB; - if (offCB == nullptr) { - HILOG_ERROR("%{public}s, offCB == nullptr.", __func__); - return WrapVoidToJS(env); - } - offCB->cbBase.cbInfo.env = env; - offCB->cbBase.asyncWork = nullptr; - offCB->cbBase.deferred = nullptr; - offCB->cbBase.ability = nullptr; - - napi_value ret = UnRegisterWrap(env, info, offCB); - if (ret == nullptr) { - HILOG_ERROR("%{public}s, ret == nullptr.", __func__); - if (offCB != nullptr) { - delete offCB; - offCB = nullptr; - } - ret = WrapVoidToJS(env); - } - HILOG_INFO("%{public}s,called end", __func__); - return ret; -} - -/** - * @brief Off processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param insertCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value UnRegisterWrap(napi_env env, napi_callback_info info, DSHelperOnOffCB *offCB) -{ - HILOG_INFO("%{public}s,called", __func__); - size_t argc = ARGS_THREE; - const size_t argcPromise = ARGS_TWO; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = 0; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &thisVar, nullptr)); - NAPI_ASSERT(env, argc <= argCountWithAsync && argc <= ARGS_MAX_COUNT, "UnRegisterWrap: Wrong argument count"); - offCB->result = INVALID_PARAMETER; - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); - if (valuetype == napi_string) { - std::string type = NapiValueToStringUtf8(env, args[PARAM0]); - if (type == "dataChange") { - offCB->result = NO_ERROR; - } - } - offCB->uri = ""; - if (argc > ARGS_TWO) { - NAPI_CALL(env, napi_typeof(env, args[PARAM1], &valuetype)); - if (valuetype == napi_string) { - offCB->uri = NapiValueToStringUtf8(env, args[PARAM1]); - } else { - offCB->result = INVALID_PARAMETER; - } - NAPI_CALL(env, napi_typeof(env, args[PARAM2], &valuetype)); - if (valuetype == napi_function) { - NAPI_CALL(env, napi_create_reference(env, args[PARAM2], 1, &offCB->cbBase.cbInfo.callback)); - } else { - offCB->result = INVALID_PARAMETER; - } - } else { - NAPI_CALL(env, napi_typeof(env, args[PARAM1], &valuetype)); - if (valuetype == napi_string) { - offCB->uri = NapiValueToStringUtf8(env, args[PARAM1]); - } else if (valuetype == napi_function) { - NAPI_CALL(env, napi_create_reference(env, args[PARAM1], 1, &offCB->cbBase.cbInfo.callback)); - } else { - offCB->result = INVALID_PARAMETER; - } - } - HILOG_INFO("%{public}s,uri=%{public}s", __func__, offCB->uri.c_str()); - DataShareHelper *objectInfo = nullptr; - napi_unwrap(env, thisVar, (void **)&objectInfo); - offCB->dataShareHelper = objectInfo; - ret = UnRegisterAsync(env, args, argc, argcPromise, offCB); - return ret; -} - -napi_value UnRegisterAsync( - napi_env env, napi_value *args, size_t argc, const size_t argcPromise, DSHelperOnOffCB *offCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || offCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = 0; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - - if (offCB->result == NO_ERROR) { - FindRegisterObs(env, offCB); - } - - NAPI_CALL(env, - napi_create_async_work( - env, - nullptr, - resourceName, - UnRegisterExecuteCB, - UnRegisterCompleteCB, - (void *)offCB, - &offCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, offCB->cbBase.asyncWork)); - napi_value result = 0; - NAPI_CALL(env, napi_get_null(env, &result)); - return result; -} - -static void FindRegisterObsByCallBack(napi_env env, DSHelperOnOffCB *data) -{ - HILOG_INFO("NAPI_UnRegister, UnRegisterExecuteCB callback is not null."); - if (data == nullptr || data->dataShareHelper == nullptr) { - HILOG_ERROR("NAPI_UnRegister, param is null."); - return; - } - napi_value callbackA = 0; - napi_get_reference_value(data->cbBase.cbInfo.env, data->cbBase.cbInfo.callback, &callbackA); - std::string strUri = data->uri; - do { - auto helper = std::find_if( - registerInstances_.begin(), - registerInstances_.end(), - [callbackA, strUri](const DSHelperOnOffCB *helper) { - bool result = false; - if (helper == nullptr || helper->cbBase.cbInfo.callback == nullptr) { - HILOG_ERROR("%{public}s is nullptr", ((helper == nullptr) ? "helper" : "cbBase.cbInfo.callback")); - return result; - } - if (helper->uri != strUri) { - HILOG_ERROR("uri inconsistent, h=[%{public}s] u=[%{public}s]", helper->uri.c_str(), strUri.c_str()); - return result; - } - napi_value callbackB = 0; - napi_get_reference_value(helper->cbBase.cbInfo.env, helper->cbBase.cbInfo.callback, &callbackB); - auto ret = napi_strict_equals(helper->cbBase.cbInfo.env, callbackA, callbackB, &result); - HILOG_INFO("NAPI_UnRegister cb equals status=%{public}d result=%{public}d.", ret, result); - return result; - }); - if (helper != registerInstances_.end()) { - data->NotifyList.emplace_back(*helper); - registerInstances_.erase(helper); - HILOG_INFO("NAPI_UnRegister Instances erase size = %{public}zu", registerInstances_.size()); - } else { - HILOG_INFO("NAPI_UnRegister not match any callback. %{public}zu", registerInstances_.size()); - break; - } - } while (true); - HILOG_INFO("NAPI_UnRegister, UnRegisterExecuteCB FindRegisterObsByCallBack Called End."); -} - -void FindRegisterObs(napi_env env, DSHelperOnOffCB *data) -{ - HILOG_INFO("NAPI_UnRegister, FindRegisterObs main event thread execute."); - if (data == nullptr || data->dataShareHelper == nullptr) { - HILOG_ERROR("NAPI_UnRegister, param is null."); - return; - } - if (data->cbBase.cbInfo.callback != nullptr) { - HILOG_INFO("NAPI_UnRegister, UnRegisterExecuteCB callback is not null."); - FindRegisterObsByCallBack(env, data); - } else { - if (data->uri.empty()) { - HILOG_ERROR("NAPI_UnRegister, error: uri is empty."); - return; - } - - HILOG_INFO("NAPI_UnRegister, uri=%{public}s.", data->uri.c_str()); - std::string strUri = data->uri; - do { - auto helper = std::find_if(registerInstances_.begin(), registerInstances_.end(), - [strUri](const DSHelperOnOffCB *helper) { return helper->uri == strUri; }); - if (helper != registerInstances_.end()) { - OHOS::Uri uri((*helper)->uri); - data->NotifyList.emplace_back(*helper); - registerInstances_.erase(helper); - HILOG_INFO("NAPI_UnRegister Instances erase size = %{public}zu", registerInstances_.size()); - } else { - HILOG_INFO("NAPI_UnRegister not match any uri."); - break; - } - } while (true); - } - HILOG_INFO("NAPI_UnRegister, FindRegisterObs main event thread execute.end %{public}zu", data->NotifyList.size()); -} - -void UnRegisterExecuteCB(napi_env env, void *data) -{ - HILOG_INFO("NAPI_UnRegister, UnRegisterExecuteCB main event thread execute."); - DSHelperOnOffCB *offCB = static_cast(data); - if (offCB == nullptr || offCB->dataShareHelper == nullptr) { - HILOG_ERROR("NAPI_UnRegister, param is null."); - if (offCB != nullptr) { - delete offCB; - offCB = nullptr; - } - return; - } - HILOG_INFO("NAPI_UnRegister, offCB->DestoryList size is %{public}zu", offCB->NotifyList.size()); - for (auto &iter : offCB->NotifyList) { - if (iter != nullptr && iter->observer != nullptr) { - OHOS::Uri uri(iter->uri); - iter->dataShareHelper->UnregisterObserver(uri, iter->observer); - offCB->DestoryList.emplace_back(iter); - } - } - offCB->NotifyList.clear(); - HILOG_INFO("NAPI_UnRegister, UnRegisterExecuteCB main event thread execute. end"); -} - -void UnRegisterCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_UnRegister, main event thread complete."); - // cannot run it in executeCB, because need to use napi_strict_equals compare callbacks. - DSHelperOnOffCB *offCB = static_cast(data); - if (offCB == nullptr || offCB->dataShareHelper == nullptr) { - HILOG_ERROR("NAPI_UnRegister, param is null."); - if (offCB != nullptr) { - delete offCB; - offCB = nullptr; - } - return; - } - HILOG_INFO("NAPI_UnRegister, offCB->DestoryList size is %{public}zu", offCB->DestoryList.size()); - for (auto &iter : offCB->DestoryList) { - HILOG_INFO("NAPI_UnRegister ReleaseJSCallback. 1 ---"); - if (iter->observer != nullptr) { - if (iter->observer->GetWorkPre() == 1 && iter->observer->GetWorkRun() == 0) { - iter->observer->SetAssociatedObject(iter); - iter->observer->ChangeWorkInt(); - HILOG_INFO("NAPI_UnRegister ReleaseJSCallback. 3 ---"); - } else { - iter->observer->ReleaseJSCallback(); - delete iter; - iter = nullptr; - HILOG_INFO("NAPI_UnRegister ReleaseJSCallback. 4 ---"); - } - } - } - - offCB->DestoryList.clear(); - if (offCB != nullptr) { - delete offCB; - offCB = nullptr; - } - - HILOG_INFO("NAPI_UnRegister, main event thread complete. end"); -} - -void NAPIDataShareObserver::ReleaseJSCallback() -{ - if (ref_ == nullptr) { - HILOG_ERROR("NAPIDataShareObserver::ReleaseJSCallback, ref_ is null."); - return; - } - napi_delete_reference(env_, ref_); - HILOG_INFO("NAPIDataShareObserver::%{public}s, called. end", __func__); -} - -void NAPIDataShareObserver::SetAssociatedObject(DSHelperOnOffCB* object) -{ - onCB_ = object; - HILOG_INFO("NAPIDataShareObserver::%{public}s, called. end", __func__); -} - -void NAPIDataShareObserver::ChangeWorkPre() -{ - HILOG_INFO("NAPIDataShareObserver::%{public}s, called.", __func__); - std::lock_guard lock_l(mutex_); - workPre_ = 1; - HILOG_INFO("NAPIDataShareObserver::%{public}s, called. end %{public}d", __func__, workPre_); -} -void NAPIDataShareObserver::ChangeWorkRun() -{ - workRun_ = 1; - HILOG_INFO("NAPIDataShareObserver::%{public}s, called. end %{public}d", __func__, workRun_); -} -void NAPIDataShareObserver::ChangeWorkInt() -{ - intrust_ = 1; - HILOG_INFO("NAPIDataShareObserver::%{public}s, called. end %{public}d", __func__, intrust_); -} - -void NAPIDataShareObserver::ChangeWorkPreDone() -{ - HILOG_INFO("NAPIDataShareObserver::%{public}s, called.", __func__); - std::lock_guard lock_l(mutex_); - workPre_ = 0; - HILOG_INFO("NAPIDataShareObserver::%{public}s, called. end %{public}d", __func__, workPre_); -} - -void NAPIDataShareObserver::ChangeWorkRunDone() -{ - workRun_ = 0; - intrust_ = 0; - HILOG_INFO("NAPIDataShareObserver::%{public}s, called end %{public}d %{public}d", __func__, workRun_, intrust_); -} - -int NAPIDataShareObserver::GetWorkPre() -{ - HILOG_INFO("NAPIDataShareObserver::%{public}s, called.", __func__); - std::lock_guard lock_l(mutex_); - HILOG_INFO("NAPIDataShareObserver::%{public}s, called. end %{public}d", __func__, workPre_); - return workPre_; -} - -int NAPIDataShareObserver::GetWorkInt() -{ - HILOG_INFO("NAPIDataShareObserver::%{public}s, called. end %{public}d", __func__, intrust_); - return intrust_; -} - -int NAPIDataShareObserver::GetWorkRun() -{ - HILOG_INFO("NAPIDataShareObserver::%{public}s, called. %{public}d", __func__, workRun_); - return workRun_; -} - -const DSHelperOnOffCB* NAPIDataShareObserver::GetAssociatedObject(void) -{ - HILOG_INFO("NAPIDataShareObserver::%{public}s, called.", __func__); - return onCB_; -} - -void NAPIDataShareObserver::SetEnv(const napi_env &env) -{ - env_ = env; - HILOG_INFO("NAPIDataShareObserver::%{public}s, called. end", __func__); -} - -void NAPIDataShareObserver::SetCallbackRef(const napi_ref &ref) -{ - ref_ = ref; - HILOG_INFO("NAPIDataShareObserver::%{public}s, called. end", __func__); -} - -static void OnChangeJSThreadWorker(uv_work_t *work, int status) -{ - HILOG_INFO("OnChange, uv_queue_work"); - if (work == nullptr) { - HILOG_ERROR("OnChange, uv_queue_work input work is nullptr"); - return; - } - DSHelperOnOffCB *onCB = (DSHelperOnOffCB *)work->data; - NAPIDataShareObserver* obs = onCB->observer; - onCB->observer = nullptr; - if (obs != nullptr) { - obs->ChangeWorkRun(); - } - napi_value result[ARGS_TWO] = {0}; - result[PARAM0] = GetCallbackErrorValue(onCB->cbBase.cbInfo.env, NO_ERROR); - napi_value callback = 0; - napi_value undefined = 0; - napi_get_undefined(onCB->cbBase.cbInfo.env, &undefined); - napi_value callResult = 0; - napi_get_reference_value(onCB->cbBase.cbInfo.env, onCB->cbBase.cbInfo.callback, &callback); - napi_call_function(onCB->cbBase.cbInfo.env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult); - if (obs != nullptr) { - if (obs->GetWorkInt() == 1) { - obs->ReleaseJSCallback(); - const DSHelperOnOffCB* assicuated = obs->GetAssociatedObject(); - if (assicuated != nullptr) { - HILOG_INFO("OnChange, uv_queue_work ReleaseJSCallback Called"); - obs->SetAssociatedObject(nullptr); - delete assicuated; - assicuated = nullptr; - } - } else { - obs->ChangeWorkRunDone(); - obs->ChangeWorkPreDone(); - } - } - if (onCB != nullptr) { - delete onCB; - onCB = nullptr; - } - if (work != nullptr) { - delete work; - work = nullptr; - } - HILOG_INFO("OnChange, uv_queue_work. end"); -} - -void NAPIDataShareObserver::OnChange() -{ - if (ref_ == nullptr) { - HILOG_ERROR("%{public}s, OnChange ref is nullptr.", __func__); - return; - } - ChangeWorkPre(); - uv_loop_s *loop = nullptr; - napi_get_uv_event_loop(env_, &loop); - if (loop == nullptr) { - HILOG_ERROR("%{public}s, loop == nullptr.", __func__); - ChangeWorkPreDone(); - return; - } - uv_work_t *work = new uv_work_t; - if (work == nullptr) { - HILOG_ERROR("%{public}s, work==nullptr.", __func__); - ChangeWorkPreDone(); - return; - } - DSHelperOnOffCB *onCB = new (std::nothrow) DSHelperOnOffCB; - if (onCB == nullptr) { - HILOG_ERROR("%{public}s, onCB == nullptr.", __func__); - if (work != nullptr) { - delete work; - work = nullptr; - } - ChangeWorkPreDone(); - return; - } - onCB->cbBase.cbInfo.env = env_; - onCB->cbBase.cbInfo.callback = ref_; - onCB->observer = this; - work->data = (void *)onCB; - int rev = uv_queue_work( - loop, - work, - [](uv_work_t *work) {}, - OnChangeJSThreadWorker); - if (rev != 0) { - if (onCB != nullptr) { - delete onCB; - onCB = nullptr; - } - if (work != nullptr) { - delete work; - work = nullptr; - } - } - HILOG_INFO("%{public}s, called. end", __func__); -} - -napi_value NAPI_GetType(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s,called", __func__); - DSHelperGetTypeCB *gettypeCB = new (std::nothrow) DSHelperGetTypeCB; - if (gettypeCB == nullptr) { - HILOG_ERROR("%{public}s, gettypeCB == nullptr.", __func__); - return WrapVoidToJS(env); - } - gettypeCB->cbBase.cbInfo.env = env; - gettypeCB->cbBase.asyncWork = nullptr; - gettypeCB->cbBase.deferred = nullptr; - gettypeCB->cbBase.ability = nullptr; - - napi_value ret = GetTypeWrap(env, info, gettypeCB); - if (ret == nullptr) { - HILOG_ERROR("%{public}s,ret == nullptr", __func__); - if (gettypeCB != nullptr) { - delete gettypeCB; - gettypeCB = nullptr; - } - ret = WrapVoidToJS(env); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} - -napi_value GetTypeWrap(napi_env env, napi_callback_info info, DSHelperGetTypeCB *gettypeCB) -{ - HILOG_INFO("%{public}s,called", __func__); - size_t argcAsync = ARGS_TWO; - const size_t argcPromise = ARGS_ONE; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = 0; - napi_value thisVar = nullptr; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); - if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); - if (valuetype == napi_string) { - gettypeCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); - HILOG_INFO("%{public}s,uri=%{public}s", __func__, gettypeCB->uri.c_str()); - } else { - HILOG_ERROR("%{public}s, Wrong argument type.", __func__); - } - - DataShareHelper *objectInfo = nullptr; - napi_unwrap(env, thisVar, (void **)&objectInfo); - HILOG_INFO("%{public}s,DataShareHelper objectInfo = %{public}p", __func__, objectInfo); - gettypeCB->dataShareHelper = objectInfo; - - if (argcAsync > argcPromise) { - ret = GetTypeAsync(env, args, ARGS_ONE, gettypeCB); - } else { - ret = GetTypePromise(env, gettypeCB); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} - -napi_value GetTypeAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperGetTypeCB *gettypeCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || gettypeCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = 0; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); - if (valuetype == napi_function) { - NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &gettypeCB->cbBase.cbInfo.callback)); - } - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - GetTypeExecuteCB, - GetTypeAsyncCompleteCB, - (void *)gettypeCB, - &gettypeCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, gettypeCB->cbBase.asyncWork)); - napi_value result = 0; - NAPI_CALL(env, napi_get_null(env, &result)); - HILOG_INFO("%{public}s, asyncCallback end", __func__); - return result; -} - -napi_value GetTypePromise(napi_env env, DSHelperGetTypeCB *gettypeCB) -{ - HILOG_INFO("%{public}s, promise.", __func__); - if (gettypeCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - napi_deferred deferred; - napi_value promise = 0; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - gettypeCB->cbBase.deferred = deferred; - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - GetTypeExecuteCB, - GetTypePromiseCompleteCB, - (void *)gettypeCB, - &gettypeCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, gettypeCB->cbBase.asyncWork)); - HILOG_INFO("%{public}s, promise end.", __func__); - return promise; -} - -void GetTypeExecuteCB(napi_env env, void *data) -{ - HILOG_INFO("NAPI_GetType, worker pool thread execute."); - DSHelperGetTypeCB *gettypeCB = static_cast(data); - if (gettypeCB->dataShareHelper != nullptr) { - gettypeCB->execResult = INVALID_PARAMETER; - if (!gettypeCB->uri.empty()) { - OHOS::Uri uri(gettypeCB->uri); - gettypeCB->result = gettypeCB->dataShareHelper->GetType(uri); - gettypeCB->execResult = NO_ERROR; - } else { - HILOG_ERROR("NAPI_GetType, dataShareHelper uri is empty."); - } - } else { - HILOG_ERROR("NAPI_GetType, dataShareHelper == nullptr."); - } - HILOG_INFO("NAPI_GetType, worker pool thread execute end."); -} - -void GetTypeAsyncCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_GetType, main event thread complete."); - DSHelperGetTypeCB *gettypeCB = static_cast(data); - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value result[ARGS_TWO] = {nullptr}; - napi_value callResult = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, gettypeCB->cbBase.cbInfo.callback, &callback)); - - result[PARAM0] = GetCallbackErrorValue(env, gettypeCB->execResult); - napi_create_string_utf8(env, gettypeCB->result.c_str(), NAPI_AUTO_LENGTH, &result[PARAM1]); - - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); - - if (gettypeCB->cbBase.cbInfo.callback != nullptr) { - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, gettypeCB->cbBase.cbInfo.callback)); - } - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, gettypeCB->cbBase.asyncWork)); - delete gettypeCB; - gettypeCB = nullptr; - HILOG_INFO("NAPI_GetType, main event thread complete end."); -} - -void GetTypePromiseCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_GetType, main event thread complete."); - DSHelperGetTypeCB *gettypeCB = static_cast(data); - napi_value result = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, gettypeCB->result.c_str(), NAPI_AUTO_LENGTH, &result)); - NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, gettypeCB->cbBase.deferred, result)); - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, gettypeCB->cbBase.asyncWork)); - delete gettypeCB; - gettypeCB = nullptr; - HILOG_INFO("NAPI_GetType, main event thread complete end."); -} - -napi_value NAPI_GetFileTypes(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s,called", __func__); - DSHelperGetFileTypesCB *getfiletypesCB = new (std::nothrow) DSHelperGetFileTypesCB; - if (getfiletypesCB == nullptr) { - HILOG_ERROR("%{public}s, getfiletypesCB == nullptr.", __func__); - return WrapVoidToJS(env); - } - getfiletypesCB->cbBase.cbInfo.env = env; - getfiletypesCB->cbBase.asyncWork = nullptr; - getfiletypesCB->cbBase.deferred = nullptr; - getfiletypesCB->cbBase.ability = nullptr; - - napi_value ret = GetFileTypesWrap(env, info, getfiletypesCB); - if (ret == nullptr) { - HILOG_ERROR("%{public}s,ret == nullptr", __func__); - if (getfiletypesCB != nullptr) { - delete getfiletypesCB; - getfiletypesCB = nullptr; - } - ret = WrapVoidToJS(env); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} - -napi_value GetFileTypesWrap(napi_env env, napi_callback_info info, DSHelperGetFileTypesCB *getfiletypesCB) -{ - HILOG_INFO("%{public}s,called", __func__); - size_t argcAsync = ARGS_THREE; - const size_t argcPromise = ARGS_TWO; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = 0; - napi_value thisVar = nullptr; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); - if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); - if (valuetype == napi_string) { - getfiletypesCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); - HILOG_INFO("%{public}s,uri=%{public}s", __func__, getfiletypesCB->uri.c_str()); - } - - NAPI_CALL(env, napi_typeof(env, args[PARAM1], &valuetype)); - if (valuetype == napi_string) { - getfiletypesCB->mimeTypeFilter = NapiValueToStringUtf8(env, args[PARAM1]); - HILOG_INFO("%{public}s,mimeTypeFilter=%{public}s", __func__, getfiletypesCB->mimeTypeFilter.c_str()); - } - - DataShareHelper *objectInfo = nullptr; - napi_unwrap(env, thisVar, (void **)&objectInfo); - HILOG_INFO("%{public}s,DataShareHelper objectInfo = %{public}p", __func__, objectInfo); - getfiletypesCB->dataShareHelper = objectInfo; - - if (argcAsync > argcPromise) { - ret = GetFileTypesAsync(env, args, ARGS_TWO, getfiletypesCB); - } else { - ret = GetFileTypesPromise(env, getfiletypesCB); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} -napi_value GetFileTypesAsync( - napi_env env, napi_value *args, const size_t argCallback, DSHelperGetFileTypesCB *getfiletypesCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || getfiletypesCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = 0; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); - if (valuetype == napi_function) { - NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &getfiletypesCB->cbBase.cbInfo.callback)); - } - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - GetFileTypesExecuteCB, - GetFileTypesAsyncCompleteCB, - (void *)getfiletypesCB, - &getfiletypesCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, getfiletypesCB->cbBase.asyncWork)); - napi_value result = 0; - NAPI_CALL(env, napi_get_null(env, &result)); - HILOG_INFO("%{public}s, asyncCallback end.", __func__); - return result; -} - -napi_value GetFileTypesPromise(napi_env env, DSHelperGetFileTypesCB *getfiletypesCB) -{ - HILOG_INFO("%{public}s, promise.", __func__); - if (getfiletypesCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - napi_deferred deferred; - napi_value promise = 0; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - getfiletypesCB->cbBase.deferred = deferred; - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - GetFileTypesExecuteCB, - GetFileTypesPromiseCompleteCB, - (void *)getfiletypesCB, - &getfiletypesCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, getfiletypesCB->cbBase.asyncWork)); - HILOG_INFO("%{public}s, promise end.", __func__); - return promise; -} - -void GetFileTypesExecuteCB(napi_env env, void *data) -{ - HILOG_INFO("NAPI_GetFileTypes, worker pool thread execute."); - DSHelperGetFileTypesCB *getfiletypesCB = static_cast(data); - if (getfiletypesCB->dataShareHelper != nullptr) { - getfiletypesCB->execResult = INVALID_PARAMETER; - if (!getfiletypesCB->uri.empty()) { - OHOS::Uri uri(getfiletypesCB->uri); - HILOG_INFO("NAPI_GetFileTypes, uri:%{public}s", uri.ToString().c_str()); - HILOG_INFO("NAPI_GetFileTypes, mimeTypeFilter:%{public}s", getfiletypesCB->mimeTypeFilter.c_str()); - getfiletypesCB->result = getfiletypesCB->dataShareHelper->GetFileTypes( - uri, - getfiletypesCB->mimeTypeFilter); - getfiletypesCB->execResult = NO_ERROR; - } else { - HILOG_INFO("NAPI_GetFileTypes, dataShareHelper uri is empty."); - } - } else { - HILOG_INFO("NAPI_GetFileTypes, dataShareHelper == nullptr."); - } - HILOG_INFO("NAPI_GetFileTypes, worker pool thread execute end."); -} - -void GetFileTypesAsyncCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_GetFileTypes, main event thread complete."); - DSHelperGetFileTypesCB *getfiletypesCB = static_cast(data); - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value result[ARGS_TWO] = {nullptr}; - napi_value callResult = nullptr; - - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, getfiletypesCB->cbBase.cbInfo.callback, &callback)); - - result[PARAM0] = GetCallbackErrorValue(env, getfiletypesCB->execResult); - result[PARAM1] = WrapGetFileTypesCB(env, *getfiletypesCB); - - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); - - if (getfiletypesCB->cbBase.cbInfo.callback != nullptr) { - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, getfiletypesCB->cbBase.cbInfo.callback)); - } - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, getfiletypesCB->cbBase.asyncWork)); - delete getfiletypesCB; - getfiletypesCB = nullptr; - HILOG_INFO("NAPI_GetFileTypes, main event thread complete end."); -} - -napi_value WrapGetFileTypesCB(napi_env env, const DSHelperGetFileTypesCB &getfiletypesCB) -{ - HILOG_INFO("WrapGetFileTypesCB, called."); - HILOG_INFO("NAPI_GetFileTypes, result.size:%{public}zu", getfiletypesCB.result.size()); - for (size_t i = 0; i < getfiletypesCB.result.size(); i++) { - HILOG_INFO("NAPI_GetFileTypes, result[%{public}zu]:%{public}s", i, getfiletypesCB.result.at(i).c_str()); - } - napi_value proValue = nullptr; - - napi_value jsArrayresult = nullptr; - NAPI_CALL(env, napi_create_array(env, &jsArrayresult)); - for (size_t i = 0; i < getfiletypesCB.result.size(); i++) { - proValue = nullptr; - NAPI_CALL(env, napi_create_string_utf8(env, getfiletypesCB.result.at(i).c_str(), NAPI_AUTO_LENGTH, &proValue)); - NAPI_CALL(env, napi_set_element(env, jsArrayresult, i, proValue)); - } - HILOG_INFO("WrapGetFileTypesCB, end."); - return jsArrayresult; -} - -void GetFileTypesPromiseCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_GetFileTypes, main event thread complete."); - DSHelperGetFileTypesCB *getfiletypesCB = static_cast(data); - napi_value result = nullptr; - - result = WrapGetFileTypesCB(env, *getfiletypesCB); - NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, getfiletypesCB->cbBase.deferred, result)); - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, getfiletypesCB->cbBase.asyncWork)); - delete getfiletypesCB; - getfiletypesCB = nullptr; - HILOG_INFO("NAPI_GetFileTypes, main event thread complete end."); -} - -napi_value NAPI_NormalizeUri(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s,called", __func__); - DSHelperNormalizeUriCB *normalizeuriCB = new (std::nothrow) DSHelperNormalizeUriCB; - if (normalizeuriCB == nullptr) { - HILOG_ERROR("%{public}s, normalizeuriCB == nullptr.", __func__); - return WrapVoidToJS(env); - } - normalizeuriCB->cbBase.cbInfo.env = env; - normalizeuriCB->cbBase.asyncWork = nullptr; - normalizeuriCB->cbBase.deferred = nullptr; - normalizeuriCB->cbBase.ability = nullptr; - - napi_value ret = NormalizeUriWrap(env, info, normalizeuriCB); - if (ret == nullptr) { - HILOG_ERROR("%{public}s,ret == nullptr", __func__); - if (normalizeuriCB != nullptr) { - delete normalizeuriCB; - normalizeuriCB = nullptr; - } - ret = WrapVoidToJS(env); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} - -napi_value NormalizeUriWrap(napi_env env, napi_callback_info info, DSHelperNormalizeUriCB *normalizeuriCB) -{ - HILOG_INFO("%{public}s,called", __func__); - size_t argcAsync = ARGS_TWO; - const size_t argcPromise = ARGS_ONE; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = 0; - napi_value thisVar = nullptr; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); - if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); - if (valuetype == napi_string) { - normalizeuriCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); - HILOG_INFO("%{public}s,uri=%{public}s", __func__, normalizeuriCB->uri.c_str()); - } - - DataShareHelper *objectInfo = nullptr; - napi_unwrap(env, thisVar, (void **)&objectInfo); - HILOG_INFO("%{public}s,DataShareHelper objectInfo = %{public}p", __func__, objectInfo); - normalizeuriCB->dataShareHelper = objectInfo; - - if (argcAsync > argcPromise) { - ret = NormalizeUriAsync(env, args, ARGS_ONE, normalizeuriCB); - } else { - ret = NormalizeUriPromise(env, normalizeuriCB); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} -napi_value NormalizeUriAsync( - napi_env env, napi_value *args, const size_t argCallback, DSHelperNormalizeUriCB *normalizeuriCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || normalizeuriCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = 0; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); - if (valuetype == napi_function) { - NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &normalizeuriCB->cbBase.cbInfo.callback)); - } - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - NormalizeUriExecuteCB, - NormalizeUriAsyncCompleteCB, - (void *)normalizeuriCB, - &normalizeuriCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, normalizeuriCB->cbBase.asyncWork)); - napi_value result = 0; - NAPI_CALL(env, napi_get_null(env, &result)); - HILOG_INFO("%{public}s, asyncCallback end.", __func__); - return result; -} - -napi_value NormalizeUriPromise(napi_env env, DSHelperNormalizeUriCB *normalizeuriCB) -{ - HILOG_INFO("%{public}s, promise.", __func__); - if (normalizeuriCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - napi_deferred deferred; - napi_value promise = 0; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - normalizeuriCB->cbBase.deferred = deferred; - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - NormalizeUriExecuteCB, - NormalizeUriPromiseCompleteCB, - (void *)normalizeuriCB, - &normalizeuriCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, normalizeuriCB->cbBase.asyncWork)); - HILOG_INFO("%{public}s, promise end.", __func__); - return promise; -} - -void NormalizeUriExecuteCB(napi_env env, void *data) -{ - HILOG_INFO("NAPI_NormalizeUri, worker pool thread execute."); - DSHelperNormalizeUriCB *normalizeuriCB = static_cast(data); - Uri uriValue(normalizeuriCB->uri); - if (normalizeuriCB->dataShareHelper != nullptr) { - normalizeuriCB->execResult = INVALID_PARAMETER; - if (!normalizeuriCB->uri.empty()) { - OHOS::Uri uri(normalizeuriCB->uri); - uriValue = normalizeuriCB->dataShareHelper->NormalizeUri(uri); - normalizeuriCB->result = uriValue.ToString(); - normalizeuriCB->execResult = NO_ERROR; - } - } else { - HILOG_INFO("NAPI_NormalizeUri, dataShareHelper == nullptr"); - } - HILOG_INFO("NAPI_NormalizeUri, worker pool thread execute end."); -} - -void NormalizeUriAsyncCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_NormalizeUri, main event thread complete."); - DSHelperNormalizeUriCB *normalizeuriCB = static_cast(data); - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value result[ARGS_TWO] = {nullptr}; - napi_value callResult = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, normalizeuriCB->cbBase.cbInfo.callback, &callback)); - - result[PARAM0] = GetCallbackErrorValue(env, normalizeuriCB->execResult); - NAPI_CALL_RETURN_VOID( - env, napi_create_string_utf8(env, normalizeuriCB->result.c_str(), NAPI_AUTO_LENGTH, &result[PARAM1])); - - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); - - if (normalizeuriCB->cbBase.cbInfo.callback != nullptr) { - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, normalizeuriCB->cbBase.cbInfo.callback)); - } - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, normalizeuriCB->cbBase.asyncWork)); - delete normalizeuriCB; - normalizeuriCB = nullptr; - HILOG_INFO("NAPI_NormalizeUri, main event thread complete end."); -} - -void NormalizeUriPromiseCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_NormalizeUri, main event thread complete."); - DSHelperNormalizeUriCB *normalizeuriCB = static_cast(data); - napi_value result = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, normalizeuriCB->result.c_str(), NAPI_AUTO_LENGTH, &result)); - NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, normalizeuriCB->cbBase.deferred, result)); - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, normalizeuriCB->cbBase.asyncWork)); - delete normalizeuriCB; - normalizeuriCB = nullptr; - HILOG_INFO("NAPI_NormalizeUri, main event thread complete end."); -} - -napi_value NAPI_DenormalizeUri(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s,called", __func__); - DSHelperDenormalizeUriCB *denormalizeuriCB = new (std::nothrow) DSHelperDenormalizeUriCB; - if (denormalizeuriCB == nullptr) { - HILOG_ERROR("%{public}s, denormalizeuriCB == nullptr.", __func__); - return WrapVoidToJS(env); - } - denormalizeuriCB->cbBase.cbInfo.env = env; - denormalizeuriCB->cbBase.asyncWork = nullptr; - denormalizeuriCB->cbBase.deferred = nullptr; - denormalizeuriCB->cbBase.ability = nullptr; - - napi_value ret = DenormalizeUriWrap(env, info, denormalizeuriCB); - if (ret == nullptr) { - HILOG_ERROR("%{public}s,ret == nullptr", __func__); - if (denormalizeuriCB != nullptr) { - delete denormalizeuriCB; - denormalizeuriCB = nullptr; - } - ret = WrapVoidToJS(env); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} - -napi_value DenormalizeUriWrap(napi_env env, napi_callback_info info, DSHelperDenormalizeUriCB *denormalizeuriCB) -{ - HILOG_INFO("%{public}s,called", __func__); - size_t argcAsync = ARGS_TWO; - const size_t argcPromise = ARGS_ONE; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = 0; - napi_value thisVar = nullptr; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); - if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); - if (valuetype == napi_string) { - denormalizeuriCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); - HILOG_INFO("%{public}s,uri=%{public}s", __func__, denormalizeuriCB->uri.c_str()); - } - - DataShareHelper *objectInfo = nullptr; - napi_unwrap(env, thisVar, (void **)&objectInfo); - HILOG_INFO("%{public}s,DataShareHelper objectInfo = %{public}p", __func__, objectInfo); - denormalizeuriCB->dataShareHelper = objectInfo; - - if (argcAsync > argcPromise) { - ret = DenormalizeUriAsync(env, args, ARGS_ONE, denormalizeuriCB); - } else { - ret = DenormalizeUriPromise(env, denormalizeuriCB); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} -napi_value DenormalizeUriAsync( - napi_env env, napi_value *args, const size_t argCallback, DSHelperDenormalizeUriCB *denormalizeuriCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || denormalizeuriCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = 0; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); - if (valuetype == napi_function) { - NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &denormalizeuriCB->cbBase.cbInfo.callback)); - } - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - DenormalizeUriExecuteCB, - DenormalizeUriAsyncCompleteCB, - (void *)denormalizeuriCB, - &denormalizeuriCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, denormalizeuriCB->cbBase.asyncWork)); - napi_value result = 0; - NAPI_CALL(env, napi_get_null(env, &result)); - HILOG_INFO("%{public}s, asyncCallback end.", __func__); - return result; -} - -napi_value DenormalizeUriPromise(napi_env env, DSHelperDenormalizeUriCB *denormalizeuriCB) -{ - HILOG_INFO("%{public}s, promise.", __func__); - if (denormalizeuriCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - napi_deferred deferred; - napi_value promise = 0; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - denormalizeuriCB->cbBase.deferred = deferred; - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - DenormalizeUriExecuteCB, - DenormalizeUriPromiseCompleteCB, - (void *)denormalizeuriCB, - &denormalizeuriCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, denormalizeuriCB->cbBase.asyncWork)); - HILOG_INFO("%{public}s, promise end.", __func__); - return promise; -} - -void DenormalizeUriExecuteCB(napi_env env, void *data) -{ - HILOG_INFO("NAPI_DenormalizeUri, worker pool thread execute."); - DSHelperDenormalizeUriCB *denormalizeuriCB = static_cast(data); - Uri uriValue(denormalizeuriCB->uri); - if (denormalizeuriCB->dataShareHelper != nullptr) { - denormalizeuriCB->execResult = INVALID_PARAMETER; - if (!denormalizeuriCB->uri.empty()) { - OHOS::Uri uri(denormalizeuriCB->uri); - uriValue = denormalizeuriCB->dataShareHelper->DenormalizeUri(uri); - denormalizeuriCB->result = uriValue.ToString(); - denormalizeuriCB->execResult = NO_ERROR; - } else { - HILOG_ERROR("NAPI_DenormalizeUri, dataShareHelper uri is empty"); - } - } else { - HILOG_ERROR("NAPI_DenormalizeUri, dataShareHelper == nullptr"); - } - HILOG_INFO("NAPI_DenormalizeUri, worker pool thread execute end."); -} - -void DenormalizeUriAsyncCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_DenormalizeUri, main event thread complete."); - DSHelperDenormalizeUriCB *denormalizeuriCB = static_cast(data); - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value result[ARGS_TWO] = {nullptr}; - napi_value callResult = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, denormalizeuriCB->cbBase.cbInfo.callback, &callback)); - - result[PARAM0] = GetCallbackErrorValue(env, denormalizeuriCB->execResult); - NAPI_CALL_RETURN_VOID( - env, napi_create_string_utf8(env, denormalizeuriCB->result.c_str(), NAPI_AUTO_LENGTH, &result[PARAM1])); - - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); - - if (denormalizeuriCB->cbBase.cbInfo.callback != nullptr) { - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, denormalizeuriCB->cbBase.cbInfo.callback)); - } - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, denormalizeuriCB->cbBase.asyncWork)); - delete denormalizeuriCB; - denormalizeuriCB = nullptr; - HILOG_INFO("NAPI_DenormalizeUri, main event thread complete end."); -} - -void DenormalizeUriPromiseCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_DenormalizeUri, main event thread complete."); - DSHelperDenormalizeUriCB *denormalizeuriCB = static_cast(data); - napi_value result = nullptr; - NAPI_CALL_RETURN_VOID( - env, napi_create_string_utf8(env, denormalizeuriCB->result.c_str(), NAPI_AUTO_LENGTH, &result)); - NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, denormalizeuriCB->cbBase.deferred, result)); - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, denormalizeuriCB->cbBase.asyncWork)); - delete denormalizeuriCB; - denormalizeuriCB = nullptr; - HILOG_INFO("NAPI_DenormalizeUri, main event thread complete end."); -} - -void UnwrapDataAbilityPredicates(NativeRdb::DataAbilityPredicates &predicates, napi_env env, napi_value value) -{ - auto tempPredicates = DataAbilityJsKit::DataAbilityPredicatesProxy::GetNativePredicates(env, value); - if (tempPredicates == nullptr) { - HILOG_ERROR("%{public}s, GetNativePredicates retval Marshalling failed.", __func__); - return; - } - predicates = *tempPredicates; -} - -/** - * @brief DataShareHelper NAPI method : insert. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_Delete(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s,called", __func__); - DSHelperDeleteCB *deleteCB = new (std::nothrow) DSHelperDeleteCB; - if (deleteCB == nullptr) { - HILOG_ERROR("%{public}s, deleteCB == nullptr.", __func__); - return WrapVoidToJS(env); - } - deleteCB->cbBase.cbInfo.env = env; - deleteCB->cbBase.asyncWork = nullptr; - deleteCB->cbBase.deferred = nullptr; - deleteCB->cbBase.ability = nullptr; - - napi_value ret = DeleteWrap(env, info, deleteCB); - if (ret == nullptr) { - HILOG_ERROR("%{public}s,ret == nullptr", __func__); - if (deleteCB != nullptr) { - delete deleteCB; - deleteCB = nullptr; - } - ret = WrapVoidToJS(env); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} - -/** - * @brief Insert processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param insertCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value DeleteWrap(napi_env env, napi_callback_info info, DSHelperDeleteCB *deleteCB) -{ - HILOG_INFO("%{public}s,called", __func__); - size_t argcAsync = ARGS_THREE; - const size_t argcPromise = ARGS_TWO; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = 0; - napi_value thisVar = nullptr; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); - if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); - if (valuetype == napi_string) { - deleteCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); - HILOG_INFO("%{public}s,uri=%{public}s", __func__, deleteCB->uri.c_str()); - } - - UnwrapDataAbilityPredicates(deleteCB->predicates, env, args[PARAM1]); - DataShareHelper *objectInfo = nullptr; - napi_unwrap(env, thisVar, (void **)&objectInfo); - HILOG_INFO("%{public}s,DataShareHelper objectInfo = %{public}p", __func__, objectInfo); - deleteCB->dataShareHelper = objectInfo; - - if (argcAsync > argcPromise) { - ret = DeleteAsync(env, args, ARGS_TWO, deleteCB); - } else { - ret = DeletePromise(env, deleteCB); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} - -napi_value DeleteAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperDeleteCB *deleteCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || deleteCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = 0; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); - if (valuetype == napi_function) { - NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &deleteCB->cbBase.cbInfo.callback)); - } - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - DeleteExecuteCB, - DeleteAsyncCompleteCB, - (void *)deleteCB, - &deleteCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, deleteCB->cbBase.asyncWork)); - napi_value result = 0; - NAPI_CALL(env, napi_get_null(env, &result)); - HILOG_INFO("%{public}s, asyncCallback end.", __func__); - return result; -} - -napi_value DeletePromise(napi_env env, DSHelperDeleteCB *deleteCB) -{ - HILOG_INFO("%{public}s, promise.", __func__); - if (deleteCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - napi_deferred deferred; - napi_value promise = 0; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - deleteCB->cbBase.deferred = deferred; - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - DeleteExecuteCB, - DeletePromiseCompleteCB, - (void *)deleteCB, - &deleteCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, deleteCB->cbBase.asyncWork)); - HILOG_INFO("%{public}s, promise end.", __func__); - return promise; -} - -void DeleteExecuteCB(napi_env env, void *data) -{ - HILOG_INFO("NAPI_Delete, worker pool thread execute."); - DSHelperDeleteCB *deleteCB = static_cast(data); - if (deleteCB->dataShareHelper != nullptr) { - deleteCB->execResult = INVALID_PARAMETER; - if (!deleteCB->uri.empty()) { - OHOS::Uri uri(deleteCB->uri); - deleteCB->result = deleteCB->dataShareHelper->Delete(uri, deleteCB->predicates); - deleteCB->execResult = NO_ERROR; - } else { - HILOG_ERROR("NAPI_Delete, dataShareHelper uri is empty"); - } - } else { - HILOG_ERROR("NAPI_Delete, dataShareHelper == nullptr"); - } - HILOG_INFO("NAPI_Delete, worker pool thread execute end."); -} - -void DeleteAsyncCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_Delete, main event thread complete."); - DSHelperDeleteCB *DeleteCB = static_cast(data); - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value result[ARGS_TWO] = {nullptr}; - napi_value callResult = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, DeleteCB->cbBase.cbInfo.callback, &callback)); - - result[PARAM0] = GetCallbackErrorValue(env, DeleteCB->execResult); - napi_create_int32(env, DeleteCB->result, &result[PARAM1]); - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); - - if (DeleteCB->cbBase.cbInfo.callback != nullptr) { - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, DeleteCB->cbBase.cbInfo.callback)); - } - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, DeleteCB->cbBase.asyncWork)); - delete DeleteCB; - DeleteCB = nullptr; - HILOG_INFO("NAPI_Delete, main event thread complete end."); -} - -void DeletePromiseCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_Delete, main event thread complete."); - DSHelperDeleteCB *DeleteCB = static_cast(data); - napi_value result = nullptr; - napi_create_int32(env, DeleteCB->result, &result); - NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, DeleteCB->cbBase.deferred, result)); - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, DeleteCB->cbBase.asyncWork)); - delete DeleteCB; - DeleteCB = nullptr; - HILOG_INFO("NAPI_Delete, main event thread complete end."); -} - -/** - * @brief DataShareHelper NAPI method : insert. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_Update(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s,called", __func__); - DSHelperUpdateCB *updateCB = new (std::nothrow) DSHelperUpdateCB; - if (updateCB == nullptr) { - HILOG_ERROR("%{public}s, updateCB == nullptr.", __func__); - return WrapVoidToJS(env); - } - updateCB->cbBase.cbInfo.env = env; - updateCB->cbBase.asyncWork = nullptr; - updateCB->cbBase.deferred = nullptr; - updateCB->cbBase.ability = nullptr; - - napi_value ret = UpdateWrap(env, info, updateCB); - if (ret == nullptr) { - HILOG_ERROR("%{public}s,ret == nullptr", __func__); - if (updateCB != nullptr) { - delete updateCB; - updateCB = nullptr; - } - ret = WrapVoidToJS(env); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} - -/** - * @brief Insert processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param insertCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value UpdateWrap(napi_env env, napi_callback_info info, DSHelperUpdateCB *updateCB) -{ - HILOG_INFO("%{public}s,called", __func__); - size_t argcAsync = ARGS_FOUR; - const size_t argcPromise = ARGS_THREE; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = 0; - napi_value thisVar = nullptr; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); - if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); - if (valuetype == napi_string) { - updateCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); - HILOG_INFO("%{public}s,uri=%{public}s", __func__, updateCB->uri.c_str()); - } - - updateCB->valueBucket.Clear(); - AnalysisValuesBucket(updateCB->valueBucket, env, args[PARAM1]); - UnwrapDataAbilityPredicates(updateCB->predicates, env, args[PARAM2]); - DataShareHelper *objectInfo = nullptr; - napi_unwrap(env, thisVar, (void **)&objectInfo); - HILOG_INFO("%{public}s,DataShareHelper objectInfo = %{public}p", __func__, objectInfo); - updateCB->dataShareHelper = objectInfo; - - if (argcAsync > argcPromise) { - ret = UpdateAsync(env, args, ARGS_THREE, updateCB); - } else { - ret = UpdatePromise(env, updateCB); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} - -napi_value UpdateAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperUpdateCB *updateCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || updateCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = 0; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); - if (valuetype == napi_function) { - NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &updateCB->cbBase.cbInfo.callback)); - } - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - UpdateExecuteCB, - UpdateAsyncCompleteCB, - (void *)updateCB, - &updateCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, updateCB->cbBase.asyncWork)); - napi_value result = 0; - NAPI_CALL(env, napi_get_null(env, &result)); - HILOG_INFO("%{public}s, asyncCallback end.", __func__); - return result; -} - -napi_value UpdatePromise(napi_env env, DSHelperUpdateCB *updateCB) -{ - HILOG_INFO("%{public}s, promise.", __func__); - if (updateCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - napi_deferred deferred; - napi_value promise = 0; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - updateCB->cbBase.deferred = deferred; - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - UpdateExecuteCB, - UpdatePromiseCompleteCB, - (void *)updateCB, - &updateCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, updateCB->cbBase.asyncWork)); - HILOG_INFO("%{public}s, promise end.", __func__); - return promise; -} - -void UpdateExecuteCB(napi_env env, void *data) -{ - HILOG_INFO("NAPI_Update, worker pool thread execute."); - DSHelperUpdateCB *updateCB = static_cast(data); - if (updateCB->dataShareHelper != nullptr) { - updateCB->execResult = INVALID_PARAMETER; - if (!updateCB->uri.empty()) { - OHOS::Uri uri(updateCB->uri); - updateCB->result = updateCB->dataShareHelper->Update(uri, updateCB->valueBucket, updateCB->predicates); - updateCB->execResult = NO_ERROR; - } else { - HILOG_ERROR("NAPI_Update, dataShareHelper uri is empty"); - } - } else { - HILOG_ERROR("NAPI_Update, dataShareHelper == nullptr"); - } - HILOG_INFO("NAPI_Update, worker pool thread execute end."); -} - -void UpdateAsyncCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_Update, main event thread complete."); - DSHelperUpdateCB *updateCB = static_cast(data); - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value result[ARGS_TWO] = {nullptr}; - napi_value callResult = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, updateCB->cbBase.cbInfo.callback, &callback)); - - result[PARAM0] = GetCallbackErrorValue(env, updateCB->execResult); - napi_create_int32(env, updateCB->result, &result[PARAM1]); - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); - - if (updateCB->cbBase.cbInfo.callback != nullptr) { - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, updateCB->cbBase.cbInfo.callback)); - } - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, updateCB->cbBase.asyncWork)); - delete updateCB; - updateCB = nullptr; - HILOG_INFO("NAPI_Update, main event thread complete end."); -} - -void UpdatePromiseCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_Update, main event thread complete."); - DSHelperUpdateCB *updateCB = static_cast(data); - napi_value result = nullptr; - napi_create_int32(env, updateCB->result, &result); - NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, updateCB->cbBase.deferred, result)); - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, updateCB->cbBase.asyncWork)); - delete updateCB; - updateCB = nullptr; - HILOG_INFO("NAPI_Update, main event thread complete end."); -} - -/** - * @brief DataShareHelper NAPI method : insert. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_OpenFile(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s,called", __func__); - DSHelperOpenFileCB *openFileCB = new (std::nothrow) DSHelperOpenFileCB; - if (openFileCB == nullptr) { - HILOG_ERROR("%{public}s, openFileCB == nullptr.", __func__); - return WrapVoidToJS(env); - } - openFileCB->cbBase.cbInfo.env = env; - openFileCB->cbBase.asyncWork = nullptr; - openFileCB->cbBase.deferred = nullptr; - openFileCB->cbBase.ability = nullptr; - - napi_value ret = OpenFileWrap(env, info, openFileCB); - if (ret == nullptr) { - HILOG_ERROR("%{public}s,ret == nullptr", __func__); - if (openFileCB != nullptr) { - delete openFileCB; - openFileCB = nullptr; - } - ret = WrapVoidToJS(env); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} - -/** - * @brief Insert processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param insertCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value OpenFileWrap(napi_env env, napi_callback_info info, DSHelperOpenFileCB *openFileCB) -{ - HILOG_INFO("%{public}s,called", __func__); - size_t argcAsync = ARGS_THREE; - const size_t argcPromise = ARGS_TWO; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = 0; - napi_value thisVar = nullptr; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); - if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); - if (valuetype == napi_string) { - openFileCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); - HILOG_INFO("%{public}s,uri=%{public}s", __func__, openFileCB->uri.c_str()); - } - - NAPI_CALL(env, napi_typeof(env, args[PARAM1], &valuetype)); - if (valuetype == napi_string) { - openFileCB->mode = NapiValueToStringUtf8(env, args[PARAM1]); - HILOG_INFO("%{public}s,mode=%{public}s", __func__, openFileCB->mode.c_str()); - } - - DataShareHelper *objectInfo = nullptr; - napi_unwrap(env, thisVar, (void **)&objectInfo); - HILOG_INFO("%{public}s,DataShareHelper objectInfo = %{public}p", __func__, objectInfo); - openFileCB->dataShareHelper = objectInfo; - - if (argcAsync > argcPromise) { - ret = OpenFileAsync(env, args, ARGS_TWO, openFileCB); - } else { - ret = OpenFilePromise(env, openFileCB); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} - -napi_value OpenFileAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperOpenFileCB *openFileCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || openFileCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = 0; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); - if (valuetype == napi_function) { - NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &openFileCB->cbBase.cbInfo.callback)); - } - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - OpenFileExecuteCB, - OpenFileAsyncCompleteCB, - (void *)openFileCB, - &openFileCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, openFileCB->cbBase.asyncWork)); - napi_value result = 0; - NAPI_CALL(env, napi_get_null(env, &result)); - HILOG_INFO("%{public}s, asyncCallback end.", __func__); - return result; -} - -napi_value OpenFilePromise(napi_env env, DSHelperOpenFileCB *openFileCB) -{ - HILOG_INFO("%{public}s, promise.", __func__); - if (openFileCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - napi_deferred deferred; - napi_value promise = 0; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - openFileCB->cbBase.deferred = deferred; - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - OpenFileExecuteCB, - OpenFilePromiseCompleteCB, - (void *)openFileCB, - &openFileCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, openFileCB->cbBase.asyncWork)); - HILOG_INFO("%{public}s, promise end.", __func__); - return promise; -} - -void OpenFileExecuteCB(napi_env env, void *data) -{ - HILOG_INFO("NAPI_OpenFile, worker pool thread execute."); - DSHelperOpenFileCB *OpenFileCB = static_cast(data); - if (OpenFileCB->dataShareHelper != nullptr) { - OpenFileCB->execResult = INVALID_PARAMETER; - if (!OpenFileCB->uri.empty()) { - OHOS::Uri uri(OpenFileCB->uri); - OpenFileCB->result = OpenFileCB->dataShareHelper->OpenFile(uri, OpenFileCB->mode); - OpenFileCB->execResult = NO_ERROR; - } else { - HILOG_ERROR("NAPI_OpenFile, dataShareHelper uri is empty"); - } - } else { - HILOG_ERROR("NAPI_OpenFile, dataShareHelper == nullptr"); - } - HILOG_INFO("NAPI_OpenFile, worker pool thread execute end."); -} - -void OpenFileAsyncCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_OpenFile, main event thread complete."); - DSHelperOpenFileCB *OpenFileCB = static_cast(data); - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value result[ARGS_TWO] = {nullptr}; - napi_value callResult = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, OpenFileCB->cbBase.cbInfo.callback, &callback)); - - result[PARAM0] = GetCallbackErrorValue(env, OpenFileCB->execResult); - napi_create_int32(env, OpenFileCB->result, &result[PARAM1]); - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); - - if (OpenFileCB->cbBase.cbInfo.callback != nullptr) { - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, OpenFileCB->cbBase.cbInfo.callback)); - } - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, OpenFileCB->cbBase.asyncWork)); - delete OpenFileCB; - OpenFileCB = nullptr; - HILOG_INFO("NAPI_OpenFile, main event thread complete end."); -} - -void OpenFilePromiseCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_OpenFileCB, main event thread complete."); - DSHelperOpenFileCB *OpenFileCB = static_cast(data); - napi_value result = nullptr; - napi_create_int32(env, OpenFileCB->result, &result); - NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, OpenFileCB->cbBase.deferred, result)); - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, OpenFileCB->cbBase.asyncWork)); - delete OpenFileCB; - OpenFileCB = nullptr; - HILOG_INFO("NAPI_OpenFileCB, main event thread complete end."); -} - -/** - * @brief DataShareHelper NAPI method : insert. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_BatchInsert(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s,called", __func__); - DSHelperBatchInsertCB *BatchInsertCB = new (std::nothrow) DSHelperBatchInsertCB; - if (BatchInsertCB == nullptr) { - HILOG_ERROR("%{public}s, BatchInsertCB == nullptr.", __func__); - return WrapVoidToJS(env); - } - BatchInsertCB->cbBase.cbInfo.env = env; - BatchInsertCB->cbBase.asyncWork = nullptr; - BatchInsertCB->cbBase.deferred = nullptr; - BatchInsertCB->cbBase.ability = nullptr; - - napi_value ret = BatchInsertWrap(env, info, BatchInsertCB); - if (ret == nullptr) { - HILOG_ERROR("%{public}s,ret == nullptr", __func__); - if (BatchInsertCB != nullptr) { - delete BatchInsertCB; - BatchInsertCB = nullptr; - } - ret = WrapVoidToJS(env); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} - -std::vector NapiValueObject(napi_env env, napi_value param) -{ - HILOG_INFO("%{public}s,called", __func__); - std::vector result; - UnwrapArrayObjectFromJS(env, param, result); - return result; -} - -bool UnwrapArrayObjectFromJS(napi_env env, napi_value param, std::vector &value) -{ - HILOG_INFO("%{public}s,called", __func__); - uint32_t arraySize = 0; - napi_value jsValue = nullptr; - std::string strValue = ""; - - if (!IsArrayForNapiValue(env, param, arraySize)) { - HILOG_INFO("%{public}s, IsArrayForNapiValue is false", __func__); - return false; - } - - value.clear(); - for (uint32_t i = 0; i < arraySize; i++) { - jsValue = nullptr; - if (napi_get_element(env, param, i, &jsValue) != napi_ok) { - HILOG_INFO("%{public}s, napi_get_element is false", __func__); - return false; - } - - NativeRdb::ValuesBucket valueBucket; - valueBucket.Clear(); - AnalysisValuesBucket(valueBucket, env, jsValue); - - value.push_back(valueBucket); - } - HILOG_INFO("%{public}s,end", __func__); - return true; -} - -/** - * @brief Insert processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param insertCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value BatchInsertWrap(napi_env env, napi_callback_info info, DSHelperBatchInsertCB *batchInsertCB) -{ - HILOG_INFO("%{public}s,called", __func__); - size_t argcAsync = ARGS_THREE; - const size_t argcPromise = ARGS_TWO; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = 0; - napi_value thisVar = nullptr; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); - if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); - if (valuetype == napi_string) { - batchInsertCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); - HILOG_INFO("%{public}s,uri=%{public}s", __func__, batchInsertCB->uri.c_str()); - } - - batchInsertCB->values = NapiValueObject(env, args[PARAM1]); - - DataShareHelper *objectInfo = nullptr; - napi_unwrap(env, thisVar, (void **)&objectInfo); - HILOG_INFO("%{public}s,DataShareHelper objectInfo = %{public}p", __func__, objectInfo); - batchInsertCB->dataShareHelper = objectInfo; - - if (argcAsync > argcPromise) { - ret = BatchInsertAsync(env, args, ARGS_TWO, batchInsertCB); - } else { - ret = BatchInsertPromise(env, batchInsertCB); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} - -napi_value BatchInsertAsync( - napi_env env, napi_value *args, const size_t argCallback, DSHelperBatchInsertCB *batchInsertCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || batchInsertCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = 0; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); - if (valuetype == napi_function) { - NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &batchInsertCB->cbBase.cbInfo.callback)); - } - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - BatchInsertExecuteCB, - BatchInsertAsyncCompleteCB, - (void *)batchInsertCB, - &batchInsertCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, batchInsertCB->cbBase.asyncWork)); - napi_value result = 0; - NAPI_CALL(env, napi_get_null(env, &result)); - HILOG_INFO("%{public}s, asyncCallback end.", __func__); - return result; -} - -napi_value BatchInsertPromise(napi_env env, DSHelperBatchInsertCB *batchInsertCB) -{ - HILOG_INFO("%{public}s, promise.", __func__); - if (batchInsertCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - napi_deferred deferred; - napi_value promise = 0; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - batchInsertCB->cbBase.deferred = deferred; - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - BatchInsertExecuteCB, - BatchInsertPromiseCompleteCB, - (void *)batchInsertCB, - &batchInsertCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, batchInsertCB->cbBase.asyncWork)); - HILOG_INFO("%{public}s, promise end.", __func__); - return promise; -} - -void BatchInsertExecuteCB(napi_env env, void *data) -{ - HILOG_INFO("NAPI_BatchInsert, worker pool thread execute."); - DSHelperBatchInsertCB *batchInsertCB = static_cast(data); - if (batchInsertCB->dataShareHelper != nullptr) { - batchInsertCB->execResult = INVALID_PARAMETER; - if (!batchInsertCB->uri.empty()) { - OHOS::Uri uri(batchInsertCB->uri); - batchInsertCB->result = batchInsertCB->dataShareHelper->BatchInsert(uri, batchInsertCB->values); - batchInsertCB->execResult = NO_ERROR; - } else { - HILOG_ERROR("NAPI_BatchInsert, dataShareHelper uri is empyt"); - } - } else { - HILOG_ERROR("NAPI_BatchInsert, dataShareHelper == nullptr"); - } - HILOG_INFO("NAPI_BatchInsert, worker pool thread execute end."); -} - -void BatchInsertAsyncCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_BatchInsert, main event thread complete."); - DSHelperBatchInsertCB *BatchInsertCB = static_cast(data); - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value result[ARGS_TWO] = {nullptr}; - napi_value callResult = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, BatchInsertCB->cbBase.cbInfo.callback, &callback)); - - result[PARAM0] = GetCallbackErrorValue(env, BatchInsertCB->execResult); - napi_create_int32(env, BatchInsertCB->result, &result[PARAM1]); - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); - - if (BatchInsertCB->cbBase.cbInfo.callback != nullptr) { - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, BatchInsertCB->cbBase.cbInfo.callback)); - } - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, BatchInsertCB->cbBase.asyncWork)); - delete BatchInsertCB; - BatchInsertCB = nullptr; - HILOG_INFO("NAPI_BatchInsert, main event thread complete end."); -} - -void BatchInsertPromiseCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_BatchInsertCB, main event thread complete."); - DSHelperBatchInsertCB *BatchInsertCB = static_cast(data); - napi_value result = nullptr; - napi_create_int32(env, BatchInsertCB->result, &result); - NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, BatchInsertCB->cbBase.deferred, result)); - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, BatchInsertCB->cbBase.asyncWork)); - delete BatchInsertCB; - BatchInsertCB = nullptr; - HILOG_INFO("NAPI_BatchInsertCB, main event thread complete end."); -} - -/** - * @brief DataShareHelper NAPI method : insert. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_Query(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s,called", __func__); - DSHelperQueryCB *QueryCB = new (std::nothrow) DSHelperQueryCB; - if (QueryCB == nullptr) { - HILOG_ERROR("%{public}s, QueryCB == nullptr.", __func__); - return WrapVoidToJS(env); - } - QueryCB->cbBase.cbInfo.env = env; - QueryCB->cbBase.asyncWork = nullptr; - QueryCB->cbBase.deferred = nullptr; - QueryCB->cbBase.ability = nullptr; - - napi_value ret = QueryWrap(env, info, QueryCB); - if (ret == nullptr) { - HILOG_ERROR("%{public}s,ret == nullptr", __func__); - if (QueryCB != nullptr) { - delete QueryCB; - QueryCB = nullptr; - } - ret = WrapVoidToJS(env); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} - -/** - * @brief Insert processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param insertCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value QueryWrap(napi_env env, napi_callback_info info, DSHelperQueryCB *queryCB) -{ - HILOG_INFO("%{public}s,called", __func__); - size_t argcAsync = ARGS_FOUR; - const size_t argcPromise = ARGS_THREE; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = 0; - napi_value thisVar = nullptr; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); - if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[PARAM0], &valuetype)); - if (valuetype == napi_string) { - queryCB->uri = NapiValueToStringUtf8(env, args[PARAM0]); - HILOG_INFO("%{public}s,uri=%{public}s", __func__, queryCB->uri.c_str()); - } - - std::vector result; - bool arrayStringbool = false; - arrayStringbool = NapiValueToArrayStringUtf8(env, args[PARAM1], result); - if (!arrayStringbool) { - HILOG_ERROR("%{public}s, The return value of arraystringbool is false", __func__); - } - queryCB->columns = result; - for (size_t i = 0; i < queryCB->columns.size(); i++) { - HILOG_INFO("%{public}s,columns=%{public}s", __func__, queryCB->columns.at(i).c_str()); - } - - UnwrapDataAbilityPredicates(queryCB->predicates, env, args[PARAM2]); - DataShareHelper *objectInfo = nullptr; - napi_unwrap(env, thisVar, (void **)&objectInfo); - HILOG_INFO("%{public}s,DataShareHelper objectInfo = %{public}p", __func__, objectInfo); - queryCB->dataShareHelper = objectInfo; - - if (argcAsync > argcPromise) { - ret = QueryAsync(env, args, ARGS_THREE, queryCB); - } else { - ret = QueryPromise(env, queryCB); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} - -napi_value QueryAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperQueryCB *queryCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || queryCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = 0; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); - if (valuetype == napi_function) { - NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &queryCB->cbBase.cbInfo.callback)); - } - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - QueryExecuteCB, - QueryAsyncCompleteCB, - (void *)queryCB, - &queryCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, queryCB->cbBase.asyncWork)); - napi_value result = 0; - NAPI_CALL(env, napi_get_null(env, &result)); - HILOG_INFO("%{public}s, asyncCallback end.", __func__); - return result; -} - -napi_value QueryPromise(napi_env env, DSHelperQueryCB *queryCB) -{ - HILOG_INFO("%{public}s, promise.", __func__); - if (queryCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - napi_deferred deferred; - napi_value promise = 0; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - queryCB->cbBase.deferred = deferred; - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - QueryExecuteCB, - QueryPromiseCompleteCB, - (void *)queryCB, - &queryCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, queryCB->cbBase.asyncWork)); - HILOG_INFO("%{public}s, promise end.", __func__); - return promise; -} - -void QueryPromiseCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_DSHelperQueryCB, main event thread complete."); - DSHelperQueryCB *QueryCB = static_cast(data); - napi_value result = nullptr; - result = WrapResultSet(env, QueryCB->result); - NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, QueryCB->cbBase.deferred, result)); - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, QueryCB->cbBase.asyncWork)); - delete QueryCB; - QueryCB = nullptr; - HILOG_INFO("NAPI_DSHelperQueryCB, main event thread complete end."); -} - -void QueryExecuteCB(napi_env env, void *data) -{ - HILOG_INFO("NAPI_Query, worker pool thread execute."); - DSHelperQueryCB *queryCB = static_cast(data); - if (queryCB->dataShareHelper != nullptr) { - queryCB->execResult = INVALID_PARAMETER; - if (!queryCB->uri.empty()) { - OHOS::Uri uri(queryCB->uri); - auto resultset = queryCB->dataShareHelper->Query(uri, queryCB->columns, queryCB->predicates); - if (resultset != nullptr) { - queryCB->result = resultset; - queryCB->execResult = NO_ERROR; - } else { - HILOG_INFO("NAPI_Query, resultset == nullptr."); - } - } else { - HILOG_ERROR("NAPI_Query, dataShareHelper uri is empty"); - } - } else { - HILOG_ERROR("NAPI_Query, dataShareHelper == nullptr"); - } - HILOG_INFO("NAPI_Query, worker pool thread execute end."); -} - -void QueryAsyncCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_Query, main event thread complete."); - DSHelperQueryCB *queryCB = static_cast(data); - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value result[ARGS_TWO] = {nullptr}; - napi_value callResult = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, queryCB->cbBase.cbInfo.callback, &callback)); - - result[PARAM0] = GetCallbackErrorValue(env, queryCB->execResult); - result[PARAM1] = WrapResultSet(env, queryCB->result); - - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); - - if (queryCB->cbBase.cbInfo.callback != nullptr) { - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, queryCB->cbBase.cbInfo.callback)); - } - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, queryCB->cbBase.asyncWork)); - delete queryCB; - queryCB = nullptr; - HILOG_INFO("NAPI_Query, main event thread complete end."); -} - -napi_value WrapResultSet(napi_env env, const std::shared_ptr &resultSet) -{ - HILOG_INFO("%{public}s,called", __func__); - if (resultSet == nullptr) { - HILOG_ERROR("%{public}s, input parameter resultSet is nullptr", __func__); - return WrapVoidToJS(env); - } - - return RdbJsKit::ResultSetProxy::NewInstance(env, resultSet); -} - -napi_value NAPI_Release(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s,called", __func__); - DSHelperReleaseCB *releaseCB = new (std::nothrow) DSHelperReleaseCB; - if (releaseCB == nullptr) { - HILOG_ERROR("%{public}s, releaseCB == nullptr.", __func__); - return WrapVoidToJS(env); - } - releaseCB->cbBase.cbInfo.env = env; - releaseCB->cbBase.asyncWork = nullptr; - releaseCB->cbBase.deferred = nullptr; - - napi_value ret = ReleaseWrap(env, info, releaseCB); - if (ret == nullptr) { - HILOG_ERROR("%{public}s,ret == nullptr", __func__); - if (releaseCB != nullptr) { - delete releaseCB; - releaseCB = nullptr; - } - ret = WrapVoidToJS(env); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} - -napi_value ReleaseWrap(napi_env env, napi_callback_info info, DSHelperReleaseCB *releaseCB) -{ - HILOG_INFO("%{public}s,called", __func__); - size_t argcAsync = ARGS_ONE; - const size_t argcPromise = ARGS_ZERO; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = nullptr; - napi_value thisVar = nullptr; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, &thisVar, nullptr)); - if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - DataShareHelper *objectInfo = nullptr; - napi_unwrap(env, thisVar, (void **)&objectInfo); - HILOG_INFO("DataShareHelper ReleaseWrap objectInfo = %{public}p", objectInfo); - releaseCB->dataShareHelper = objectInfo; - - if (argcAsync > argcPromise) { - ret = ReleaseAsync(env, args, PARAM0, releaseCB); - } else { - ret = ReleasePromise(env, releaseCB); - } - HILOG_INFO("%{public}s,end", __func__); - return ret; -} - -napi_value ReleaseAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperReleaseCB *releaseCB) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || releaseCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = 0; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); - if (valuetype == napi_function) { - NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &releaseCB->cbBase.cbInfo.callback)); - } - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - ReleaseExecuteCB, - ReleaseAsyncCompleteCB, - (void *)releaseCB, - &releaseCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, releaseCB->cbBase.asyncWork)); - napi_value result = 0; - NAPI_CALL(env, napi_get_null(env, &result)); - HILOG_INFO("%{public}s, asyncCallback end.", __func__); - return result; -} - -napi_value ReleasePromise(napi_env env, DSHelperReleaseCB *releaseCB) -{ - HILOG_INFO("%{public}s, promise.", __func__); - if (releaseCB == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - napi_deferred deferred; - napi_value promise = 0; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - releaseCB->cbBase.deferred = deferred; - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - ReleaseExecuteCB, - ReleasePromiseCompleteCB, - (void *)releaseCB, - &releaseCB->cbBase.asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, releaseCB->cbBase.asyncWork)); - HILOG_INFO("%{public}s, promise end.", __func__); - return promise; -} - -void ReleaseExecuteCB(napi_env env, void *data) -{ - HILOG_INFO("NAPI_Release, worker pool thread execute."); - DSHelperReleaseCB *releaseCB = static_cast(data); - if (releaseCB->dataShareHelper != nullptr) { - releaseCB->result = releaseCB->dataShareHelper->Release(); - } else { - HILOG_ERROR("NAPI_Release, dataShareHelper == nullptr"); - } - HILOG_INFO("NAPI_Release, worker pool thread execute end."); -} - -void ReleaseAsyncCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_Release, main event thread complete."); - DSHelperReleaseCB *releaseCB = static_cast(data); - napi_value callback = nullptr; - napi_value undefined = nullptr; - napi_value result[ARGS_TWO] = {nullptr}; - napi_value callResult = nullptr; - NAPI_CALL_RETURN_VOID(env, napi_get_undefined(env, &undefined)); - NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, releaseCB->cbBase.cbInfo.callback, &callback)); - - result[PARAM0] = GetCallbackErrorValue(env, NO_ERROR); - napi_get_boolean(env, releaseCB->result, &result[PARAM1]); - NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_TWO, &result[PARAM0], &callResult)); - - if (releaseCB->cbBase.cbInfo.callback != nullptr) { - NAPI_CALL_RETURN_VOID(env, napi_delete_reference(env, releaseCB->cbBase.cbInfo.callback)); - } - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, releaseCB->cbBase.asyncWork)); - delete releaseCB; - releaseCB = nullptr; - HILOG_INFO("NAPI_Release, main event thread complete end."); -} - -void ReleasePromiseCompleteCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("NAPI_Release, main event thread complete."); - DSHelperReleaseCB *releaseCB = static_cast(data); - napi_value result = nullptr; - napi_get_boolean(env, releaseCB->result, &result); - NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, releaseCB->cbBase.deferred, result)); - NAPI_CALL_RETURN_VOID(env, napi_delete_async_work(env, releaseCB->cbBase.asyncWork)); - delete releaseCB; - releaseCB = nullptr; - HILOG_INFO("NAPI_Release, main event thread complete end."); -} -} // namespace AppExecFwk -} // namespace OHOS diff --git a/interfaces/kits/napi/aafwk/dataShare/napi_datashare_helper.h b/interfaces/kits/napi/aafwk/dataShare/napi_datashare_helper.h deleted file mode 100644 index 4cbaeafaf183dd74c3ad13fab596677fe860a8b4..0000000000000000000000000000000000000000 --- a/interfaces/kits/napi/aafwk/dataShare/napi_datashare_helper.h +++ /dev/null @@ -1,426 +0,0 @@ -/* - * Copyright (c) 2022 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. - */ - -#ifndef OHOS_APPEXECFWK_NAPI_DATASHARE_HELPER_H -#define OHOS_APPEXECFWK_NAPI_DATASHARE_HELPER_H -#include "data_ability_observer_stub.h" -#include "data_share_common.h" - -namespace OHOS { -namespace AppExecFwk { -class NAPIDataShareObserver : public AAFwk::DataAbilityObserverStub { -public: - void OnChange() override; - void SetEnv(const napi_env &env); - void SetCallbackRef(const napi_ref &ref); - void ReleaseJSCallback(); - - void SetAssociatedObject(DSHelperOnOffCB* object); - const DSHelperOnOffCB* GetAssociatedObject(void); - - void ChangeWorkPre(); - void ChangeWorkRun(); - void ChangeWorkInt(); - void ChangeWorkPreDone(); - void ChangeWorkRunDone(); - int GetWorkPre(); - int GetWorkRun(); - int GetWorkInt(); - -private: - napi_env env_ = nullptr; - napi_ref ref_ = nullptr; - DSHelperOnOffCB* onCB_ = nullptr; - int workPre_ = 0; - int workRun_ = 0; - int intrust_ = 0; - std::mutex mutex_; -}; - -/** - * @brief DataShareHelper NAPI module registration. - * - * @param env The environment that the Node-API call is invoked under. - * @param exports An empty object via the exports parameter as a convenience. - * - * @return The return value from Init is treated as the exports object for the module. - */ -napi_value DataShareHelperInit(napi_env env, napi_value exports); -napi_value DataShareHelperConstructor(napi_env env, napi_callback_info info); - -/** - * @brief DataShareHelper NAPI method : insert. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_Insert(napi_env env, napi_callback_info info); - -/** - * @brief Insert processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param insertCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value InsertWrap(napi_env env, napi_callback_info info, DSHelperInsertCB *insertCB); - -/** - * @brief Insert Async. - * - * @param env The environment that the Node-API call is invoked under. - * @param args Indicates the arguments passed into the callback. - * @param argcPromise Asynchronous data processing. - * @param insertCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value InsertAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperInsertCB *insertCB); - -/** - * @brief Insert Promise. - * - * @param env The environment that the Node-API call is invoked under. - * @param insertCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value InsertPromise(napi_env env, DSHelperInsertCB *insertCB); - -/** - * @brief Insert asynchronous processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void InsertExecuteCB(napi_env env, void *data); - -/** - * @brief The callback at the end of the asynchronous callback. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void InsertAsyncCompleteCB(napi_env env, napi_status status, void *data); - -/** - * @brief The callback at the end of the Promise callback. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void InsertPromiseCompleteCB(napi_env env, napi_status status, void *data); - -/** - * @brief DataShareHelper NAPI method : notifyChange. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_NotifyChange(napi_env env, napi_callback_info info); - -/** - * @brief NotifyChange processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param notifyChangeCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value NotifyChangeWrap(napi_env env, napi_callback_info info, DSHelperNotifyChangeCB *notifyChangeCB); - -/** - * @brief NotifyChange Async. - * - * @param env The environment that the Node-API call is invoked under. - * @param args Indicates the arguments passed into the callback. - * @param argcPromise Asynchronous data processing. - * @param notifyChangeCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value NotifyChangeAsync( - napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DSHelperNotifyChangeCB *notifyChangeCB); - -/** - * @brief NotifyChange Promise. - * - * @param env The environment that the Node-API call is invoked under. - * @param notifyChangeCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value NotifyChangePromise(napi_env env, DSHelperNotifyChangeCB *notifyChangeCB); - -/** - * @brief NotifyChange asynchronous processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void NotifyChangeExecuteCB(napi_env env, void *data); - -/** - * @brief The callback at the end of the asynchronous callback. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void NotifyChangeAsyncCompleteCB(napi_env env, napi_status status, void *data); - -/** - * @brief The callback at the end of the Promise callback. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void NotifyChangePromiseCompleteCB(napi_env env, napi_status status, void *data); - -/** - * @brief DataShareHelper NAPI method : on. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_Register(napi_env env, napi_callback_info info); - -/** - * @brief On processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param insertCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value RegisterWrap(napi_env env, napi_callback_info info, DSHelperOnOffCB *insertCB); - -/** - * @brief On Async. - * - * @param env The environment that the Node-API call is invoked under. - * @param args Indicates the arguments passed into the callback. - * @param argcPromise Asynchronous data processing. - * @param insertCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value RegisterAsync( - napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DSHelperOnOffCB *insertCB); - -/** - * @brief On asynchronous processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void RegisterExecuteCB(napi_env env, void *data); -void RegisterCompleteCB(napi_env env, napi_status status, void *data); - -/** - * @brief DataShareHelper NAPI method : off. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_UnRegister(napi_env env, napi_callback_info info); - -/** - * @brief Off processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param insertCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value UnRegisterWrap(napi_env env, napi_callback_info info, DSHelperOnOffCB *insertCB); - -/** - * @brief Off Async. - * - * @param env The environment that the Node-API call is invoked under. - * @param args Indicates the arguments passed into the callback. - * @param argcPromise Asynchronous data processing. - * @param insertCB Process data asynchronously. - * - * @return Return JS data successfully, otherwise return nullptr. - */ -napi_value UnRegisterAsync( - napi_env env, napi_value *args, size_t argcAsync, const size_t argcPromise, DSHelperOnOffCB *insertCB); - -/** - * @brief Off asynchronous processing function. - * - * @param env The environment that the Node-API call is invoked under. - * @param data Point to asynchronous processing of data. - */ -void UnRegisterExecuteCB(napi_env env, void *data); -void UnRegisterCompleteCB(napi_env env, napi_status status, void *data); -void FindRegisterObs(napi_env env, DSHelperOnOffCB *data); -/** - * @brief Parse the ValuesBucket parameters. - * - * @param param Indicates the want parameters saved the parse result. - * @param env The environment that the Node-API call is invoked under. - * @param args Indicates the arguments passed into the callback. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value UnwrapValuesBucket(std::string &value, napi_env env, napi_value args); - -static std::vector registerInstances_; -napi_value NAPI_Release(napi_env env, napi_callback_info info); - -napi_value ReleaseWrap(napi_env env, napi_callback_info info, DSHelperReleaseCB *releaseCB); - -napi_value ReleaseAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperReleaseCB *releaseCB); - -napi_value ReleasePromise(napi_env env, DSHelperReleaseCB *releaseCB); - -void ReleaseExecuteCB(napi_env env, void *data); - -void ReleaseAsyncCompleteCB(napi_env env, napi_status status, void *data); - -void ReleasePromiseCompleteCB(napi_env env, napi_status status, void *data); - -napi_value NAPI_GetType(napi_env env, napi_callback_info info); -napi_value NAPI_GetType(napi_env env, napi_callback_info info); -napi_value GetTypeWrap(napi_env env, napi_callback_info info, DSHelperGetTypeCB *gettypeCB); -napi_value GetTypeAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperGetTypeCB *gettypeCB); -napi_value GetTypePromise(napi_env env, DSHelperGetTypeCB *gettypeCB); -void GetTypeExecuteCB(napi_env env, void *data); -void GetTypeAsyncCompleteCB(napi_env env, napi_status status, void *data); -void GetTypePromiseCompleteCB(napi_env env, napi_status status, void *data); - -napi_value NAPI_GetFileTypes(napi_env env, napi_callback_info info); -napi_value NAPI_GetFileTypes(napi_env env, napi_callback_info info); -napi_value GetFileTypesWrap(napi_env env, napi_callback_info info, DSHelperGetFileTypesCB *getfiletypesCB); -napi_value GetFileTypesAsync( - napi_env env, napi_value *args, const size_t argCallback, DSHelperGetFileTypesCB *getfiletypesCB); -napi_value GetFileTypesPromise(napi_env env, DSHelperGetFileTypesCB *getfiletypesCB); -void GetFileTypesExecuteCB(napi_env env, void *data); -void GetFileTypesAsyncCompleteCB(napi_env env, napi_status status, void *data); -void GetFileTypesPromiseCompleteCB(napi_env env, napi_status status, void *data); -napi_value WrapGetFileTypesCB(napi_env env, const DSHelperGetFileTypesCB &getfiletypesCB); - -napi_value NAPI_NormalizeUri(napi_env env, napi_callback_info info); -napi_value NAPI_NormalizeUri(napi_env env, napi_callback_info info); -napi_value NormalizeUriWrap(napi_env env, napi_callback_info info, DSHelperNormalizeUriCB *normalizeuriCB); -napi_value NormalizeUriAsync( - napi_env env, napi_value *args, const size_t argCallback, DSHelperNormalizeUriCB *normalizeuriCB); -napi_value NormalizeUriPromise(napi_env env, DSHelperNormalizeUriCB *normalizeuriCB); -void NormalizeUriExecuteCB(napi_env env, void *data); -void NormalizeUriAsyncCompleteCB(napi_env env, napi_status status, void *data); -void NormalizeUriPromiseCompleteCB(napi_env env, napi_status status, void *data); - -napi_value NAPI_DenormalizeUri(napi_env env, napi_callback_info info); -napi_value NAPI_DenormalizeUri(napi_env env, napi_callback_info info); -napi_value DenormalizeUriWrap(napi_env env, napi_callback_info info, DSHelperDenormalizeUriCB *denormalizeuriCB); -napi_value DenormalizeUriAsync( - napi_env env, napi_value *args, const size_t argCallback, DSHelperDenormalizeUriCB *denormalizeuriCB); -napi_value DenormalizeUriPromise(napi_env env, DSHelperDenormalizeUriCB *denormalizeuriCB); -void DenormalizeUriExecuteCB(napi_env env, void *data); -void DenormalizeUriAsyncCompleteCB(napi_env env, napi_status status, void *data); -void DenormalizeUriPromiseCompleteCB(napi_env env, napi_status status, void *data); - -napi_value NAPI_Delete(napi_env env, napi_callback_info info); - -napi_value DeleteWrap(napi_env env, napi_callback_info info, DSHelperDeleteCB *deleteCB); -napi_value DeleteAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperDeleteCB *deleteCB); - -napi_value DeletePromise(napi_env env, DSHelperDeleteCB *deleteCB); - -void DeleteExecuteCB(napi_env env, void *data); - -void DeleteAsyncCompleteCB(napi_env env, napi_status status, void *data); - -void DeletePromiseCompleteCB(napi_env env, napi_status status, void *data); - -napi_value NAPI_Update(napi_env env, napi_callback_info info); - -napi_value UpdateWrap(napi_env env, napi_callback_info info, DSHelperUpdateCB *updateCB); -napi_value UpdateAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperUpdateCB *updateCB); - -napi_value UpdatePromise(napi_env env, DSHelperUpdateCB *updateCB); - -void UpdateExecuteCB(napi_env env, void *data); - -void UpdateAsyncCompleteCB(napi_env env, napi_status status, void *data); - -void UpdatePromiseCompleteCB(napi_env env, napi_status status, void *data); - -napi_value NAPI_OpenFile(napi_env env, napi_callback_info info); - -napi_value OpenFileWrap(napi_env env, napi_callback_info info, DSHelperOpenFileCB *openFileCB); -napi_value OpenFileAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperOpenFileCB *openFileCB); - -napi_value OpenFilePromise(napi_env env, DSHelperOpenFileCB *openFileCB); - -void OpenFileExecuteCB(napi_env env, void *data); - -void OpenFileAsyncCompleteCB(napi_env env, napi_status status, void *data); - -void OpenFilePromiseCompleteCB(napi_env env, napi_status status, void *data); - -napi_value NAPI_BatchInsert(napi_env env, napi_callback_info info); - -napi_value BatchInsertWrap(napi_env env, napi_callback_info info, DSHelperBatchInsertCB *batchInsertCB); -napi_value BatchInsertAsync( - napi_env env, napi_value *args, const size_t argCallback, DSHelperBatchInsertCB *batchInsertCB); - -napi_value BatchInsertPromise(napi_env env, DSHelperBatchInsertCB *batchInsertCB); - -void BatchInsertExecuteCB(napi_env env, void *data); - -void BatchInsertAsyncCompleteCB(napi_env env, napi_status status, void *data); - -void BatchInsertPromiseCompleteCB(napi_env env, napi_status status, void *data); - -std::vector NapiValueObject(napi_env env, napi_value param); - -bool UnwrapArrayObjectFromJS(napi_env env, napi_value param, std::vector &value); - -napi_value NAPI_Query(napi_env env, napi_callback_info info); - -napi_value QueryWrap(napi_env env, napi_callback_info info, DSHelperQueryCB *queryCB); - -napi_value QueryAsync(napi_env env, napi_value *args, const size_t argCallback, DSHelperQueryCB *queryCB); - -napi_value QueryPromise(napi_env env, DSHelperQueryCB *queryCB); - -void QueryExecuteCB(napi_env env, void *data); - -void QueryAsyncCompleteCB(napi_env env, napi_status status, void *data); - -void QueryPromiseCompleteCB(napi_env env, napi_status status, void *data); - -napi_value WrapResultSet(napi_env env, const std::shared_ptr &resultSet); - -void AnalysisValuesBucket(NativeRdb::ValuesBucket &value, const napi_env &env, const napi_value &arg); -void SetValuesBucketObject( - NativeRdb::ValuesBucket &valuesBucket, const napi_env &env, std::string keyStr, napi_value value); - -void UnwrapDataAbilityPredicates(NativeRdb::DataAbilityPredicates &predicates, napi_env env, napi_value value); -} // namespace AppExecFwk -} // namespace OHOS -#endif /* OHOS_APPEXECFWK_NAPI_DATASHARE_HELPER_H */ diff --git a/interfaces/kits/napi/aafwk/dataShare/native_datashare_module.cpp b/interfaces/kits/napi/aafwk/dataShare/native_datashare_module.cpp deleted file mode 100644 index 078fee397f31628b7d2e4ac358ab6447b257b8c1..0000000000000000000000000000000000000000 --- a/interfaces/kits/napi/aafwk/dataShare/native_datashare_module.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2022 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 "napi_datashare_helper.h" -#include "napi/native_api.h" -#include "napi/native_node_api.h" - -namespace OHOS { -namespace AppExecFwk { -EXTERN_C_START -/* - * The module initialization. - */ -static napi_value Init(napi_env env, napi_value exports) -{ - DataShareHelperInit(env, exports); - return exports; -} -EXTERN_C_END - -/* - * The module definition. - */ -static napi_module _module = { - .nm_version = 1, - .nm_flags = 0, - .nm_filename = nullptr, - .nm_register_func = Init, - .nm_modname = "data.dataShare", - .nm_priv = ((void *)0), - .reserved = {0} -}; - -/* - * The module registration. - */ -extern "C" __attribute__((constructor)) void RegisterModule(void) -{ - napi_module_register(&_module); -} -} // namespace AppExecFwk -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/BUILD.gn b/interfaces/kits/napi/aafwk/inner/napi_common/BUILD.gn index e3904f5ff160919524f5b74c747bf308d532c1fb..aff79d10f1b410b9f906fc6dc86d20f26b94b09d 100644 --- a/interfaces/kits/napi/aafwk/inner/napi_common/BUILD.gn +++ b/interfaces/kits/napi/aafwk/inner/napi_common/BUILD.gn @@ -30,7 +30,6 @@ ohos_shared_library("napi_common") { ] deps = [ - "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//foundation/aafwk/standard/interfaces/innerkits/base:base", diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/feature_ability_common.h b/interfaces/kits/napi/aafwk/inner/napi_common/feature_ability_common.h index 6738cc3a15cf35d11cfc3b0efa5e51adca525255..5441466206d55018796e8ed033023cf83520c0a8 100644 --- a/interfaces/kits/napi/aafwk/inner/napi_common/feature_ability_common.h +++ b/interfaces/kits/napi/aafwk/inner/napi_common/feature_ability_common.h @@ -58,7 +58,6 @@ struct AsyncCallbackInfo { napi_async_work asyncWork = nullptr; napi_deferred deferred = nullptr; Ability *ability = nullptr; - Notification::WantAgent::WantAgent *wantAgent = nullptr; CallAbilityParam param; CallbackInfo aceCallback; bool native_result; diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.cpp b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.cpp index a5b9eda80d3fab79b267d07209fa8e21e40ffad3..71d51480c3887c7cb8230f16a2dc033f858265b8 100644 --- a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.cpp +++ b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.cpp @@ -3501,333 +3501,5 @@ napi_value AcquireDataAbilityHelperWrap(napi_env env, napi_callback_info info, D HILOG_INFO("%{public}s,end", __func__); return result; } - -napi_value UnwrapParamForWantAgent(napi_env &env, napi_value &args, Notification::WantAgent::WantAgent *&wantAgent) -{ - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); - napi_value wantAgentParam = nullptr; - napi_value result = nullptr; - - bool hasProperty = false; - NAPI_CALL(env, napi_has_named_property(env, args, "wantAgent", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, args, "wantAgent", &wantAgentParam); - NAPI_CALL(env, napi_typeof(env, wantAgentParam, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); - napi_unwrap(env, wantAgentParam, (void **)&wantAgent); - } - - napi_get_null(env, &result); - return result; -} - -void StartBackgroundRunningExecuteCB(napi_env env, void *data) -{ - HILOG_INFO("%{public}s called.", __func__); - AsyncCallbackInfo *asyncCallbackInfo = (AsyncCallbackInfo *)data; - if (asyncCallbackInfo == nullptr) { - HILOG_ERROR("%{public}s asyncCallbackInfo == nullptr", __func__); - return; - } - if (asyncCallbackInfo->errCode == NAPI_ERR_PARAM_INVALID) { - HILOG_ERROR("parse input param failed"); - return; - } - if (asyncCallbackInfo->ability == nullptr) { - asyncCallbackInfo->errCode = NAPI_ERR_ACE_ABILITY; - HILOG_ERROR("%{public}s ability == nullptr", __func__); - return; - } - const std::shared_ptr info = asyncCallbackInfo->ability->GetAbilityInfo(); - if (info == nullptr) { - HILOG_ERROR("abilityinfo is null"); - asyncCallbackInfo->errCode = NAPI_ERR_ACE_ABILITY; - return; - } - - asyncCallbackInfo->errCode = asyncCallbackInfo->ability->StartBackgroundRunning(*asyncCallbackInfo->wantAgent); - - HILOG_INFO("%{public}s end.", __func__); -} - -void BackgroundRunningCallbackCompletedCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("%{public}s called.", __func__); - AsyncCallbackInfo *asyncCallbackInfo = static_cast(data); - napi_value callback = 0; - napi_value undefined = 0; - napi_value result[ARGS_TWO] = {0}; - napi_value callResult = 0; - napi_get_undefined(env, &undefined); - if (asyncCallbackInfo->errCode == NAPI_ERR_NO_ERROR) { - result[0] = WrapUndefinedToJS(env); - napi_create_int32(env, 0, &result[1]); - } else { - result[1] = WrapUndefinedToJS(env); - result[0] = GetCallbackErrorValue(env, asyncCallbackInfo->errCode); - } - - napi_get_reference_value(env, asyncCallbackInfo->cbInfo.callback, &callback); - napi_call_function(env, undefined, callback, ARGS_TWO, result, &callResult); - - if (asyncCallbackInfo->cbInfo.callback != nullptr) { - napi_delete_reference(env, asyncCallbackInfo->cbInfo.callback); - } - napi_delete_async_work(env, asyncCallbackInfo->asyncWork); - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - HILOG_INFO("%{public}s end.", __func__); -} - -void BackgroundRunningPromiseCompletedCB(napi_env env, napi_status status, void *data) -{ - HILOG_INFO("%{public}s called.", __func__); - AsyncCallbackInfo *asyncCallbackInfo = static_cast(data); - napi_value result = 0; - if (asyncCallbackInfo->errCode == NAPI_ERR_NO_ERROR) { - napi_create_int32(env, 0, &result); - napi_resolve_deferred(env, asyncCallbackInfo->deferred, result); - } else { - result = GetCallbackErrorValue(env, asyncCallbackInfo->errCode); - napi_reject_deferred(env, asyncCallbackInfo->deferred, result); - } - - napi_delete_async_work(env, asyncCallbackInfo->asyncWork); - HILOG_INFO("%{public}s, end.", __func__); - delete asyncCallbackInfo; -} - -napi_value StartBackgroundRunningAsync( - napi_env env, napi_value *args, const size_t argCallback, AsyncCallbackInfo *asyncCallbackInfo) -{ - HILOG_INFO("%{public}s asyncCallback.", __func__); - if (args == nullptr || asyncCallbackInfo == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = 0; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - - napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, args[argCallback], &valuetype)); - if (valuetype == napi_function) { - NAPI_CALL(env, napi_create_reference(env, args[argCallback], 1, &asyncCallbackInfo->cbInfo.callback)); - } - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - StartBackgroundRunningExecuteCB, - BackgroundRunningCallbackCompletedCB, - (void *)asyncCallbackInfo, - &asyncCallbackInfo->asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); - - HILOG_INFO("%{public}s asyncCallback end.", __func__); - return WrapVoidToJS(env); -} - -napi_value StartBackgroundRunningPromise(napi_env env, AsyncCallbackInfo *asyncCallbackInfo) -{ - HILOG_INFO("%{public}s, promise.", __func__); - if (asyncCallbackInfo == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName; - NAPI_CALL(env, napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName)); - napi_deferred deferred; - napi_value promise = 0; - NAPI_CALL(env, napi_create_promise(env, &deferred, &promise)); - asyncCallbackInfo->deferred = deferred; - - NAPI_CALL(env, - napi_create_async_work(env, - nullptr, - resourceName, - StartBackgroundRunningExecuteCB, - BackgroundRunningPromiseCompletedCB, - (void *)asyncCallbackInfo, - &asyncCallbackInfo->asyncWork)); - NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); - HILOG_INFO("%{public}s, end.", __func__); - return promise; -} - -napi_value StartBackgroundRunningWrap(napi_env &env, napi_callback_info &info, AsyncCallbackInfo *asyncCallbackInfo) -{ - HILOG_INFO("%{public}s called.", __func__); - size_t paramNums = 3; - const size_t minParamNums = 2; - const size_t maxParamNums = 3; - napi_value args[maxParamNums] = {nullptr}; - napi_value ret = 0; - - NAPI_CALL(env, napi_get_cb_info(env, info, ¶mNums, args, NULL, NULL)); - - if (paramNums < minParamNums || paramNums > maxParamNums) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - if (UnwrapParamForWantAgent(env, args[1], asyncCallbackInfo->wantAgent) == nullptr) { - asyncCallbackInfo->errCode = NAPI_ERR_PARAM_INVALID; - } - - if (paramNums == maxParamNums) { - ret = StartBackgroundRunningAsync(env, args, maxParamNums - 1, asyncCallbackInfo); - } else { - ret = StartBackgroundRunningPromise(env, asyncCallbackInfo); - } - - HILOG_INFO("%{public}s end.", __func__); - return ret; -} - -napi_value NAPI_StartBackgroundRunningCommon(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s called.", __func__); - AsyncCallbackInfo *asyncCallbackInfo = CreateAsyncCallbackInfo(env); - if (asyncCallbackInfo == nullptr) { - HILOG_ERROR("%{public}s asyncCallbackInfo == nullpter", __func__); - return WrapVoidToJS(env); - } - - asyncCallbackInfo->errCode = NAPI_ERR_NO_ERROR; - napi_value ret = StartBackgroundRunningWrap(env, info, asyncCallbackInfo); - if (ret == nullptr) { - HILOG_ERROR("%{public}s ret == nullpter", __func__); - if (asyncCallbackInfo != nullptr) { - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - } - ret = WrapVoidToJS(env); - } - HILOG_INFO("%{public}s end.", __func__); - return ret; -} - -void CancelBackgroundRunningExecuteCB(napi_env env, void *data) -{ - HILOG_INFO("NAPI_PACancelBackgroundRunning, worker pool thread execute."); - AsyncCallbackInfo *asyncCallbackInfo = static_cast(data); - if (asyncCallbackInfo->ability != nullptr) { - asyncCallbackInfo->ability->StopBackgroundRunning(); - } else { - HILOG_ERROR("NAPI_PACancelBackgroundRunning, ability == nullptr"); - } - HILOG_INFO("NAPI_PACancelBackgroundRunning, worker pool thread execute end."); -} - -napi_value CancelBackgroundRunningAsync( - napi_env env, napi_value *args, const size_t argCallback, AsyncCallbackInfo *asyncCallbackInfo) -{ - HILOG_INFO("%{public}s, asyncCallback.", __func__); - if (args == nullptr || asyncCallbackInfo == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = 0; - napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); - - napi_valuetype valuetype = napi_undefined; - napi_typeof(env, args[argCallback], &valuetype); - if (valuetype == napi_function) { - napi_create_reference(env, args[argCallback], 1, &asyncCallbackInfo->cbInfo.callback); - } - - napi_create_async_work( - env, - nullptr, - resourceName, - CancelBackgroundRunningExecuteCB, - BackgroundRunningCallbackCompletedCB, - (void *)asyncCallbackInfo, - &asyncCallbackInfo->asyncWork); - napi_queue_async_work(env, asyncCallbackInfo->asyncWork); - napi_value result = 0; - napi_get_null(env, &result); - HILOG_INFO("%{public}s, asyncCallback end", __func__); - return result; -} - -napi_value CancelBackgroundRunningPromise(napi_env env, AsyncCallbackInfo *asyncCallbackInfo) -{ - HILOG_INFO("%{public}s, promise.", __func__); - if (asyncCallbackInfo == nullptr) { - HILOG_ERROR("%{public}s, param == nullptr.", __func__); - return nullptr; - } - napi_value resourceName = 0; - napi_create_string_latin1(env, __func__, NAPI_AUTO_LENGTH, &resourceName); - napi_deferred deferred; - napi_value promise = 0; - napi_create_promise(env, &deferred, &promise); - - asyncCallbackInfo->deferred = deferred; - - napi_create_async_work( - env, - nullptr, - resourceName, - CancelBackgroundRunningExecuteCB, - BackgroundRunningPromiseCompletedCB, - (void *)asyncCallbackInfo, - &asyncCallbackInfo->asyncWork); - napi_queue_async_work(env, asyncCallbackInfo->asyncWork); - HILOG_INFO("%{public}s, promise end", __func__); - return promise; -} - -napi_value CancelBackgroundRunningWrap(napi_env &env, napi_callback_info &info, AsyncCallbackInfo *asyncCallbackInfo) -{ - HILOG_INFO("%{public}s called.", __func__); - size_t argcAsync = 1; - const size_t argcPromise = 0; - const size_t argCountWithAsync = argcPromise + ARGS_ASYNC_COUNT; - napi_value args[ARGS_MAX_COUNT] = {nullptr}; - napi_value ret = 0; - - NAPI_CALL(env, napi_get_cb_info(env, info, &argcAsync, args, NULL, NULL)); - if (argcAsync > argCountWithAsync || argcAsync > ARGS_MAX_COUNT) { - HILOG_ERROR("%{public}s, Wrong argument count.", __func__); - return nullptr; - } - - if (argcAsync > argcPromise) { - ret = CancelBackgroundRunningAsync(env, args, 0, asyncCallbackInfo); - } else { - ret = CancelBackgroundRunningPromise(env, asyncCallbackInfo); - } - - HILOG_INFO("%{public}s end.", __func__); - return ret; -} - -napi_value NAPI_CancelBackgroundRunningCommon(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s called.", __func__); - AsyncCallbackInfo *asyncCallbackInfo = CreateAsyncCallbackInfo(env); - if (asyncCallbackInfo == nullptr) { - HILOG_ERROR("%{public}s asyncCallbackInfo == nullpter", __func__); - return WrapVoidToJS(env); - } - - asyncCallbackInfo->errCode = NAPI_ERR_NO_ERROR; - napi_value ret = CancelBackgroundRunningWrap(env, info, asyncCallbackInfo); - if (ret == nullptr) { - HILOG_ERROR("%{public}s ret == nullpter", __func__); - if (asyncCallbackInfo != nullptr) { - delete asyncCallbackInfo; - asyncCallbackInfo = nullptr; - } - ret = WrapVoidToJS(env); - } - HILOG_INFO("%{public}s end.", __func__); - return ret; -} } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.h b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.h index c15bb499a33e9a60b12ae6695c2c7f6007fe32f4..293bf2024146ca05df5f83b876d0294ebecf9d18 100644 --- a/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.h +++ b/interfaces/kits/napi/aafwk/inner/napi_common/napi_common_ability.h @@ -26,7 +26,7 @@ const std::int32_t STR_MAX_SIZE = 128; napi_value *GetGlobalClassContext(void); -napi_status SaveGlobalDataAbilityHelper(napi_env env, napi_value constructor); +napi_status SaveGlobalDataAbilityHelper(napi_env env, napi_value constructor); napi_value GetGlobalDataAbilityHelper(napi_env env); bool& GetDataAbilityHelperStatus(); @@ -227,26 +227,6 @@ napi_value NAPI_AcquireDataAbilityHelperCommon(napi_env env, napi_callback_info napi_value ConvertAbilityInfo(napi_env env, const AbilityInfo &abilityInfo); -/** - * @brief start background running. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_StartBackgroundRunningCommon(napi_env env, napi_callback_info info); - -/** - * @brief cancel background running. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_CancelBackgroundRunningCommon(napi_env env, napi_callback_info info); - bool CheckAbilityType(const CBBase *cbBase); struct ConnecttionKey { diff --git a/interfaces/kits/napi/aafwk/mission_manager/mission_manager.cpp b/interfaces/kits/napi/aafwk/mission_manager/mission_manager.cpp index d7e9f78a1d5e6b2a80f61c24b4e3418119dc93f8..da1fb0fdefd2578c4ccad5de89e31a4aca26e130 100644 --- a/interfaces/kits/napi/aafwk/mission_manager/mission_manager.cpp +++ b/interfaces/kits/napi/aafwk/mission_manager/mission_manager.cpp @@ -23,15 +23,12 @@ #include "js_mission_listener.h" #include "js_runtime_utils.h" #include "mission_snapshot.h" -#include "napi_common_start_options.h" #include "pixel_map_napi.h" -#include "start_options.h" #include namespace OHOS { namespace AbilityRuntime { -constexpr size_t ARGC_ONE = 1; using namespace OHOS::AppExecFwk; using AbilityManagerClient = AAFwk::AbilityManagerClient; namespace { @@ -455,23 +452,14 @@ private: HILOG_ERROR("Parse missionId failed"); errCode = ERR_NOT_OK; } - decltype(info.argc) unwrapArgc = 1; - - AAFwk::StartOptions startOptions; - if (info.argc > ARGC_ONE && info.argv[1]->TypeOf() == NATIVE_OBJECT) { - HILOG_INFO("OnMoveMissionToFront start options is used."); - AppExecFwk::UnwrapStartOptions(reinterpret_cast(&engine), - reinterpret_cast(info.argv[1]), startOptions); - unwrapArgc++; - } + AsyncTask::CompleteCallback complete = - [missionId, errCode, startOptions, unwrapArgc](NativeEngine &engine, AsyncTask &task, int32_t status) { + [missionId, errCode](NativeEngine &engine, AsyncTask &task, int32_t status) { if (errCode != 0) { task.Reject(engine, CreateJsError(engine, errCode, "Invalidate params.")); return; } - auto ret = (unwrapArgc == 1) ? AbilityManagerClient::GetInstance()->MoveMissionToFront(missionId) : - AbilityManagerClient::GetInstance()->MoveMissionToFront(missionId, startOptions); + auto ret = AbilityManagerClient::GetInstance()->MoveMissionToFront(missionId); if (ret == 0) { task.Resolve(engine, engine.CreateUndefined()); } else { @@ -479,7 +467,7 @@ private: } }; - NativeValue* lastParam = (info.argc <= unwrapArgc) ? nullptr : info.argv[unwrapArgc]; + NativeValue* lastParam = (info.argc <= 1) ? nullptr : info.argv[1]; NativeValue* result = nullptr; AsyncTask::Schedule( engine, CreateAsyncTaskWithLastParam(engine, lastParam, nullptr, std::move(complete), &result)); @@ -517,6 +505,7 @@ NativeValue* JsMissionManagerInit(NativeEngine* engine, NativeValue* exportObj) BindNativeFunction(*engine, *object, "clearMission", JsMissionManager::ClearMission); BindNativeFunction(*engine, *object, "clearAllMissions", JsMissionManager::ClearAllMissions); BindNativeFunction(*engine, *object, "moveMissionToFront", JsMissionManager::MoveMissionToFront); + BindNativeFunction(*engine, *object, "moveMissionToFront", JsMissionManager::MoveMissionToFront); return engine->CreateUndefined(); } } // namespace AbilityRuntime diff --git a/interfaces/kits/napi/aafwk/particleAbility/particle_ability.cpp b/interfaces/kits/napi/aafwk/particleAbility/particle_ability.cpp index aa4f8065c8df8dfb983ff5380b7d93b94fa17f7b..c5dd1ae82d3aa0263fe4eeb7e83e6bbdabecf757 100644 --- a/interfaces/kits/napi/aafwk/particleAbility/particle_ability.cpp +++ b/interfaces/kits/napi/aafwk/particleAbility/particle_ability.cpp @@ -182,34 +182,6 @@ napi_value NAPI_PAAcquireDataAbilityHelper(napi_env env, napi_callback_info info return NAPI_AcquireDataAbilityHelperCommon(env, info, AbilityType::UNKNOWN); } -/** - * @brief ParticleAbility NAPI method : startBackgroundRunning. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_PAStartBackgroundRunning(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s,called", __func__); - return NAPI_StartBackgroundRunningCommon(env, info); -} - -/** - * @brief ParticleAbility NAPI method : cancelBackgroundRunning. - * - * @param env The environment that the Node-API call is invoked under. - * @param info The callback info passed into the callback function. - * - * @return The return value from NAPI C++ to JS for the module. - */ -napi_value NAPI_PACancelBackgroundRunning(napi_env env, napi_callback_info info) -{ - HILOG_INFO("%{public}s,called", __func__); - return NAPI_CancelBackgroundRunningCommon(env, info); -} - /** * @brief ParticleAbility NAPI module registration. * @@ -233,8 +205,6 @@ napi_value ParticleAbilityInit(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("connectAbility", NAPI_PAConnectAbility), DECLARE_NAPI_FUNCTION("disconnectAbility", NAPI_PADisConnectAbility), DECLARE_NAPI_FUNCTION("acquireDataAbilityHelper", NAPI_PAAcquireDataAbilityHelper), - DECLARE_NAPI_FUNCTION("startBackgroundRunning", NAPI_PAStartBackgroundRunning), - DECLARE_NAPI_FUNCTION("cancelBackgroundRunning", NAPI_PACancelBackgroundRunning), }; napi_define_properties(env, exports, sizeof(properties) / sizeof(properties[0]), properties); diff --git a/services/abilitymgr/include/ability_manager_proxy.h b/services/abilitymgr/include/ability_manager_proxy.h index 79f078b1c1ea5a460e7915e3649b7c342dcc7acb..18ad4c0f89afc025f3d444129d31fc0048c16477 100644 --- a/services/abilitymgr/include/ability_manager_proxy.h +++ b/services/abilitymgr/include/ability_manager_proxy.h @@ -519,7 +519,7 @@ public: virtual void NotifyCompleteContinuation(const std::string &deviceId, int32_t sessionId, bool isSuccess) override; - virtual int NotifyContinuationResult(int32_t missionId, int32_t result) override; + virtual int NotifyContinuationResult(int32_t missionId, const int32_t result) override; virtual int StartSyncRemoteMissions(const std::string& devId, bool fixConflict, int64_t tag) override; @@ -544,9 +544,7 @@ public: virtual int CleanAllMissions() override; virtual int MoveMissionToFront(int32_t missionId) override; - - virtual int MoveMissionToFront(int32_t missionId, const StartOptions &startOptions) override; - + /** * Start Ability, connect session with common ability. * @@ -657,7 +655,7 @@ public: * @param pid The not response process ID. */ virtual bool SendANRProcessID(int pid) override; - + private: template int GetParcelableInfos(MessageParcel &reply, std::vector &parcelableInfos); diff --git a/services/abilitymgr/include/ability_manager_service.h b/services/abilitymgr/include/ability_manager_service.h index 212db26fad7fcdc9db69d9737ca6cfd753e6d43f..925610fa4e9cbe9ffd39f298e3bb8e9313fbe6e3 100644 --- a/services/abilitymgr/include/ability_manager_service.h +++ b/services/abilitymgr/include/ability_manager_service.h @@ -215,7 +215,7 @@ public: * @param result, continuation result. * @return Returns ERR_OK on success, others on failure. */ - virtual int NotifyContinuationResult(int32_t missionId, int32_t result) override; + virtual int NotifyContinuationResult(int32_t missionId, const int32_t result) override; /** * RegisterMissionListener, register remote device mission listener. @@ -659,8 +659,6 @@ public: virtual int MoveMissionToFront(int32_t missionId) override; - virtual int MoveMissionToFront(int32_t missionId, const StartOptions &startOptions) override; - virtual int StartSyncRemoteMissions(const std::string& devId, bool fixConflict, int64_t tag) override; virtual int StopSyncRemoteMissions(const std::string& devId) override; @@ -1109,8 +1107,6 @@ private: int DelegatorMoveMissionToFront(int32_t missionId); - void StartupResidentProcess(); - using DumpFuncType = void (AbilityManagerService::*)(const std::string &args, std::vector &info); std::map dumpFuncMap_; diff --git a/services/abilitymgr/include/ability_manager_stub.h b/services/abilitymgr/include/ability_manager_stub.h index 448a262cf098f14e2968ecb5bf23bd584b459dfc..08bacb824caa2785704e9e4b3c9a011d17086494 100644 --- a/services/abilitymgr/include/ability_manager_stub.h +++ b/services/abilitymgr/include/ability_manager_stub.h @@ -142,7 +142,7 @@ private: int CleanMissionInner(MessageParcel &data, MessageParcel &reply); int CleanAllMissionsInner(MessageParcel &data, MessageParcel &reply); int MoveMissionToFrontInner(MessageParcel &data, MessageParcel &reply); - + // for new version ability (call ability) int StartAbilityByCallInner(MessageParcel &data, MessageParcel &reply); int ReleaseInner(MessageParcel &data, MessageParcel &reply); @@ -170,7 +170,6 @@ private: int DoAbilityBackgroundInner(MessageParcel &data, MessageParcel &reply); int IsRunningInStabilityTestInner(MessageParcel &data, MessageParcel &reply); - int MoveMissionToFrontByOptionsInner(MessageParcel &data, MessageParcel &reply); using RequestFuncType = int (AbilityManagerStub::*)(MessageParcel &data, MessageParcel &reply); std::map requestFuncMap_; diff --git a/services/abilitymgr/include/ability_record.h b/services/abilitymgr/include/ability_record.h index 78633a38fd5098102beb2bfce47eb5f774c08506..1753d77f382755f88166fd82da4dd5f61f2f8f47 100644 --- a/services/abilitymgr/include/ability_record.h +++ b/services/abilitymgr/include/ability_record.h @@ -670,7 +670,7 @@ public: * dump ability state info. * */ - void DumpAbilityState(std::vector &info, bool isClient, const std::vector ¶ms); + void DumpAbilityState(std::vector &info, bool isClient); void SetStartTime(); @@ -755,7 +755,7 @@ public: void SetLaunchReason(const LaunchReason &reason); void SetLastExitReason(const LastExitReason &reason); void ContinueAbility(const std::string& deviceId); - void NotifyContinuationResult(int32_t result); + void NotifyContinuationResult(const int32_t result); std::shared_ptr GetOwnedMissionList() const; void SetUseNewMission(); diff --git a/services/abilitymgr/include/ability_scheduler_proxy.h b/services/abilitymgr/include/ability_scheduler_proxy.h index 26e93b3e80d8bea367c0d788c8c6e65735eed9da..7b505783d67ffed965163aa966fca4e500350af7 100644 --- a/services/abilitymgr/include/ability_scheduler_proxy.h +++ b/services/abilitymgr/include/ability_scheduler_proxy.h @@ -297,7 +297,7 @@ public: * @param The continuation result. * @return */ - void NotifyContinuationResult(int32_t result) override; + void NotifyContinuationResult(const int32_t result) override; /** * Dump Ability Runner info. @@ -305,7 +305,7 @@ public: * @param * @return Ability Runner info. */ - void DumpAbilityInfo(const std::vector ¶ms, std::vector &info) override; + void DumpAbilityInfo(std::vector &info) override; sptr CallRequest() override; private: diff --git a/services/abilitymgr/include/lifecycle_deal.h b/services/abilitymgr/include/lifecycle_deal.h index 2d894433ff1c29d420d918b1249f19c81a7f8676..dfca7756eda6849fc118f0ba3d21d6a97f5d7dfe 100644 --- a/services/abilitymgr/include/lifecycle_deal.h +++ b/services/abilitymgr/include/lifecycle_deal.h @@ -58,7 +58,7 @@ public: void ForegroundNew(const Want &want, LifeCycleStateInfo &stateInfo); void BackgroundNew(const Want &want, LifeCycleStateInfo &stateInfo); void ContinueAbility(const std::string& deviceId); - void NotifyContinuationResult(int32_t result); + void NotifyContinuationResult(const int32_t result); private: sptr GetScheduler(); diff --git a/services/abilitymgr/include/mission_list.h b/services/abilitymgr/include/mission_list.h index 30b4140bdccb8cc55bb67d272d8929f197d6595f..ca093f4dca82080e320e19ea6fc125777d6e788b 100644 --- a/services/abilitymgr/include/mission_list.h +++ b/services/abilitymgr/include/mission_list.h @@ -174,9 +174,7 @@ public: * @param info dump result. */ void DumpList(std::vector &info, bool isClient); - - void DumpStateByRecordId( - std::vector &info, bool isClient, int32_t abilityRecordId, const std::vector ¶ms); + void DumpStateByRecordId(std::vector &info, bool isClient, int32_t abilityRecordId); std::shared_ptr GetMissionBySpecifiedFlag(const std::string &flag) const; private: diff --git a/services/abilitymgr/include/mission_list_manager.h b/services/abilitymgr/include/mission_list_manager.h index 191b986b813fa8f67372ea71b95d9ed57a293172..650085f7f87e4e4dd9bea2c173f0f9db2a447d8a 100644 --- a/services/abilitymgr/include/mission_list_manager.h +++ b/services/abilitymgr/include/mission_list_manager.h @@ -27,7 +27,6 @@ #include "mission_info.h" #include "mission_snapshot.h" #include "snapshot.h" -#include "start_options.h" #include "want.h" namespace OHOS { @@ -68,10 +67,9 @@ public: int GetMissionInfo(int32_t missionId, MissionInfo &missionInfo); - int MoveMissionToFront(int32_t missionId, std::shared_ptr startOptions = nullptr); + int MoveMissionToFront(int32_t missionId); - int MoveMissionToFront(int32_t missionId, bool isCallerFromLauncher, - std::shared_ptr startOptions = nullptr); + int MoveMissionToFront(int32_t missionId, bool isCallerFromLauncher); /** * OnAbilityRequestDone, app manager service call this interface after ability request done. @@ -264,14 +262,7 @@ public: */ void DumpMissionList(std::vector &info, bool isClient, const std::string &args = ""); - /** - * @brief dump mission list by id with params - * - * @param info dump result. - * @param params dump params. - */ - void DumpMissionListByRecordId( - std::vector& info, bool isClient, int32_t abilityRecordId, const std::vector& params); + void DumpMissionListByRecordId(std::vector &info, bool isClient, int32_t abilityRecordId); /** * @brief dump mission by id @@ -303,6 +294,7 @@ public: * @param element, target ability name. */ int ReleaseLocked(const sptr &connect, const AppExecFwk::ElementName &element); + /** * @brief register snapshotHandler * @param handler the snapshotHandler diff --git a/services/abilitymgr/src/ability_manager_client.cpp b/services/abilitymgr/src/ability_manager_client.cpp index bf217771d1488adbb712d5bb4fa0d7b61669109c..ec19bb5290a81717b830a017248cf65c3f139963 100644 --- a/services/abilitymgr/src/ability_manager_client.cpp +++ b/services/abilitymgr/src/ability_manager_client.cpp @@ -772,14 +772,6 @@ ErrCode AbilityManagerClient::MoveMissionToFront(int32_t missionId) return abms->MoveMissionToFront(missionId); } -ErrCode AbilityManagerClient::MoveMissionToFront(int32_t missionId, const StartOptions &startOptions) -{ - CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); - - sptr abms = iface_cast(remoteObject_); - return abms->MoveMissionToFront(missionId, startOptions); -} - ErrCode AbilityManagerClient::StartAbilityByCall( const Want &want, const sptr &connect, const sptr &callToken) { @@ -932,14 +924,5 @@ ErrCode AbilityManagerClient::DoAbilityBackground(const sptr &tok sptr abms = iface_cast(remoteObject_); return abms->DoAbilityBackground(token, flag); } - -ErrCode AbilityManagerClient::SetAbilityController(const sptr &abilityController, - bool imAStabilityTest) -{ - CHECK_REMOTE_OBJECT_AND_RETURN(remoteObject_, ABILITY_SERVICE_NOT_CONNECTED); - - sptr abms = iface_cast(remoteObject_); - return abms->SetAbilityController(abilityController, imAStabilityTest); -} } // namespace AAFwk } // namespace AAFwk diff --git a/services/abilitymgr/src/ability_manager_proxy.cpp b/services/abilitymgr/src/ability_manager_proxy.cpp index 14980e300315e32a10b6ffa25922384bbceff0d5..86db7a562d30993b0ea3aef66f6128bfe7644063 100644 --- a/services/abilitymgr/src/ability_manager_proxy.cpp +++ b/services/abilitymgr/src/ability_manager_proxy.cpp @@ -1721,7 +1721,7 @@ void AbilityManagerProxy::NotifyCompleteContinuation(const std::string &deviceId } } -int AbilityManagerProxy::NotifyContinuationResult(int32_t missionId, int32_t result) +int AbilityManagerProxy::NotifyContinuationResult(int32_t missionId, const int32_t result) { MessageParcel data; MessageParcel reply; @@ -1996,32 +1996,6 @@ int AbilityManagerProxy::MoveMissionToFront(int32_t missionId) return reply.ReadInt32(); } -int AbilityManagerProxy::MoveMissionToFront(int32_t missionId, const StartOptions &startOptions) -{ - int error; - MessageParcel data; - MessageParcel reply; - MessageOption option; - - if (!WriteInterfaceToken(data)) { - return INNER_ERR; - } - if (!data.WriteInt32(missionId)) { - HILOG_ERROR("move mission to front , WriteInt32 fail."); - return ERR_INVALID_VALUE; - } - if (!data.WriteParcelable(&startOptions)) { - HILOG_ERROR("startOptions write failed."); - return INNER_ERR; - } - error = Remote()->SendRequest(IAbilityManager::MOVE_MISSION_TO_FRONT_BY_OPTIONS, data, reply, option); - if (error != NO_ERROR) { - HILOG_ERROR("move mission to front, SendRequest error: %d", error); - return error; - } - return reply.ReadInt32(); -} - int AbilityManagerProxy::StartUser(int userId) { int error; diff --git a/services/abilitymgr/src/ability_manager_service.cpp b/services/abilitymgr/src/ability_manager_service.cpp index 55b4fdf972742a1c741ce63a4396f517a7c038fa..f3f806dacc33705190c32b8c39e9e5fc8804ed15 100644 --- a/services/abilitymgr/src/ability_manager_service.cpp +++ b/services/abilitymgr/src/ability_manager_service.cpp @@ -288,6 +288,10 @@ int AbilityManagerService::StartAbilityInner(const Want &want, const sptr &connect) @@ -1011,15 +1023,13 @@ int AbilityManagerService::StartContinuation(const Want &want, const sptrMoveMissionToFront(missionId); } -int AbilityManagerService::MoveMissionToFront(int32_t missionId, const StartOptions &startOptions) -{ - HILOG_INFO("request MoveMissionToFront, missionId:%{public}d", missionId); - CHECK_POINTER_AND_RETURN(currentMissionListManager_, ERR_NO_INIT); - CHECK_POINTER_AND_RETURN(iBundleManager_, ERR_NO_INIT); - - if (!CheckCallerIsSystemAppByIpc()) { - HILOG_ERROR("caller is not system app"); - return CALLER_ISNOT_SYSTEMAPP; - } - - auto options = std::make_shared(startOptions); - return currentMissionListManager_->MoveMissionToFront(missionId, options); -} - std::shared_ptr AbilityManagerService::GetServiceRecordByElementName(const std::string &element) { return connectManager_->GetServiceRecordByElementName(element); @@ -1506,6 +1501,10 @@ sptr AbilityManagerService::AcquireDataAbility( abilityRequest.appInfo.bundleName.c_str(), abilityRequest.abilityInfo.name.c_str()); + if (CheckStaticCfgPermission(abilityRequest.abilityInfo) != ERR_OK) { + return nullptr; + } + CHECK_POINTER_AND_RETURN(dataAbilityManager_, nullptr); return dataAbilityManager_->Acquire(abilityRequest, tryBind, callerToken, isSystem); } @@ -1700,10 +1699,9 @@ void AbilityManagerService::DumpSysAbilityInner( if (argList.empty()) { return; } - if (argList.size() >= MIN_DUMP_ARGUMENT_NUM) { + if (argList.size() == MIN_DUMP_ARGUMENT_NUM) { HILOG_INFO("argList = %{public}s", argList[1].c_str()); - std::vector params(argList.begin() + MIN_DUMP_ARGUMENT_NUM, argList.end()); - targetManager->DumpMissionListByRecordId(info, isClient, std::stoi(argList[1]), params); + targetManager->DumpMissionListByRecordId(info, isClient, std::stoi(argList[1])); } else { info.emplace_back("error: invalid argument, please see 'ability dumpsys -h'."); } @@ -3216,7 +3214,8 @@ void AbilityManagerService::StartSystemApplication() StartingSystemUiAbility(); - StartupResidentProcess(); + // Location may change + DelayedSingleton::GetInstance()->StartupResidentProcess(); } void AbilityManagerService::StartingSystemUiAbility() @@ -4260,25 +4259,24 @@ int AbilityManagerService::CheckStaticCfgPermission(AppExecFwk::AbilityInfo &abi abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::DATASHARE) || (abilityInfo.type == AppExecFwk::AbilityType::DATA)) { // just need check the read permission and write permission of extension ability or data ability - if (!abilityInfo.readPermission.empty()) { - int checkReadPermission = AccessTokenKit::VerifyAccessToken(tokenId, abilityInfo.readPermission); - if (checkReadPermission == ERR_OK) { - return AppExecFwk::Constants::PERMISSION_GRANTED; - } - HILOG_WARN("verify access token fail, read permission: %{public}s", abilityInfo.readPermission.c_str()); + if (!abilityInfo.readPermission.empty() && + AccessTokenKit::VerifyAccessToken(tokenId, abilityInfo.readPermission) + != AppExecFwk::Constants::PERMISSION_GRANTED) { + HILOG_ERROR("verify access token failed, read permission: %{public}s", + abilityInfo.readPermission.c_str()); + return AppExecFwk::Constants::PERMISSION_NOT_GRANTED; } - if (!abilityInfo.writePermission.empty()) { - int checkWritePermission = AccessTokenKit::VerifyAccessToken(tokenId, abilityInfo.writePermission); - if (checkWritePermission == ERR_OK) { - return AppExecFwk::Constants::PERMISSION_GRANTED; - } - HILOG_WARN("verify access token fail, write permission: %{public}s", abilityInfo.writePermission.c_str()); + if (!abilityInfo.writePermission.empty() && + AccessTokenKit::VerifyAccessToken(tokenId, abilityInfo.writePermission) + != AppExecFwk::Constants::PERMISSION_GRANTED) { + HILOG_ERROR("verify access token failed, write permission: %{public}s", + abilityInfo.writePermission.c_str()); + return AppExecFwk::Constants::PERMISSION_NOT_GRANTED; } - if (!abilityInfo.readPermission.empty() || !abilityInfo.writePermission.empty()) { // 'readPermission' and 'writePermission' take precedence over 'permission' // when 'readPermission' or 'writePermission' is not empty, no need check 'permission' - return AppExecFwk::Constants::PERMISSION_NOT_GRANTED; + return ERR_OK; } } @@ -4290,31 +4288,12 @@ int AbilityManagerService::CheckStaticCfgPermission(AppExecFwk::AbilityInfo &abi for (auto permission : abilityInfo.permissions) { if (AccessTokenKit::VerifyAccessToken(tokenId, permission) != AppExecFwk::Constants::PERMISSION_GRANTED) { - HILOG_ERROR("verify access token fail, permission: %{public}s", permission.c_str()); + HILOG_ERROR("verify access token failed, permission: %{public}s", permission.c_str()); return AppExecFwk::Constants::PERMISSION_NOT_GRANTED; } } return ERR_OK; } - -void AbilityManagerService::StartupResidentProcess() -{ - // Location may change - std::vector bundleInfos; - (void)iBundleManager_->QueryKeepAliveBundleInfos(bundleInfos); - for (auto bundleInfo : bundleInfos) { - for (auto hapModuleInfo : bundleInfo.hapModuleInfos) { - if (!hapModuleInfo.mainElementName.empty()) { - AppExecFwk::AbilityInfo abilityInfo; - Want want; - want.SetElementName(hapModuleInfo.bundleName, hapModuleInfo.mainElementName); - (void)StartAbility(want, USER_ID_NO_HEAD, DEFAULT_INVAL_VALUE); // user 0 - } - } - } - - DelayedSingleton::GetInstance()->StartupResidentProcess(); -} } // namespace AAFwk } // namespace OHOS diff --git a/services/abilitymgr/src/ability_manager_stub.cpp b/services/abilitymgr/src/ability_manager_stub.cpp index 6d679b09bd3028d11fc41353602eb6c28359f4b5..d9088839c36d2b4c77dced73dbe1bf51d5cf4559 100644 --- a/services/abilitymgr/src/ability_manager_stub.cpp +++ b/services/abilitymgr/src/ability_manager_stub.cpp @@ -125,7 +125,6 @@ void AbilityManagerStub::SecondStepInit() requestFuncMap_[CLEAN_MISSION] = &AbilityManagerStub::CleanMissionInner; requestFuncMap_[CLEAN_ALL_MISSIONS] = &AbilityManagerStub::CleanAllMissionsInner; requestFuncMap_[MOVE_MISSION_TO_FRONT] = &AbilityManagerStub::MoveMissionToFrontInner; - requestFuncMap_[MOVE_MISSION_TO_FRONT_BY_OPTIONS] = &AbilityManagerStub::MoveMissionToFrontByOptionsInner; requestFuncMap_[START_CALL_ABILITY] = &AbilityManagerStub::StartAbilityByCallInner; requestFuncMap_[RELEASE_CALL_ABILITY] = &AbilityManagerStub::ReleaseInner; requestFuncMap_[SET_MISSION_LABEL] = &AbilityManagerStub::SetMissionLabelInner; @@ -1149,25 +1148,9 @@ int AbilityManagerStub::MoveMissionToFrontInner(MessageParcel &data, MessageParc return NO_ERROR; } -int AbilityManagerStub::MoveMissionToFrontByOptionsInner(MessageParcel &data, MessageParcel &reply) -{ - int32_t missionId = data.ReadInt32(); - StartOptions *startOptions = data.ReadParcelable(); - if (startOptions == nullptr) { - HILOG_ERROR("startOptions is nullptr"); - return ERR_INVALID_VALUE; - } - int result = MoveMissionToFront(missionId, *startOptions); - if (!reply.WriteInt32(result)) { - HILOG_ERROR("MoveMissionToFront failed."); - return ERR_INVALID_VALUE; - } - return NO_ERROR; -} - int AbilityManagerStub::StartAbilityByCallInner(MessageParcel &data, MessageParcel &reply) { - + HILOG_DEBUG("AbilityManagerStub::StartAbilityByCallInner begin."); Want *want = data.ReadParcelable(); if (want == nullptr) { @@ -1183,7 +1166,7 @@ int AbilityManagerStub::StartAbilityByCallInner(MessageParcel &data, MessageParc reply.WriteInt32(result); delete want; - + HILOG_DEBUG("AbilityManagerStub::StartAbilityByCallInner end."); return NO_ERROR; diff --git a/services/abilitymgr/src/ability_record.cpp b/services/abilitymgr/src/ability_record.cpp index 1c398aea0b90b98c5180e65ab9820fccf7eba9df..90c73efb5bda9d2bf5b4be75508c4a9429c2603b 100644 --- a/services/abilitymgr/src/ability_record.cpp +++ b/services/abilitymgr/src/ability_record.cpp @@ -922,8 +922,7 @@ void AbilityRecord::Dump(std::vector &info) } } -void AbilityRecord::DumpAbilityState( - std::vector &info, bool isClient, const std::vector ¶ms) +void AbilityRecord::DumpAbilityState(std::vector &info, bool isClient) { HILOG_INFO("%{public}s begin.", __func__); std::string dumpInfo = " AbilityRecord ID #" + std::to_string(recordId_); @@ -955,10 +954,7 @@ void AbilityRecord::DumpAbilityState( // add dump client info if (isClient && scheduler_ && isReady_) { - scheduler_->DumpAbilityInfo(params, info); - if (!params.empty()) { - return; - } + scheduler_->DumpAbilityInfo(info); AppExecFwk::Configuration config; if (DelayedSingleton::GetInstance()->GetConfiguration(config) == ERR_OK) { info.emplace_back(" configuration: " + config.GetName()); @@ -996,8 +992,7 @@ void AbilityRecord::DumpService(std::vector &info, bool isClient) c } // add dump client info if (isClient && scheduler_ && isReady_) { - std::vector params; - scheduler_->DumpAbilityInfo(params, info); + scheduler_->DumpAbilityInfo(info); AppExecFwk::Configuration config; if (DelayedSingleton::GetInstance()->GetConfiguration(config) == ERR_OK) { info.emplace_back(" configuration: " + config.GetName()); @@ -1297,7 +1292,7 @@ void AbilityRecord::SetLastExitReason(const LastExitReason &reason) lifeCycleStateInfo_.launchParam.lastExitReason = reason; } -void AbilityRecord::NotifyContinuationResult(int32_t result) +void AbilityRecord::NotifyContinuationResult(const int32_t result) { HILOG_INFO("NotifyContinuationResult."); CHECK_POINTER(lifecycleDeal_); diff --git a/services/abilitymgr/src/ability_scheduler_proxy.cpp b/services/abilitymgr/src/ability_scheduler_proxy.cpp index bdf34a06b6fb454fb7b35c5dd6a742506fc16e88..c95d108a3ee91392b4f3d27a6d0277e701f60079 100755 --- a/services/abilitymgr/src/ability_scheduler_proxy.cpp +++ b/services/abilitymgr/src/ability_scheduler_proxy.cpp @@ -981,7 +981,7 @@ void AbilitySchedulerProxy::NotifyContinuationResult(int32_t result) } } -void AbilitySchedulerProxy::DumpAbilityInfo(const std::vector ¶ms, std::vector &info) +void AbilitySchedulerProxy::DumpAbilityInfo(std::vector &info) { MessageParcel data; MessageParcel reply; @@ -991,11 +991,6 @@ void AbilitySchedulerProxy::DumpAbilityInfo(const std::vector ¶ return; } - if (!data.WriteStringVector(params)) { - HILOG_ERROR("DumpAbilityRunner fail to write params"); - return; - } - int32_t err = Remote()->SendRequest(IAbilityScheduler::DUMP_ABILITY_RUNNER_INNER, data, reply, option); if (err != NO_ERROR) { HILOG_ERROR("DumpAbilityRunner fail to SendRequest. err: %d", err); diff --git a/services/abilitymgr/src/ability_scheduler_stub.cpp b/services/abilitymgr/src/ability_scheduler_stub.cpp index 89e19940414d40019d3d127e4c5bf403428909a0..e72008a219afa220a12a33610a3d42095d322274 100644 --- a/services/abilitymgr/src/ability_scheduler_stub.cpp +++ b/services/abilitymgr/src/ability_scheduler_stub.cpp @@ -580,13 +580,10 @@ int AbilitySchedulerStub::NotifyContinuationResultInner(MessageParcel &data, Mes int AbilitySchedulerStub::DumpAbilityInfoInner(MessageParcel &data, MessageParcel &reply) { + std::vector infos; - std::vector params; - if (!data.ReadStringVector(¶ms)) { - HILOG_INFO("DumpAbilityInfoInner read params error"); - return NO_ERROR; - } - DumpAbilityInfo(params, infos); + + DumpAbilityInfo(infos); for (const auto & infostep:infos) { HILOG_INFO("DumpAbilityInfoInner infos = %{public}s", infostep.c_str()); diff --git a/services/abilitymgr/src/lifecycle_deal.cpp b/services/abilitymgr/src/lifecycle_deal.cpp index 2ab80063fdc0cb4072e980eaec8092221e10e684..3e5160e9f9af4528541115b74dfe4170e24b7d1d 100755 --- a/services/abilitymgr/src/lifecycle_deal.cpp +++ b/services/abilitymgr/src/lifecycle_deal.cpp @@ -160,7 +160,7 @@ void LifecycleDeal::ContinueAbility(const std::string& deviceId) abilityScheduler_->ContinueAbility(deviceId); } -void LifecycleDeal::NotifyContinuationResult(int32_t result) +void LifecycleDeal::NotifyContinuationResult(const int32_t result) { HILOG_INFO("NotifyContinuationResult."); auto abilityScheduler = GetScheduler(); diff --git a/services/abilitymgr/src/mission_list.cpp b/services/abilitymgr/src/mission_list.cpp index 24e621a68082b5c85b1767724a845846e08d93cf..439df45cef9005ed2e283c1f95802acfcdfc8682 100644 --- a/services/abilitymgr/src/mission_list.cpp +++ b/services/abilitymgr/src/mission_list.cpp @@ -264,8 +264,7 @@ void MissionList::Dump(std::vector& info) } } -void MissionList::DumpStateByRecordId( - std::vector &info, bool isClient, int32_t abilityRecordId, const std::vector ¶ms) +void MissionList::DumpStateByRecordId(std::vector &info, bool isClient, int32_t abilityRecordId) { for (const auto& mission : missions_) { if (mission) { @@ -273,7 +272,7 @@ void MissionList::DumpStateByRecordId( if (abilityRecord) { if (abilityRecord->GetRecordId() == abilityRecordId) { HILOG_INFO("record begain to call DumpAbilityState %{public}s", __func__); - abilityRecord->DumpAbilityState(info, isClient, params); + abilityRecord->DumpAbilityState(info, isClient); return; } } @@ -295,8 +294,7 @@ void MissionList::DumpList(std::vector &info, bool isClient) auto abilityRecord = mission->GetAbilityRecord(); if (abilityRecord) { HILOG_INFO("record begain to call DumpAbilityState %{public}s", __func__); - std::vector params; - abilityRecord->DumpAbilityState(info, isClient, params); + abilityRecord->DumpAbilityState(info, isClient); } } } diff --git a/services/abilitymgr/src/mission_list_manager.cpp b/services/abilitymgr/src/mission_list_manager.cpp index 198261ccc0282378433bee6e8a8330e1c43d26df..4447b96782cc87ac06cda0d3d3ca2a07609e7339 100644 --- a/services/abilitymgr/src/mission_list_manager.cpp +++ b/services/abilitymgr/src/mission_list_manager.cpp @@ -145,14 +145,13 @@ int MissionListManager::GetMissionInfo(int32_t missionId, MissionInfo &missionIn return DelayedSingleton::GetInstance()->GetMissionInfoById(missionId, missionInfo); } -int MissionListManager::MoveMissionToFront(int32_t missionId, std::shared_ptr startOptions) +int MissionListManager::MoveMissionToFront(int32_t missionId) { std::lock_guard guard(managerLock_); - return MoveMissionToFront(missionId, true, startOptions); + return MoveMissionToFront(missionId, true); } -int MissionListManager::MoveMissionToFront(int32_t missionId, bool isCallerFromLauncher, - std::shared_ptr startOptions) +int MissionListManager::MoveMissionToFront(int32_t missionId, bool isCallerFromLauncher) { HILOG_INFO("move mission to front:%{public}d.", missionId); std::lock_guard guard(managerLock_); @@ -178,11 +177,7 @@ int MissionListManager::MoveMissionToFront(int32_t missionId, bool isCallerFromL HILOG_ERROR("get target ability record failed, missionId: %{public}d", missionId); return MOVE_MISSION_FAILED; } - if (startOptions != nullptr) { - Want want(targetAbilityRecord->GetWant()); - want.SetParam(Want::PARAM_RESV_WINDOW_MODE, startOptions->GetWindowMode()); - targetAbilityRecord->SetWant(want); - } + // schedule target ability to foreground. targetAbilityRecord->ProcessForegroundAbility(); HILOG_DEBUG("SetMovingState, missionId: %{public}d", missionId); @@ -1579,7 +1574,7 @@ void MissionListManager::Dump(std::vector &info) } void MissionListManager::DumpMissionListByRecordId( - std::vector &info, bool isClient, int32_t abilityRecordId, const std::vector ¶ms) + std::vector &info, bool isClient, int32_t abilityRecordId) { std::lock_guard guard(managerLock_); std::string dumpInfo = "User ID #" + std::to_string(userId_); @@ -1587,23 +1582,23 @@ void MissionListManager::DumpMissionListByRecordId( for (const auto& missionList : currentMissionLists_) { if (missionList && missionList != launcherList_) { HILOG_INFO("missionList begain to call DumpMissionListByRecordId %{public}s", __func__); - missionList->DumpStateByRecordId(info, isClient, abilityRecordId, params); + missionList->DumpStateByRecordId(info, isClient, abilityRecordId); } } if (defaultStandardList_) { HILOG_INFO("defaultStandardList begain to call DumpMissionListByRecordId %{public}s", __func__); - defaultStandardList_->DumpStateByRecordId(info, isClient, abilityRecordId, params); + defaultStandardList_->DumpStateByRecordId(info, isClient, abilityRecordId); } if (defaultSingleList_) { HILOG_INFO("defaultSingleList begain to call DumpMissionListByRecordId %{public}s", __func__); - defaultSingleList_->DumpStateByRecordId(info, isClient, abilityRecordId, params); + defaultSingleList_->DumpStateByRecordId(info, isClient, abilityRecordId); } if (launcherList_) { HILOG_INFO("launcherList begain to call DumpMissionListByRecordId %{public}s", __func__); - launcherList_->DumpStateByRecordId(info, isClient, abilityRecordId, params); + launcherList_->DumpStateByRecordId(info, isClient, abilityRecordId); } } void MissionListManager::DumpMissionList(std::vector &info, bool isClient, const std::string &args) diff --git a/services/abilitymgr/src/pending_want_manager.cpp b/services/abilitymgr/src/pending_want_manager.cpp index 22f19601b8c02d36bb11446594af8d4c9540bac3..f7461d333c9aec19453050c2e60d7df1ea15c303 100644 --- a/services/abilitymgr/src/pending_want_manager.cpp +++ b/services/abilitymgr/src/pending_want_manager.cpp @@ -235,8 +235,7 @@ int32_t PendingWantManager::DeviceIdDetermine( return result; } DistributedClient dmsClient; - uint32_t accessToken = IPCSkeleton::GetCallingTokenID(); - result = dmsClient.StartRemoteAbility(want, callerUid, requestCode, accessToken); + result = dmsClient.StartRemoteAbility(want, callerUid, requestCode); if (result != ERR_OK) { HILOG_ERROR("%{public}s: StartRemoteAbility Error! result = %{public}d", __func__, result); } diff --git a/services/abilitymgr/src/start_options.cpp b/services/abilitymgr/src/start_options.cpp index 0ec49ac7681aa67f58e87bba2cefa593cdfc4671..20eb4bfd33af410f4bf68d5d27c14aa979080452 100644 --- a/services/abilitymgr/src/start_options.cpp +++ b/services/abilitymgr/src/start_options.cpp @@ -20,21 +20,6 @@ namespace AAFwk { const std::string StartOptions::STRING_DISPLAY_ID = "ohos.aafwk.displayId"; -StartOptions::StartOptions(const StartOptions &other) -{ - windowMode_ = other.windowMode_; - displayId_ = other.displayId_; -} - -StartOptions &StartOptions::operator=(const StartOptions &other) -{ - if (this != &other) { - windowMode_ = other.windowMode_; - displayId_ = other.displayId_; - } - return *this; -} - bool StartOptions::ReadFromParcel(Parcel &parcel) { SetWindowMode(parcel.ReadInt32()); diff --git a/services/abilitymgr/test/mock/libs/aakit/include/ability_scheduler.h b/services/abilitymgr/test/mock/libs/aakit/include/ability_scheduler.h index bc9551997f34f767b915a6c10623cb226b352070..03bb8e5c183f9a09b5bf7320e82f049387619487 100755 --- a/services/abilitymgr/test/mock/libs/aakit/include/ability_scheduler.h +++ b/services/abilitymgr/test/mock/libs/aakit/include/ability_scheduler.h @@ -97,11 +97,11 @@ public: { return std::vector>(); }; - virtual void NotifyContinuationResult(int32_t result) override + virtual void NotifyContinuationResult(const int32_t result) override {}; virtual void ContinueAbility(const std::string& deviceId) override {}; - virtual void DumpAbilityInfo(const std::vector ¶ms, std::vector &info) override + virtual void DumpAbilityInfo(std::vector &info) override {}; virtual sptr CallRequest() override { diff --git a/services/abilitymgr/test/mock/libs/ability_scheduler_mock/ability_scheduler_mock.h b/services/abilitymgr/test/mock/libs/ability_scheduler_mock/ability_scheduler_mock.h index ec5ea8943c5098f01998f4854e1d93311e8bcff4..34bcf6228f5ab4af557b514bdd3d538270aa7c60 100755 --- a/services/abilitymgr/test/mock/libs/ability_scheduler_mock/ability_scheduler_mock.h +++ b/services/abilitymgr/test/mock/libs/ability_scheduler_mock/ability_scheduler_mock.h @@ -41,9 +41,9 @@ public: MOCK_METHOD3(ScheduleCommandAbility, void(const Want &, bool, int)); MOCK_METHOD1(NotifyTopActiveAbilityChanged, void(bool flag)); MOCK_METHOD2(NotifyMultiWinModeChanged, void(int32_t winModeKey, bool flag)); - MOCK_METHOD1(NotifyContinuationResult, void(int32_t result)); + MOCK_METHOD1(NotifyContinuationResult, void(const int32_t result)); MOCK_METHOD1(ContinueAbility, void(const std::string& deviceId)); - MOCK_METHOD2(DumpAbilityInfo, void(const std::vector ¶ms, std::vector &info)); + MOCK_METHOD1(DumpAbilityInfo, void(std::vector &info)); int InvokeSendRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) { @@ -150,4 +150,4 @@ public: int code_ = 0; }; } // namespace AAFwk -} // namespace OHOS +} // namespace OHOS \ No newline at end of file diff --git a/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/mock_bundle_manager.h b/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/mock_bundle_manager.h index 9f26de661771c5f56c1dd80f737cdceb9412281d..79b09256f748216e152e658d460b9647a3d62eb2 100644 --- a/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/mock_bundle_manager.h +++ b/services/abilitymgr/test/mock/libs/appexecfwk_core/include/bundlemgr/mock_bundle_manager.h @@ -180,6 +180,8 @@ public: MOCK_METHOD1(HasSystemCapability, bool(const std::string &capName)); MOCK_METHOD1(GetSystemAvailableCapabilities, bool(std::vector &systemCaps)); MOCK_METHOD0(IsSafeMode, bool()); + MOCK_METHOD2(CleanBundleCacheFiles, + bool(const std::string &bundleName, const sptr &cleanCacheCallback)); MOCK_METHOD2(CleanBundleDataFiles, bool(const std::string &bundleName, const int userId)); MOCK_METHOD3(RequestPermissionFromUser, bool(const std::string &bundleName, const std::string &permission, const int userId)); @@ -189,6 +191,7 @@ public: MOCK_METHOD4( DumpInfos, bool(const DumpFlag flag, const std::string &bundleName, int32_t userId, std::string &result)); MOCK_METHOD1(IsApplicationEnabled, bool(const std::string &bundleName)); + MOCK_METHOD2(SetApplicationEnabled, bool(const std::string &bundleName, bool isEnable)); MOCK_METHOD0(GetBundleInstaller, sptr()); MOCK_METHOD0(GetBundleUserMgr, sptr()); MOCK_METHOD2(GetAppIdByBundleName, std::string(const std::string &bundleName, const int userId)); @@ -197,6 +200,7 @@ public: MOCK_METHOD2(QueryAbilityInfos, bool(const Want &want, std::vector &abilityInfos)); MOCK_METHOD2(QueryAbilityInfosForClone, bool(const Want &want, std::vector &abilityInfos)); MOCK_METHOD1(IsAbilityEnabled, bool(const AbilityInfo &abilityInfo)); + MOCK_METHOD2(SetAbilityEnabled, bool(const AbilityInfo &abilityInfo, bool isEnabled)); MOCK_METHOD2(GetAbilityIcon, std::string(const std::string &bundleName, const std::string &className)); MOCK_METHOD3( CanRequestPermission, bool(const std::string &bundleName, const std::string &permissionName, const int userId)); @@ -260,11 +264,14 @@ public: MOCK_METHOD1(HasSystemCapability, bool(const std::string &capName)); MOCK_METHOD1(GetSystemAvailableCapabilities, bool(std::vector &systemCaps)); MOCK_METHOD0(IsSafeMode, bool()); + MOCK_METHOD2(CleanBundleCacheFiles, + bool(const std::string &bundleName, const sptr &cleanCacheCallback)); MOCK_METHOD2(CleanBundleDataFiles, bool(const std::string &bundleName, const int userId)); MOCK_METHOD3(RequestPermissionFromUser, bool(const std::string &bundleName, const std::string &permission, const int userId)); MOCK_METHOD1(RegisterBundleStatusCallback, bool(const sptr &bundleStatusCallback)); MOCK_METHOD1(ClearBundleStatusCallback, bool(const sptr &)); + MOCK_METHOD2(SetApplicationEnabled, bool(const std::string &bundleName, bool isEnable)); MOCK_METHOD0(GetBundleInstaller, sptr()); MOCK_METHOD0(GetBundleUserMgr, sptr()); MOCK_METHOD2(GetAppIdByBundleName, std::string(const std::string &bundleName, const int userId)); @@ -273,6 +280,7 @@ public: MOCK_METHOD2(QueryAbilityInfos, bool(const Want &want, std::vector &abilityInfos)); MOCK_METHOD2(QueryAbilityInfosForClone, bool(const Want &want, std::vector &abilityInfos)); MOCK_METHOD1(IsAbilityEnabled, bool(const AbilityInfo &abilityInfo)); + MOCK_METHOD2(SetAbilityEnabled, bool(const AbilityInfo &abilityInfo, bool isEnabled)); MOCK_METHOD2(GetAbilityIcon, std::string(const std::string &bundleName, const std::string &className)); MOCK_METHOD3( CanRequestPermission, bool(const std::string &bundleName, const std::string &permissionName, const int userId)); diff --git a/services/abilitymgr/test/unittest/phone/ability_manager_proxy_test/ability_manager_stub_mock.h b/services/abilitymgr/test/unittest/phone/ability_manager_proxy_test/ability_manager_stub_mock.h index d06f56e642388d74941941be13ebd7a81aac4850..bf6c9c53302e39e565fa0e7079fd49594664db66 100644 --- a/services/abilitymgr/test/unittest/phone/ability_manager_proxy_test/ability_manager_stub_mock.h +++ b/services/abilitymgr/test/unittest/phone/ability_manager_proxy_test/ability_manager_stub_mock.h @@ -393,7 +393,7 @@ public: MOCK_METHOD2(GetPendingRequestWant, int(const sptr &target, std::shared_ptr &want)); MOCK_METHOD1(GetSystemMemoryAttr, void(AppExecFwk::SystemMemoryAttr &memoryInfo)); MOCK_METHOD3(StartContinuation, int(const Want &want, const sptr &abilityToken, int32_t status)); - MOCK_METHOD2(NotifyContinuationResult, int(int32_t missionId, int32_t result)); + MOCK_METHOD2(NotifyContinuationResult, int(int32_t missionId, const int32_t result)); MOCK_METHOD5(ContinueMission, int(const std::string &srcDeviceId, const std::string &dstDeviceId, int32_t missionId, const sptr &callBack, AAFwk::WantParams &wantParams)); MOCK_METHOD2(ContinueAbility, int(const std::string &deviceId, int32_t missionId)); @@ -409,7 +409,6 @@ public: MOCK_METHOD1(CleanMission, int(int32_t missionId)); MOCK_METHOD0(CleanAllMissions, int()); MOCK_METHOD1(MoveMissionToFront, int(int32_t missionId)); - MOCK_METHOD2(MoveMissionToFront, int(int32_t missionId, const StartOptions &startOptions)); MOCK_METHOD2(SetMissionLabel, int(const sptr &token, const std::string &label)); MOCK_METHOD2(GetWantSenderInfo, int(const sptr &target, std::shared_ptr &info)); MOCK_METHOD1(GetAbilityRunningInfos, int(std::vector &info)); diff --git a/services/abilitymgr/test/unittest/phone/ability_manager_service_test/ability_manager_service_test.cpp b/services/abilitymgr/test/unittest/phone/ability_manager_service_test/ability_manager_service_test.cpp index 827759c89454fc630c0d57d05326f3c72a3a8381..9afa0aa24239431f634e862c6cb59d363e02a153 100644 --- a/services/abilitymgr/test/unittest/phone/ability_manager_service_test/ability_manager_service_test.cpp +++ b/services/abilitymgr/test/unittest/phone/ability_manager_service_test/ability_manager_service_test.cpp @@ -98,8 +98,8 @@ public: public: AbilityRequest abilityRequest_; + std::shared_ptr abilityMs_ {nullptr}; std::shared_ptr abilityRecord_ {nullptr}; - std::shared_ptr abilityMs_ = DelayedSingleton::GetInstance(); }; int AbilityManagerServiceTest::StartAbility(const Want &want) @@ -161,7 +161,9 @@ void AbilityManagerServiceTest::OnStartAms() void AbilityManagerServiceTest::OnStopAms() { - abilityMs_->OnStop(); + abilityMs_->eventLoop_.reset(); + abilityMs_->handler_.reset(); + abilityMs_->state_ = ServiceRunningState::STATE_NOT_START; } void AbilityManagerServiceTest::SetUpTestCase() @@ -177,6 +179,7 @@ void AbilityManagerServiceTest::TearDownTestCase() void AbilityManagerServiceTest::SetUp() { + abilityMs_ = OHOS::DelayedSingleton::GetInstance(); OnStartAms(); WaitUntilTaskFinished(); if (abilityRecord_ == nullptr) { @@ -185,11 +188,13 @@ void AbilityManagerServiceTest::SetUp() abilityRequest_.abilityInfo.type = AbilityType::DATA; abilityRecord_ = AbilityRecord::CreateAbilityRecord(abilityRequest_); } + } void AbilityManagerServiceTest::TearDown() { OnStopAms(); + OHOS::DelayedSingleton::DestroyInstance(); } /* diff --git a/services/abilitymgr/test/unittest/phone/ability_manager_stub_test/ability_manager_stub_impl_mock.h b/services/abilitymgr/test/unittest/phone/ability_manager_stub_test/ability_manager_stub_impl_mock.h index ea21028ca66dcab3e9d6250d3d68cf69d9daac44..344172f54992adb057a04bf43afd08fe0e37b215 100644 --- a/services/abilitymgr/test/unittest/phone/ability_manager_stub_test/ability_manager_stub_impl_mock.h +++ b/services/abilitymgr/test/unittest/phone/ability_manager_stub_test/ability_manager_stub_impl_mock.h @@ -49,7 +49,7 @@ public: MOCK_METHOD2(GetWantSenderInfo, int(const sptr &target, std::shared_ptr &info)); MOCK_METHOD2(SetMissionLabel, int(const sptr &token, const std::string &label)); MOCK_METHOD3(StartContinuation, int(const Want &want, const sptr &abilityToken, int32_t status)); - MOCK_METHOD2(NotifyContinuationResult, int(int32_t missionId, int32_t result)); + MOCK_METHOD2(NotifyContinuationResult, int(int32_t missionId, const int32_t result)); MOCK_METHOD5(ContinueMission, int(const std::string &srcDeviceId, const std::string &dstDeviceId, int32_t missionId, const sptr &callBack, AAFwk::WantParams &wantParams)); MOCK_METHOD2(ContinueAbility, int(const std::string &deviceId, int32_t missionId)); @@ -357,10 +357,6 @@ public: { return 0; } - virtual int MoveMissionToFront(int32_t missionId, const StartOptions &startOptions) override - { - return 0; - } virtual int GetMissionInfos(const std::string& deviceId, int32_t numMax, std::vector &missionInfos) override { diff --git a/services/abilitymgr/test/unittest/phone/ability_manager_test/ability_manager_stub_mock.h b/services/abilitymgr/test/unittest/phone/ability_manager_test/ability_manager_stub_mock.h index 2b6a3166749c55e03cb0f1542c2a28989c081914..c7af16c31827a49985c07079bb982642dffd58b2 100644 --- a/services/abilitymgr/test/unittest/phone/ability_manager_test/ability_manager_stub_mock.h +++ b/services/abilitymgr/test/unittest/phone/ability_manager_test/ability_manager_stub_mock.h @@ -124,7 +124,7 @@ public: return 0; } MOCK_METHOD3(StartContinuation, int(const Want &want, const sptr &abilityToken, int32_t status)); - MOCK_METHOD2(NotifyContinuationResult, int(int32_t missionId, int32_t result)); + MOCK_METHOD2(NotifyContinuationResult, int(int32_t missionId, const int32_t result)); MOCK_METHOD5(ContinueMission, int(const std::string &srcDeviceId, const std::string &dstDeviceId, int32_t missionId, const sptr &callBack, AAFwk::WantParams &wantParams)); MOCK_METHOD2(ContinueAbility, int(const std::string &deviceId, int32_t missionId)); diff --git a/services/abilitymgr/test/unittest/phone/ability_scheduler_stub_test/ability_schedule_stub_mock.h b/services/abilitymgr/test/unittest/phone/ability_scheduler_stub_test/ability_schedule_stub_mock.h index ce061009455fb9542e134f5bd19a36c0883b36d4..a1a4ef18a9813e5b80d0881985e723586171e0d7 100755 --- a/services/abilitymgr/test/unittest/phone/ability_scheduler_stub_test/ability_schedule_stub_mock.h +++ b/services/abilitymgr/test/unittest/phone/ability_scheduler_stub_test/ability_schedule_stub_mock.h @@ -129,11 +129,11 @@ public: { return std::vector>(); } - virtual void NotifyContinuationResult(int32_t result) override + virtual void NotifyContinuationResult(const int32_t result) override {} virtual void ContinueAbility(const std::string& deviceId) override {} - virtual void DumpAbilityInfo(const std::vector ¶ms, std::vector &info) override + virtual void DumpAbilityInfo(std::vector &info) override {} virtual sptr CallRequest() override { @@ -143,4 +143,4 @@ public: } // namespace AAFwk } // namespace OHOS -#endif +#endif \ No newline at end of file diff --git a/services/abilitymgr/test/unittest/phone/abilityms_appms_test/abilityms_appms_test.cpp b/services/abilitymgr/test/unittest/phone/abilityms_appms_test/abilityms_appms_test.cpp index a529e853178f331ecd1a0a2491bc7356270dafe6..2ea8b76aa7abcea5c565ed08fd0d51d580ac1ce9 100644 --- a/services/abilitymgr/test/unittest/phone/abilityms_appms_test/abilityms_appms_test.cpp +++ b/services/abilitymgr/test/unittest/phone/abilityms_appms_test/abilityms_appms_test.cpp @@ -86,7 +86,8 @@ public: public: std::shared_ptr abilityRecord_ {nullptr}; - std::shared_ptr abilityMs_ = DelayedSingleton::GetInstance(); + std::shared_ptr callback_ {nullptr}; + std::shared_ptr abilityMs_ {nullptr}; }; void AbilityMsAppmsTest::OnStartabilityAms() @@ -134,20 +135,18 @@ void AbilityMsAppmsTest::OnStartabilityAms() } void AbilityMsAppmsTest::SetUpTestCase(void) -{ - DelayedSingleton::GetInstance()->RegisterSystemAbility( - OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, new BundleMgrService()); - DelayedSingleton::GetInstance()->Init(std::make_shared()); -} - +{} void AbilityMsAppmsTest::TearDownTestCase(void) -{ - OHOS::DelayedSingleton::DestroyInstance(); - DelayedSingleton::DestroyInstance(); -} +{} void AbilityMsAppmsTest::SetUp(void) { + DelayedSingleton::GetInstance()->RegisterSystemAbility( + OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, new BundleMgrService()); + DelayedSingleton::GetInstance(); + callback_ = std::make_shared(); + DelayedSingleton::GetInstance()->Init(callback_); + abilityMs_ = DelayedSingleton::GetInstance(); OnStartabilityAms(); StartAbility(); GTEST_LOG_(INFO) << "SetUp"; @@ -155,7 +154,8 @@ void AbilityMsAppmsTest::SetUp(void) void AbilityMsAppmsTest::TearDown(void) { - abilityMs_->OnStop(); + OHOS::DelayedSingleton::DestroyInstance(); + DelayedSingleton::DestroyInstance(); GTEST_LOG_(INFO) << "TearDown"; } diff --git a/services/abilitymgr/test/unittest/phone/lifecycle_test/lifecycle_test.cpp b/services/abilitymgr/test/unittest/phone/lifecycle_test/lifecycle_test.cpp index 26defef799bf23db350d245c59deccdb4bf553dd..4870fe569abdfd78e40e2927771c7d2bc765a489 100644 --- a/services/abilitymgr/test/unittest/phone/lifecycle_test/lifecycle_test.cpp +++ b/services/abilitymgr/test/unittest/phone/lifecycle_test/lifecycle_test.cpp @@ -80,7 +80,7 @@ public: public: int startLancherFlag_ = false; - std::shared_ptr abilityMs_ = OHOS::DelayedSingleton::GetInstance(); + std::shared_ptr abilityMs_ {nullptr}; std::shared_ptr launcherAbilityRecord_ {nullptr}; // launcher ability OHOS::sptr launcherToken_ {nullptr}; // token of launcher ability std::shared_ptr nextAbilityRecord_ {nullptr}; // ability being launched @@ -143,6 +143,7 @@ void LifecycleTest::TearDownTestCase(void) void LifecycleTest::SetUp(void) { + abilityMs_ = OHOS::DelayedSingleton::GetInstance(); OnStartabilityAms(); WaitUntilTaskFinished(); StartLauncherAbility(); @@ -151,7 +152,11 @@ void LifecycleTest::SetUp(void) void LifecycleTest::TearDown(void) { - abilityMs_->OnStop(); + abilityMs_->eventLoop_->Stop(); + abilityMs_->eventLoop_.reset(); + abilityMs_->handler_.reset(); + abilityMs_->state_ = ServiceRunningState::STATE_NOT_START; + OHOS::DelayedSingleton::DestroyInstance(); launcherAbilityRecord_.reset(); launcherToken_ = nullptr; nextAbilityRecord_.reset(); @@ -159,6 +164,7 @@ void LifecycleTest::TearDown(void) launcherScheduler_ = nullptr; nextScheduler_ = nullptr; command_.reset(); + abilityMs_ = nullptr; startLancherFlag_ = false; } diff --git a/services/appmgr/include/app_mgr_service_inner.h b/services/appmgr/include/app_mgr_service_inner.h index 6d38e4a0c079e9a394369b8e80b4ee6fd2c8aafc..a80d7d69f66bf6b351903ed0d40b2fa423168185 100644 --- a/services/appmgr/include/app_mgr_service_inner.h +++ b/services/appmgr/include/app_mgr_service_inner.h @@ -208,7 +208,7 @@ public: * * @return ERR_OK, return back success, others fail. */ - virtual int32_t KillApplication(const std::string &bundleName); + virtual int32_t KillApplication(const std::string &bundleName, int32_t callerUid); /** * KillApplicationByUid, call KillApplicationByUid() through proxy object, kill the application. diff --git a/services/appmgr/src/ams_mgr_scheduler.cpp b/services/appmgr/src/ams_mgr_scheduler.cpp index 90019d2fbe1b8e564b756556fa1f87fad52dc5e1..5c08b91c7185a77c8469fea9079bf29e0267674e 100644 --- a/services/appmgr/src/ams_mgr_scheduler.cpp +++ b/services/appmgr/src/ams_mgr_scheduler.cpp @@ -193,7 +193,9 @@ int32_t AmsMgrScheduler::KillApplication(const std::string &bundleName) if (!IsReady()) { return ERR_INVALID_OPERATION; } - return amsMgrServiceInner_->KillApplication(bundleName); + + int32_t callerUid = IPCSkeleton::GetCallingUid(); + return amsMgrServiceInner_->KillApplication(bundleName, callerUid); } int32_t AmsMgrScheduler::KillApplicationByUid(const std::string &bundleName, const int uid) diff --git a/services/appmgr/src/app_mgr_service_inner.cpp b/services/appmgr/src/app_mgr_service_inner.cpp index 659ac291268f1f0cea9dcfa766ed876192222286..88ce4b1e1cd2d9607bed8a9bde90820dbe315e18 100644 --- a/services/appmgr/src/app_mgr_service_inner.cpp +++ b/services/appmgr/src/app_mgr_service_inner.cpp @@ -341,18 +341,29 @@ void AppMgrServiceInner::ApplicationTerminated(const int32_t recordId) APP_LOGI("application is terminated"); } -int32_t AppMgrServiceInner::KillApplication(const std::string &bundleName) +int32_t AppMgrServiceInner::KillApplication(const std::string &bundleName, int32_t callerUid) { if (!appRunningManager_) { APP_LOGE("appRunningManager_ is nullptr"); return ERR_NO_INIT; } + auto userId = GetUserIdByUid(callerUid); + APP_LOGI("userId:%{public}d", userId); + + auto bundleMgr_ = remoteClientManager_->GetBundleManager(); + if (bundleMgr_ == nullptr) { + APP_LOGE("GetBundleManager fail"); + return ERR_NO_INIT; + } + int uid = bundleMgr_->GetUidByBundleName(bundleName, userId); + APP_LOGI("uid value is %{public}d", uid); + int result = ERR_OK; int64_t startTime = SystemTimeMillis(); std::list pids; - if (!appRunningManager_->ProcessExitByBundleName(bundleName, pids)) { + if (!appRunningManager_->ProcessExitByBundleNameAndUid(bundleName, uid, pids)) { APP_LOGI("The process corresponding to the package name did not start"); return result; } @@ -451,7 +462,9 @@ int32_t AppMgrServiceInner::KillApplicationByUserId(const std::string &bundleNam void AppMgrServiceInner::ClearUpApplicationData(const std::string &bundleName, int32_t callerUid, pid_t callerPid) { BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__); - ClearUpApplicationDataByUserId(bundleName, callerUid, callerPid, Constants::DEFAULT_USERID); + auto userId = GetUserIdByUid(callerUid); + APP_LOGI("userId:%{public}d", userId); + ClearUpApplicationDataByUserId(bundleName, callerUid, callerPid, userId); } void AppMgrServiceInner::ClearUpApplicationDataByUserId( @@ -1721,23 +1734,9 @@ void AppMgrServiceInner::StartResidentProcess(const std::vector &inf } for (auto &bundle : infos) { - auto processName = bundle.applicationInfo.process.empty() ? - bundle.applicationInfo.bundleName : bundle.applicationInfo.process; + auto processName = + bundle.applicationInfo.process.empty() ? bundle.applicationInfo.bundleName : bundle.applicationInfo.process; APP_LOGI("processName = [%{public}s]", processName.c_str()); - - bool allElementNameEmpty = true; - for (auto hapModuleInfo : bundle.hapModuleInfos) { - if (!hapModuleInfo.mainElementName.empty()) { - // already start main element and process, no need start process again - allElementNameEmpty = false; - break; - } - } - if (!allElementNameEmpty) { - APP_LOGW("processName [%{public}s] Already exists ", processName.c_str()); - continue; - } - // Inspection records auto appRecord = appRunningManager_->CheckAppRunningRecordIsExist( bundle.applicationInfo.name, processName, bundle.applicationInfo.uid, bundle); diff --git a/services/appmgr/test/mock/include/mock_app_mgr_service_inner.h b/services/appmgr/test/mock/include/mock_app_mgr_service_inner.h index 5b0ceb1b50b0174807e1aebc8929968dcfca069e..0d4a28ebf18e1b5dd8d95beeb57b5ff29e7118d7 100644 --- a/services/appmgr/test/mock/include/mock_app_mgr_service_inner.h +++ b/services/appmgr/test/mock/include/mock_app_mgr_service_inner.h @@ -39,7 +39,7 @@ public: MOCK_METHOD1(ApplicationTerminated, void(const int32_t recordId)); MOCK_METHOD2(UpdateAbilityState, void(const sptr &token, const AbilityState state)); MOCK_METHOD1(TerminateAbility, void(const sptr &token)); - MOCK_METHOD1(KillApplication, int32_t(const std::string &bundleName)); + MOCK_METHOD2(KillApplication, int32_t(const std::string &bundleName, int32_t callerUid)); MOCK_METHOD2(KillApplicationByUid, int(const std::string &, const int uid)); MOCK_METHOD1(AbilityTerminated, void(const sptr &token)); MOCK_METHOD3(ClearUpApplicationData, void(const std::string &, const int32_t, const pid_t)); diff --git a/services/appmgr/test/mock/include/mock_bundle_manager.h b/services/appmgr/test/mock/include/mock_bundle_manager.h index 0ffda0cf9d4dcb35969c67a21916e634b08e6151..ba570e769af0070b18ffe524da2c9347ced334db 100755 --- a/services/appmgr/test/mock/include/mock_bundle_manager.h +++ b/services/appmgr/test/mock/include/mock_bundle_manager.h @@ -44,6 +44,7 @@ public: bool(const std::string &bundleName, const std::string &permission, const int userId)); MOCK_METHOD2(GetNameForUid, bool(const int uid, std::string &name)); MOCK_METHOD2(GetBundlesForUid, bool(const int uid, std::vector &)); + MOCK_METHOD2(SetAbilityEnabled, bool(const AbilityInfo &, bool)); MOCK_METHOD1(IsAbilityEnabled, bool(const AbilityInfo &)); MOCK_METHOD2(GetAbilityIcon, std::string(const std::string &bundleName, const std::string &className)); MOCK_METHOD1(RegisterAllPermissionsChanged, bool(const sptr &callback)); @@ -174,6 +175,12 @@ public: { return true; }; + // clears cache data of a specified application. + virtual bool CleanBundleCacheFiles( + const std::string &bundleName, const sptr &cleanCacheCallback) override + { + return true; + }; virtual bool CleanBundleDataFiles(const std::string &bundleName, const int userId = 0) override { return true; @@ -246,6 +253,7 @@ public: bool(const std::string &bundleName, const std::string &permission, const int userId)); MOCK_METHOD2(GetNameForUid, bool(const int uid, std::string &name)); MOCK_METHOD2(GetBundlesForUid, bool(const int uid, std::vector &)); + MOCK_METHOD2(SetAbilityEnabled, bool(const AbilityInfo &, bool)); MOCK_METHOD1(IsAbilityEnabled, bool(const AbilityInfo &)); MOCK_METHOD2(GetAbilityIcon, std::string(const std::string &bundleName, const std::string &className)); MOCK_METHOD1(RegisterAllPermissionsChanged, bool(const sptr &callback)); @@ -340,6 +348,12 @@ public: { return true; }; + // clears cache data of a specified application. + virtual bool CleanBundleCacheFiles( + const std::string &bundleName, const sptr &cleanCacheCallback) override + { + return true; + }; virtual bool RegisterBundleStatusCallback(const sptr &bundleStatusCallback) override { @@ -375,6 +389,10 @@ public: { return true; }; + virtual bool SetApplicationEnabled(const std::string &bundleName, bool isEnable) override + { + return true; + }; virtual bool GetAllFormsInfo(std::vector &formInfos) override { return true; @@ -403,8 +421,7 @@ public: return true; } virtual bool NotifyAbilityLifeStatus( - const std::string &bundleName, const std::string &abilityName, - const int64_t launchTime, const int uid = 0) override + const std::string &bundleName, const std::string &abilityName, const int64_t launchTime, const int uid = 0) override { return true; } diff --git a/services/appmgr/test/mock/src/mock_bundle_manager.cpp b/services/appmgr/test/mock/src/mock_bundle_manager.cpp index ca3ec28c311c6baa4388604409ed6cb968bbdbc5..562ad2b5c03a7068f6f2e11662a4e38e7b508365 100644 --- a/services/appmgr/test/mock/src/mock_bundle_manager.cpp +++ b/services/appmgr/test/mock/src/mock_bundle_manager.cpp @@ -52,6 +52,7 @@ bool BundleMgrProxy::GetApplicationInfo( std::string BundleMgrProxy::GetAppType(const std::string &bundleName) { + GTEST_LOG_(INFO) << " BundleMgrProxy::GetAppTyp"; return "system"; } @@ -104,17 +105,20 @@ bool BundleMgrService::GetApplicationInfo( std::string BundleMgrService::GetAppType(const std::string &bundleName) { + GTEST_LOG_(INFO) << " BundleMgrService::GetAppType"; return "system"; } bool BundleMgrService::GetHapModuleInfo(const AbilityInfo &abilityInfo, HapModuleInfo &hapModuleInfo) { + GTEST_LOG_(INFO) << " BundleMgrService::GetHapModuleInfo"; hapModuleInfo.name = "Captain"; return true; } bool BundleMgrProxy::GetHapModuleInfo(const AbilityInfo &abilityInfo, HapModuleInfo &hapModuleInfo) { + GTEST_LOG_(INFO) << " BundleMgrService::GetHapModuleInfo"; hapModuleInfo.name = "Captain"; return true; } diff --git a/services/appmgr/test/unittest/ams_app_life_cycle_test/ams_app_life_cycle_test.cpp b/services/appmgr/test/unittest/ams_app_life_cycle_test/ams_app_life_cycle_test.cpp index 1a1d2e20a582f8da8a841ca8301e79c406949289..b0196d811e79e8b062615cb6941be92cec824138 100644 --- a/services/appmgr/test/unittest/ams_app_life_cycle_test/ams_app_life_cycle_test.cpp +++ b/services/appmgr/test/unittest/ams_app_life_cycle_test/ams_app_life_cycle_test.cpp @@ -86,7 +86,6 @@ protected: std::shared_ptr serviceInner_; sptr mock_token_ = nullptr; sptr mockBundleMgr = nullptr; - std::shared_ptr runner_ = nullptr; std::shared_ptr handler_ = nullptr; sptr mockAppStateCallbackStub_ = nullptr; }; @@ -104,17 +103,13 @@ void AmsAppLifeCycleTest::SetUp() mockBundleMgr = new (std::nothrow) BundleMgrService(); serviceInner_->SetBundleManager(mockBundleMgr); - runner_ = EventRunner::Create("AmsAppLifeCycleTest"); - handler_ = std::make_shared(runner_, serviceInner_); + auto runner = EventRunner::Create("AmsAppLifeCycleTest"); + handler_ = std::make_shared(runner, serviceInner_); serviceInner_->SetEventHandler(handler_); } void AmsAppLifeCycleTest::TearDown() -{ - serviceInner_ = nullptr; - handler_ = nullptr; - runner_.reset(); -} +{} std::shared_ptr AmsAppLifeCycleTest::StartProcessAndLoadAbility(const sptr &token, const sptr &preToken, const std::shared_ptr &abilityInfo, @@ -1477,10 +1472,74 @@ HWTEST_F(AmsAppLifeCycleTest, Stop_003, TestSize.Level1) */ HWTEST_F(AmsAppLifeCycleTest, KillApplication_001, TestSize.Level1) { - int result = serviceInner_->KillApplication("hwei.ss.bb"); + auto uid = 1000; + int result = serviceInner_->KillApplication("hwei.ss.bb", uid); EXPECT_EQ(ERR_OK, result); } +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Kill application + * CaseDescription: Verify if AppMgrService Kill by appname successfully. + */ +HWTEST_F(AmsAppLifeCycleTest, KillApplication_002, TestSize.Level1) +{ + const pid_t NEW_PID = 123; + auto abilityInfo = GetAbilityInfoByIndex("0"); + auto appInfo = GetApplication(); + sptr token = GetMockToken(); + + std::shared_ptr mockClientPtr = std::make_shared(); + EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(1).WillOnce(DoAll(SetArgReferee<1>(NEW_PID), Return(ERR_OK))); + + serviceInner_->SetAppSpawnClient(mockClientPtr); + + serviceInner_->LoadAbility(token, nullptr, abilityInfo, appInfo); + BundleInfo bundleInfo; + bundleInfo.appId = "com.ohos.test.helloworld_code123"; + auto appRecord = serviceInner_->appRunningManager_->CheckAppRunningRecordIsExist( + appInfo->name, appInfo->name, appInfo->uid, bundleInfo); + EXPECT_EQ(appRecord->GetPriorityObject()->GetPid(), NEW_PID); + + pid_t pid = fork(); + if (pid > 0) { + appRecord->GetPriorityObject()->SetPid(pid); + } + + sptr mockAppScheduler = new MockAppScheduler(); + sptr client = iface_cast(mockAppScheduler.GetRefPtr()); + appRecord->SetApplicationClient(client); + EXPECT_CALL(*mockAppScheduler, ScheduleProcessSecurityExit()).Times(1); + + auto uid = 1000; + int ret = serviceInner_->KillApplication(abilityInfo->applicationName, uid); + EXPECT_EQ(ERR_OK, ret); +} + +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: Schedule + * FunctionPoints: Kill application + * CaseDescription: Verify if AppMgrService Kill by pid successfully. + */ +HWTEST_F(AmsAppLifeCycleTest, KillProcessByPid001, TestSize.Level1) +{ + pid_t pid = fork(); + + if (pid > 0) { + int32_t ret = serviceInner_->KillProcessByPid(pid); + EXPECT_EQ(ERR_OK, ret); + } + + if (pid == 0) { + int32_t ret = serviceInner_->KillProcessByPid(pid); + EXPECT_EQ(-1, ret); + } +} + /* * Feature: AMS * Function: AppLifeCycle @@ -1837,6 +1896,33 @@ HWTEST_F(AmsAppLifeCycleTest, ClearUpApplicationData_001, TestSize.Level1) serviceInner_->ClearUpApplicationData(appRecord->GetBundleName(), appRecord->GetUid(), NEW_PID); } +/* + * Feature: AMS + * Function: AppLifeCycle + * SubFunction: ClearUpApplicationData + * FunctionPoints: UnsuspendApplication + * CaseDescription: test application state is APP_STATE_BACKGROUND(apprecord is nullptr) + */ +HWTEST_F(AmsAppLifeCycleTest, ClearUpApplicationData_002, TestSize.Level1) +{ + auto abilityInfo = GetAbilityInfoByIndex("110"); + auto appInfo = GetApplication(); + sptr token = GetMockToken(); + + int32_t pid = fork(); + + if (pid > 0) { + auto appRecord = StartProcessAndLoadAbility(token, nullptr, abilityInfo, appInfo, pid); + + EXPECT_CALL(*mockBundleMgr, CleanBundleDataFiles(_, _)).Times(1).WillOnce(Return(101)); + appRecord->SetUid(101); + sptr mockAppScheduler = new MockAppScheduler(); + sptr client = iface_cast(mockAppScheduler.GetRefPtr()); + appRecord->SetApplicationClient(client); + serviceInner_->ClearUpApplicationData(appRecord->GetBundleName(), appRecord->GetUid(), pid); + } +} + /* * Feature: AMS * Function: AppLifeCycle::IsBackgroundRunningRestricted diff --git a/services/appmgr/test/unittest/ams_mgr_scheduler_test/ams_mgr_scheduler_test.cpp b/services/appmgr/test/unittest/ams_mgr_scheduler_test/ams_mgr_scheduler_test.cpp index 6734c2ef1319131bb2e9c1c6a80b85d710ea1f83..526ec395e38ec0e3b38db2c28ba15d6f45248a62 100644 --- a/services/appmgr/test/unittest/ams_mgr_scheduler_test/ams_mgr_scheduler_test.cpp +++ b/services/appmgr/test/unittest/ams_mgr_scheduler_test/ams_mgr_scheduler_test.cpp @@ -311,7 +311,7 @@ HWTEST_F(AmsMgrSchedulerTest, AmsMgrScheduler_008, TestSize.Level1) auto mockAppMgrServiceInner = GetMockAppMgrServiceInner(); auto amsEventHandler = GetAmsEventHandler(); - EXPECT_CALL(*mockAppMgrServiceInner, KillApplication(_)).Times(1).WillOnce(Return(ERR_OK)); + EXPECT_CALL(*mockAppMgrServiceInner, KillApplication(_, _)).Times(1).WillOnce(Return(ERR_OK)); // check params AppMgrServiceInner std::unique_ptr amsMgrScheduler2 = std::make_unique(nullptr, amsEventHandler); diff --git a/services/appmgr/test/unittest/ams_service_event_drive_test/ams_service_event_drive_test.cpp b/services/appmgr/test/unittest/ams_service_event_drive_test/ams_service_event_drive_test.cpp index f17bbdbe68929302eb15f30b31a88f0c67a71447..093b1e7ccb936ef01098e9ff1492f75bf713b2ad 100644 --- a/services/appmgr/test/unittest/ams_service_event_drive_test/ams_service_event_drive_test.cpp +++ b/services/appmgr/test/unittest/ams_service_event_drive_test/ams_service_event_drive_test.cpp @@ -47,7 +47,7 @@ public: std::shared_ptr GetAmsEventHandler(); protected: - std::shared_ptr appMgrService_ = std::make_shared(); + std::shared_ptr appMgrService_; }; void AmsServiceEventDriveTest::SetUpTestCase() @@ -58,13 +58,11 @@ void AmsServiceEventDriveTest::TearDownTestCase() void AmsServiceEventDriveTest::SetUp() { - appMgrService_->OnStart(); + appMgrService_ = std::make_shared(); } void AmsServiceEventDriveTest::TearDown() -{ - appMgrService_->OnStop(); -} +{} /* * Feature: AppMgrService @@ -286,7 +284,6 @@ HWTEST_F(AmsServiceEventDriveTest, EventDrive_009, TestSize.Level1) { APP_LOGI("ams_service_event_drive_test_009 start"); - appMgrService_->OnStop(); std::shared_ptr innerService = std::make_shared(); appMgrService_->SetInnerService(innerService); @@ -310,7 +307,6 @@ HWTEST_F(AmsServiceEventDriveTest, EventDrive_010, TestSize.Level1) { APP_LOGI("ams_service_event_drive_test_010 start"); - appMgrService_->OnStop(); std::shared_ptr innerService = std::make_shared(); appMgrService_->SetInnerService(innerService); @@ -334,7 +330,6 @@ HWTEST_F(AmsServiceEventDriveTest, EventDrive_011, TestSize.Level1) { APP_LOGI("ams_service_event_drive_test_011 start"); - appMgrService_->OnStop(); std::shared_ptr innerService = std::make_shared(); appMgrService_->SetInnerService(innerService); @@ -358,7 +353,6 @@ HWTEST_F(AmsServiceEventDriveTest, EventDrive_012, TestSize.Level1) { APP_LOGI("ams_service_event_drive_test_012 start"); - appMgrService_->OnStop(); std::shared_ptr innerService = std::make_shared(); appMgrService_->SetInnerService(innerService); @@ -382,7 +376,6 @@ HWTEST_F(AmsServiceEventDriveTest, EventDrive_013, TestSize.Level1) { APP_LOGI("ams_service_event_drive_test_013 start"); - appMgrService_->OnStop(); std::shared_ptr innerService = std::make_shared(); appMgrService_->SetInnerService(innerService); @@ -406,7 +399,6 @@ HWTEST_F(AmsServiceEventDriveTest, EventDrive_014, TestSize.Level1) { APP_LOGI("ams_service_event_drive_test_014 start"); - appMgrService_->OnStop(); std::shared_ptr innerService = std::make_shared(); appMgrService_->SetInnerService(innerService); @@ -430,7 +422,6 @@ HWTEST_F(AmsServiceEventDriveTest, EventDrive_015, TestSize.Level1) { APP_LOGI("ams_service_event_drive_test_015 start"); - appMgrService_->OnStop(); std::shared_ptr innerService = std::make_shared(); appMgrService_->SetInnerService(innerService); @@ -452,7 +443,6 @@ HWTEST_F(AmsServiceEventDriveTest, EventDrive_016, TestSize.Level1) { APP_LOGI("ams_service_event_drive_test_016 start"); - appMgrService_->OnStop(); std::shared_ptr innerService = std::make_shared(); appMgrService_->SetInnerService(innerService); @@ -866,7 +856,6 @@ HWTEST_F(AmsServiceEventDriveTest, EventDrive_035, TestSize.Level1) { APP_LOGI("ams_service_event_drive_test_035 start"); - appMgrService_->OnStop(); std::shared_ptr innerService = std::make_shared(); appMgrService_->SetInnerService(innerService); @@ -939,7 +928,6 @@ HWTEST_F(AmsServiceEventDriveTest, EventDrive_038, TestSize.Level1) { APP_LOGI("ams_service_event_drive_test_038 start"); - appMgrService_->OnStop(); std::shared_ptr innerService = std::make_shared(); appMgrService_->SetInnerService(innerService); @@ -982,6 +970,7 @@ HWTEST_F(AmsServiceEventDriveTest, EventDrive_039, TestSize.Level1) * EnvConditions: Mobile that can run ohos test framework * CaseDescription: Verify if QueryServiceState act normal after AppMgrService stopped */ +/* HWTEST_F(AmsServiceEventDriveTest, EventDrive_040, TestSize.Level1) { APP_LOGI("AppMgrService::EventDrive_040 start 1"); @@ -1001,6 +990,7 @@ HWTEST_F(AmsServiceEventDriveTest, EventDrive_040, TestSize.Level1) APP_LOGI("AppMgrService::EventDrive_040 end"); } +*/ /* * Feature: AppMgrService diff --git a/services/formmgr/src/form_mgr_service.cpp b/services/formmgr/src/form_mgr_service.cpp index e61d0f15ae9d196a1fb8cd2b51d183ee3be95871..7eff4a62a66e85c7ae3767620e5c01cd9d6045fb 100644 --- a/services/formmgr/src/form_mgr_service.cpp +++ b/services/formmgr/src/form_mgr_service.cpp @@ -61,10 +61,8 @@ FormMgrService::FormMgrService() FormMgrService::~FormMgrService() { - if (formSysEventReceiver_ != nullptr) { - EventFwk::CommonEventManager::UnSubscribeCommonEvent(formSysEventReceiver_); - formSysEventReceiver_ = nullptr; - } + EventFwk::CommonEventManager::UnSubscribeCommonEvent(formSysEventReceiver_); + formSysEventReceiver_ = nullptr; } bool FormMgrService::IsReady() const diff --git a/services/formmgr/test/mock/include/mock_ability_manager.h b/services/formmgr/test/mock/include/mock_ability_manager.h index 80b69f608f24e525fd8dc03643322e487228db95..1471e06786061003bfaac3306805a6f80642e335 100644 --- a/services/formmgr/test/mock/include/mock_ability_manager.h +++ b/services/formmgr/test/mock/include/mock_ability_manager.h @@ -268,7 +268,7 @@ public: { return 0; } - int NotifyContinuationResult(int32_t missionId, int32_t result) override + int NotifyContinuationResult(int32_t missionId, const int32_t result) override { return 0; } @@ -329,10 +329,7 @@ public: { return 0; } - virtual int MoveMissionToFront(int32_t missionId, const StartOptions &startOptions) override - { - return 0; - } + virtual int SetMissionLabel(const sptr &token, const std::string &lable) override { @@ -712,7 +709,7 @@ public: { return 0; } - int NotifyContinuationResult(int32_t missionId, int32_t result) override + int NotifyContinuationResult(int32_t missionId, const int32_t result) override { return 0; } @@ -801,10 +798,6 @@ public: { return 0; } - virtual int MoveMissionToFront(int32_t missionId, const StartOptions &startOptions) override - { - return 0; - } virtual int StartSyncRemoteMissions(const std::string& devId, bool fixConflict, int64_t tag) override { return 0; diff --git a/services/formmgr/test/mock/include/mock_bundle_manager.h b/services/formmgr/test/mock/include/mock_bundle_manager.h index b833123f9a4b78e6f411569c1652e57871bb78a6..91459d4fde8f36c7abdb5b64147eb8cc9744d386 100755 --- a/services/formmgr/test/mock/include/mock_bundle_manager.h +++ b/services/formmgr/test/mock/include/mock_bundle_manager.h @@ -40,6 +40,7 @@ public: bool(const std::string &bundleName, const std::string &permission, const int userId)); MOCK_METHOD2(GetNameForUid, bool(const int uid, std::string &name)); MOCK_METHOD2(GetBundlesForUid, bool(const int uid, std::vector &)); + MOCK_METHOD2(SetAbilityEnabled, bool(const AbilityInfo &, bool)); MOCK_METHOD1(IsAbilityEnabled, bool(const AbilityInfo &)); MOCK_METHOD1(RegisterAllPermissionsChanged, bool(const sptr &callback)); MOCK_METHOD2(RegisterPermissionsChanged, @@ -157,6 +158,12 @@ public: { return true; } + // clears cache data of a specified application. + virtual bool CleanBundleCacheFiles( + const std::string &bundleName, const sptr &cleanCacheCallback) override + { + return true; + } virtual bool CleanBundleDataFiles(const std::string &bundleName, const int userId = 0) override { return true; @@ -233,6 +240,10 @@ public: { return true; } + virtual bool SetApplicationEnabled(const std::string &bundleName, bool isEnable) override + { + return true; + } virtual bool GetBundleInfo( const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo, int32_t userId) override; @@ -259,6 +270,7 @@ public: bool(const std::string &bundleName, const std::string &permission, const int userId)); MOCK_METHOD2(GetNameForUid, bool(const int uid, std::string &name)); MOCK_METHOD2(GetBundlesForUid, bool(const int uid, std::vector &)); + MOCK_METHOD2(SetAbilityEnabled, bool(const AbilityInfo &, bool)); MOCK_METHOD1(IsAbilityEnabled, bool(const AbilityInfo &)); MOCK_METHOD1(RegisterAllPermissionsChanged, bool(const sptr &callback)); MOCK_METHOD2(RegisterPermissionsChanged, @@ -351,6 +363,12 @@ public: { return true; }; + // clears cache data of a specified application. + virtual bool CleanBundleCacheFiles( + const std::string &bundleName, const sptr &cleanCacheCallback) override + { + return true; + }; virtual bool RegisterBundleStatusCallback(const sptr &bundleStatusCallback) override { @@ -390,6 +408,10 @@ public: return true; }; + virtual bool SetApplicationEnabled(const std::string &bundleName, bool isEnable) override + { + return true; + }; virtual bool GetBundleGidsByUid(const std::string &bundleName, const int &uid, std::vector &gids) override { return true; @@ -462,8 +484,7 @@ public: return true; } virtual bool NotifyAbilityLifeStatus( - const std::string &bundleName, const std::string &abilityName, - const int64_t launchTime, const int uid = 0) override + const std::string &bundleName, const std::string &abilityName, const int64_t launchTime, const int uid = 0) override { return true; } diff --git a/services/formmgr/test/unittest/fms_form_host_record_test/fms_form_host_record_test.cpp b/services/formmgr/test/unittest/fms_form_host_record_test/fms_form_host_record_test.cpp index 2388329a8ad8024337b0521f529a4ea82cd2147a..2b29e51a9f858eec7b2c2ec176467de61ad1a13b 100644 --- a/services/formmgr/test/unittest/fms_form_host_record_test/fms_form_host_record_test.cpp +++ b/services/formmgr/test/unittest/fms_form_host_record_test/fms_form_host_record_test.cpp @@ -67,13 +67,13 @@ public: protected: sptr token_; std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); + + sptr mockBundleMgr_; + sptr mockAbilityMgrServ_; }; void FmsFormHostRecordTest::SetUpTestCase() -{ - FormBmsHelper::GetInstance().SetBundleManager(new BundleMgrService()); - FormAmsHelper::GetInstance().SetAbilityManager(new MockAbilityMgrService()); -} +{} void FmsFormHostRecordTest::TearDownTestCase() {} @@ -81,6 +81,14 @@ void FmsFormHostRecordTest::TearDownTestCase() void FmsFormHostRecordTest::SetUp() { formyMgrServ_->OnStart(); + + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + EXPECT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); + + mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); + FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); + token_ = new (std::nothrow) MockFormHostClient(); // Permission install diff --git a/services/formmgr/test/unittest/fms_form_mgr_add_form_test/fms_form_mgr_add_form_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_add_form_test/fms_form_mgr_add_form_test.cpp index f651a81d5c3cf678aed0772d7045224e2696d02b..e6cad4e0edc7752ef33a9b13b06a592dae3d3e5f 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_add_form_test/fms_form_mgr_add_form_test.cpp +++ b/services/formmgr/test/unittest/fms_form_mgr_add_form_test/fms_form_mgr_add_form_test.cpp @@ -71,20 +71,30 @@ public: protected: sptr token_; std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); + + sptr mockBundleMgr_; + sptr mockAbilityMgrServ_; }; void FmsFormMgrAddFormTest::SetUpTestCase() -{ - FormBmsHelper::GetInstance().SetBundleManager(new BundleMgrService()); - FormAmsHelper::GetInstance().SetAbilityManager(new MockAbilityMgrService()); -} +{} void FmsFormMgrAddFormTest::TearDownTestCase() {} void FmsFormMgrAddFormTest::SetUp() { + // APP_LOGI("fms_form_mgr_client_test_001 setup"); formyMgrServ_->OnStart(); + + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + EXPECT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); + + mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); + FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); + + // APP_LOGI("fms_form_mgr_client_test_001 FormMgrService started"); token_ = new (std::nothrow) MockFormHostClient(); // Permission install @@ -106,9 +116,7 @@ void FmsFormMgrAddFormTest::SetUp() } void FmsFormMgrAddFormTest::TearDown() -{ - formyMgrServ_->OnStop(); -} +{} /* * Feature: FormMgrService diff --git a/services/formmgr/test/unittest/fms_form_mgr_cast_temp_form_test/fms_form_mgr_cast_temp_form_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_cast_temp_form_test/fms_form_mgr_cast_temp_form_test.cpp index cd116a163b87249677aa54f07fa8f49e62ab70bf..9dd4306f69d7445d388caaf6e90e1718683d47c5 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_cast_temp_form_test/fms_form_mgr_cast_temp_form_test.cpp +++ b/services/formmgr/test/unittest/fms_form_mgr_cast_temp_form_test/fms_form_mgr_cast_temp_form_test.cpp @@ -70,13 +70,13 @@ public: protected: sptr token_; std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); + + sptr mockBundleMgr_; + sptr mockAbilityMgrServ_; }; void FmsFormMgrCastTempFormTest::SetUpTestCase() -{ - FormBmsHelper::GetInstance().SetBundleManager(new BundleMgrService()); - FormAmsHelper::GetInstance().SetAbilityManager(new MockAbilityMgrService()); -} +{} void FmsFormMgrCastTempFormTest::TearDownTestCase() {} @@ -84,6 +84,14 @@ void FmsFormMgrCastTempFormTest::TearDownTestCase() void FmsFormMgrCastTempFormTest::SetUp() { formyMgrServ_->OnStart(); + + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + ASSERT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); + + mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); + FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); + token_ = new (std::nothrow) MockFormHostClient(); // Permission install diff --git a/services/formmgr/test/unittest/fms_form_mgr_death_callback_test/fms_form_mgr_death_callback_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_death_callback_test/fms_form_mgr_death_callback_test.cpp index a28dee10fdda2ff2ab35cffa6acdf77eec105f0a..f9b45712fd4874fd9d63f026fffb4bbe1efa2395 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_death_callback_test/fms_form_mgr_death_callback_test.cpp +++ b/services/formmgr/test/unittest/fms_form_mgr_death_callback_test/fms_form_mgr_death_callback_test.cpp @@ -72,20 +72,30 @@ public: protected: sptr token_; std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); + + sptr mockBundleMgr_; + sptr mockAbilityMgrServ_; }; void FmsFormMgrDeathCallbackTest::SetUpTestCase() -{ - FormBmsHelper::GetInstance().SetBundleManager(new BundleMgrService()); - FormAmsHelper::GetInstance().SetAbilityManager(new MockAbilityMgrService()); -} +{} void FmsFormMgrDeathCallbackTest::TearDownTestCase() {} void FmsFormMgrDeathCallbackTest::SetUp() { + // APP_LOGI("fms_form_mgr_client_test_001 setup"); formyMgrServ_->OnStart(); + + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + EXPECT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); + + mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); + FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); + + // APP_LOGI("fms_form_mgr_client_test_001 FormMgrService started"); token_ = new (std::nothrow) MockFormHostClient(); // Permission install diff --git a/services/formmgr/test/unittest/fms_form_mgr_delete_form_test/fms_form_mgr_delete_form_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_delete_form_test/fms_form_mgr_delete_form_test.cpp index 0f35979671fdb3f3bba40f9d009b301bb124e74c..d0ec63205f1c316a60b86966b7a773454f64bf51 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_delete_form_test/fms_form_mgr_delete_form_test.cpp +++ b/services/formmgr/test/unittest/fms_form_mgr_delete_form_test/fms_form_mgr_delete_form_test.cpp @@ -67,13 +67,13 @@ public: protected: sptr token_; std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); + + sptr mockBundleMgr_; + sptr mockAbilityMgrServ_; }; void FmsFormMgrDeleteFormTest::SetUpTestCase() -{ - FormBmsHelper::GetInstance().SetBundleManager(new BundleMgrService()); - FormAmsHelper::GetInstance().SetAbilityManager(new MockAbilityMgrService()); -} +{} void FmsFormMgrDeleteFormTest::TearDownTestCase() {} @@ -81,6 +81,14 @@ void FmsFormMgrDeleteFormTest::TearDownTestCase() void FmsFormMgrDeleteFormTest::SetUp() { formyMgrServ_->OnStart(); + + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + EXPECT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); + + mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); + FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); + token_ = new (std::nothrow) MockFormHostClient(); // Permission install diff --git a/services/formmgr/test/unittest/fms_form_mgr_lifecycle_update_test/fms_form_mgr_lifecycle_update_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_lifecycle_update_test/fms_form_mgr_lifecycle_update_test.cpp index 1718061927e7b57c7bf0375a7bc6085d8506d452..045433d88f0cb1d388eb92f59bd8a9e875694873 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_lifecycle_update_test/fms_form_mgr_lifecycle_update_test.cpp +++ b/services/formmgr/test/unittest/fms_form_mgr_lifecycle_update_test/fms_form_mgr_lifecycle_update_test.cpp @@ -56,22 +56,27 @@ public: void InitFormItemInfo(int64_t formId, FormItemInfo &formItemInfo) const; protected: + sptr mockBundleMgr_; std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); sptr token_; }; void FmsFormMgrLifecycleUpdateTest::SetUpTestCase() -{ - FormBmsHelper::GetInstance().SetBundleManager(new BundleMgrService()); -} +{} void FmsFormMgrLifecycleUpdateTest::TearDownTestCase() {} void FmsFormMgrLifecycleUpdateTest::SetUp() { + // APP_LOGI("fms_form_mgr_enable_update_test_001 setup"); formyMgrServ_->OnStart(); + // mock BundleMgr + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + ASSERT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); + // token token_ = new (std::nothrow) MockFormHostClient(); diff --git a/services/formmgr/test/unittest/fms_form_mgr_message_event_test/fms_form_mgr_message_event_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_message_event_test/fms_form_mgr_message_event_test.cpp index cc7870b1dcf6641b1715459f74dd2e714c7ed8f3..efa7bc176640925699a4dbb43db945464055118c 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_message_event_test/fms_form_mgr_message_event_test.cpp +++ b/services/formmgr/test/unittest/fms_form_mgr_message_event_test/fms_form_mgr_message_event_test.cpp @@ -69,13 +69,13 @@ public: protected: sptr token_; std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); + + sptr mockBundleMgr_; + sptr mockAbilityMgrServ_; }; void FmsFormMgrMessageEventTest::SetUpTestCase() -{ - FormBmsHelper::GetInstance().SetBundleManager(new BundleMgrService()); - FormAmsHelper::GetInstance().SetAbilityManager(new MockAbilityMgrService()); -} +{} void FmsFormMgrMessageEventTest::TearDownTestCase() {} @@ -83,6 +83,14 @@ void FmsFormMgrMessageEventTest::TearDownTestCase() void FmsFormMgrMessageEventTest::SetUp() { formyMgrServ_->OnStart(); + + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + EXPECT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); + + mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); + FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); + token_ = new (std::nothrow) MockFormHostClient(); // Permission install diff --git a/services/formmgr/test/unittest/fms_form_mgr_notify_invisible_forms_test/fms_form_mgr_notify_invisible_forms_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_notify_invisible_forms_test/fms_form_mgr_notify_invisible_forms_test.cpp index bb38d6a70fd7392108626bd9879b8335d02f9482..4f5adb323644a65f7abc2b66fd7eccaee70487dc 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_notify_invisible_forms_test/fms_form_mgr_notify_invisible_forms_test.cpp +++ b/services/formmgr/test/unittest/fms_form_mgr_notify_invisible_forms_test/fms_form_mgr_notify_invisible_forms_test.cpp @@ -45,27 +45,36 @@ const std::string DEF_LABEL1 = "PermissionFormRequireGrant"; class FmsFormMgrNotifyInvisibleFormsTest : public testing::Test { public: + FmsFormMgrNotifyInvisibleFormsTest() : formMgrService_(nullptr) + {} + ~FmsFormMgrNotifyInvisibleFormsTest() + {} static void SetUpTestCase(void); static void TearDownTestCase(void); void SetUp(); void TearDown(); protected: sptr token_; - std::shared_ptr formMgrService_; + sptr mockBundleMgr_; + std::shared_ptr formMgrService_ = DelayedSingleton::GetInstance(); }; void FmsFormMgrNotifyInvisibleFormsTest::SetUpTestCase(void) -{ - FormBmsHelper::GetInstance().SetBundleManager(new BundleMgrService()); -} +{} void FmsFormMgrNotifyInvisibleFormsTest::TearDownTestCase(void) {} void FmsFormMgrNotifyInvisibleFormsTest::SetUp(void) { - formMgrService_ = DelayedSingleton::GetInstance(); + formMgrService_ = std::make_shared(); + formMgrService_->OnStart(); + // mock BundleMgr + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + ASSERT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); + // token token_ = new (std::nothrow) OHOS::AppExecFwk::MockFormHostClient(); @@ -91,10 +100,7 @@ void FmsFormMgrNotifyInvisibleFormsTest::SetUp(void) } void FmsFormMgrNotifyInvisibleFormsTest::TearDown(void) -{ - formMgrService_->OnStop(); - token_ = nullptr; -} +{} /** * @tc.number: FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_002 diff --git a/services/formmgr/test/unittest/fms_form_mgr_notify_visible_forms_test/fms_form_mgr_notify_visible_forms_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_notify_visible_forms_test/fms_form_mgr_notify_visible_forms_test.cpp index a5d4d7f233e7e2d088ae013a98c6ec08fd4bd382..843686dbc7cd3893bd5961fd19b5246e3031f542 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_notify_visible_forms_test/fms_form_mgr_notify_visible_forms_test.cpp +++ b/services/formmgr/test/unittest/fms_form_mgr_notify_visible_forms_test/fms_form_mgr_notify_visible_forms_test.cpp @@ -56,20 +56,23 @@ public: void TearDown(); protected: sptr token_; - std::shared_ptr formMgrService_; + sptr mockBundleMgr_; + std::shared_ptr formMgrService_ = DelayedSingleton::GetInstance(); }; void FmsFormMgrNotifyVisibleFormsTest::SetUpTestCase(void) -{ - FormBmsHelper::GetInstance().SetBundleManager(new BundleMgrService()); -} +{} void FmsFormMgrNotifyVisibleFormsTest::TearDownTestCase(void) {} void FmsFormMgrNotifyVisibleFormsTest::SetUp(void) { - formMgrService_ = DelayedSingleton::GetInstance(); + formMgrService_ = std::make_shared(); formMgrService_->OnStart(); + + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + ASSERT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); token_ = new (std::nothrow) MockFormHostClient(); // Permission install diff --git a/services/formmgr/test/unittest/fms_form_mgr_release_form_test/fms_form_mgr_release_form_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_release_form_test/fms_form_mgr_release_form_test.cpp index d8122862fcb50fc75c600dbe4be1a70d4539cef7..ca8bdd6c2a42ae9d79bf821fd2790dd5aaed9b13 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_release_form_test/fms_form_mgr_release_form_test.cpp +++ b/services/formmgr/test/unittest/fms_form_mgr_release_form_test/fms_form_mgr_release_form_test.cpp @@ -62,12 +62,11 @@ public: protected: sptr token_; std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); + sptr mockBundleMgr_; }; void FmsFormMgrReleaseFormTest::SetUpTestCase() -{ - FormBmsHelper::GetInstance().SetBundleManager(new BundleMgrService()); -} +{} void FmsFormMgrReleaseFormTest::TearDownTestCase() {} @@ -75,6 +74,9 @@ void FmsFormMgrReleaseFormTest::TearDownTestCase() void FmsFormMgrReleaseFormTest::SetUp() { formyMgrServ_->OnStart(); + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + ASSERT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); token_ = new (std::nothrow) MockFormHostClient(); // Permission install diff --git a/services/formmgr/test/unittest/fms_form_mgr_request_form_test/fms_form_mgr_request_form_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_request_form_test/fms_form_mgr_request_form_test.cpp index 08af6003557e775003a456ff6ca32665cf8f3c8b..feaecd160542faf7eb4113b37f862ba5294ad14a 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_request_form_test/fms_form_mgr_request_form_test.cpp +++ b/services/formmgr/test/unittest/fms_form_mgr_request_form_test/fms_form_mgr_request_form_test.cpp @@ -57,15 +57,14 @@ public: void TearDown(); protected: + sptr mockAbilityMgrServ_; + sptr mockBundleMgr_; sptr token_; std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); }; void FmsFormMgrRequestFormTest::SetUpTestCase() -{ - FormBmsHelper::GetInstance().SetBundleManager(new BundleMgrService()); - FormAmsHelper::GetInstance().SetAbilityManager(new MockAbilityMgrService()); -} +{} void FmsFormMgrRequestFormTest::TearDownTestCase() {} @@ -73,8 +72,15 @@ void FmsFormMgrRequestFormTest::TearDownTestCase() void FmsFormMgrRequestFormTest::SetUp() { formyMgrServ_->OnStart(); + token_ = new (std::nothrow) MockFormHostClient(); + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + ASSERT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); + + mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); + FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); // Permission install std::vector permList; Permission::PermissionDef permDef; diff --git a/services/formmgr/test/unittest/fms_form_mgr_update_form_test/fms_form_mgr_update_form_test.cpp b/services/formmgr/test/unittest/fms_form_mgr_update_form_test/fms_form_mgr_update_form_test.cpp index 311ee272f6fe04bc3677a9026490d01ec52476ac..559958c4f72d4edba4e72370eaa70fceb3052a70 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_update_form_test/fms_form_mgr_update_form_test.cpp +++ b/services/formmgr/test/unittest/fms_form_mgr_update_form_test/fms_form_mgr_update_form_test.cpp @@ -63,13 +63,13 @@ public: protected: sptr token_; std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); + + sptr mockBundleMgr_; + sptr mockAbilityMgrServ_; }; void FmsFormMgrUpdateFormTest::SetUpTestCase() -{ - FormBmsHelper::GetInstance().SetBundleManager(new BundleMgrService()); - FormAmsHelper::GetInstance().SetAbilityManager(new MockAbilityMgrService()); -} +{} void FmsFormMgrUpdateFormTest::TearDownTestCase() {} @@ -77,7 +77,16 @@ void FmsFormMgrUpdateFormTest::TearDownTestCase() void FmsFormMgrUpdateFormTest::SetUp() { APP_LOGI("fms_form_mgr_client_updateForm_test_001 setup"); + formyMgrServ_->OnStart(); + + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + ASSERT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); + + mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); + FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); + token_ = new (std::nothrow) MockFormHostClient(); // Permission install diff --git a/services/formmgr/test/unittest/fms_form_provider_mgr_test/fms_form_provider_mgr_test.cpp b/services/formmgr/test/unittest/fms_form_provider_mgr_test/fms_form_provider_mgr_test.cpp index a7ccb2ab73e8b038321645ce00b51c8a9ae78ada..cec93e35f57136a431338a6ed079da5aa2f2359a 100644 --- a/services/formmgr/test/unittest/fms_form_provider_mgr_test/fms_form_provider_mgr_test.cpp +++ b/services/formmgr/test/unittest/fms_form_provider_mgr_test/fms_form_provider_mgr_test.cpp @@ -68,20 +68,30 @@ public: protected: sptr token_; std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); + + sptr mockBundleMgr_; + sptr mockAbilityMgrServ_; }; void FmsFormProviderMgrTest::SetUpTestCase() -{ - FormBmsHelper::GetInstance().SetBundleManager(new BundleMgrService()); - FormAmsHelper::GetInstance().SetAbilityManager(new MockAbilityMgrService()); -} +{} void FmsFormProviderMgrTest::TearDownTestCase() {} void FmsFormProviderMgrTest::SetUp() { + // APP_LOGI("fms_form_mgr_client_test_001 setup"); formyMgrServ_->OnStart(); + + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + EXPECT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); + + mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); + FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); + + // APP_LOGI("fms_form_mgr_client_test_001 FormMgrService started"); token_ = new (std::nothrow) MockFormHostClient(); // Permission install diff --git a/services/formmgr/test/unittest/fms_form_set_next_refresh_test/fms_form_set_next_refresh_test.cpp b/services/formmgr/test/unittest/fms_form_set_next_refresh_test/fms_form_set_next_refresh_test.cpp index 7d18793db1e47d023bc416d3c57b93e9cba33465..c363f16e3a2b47b72c509f68f05106fe8876a3d3 100644 --- a/services/formmgr/test/unittest/fms_form_set_next_refresh_test/fms_form_set_next_refresh_test.cpp +++ b/services/formmgr/test/unittest/fms_form_set_next_refresh_test/fms_form_set_next_refresh_test.cpp @@ -49,32 +49,35 @@ public: {} ~FmsFormSetNextRefreshTest() {} + std::shared_ptr formSetNextRefresh_ = DelayedSingleton::GetInstance(); static void SetUpTestCase(void); static void TearDownTestCase(void); void SetUp(); void TearDown(); protected: - std::shared_ptr formSetNextRefresh_; + sptr mockBundleMgr_; }; - void FmsFormSetNextRefreshTest::SetUpTestCase(void) -{ - FormBmsHelper::GetInstance().SetBundleManager(new BundleMgrService()); -} +{} void FmsFormSetNextRefreshTest::TearDownTestCase(void) {} void FmsFormSetNextRefreshTest::SetUp(void) { - formSetNextRefresh_ = DelayedSingleton::GetInstance(); + formSetNextRefresh_ = std::make_shared(); + formSetNextRefresh_->OnStart(); + + // mock BundleMgr + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + ASSERT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); } void FmsFormSetNextRefreshTest::TearDown(void) -{ - formSetNextRefresh_->OnStop(); -} +{} + /** * @tc.number: FmsFormSetNextRefreshTest_SetNextRefreshTime_001 diff --git a/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/fms_form_sys_event_receiver_test.cpp b/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/fms_form_sys_event_receiver_test.cpp index 15ec57859335cf3ebf0f4409d858cde6dc3c103e..ada590a92a1c663f0f32c6b9cd07cdec0bbff63e 100644 --- a/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/fms_form_sys_event_receiver_test.cpp +++ b/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/fms_form_sys_event_receiver_test.cpp @@ -82,20 +82,30 @@ public: protected: sptr token_; std::shared_ptr formyMgrServ_ = DelayedSingleton::GetInstance(); + + sptr mockBundleMgr_; + sptr mockAbilityMgrServ_; }; void FmsFormSysEventReceiverTest::SetUpTestCase() -{ - FormBmsHelper::GetInstance().SetBundleManager(new BundleMgrService()); - FormAmsHelper::GetInstance().SetAbilityManager(new MockAbilityMgrService()); -} +{} void FmsFormSysEventReceiverTest::TearDownTestCase() {} void FmsFormSysEventReceiverTest::SetUp() { + // APP_LOGI("fms_form_mgr_client_test_001 setup"); formyMgrServ_->OnStart(); + + mockBundleMgr_ = new (std::nothrow) BundleMgrService(); + EXPECT_TRUE(mockBundleMgr_ != nullptr); + FormBmsHelper::GetInstance().SetBundleManager(mockBundleMgr_); + + mockAbilityMgrServ_ = new (std::nothrow) MockAbilityMgrService(); + FormAmsHelper::GetInstance().SetAbilityManager(mockAbilityMgrServ_); + + // APP_LOGI("fms_form_mgr_client_test_001 FormMgrService started"); token_ = new (std::nothrow) MockFormHostClient(); // Permission install diff --git a/services/formmgr/test/unittest/fms_form_timer_mgr_test/fms_form_timer_mgr_test.cpp b/services/formmgr/test/unittest/fms_form_timer_mgr_test/fms_form_timer_mgr_test.cpp index 0e1a0d43edcbdb8a9e5753b29128d2c20e41e4be..e41de5bc00a17ef34651ae5448d870d61e196bd8 100644 --- a/services/formmgr/test/unittest/fms_form_timer_mgr_test/fms_form_timer_mgr_test.cpp +++ b/services/formmgr/test/unittest/fms_form_timer_mgr_test/fms_form_timer_mgr_test.cpp @@ -539,6 +539,9 @@ HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0027, Function | MediumTest | Lev GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0027 start"; bool isAddOk4 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_6, 10, 30, 0); EXPECT_EQ(isAddOk4, true); + + std::this_thread::sleep_for(std::chrono::milliseconds(Constants::MIN_PERIOD)); + GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0027 end"; } } diff --git a/services/test/mock/include/appmgr/mock_ability_mgr_host.h b/services/test/mock/include/appmgr/mock_ability_mgr_host.h index 171319d34d773303259bfca9f38da1bf778eb1dd..3707f0dd010db4a3ecf8779b84293192b1f3c6e5 100644 --- a/services/test/mock/include/appmgr/mock_ability_mgr_host.h +++ b/services/test/mock/include/appmgr/mock_ability_mgr_host.h @@ -313,7 +313,7 @@ public: { return 0; } - int NotifyContinuationResult(int32_t missionId, int32_t result) override + int NotifyContinuationResult(int32_t missionId, const int32_t result) override { return 0; } @@ -375,10 +375,6 @@ public: { return 0; } - virtual int MoveMissionToFront(int32_t missionId, const StartOptions &startOptions) override - { - return 0; - } virtual int StartSyncRemoteMissions(const std::string& devId, bool fixConflict, int64_t tag) override { return 0; diff --git a/services/test/mock/include/mock_ability_mgr_service.h b/services/test/mock/include/mock_ability_mgr_service.h index 385f2b969d4f9d2b02c46db04ee44faba1634647..83fe2e1c4b33e5532f2c4b05e6fbde0fff269861 100644 --- a/services/test/mock/include/mock_ability_mgr_service.h +++ b/services/test/mock/include/mock_ability_mgr_service.h @@ -96,7 +96,7 @@ public: MOCK_METHOD1(SetShowOnLockScreen, int(bool isAllow)); MOCK_METHOD1(GetSystemMemoryAttr, void(AppExecFwk::SystemMemoryAttr &memoryInfo)); MOCK_METHOD3(StartContinuation, int(const Want &want, const sptr &abilityToken, int32_t status)); - MOCK_METHOD2(NotifyContinuationResult, int(int32_t missionId, int32_t result)); + MOCK_METHOD2(NotifyContinuationResult, int(int32_t missionId, const int32_t result)); MOCK_METHOD5(ContinueMission, int(const std::string &srcDeviceId, const std::string &dstDeviceId, int32_t missionId, const sptr &callBack, AAFwk::WantParams &wantParams)); MOCK_METHOD2(ContinueAbility, int(const std::string &deviceId, int32_t missionId)); @@ -112,7 +112,6 @@ public: MOCK_METHOD1(CleanMission, int(int32_t missionId)); MOCK_METHOD0(CleanAllMissions, int()); MOCK_METHOD1(MoveMissionToFront, int(int32_t missionId)); - MOCK_METHOD2(MoveMissionToFront, int(int32_t missionId, const StartOptions &startOptions)); MOCK_METHOD2(SetMissionLabel, int(const sptr &token, const std::string &label)); MOCK_METHOD1(ClearUpApplicationData, int(const std::string &)); diff --git a/services/test/mock/include/mock_ability_scheduler.h b/services/test/mock/include/mock_ability_scheduler.h index a5ab5274fef0fa390b0291b97ecb6d5a65caf1b4..b4afe3f78cca5d9149c8dbcc8ee1c7682e2af15a 100755 --- a/services/test/mock/include/mock_ability_scheduler.h +++ b/services/test/mock/include/mock_ability_scheduler.h @@ -42,9 +42,9 @@ public: ScheduleUnregisterObserver, bool(const Uri &uri, const sptr &dataObserver)); MOCK_METHOD1(ScheduleNotifyChange, bool(const Uri &uri)); MOCK_METHOD1(ExecuteBatch, std::vector>(const std::vector> &operations)); - MOCK_METHOD1(NotifyContinuationResult, void(int32_t result)); + MOCK_METHOD1(NotifyContinuationResult, void(const int32_t result)); MOCK_METHOD1(ContinueAbility, void(const std::string& deviceId)); - MOCK_METHOD2(DumpAbilityInfo, void(const std::vector ¶ms, std::vector &info)); + MOCK_METHOD1(DumpAbilityInfo, void(std::vector &info)); std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) { std::vector types; diff --git a/services/test/mock/include/mock_ability_scheduler_stub.h b/services/test/mock/include/mock_ability_scheduler_stub.h index 5e36df317adb91c9d33653e3639f2a032a2f9b15..1913d5afb088e839c3f1d10432e28b0e698e94af 100755 --- a/services/test/mock/include/mock_ability_scheduler_stub.h +++ b/services/test/mock/include/mock_ability_scheduler_stub.h @@ -51,9 +51,9 @@ public: MOCK_METHOD1(ScheduleNotifyChange, bool(const Uri &uri)); MOCK_METHOD1(ExecuteBatch, std::vector>( const std::vector> &operations)); - MOCK_METHOD1(NotifyContinuationResult, void(int32_t result)); + MOCK_METHOD1(NotifyContinuationResult, void(const int32_t result)); MOCK_METHOD1(ContinueAbility, void(const std::string& deviceId)); - MOCK_METHOD2(DumpAbilityInfo, void(const std::vector ¶ms, std::vector &info)); + MOCK_METHOD1(DumpAbilityInfo, void(std::vector &info)); virtual sptr CallRequest() { diff --git a/services/test/mock/include/mock_bundle_mgr.h b/services/test/mock/include/mock_bundle_mgr.h index ebba5c6557f8cc0c77e807a38f76d11073ff1f45..fed3a4471462bf0930e9ae5670c66b686303f43e 100644 --- a/services/test/mock/include/mock_bundle_mgr.h +++ b/services/test/mock/include/mock_bundle_mgr.h @@ -229,6 +229,8 @@ public: MOCK_METHOD1(HasSystemCapability, bool(const std::string &capName)); MOCK_METHOD1(GetSystemAvailableCapabilities, bool(std::vector &systemCaps)); MOCK_METHOD0(IsSafeMode, bool()); + MOCK_METHOD2(CleanBundleCacheFiles, + bool(const std::string &bundleName, const sptr &cleanCacheCallback)); MOCK_METHOD2(CleanBundleDataFiles, bool(const std::string &bundleName, const int userId)); MOCK_METHOD1(RegisterBundleStatusCallback, bool(const sptr &bundleStatusCallback)); MOCK_METHOD1(ClearBundleStatusCallback, bool(const sptr &bundleStatusCallback)); @@ -236,10 +238,12 @@ public: MOCK_METHOD4( DumpInfos, bool(const DumpFlag flag, const std::string &bundleName, int32_t userId, std::string &result)); MOCK_METHOD1(IsApplicationEnabled, bool(const std::string &bundleName)); + MOCK_METHOD2(SetApplicationEnabled, bool(const std::string &bundleName, bool isEnable)); MOCK_METHOD0(GetBundleInstaller, sptr()); MOCK_METHOD0(GetBundleUserMgr, sptr()); MOCK_METHOD2(GetNameForUid, bool(const int uid, std::string &name)); MOCK_METHOD2(GetBundlesForUid, bool(const int uid, std::vector &)); + MOCK_METHOD2(SetAbilityEnabled, bool(const AbilityInfo &, bool)); MOCK_METHOD1(IsAbilityEnabled, bool(const AbilityInfo &)); MOCK_METHOD2(GetAbilityIcon, std::string(const std::string &bundleName, const std::string &className)); MOCK_METHOD1(RegisterAllPermissionsChanged, bool(const sptr &callback)); @@ -290,6 +294,8 @@ public: MOCK_METHOD1(HasSystemCapability, bool(const std::string &capName)); MOCK_METHOD1(GetSystemAvailableCapabilities, bool(std::vector &systemCaps)); MOCK_METHOD0(IsSafeMode, bool()); + MOCK_METHOD2(CleanBundleCacheFiles, + bool(const std::string &bundleName, const sptr &cleanCacheCallback)); MOCK_METHOD2(CleanBundleDataFiles, bool(const std::string &bundleName, const int userId)); MOCK_METHOD1(RegisterBundleStatusCallback, bool(const sptr &bundleStatusCallback)); MOCK_METHOD1(ClearBundleStatusCallback, bool(const sptr &bundleStatusCallback)); @@ -297,6 +303,7 @@ public: MOCK_METHOD4( DumpInfos, bool(const DumpFlag flag, const std::string &bundleName, int32_t userId, std::string &result)); MOCK_METHOD1(IsApplicationEnabled, bool(const std::string &bundleName)); + MOCK_METHOD2(SetApplicationEnabled, bool(const std::string &bundleName, bool isEnable)); MOCK_METHOD0(GetBundleInstaller, sptr()); MOCK_METHOD0(GetBundleUserMgr, sptr()); MOCK_METHOD3( @@ -305,6 +312,7 @@ public: bool(const std::string &bundleName, const std::string &permission, const int userId)); MOCK_METHOD2(GetNameForUid, bool(const int uid, std::string &name)); MOCK_METHOD2(GetBundlesForUid, bool(const int uid, std::vector &)); + MOCK_METHOD2(SetAbilityEnabled, bool(const AbilityInfo &, bool)); MOCK_METHOD1(IsAbilityEnabled, bool(const AbilityInfo &)); MOCK_METHOD2(GetAbilityIcon, std::string(const std::string &bundleName, const std::string &className)); MOCK_METHOD1(RegisterAllPermissionsChanged, bool(const sptr &callback)); diff --git a/services/test/moduletest/common/ams/app_life_cycle_test/ams_app_life_cycle_module_test.cpp b/services/test/moduletest/common/ams/app_life_cycle_test/ams_app_life_cycle_module_test.cpp index 41ae0c5b356eb4ae89040f745f099435a68b994d..1b777e6470436aacbee5ee23bbf9120b5956bd67 100755 --- a/services/test/moduletest/common/ams/app_life_cycle_test/ams_app_life_cycle_module_test.cpp +++ b/services/test/moduletest/common/ams/app_life_cycle_test/ams_app_life_cycle_module_test.cpp @@ -682,7 +682,8 @@ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_006, TestSize.Level2) CheckState(appRunningRecord, token, AbilityState::ABILITY_STATE_BACKGROUND, ApplicationState::APP_STATE_BACKGROUND); EXPECT_CALL(*mockAppScheduler, ScheduleProcessSecurityExit()).Times(1); - int32_t ret = serviceInner_->KillApplication(appInfo->bundleName); + auto uid = 1000; + int32_t ret = serviceInner_->KillApplication(appInfo->bundleName, uid); EXPECT_EQ(ret, 0); serviceInner_->OnRemoteDied(mockAppScheduler); // A faked death recipient. auto record = serviceInner_->GetAppRunningRecordByAppRecordId(recordId); @@ -1710,7 +1711,9 @@ HWTEST_F(AmsAppLifeCycleModuleTest, KillApplication_001, TestSize.Level1) EXPECT_EQ(2, static_cast(appMap.size())); EXPECT_CALL(*mockAppScheduler, ScheduleProcessSecurityExit()).Times(1); EXPECT_CALL(*mockAppScheduler1, ScheduleProcessSecurityExit()).Times(1); - int32_t ret = serviceInner_->KillApplication("com.ohos.test.helloworld0"); + + auto uid = 1000; + int32_t ret = serviceInner_->KillApplication("com.ohos.test.helloworld0", uid); EXPECT_EQ(ret, 0); serviceInner_->OnRemoteDied(mockAppScheduler); // A faked death recipient. auto appMap1 = serviceInner_->appRunningManager_->GetAppRunningRecordMap(); @@ -1764,7 +1767,9 @@ HWTEST_F(AmsAppLifeCycleModuleTest, KillApplication_002, TestSize.Level1) auto appMap = serviceInner_->appRunningManager_->GetAppRunningRecordMap(); EXPECT_EQ(2, static_cast(appMap.size())); EXPECT_CALL(*mockAppScheduler, ScheduleProcessSecurityExit()).Times(1); - int32_t ret = serviceInner_->KillApplication("com.ohos.test.helloworld103"); + + auto uid = 1000; + int32_t ret = serviceInner_->KillApplication("com.ohos.test.helloworld103", uid); EXPECT_EQ(ret, 0); serviceInner_->OnRemoteDied(mockAppScheduler); // A faked death recipient. auto appMap1 = serviceInner_->appRunningManager_->GetAppRunningRecordMap(); @@ -1815,7 +1820,9 @@ HWTEST_F(AmsAppLifeCycleModuleTest, KillApplication_003, TestSize.Level1) auto appMap = serviceInner_->appRunningManager_->GetAppRunningRecordMap(); EXPECT_EQ(1, static_cast(appMap.size())); EXPECT_CALL(*mockAppScheduler, ScheduleProcessSecurityExit()).Times(1); - int32_t ret = serviceInner_->KillApplication("com.ohos.test.helloworld101"); + + auto uid = 1000; + int32_t ret = serviceInner_->KillApplication("com.ohos.test.helloworld101", uid); EXPECT_EQ(ret, 0); serviceInner_->OnRemoteDied(mockAppScheduler); // A faked death recipient. auto appMap1 = serviceInner_->appRunningManager_->GetAppRunningRecordMap(); diff --git a/services/test/moduletest/common/ams/app_mgr_service_test/ams_app_mgr_service_module_test.cpp b/services/test/moduletest/common/ams/app_mgr_service_test/ams_app_mgr_service_module_test.cpp index 7cf2697ee730eee1351e0f6f82f97a9515eb952e..a288a15525deefec6339adeea6b328d9a20d028b 100644 --- a/services/test/moduletest/common/ams/app_mgr_service_test/ams_app_mgr_service_module_test.cpp +++ b/services/test/moduletest/common/ams/app_mgr_service_test/ams_app_mgr_service_module_test.cpp @@ -418,7 +418,7 @@ HWTEST_F(AppMgrServiceModuleTest, KillApplication_001, TestSize.Level1) bool testResult = false; Semaphore sem(0); - auto mockHandler = [&testResult, testBundleName, &sem](const std::string &bundleName) { + auto mockHandler = [&testResult, testBundleName, &sem](const std::string &bundleName, int32_t callerUid) { testResult = (bundleName == testBundleName); sem.Post(); return 0; @@ -427,7 +427,7 @@ HWTEST_F(AppMgrServiceModuleTest, KillApplication_001, TestSize.Level1) for (int i = 0; i < COUNT; ++i) { testResult = false; - EXPECT_CALL(*mockAppMgrServiceInner_, KillApplication(_)).Times(1).WillOnce(Invoke(mockHandler)); + EXPECT_CALL(*mockAppMgrServiceInner_, KillApplication(_, _)).Times(1).WillOnce(Invoke(mockHandler)); int ret = appMgrService_->GetAmsMgr()->KillApplication(testBundleName); diff --git a/services/test/moduletest/common/ams/ipc_ams_mgr_test/ams_ipc_ams_mgr_module_test.cpp b/services/test/moduletest/common/ams/ipc_ams_mgr_test/ams_ipc_ams_mgr_module_test.cpp index b85df8ce86fde64468c9c2aacdd56985641c687f..c3650a192cf77f324db534fc4357ad8ff4e75085 100644 --- a/services/test/moduletest/common/ams/ipc_ams_mgr_test/ams_ipc_ams_mgr_module_test.cpp +++ b/services/test/moduletest/common/ams/ipc_ams_mgr_test/ams_ipc_ams_mgr_module_test.cpp @@ -368,7 +368,7 @@ HWTEST_F(AmsIpcAmsmgrModuleTest, ExcuteAmsmgrIPCInterface_006, TestSize.Level3) mockMockAppMgr->Wait(); for (int i = 0; i < COUNT; i++) { - EXPECT_CALL(*mockAppMgrServiceInner, KillApplication(_)) + EXPECT_CALL(*mockAppMgrServiceInner, KillApplication(_, _)) .WillOnce(InvokeWithoutArgs(mockAppMgrServiceInner.get(), &MockAppMgrServiceInner::Post4Int)); amsMgrScheduler_->KillApplication(bundleName); mockAppMgrServiceInner->Wait(); diff --git a/test/resource/amssystemtestability/abilitySrc/amsStDataAbility/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsStDataAbility/BUILD.gn index 1e0fab8598d55dcc96693697267efddc809957e7..4631a17f0de0c69cf112e02af0fa6b4e7752fab8 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsStDataAbility/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsStDataAbility/BUILD.gn @@ -13,7 +13,7 @@ import("//build/ohos.gni") import("//foundation/aafwk/standard/aafwk.gni") -SUBDEMOSYSTEM_DIR = "//foundation/appexecfwk/standard/test/resource/amssystemtestability/abilitySrc/amsStDataAbility" +SUBDEMOSYSTEM_DIR = "${system_test_app_path}/amsStDataAbility" EVENT_DIR = "//base/notification/ces_standard/cesfwk" config("verify_act_ability_config") { diff --git a/test/resource/amssystemtestability/abilitySrc/amsStDataAbility/include/verify_act_data_ability.h b/test/resource/amssystemtestability/abilitySrc/amsStDataAbility/include/verify_act_data_ability.h index b8967ce1f7bf707f6cd1a4b0b590a8807a824ad6..9f87dcda97ccf6d489008501095208b98ee11a70 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsStDataAbility/include/verify_act_data_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsStDataAbility/include/verify_act_data_ability.h @@ -41,13 +41,10 @@ public: virtual int BatchInsert(const Uri &uri, const std::vector &values) override; std::vector> sharedList_; -}; -class InsertTestOpenCallback : public NativeRdb::RdbOpenCallback { -public: - int OnCreate(NativeRdb::RdbStore &rdbStore) override; - int OnUpgrade(NativeRdb::RdbStore &rdbStore, int oldVersion, int newVersion) override; - static const std::string CREATE_TABLE_TEST; + virtual std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) override; + virtual Uri NormalizeUri(const Uri &uri) override; + virtual Uri DenormalizeUri(const Uri &uri) override; }; } // namespace AppExecFwk } // namespace OHOS diff --git a/test/resource/amssystemtestability/abilitySrc/amsStDataAbility/src/verify_act_data_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsStDataAbility/src/verify_act_data_ability.cpp index b5bcbb9676e7a1808257a100d3fb31d57175fd1e..f5887fce9d186dfdfb066bba9d4b2537f655454a 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsStDataAbility/src/verify_act_data_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsStDataAbility/src/verify_act_data_ability.cpp @@ -4,7 +4,7 @@ * 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 + * http://www.apache.org/licenses/LICENSERETURN_ERROR2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -14,11 +14,13 @@ */ #include "abs_shared_result_set.h" +#include "ability_loader.h" +#include "app_log_wrapper.h" +#include "data_ability_helper.h" #include "data_ability_predicates.h" +#include "rdb_helper.h" +#include "rdb_open_callback.h" #include "values_bucket.h" - -#include "app_log_wrapper.h" -#include "ability_loader.h" #include "verify_act_data_ability.h" namespace OHOS { @@ -28,8 +30,25 @@ static std::shared_ptr testStore; static const std::string RDB_TEST_PATH = "/data/test/"; static const std::string DATABASE_FILE_NAME = "insert_test.db"; static const std::string DATABASE_NAME = RDB_TEST_PATH + "insert_test.db"; -static const int defaultReturn = 1; -} +static int defaultReturn = 1; +static const double ageI = 24; +static const double salaryI = 2024.20; +static const int returnError = 0; +static const int returnError1 = -1; +static const int returnError2 = -2; +static const int returnError3 = -3; +static const int value1 = 0; +static const int value2 = 1; +static const int value3 = 2; +static const int value4 = 3; +} // namespace + +class InsertTestOpenCallback : public NativeRdb::RdbOpenCallback { +public: + int OnCreate(NativeRdb::RdbStore &rdbStore) override; + int OnUpgrade(NativeRdb::RdbStore &rdbStore, int oldVersion, int newVersion) override; + static const std::string CREATE_TABLE_TEST; +}; const std::string InsertTestOpenCallback::CREATE_TABLE_TEST = std::string("CREATE TABLE IF NOT EXISTS test ") + std::string("(id INTEGER PRIMARY KEY AUTOINCREMENT, " @@ -38,12 +57,14 @@ const std::string InsertTestOpenCallback::CREATE_TABLE_TEST = int InsertTestOpenCallback::OnCreate(NativeRdb::RdbStore &store) { + APP_LOGI("VerifyActDataAbility OnCreate"); return store.ExecuteSql(CREATE_TABLE_TEST); } int InsertTestOpenCallback::OnUpgrade(NativeRdb::RdbStore &store, int oldVersion, int newVersion) { - return 0; + APP_LOGI("VerifyActDataAbility OnUpgrade"); + return returnError; } void VerifyActDataAbility::OnStart(const Want &want) @@ -56,48 +77,149 @@ void VerifyActDataAbility::OnStart(const Want &want) int VerifyActDataAbility::Insert(const Uri &uri, const NativeRdb::ValuesBucket &value) { APP_LOGI("VerifyActDataAbility <<<>>>"); + std::shared_ptr dataUri = std::make_shared("dataability:///com.ix.VerifyActDataAbility"); + auto notify = DataAbilityHelper::Creator(GetContext(), dataUri); + if (notify == nullptr) { + APP_LOGE("VerifyActDataAbility <<<>>>"); + return returnError; + } + notify->NotifyChange(*dataUri); + + APP_LOGI("VerifyActDataAbility Insert uri.ToString = %{public}s", uri.ToString().c_str()); + APP_LOGI("VerifyActDataAbility Insert dataUri.ToString = %{public}s", dataUri->ToString().c_str()); + APP_LOGI("VerifyActDataAbility uri.Equals = %{public}d", uri.Equals(*dataUri)); + if (uri.Equals(*dataUri) != 1) { + return returnError1; + } + + defaultReturn = 1; + std::map valuesMap; + value.GetAll(valuesMap); + int valuesMapSize = valuesMap.size(); + APP_LOGI("VerifyActDataAbility value = %{public}d", valuesMapSize); + if (!valuesMapSize) + return returnError2; + for (auto item = valuesMap.begin(); item != valuesMap.end(); item++) { + auto valueFirst = item->first; + auto valueSecond = item->second; + int iEOK = 0; + APP_LOGI("VerifyActDataAbility valueSecond.GetType[%{public}d]]", valueSecond.GetType()); + if (valueFirst.compare("name") == 0) { + std::string val; + iEOK = valueSecond.GetString(val); + APP_LOGI("VerifyActDataAbility it iEOK[%{public}d]]", iEOK); + APP_LOGI("VerifyActDataAbility it[%{public}s],[%{public}s]", valueFirst.c_str(), val.c_str()); + if (val.compare("ActsDataAbilityHelperTest")) { + return returnError2; + break; + } + } else if (valueFirst.compare("age") == 0) { + double age; + iEOK = valueSecond.GetDouble(age); + APP_LOGI("VerifyActDataAbility it iEOK[%{public}d]", iEOK); + APP_LOGI("VerifyActDataAbility it[%{public}s],[%{public}f]", valueFirst.c_str(), age); + if (age != ageI) { + return returnError2; + break; + } + } else if (valueFirst.compare("salary") == 0) { + double salary; + iEOK = valueSecond.GetDouble(salary); + APP_LOGI("VerifyActDataAbility it iEOK[%{public}d]]", iEOK); + APP_LOGI("VerifyActDataAbility it[%{public}s],[%{public}f]", valueFirst.c_str(), salary); + if (salary != salaryI) { + return returnError2; + break; + } + } else { + APP_LOGI("VerifyActDataAbility it default[%{public}s]", valueFirst.c_str()); + break; + } + } + + int errCode = 0; + std::string dbDir = GetDatabaseDir(); + NativeRdb::RdbStoreConfig config(dbDir + "/" + DATABASE_FILE_NAME); + InsertTestOpenCallback helper; + testStore = NativeRdb::RdbHelper::GetRdbStore(config, 1, helper, errCode); + APP_LOGI("VerifyActDataAbility Insert Patch %{public}s", (dbDir + "/" + DATABASE_FILE_NAME).c_str()); + + if (testStore == nullptr) { + APP_LOGI("VerifyActDataAbility <<<>>> testStore is nullptr, data will be empty"); + return returnError3; + } + + int64_t id; + int insertError; + if ((insertError = testStore->Insert(id, "test", value)) != 0) { + APP_LOGE("VerifyActDataAbility <<<>>> store->Insert Error %{public}d", insertError); + return insertError; + } + return defaultReturn; } std::shared_ptr VerifyActDataAbility::Query( const Uri &uri, const std::vector &columns, const NativeRdb::DataAbilityPredicates &predicates) { + APP_LOGI("VerifyActDataAbility <<<>>>"); + std::shared_ptr dataUri = std::make_shared("dataability:///com.ix.VerifyActDataAbility"); + + APP_LOGI("VerifyActDataAbility Query uri.ToString = %{public}s", uri.ToString().c_str()); + APP_LOGI("VerifyActDataAbility Query dataUri.ToString = %{public}s", dataUri->ToString().c_str()); + APP_LOGI("VerifyActDataAbility uri.Equals = %{public}d", uri.Equals(*dataUri)); + if (uri.Equals(*dataUri) != 1) { + return nullptr; + } + int indexI = 0; + for (const auto &item : columns) { + switch (indexI++) { + case value1: + if (item.compare("value1") != 0) + return nullptr; + break; + case value2: + if (item.compare("value2") != 0) + return nullptr; + break; + case value3: + if (item.compare("value3") != 0) + return nullptr; + break; + case value4: + if (item.compare("value4") != 0) + return nullptr; + break; + default: + APP_LOGI("VerifyActDataAbility indexI = [%{public}d]]", indexI); + } + } + + APP_LOGI("VerifyActDataAbility Query predicates"); + APP_LOGI("VerifyActDataAbility Query predicates.Is = %{public}d", predicates.IsRawSelection()); + APP_LOGI("VerifyActDataAbility Query predicates.Get = %{public}d", predicates.GetJudgeSource()); + int errCode = 0; std::string dbDir = GetDatabaseDir(); NativeRdb::RdbStoreConfig config(dbDir + "/" + DATABASE_FILE_NAME); InsertTestOpenCallback helper; testStore = NativeRdb::RdbHelper::GetRdbStore(config, 1, helper, errCode); - APP_LOGI("VerifyActDataAbility <<<>>> Patch %{public}s", (dbDir + "/" + DATABASE_FILE_NAME).c_str()); - - int64_t id; - NativeRdb::ValuesBucket values; - int idValue = 1; - int age = 18; - double salary = 100.5; - - values.PutInt("id", idValue); - values.PutString("name", std::string("zhangsan")); - values.PutInt("age", age); - values.PutDouble("salary", salary); - values.PutBlob("blobType", std::vector {1, 2, 3}); + APP_LOGI("VerifyActDataAbility Query Patch %{public}s", (dbDir + "/" + DATABASE_FILE_NAME).c_str()); if (testStore == nullptr) { APP_LOGI("VerifyActDataAbility <<<>>> testStore is nullptr, data will be empty"); return nullptr; } - if (testStore->Replace(id, "test", values) != 0) { - APP_LOGE("VerifyActDataAbility <<<>>> store->Replace Error"); - return nullptr; - } - std::unique_ptr rresultSet = - testStore->QuerySql("SELECT * FROM test WHERE name = ?", std::vector {"zhangsan"}); + testStore->QuerySql("SELECT * FROM test WHERE name = ?" , + std::vector {"ActsDataAbilityHelperTest"}); if (rresultSet == nullptr) { APP_LOGE("VerifyActDataAbility <<<>>> rresultSet is nullptr"); return nullptr; } + APP_LOGE("VerifyActDataAbility <<<>>> ret(rresultSet.release()"); std::shared_ptr ret(rresultSet.release()); sharedList_.push_back(ret); return ret; @@ -107,30 +229,291 @@ int VerifyActDataAbility::Update( const Uri &uri, const NativeRdb::ValuesBucket &value, const NativeRdb::DataAbilityPredicates &predicates) { APP_LOGI("VerifyActDataAbility <<<>>>"); + std::shared_ptr dataUri = std::make_shared("dataability:///com.ix.VerifyActDataAbility"); + auto notify = DataAbilityHelper::Creator(GetContext(), dataUri); + if (notify == nullptr) { + APP_LOGE("VerifyActDataAbility <<<>>>"); + return returnError; + } + notify->NotifyChange(*dataUri); + + APP_LOGI("VerifyActDataAbility Update uri.ToString = %{public}s", uri.ToString().c_str()); + APP_LOGI("VerifyActDataAbility Update dataUri.ToString = %{public}s", dataUri->ToString().c_str()); + APP_LOGI("VerifyActDataAbility uri.Equals = %{public}d", uri.Equals(*dataUri)); + if (uri.Equals(*dataUri) != 1) { + return returnError1; + } + + defaultReturn = 1; + std::map valuesMap; + value.GetAll(valuesMap); + int valuesMapSize = valuesMap.size(); + APP_LOGI("VerifyActDataAbility value = %{public}d", valuesMapSize); + if (!valuesMapSize) + return returnError2; + for (auto item = valuesMap.begin(); item != valuesMap.end(); item++) { + auto valueFirst = item->first; + auto valueSecond = item->second; + APP_LOGI("VerifyActDataAbility valueSecond.GetType[%{public}d]]", valueSecond.GetType()); + if (valueFirst.compare("name") == 0) { + std::string val; + valueSecond.GetString(val); + APP_LOGI("VerifyActDataAbility it[%{public}s],[%{public}s]", valueFirst.c_str(), val.c_str()); + if (val.compare("ActsDataAbilityHelperTest")) { + return returnError2; + break; + } + } else if (valueFirst.compare("age") == 0) { + double age; + valueSecond.GetDouble(age); + APP_LOGI("VerifyActDataAbility it[%{public}s],[%{public}f]", valueFirst.c_str(), age); + if (age != ageI) { + return returnError2; + break; + } + } else if (valueFirst.compare("salary") == 0) { + double salary; + valueSecond.GetDouble(salary); + APP_LOGI("VerifyActDataAbility it[%{public}s],[%{public}f]", valueFirst.c_str(), salary); + if (salary != salaryI) { + return returnError2; + break; + } + } else { + APP_LOGI("VerifyActDataAbility it default[%{public}s]", valueFirst.c_str()); + break; + } + } + APP_LOGI("VerifyActDataAbility Update predicates = %{public}d", predicates.IsRawSelection()); + APP_LOGI("VerifyActDataAbility Update predicates.Get = %{public}d", predicates.GetJudgeSource()); + + int errCode = 0; + std::string dbDir = GetDatabaseDir(); + NativeRdb::RdbStoreConfig config(dbDir + "/" + DATABASE_FILE_NAME); + InsertTestOpenCallback helper; + testStore = NativeRdb::RdbHelper::GetRdbStore(config, 1, helper, errCode); + APP_LOGI("VerifyActDataAbility Update Patch %{public}s", (dbDir + "/" + DATABASE_FILE_NAME).c_str()); + + if (testStore == nullptr) { + APP_LOGI("VerifyActDataAbility <<<>>> testStore is nullptr, data will be empty"); + return returnError3; + } + + int changedRows; + int updatError; + if ((updatError = testStore->Update(changedRows, "test", value)) != 0) { + APP_LOGE("VerifyActDataAbility <<<>>> store->Replace changedRows %{public}d Error %{public}d", + changedRows, + updatError); + return updatError; + } return defaultReturn; } int VerifyActDataAbility::Delete(const Uri &uri, const NativeRdb::DataAbilityPredicates &predicates) { APP_LOGI("VerifyActDataAbility <<<>>>"); + std::shared_ptr dataUri = std::make_shared("dataability:///com.ix.VerifyActDataAbility"); + auto notify = DataAbilityHelper::Creator(GetContext(), dataUri); + if (notify == nullptr) { + APP_LOGE("VerifyActDataAbility <<<>>>"); + return returnError; + } + notify->NotifyChange(*dataUri); + + defaultReturn = 1; + APP_LOGI("VerifyActDataAbility Delete uri.ToString = %{public}s", uri.ToString().c_str()); + APP_LOGI("VerifyActDataAbility Delete dataUri.ToString = %{public}s", dataUri->ToString().c_str()); + APP_LOGI("VerifyActDataAbility uri.Equals is = %{public}d", uri.Equals(*dataUri)); + if (uri.Equals(*dataUri) != 1) { + return returnError; + } + APP_LOGI("VerifyActDataAbility Delete predicates.Is = %{public}d", predicates.IsRawSelection()); + APP_LOGI("VerifyActDataAbility Delete predicates.Get = %{public}d", predicates.GetJudgeSource()); + + int errCode = 0; + std::string dbDir = GetDatabaseDir(); + NativeRdb::RdbStoreConfig config(dbDir + "/" + DATABASE_FILE_NAME); + InsertTestOpenCallback helper; + testStore = NativeRdb::RdbHelper::GetRdbStore(config, 1, helper, errCode); + APP_LOGI("VerifyActDataAbility Delete Patch %{public}s", (dbDir + "/" + DATABASE_FILE_NAME).c_str()); + + if (testStore == nullptr) { + APP_LOGI("VerifyActDataAbility <<<>>> testStore is nullptr, data will be empty"); + return returnError3; + } + + int changedRows; + int deleteError; + if ((deleteError = testStore->Delete(changedRows, "test")) != 0) { + APP_LOGE("VerifyActDataAbility <<<>>> store->Delete changedRows %{public}d Error %{public}d", + changedRows, + deleteError); + return deleteError; + } return defaultReturn; } std::string VerifyActDataAbility::GetType(const Uri &uri) { APP_LOGI("VerifyActDataAbility <<<>>>"); + APP_LOGI("VerifyActDataAbility GetType uri = %{public}s", uri.ToString().c_str()); + std::shared_ptr dataUri = std::make_shared("dataability:///com.ix.VerifyActDataAbility3"); + APP_LOGI("VerifyActDataAbility GetType dataUri.ToString = %{public}s", dataUri->ToString().c_str()); + APP_LOGI("VerifyActDataAbility uri.Equals = %{public}d", uri.Equals(*dataUri)); + if (uri.Equals(*dataUri) == 1) { + return nullptr; + } std::string retval(uri.ToString()); return retval; } int VerifyActDataAbility::OpenFile(const Uri &uri, const std::string &mode) { APP_LOGI("VerifyActDataAbility <<<>>>"); - return 0; + std::shared_ptr dataUri = std::make_shared("dataability:///com.ix.VerifyActDataAbility"); + defaultReturn = 1; + APP_LOGI("VerifyActDataAbility Delete uri.ToString = %{public}s", uri.ToString().c_str()); + APP_LOGI("VerifyActDataAbility Delete dataUri.ToString = %{public}s", dataUri->ToString().c_str()); + APP_LOGI("VerifyActDataAbility uri.Equals = %{public}d", uri.Equals(*dataUri)); + if (uri.Equals(*dataUri) != 1) { + return returnError1; + } + APP_LOGI("VerifyActDataAbility OpenFile mode = %{public}s", mode.c_str()); + if (!(mode.compare("r") == 0 || mode.compare("w") == 0 || mode.compare("wt") == 0 || mode.compare("wa") == 0 || + mode.compare("rw") == 0 || mode.compare("rwt") == 0)) { + if (mode.compare("A1@k#4%$,.<>)(oioiu*((*&(&*giIGT^%&^Ug;sdfk;losd*7873iug8%&^$&%]ERFUy&^%&&R7") == 0) { + defaultReturn = returnError2; + } else + defaultReturn = returnError3; + } + APP_LOGI("VerifyActDataAbility OpenFile defaultReturn = %{public}d", defaultReturn); + return defaultReturn; } int VerifyActDataAbility::BatchInsert(const Uri &uri, const std::vector &values) { APP_LOGI("VerifyActDataAbility <<<>>>"); - return Ability::BatchInsert(uri, values); + std::shared_ptr dataUri = std::make_shared("dataability:///com.ix.VerifyActDataAbility"); + defaultReturn = 1; + APP_LOGI("VerifyActDataAbility BatchInsert uri.ToString = %{public}s", uri.ToString().c_str()); + APP_LOGI("VerifyActDataAbility BatchInsert dataUri.ToString = %{public}s", dataUri->ToString().c_str()); + APP_LOGI("VerifyActDataAbility uri.Equals = %{public}d", uri.Equals(*dataUri)); + if (uri.Equals(*dataUri) != 1) { + return returnError1; + } + + defaultReturn = 1; + std::map valuesMap; + for (auto it = values.begin(); it != values.end(); it++) { + it->GetAll(valuesMap); + int valuesMapSize = values.size(); + APP_LOGI("VerifyActDataAbility value = %{public}d", valuesMapSize); + if (!valuesMapSize) + return returnError2; + for (auto item = valuesMap.begin(); item != valuesMap.end(); item++) { + auto valueFirst = item->first; + auto valueSecond = item->second; + APP_LOGI("VerifyActDataAbility valueSecond.GetType[%{public}d]]", valueSecond.GetType()); + if (valueFirst.compare("name") == 0) { + std::string val; + valueSecond.GetString(val); + APP_LOGI("VerifyActDataAbility it[%{public}s],[%{public}s]", valueFirst.c_str(), val.c_str()); + if (val.compare("ActsDataAbilityHelperTest")) { + return returnError2; + break; + } + } else if (valueFirst.compare("age") == 0) { + double age; + valueSecond.GetDouble(age); + APP_LOGI("VerifyActDataAbility it[%{public}s],[%{public}f]", valueFirst.c_str(), age); + if (age != ageI) { + return returnError2; + break; + } + } else if (valueFirst.compare("salary") == 0) { + double salary; + valueSecond.GetDouble(salary); + APP_LOGI("VerifyActDataAbility it[%{public}s],[%{public}f]", valueFirst.c_str(), salary); + if (salary != salaryI) { + return returnError2; + break; + } + } else { + APP_LOGI("VerifyActDataAbility it default[%{public}s]", valueFirst.c_str()); + break; + } + } + } + + int retAbilityBatchInsert = Ability::BatchInsert(uri, values); + APP_LOGI("VerifyActDataAbility BatchInsert retAbility = %{public}d", retAbilityBatchInsert); + return retAbilityBatchInsert; +} +std::vector VerifyActDataAbility::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) +{ + APP_LOGI("VerifyActDataAbility <<<>>>"); + std::shared_ptr dataUri = std::make_shared("dataability:///com.ix.VerifyActDataAbility"); + defaultReturn = 1; + APP_LOGI("VerifyActDataAbility Delete uri.ToString = %{public}s", uri.ToString().c_str()); + APP_LOGI("VerifyActDataAbility Delete dataUri.ToString = %{public}s", dataUri->ToString().c_str()); + APP_LOGI("VerifyActDataAbility uri.Equals = %{public}d", uri.Equals(*dataUri)); + std::vector vectorFileTypes; + if (uri.Equals(*dataUri) != 1) { + APP_LOGE("VerifyActDataAbility uri.Equals(*dataUri) != 1"); + vectorFileTypes.push_back("Uri error"); + return vectorFileTypes; + } + + if (mimeTypeFilter.compare("*/*") == 0) { + vectorFileTypes.push_back("hap"); + vectorFileTypes.push_back("jpg"); + vectorFileTypes.push_back("image/png"); + } else if (mimeTypeFilter.compare("image/*") == 0) { + vectorFileTypes.push_back("image/png"); + } else if (mimeTypeFilter.compare("*/jpg") == 0) { + vectorFileTypes.push_back("jpg"); + } else if (mimeTypeFilter.compare("returnUndefined") == 0) { + return {}; + } + + return vectorFileTypes; } +Uri VerifyActDataAbility::NormalizeUri(const Uri &uri) +{ + APP_LOGI("VerifyActDataAbility <<<>>>"); + APP_LOGI("VerifyActDataAbility NormalizeUri uri = %{public}s", uri.ToString().c_str()); + std::shared_ptr dataUri = std::make_shared("dataability:///com.ix.VerifyActDataAbility"); + std::shared_ptr dataUri3 = std::make_shared("dataability:///com.ix.VerifyActDataAbility3"); + Uri dataUriNull(""); + Uri dataUriError("errorUri"); + APP_LOGI("VerifyActDataAbility NormalizeUri dataUri.ToString = %{public}s", dataUri->ToString().c_str()); + APP_LOGI("VerifyActDataAbility uri.Equals = %{public}d", uri.Equals(*dataUri)); + if (uri.Equals(*dataUri) != 1) { + if (uri.Equals(*dataUri3) == 1) { + return dataUriNull; + } + return dataUriError; + } + return uri; +} + +Uri VerifyActDataAbility::DenormalizeUri(const Uri &uri) +{ + APP_LOGI("VerifyActDataAbility <<<>>>"); + APP_LOGI("VerifyActDataAbility DenormalizeUri uri = %{public}s", uri.ToString().c_str()); + std::shared_ptr dataUri = std::make_shared("dataability:///com.ix.VerifyActDataAbility"); + std::shared_ptr dataUri3 = std::make_shared("dataability:///com.ix.VerifyActDataAbility3"); + Uri dataUriNull(""); + Uri dataUriError("errorUri"); + APP_LOGI("VerifyActDataAbility DenormalizeUri dataUri.ToString = %{public}s", dataUri->ToString().c_str()); + APP_LOGI("VerifyActDataAbility uri.Equals = %{public}d", uri.Equals(*dataUri)); + + if (uri.Equals(*dataUri) != 1) { + if (uri.Equals(*dataUri3) == 1) { + return dataUriNull; + } + return dataUriError; + } + return uri; +} REGISTER_AA(VerifyActDataAbility); } // namespace AppExecFwk } // namespace OHOS diff --git a/tools/aa/src/ability_command.cpp b/tools/aa/src/ability_command.cpp index c95050bd1d00af2eabee89ff1f29d32df01598ae..b08e0b38bef21056a1499384e31421e655fbc544 100644 --- a/tools/aa/src/ability_command.cpp +++ b/tools/aa/src/ability_command.cpp @@ -629,13 +629,9 @@ ErrCode AbilityManagerShellCommand::RunAsDumpsysCommand() if (isfirstCommand == false) { isfirstCommand = true; } else { - // 'aa dumpsys -i 10 -element -lastpage' - // 'aa dumpsys -i 10 -render -lastpage' - if (strcmp(optarg, "astpage")) { - result = OHOS::ERR_INVALID_VALUE; - resultReceiver_.append(HELP_MSG_DUMPSYS); - return result; - } + result = OHOS::ERR_INVALID_VALUE; + resultReceiver_.append(HELP_MSG_DUMPSYS); + return result; } // 'aa dumpsys -l' // 'aa dumpsys --mission-list' @@ -652,12 +648,9 @@ ErrCode AbilityManagerShellCommand::RunAsDumpsysCommand() return result; } } else { - // 'aa dumpsys -i 10 -inspector' - if (strcmp(optarg, "nspector")) { - result = OHOS::ERR_INVALID_VALUE; - resultReceiver_.append(HELP_MSG_DUMPSYS); - return result; - } + result = OHOS::ERR_INVALID_VALUE; + resultReceiver_.append(HELP_MSG_DUMPSYS); + return result; } // 'aa dumpsys -i' // 'aa dumpsys --ability' @@ -667,12 +660,9 @@ ErrCode AbilityManagerShellCommand::RunAsDumpsysCommand() if (isfirstCommand == false) { isfirstCommand = true; } else { - // 'aa dumpsys -i 10 -element' - if (strcmp(optarg, "lement")) { - result = OHOS::ERR_INVALID_VALUE; - resultReceiver_.append(HELP_MSG_DUMPSYS); - return result; - } + result = OHOS::ERR_INVALID_VALUE; + resultReceiver_.append(HELP_MSG_DUMPSYS); + return result; } // 'aa dumpsys -e' // 'aa dumpsys --extension' @@ -694,12 +684,9 @@ ErrCode AbilityManagerShellCommand::RunAsDumpsysCommand() if (isfirstCommand == false) { isfirstCommand = true; } else { - // 'aa dumpsys -i 10 -render' - if (strcmp(optarg, "ender")) { - result = OHOS::ERR_INVALID_VALUE; - resultReceiver_.append(HELP_MSG_DUMPSYS); - return result; - } + result = OHOS::ERR_INVALID_VALUE; + resultReceiver_.append(HELP_MSG_DUMPSYS); + return result; } // 'aa dumpsys -r' // 'aa dumpsys --process' diff --git a/tools/test/mock/mock_ability_manager_stub.h b/tools/test/mock/mock_ability_manager_stub.h index 990e06c9547b1c3e382a365cdd16976561d00fe3..15e4358bf46a0f67c01d226d8c625c77502db367 100644 --- a/tools/test/mock/mock_ability_manager_stub.h +++ b/tools/test/mock/mock_ability_manager_stub.h @@ -119,7 +119,7 @@ public: MOCK_METHOD1(SetShowOnLockScreen, int(bool isAllow)); MOCK_METHOD1(GetSystemMemoryAttr, void(AppExecFwk::SystemMemoryAttr &memoryInfo)); MOCK_METHOD3(StartContinuation, int(const Want &want, const sptr &abilityToken, int32_t status)); - MOCK_METHOD2(NotifyContinuationResult, int(int32_t missionId, int32_t result)); + MOCK_METHOD2(NotifyContinuationResult, int(int32_t missionId, const int32_t result)); MOCK_METHOD5(ContinueMission, int(const std::string &srcDeviceId, const std::string &dstDeviceId, int32_t missionId, const sptr &callBack, AAFwk::WantParams &wantParams)); MOCK_METHOD2(ContinueAbility, int(const std::string &deviceId, int32_t missionId)); @@ -135,7 +135,6 @@ public: MOCK_METHOD1(CleanMission, int(int32_t missionId)); MOCK_METHOD0(CleanAllMissions, int()); MOCK_METHOD1(MoveMissionToFront, int(int32_t missionId)); - MOCK_METHOD2(MoveMissionToFront, int(int32_t missionId, const StartOptions &startOptions)); MOCK_METHOD2(SetMissionLabel, int(const sptr &token, const std::string &label)); MOCK_METHOD1(ClearUpApplicationData, int(const std::string &)); diff --git a/zidl/bundle.json b/zidl/bundle.json deleted file mode 100644 index 5127a051270eadcfa02b16b87ed6df6283e59b82..0000000000000000000000000000000000000000 --- a/zidl/bundle.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "name": "@ohos/zidl", - "description": "提供自动生成Extension 服务端及客户端接口文件的能力", - "version": "3.1", - "license": "Apache License 2.0", - "publishAs": "code-segment", - "segment": { - "destPath": "foundation/aafwk/standard/zidl" - }, - "dirs": {}, - "scripts": {}, - "component": { - "name": "zidl", - "subsystem": "aafwk", - "syscap": [], - "features": [], - "adapted_system_type": [ - "standard" - ], - "rom": "", - "ram": "", - "deps": { - "components": [ - "hiviewdfx_hilog_native", - "ipc", - "samgr_standard", - "utils_base" - ], - "third_party": [] - }, - "build": { - "sub_component": [], - "inner_kits": [], - "test": [] - } - } -} \ No newline at end of file diff --git a/zidl/test/native/BUILD.gn b/zidl/test/native/BUILD.gn deleted file mode 100644 index 8dc9839a534d3031f43865f20e9d586abb410ba7..0000000000000000000000000000000000000000 --- a/zidl/test/native/BUILD.gn +++ /dev/null @@ -1,69 +0,0 @@ -# Copyright (C) 2021 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. - -import("//build/ohos.gni") - -IPC_SUBSYSTEM_DIR = "//foundation/communication/ipc" -ZIDL_TEST_DIR = "//foundation/aafwk/standard/zidl/test/native" - -config("ipc_test_config") { - include_dirs = [ - "//utils/native/base/include", - "$ZIDL_TEST_DIR/include", - "$IPC_SUBSYSTEM_DIR/utils/include", - "$IPC_SUBSYSTEM_DIR/ipc/native/src/mock/include", - "//utils/system/safwk/native/include", - ] -} - -ohos_executable("zidl_server_test") { - sources = [ - "./src/main_server.cpp", - "./src/test_service.cpp", - "./src/zidl_test_service_stub.cpp", - ] - - configs = [ ":ipc_test_config" ] - - deps = [ "//utils/native/base:utils" ] - - external_deps = [ - "hiviewdfx_hilog_native:libhilog", - "ipc:ipc_core", - "samgr_standard:samgr_proxy", - ] - - subsystem_name = "aafwk" - part_name = "zidl" -} - -ohos_executable("zidl_client_test") { - sources = [ - "./src/main_client.cpp", - "./src/test_client.cpp", - "./src/zidl_test_service_proxy.cpp", - ] - - configs = [ ":ipc_test_config" ] - - deps = [ "//utils/native/base:utils" ] - - external_deps = [ - "hiviewdfx_hilog_native:libhilog", - "ipc:ipc_core", - "samgr_standard:samgr_proxy", - ] - - subsystem_name = "aafwk" - part_name = "zidl" -} diff --git a/zidl/test/native/include/izidl_test_service.h b/zidl/test/native/include/izidl_test_service.h deleted file mode 100644 index 3f6308363a862f1f80097c1ee05e42f1674e2e20..0000000000000000000000000000000000000000 --- a/zidl/test/native/include/izidl_test_service.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (C) 2021 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. - */ - -#ifndef OHOS_IZIDLTESTSERVICE_H -#define OHOS_IZIDLTESTSERVICE_H - -#include -#include - -namespace OHOS { -class IZidlTestService : public IRemoteBroker { -public: - DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.IZidlTestService"); - - virtual ErrCode TestIntTransaction( - /* [in] */ int _data, - /* [out] */ int& result) = 0; - - virtual ErrCode TestStringTransaction( - /* [in] */ const std::string& _data) = 0; -}; -} // namespace OHOS -#endif // OHOS_IZIDLTESTSERVICE_H - diff --git a/zidl/test/native/include/test_client.h b/zidl/test/native/include/test_client.h deleted file mode 100644 index 4d54213003bfe72fd624092c6743bf2ae1e8f840..0000000000000000000000000000000000000000 --- a/zidl/test/native/include/test_client.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (C) 2021 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. - */ - -#ifndef OHOS_IPC_TEST_SERVICE_CLIENT_H -#define OHOS_IPC_TEST_SERVICE_CLIENT_H - -#include "ipc_debug.h" -#include "log_tags.h" -#include "zidl_test_service_proxy.h" - -namespace OHOS { -class TestClient { -public: - int ConnectService(); - void StartIntTransaction(); - void StartStringTransaction(); -private: - static constexpr HiviewDFX::HiLogLabel LABEL = { LOG_CORE, LOG_ID_IPC, "TestClient" }; - sptr testService_; -}; -} // namespace OHOS -#endif // OHOS_IPC_TEST_SERVICE_CLIENT_H diff --git a/zidl/test/native/include/test_service.h b/zidl/test/native/include/test_service.h deleted file mode 100644 index 2c29658c7610e136a528f3f3173ac0162ace7a14..0000000000000000000000000000000000000000 --- a/zidl/test/native/include/test_service.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (C) 2021 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. - */ - -#ifndef OHOS_IPC_TEST_SERVICE_H -#define OHOS_IPC_TEST_SERVICE_H - -#include "hilog/log.h" -#include "log_tags.h" -#include "zidl_test_service_stub.h" - -namespace OHOS { -class TestService : public ZidlTestServiceStub { -public: - TestService(); - ~TestService(); - static int Instantiate(); - ErrCode TestIntTransaction(int data, int &rep) override; - ErrCode TestStringTransaction(const std::string& data) override; -private: - static constexpr HiviewDFX::HiLogLabel LABEL = { LOG_CORE, LOG_ID_IPC, "TestService" }; -}; -} // namespace OHOS -#endif // OHOS_IPC_TEST_SERVICE_H - diff --git a/zidl/test/native/include/zidl_test_service_proxy.h b/zidl/test/native/include/zidl_test_service_proxy.h deleted file mode 100644 index 7e9ea4dcd58315a03ba8a4c7f7125bb3214e14f4..0000000000000000000000000000000000000000 --- a/zidl/test/native/include/zidl_test_service_proxy.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (C) 2021 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. - */ - -#ifndef OHOS_ZIDLTESTSERVICEPROXY_H -#define OHOS_ZIDLTESTSERVICEPROXY_H - -#include "izidl_test_service.h" -#include - -namespace OHOS { -class ZidlTestServiceProxy : public IRemoteProxy { -public: - explicit ZidlTestServiceProxy( - /* [in] */ const sptr& remote) - : IRemoteProxy(remote) - {} - - virtual ~ZidlTestServiceProxy() - {} - - ErrCode TestIntTransaction( - /* [in] */ int _data, - /* [out] */ int& result) override; - - ErrCode TestStringTransaction( - /* [in] */ const std::string& _data) override; - -private: - static constexpr int COMMAND_TEST_INT_TRANSACTION = MIN_TRANSACTION_ID + 0; - static constexpr int COMMAND_TEST_STRING_TRANSACTION = MIN_TRANSACTION_ID + 1; - - static inline BrokerDelegator delegator_; -}; -} // namespace OHOS -#endif // OHOS_ZIDLTESTSERVICEPROXY_H - diff --git a/zidl/test/native/include/zidl_test_service_stub.h b/zidl/test/native/include/zidl_test_service_stub.h deleted file mode 100644 index d88b615bb1f380471cc91f3488de49b4e37a9ca4..0000000000000000000000000000000000000000 --- a/zidl/test/native/include/zidl_test_service_stub.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) 2021 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. - */ - -#ifndef OHOS_ZIDLTESTSERVICESTUB_H -#define OHOS_ZIDLTESTSERVICESTUB_H - -#include "izidl_test_service.h" -#include - -namespace OHOS { -class ZidlTestServiceStub : public IRemoteStub { -public: - int OnRemoteRequest( - /* [in] */ uint32_t code, - /* [in] */ MessageParcel& data, - /* [out] */ MessageParcel& reply, - /* [in] */ MessageOption& option) override; - -private: - static constexpr int COMMAND_TEST_INT_TRANSACTION = MIN_TRANSACTION_ID + 0; - static constexpr int COMMAND_TEST_STRING_TRANSACTION = MIN_TRANSACTION_ID + 1; -}; -} // namespace OHOS -#endif // OHOS_ZIDLTESTSERVICESTUB_H - diff --git a/zidl/test/native/src/main_client.cpp b/zidl/test/native/src/main_client.cpp deleted file mode 100644 index 7238b197b761aae55e91afc61943e2e57bdb0a79..0000000000000000000000000000000000000000 --- a/zidl/test/native/src/main_client.cpp +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (C) 2021 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 "ipc_debug.h" -#include "ipc_skeleton.h" -#include "log_tags.h" -#include "test_client.h" - -using namespace OHOS; -using namespace OHOS::HiviewDFX; -static constexpr HiLogLabel LABEL = { LOG_CORE, LOG_ID_IPC, "IPCTestClient" }; - -enum TestCommand { - TEST_CMD_NONE = 0, - TEST_CMD_INT_TRANS = 1, - TEST_CMD_STRING_TRANS = 2 -}; - -namespace { -std::vector GetArgvOptions(int argc, char **argv) -{ - std::vector argvOptions; - for (int i = 1; i < argc; i++) { - argvOptions.emplace_back(std::string(argv[i])); - } - return argvOptions; -} -} - -int main(int argc, char *argv[]) -{ - TestCommand commandId = TestCommand::TEST_CMD_INT_TRANS; - if (argc > 1) { - commandId = TestCommand(atoi(argv[1])); - } else { - ZLOGE(LABEL, "unknown command"); - } - std::vector argvOptions; - argvOptions = GetArgvOptions(argc, argv); - std::unique_ptr testClient = std::make_unique(); - if (testClient->ConnectService()) { - return -1; - } - - ZLOGE(LABEL, "commandId= : %{public}d", commandId); - switch (commandId) { - case TestCommand::TEST_CMD_INT_TRANS: - testClient->StartIntTransaction(); - break; - case TestCommand::TEST_CMD_STRING_TRANS: - testClient->StartStringTransaction(); - break; - default: - ZLOGI(LABEL, "main arg error"); - break; - } - - IPCSkeleton::JoinWorkThread(); - return 0; -} diff --git a/zidl/test/native/src/main_server.cpp b/zidl/test/native/src/main_server.cpp deleted file mode 100644 index 0765721662f13cc7186abd8f38f65ae55ab2e32c..0000000000000000000000000000000000000000 --- a/zidl/test/native/src/main_server.cpp +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (C) 2021 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 "ipc_debug.h" -#include "ipc_skeleton.h" -#include "log_tags.h" -#include "test_service.h" - -using namespace OHOS; -using namespace OHOS::HiviewDFX; - -[[maybe_unused]]static constexpr HiLogLabel LABEL = { LOG_CORE, LOG_ID_IPC, "IPCTestServer" }; - -int main(int argc __attribute__((unused)), char **argv __attribute__((unused))) -{ - TestService::Instantiate(); - ZLOGI(LABEL, "call StartThreadPool"); - IPCSkeleton::JoinWorkThread(); -} diff --git a/zidl/test/native/src/test_client.cpp b/zidl/test/native/src/test_client.cpp deleted file mode 100644 index b2e7abd8e58246ac15daa516e5d6448c387610d9..0000000000000000000000000000000000000000 --- a/zidl/test/native/src/test_client.cpp +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (C) 2021 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 "test_client.h" - -#include "if_system_ability_manager.h" -#include "ipc_debug.h" -#include "ipc_skeleton.h" -#include "iservice_registry.h" -#include "system_ability_definition.h" - -namespace OHOS { -int TestClient::ConnectService() -{ - auto saMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (saMgr == nullptr) { - ZLOGE(LABEL, "get registry fail"); - return -1; - } - - sptr object = saMgr->GetSystemAbility(IPC_TEST_SERVICE); - - if (object != nullptr) { - ZLOGE(LABEL, "Got test Service object"); - testService_ = (new (std::nothrow) ZidlTestServiceProxy(object)); - } - - if (testService_ == nullptr) { - ZLOGE(LABEL, "Could not find Test Service!"); - return -1; - } - - return 0; -} - -void TestClient::StartIntTransaction() -{ - if (testService_ != nullptr) { - ZLOGE(LABEL, "StartIntTransaction"); - [[maybe_unused]] int result = 0; - testService_->TestIntTransaction(1234, result); // 1234 : test number - ZLOGE(LABEL, "Rec result from server %{public}d.", result); - } -} - -void TestClient::StartStringTransaction() -{ - if (testService_ != nullptr) { - ZLOGI(LABEL, "StartIntTransaction"); - testService_->TestStringTransaction("ZIDL Test"); - } -} -} // namespace OHOS diff --git a/zidl/test/native/src/test_service.cpp b/zidl/test/native/src/test_service.cpp deleted file mode 100644 index acf2f6346c17ab84290836cc40f4043b6bead25c..0000000000000000000000000000000000000000 --- a/zidl/test/native/src/test_service.cpp +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) 2021 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 "test_service.h" - -#include - -#include "if_system_ability_manager.h" -#include "ipc_debug.h" -#include "ipc_skeleton.h" -#include "iservice_registry.h" -#include "system_ability_definition.h" - -namespace OHOS { -using namespace OHOS::HiviewDFX; - -int TestService::Instantiate() -{ - ZLOGI(LABEL, "%{public}s call in", __func__); - auto saMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (saMgr == nullptr) { - ZLOGE(LABEL, "%{public}s:fail to get Registry", __func__); - return -ENODEV; - } - - sptr newInstance = new TestService(); - int result = saMgr->AddSystemAbility(IPC_TEST_SERVICE, newInstance); - ZLOGI(LABEL, "%{public}s: IPC_TEST_SERVICE result = %{public}d", __func__, result); - return result; -} - -TestService::TestService() -{ -} - -TestService::~TestService() -{ -} - -ErrCode TestService::TestIntTransaction(int data, int &rep) -{ - ZLOGE(LABEL, " TestService:read from client data = %{public}d", data); - rep = data + data; - return ERR_NONE; -} - -ErrCode TestService::TestStringTransaction(const std::string &data) -{ - ZLOGE(LABEL, "TestService:read string from client data = %{public}s", data.c_str()); - return data.size(); -} -} // namespace OHOS diff --git a/zidl/test/native/src/zidl_test_service_proxy.cpp b/zidl/test/native/src/zidl_test_service_proxy.cpp deleted file mode 100644 index 314cadb6a2439edfa10ee96f7592b1e1398496d7..0000000000000000000000000000000000000000 --- a/zidl/test/native/src/zidl_test_service_proxy.cpp +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) 2021 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 "zidl_test_service_proxy.h" - -namespace OHOS { -ErrCode ZidlTestServiceProxy::TestIntTransaction( - /* [in] */ int _data, - /* [out] */ int& result) -{ - MessageParcel data; - MessageParcel reply; - MessageOption option(MessageOption::TF_SYNC); - - data.WriteInt32(_data); - - int32_t st = Remote()->SendRequest(COMMAND_TEST_INT_TRANSACTION, data, reply, option); - if (st != ERR_NONE) { - return st; - } - - ErrCode ec = reply.ReadInt32(); - if (FAILED(ec)) { - return ec; - } - - result = reply.ReadInt32(); - return ERR_OK; -} - -ErrCode ZidlTestServiceProxy::TestStringTransaction( - /* [in] */ const std::string& _data) -{ - MessageParcel data; - MessageParcel reply; - MessageOption option(MessageOption::TF_SYNC); - - data.WriteString16(Str8ToStr16(_data)); - - int32_t st = Remote()->SendRequest(COMMAND_TEST_STRING_TRANSACTION, data, reply, option); - if (st != ERR_NONE) { - return st; - } - - ErrCode ec = reply.ReadInt32(); - if (FAILED(ec)) { - return ec; - } - - return ERR_OK; -} -} // namespace OHOS diff --git a/zidl/test/native/src/zidl_test_service_stub.cpp b/zidl/test/native/src/zidl_test_service_stub.cpp deleted file mode 100644 index adf63cd1dec69afef101456b7cffca5198ed5be7..0000000000000000000000000000000000000000 --- a/zidl/test/native/src/zidl_test_service_stub.cpp +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (C) 2021 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 "zidl_test_service_stub.h" - -namespace OHOS { -int ZidlTestServiceStub::OnRemoteRequest( - /* [in] */ uint32_t code, - /* [in] */ MessageParcel& data, - /* [out] */ MessageParcel& reply, - /* [in] */ MessageOption& option) -{ - switch (code) { - case COMMAND_TEST_INT_TRANSACTION: { - int _data = data.ReadInt32(); - int result; - ErrCode ec = TestIntTransaction(_data, result); - reply.WriteInt32(ec); - if (SUCCEEDED(ec)) { - reply.WriteInt32(result); - } - return ERR_NONE; - } - case COMMAND_TEST_STRING_TRANSACTION: { - std::string _data = Str16ToStr8(data.ReadString16()); - ErrCode ec = TestStringTransaction(_data); - reply.WriteInt32(ec); - return ERR_NONE; - } - default: - return IPCObjectStub::OnRemoteRequest(code, data, reply, option); - } - - return ERR_TRANSACTION_FAILED; -} -} // namespace OHOS diff --git a/zidl/test/zidlgen/IZidlTestService.zidl b/zidl/test/zidlgen/IZidlTestService.zidl deleted file mode 100644 index 8d2fa0b91c567c7389072eccfddf51cded5daa18..0000000000000000000000000000000000000000 --- a/zidl/test/zidlgen/IZidlTestService.zidl +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright (C) 2021 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. - */ - -interface OHOS.IZidlTestService { - int TestIntTransaction([in] int data); - void TestStringTransaction([in] String data); -} \ No newline at end of file diff --git a/zidl/test/zidlgen/zidl b/zidl/test/zidlgen/zidl deleted file mode 100644 index c3bde7295221617c5bdc4e7a695702a580ac0c22..0000000000000000000000000000000000000000 Binary files a/zidl/test/zidlgen/zidl and /dev/null differ