diff --git a/interfaces/innerkits/appexecfwk_base/include/ability_info.h b/interfaces/innerkits/appexecfwk_base/include/ability_info.h index 781e7c29090d41729f39b2c15e15545bfda192d8..d48c3cf73461f1fc0ed2a84d7602d4262f9e8f75 100644 --- a/interfaces/innerkits/appexecfwk_base/include/ability_info.h +++ b/interfaces/innerkits/appexecfwk_base/include/ability_info.h @@ -158,7 +158,7 @@ struct AbilityInfo : public Parcelable { DisplayOrientation orientation = DisplayOrientation::UNSPECIFIED; LaunchMode launchMode = LaunchMode::STANDARD; std::string srcPath; - std::string srcLanguage="js"; + std::string srcLanguage = "js"; std::vector permissions; std::string process; diff --git a/interfaces/innerkits/appexecfwk_base/include/appexecfwk_errors.h b/interfaces/innerkits/appexecfwk_base/include/appexecfwk_errors.h index 14ee10d64f7ccf8279f5c000ca18517c6ab17796..999fd70b24ddc04e578970ae08ad1152716703ea 100644 --- a/interfaces/innerkits/appexecfwk_base/include/appexecfwk_errors.h +++ b/interfaces/innerkits/appexecfwk_base/include/appexecfwk_errors.h @@ -19,6 +19,7 @@ #include "errors.h" namespace OHOS { + enum { APPEXECFWK_MODULE_COMMON = 0x00, APPEXECFWK_MODULE_APPMGR = 0x01, @@ -108,33 +109,63 @@ enum { constexpr ErrCode APPEXECFWK_FORMMGR_ERR_OFFSET = ErrCodeOffset(SUBSYS_APPEXECFWK, APPEXECFWK_MODULE_FORMMGR); enum { ERR_APPEXECFWK_FORM_COMMON_CODE = APPEXECFWK_FORMMGR_ERR_OFFSET + 1, - ERR_APPEXECFWK_FORM_PERMISSION_DENY, + ERR_APPEXECFWK_FORM_PERMISSION_DENY, + ERR_APPEXECFWK_FORM_INTENT_PARCEL, ERR_APPEXECFWK_FORM_GET_INFO_FAILED, + ERR_APPEXECFWK_FORM_GET_SYSMGR_FAILED, ERR_APPEXECFWK_FORM_GET_BUNDLE_FAILED, + ERR_APPEXECFWK_FORM_GET_FMS_FAILED, + ERR_APPEXECFWK_FORM_ADD_DEATH_RECIPIENT_FAILED, + ERR_APPEXECFWK_FORM_BIND_FORMSUPPLY_FAILED, ERR_APPEXECFWK_FORM_INVALID_PARAM, ERR_APPEXECFWK_FORM_CFG_NOT_MATCH_ID, - ERR_APPEXECFWK_FORM_NOT_EXIST_ID, + ERR_APPEXECFWK_FORM_ADD_NOT_EXIST_ID, ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED, - ERR_APPEXECFWK_FORM_MAX_SYSTEM_FORMS, + ERR_APPEXECFWK_FORM_EXCEED_MAX_NUMBER, ERR_APPEXECFWK_FORM_EXCEED_INSTANCES_PER_FORM, ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF, - ERR_APPEXECFWK_FORM_PROVIDER_DEL_FAIL, - ERR_APPEXECFWK_FORM_MAX_FORMS_PER_CLIENT, - ERR_APPEXECFWK_FORM_MAX_SYSTEM_TEMP_FORMS, + ERR_APPEXECFWK_FORM_SUPPLIER_DEL_FAIL, ERR_APPEXECFWK_FORM_NO_SUCH_MODULE, ERR_APPEXECFWK_FORM_NO_SUCH_ABILITY, ERR_APPEXECFWK_FORM_NO_SUCH_DIMENSION, ERR_APPEXECFWK_FORM_FA_NOT_INSTALLED, - ERR_APPEXECFWK_FORM_MAX_REQUEST, - ERR_APPEXECFWK_FORM_MAX_REFRESH, - ERR_APPEXECFWK_FORM_GET_BMS_FAILED, + ERR_APPEXECFWK_FORM_INFO_NOT_EXIST, + ERR_APPEXECFWK_FORM_HOST_INFO_NOT_EXIST, + ERR_CODE_COMMON, + ERR_NOT_EXIST_ID, + ERR_MAX_RECORDS_PER_APP, + ERR_PERMISSION_DENY, + ERR_MAX_SYSTEM_FORMS, + ERR_MAX_INSTANCES_PER_FORM, + ERR_OPERATION_FORM_NOT_SELF, + ERR_PROVIDER_DEL_FAIL, + ERR_MAX_FORMS_PER_CLIENT, + ERR_MAX_REFRESH, + ERR_MAX_SYSTEM_TEMP_FORMS, + ERR_FORM_NO_SUCH_MODULE, + ERR_FORM_NO_SUCH_ABILITY, + ERR_FORM_NO_SUCH_DIMENSION, + ERR_FORM_FA_NOT_INSTALLED, + ERR_FORM_INVALID_PARAM, + ERR_DELETE_FORM_TIMER, + ERR_CFG_NOT_MATCH_ID, + ERR_APPEXECFWK_FORM_DBCACHE_FIND_FAIL, + ERR_APPEXECFWK_FORM_JSON_CREATE_DIR_FAIL, + ERR_APPEXECFWK_FORM_JSON_NEW_FILE_FAIL, + ERR_APPEXECFWK_FORM_JSON_NO_DIR, + ERR_APPEXECFWK_FORM_JSON_OPEN_FAIL, + ERR_APPEXECFWK_FORM_JSON_FILE_EMPTY, + ERR_APPEXECFWK_FORM_JSON_FIND_FAIL, + ERR_APPEXECFWK_FORM_JSON_PARSE_FAIL, + ERR_APPEXECFWK_FORM_JSON_DELETE_FAIL, - // error code in sdk - ERR_APPEXECFWK_FORM_GET_FMS_FAILED, - ERR_APPEXECFWK_FORM_SEND_FMS_MSG, - ERR_APPEXECFWK_FORM_FORM_DUPLICATE_ADDED, - ERR_APPEXECFWK_FORM_IN_RECOVER, - ERR_APPEXECFWK_FORM_GET_SYSMGR_FAILED + // error code in sdk + ERR_GET_FMS_RPC, + ERR_FORM_DUPLICATE_ADDED, + ERR_SEND_FMS_MSG, + ERR_GET_BMS_RPC, + ERR_SEND_BMS_MSG, + ERR_IN_RECOVER, }; constexpr ErrCode APPEXECFWK_APPEXECFWK_ERR_OFFSET = ErrCodeOffset(SUBSYS_APPEXECFWK, APPEXECFWK_MODULE_APPEXECFWK); enum { diff --git a/interfaces/innerkits/appexecfwk_base/include/form_info.h b/interfaces/innerkits/appexecfwk_base/include/form_info.h index 6048620d7fdef30262521fe34f478edfa0d02528..3b28190c973c738895925a1275ea296b91e4cffd 100644 --- a/interfaces/innerkits/appexecfwk_base/include/form_info.h +++ b/interfaces/innerkits/appexecfwk_base/include/form_info.h @@ -21,6 +21,7 @@ namespace OHOS { namespace AppExecFwk { + enum class FormsColorMode { AUTO_MODE = -1, DARK_MODE = 0, @@ -67,6 +68,7 @@ struct FormInfo : public Parcelable { virtual bool Marshalling(Parcel &parcel) const override; static FormInfo *Unmarshalling(Parcel &parcel); }; + } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_INTERFACES_INNERKITS_APPEXECFWK_BASE_INCLUDE_FORM_H diff --git a/interfaces/innerkits/appexecfwk_base/include/form_provider_data.h b/interfaces/innerkits/appexecfwk_base/include/form_provider_data.h index e23be681025b11ab529ab0704d1c407fed8655ec..51f2a3ef4fcb45d9b9215c4ef526aa5de65ec331 100644 --- a/interfaces/innerkits/appexecfwk_base/include/form_provider_data.h +++ b/interfaces/innerkits/appexecfwk_base/include/form_provider_data.h @@ -1,164 +1,163 @@ -/* - * 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 FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_DATA_H -#define FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_DATA_H - -#include -#include -#include - -#include "ashmem.h" -#include "message_parcel.h" -#include "nlohmann/json.hpp" -#include "parcel.h" - -namespace OHOS { -namespace AppExecFwk { -/** - * @class FormProviderData - * Defines form provider data. - */ -class FormProviderData : public Parcelable { -public: - /** - * @brief Constructor. - */ - FormProviderData(); - - /** - * @brief A constructor used to create a {@code FormProviderData} instance with data of - * the {@code nlohmann::json} type specified. - * @param jsonData Indicates the data to be carried in the new {@code FormProviderData} instance, - * in {@code nlohmann::json} format. - */ - FormProviderData(nlohmann::json &jsonData); - - /** - * @brief A constructor used to create a {@code FormProviderData} instance with data of the {@code String} type - * specified. - * @param jsonDataString Indicates the data to be carried in the new {@code FormProviderData} instance, in JSON - * string format. - */ - FormProviderData(std::string jsonDataString); - - /** - * @brief Destructor. - */ - virtual ~FormProviderData(){}; - - /** - * @brief Updates form data in this {@code FormProviderData} object. - * @param jsonData Indicates the new data to use, in {@code nlohmann::json} format. - */ - void UpdateData(nlohmann::json &jsonData); - - /** - * @brief Obtains the form data stored in this {@code FormProviderData} object. - * @return Returns json string format - */ - std::string GetDataString() const; - - /** - * @brief Adds an image to this {@code FormProviderData} instance. - * @param picName Indicates the name of the image to add. - * @param data Indicates the binary data of the image content. - */ - void AddImageData(std::string picName, char *data); - - /** - * @brief Removes data of an image with the specified {@code picName} from this {@code FormProviderData} instance. - * @param picName Indicates the name of the image to remove. - */ - void RemoveImageData(std::string picName); - - /** - * @brief Obtains the add/remove state stored in this {@code FormProviderData} object. - * @return Returns the add/remove state of shared image data. - */ - int32_t GetImageDataState(); - - /** - * @brief Updates imageDataState in this {@code FormProviderData} object. - * @param imageDataState Indicates the imageDataState to update. - */ - void SetImageDataState(int32_t imageDataState); - - /** - * @brief Obtains the imageDataMap stored in this {@code FormProviderData} object. - * @return Returns the map that contains shared image data. - */ - std::map, int32_t>> GetImageDataMap(); - - /** - * @brief Updates imageDataMap in this {@code FormProviderData} object. - * @param imageDataMap Indicates the imageDataMap to update. - */ - void SetImageDataMap(std::map, int32_t>> imageDataMap); - - /** - * @brief Obtains the form data stored in this {@code FormProviderData} object. - * @return Returns json data - */ - nlohmann::json GetData() const; - /** - * @brief Set the form data stored from string string. - * @param Returns string string. - */ - void SetDataString(std::string &jsonDataString); - /** - * @brief Merge new data to FormProviderData. - * @param addJsonData data to merge to FormProviderData - */ - void MergeData(nlohmann::json &addJsonData); - - /** - * Read this {@code FormProviderData} object from a Parcel. - * @param parcel the parcel - * eturn Returns {@code true} if the marshalling is successful; returns {@code false} otherwise. - */ - bool ReadFromParcel(Parcel &parcel); - /** - * @brief Marshals this {@code FormProviderData} object into a {@link ohos.utils.Parcel} object. - * @param parcel Indicates the {@code Parcel} object for marshalling. - * @return Returns {@code true} if the marshalling is successful; returns {@code false} otherwise. - */ - virtual bool Marshalling(Parcel &parcel) const override; - - /** - * @brief Unmarshals this {@code FormProviderData} object from a {@link ohos.utils.Parcel} object. - * @param parcel Indicates the {@code Parcel} object for unmarshalling. - * @return Returns FormProviderData. - */ - static FormProviderData* Unmarshalling(Parcel &parcel); - - /** - * @brief Clear imageDataMap, rawImageBytesMap, imageDataState and jsonFormProviderData. - */ - void ClearData(); - -private: - bool WriteImageDataToParcel(Parcel &parcel, std::string picName, char *data) const; - -private: - nlohmann::json jsonFormProviderData_; - std::map, int32_t>> imageDataMap_; - std::map rawImageBytesMap_; - int32_t imageDataState_; -}; -} // namespace AppExecFwk -} // namespace OHOS - -#endif // FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_DATA_H +/* + * 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 FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_DATA_H +#define FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_DATA_H + +#include +#include + +#include "ashmem.h" +#include "message_parcel.h" +#include "nlohmann/json.hpp" +#include "parcel.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormProviderData + * Defines form provider data. + */ +class FormProviderData : public Parcelable { +public: + /** + * @brief Constructor. + */ + FormProviderData(); + + /** + * @brief A constructor used to create a {@code FormProviderData} instance with data of + * the {@code nlohmann::json} type specified. + * @param jsonData Indicates the data to be carried in the new {@code FormProviderData} instance, + * in {@code nlohmann::json} format. + */ + FormProviderData(nlohmann::json &jsonData); + + /** + * @brief A constructor used to create a {@code FormProviderData} instance with data of the {@code String} type + * specified. + * @param jsonDataString Indicates the data to be carried in the new {@code FormProviderData} instance, in JSON + * string format. + */ + FormProviderData(std::string jsonDataString); + + /** + * @brief Destructor. + */ + virtual ~FormProviderData(){}; + + /** + * @brief Updates form data in this {@code FormProviderData} object. + * @param jsonData Indicates the new data to use, in {@code nlohmann::json} format. + */ + void UpdateData(nlohmann::json &jsonData); + + /** + * @brief Obtains the form data stored in this {@code FormProviderData} object. + * @return Returns json string format + */ + std::string GetDataString() const; + + /** + * @brief Adds an image to this {@code FormProviderData} instance. + * @param picName Indicates the name of the image to add. + * @param data Indicates the binary data of the image content. + */ + void AddImageData(std::string picName, char *data); + + /** + * @brief Removes data of an image with the specified {@code picName} from this {@code FormProviderData} instance. + * @param picName Indicates the name of the image to remove. + */ + void RemoveImageData(std::string picName); + + /** + * @brief Obtains the add/remove state stored in this {@code FormProviderData} object. + * @return Returns the add/remove state of shared image data. + */ + int32_t GetImageDataState(); + + /** + * @brief Updates imageDataState in this {@code FormProviderData} object. + * @param imageDataState Indicates the imageDataState to update. + */ + void SetImageDataState(int32_t imageDataState); + + /** + * @brief Obtains the imageDataMap stored in this {@code FormProviderData} object. + * @return Returns the map that contains shared image data. + */ + std::map, int32_t>> GetImageDataMap(); + + /** + * @brief Updates imageDataMap in this {@code FormProviderData} object. + * @param imageDataMap Indicates the imageDataMap to update. + */ + void SetImageDataMap(std::map, int32_t>> imageDataMap); + + /** + * @brief Obtains the form data stored in this {@code FormProviderData} object. + * @return Returns json data + */ + nlohmann::json GetData() const; + /** + * @brief Set the form data stored from string string. + * @param Returns string string. + */ + void SetDataString(std::string &jsonDataString); + /** + * @brief Merge new data to FormProviderData. + * @param addJsonData data to merge to FormProviderData + */ + void MergeData(nlohmann::json &addJsonData); + + /** + * Read this {@code FormProviderData} object from a Parcel. + * @param parcel the parcel + * eturn Returns {@code true} if the marshalling is successful; returns {@code false} otherwise. + */ + bool ReadFromParcel(Parcel &parcel); + /** + * @brief Marshals this {@code FormProviderData} object into a {@link ohos.utils.Parcel} object. + * @param parcel Indicates the {@code Parcel} object for marshalling. + * @return Returns {@code true} if the marshalling is successful; returns {@code false} otherwise. + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * @brief Unmarshals this {@code FormProviderData} object from a {@link ohos.utils.Parcel} object. + * @param parcel Indicates the {@code Parcel} object for unmarshalling. + * @return Returns FormProviderData. + */ + static FormProviderData* Unmarshalling(Parcel &parcel); + + /** + * @brief Clear imageDataMap, rawImageBytesMap, imageDataState and jsonFormProviderData. + */ + void ClearData(); + +private: + bool WriteImageDataToParcel(Parcel &parcel, std::string picName, char *data) const; + +private: + nlohmann::json jsonFormProviderData_; + std::map, int32_t>> imageDataMap_; + std::map rawImageBytesMap_; + int32_t imageDataState_; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_DATA_H diff --git a/interfaces/innerkits/appexecfwk_base/include/form_provider_info.h b/interfaces/innerkits/appexecfwk_base/include/form_provider_info.h index 522b8584d0550a395022032aa42dd9a85c6d93f6..73bfd4a478cf0b6a8c48a99b5600d4064c19f6ec 100644 --- a/interfaces/innerkits/appexecfwk_base/include/form_provider_info.h +++ b/interfaces/innerkits/appexecfwk_base/include/form_provider_info.h @@ -1,98 +1,114 @@ -/* - * 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 FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_INFO_H -#define FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_INFO_H - -#include -#include "form_provider_data.h" -#include "parcel.h" - -namespace OHOS { -namespace AppExecFwk { -/** - * @struct FormProviderInfo - * Defines form provider info. - */ -class FormProviderInfo : public Parcelable { -public: - FormProviderInfo() = default; - ~FormProviderInfo() = default; - - /** - * @brief Set the form data. - * @param formProviderData The form data. - */ - inline void SetFormData(const FormProviderData &formProviderData) - { - jsBindingData_ = formProviderData; - } - - /** - * @brief Get the form data. - * @return the form data. - */ - inline FormProviderData GetFormData() const - { - return jsBindingData_; - } - /** - * @brief Get the form data. - * @return the form data. - */ - inline std::string GetFormDataString() const - { - return jsBindingData_.GetDataString(); - } - - /** - * @brief Set the upgrade flg. - * @param upgradeFlg The upgrade flg. - */ - inline void SetUpgradeFlg(const bool upgradeFlg) - { - upgradeFlg_ = upgradeFlg; - } - /** - * @brief Get the upgrade flg. - * @return the upgrade flg. - */ - inline bool GetUpgradeFlg() const - { - return upgradeFlg_; - } - - /** - * @brief Set form date by string. - * @param dataString string json data. - */ - void SetFormDataString(std::string &dataString); - - /** - * @brief Merge new data to FormProviderData. - * @param addJsonData data to merge to FormProviderData - */ - void MergeData(nlohmann::json &addJsonData); - - bool ReadFromParcel(Parcel &parcel); - virtual bool Marshalling(Parcel &parcel) const override; - static FormProviderInfo *Unmarshalling(Parcel &parcel); -private: - FormProviderData jsBindingData_; - bool upgradeFlg_; -}; -} // namespace AppExecFwk -} // namespace OHOS -#endif // FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_INFO_H +/* + * 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 FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_INFO_H +#define FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_INFO_H + +#include +#include "form_provider_data.h" +#include "parcel.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @struct FormProviderInfo + * Defines form provider info. + */ +class FormProviderInfo : public Parcelable { +public: + FormProviderInfo() = default; + ~FormProviderInfo() = default; + /** + * @brief Set the id of the form. + * @param formId the id of the form. + */ + inline void SetFormId(const int64_t formId) + { + formId_ = formId; + } + /** + * @brief Get the id of the form. + * @return the id of the form. + */ + inline int64_t GetFormId() const + { + return formId_; + } + /** + * @brief Set the form data. + * @param formProviderData The form data. + */ + inline void SetFormData(const FormProviderData &formProviderData) + { + jsBindingData_ = formProviderData; + } + + /** + * @brief Get the form data. + * @return the form data. + */ + inline FormProviderData GetFormData() const + { + return jsBindingData_; + } + /** + * @brief Get the form data. + * @return the form data. + */ + inline std::string GetFormDataString() const + { + return jsBindingData_.GetDataString(); + } + + /** + * @brief Set the upgrade flg. + * @param upgradeFlg The upgrade flg. + */ + inline void SetUpgradeFlg(const bool upgradeFlg) + { + upgradeFlg_ = upgradeFlg; + } + /** + * @brief Get the upgrade flg. + * @return the upgrade flg. + */ + inline bool GetUpgradeFlg() const + { + return upgradeFlg_; + } + + /** + * @brief Set form date by string. + * @param dataString string json data. + */ + void SetFormDataString(std::string &dataString); + + /** + * @brief Merge new data to FormProviderData. + * @param addJsonData data to merge to FormProviderData + */ + void MergeData(nlohmann::json &addJsonData); + + bool ReadFromParcel(Parcel &parcel); + virtual bool Marshalling(Parcel &parcel) const override; + static FormProviderInfo *Unmarshalling(Parcel &parcel); +private: + int64_t formId_; + FormProviderData jsBindingData_; + bool upgradeFlg_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_OHOS_FORM_PROVIDER_INFO_H diff --git a/interfaces/innerkits/appexecfwk_base/src/ability_info.cpp b/interfaces/innerkits/appexecfwk_base/src/ability_info.cpp index a71151fa06a767b9dda71e84012b1e0079e8bc2b..cbd638a7fbd422bc8fffe44a727a59ca85e3f37d 100644 --- a/interfaces/innerkits/appexecfwk_base/src/ability_info.cpp +++ b/interfaces/innerkits/appexecfwk_base/src/ability_info.cpp @@ -79,7 +79,8 @@ const std::string JSON_KEY_LABEL_ID = "labelId"; const std::string JSON_KEY_DESCRIPTION_ID = "descriptionId"; const std::string JSON_KEY_ICON_ID = "iconId"; const std::string JSON_KEY_FORM_ENABLED = "formEnabled"; - +const std::string JSON_KEY_SRC_PATH = "srcPath"; +const std::string JSON_KEY_SRC_LANGUAGE = "srcLanguage"; } // namespace bool AbilityInfo::ReadFromParcel(Parcel &parcel) @@ -103,6 +104,8 @@ bool AbilityInfo::ReadFromParcel(Parcel &parcel) targetAbility = Str16ToStr8(parcel.ReadString16()); readPermission = Str16ToStr8(parcel.ReadString16()); writePermission = Str16ToStr8(parcel.ReadString16()); + srcPath = Str16ToStr8(parcel.ReadString16()); + srcLanguage = Str16ToStr8(parcel.ReadString16()); visible = parcel.ReadBool(); isLauncherAbility = parcel.ReadBool(); isNativeAbility = parcel.ReadBool(); @@ -233,6 +236,8 @@ bool AbilityInfo::Marshalling(Parcel &parcel) const WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(targetAbility)); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(readPermission)); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(writePermission)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(srcPath)); + WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(String16, parcel, Str8ToStr16(srcLanguage)); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Bool, parcel, visible); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Bool, parcel, isLauncherAbility); WRITE_PARCEL_AND_RETURN_FALSE_IF_FAIL(Bool, parcel, isNativeAbility); @@ -375,6 +380,8 @@ void to_json(nlohmann::json &jsonObject, const AbilityInfo &abilityInfo) {JSON_KEY_SUPPORT_PIP_MODE, abilityInfo.supportPipMode}, {JSON_KEY_READ_PERMISSION, abilityInfo.readPermission}, {JSON_KEY_WRITE_PERMISSION, abilityInfo.writePermission}, + {JSON_KEY_SRC_PATH, abilityInfo.srcPath}, + {JSON_KEY_SRC_LANGUAGE, abilityInfo.srcLanguage}, {JSON_KEY_CONFIG_CHANGES, abilityInfo.configChanges}, {JSON_KEY_FORM_ENTITY, abilityInfo.formEntity}, {JSON_KEY_MIN_FORM_HEIGHT, abilityInfo.minFormHeight}, @@ -449,6 +456,8 @@ void from_json(const nlohmann::json &jsonObject, AbilityInfo &abilityInfo) abilityInfo.supportPipMode = jsonObject.at(JSON_KEY_SUPPORT_PIP_MODE).get(); abilityInfo.readPermission = jsonObject.at(JSON_KEY_READ_PERMISSION).get(); abilityInfo.writePermission = jsonObject.at(JSON_KEY_WRITE_PERMISSION).get(); + abilityInfo.srcPath = jsonObject.at(JSON_KEY_SRC_PATH).get(); + abilityInfo.srcLanguage = jsonObject.at(JSON_KEY_SRC_LANGUAGE).get(); abilityInfo.configChanges = jsonObject.at(JSON_KEY_CONFIG_CHANGES).get>(); abilityInfo.formEntity = jsonObject.at(JSON_KEY_FORM_ENTITY).get(); abilityInfo.minFormHeight = jsonObject.at(JSON_KEY_MIN_FORM_HEIGHT).get(); diff --git a/interfaces/innerkits/appexecfwk_base/src/application_info.cpp b/interfaces/innerkits/appexecfwk_base/src/application_info.cpp index d24b23b86cacbe6310474a157e212c7a6bdc5e24..41ba13b3306eb06019a6bf43d7319c9b5fa1c5c3 100644 --- a/interfaces/innerkits/appexecfwk_base/src/application_info.cpp +++ b/interfaces/innerkits/appexecfwk_base/src/application_info.cpp @@ -232,7 +232,7 @@ void ApplicationInfo::ConvertToCompatibleApplicationInfo(CompatibleApplicationIn compatibleApplicationInfo.permissions = permissions; compatibleApplicationInfo.moduleInfos = moduleInfos; compatibleApplicationInfo.supportedModes = supportedModes; - compatibleApplicationInfo.enabled = debug; + compatibleApplicationInfo.enabled = enabled; } } // namespace AppExecFwk diff --git a/interfaces/innerkits/appexecfwk_base/src/form_info.cpp b/interfaces/innerkits/appexecfwk_base/src/form_info.cpp index 9e589c283d149557e8d2057d85149b45ba129780..7f9f1d2e23f69f72ba35bea6f63113f9640b9d23 100644 --- a/interfaces/innerkits/appexecfwk_base/src/form_info.cpp +++ b/interfaces/innerkits/appexecfwk_base/src/form_info.cpp @@ -29,7 +29,9 @@ namespace OHOS { namespace AppExecFwk { + namespace { + const std::string JSON_KEY_COLOR_MODE = "colorMode"; const std::string JSON_KEY_PACKAGE = "package"; const std::string JSON_KEY_SUPPORT_DIMENSIONS = "supportDimensions"; @@ -55,6 +57,7 @@ const std::string JSON_KEY_FORM_VISIBLE_NOTIFY = "formVisibleNotify"; const std::string JSON_KEY_RELATED_BUNDLE_NAME = "relatedBundleName"; const std::string JSON_KEY_DEFAULT_FLAG = "defaultFlag"; const std::string JSON_KEY_PORTRAIT_LAYOUTS = "portraitLayouts"; + } // namespace bool FormInfo::ReadFromParcel(Parcel &parcel) @@ -181,16 +184,12 @@ bool FormInfo::Marshalling(Parcel &parcel) const void to_json(nlohmann::json &jsonObject, const FormCustomizeData &customizeDatas) { - jsonObject = nlohmann::json{ - {JSON_KEY_NAME, customizeDatas.name}, - {JSON_KEY_VALUE, customizeDatas.value} - }; + jsonObject = nlohmann::json{{JSON_KEY_NAME, customizeDatas.name}, {JSON_KEY_VALUE, customizeDatas.value}}; } void to_json(nlohmann::json &jsonObject, const FormInfo &formInfo) { - jsonObject = nlohmann::json{ - {JSON_KEY_NAME, formInfo.name}, + jsonObject = nlohmann::json{{JSON_KEY_NAME, formInfo.name}, {JSON_KEY_PACKAGE, formInfo.package}, {JSON_KEY_BUNDLE_NAME, formInfo.bundleName}, {JSON_KEY_MODULE_NAME, formInfo.moduleName}, @@ -213,8 +212,7 @@ void to_json(nlohmann::json &jsonObject, const FormInfo &formInfo) {JSON_KEY_SUPPORT_DIMENSIONS, formInfo.supportDimensions}, {JSON_KEY_CUSTOMIZE_DATA, formInfo.customizeDatas}, {JSON_KEY_LANDSCAPE_LAYOUTS, formInfo.landscapeLayouts}, - {JSON_KEY_PORTRAIT_LAYOUTS, formInfo.portraitLayouts} - }; + {JSON_KEY_PORTRAIT_LAYOUTS, formInfo.portraitLayouts}}; } void from_json(const nlohmann::json &jsonObject, FormCustomizeData &customizeDatas) @@ -250,5 +248,6 @@ void from_json(const nlohmann::json &jsonObject, FormInfo &formInfo) formInfo.landscapeLayouts = jsonObject.at(JSON_KEY_LANDSCAPE_LAYOUTS).get>(); formInfo.portraitLayouts = jsonObject.at(JSON_KEY_PORTRAIT_LAYOUTS).get>(); } + } // namespace AppExecFwk } // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_base/src/form_js_info.cpp b/interfaces/innerkits/appexecfwk_base/src/form_js_info.cpp index 13a5d3c2684590d10ba36156844b6dda4c35fd5b..df1deb988a0721179d6f4ac36ef2099404b73057 100644 --- a/interfaces/innerkits/appexecfwk_base/src/form_js_info.cpp +++ b/interfaces/innerkits/appexecfwk_base/src/form_js_info.cpp @@ -1,92 +1,91 @@ -/* - * 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 "form_js_info.h" -#include "string_ex.h" - -namespace OHOS { -namespace AppExecFwk { -bool FormJsInfo::ReadFromParcel(Parcel &parcel) -{ - formId = parcel.ReadInt64(); - formName = Str16ToStr8(parcel.ReadString16()); - bundleName = Str16ToStr8(parcel.ReadString16()); - abilityName = Str16ToStr8(parcel.ReadString16()); - - formTempFlg = parcel.ReadBool(); - jsFormCodePath = Str16ToStr8(parcel.ReadString16()); - formData = Str16ToStr8(parcel.ReadString16()); - - auto bindingData = parcel.ReadParcelable(); - formProviderData = *bindingData; - if (nullptr == bindingData){ - return false; - } - return true; -} - -FormJsInfo *FormJsInfo::Unmarshalling(Parcel &parcel) -{ - FormJsInfo *formJsInfo = new (std::nothrow) FormJsInfo(); - if (formJsInfo && !formJsInfo->ReadFromParcel(parcel)) { - delete formJsInfo; - formJsInfo = nullptr; - } - return formJsInfo; -} - -bool FormJsInfo::Marshalling(Parcel &parcel) const -{ - // write formId - if (!parcel.WriteInt64(formId)) { - return false; - } - // write formName - if (!parcel.WriteString16(Str8ToStr16(formName))) { - return false; - } - // write bundleName - if (!parcel.WriteString16(Str8ToStr16(bundleName))) { - return false; - } - // write abilityName - if (!parcel.WriteString16(Str8ToStr16(abilityName))) { - return false; - } - - // write tempFlag - if (!parcel.WriteBool(formTempFlg)) { - return false; - } - - // write jsFormCodePath - if (!parcel.WriteString16(Str8ToStr16(jsFormCodePath))) { - return false; - } - - // write formData - if (!parcel.WriteString16(Str8ToStr16(formData))) { - return false; - } - - // write formProviderData - if (!parcel.WriteParcelable(&formProviderData)) { - return false; - } - - return true; -} -} // namespace AppExecFwk +/* + * 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 "form_js_info.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +bool FormJsInfo::ReadFromParcel(Parcel &parcel) +{ + formId = parcel.ReadInt64(); + formName = Str16ToStr8(parcel.ReadString16()); + bundleName = Str16ToStr8(parcel.ReadString16()); + abilityName = Str16ToStr8(parcel.ReadString16()); + + formTempFlg = parcel.ReadBool(); + jsFormCodePath = Str16ToStr8(parcel.ReadString16()); + formData = Str16ToStr8(parcel.ReadString16()); + + auto bindingData = parcel.ReadParcelable(); + formProviderData = *bindingData; + + return true; +} + +FormJsInfo *FormJsInfo::Unmarshalling(Parcel &parcel) +{ + FormJsInfo *formJsInfo = new (std::nothrow) FormJsInfo(); + if (formJsInfo && !formJsInfo->ReadFromParcel(parcel)) { + delete formJsInfo; + formJsInfo = nullptr; + } + return formJsInfo; +} + +bool FormJsInfo::Marshalling(Parcel &parcel) const +{ + // write formId + if (!parcel.WriteInt64(formId)) { + return false; + } + // write formName + if (!parcel.WriteString16(Str8ToStr16(formName))) { + return false; + } + // write bundleName + if (!parcel.WriteString16(Str8ToStr16(bundleName))) { + return false; + } + // write abilityName + if (!parcel.WriteString16(Str8ToStr16(abilityName))) { + return false; + } + + // write tempFlag + if (!parcel.WriteBool(formTempFlg)) { + return false; + } + + // write jsFormCodePath + if (!parcel.WriteString16(Str8ToStr16(jsFormCodePath))) { + return false; + } + + // write formData + if (!parcel.WriteString16(Str8ToStr16(formData))) { + return false; + } + + // write formProviderData + if (!parcel.WriteParcelable(&formProviderData)) { + return false; + } + + + return true; +} +} // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/appexecfwk_base/src/form_provider_data.cpp b/interfaces/innerkits/appexecfwk_base/src/form_provider_data.cpp index 918a832f4048055e3191ddb7def4be7bb65e4648..e314d468e144efc2d81f3895e5c8874507c0fd7b 100644 --- a/interfaces/innerkits/appexecfwk_base/src/form_provider_data.cpp +++ b/interfaces/innerkits/appexecfwk_base/src/form_provider_data.cpp @@ -1,324 +1,321 @@ -/* - * 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 - -#include "app_log_wrapper.h" -#include "form_provider_data.h" -#include "message_parcel.h" -#include "string_ex.h" - -namespace OHOS { -namespace AppExecFwk { -const int IMAGE_DATA_STATE_REMOVED = -1; -const int IMAGE_DATA_STATE_NO_OPERATION = 0; -const int IMAGE_DATA_STATE_ADDED = 1; -const std::string JSON_EMPTY_STRING = "{}"; - -/** - * @brief Constructor. - */ -FormProviderData::FormProviderData() -{ - jsonFormProviderData_.clear(); -} - -/** - * @brief A constructor used to create a {@code FormProviderData} instance with data of - * the {@code nlohmann::json} type specified. - * @param jsonData Indicates the data to be carried in the new {@code FormProviderData} instance, - * in {@code nlohmann::json} format. - */ -FormProviderData::FormProviderData(nlohmann::json &jsonData) -{ - jsonFormProviderData_ = jsonData; -} - -/** - * @brief A constructor used to create a {@code FormProviderData} instance with data of the {@code String} type - * specified. - * @param jsonDataString Indicates the data to be carried in the new {@code FormProviderData} instance, - * in JSON string format. - */ -FormProviderData::FormProviderData(std::string jsonDataString) -{ - if(jsonDataString.empty()) { - jsonDataString = JSON_EMPTY_STRING; - } - jsonFormProviderData_ = nlohmann::json::parse(jsonDataString); -} - -/** - * @brief Updates form data in this {@code FormProviderData} object. - * @param jsonData Indicates the new data to use, in {@code ZSONObject} format. - */ -void FormProviderData::UpdateData(nlohmann::json &jsonData) -{ - jsonFormProviderData_ = jsonData; -} -/** - * @brief Obtains the form data stored in this {@code FormProviderData} object. - * @return Returns json data - */ -nlohmann::json FormProviderData::GetData() const -{ - return jsonFormProviderData_; -} -/** - * @brief Obtains the form data stored in this {@code FormProviderData} object. - * @return Returns json string format - */ -std::string FormProviderData::GetDataString() const -{ - APP_LOGI("%{public}s called", __func__); - std::string dataStr = jsonFormProviderData_.empty() ? "" : jsonFormProviderData_.dump(); - APP_LOGI("%{public}s, data: %{public}s", __func__, dataStr.c_str()); - return dataStr; -} - -/** - * @brief Adds an image to this {@code FormProviderData} instance. - * @param picName Indicates the name of the image to add. - * @param data Indicates the binary data of the image content. - */ -void FormProviderData::AddImageData(std::string picName, char *data) -{ - if ((picName.length() == 0) || (sizeof(data) == 0)) { - APP_LOGE("input param is NULL!"); - return; - } - - rawImageBytesMap_[picName] = data; - - imageDataState_ = IMAGE_DATA_STATE_ADDED; -} - -/** - * @brief Removes data of an image with the specified {@code picName} from this {@code FormProviderData} instance. - * @param picName Indicates the name of the image to remove. - */ -void FormProviderData::RemoveImageData(std::string picName) -{ - rawImageBytesMap_.erase(picName); -} - -/** - * @brief Set the form data stored from string string. - * @param Returns string string. - */ -void FormProviderData::SetDataString(std::string &jsonDataString) -{ - APP_LOGI("%{public}s called", __func__); - if(jsonDataString.empty()) { - jsonDataString = JSON_EMPTY_STRING; - } - jsonFormProviderData_ = nlohmann::json::parse(jsonDataString); -} -/** - * @brief Merge new data to FormProviderData. - * @param addJsonData data to merge to FormProviderData - */ -void FormProviderData::MergeData(nlohmann::json &addJsonData) -{ - APP_LOGI("%{public}s called", __func__); - if (addJsonData.empty()) { - return; - } - - if (jsonFormProviderData_.empty()) { - jsonFormProviderData_ = addJsonData; - return; - } - - for (auto && [key, value] : addJsonData.items()) { - jsonFormProviderData_[key] = value; - } -} - -/** - * @brief Obtains the imageDataMap stored in this {@code FormProviderData} object. - * @return Returns the map that contains shared image data. - */ -std::map, int32_t>> FormProviderData::GetImageDataMap() -{ - return imageDataMap_; -} - -/** - * @brief Obtains the add/remove state stored in this {@code FormProviderData} object. - * @return Returns the add/remove state of shared image data. - */ -int32_t FormProviderData::GetImageDataState() -{ - return imageDataState_; -} - -/** - * @brief Updates imageDataState in this {@code FormProviderData} object. - * @param imageDataState Indicates the imageDataState to update. - */ -void FormProviderData::SetImageDataState(int32_t imageDataState) -{ - imageDataState_ = imageDataState; -} - -/** - * @brief Updates imageDataMap in this {@code FormProviderData} object. - * @param imageDataMap Indicates the imageDataMap to update. - */ -void FormProviderData::SetImageDataMap(std::map, int32_t>> imageDataMap) -{ - imageDataMap_ = imageDataMap; -} - -/** - * Read this {@code FormProviderData} object from a Parcel. - * @param parcel the parcel - * eturn Returns {@code true} if the marshalling is successful; returns {@code false} otherwise. - */ -bool FormProviderData::ReadFromParcel(Parcel &parcel) -{ - jsonFormProviderData_ = nlohmann::json::parse(Str16ToStr8(parcel.ReadString16())); - - imageDataState_ = parcel.ReadInt32(); - switch (imageDataState_) { - case IMAGE_DATA_STATE_ADDED: { - int32_t imageDataNum = parcel.ReadInt32(); - for (int32_t i = 0; i < imageDataNum; i++) { - MessageParcel* messageParcel = (MessageParcel*)&parcel; - sptr ashmem = messageParcel->ReadAshmem(); - if (ashmem == nullptr) { - APP_LOGE("%{public}s failed, ashmem is nullptr", __func__); - return false; - } - - int32_t len = parcel.ReadInt32(); - std::pair, int32_t> imageDataRecord = std::make_pair(ashmem, len); - imageDataMap_.emplace(Str16ToStr8(parcel.ReadString16()), imageDataRecord); - } - break; - } - case IMAGE_DATA_STATE_NO_OPERATION: - case IMAGE_DATA_STATE_REMOVED: - break; - default: - APP_LOGW("%{public}s failed, unexpected imageDataState_ %{public}d", __func__, imageDataState_); - break; - } - return true; -} - -/** - * @brief Marshals this {@code FormProviderData} object into a {@link ohos.utils.Parcel} object. - * @param parcel Indicates the {@code Parcel} object for marshalling. - * @return Returns {@code true} if the marshalling is successful; returns {@code false} otherwise. - */ -bool FormProviderData::Marshalling(Parcel &parcel) const -{ - APP_LOGI("%{public}s called, jsonFormProviderData_: %{public}s", __func__, jsonFormProviderData_.dump().c_str()); - if (!parcel.WriteString16(Str8ToStr16(jsonFormProviderData_.empty() ? JSON_EMPTY_STRING : jsonFormProviderData_.dump()))) { - return false; - } - - parcel.WriteInt32(imageDataState_); - switch (imageDataState_) { - case IMAGE_DATA_STATE_ADDED: { - if (rawImageBytesMap_.size() == 0) { - APP_LOGE("%{public}s failed, rawImageBytesMap_ is empty", __func__); - return false; - } - parcel.WriteInt32(rawImageBytesMap_.size()); // firstly write the number of shared image to add - for (auto &entry : rawImageBytesMap_) { - if (!WriteImageDataToParcel(parcel, entry.first, entry.second)) { - APP_LOGE("%{public}s failed, the picture name is %{public}s", __func__, entry.first.c_str()); - return false; - } - parcel.WriteInt32(sizeof(entry.second)); - parcel.WriteString16(Str8ToStr16(entry.first)); - } - break; - } - case IMAGE_DATA_STATE_NO_OPERATION: - case IMAGE_DATA_STATE_REMOVED: - break; - default: - APP_LOGW("%{public}s failed, unexpected imageDataState_ %{public}d", __func__, imageDataState_); - break; - } - return true; -} - -/** - * @brief Unmarshals this {@code FormProviderData} object from a {@link ohos.utils.Parcel} object. - * @param parcel Indicates the {@code Parcel} object for unmarshalling. - * @return FormProviderData. - */ -FormProviderData* FormProviderData::Unmarshalling(Parcel &parcel) -{ - FormProviderData *formProviderData = new (std::nothrow) FormProviderData(); - if (formProviderData && !formProviderData->ReadFromParcel(parcel)) { - delete formProviderData; - formProviderData = nullptr; - } - std::string str = formProviderData->GetDataString(); - APP_LOGI("%{public}s, , provider data length: %{public}zu, provider data: %{public}s", __func__, str.length(), str.c_str()); - return formProviderData; -} - -/** - * @brief Clear imageDataMap, rawImageBytesMap_, imageDataState_ and jsonFormProviderData_. - */ -void FormProviderData::ClearData() -{ - jsonFormProviderData_.clear(); -} - -bool FormProviderData::WriteImageDataToParcel(Parcel &parcel, std::string picName, char *data) const -{ - sptr ashmem = Ashmem::CreateAshmem(picName.c_str(), sizeof(data)); - if (ashmem == nullptr) { - APP_LOGE("create shared memory fail"); - return false; - } - - bool ret = ashmem->MapReadAndWriteAshmem(); - if (!ret) { - APP_LOGE("map shared memory fail"); - return false; - } - - ret = ashmem->WriteToAshmem(data, sizeof(data), 0); - if (!ret) { - APP_LOGE("write image data to shared memory fail"); - return false; - } - - ashmem->UnmapAshmem(); - - MessageParcel* messageParcel = (MessageParcel*)&parcel; - ret = messageParcel->WriteAshmem(ashmem); - - ashmem->CloseAshmem(); // close ashmem after writeAshmem because writeAshmem will dup fd - if (!ret) { - APP_LOGE("writeAshmem fail, the picture name is %{public}s", picName.c_str()); - return false; - } - - return true; -} -} // namespace AppExecFwk -} // namespace OHOS +/* + * 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 "app_log_wrapper.h" +#include "form_provider_data.h" +#include "message_parcel.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +const int IMAGE_DATA_STATE_REMOVED = -1; +const int IMAGE_DATA_STATE_NO_OPERATION = 0; +const int IMAGE_DATA_STATE_ADDED = 1; + +/** + * @brief Constructor. + */ +FormProviderData::FormProviderData() +{ + jsonFormProviderData_.clear(); +} + +/** + * @brief A constructor used to create a {@code FormProviderData} instance with data of + * the {@code nlohmann::json} type specified. + * @param jsonData Indicates the data to be carried in the new {@code FormProviderData} instance, + * in {@code nlohmann::json} format. + */ +FormProviderData::FormProviderData(nlohmann::json &jsonData) +{ + jsonFormProviderData_ = jsonData; +} + +/** + * @brief A constructor used to create a {@code FormProviderData} instance with data of the {@code String} type + * specified. + * @param jsonDataString Indicates the data to be carried in the new {@code FormProviderData} instance, + * in JSON string format. + */ +FormProviderData::FormProviderData(std::string jsonDataString) +{ + jsonFormProviderData_ = nlohmann::json::parse(jsonDataString); +} + +/** + * @brief Updates form data in this {@code FormProviderData} object. + * @param jsonData Indicates the new data to use, in {@code ZSONObject} format. + */ +void FormProviderData::UpdateData(nlohmann::json &jsonData) +{ + jsonFormProviderData_ = jsonData; +} +/** + * @brief Obtains the form data stored in this {@code FormProviderData} object. + * @return Returns json data + */ +nlohmann::json FormProviderData::GetData() const +{ + return jsonFormProviderData_; +} +/** + * @brief Obtains the form data stored in this {@code FormProviderData} object. + * @return Returns json string format + */ +std::string FormProviderData::GetDataString() const +{ + APP_LOGI("%{public}s called", __func__); + return jsonFormProviderData_.empty() ? "" : jsonFormProviderData_.dump(); +} + +/** + * @brief Adds an image to this {@code FormProviderData} instance. + * @param picName Indicates the name of the image to add. + * @param data Indicates the binary data of the image content. + */ +void FormProviderData::AddImageData(std::string picName, char *data) +{ + if ((picName.length() == 0) || (sizeof(data) == 0)) { + APP_LOGE("input param is NULL!"); + return; + } + + rawImageBytesMap_[picName] = data; + + imageDataState_ = IMAGE_DATA_STATE_ADDED; +} + +/** + * @brief Removes data of an image with the specified {@code picName} from this {@code FormProviderData} instance. + * @param picName Indicates the name of the image to remove. + */ +void FormProviderData::RemoveImageData(std::string picName) +{ + rawImageBytesMap_.erase(picName); +} + +/** + * @brief Set the form data stored from string string. + * @param Returns string string. + */ +void FormProviderData::SetDataString(std::string &jsonDataString) +{ + APP_LOGI("%{public}s called", __func__); + jsonFormProviderData_ = nlohmann::json::parse(jsonDataString); +} +/** + * @brief Merge new data to FormProviderData. + * @param addJsonData data to merge to FormProviderData + */ +void FormProviderData::MergeData(nlohmann::json &addJsonData) +{ + APP_LOGI("%{public}s called", __func__); + if (addJsonData.empty()) { + return; + } + + if (jsonFormProviderData_.empty()) { + jsonFormProviderData_ = addJsonData; + return; + } + + for (auto &it : addJsonData.items()) { + jsonFormProviderData_[it.key()] = it.value(); + } +} + +/** + * @brief Obtains the imageDataMap stored in this {@code FormProviderData} object. + * @return Returns the map that contains shared image data. + */ +std::map, int32_t>> FormProviderData::GetImageDataMap() +{ + return imageDataMap_; +} + +/** + * @brief Obtains the add/remove state stored in this {@code FormProviderData} object. + * @return Returns the add/remove state of shared image data. + */ +int32_t FormProviderData::GetImageDataState() +{ + return imageDataState_; +} + +/** + * @brief Updates imageDataState in this {@code FormProviderData} object. + * @param imageDataState Indicates the imageDataState to update. + */ +void FormProviderData::SetImageDataState(int32_t imageDataState) +{ + imageDataState_ = imageDataState; +} + +/** + * @brief Updates imageDataMap in this {@code FormProviderData} object. + * @param imageDataMap Indicates the imageDataMap to update. + */ +void FormProviderData::SetImageDataMap(std::map, int32_t>> imageDataMap) +{ + imageDataMap_ = imageDataMap; +} + +/** + * Read this {@code FormProviderData} object from a Parcel. + * @param parcel the parcel + * eturn Returns {@code true} if the marshalling is successful; returns {@code false} otherwise. + */ +bool FormProviderData::ReadFromParcel(Parcel &parcel) +{ + jsonFormProviderData_ = nlohmann::json::parse(Str16ToStr8(parcel.ReadString16())); + // MessageParcel* messageParcel = dynamic_cast&parcel; // dynamic_cast need rtti + // if(messageParcel == nullptr) { + // return true; + // } + + imageDataState_ = parcel.ReadInt32(); + switch (imageDataState_) { + case IMAGE_DATA_STATE_ADDED: { + int32_t imageDataNum = parcel.ReadInt32(); + for (int32_t i = 0; i < imageDataNum; i++) { + MessageParcel* messageParcel = (MessageParcel*)&parcel; + sptr ashmem = messageParcel->ReadAshmem(); + if (ashmem == nullptr) { + APP_LOGE("%{public}s failed, ashmem is nullptr", __func__); + return false; + } + + int32_t len = parcel.ReadInt32(); + std::pair, int32_t> imageDataRecord = std::make_pair(ashmem, len); + imageDataMap_.emplace(Str16ToStr8(parcel.ReadString16()), imageDataRecord); + } + break; + } + case IMAGE_DATA_STATE_NO_OPERATION: + case IMAGE_DATA_STATE_REMOVED: + break; + default: + APP_LOGW("%{public}s failed, unexpected imageDataState_ %{public}d", __func__, imageDataState_); + break; + } + return true; +} + +/** + * @brief Marshals this {@code FormProviderData} object into a {@link ohos.utils.Parcel} object. + * @param parcel Indicates the {@code Parcel} object for marshalling. + * @return Returns {@code true} if the marshalling is successful; returns {@code false} otherwise. + */ +bool FormProviderData::Marshalling(Parcel &parcel) const +{ + APP_LOGI("%{public}s called", __func__); + if (!parcel.WriteString16(Str8ToStr16(jsonFormProviderData_.empty() ? "" : jsonFormProviderData_.dump()))) { + return false; + } + // MessageParcel* messageParcel = dynamic_cast&parcel; // dynamic_cast need rtti + // if(messageParcel == nullptr) { + // return true; + // } + + parcel.WriteInt32(imageDataState_); + switch (imageDataState_) { + case IMAGE_DATA_STATE_ADDED: { + if (rawImageBytesMap_.size() == 0) { + APP_LOGE("%{public}s failed, rawImageBytesMap_ is empty", __func__); + return false; + } + parcel.WriteInt32(rawImageBytesMap_.size()); // firstly write the number of shared image to add + for (auto &entry : rawImageBytesMap_) { + if (!WriteImageDataToParcel(parcel, entry.first, entry.second)) { + APP_LOGE("%{public}s failed, the picture name is %{public}s", __func__, entry.first.c_str()); + return false; + } + parcel.WriteInt32(sizeof(entry.second)); + parcel.WriteString16(Str8ToStr16(entry.first)); + } + break; + } + case IMAGE_DATA_STATE_NO_OPERATION: + case IMAGE_DATA_STATE_REMOVED: + break; + default: + APP_LOGW("%{public}s failed, unexpected imageDataState_ %{public}d", __func__, imageDataState_); + break; + } + return true; +} + +/** + * @brief Unmarshals this {@code FormProviderData} object from a {@link ohos.utils.Parcel} object. + * @param parcel Indicates the {@code Parcel} object for unmarshalling. + * @return FormProviderData. + */ +FormProviderData* FormProviderData::Unmarshalling(Parcel &parcel) +{ + FormProviderData *formProviderData = new (std::nothrow) FormProviderData(); + if (formProviderData && !formProviderData->ReadFromParcel(parcel)) { + delete formProviderData; + formProviderData = nullptr; + } + + return formProviderData; +} + +/** + * @brief Clear imageDataMap, rawImageBytesMap_, imageDataState_ and jsonFormProviderData_. + */ +void FormProviderData::ClearData() +{ + jsonFormProviderData_.clear(); +} + +bool FormProviderData::WriteImageDataToParcel(Parcel &parcel, std::string picName, char *data) const +{ + sptr ashmem = Ashmem::CreateAshmem(picName.c_str(), sizeof(data)); + if (ashmem == nullptr) { + APP_LOGE("create shared memory fail"); + return false; + } + + bool ret = ashmem->MapReadAndWriteAshmem(); + if (!ret) { + APP_LOGE("map shared memory fail"); + return false; + } + + ret = ashmem->WriteToAshmem(data, sizeof(data), 0); + if (!ret) { + APP_LOGE("write image data to shared memory fail"); + return false; + } + + ashmem->UnmapAshmem(); + + MessageParcel* messageParcel = (MessageParcel*)&parcel; + ret = messageParcel->WriteAshmem(ashmem); + + ashmem->CloseAshmem(); // close ashmem after writeAshmem because writeAshmem will dup fd + if (!ret) { + APP_LOGE("writeAshmem fail, the picture name is %{public}s", picName.c_str()); + return false; + } + + return true; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_base/src/form_provider_info.cpp b/interfaces/innerkits/appexecfwk_base/src/form_provider_info.cpp index d6b83c82a9d2ba74296b33b3f7f157e93523eec5..64773c9d5afdbb863b9ed57dddfaaaf6290691e6 100644 --- a/interfaces/innerkits/appexecfwk_base/src/form_provider_info.cpp +++ b/interfaces/innerkits/appexecfwk_base/src/form_provider_info.cpp @@ -20,6 +20,7 @@ namespace OHOS { namespace AppExecFwk { bool FormProviderInfo::ReadFromParcel(Parcel &parcel) { + formId_ = parcel.ReadInt64(); auto bindingData = parcel.ReadParcelable(); jsBindingData_ = *bindingData; return true; @@ -37,6 +38,9 @@ FormProviderInfo *FormProviderInfo::Unmarshalling(Parcel &parcel) bool FormProviderInfo::Marshalling(Parcel &parcel) const { + if (!parcel.WriteInt64(formId_)) { + return false; + } if (!parcel.WriteParcelable(&jsBindingData_)) { return false; } diff --git a/interfaces/innerkits/appexecfwk_base/src/module_usage_record.cpp b/interfaces/innerkits/appexecfwk_base/src/module_usage_record.cpp index 3ac88d068885906ffefa12f99f71cec9158986a6..369f47976ab59af6c8775c75d394d72244b0a601 100644 --- a/interfaces/innerkits/appexecfwk_base/src/module_usage_record.cpp +++ b/interfaces/innerkits/appexecfwk_base/src/module_usage_record.cpp @@ -98,4 +98,4 @@ bool ModuleUsageRecord::FromJsonString(const std::string &jsonString) return true; } } // namespace AppExecFwk -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_mgr_proxy.cpp b/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_mgr_proxy.cpp index 95724fedf293b7eb4dee9b758635233e354c1200..52b27df27bb38e05c699c197d687b38e2ac52580 100644 --- a/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_mgr_proxy.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_mgr_proxy.cpp @@ -1430,4 +1430,4 @@ bool BundleMgrProxy::SendTransactCmd(IBundleMgr::Message code, MessageParcel &da } } // namespace AppExecFwk -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_core/src/bundlemgr/launcher_service.cpp b/interfaces/innerkits/appexecfwk_core/src/bundlemgr/launcher_service.cpp index 00158f14e39c76d62955ae6ce4ed3b9143cef365..16753cb5a2898e2ca612e1e45c345175e828495d 100644 --- a/interfaces/innerkits/appexecfwk_core/src/bundlemgr/launcher_service.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/bundlemgr/launcher_service.cpp @@ -22,6 +22,7 @@ namespace OHOS { namespace AppExecFwk { + LauncherService::LauncherService() { init(); @@ -103,7 +104,7 @@ bool LauncherService::GetAbilityList( icon = appInfo.iconId; int64_t installTime = 0; - BundleFlag flags = BundleFlag::GET_BUNDLE_DEFAULT; + BundleFlag flags; flags = BundleFlag::GET_BUNDLE_WITH_ABILITIES; BundleInfo bundleInfo; if (!iBundleMgr->GetBundleInfo(bundleName, flags, bundleInfo)) { @@ -161,7 +162,7 @@ bool LauncherService::GetAbilityInfo(const Want &want, const int userId, Launche icon = appInfo.iconId; int64_t installTime = 0; - BundleFlag flags = BundleFlag::GET_BUNDLE_DEFAULT; + BundleFlag flags; flags = BundleFlag::GET_BUNDLE_WITH_ABILITIES; BundleInfo bundleInfo; if (!iBundleMgr->GetBundleInfo(bundleName, flags, bundleInfo)) { diff --git a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_host_proxy.cpp b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_host_proxy.cpp index 077a19e82ca0c0a6d5ee6bc8a3d15dbbe702aafb..c414aa53299a13264100fe6f48e1df3e29ebdfc9 100644 --- a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_host_proxy.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_host_proxy.cpp @@ -38,11 +38,8 @@ void FormHostProxy::OnAcquired(const FormJsInfo &formInfo) APP_LOGE("%{public}s, failed to write formInfo", __func__); } - error = Remote()->SendRequest( - static_cast(IFormHost::Message::FORM_HOST_ON_ACQUIRED), - data, - reply, - option); + error = Remote()->SendRequest(static_cast(IFormHost::Message::FORM_HOST_ON_ACQUIRED), data, reply, + option); if (error != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); } @@ -94,11 +91,8 @@ void FormHostProxy::OnUninstall(const std::vector &formIds) APP_LOGE("%{public}s, failed to write formIds", __func__); } - error = Remote()->SendRequest( - static_cast(IFormHost::Message::FORM_HOST_ON_UNINSTALL), - data, - reply, - option); + error = Remote()->SendRequest(static_cast(IFormHost::Message::FORM_HOST_ON_UNINSTALL), data, reply, + option); if (error != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); } @@ -112,7 +106,7 @@ int FormHostProxy::GetParcelableInfos(MessageParcel &reply, std::vector &par std::unique_ptr info(reply.ReadParcelable()); if (!info) { APP_LOGE("%{public}s, failed to read Parcelable infos", __func__); - return ERR_APPEXECFWK_PARCEL_ERROR; + return ERR_NULL_OBJECT; } parcelableInfos.emplace_back(*info); } diff --git a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_host_stub.cpp b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_host_stub.cpp index edbd2a7173465428992b41132145068ebed63c2c..ce0612183151a8386f79aa061bab8c4384dc133f 100644 --- a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_host_stub.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_host_stub.cpp @@ -12,8 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -#include "appexecfwk_errors.h" + #include "app_log_wrapper.h" #include "app_scheduler_interface.h" #include "errors.h" @@ -52,7 +51,7 @@ int FormHostStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessagePar std::u16string remoteDescriptor = data.ReadInterfaceToken(); if (descriptor != remoteDescriptor) { APP_LOGE("%{public}s failed, local descriptor is not equal to remote", __func__); - return ERR_APPEXECFWK_FORM_INVALID_PARAM; + return ERR_INVALID_STATE; } auto itFunc = memberFuncMap_.find(code); @@ -76,7 +75,7 @@ int FormHostStub::HandleAcquired(MessageParcel &data, MessageParcel &reply) std::unique_ptr formInfo(data.ReadParcelable()); if (!formInfo) { APP_LOGE("%{public}s, failed to ReadParcelable", __func__); - return ERR_APPEXECFWK_PARCEL_ERROR; + return ERR_NULL_OBJECT; } OnAcquired(*formInfo); reply.WriteInt32(ERR_OK); @@ -93,7 +92,7 @@ int FormHostStub::HandleOnUpdate(MessageParcel &data, MessageParcel &reply) std::unique_ptr formInfo(data.ReadParcelable()); if (!formInfo) { APP_LOGE("%{public}s, failed to ReadParcelable", __func__); - return ERR_APPEXECFWK_PARCEL_ERROR; + return ERR_NULL_OBJECT; } OnUpdate(*formInfo); reply.WriteInt32(ERR_OK); @@ -115,7 +114,7 @@ int FormHostStub::HandleOnUninstall(MessageParcel &data, MessageParcel &reply) reply.WriteInt32(ERR_OK); return ERR_OK; } - return ERR_APPEXECFWK_PARCEL_ERROR; + return ERR_INVALID_DATA; } } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_mgr_proxy.cpp b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_mgr_proxy.cpp index ea52dc1d756f13e2840e59ccb0368c9f596a5c3d..606a06c01288fa3b823e842906b86e563726df1d 100644 --- a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_mgr_proxy.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_mgr_proxy.cpp @@ -30,11 +30,8 @@ FormMgrProxy::FormMgrProxy(const sptr &impl) : IRemoteProxy &callerToken, - FormJsInfo &formInfo) +int FormMgrProxy::AddForm(const int64_t formId, const Want &want, const sptr &callerToken, +FormJsInfo &formInfo) { MessageParcel data; if (!WriteInterfaceToken(data)) { @@ -86,14 +83,11 @@ int FormMgrProxy::DeleteForm(const int64_t formId, const sptr &ca } MessageParcel reply; MessageOption option; - int error = Remote()->SendRequest( - static_cast(IFormMgr::Message::FORM_MGR_DELETE_FORM), - data, - reply, - option); + int error = Remote()->SendRequest(static_cast(IFormMgr::Message::FORM_MGR_DELETE_FORM), data, reply, + option); if (error != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); - return ERR_APPEXECFWK_FORM_SEND_FMS_MSG; + return error; } return reply.ReadInt32(); } @@ -127,14 +121,11 @@ int FormMgrProxy::ReleaseForm(const int64_t formId, const sptr &c MessageParcel reply; MessageOption option; - int error = Remote()->SendRequest( - static_cast(IFormMgr::Message::FORM_MGR_RELEASE_FORM), - data, - reply, - option); + int error = Remote()->SendRequest(static_cast(IFormMgr::Message::FORM_MGR_RELEASE_FORM), data, reply, + option); if (error != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); - return ERR_APPEXECFWK_FORM_SEND_FMS_MSG; + return error; } return reply.ReadInt32(); } @@ -146,10 +137,8 @@ int FormMgrProxy::ReleaseForm(const int64_t formId, const sptr &c * @param FormProviderData Form binding data. * @return Returns ERR_OK on success, others on failure. */ -int FormMgrProxy::UpdateForm( - const int64_t formId, - const std::string &bundleName, - const FormProviderData &FormProviderData) +int FormMgrProxy::UpdateForm(const int64_t formId, const std::string &bundleName, +const FormProviderData &FormProviderData) { MessageParcel data; if (!WriteInterfaceToken(data)) { @@ -171,14 +160,11 @@ int FormMgrProxy::UpdateForm( } MessageParcel reply; MessageOption option; - int error = Remote()->SendRequest( - static_cast(IFormMgr::Message::FORM_MGR_UPDATE_FORM), - data, - reply, - option); + int error = Remote()->SendRequest(static_cast(IFormMgr::Message::FORM_MGR_UPDATE_FORM), data, reply, + option); if (error != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); - return ERR_APPEXECFWK_FORM_SEND_FMS_MSG; + return error; } return reply.ReadInt32(); } @@ -208,14 +194,11 @@ int FormMgrProxy::SetNextRefreshTime(const int64_t formId, const int64_t nextTim return ERR_APPEXECFWK_PARCEL_ERROR; } MessageOption option; - int error = Remote()->SendRequest( - static_cast(IFormMgr::Message::FORM_MGR_SET_NEXT_REFRESH_TIME), - data, - reply, - option); + int error = Remote()->SendRequest(static_cast(IFormMgr::Message::FORM_MGR_SET_NEXT_REFRESH_TIME), data, + reply, option); if (error != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); - return ERR_APPEXECFWK_FORM_SEND_FMS_MSG; + return error; } return reply.ReadInt32(); } @@ -226,10 +209,8 @@ int FormMgrProxy::SetNextRefreshTime(const int64_t formId, const int64_t nextTim * @param updateType update type. * @return Returns ERR_OK on success, others on failure. */ -int FormMgrProxy::LifecycleUpdate( - const std::vector &formIds, - const sptr &callerToken, - const int32_t updateType) +int FormMgrProxy::LifecycleUpdate(const std::vector &formIds, const sptr &callerToken, +const int32_t updateType) { MessageParcel data; MessageParcel reply; @@ -251,14 +232,11 @@ int FormMgrProxy::LifecycleUpdate( return ERR_APPEXECFWK_PARCEL_ERROR; } MessageOption option; - int error = Remote()->SendRequest( - static_cast(IFormMgr::Message::FORM_MGR_LIFECYCLE_UPDATE), - data, - reply, - option); + int error = Remote()->SendRequest(static_cast(IFormMgr::Message::FORM_MGR_LIFECYCLE_UPDATE), + data, reply, option); if (error != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); - return ERR_APPEXECFWK_FORM_SEND_FMS_MSG; + return error; } return reply.ReadInt32(); @@ -294,14 +272,11 @@ int FormMgrProxy::RequestForm(const int64_t formId, const sptr &c MessageParcel reply; MessageOption option; - int error = Remote()->SendRequest( - static_cast(IFormMgr::Message::FORM_MGR_REQUEST_FORM), - data, - reply, - option); + int error = Remote()->SendRequest(static_cast(IFormMgr::Message::FORM_MGR_REQUEST_FORM), + data, reply, option); if (error != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); - return ERR_APPEXECFWK_FORM_SEND_FMS_MSG; + return error; } return reply.ReadInt32(); } @@ -313,10 +288,8 @@ int FormMgrProxy::RequestForm(const int64_t formId, const sptr &c * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. * @return Returns ERR_OK on success, others on failure. */ -int FormMgrProxy::NotifyWhetherVisibleForms( - const std::vector &formIds, - const sptr &callerToken, - const int32_t formVisibleType) +int FormMgrProxy::NotifyWhetherVisibleForms(const std::vector &formIds, +const sptr &callerToken, const int32_t formVisibleType) { MessageParcel data; if (!WriteInterfaceToken(data)) { @@ -341,14 +314,11 @@ int FormMgrProxy::NotifyWhetherVisibleForms( MessageParcel reply; MessageOption option; - int error = Remote()->SendRequest( - static_cast(IFormMgr::Message::FORM_MGR_NOTIFY_FORM_WHETHER_VISIBLE), - data, - reply, - option); + int error = Remote()->SendRequest(static_cast(IFormMgr::Message::FORM_MGR_NOTIFY_FORM_WHETHER_VISIBLE), + data, reply, option); if (error != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); - return ERR_APPEXECFWK_FORM_SEND_FMS_MSG; + return error; } return reply.ReadInt32(); } @@ -377,15 +347,11 @@ int FormMgrProxy::CastTempForm(const int64_t formId, const sptr & MessageParcel reply; MessageOption option; - int error = Remote()->SendRequest( - static_cast( - IFormMgr::Message::FORM_MGR_CAST_TEMP_FORM), - data, - reply, - option); + int error = Remote()->SendRequest(static_cast(IFormMgr::Message::FORM_MGR_CAST_TEMP_FORM), + data, reply, option); if (error != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); - return ERR_APPEXECFWK_FORM_SEND_FMS_MSG; + return error; } return reply.ReadInt32(); } @@ -490,14 +456,11 @@ int FormMgrProxy::MessageEvent(const int64_t formId, const Want &want, const spt MessageParcel reply; MessageOption option; - int error = Remote()->SendRequest( - static_cast(IFormMgr::Message::FORM_MGR_MESSAGE_EVENT), - data, - reply, - option); + int error = Remote()->SendRequest(static_cast(IFormMgr::Message::FORM_MGR_MESSAGE_EVENT), data, + reply, option); if (error != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); - return ERR_APPEXECFWK_FORM_SEND_FMS_MSG; + return error; } return reply.ReadInt32(); } @@ -510,7 +473,7 @@ int FormMgrProxy::GetParcelableInfos(MessageParcel &reply, std::vector &parc std::unique_ptr info(reply.ReadParcelable()); if (!info) { APP_LOGE("%{public}s, failed to Read Parcelable infos", __func__); - return ERR_APPEXECFWK_PARCEL_ERROR; + return ERR_NULL_OBJECT; } parcelableInfos.emplace_back(*info); } @@ -546,7 +509,7 @@ int FormMgrProxy::GetStringInfo(IFormMgr::Message code, MessageParcel &data, std } if (stringInfoList.empty()) { APP_LOGI("%{public}s, No string info", __func__); - return ERR_APPEXECFWK_FORM_COMMON_CODE; + return ERR_APPEXECFWK_FORM_INFO_NOT_EXIST; } for (auto &info : stringInfoList) { stringInfo += info; @@ -591,7 +554,7 @@ int FormMgrProxy::SendTransactCmd(IFormMgr::Message code, MessageParcel &data, M int32_t result = remote->SendRequest(static_cast(code), data, reply, option); if (result != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d, cmd: %{public}d", __func__, result, code); - return ERR_APPEXECFWK_FORM_SEND_FMS_MSG; + return result; } return ERR_OK; } diff --git a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_mgr_stub.cpp b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_mgr_stub.cpp index 42c11f891676683a566f69fb89c235ec015955ff..ce4f6173ab07a17d413b433bb16c04ec7eeb05ce 100644 --- a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_mgr_stub.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_mgr_stub.cpp @@ -86,7 +86,7 @@ int FormMgrStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParc std::u16string remoteDescriptor = data.ReadInterfaceToken(); if (descriptor != remoteDescriptor) { APP_LOGE("%{public}s failed, local descriptor is not equal to remote", __func__); - return ERR_APPEXECFWK_FORM_INVALID_PARAM; + return ERR_INVALID_STATE; } auto itFunc = memberFuncMap_.find(code); @@ -116,7 +116,7 @@ int32_t FormMgrStub::HandleAddForm(MessageParcel &data, MessageParcel &reply) sptr client = data.ReadParcelable(); if (client == nullptr) { APP_LOGE("%{public}s, failed to RemoteObject invalidate", __func__); - return ERR_APPEXECFWK_PARCEL_ERROR; + return ERR_APPEXECFWK_SERVICE_NOT_CONNECTED; } FormJsInfo formInfo; @@ -137,7 +137,7 @@ int32_t FormMgrStub::HandleDeleteForm(MessageParcel &data, MessageParcel &reply) int64_t formId = data.ReadInt64(); sptr client = data.ReadParcelable(); if (client == nullptr) { - return ERR_APPEXECFWK_PARCEL_ERROR; + return ERR_APPEXECFWK_SERVICE_NOT_CONNECTED; } int32_t result = DeleteForm(formId, client); reply.WriteInt32(result); @@ -154,7 +154,7 @@ int32_t FormMgrStub::HandleReleaseForm(MessageParcel &data, MessageParcel &reply int64_t formId = data.ReadInt64(); sptr client = data.ReadParcelable(); if (client == nullptr) { - return ERR_APPEXECFWK_PARCEL_ERROR; + return ERR_APPEXECFWK_SERVICE_NOT_CONNECTED; } bool delCache = data.ReadBool(); @@ -207,7 +207,7 @@ int32_t FormMgrStub::HandleLifecycleUpdate(MessageParcel &data, MessageParcel &r sptr client = data.ReadParcelable(); if (client == nullptr) { APP_LOGE("%{public}s, failed to ReadParcelable", __func__); - return ERR_APPEXECFWK_PARCEL_ERROR; + return ERR_APPEXECFWK_SERVICE_NOT_CONNECTED; } int32_t updateType = data.ReadInt32(); int32_t result = LifecycleUpdate(formIds, client, updateType); @@ -229,7 +229,7 @@ int32_t FormMgrStub::HandleRequestForm(MessageParcel &data, MessageParcel &reply sptr client = data.ReadParcelable(); if (client == nullptr) { APP_LOGE("%{public}s, failed to ReadParcelable", __func__); - return ERR_APPEXECFWK_PARCEL_ERROR; + return ERR_APPEXECFWK_SERVICE_NOT_CONNECTED; } std::unique_ptr want(data.ReadParcelable()); @@ -258,7 +258,7 @@ int32_t FormMgrStub::HandleNotifyWhetherVisibleForms(MessageParcel &data, Messag sptr client = data.ReadParcelable(); if (client == nullptr) { - return ERR_APPEXECFWK_PARCEL_ERROR; + return ERR_APPEXECFWK_SERVICE_NOT_CONNECTED; } int32_t formVisibleType = data.ReadInt32(); @@ -278,7 +278,7 @@ int32_t FormMgrStub::HandleCastTempForm(MessageParcel &data, MessageParcel &repl int64_t formId = data.ReadInt64(); sptr client = data.ReadParcelable(); if (client == nullptr) { - return ERR_APPEXECFWK_PARCEL_ERROR; + return ERR_APPEXECFWK_SERVICE_NOT_CONNECTED; } int32_t result = CastTempForm(formId, client); @@ -374,7 +374,7 @@ int32_t FormMgrStub::HandleMessageEvent(MessageParcel &data, MessageParcel &repl sptr client = data.ReadParcelable(); if (client == nullptr) { APP_LOGE("%{public}s, failed to ReadParcelable", __func__); - return ERR_APPEXECFWK_PARCEL_ERROR; + return ERR_APPEXECFWK_SERVICE_NOT_CONNECTED; } int32_t result = MessageEvent(formId, *want, client); diff --git a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_provider_proxy.cpp b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_provider_proxy.cpp index 67b77fff067433432ada5054d586cf6a57ff6e9c..9d94e233bc9324f79c319aeef1d9ff49d0a407a2 100644 --- a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_provider_proxy.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_provider_proxy.cpp @@ -25,10 +25,8 @@ namespace AppExecFwk { * @param callerToken Caller ability token. * @return Returns ERR_OK on success, others on failure. */ -int FormProviderProxy::AcquireProviderFormInfo( - const int64_t formId, - const Want &want, - const sptr &callerToken) +int FormProviderProxy::AcquireProviderFormInfo(const int64_t formId, const Want &want, +const sptr &callerToken) { int error; MessageParcel data; @@ -53,11 +51,8 @@ int FormProviderProxy::AcquireProviderFormInfo( return ERR_APPEXECFWK_PARCEL_ERROR; } - error = Remote()->SendRequest( - static_cast(IFormProvider::Message::FORM_ACQUIRE_PROVIDER_FORM_INFO), - data, - reply, - option); + error = Remote()->SendRequest(static_cast(IFormProvider::Message::FORM_ACQUIRE_PROVIDER_FORM_INFO), + data, reply, option); if (error != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); return error; @@ -96,11 +91,8 @@ int FormProviderProxy::NotifyFormDelete(const int64_t formId, const Want &want, return ERR_APPEXECFWK_PARCEL_ERROR; } - error = Remote()->SendRequest( - static_cast(IFormProvider::Message::FORM_PROVIDER_NOTIFY_FORM_DELETE), - data, - reply, - option); + error = Remote()->SendRequest(static_cast(IFormProvider::Message::FORM_PROVIDER_NOTIFY_FORM_DELETE), + data, reply, option); if (error != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); return error; @@ -114,10 +106,8 @@ int FormProviderProxy::NotifyFormDelete(const int64_t formId, const Want &want, * @param callerToken Caller ability token. * @return Returns ERR_OK on success, others on failure. */ -int FormProviderProxy::NotifyFormsDelete( - const std::vector &formIds, - const Want &want, - const sptr &callerToken) +int FormProviderProxy::NotifyFormsDelete(const std::vector &formIds, const Want &want, +const sptr &callerToken) { int error; MessageParcel data; @@ -141,11 +131,8 @@ int FormProviderProxy::NotifyFormsDelete( return ERR_APPEXECFWK_PARCEL_ERROR; } - error = Remote()->SendRequest( - static_cast(IFormProvider::Message::FORM_PROVIDER_NOTIFY_FORMS_DELETE), - data, - reply, - option); + error = Remote()->SendRequest(static_cast(IFormProvider::Message::FORM_PROVIDER_NOTIFY_FORMS_DELETE), + data, reply, option); if (error != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); return error; @@ -186,11 +173,8 @@ int FormProviderProxy::NotifyFormUpdate(const int64_t formId, const Want &want, return ERR_APPEXECFWK_PARCEL_ERROR; } - error = Remote()->SendRequest( - static_cast(IFormProvider::Message::FORM_PROVIDER_NOTIFY_FORM_UPDATE), - data, - reply, - option); + error = Remote()->SendRequest(static_cast(IFormProvider::Message::FORM_PROVIDER_NOTIFY_FORM_UPDATE), + data, reply, option); if (error != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); return error; @@ -240,11 +224,8 @@ int FormProviderProxy::EventNotify(const std::vector &formIds, const in return ERR_APPEXECFWK_PARCEL_ERROR; } - error = Remote()->SendRequest( - static_cast(IFormProvider::Message::FORM_PROVIDER_EVENT_NOTIFY), - data, - reply, - option); + error = Remote()->SendRequest(static_cast(IFormProvider::Message::FORM_PROVIDER_EVENT_NOTIFY), + data, reply, option); if (error != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); return error; @@ -259,10 +240,8 @@ int FormProviderProxy::EventNotify(const std::vector &formIds, const in * @param callerToken Caller ability token. * @return Returns ERR_OK on success, others on failure. */ -int FormProviderProxy::NotifyFormCastTempForm( - const int64_t formId, - const Want &want, - const sptr &callerToken) +int FormProviderProxy::NotifyFormCastTempForm(const int64_t formId, const Want &want, +const sptr &callerToken) { int error; MessageParcel data; @@ -274,7 +253,7 @@ int FormProviderProxy::NotifyFormCastTempForm( return ERR_APPEXECFWK_PARCEL_ERROR; } - if (!data.WriteInt64(formId)) { + if (!data. WriteInt64(formId)) { APP_LOGE("%{public}s, failed to write formId", __func__); return ERR_APPEXECFWK_PARCEL_ERROR; } @@ -287,11 +266,8 @@ int FormProviderProxy::NotifyFormCastTempForm( return ERR_APPEXECFWK_PARCEL_ERROR; } - error = Remote()->SendRequest( - static_cast(IFormProvider::Message::FORM_PROVIDER_NOTIFY_TEMP_FORM_CAST), - data, - reply, - option); + error = Remote()->SendRequest(static_cast(IFormProvider::Message::FORM_PROVIDER_NOTIFY_TEMP_FORM_CAST), + data, reply, option); if (error != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); return error; @@ -307,11 +283,8 @@ int FormProviderProxy::NotifyFormCastTempForm( * @param callerToken Form provider proxy object. * @return Returns ERR_OK on success, others on failure. */ -int FormProviderProxy::FireFormEvent( - const int64_t formId, - const std::string &message, - const Want &want, - const sptr &callerToken) +int FormProviderProxy::FireFormEvent(const int64_t formId, const std::string &message, const Want &want, +const sptr &callerToken) { MessageParcel data; if (!WriteInterfaceToken(data)) { @@ -336,11 +309,8 @@ int FormProviderProxy::FireFormEvent( } MessageParcel reply; MessageOption option; - int error = Remote()->SendRequest( - static_cast(IFormProvider::Message::FORM_PROVIDER_NOTIFY_FORM_DELETE), - data, - reply, - option); + int error = Remote()->SendRequest(static_cast(IFormProvider::Message::FORM_PROVIDER_NOTIFY_FORM_DELETE), + data, reply, option); if (error != ERR_OK) { APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); return error; diff --git a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_provider_stub.cpp b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_provider_stub.cpp index 5577337a202d69592a35af0edd4a58b5a30d6ebb..95203261c7fe4f7510dcd25ce32564438b20e9ea 100644 --- a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_provider_stub.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_provider_stub.cpp @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "appexecfwk_errors.h" + #include "app_log_wrapper.h" #include "app_scheduler_interface.h" #include "errors.h" @@ -59,7 +59,7 @@ int FormProviderStub::OnRemoteRequest(uint32_t code, MessageParcel &data, Messag std::u16string remoteDescriptor = data.ReadInterfaceToken(); if (descriptor != remoteDescriptor) { APP_LOGE("%{public}s failed, local descriptor is not equal to remote", __func__); - return ERR_APPEXECFWK_FORM_INVALID_PARAM; + return ERR_INVALID_STATE; } auto itFunc = memberFuncMap_.find(code); @@ -84,13 +84,13 @@ int FormProviderStub::HandleAcquireProviderFormInfo(MessageParcel &data, Message std::unique_ptr want(data.ReadParcelable()); if (!want) { APP_LOGE("%{public}s, failed to ReadParcelable", __func__); - return ERR_APPEXECFWK_PARCEL_ERROR; + return ERR_NULL_OBJECT; } sptr client = data.ReadParcelable(); if (client == nullptr) { APP_LOGE("%{public}s, failed to ReadParcelable", __func__); - return ERR_APPEXECFWK_PARCEL_ERROR; + return ERR_NULL_OBJECT; } int32_t result = AcquireProviderFormInfo(formId, *want, client); @@ -109,13 +109,13 @@ int FormProviderStub::HandleNotifyFormDelete(MessageParcel &data, MessageParcel std::unique_ptr want(data.ReadParcelable()); if (!want) { APP_LOGE("%{public}s fail, ReadParcelable failed", __func__); - return ERR_APPEXECFWK_PARCEL_ERROR; + return ERR_NULL_OBJECT; } sptr client = data.ReadParcelable(); if (client == nullptr) { APP_LOGE("%{public}s, failed to ReadParcelable", __func__); - return ERR_APPEXECFWK_PARCEL_ERROR; + return ERR_NULL_OBJECT; } int32_t result = NotifyFormDelete(formId, *want, client); @@ -136,13 +136,13 @@ int FormProviderStub::HandleNotifyFormsDelete(MessageParcel &data, MessageParcel std::unique_ptr want(data.ReadParcelable()); if (!want) { APP_LOGE("%{public}s fail, ReadParcelable failed", __func__); - return ERR_APPEXECFWK_PARCEL_ERROR; + return ERR_NULL_OBJECT; } sptr client = data.ReadParcelable(); if (client == nullptr) { APP_LOGE("%{public}s, failed to ReadParcelable", __func__); - return ERR_APPEXECFWK_PARCEL_ERROR; + return ERR_NULL_OBJECT; } int32_t result = NotifyFormsDelete(formIds, *want, client); @@ -165,13 +165,13 @@ int FormProviderStub::HandleNotifyFormUpdate(MessageParcel &data, MessageParcel std::unique_ptr want(data.ReadParcelable()); if (!want) { APP_LOGE("%{public}s, failed to ReadParcelable", __func__); - return ERR_APPEXECFWK_PARCEL_ERROR; + return ERR_NULL_OBJECT; } sptr client = data.ReadParcelable(); if (client == nullptr) { APP_LOGE("%{public}s, failed to ReadParcelable", __func__); - return ERR_APPEXECFWK_PARCEL_ERROR; + return ERR_NULL_OBJECT; } int32_t result = NotifyFormUpdate(formId, *want, client); @@ -195,13 +195,13 @@ int FormProviderStub::HandleEventNotify(MessageParcel &data, MessageParcel &repl std::unique_ptr want(data.ReadParcelable()); if (!want) { APP_LOGE("%{public}s, failed to ReadParcelable", __func__); - return ERR_APPEXECFWK_PARCEL_ERROR; + return ERR_NULL_OBJECT; } sptr client = data.ReadParcelable(); if (client == nullptr) { APP_LOGE("%{public}s, failed to ReadParcelable", __func__); - return ERR_APPEXECFWK_PARCEL_ERROR; + return ERR_NULL_OBJECT; } int32_t result = EventNotify(formIds, formVisibleType, *want, client); @@ -225,13 +225,13 @@ int FormProviderStub::HandleNotifyFormCastTempForm(MessageParcel &data, MessageP std::unique_ptr want(data.ReadParcelable()); if (!want) { APP_LOGE("%{public}s fail, ReadParcelable failed", __func__); - return ERR_APPEXECFWK_PARCEL_ERROR; + return ERR_NULL_OBJECT; } sptr client = data.ReadParcelable(); if (client == nullptr) { APP_LOGE("%{public}s, failed to ReadParcelable", __func__); - return ERR_APPEXECFWK_PARCEL_ERROR; + return ERR_NULL_OBJECT; } int32_t result = NotifyFormCastTempForm(formId, *want, client); @@ -251,13 +251,13 @@ int FormProviderStub::HandleFireFormEvent(MessageParcel &data, MessageParcel &re std::unique_ptr want(data.ReadParcelable()); if (!want) { APP_LOGE("%{public}s fail, ReadParcelable failed", __func__); - return ERR_APPEXECFWK_PARCEL_ERROR; + return ERR_NULL_OBJECT; } sptr client = data.ReadParcelable(); if (client == nullptr) { APP_LOGE("%{public}s, failed to ReadParcelable", __func__); - return ERR_APPEXECFWK_PARCEL_ERROR; + return ERR_NULL_OBJECT; } int32_t result = FireFormEvent(formId, message, *want, client); diff --git a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_supply_proxy.cpp b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_supply_proxy.cpp index ced74caec8cb146472a1cb80d43907ffb1c77d4e..190f65c5351d88eb2bb2419816eda8009ecf34b2 100644 --- a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_supply_proxy.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_supply_proxy.cpp @@ -1,119 +1,113 @@ -/* - * 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 "appexecfwk_errors.h" -#include "form_constants.h" -#include "form_supply_proxy.h" -#include "string_ex.h" - -namespace OHOS { -namespace AppExecFwk { -/** - * @brief Send form binding data from form provider to fms. - * @param providerFormInfo Form binding data. - * @param want input data. - * @return Returns ERR_OK on success, others on failure. - */ -int FormSupplyProxy::OnAcquire(const FormProviderInfo &formInfo, const Want& want) -{ - MessageParcel data; - if (!WriteInterfaceToken(data)) { - APP_LOGE("%{public}s, failed to WriteInterfaceToken", __func__); - return ERR_APPEXECFWK_PARCEL_ERROR; - } - if (!data.WriteParcelable(&want)) { - APP_LOGE("%{public}s, failed to write want", __func__); - return ERR_APPEXECFWK_PARCEL_ERROR; - } - - if (want.GetIntParam(Constants::PROVIDER_FLAG, ERR_OK) == ERR_OK) { - if (!data.WriteParcelable(&formInfo)) { - APP_LOGE("%{public}s, failed to write formInfo", __func__); - return ERR_APPEXECFWK_PARCEL_ERROR; - } - } - - MessageParcel reply; - MessageOption option; - int error = Remote()->SendRequest( - static_cast(IFormSupply::Message::TRANSACTION_FORM_ACQUIRED), - data, - reply, - option); - if (error != ERR_OK) { - APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); - } - return error; -} - - -/** - * @brief Send other event to fms. - * @param want input data. - * @return Returns ERR_OK on success, others on failure. - */ -int FormSupplyProxy::OnEventHandle(const Want& want) -{ - MessageParcel data; - - if (!WriteInterfaceToken(data)) { - APP_LOGE("%{public}s, failed to write interface token", __func__); - return ERR_APPEXECFWK_PARCEL_ERROR; - } - - if (!data.WriteParcelable(&want)) { - APP_LOGE("%{public}s, failed to write want", __func__); - return ERR_APPEXECFWK_PARCEL_ERROR; - } - - MessageParcel reply; - MessageOption option; - int error = Remote()->SendRequest( - static_cast(IFormSupply::Message::TRANSACTION_EVENT_HANDLE), - data, - reply, - option); - if (error != ERR_OK) { - APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); - } - return error; -} - -template -int FormSupplyProxy::GetParcelableInfos(MessageParcel &reply, std::vector &parcelableInfos) -{ - int32_t infoSize = reply.ReadInt32(); - for (int32_t i = 0; i < infoSize; i++) { - std::unique_ptr info(reply.ReadParcelable()); - if (!info) { - APP_LOGE("%{public}s, failed to ReadParcelable", __func__); - return ERR_INVALID_VALUE; - } - parcelableInfos.emplace_back(*info); - } - APP_LOGI("get parcelable infos success"); - return ERR_OK; -} - -bool FormSupplyProxy::WriteInterfaceToken(MessageParcel &data) -{ - if (!data.WriteInterfaceToken(FormSupplyProxy::GetDescriptor())) { - APP_LOGE("%{public}s, failed to write interface token failed", __func__); - return false; - } - return true; -} -} // namespace AppExecFwk -} // namespace OHOS +/* + * 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 "appexecfwk_errors.h" +#include "form_constants.h" +#include "form_supply_proxy.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @brief Send form binding data from form provider to fms. + * @param providerFormInfo Form binding data. + * @param want input data. + * @return Returns ERR_OK on success, others on failure. + */ +int FormSupplyProxy::OnAcquire(const FormProviderInfo &formInfo, const Want& want) +{ + MessageParcel data; + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to WriteInterfaceToken", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(&want)) { + APP_LOGE("%{public}s, failed to write want", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (want.GetIntParam(Constants::PROVIDER_FLAG, ERR_OK) == ERR_OK) { + if (!data.WriteParcelable(&formInfo)) { + APP_LOGE("%{public}s, failed to write formInfo", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + } + + MessageParcel reply; + MessageOption option; + int error = Remote()->SendRequest(static_cast(IFormSupply::Message::TRANSACTION_FORM_ACQUIRED), + data, reply, option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + } + return error; +} + + +/** + * @brief Send other event to fms. + * @param want input data. + * @return Returns ERR_OK on success, others on failure. + */ +int FormSupplyProxy::OnEventHandle(const Want& want) +{ + MessageParcel data; + + if (!WriteInterfaceToken(data)) { + APP_LOGE("%{public}s, failed to write interface token", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + if (!data.WriteParcelable(&want)) { + APP_LOGE("%{public}s, failed to write want", __func__); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + MessageParcel reply; + MessageOption option; + int error = Remote()->SendRequest(static_cast(IFormSupply::Message::TRANSACTION_EVENT_HANDLE), + data, reply, option); + if (error != ERR_OK) { + APP_LOGE("%{public}s, failed to SendRequest: %{public}d", __func__, error); + } + return error; +} + +template +int FormSupplyProxy::GetParcelableInfos(MessageParcel &reply, std::vector &parcelableInfos) +{ + int32_t infoSize = reply.ReadInt32(); + for (int32_t i = 0; i < infoSize; i++) { + std::unique_ptr info(reply.ReadParcelable()); + if (!info) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + return ERR_INVALID_VALUE; + } + parcelableInfos.emplace_back(*info); + } + APP_LOGI("get parcelable infos success"); + return ERR_OK; +} + +bool FormSupplyProxy::WriteInterfaceToken(MessageParcel &data) +{ + if (!data.WriteInterfaceToken(FormSupplyProxy::GetDescriptor())) { + APP_LOGE("%{public}s, failed to write interface token failed", __func__); + return false; + } + return true; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_supply_stub.cpp b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_supply_stub.cpp index 0e6ba42ce5f02d3a57456534e76d3faa869455d0..89061b1607048824fe3b7401a4e03a3450b72ed1 100644 --- a/interfaces/innerkits/appexecfwk_core/src/formmgr/form_supply_stub.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/form_supply_stub.cpp @@ -1,124 +1,124 @@ -/* - * 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 "appexecfwk_errors.h" -#include "app_log_wrapper.h" -#include "form_constants.h" -#include "form_supply_stub.h" -#include "ipc_skeleton.h" -#include "ipc_types.h" -#include "iremote_object.h" - -namespace OHOS { -namespace AppExecFwk { -FormSupplyStub::FormSupplyStub() -{ - memberFuncMap_[static_cast(IFormSupply::Message::TRANSACTION_FORM_ACQUIRED)] = - &FormSupplyStub::HandleOnAcquire; - memberFuncMap_[static_cast(IFormSupply::Message::TRANSACTION_EVENT_HANDLE)] = - &FormSupplyStub::HandleOnEventHandle; -} - -FormSupplyStub::~FormSupplyStub() -{ - memberFuncMap_.clear(); -} -/** - * @brief handle remote request. - * @param data input param. - * @param reply output param. - * @param option message option. - * @return Returns ERR_OK on success, others on failure. - */ -int FormSupplyStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) -{ - APP_LOGI("FormSupplyStub::OnReceived, code = %{public}d, flags= %{public}d.", code, option.GetFlags()); - std::u16string descriptor = FormSupplyStub::GetDescriptor(); - std::u16string remoteDescriptor = data.ReadInterfaceToken(); - if (descriptor != remoteDescriptor) { - APP_LOGE("%{public}s failed, local descriptor is not equal to remote", __func__); - return ERR_APPEXECFWK_FORM_INVALID_PARAM; - } - - auto itFunc = memberFuncMap_.find(code); - if (itFunc != memberFuncMap_.end()) { - auto memberFunc = itFunc->second; - if (memberFunc != nullptr) { - return (this->*memberFunc)(data, reply); - } - } - - return IPCObjectStub::OnRemoteRequest(code, data, reply, option); -} -/** - * @brief handle OnAcquire message. - * @param data input param. - * @param reply output param. - * @return Returns ERR_OK on success, others on failure. - */ -int FormSupplyStub::HandleOnAcquire(MessageParcel &data, MessageParcel &reply) -{ - std::unique_ptr want(data.ReadParcelable()); - if (!want) { - APP_LOGE("%{public}s, failed to ReadParcelable", __func__); - reply.WriteInt32(ERR_APPEXECFWK_PARCEL_ERROR); - return ERR_APPEXECFWK_PARCEL_ERROR; - } - - int errCode = ERR_OK; - do { - errCode = want->GetIntParam(Constants::PROVIDER_FLAG, ERR_OK); - if (errCode != ERR_OK) { - APP_LOGE("%{public}s, provider error", __func__); - break; - } - std::unique_ptr formInfo(data.ReadParcelable()); - if (formInfo == nullptr) { - APP_LOGE("%{public}s, failed to ReadParcelable", __func__); - errCode = ERR_APPEXECFWK_PARCEL_ERROR; - break; - } - int32_t result = OnAcquire(*formInfo, *want); - reply.WriteInt32(result); - return result; - } while (true); - - FormProviderInfo formProviderInfo; - want->SetParam(Constants::PROVIDER_FLAG, errCode); - OnAcquire(formProviderInfo, *want); - reply.WriteInt32(errCode); - return errCode; -} -/** - * @brief handle OnEventHandle message. - * @param data input param. - * @param reply output param. - * @return Returns ERR_OK on success, others on failure. - */ -int FormSupplyStub::HandleOnEventHandle(MessageParcel &data, MessageParcel &reply) -{ - std::unique_ptr want(data.ReadParcelable()); - if (!want) { - APP_LOGE("%{public}s, failed to ReadParcelable", __func__); - reply.WriteInt32(ERR_APPEXECFWK_PARCEL_ERROR); - return ERR_APPEXECFWK_PARCEL_ERROR; - } - - int32_t result = OnEventHandle(*want); - reply.WriteInt32(result); - return result; -} -} // namespace AppExecFwk +/* + * 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_constants.h" +#include "form_supply_stub.h" +#include "ipc_skeleton.h" +#include "ipc_types.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +FormSupplyStub::FormSupplyStub() +{ + memberFuncMap_[static_cast(IFormSupply::Message::TRANSACTION_FORM_ACQUIRED)] = + &FormSupplyStub::HandleOnAcquire; + memberFuncMap_[static_cast(IFormSupply::Message::TRANSACTION_EVENT_HANDLE)] = + &FormSupplyStub::HandleOnEventHandle; +} + +FormSupplyStub::~FormSupplyStub() +{ + memberFuncMap_.clear(); +} +/** + * @brief handle remote request. + * @param data input param. + * @param reply output param. + * @param option message option. + * @return Returns ERR_OK on success, others on failure. + */ +int FormSupplyStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + APP_LOGI("FormSupplyStub::OnReceived, code = %{public}d, flags= %{public}d.", code, option.GetFlags()); + std::u16string descriptor = FormSupplyStub::GetDescriptor(); + std::u16string remoteDescriptor = data.ReadInterfaceToken(); + if (descriptor != remoteDescriptor) { + APP_LOGE("%{public}s failed, local descriptor is not equal to remote", __func__); + return ERR_INVALID_STATE; + } + + auto itFunc = memberFuncMap_.find(code); + if (itFunc != memberFuncMap_.end()) { + auto memberFunc = itFunc->second; + if (memberFunc != nullptr) { + return (this->*memberFunc)(data, reply); + } + } + + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); +} +/** + * @brief handle OnAcquire message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int FormSupplyStub::HandleOnAcquire(MessageParcel &data, MessageParcel &reply) +{ + std::unique_ptr want(data.ReadParcelable()); + if (!want) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + reply.WriteInt32(ERR_INVALID_VALUE); + return ERR_INVALID_VALUE; + } + + int errCode = ERR_OK; + do { + errCode = want->GetIntParam(Constants::PROVIDER_FLAG, ERR_OK); + if (errCode != ERR_OK) { + APP_LOGE("%{public}s, provider error", __func__); + break; + } + std::unique_ptr formInfo(data.ReadParcelable()); + if (formInfo == nullptr) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + errCode = ERR_INVALID_VALUE; + break; + } + int32_t result = OnAcquire(*formInfo, *want); + reply.WriteInt32(result); + return result; + } while (true); + + FormProviderInfo formProviderInfo; + want->SetParam(Constants::PROVIDER_FLAG, errCode); + OnAcquire(formProviderInfo, *want); + reply.WriteInt32(errCode); + return errCode; +} +/** + * @brief handle OnEventHandle message. + * @param data input param. + * @param reply output param. + * @return Returns ERR_OK on success, others on failure. + */ +int FormSupplyStub::HandleOnEventHandle(MessageParcel &data, MessageParcel &reply) +{ + std::unique_ptr want(data.ReadParcelable()); + if (!want) { + APP_LOGE("%{public}s, failed to ReadParcelable", __func__); + reply.WriteInt32(ERR_INVALID_VALUE); + return ERR_INVALID_VALUE; + } + + int32_t result = OnEventHandle(*want); + reply.WriteInt32(result); + return result; +} +} // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/appexecfwk_core/src/formmgr/provider_connect_proxy.cpp b/interfaces/innerkits/appexecfwk_core/src/formmgr/provider_connect_proxy.cpp index eb433ebd4e68dce02e0bff470c13de67cb007f72..e966e7b0956e7bbb059b426619d100662773f100 100644 --- a/interfaces/innerkits/appexecfwk_core/src/formmgr/provider_connect_proxy.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/provider_connect_proxy.cpp @@ -30,8 +30,7 @@ namespace AppExecFwk { void ProviderConnectProxy::OnAbilityConnectDone( const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) { - APP_LOGD("%{public}s, abilityName:%{public}s,resultCode:%{public}d", - __func__, element.GetAbilityName().c_str(), resultCode); + APP_LOGD("%{public}s, abilityName:%{public}s,resultCode:%{public}d", __func__, element.GetAbilityName().c_str(), resultCode); int error; MessageParcel data; MessageParcel reply; diff --git a/interfaces/innerkits/appexecfwk_core/src/formmgr/provider_connect_stub.cpp b/interfaces/innerkits/appexecfwk_core/src/formmgr/provider_connect_stub.cpp index cee0890826f015e1247914e34c59aa5f6773395a..54323fdac89f43458456d34608c438637a6034c5 100644 --- a/interfaces/innerkits/appexecfwk_core/src/formmgr/provider_connect_stub.cpp +++ b/interfaces/innerkits/appexecfwk_core/src/formmgr/provider_connect_stub.cpp @@ -14,7 +14,7 @@ * limitations under the License. */ -#include "appexecfwk_errors.h" + #include "app_log_wrapper.h" #include "ipc_types.h" #include "message_parcel.h" @@ -44,7 +44,7 @@ int ProviderConnectStub::OnRemoteRequest( case IAbilityConnection::ON_ABILITY_CONNECT_DONE: { if (element == nullptr) { APP_LOGE("%{public}s failed, callback stub receive element is nullptr", __func__); - return ERR_APPEXECFWK_PARCEL_ERROR; + return ERR_INVALID_VALUE; } auto remoteObject = data.ReadParcelable(); auto resultCode = data.ReadInt32(); @@ -55,7 +55,7 @@ int ProviderConnectStub::OnRemoteRequest( case IAbilityConnection::ON_ABILITY_DISCONNECT_DONE: { if (element == nullptr) { APP_LOGE("%{public}s failed, callback stub receive element is nullptr", __func__); - return ERR_APPEXECFWK_PARCEL_ERROR; + return ERR_INVALID_VALUE; } auto resultCode = data.ReadInt32(); OnAbilityDisconnectDone(*element, resultCode); diff --git a/interfaces/innerkits/fmskit/BUILD.gn b/interfaces/innerkits/fmskit/BUILD.gn index 5b10fb34c816c8381aea8274db6d70c356cb0464..ced9a7112961085ee2fa9419940e206607121b25 100644 --- a/interfaces/innerkits/fmskit/BUILD.gn +++ b/interfaces/innerkits/fmskit/BUILD.gn @@ -36,7 +36,6 @@ ohos_shared_library("fmskit_native") { configs = [ ":fmskit_config" ] public_configs = [ ":fmskit_public_config" ] sources = [ - "$SUBSYSTEM_DIR/interfaces/innerkits/fmskit/native/src/form_errors.cpp", "$SUBSYSTEM_DIR/interfaces/innerkits/fmskit/native/src/form_host_client.cpp", "$SUBSYSTEM_DIR/interfaces/innerkits/fmskit/native/src/form_mgr.cpp", ] diff --git a/interfaces/innerkits/fmskit/native/include/form_errors.h b/interfaces/innerkits/fmskit/native/include/form_errors.h deleted file mode 100644 index 1510f4670de36c19256f83fd8ffe2926ffd5cfbe..0000000000000000000000000000000000000000 --- a/interfaces/innerkits/fmskit/native/include/form_errors.h +++ /dev/null @@ -1,55 +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 FOUNDATION_APPEXECFWK_OHOS_FORM_ERRORS_H -#define FOUNDATION_APPEXECFWK_OHOS_FORM_ERRORS_H - -#include -#include - -namespace OHOS { -namespace AppExecFwk { -/** - * @class FormErrors - * FormErrors is used to access form error message. - */ -class FormErrors final : public DelayedRefSingleton { - DECLARE_DELAYED_REF_SINGLETON(FormErrors) -public: - DISALLOW_COPY_AND_MOVE(FormErrors); - - /** - * @brief Get the error message content. - * - * @param errCode Error code. - * @return Message content. - */ - std::string GetErrorMessage(int errCode); - -private: - /** - * @brief Init error message map object. - * - */ - void InitErrorMessageMap(); - -private: - std::map errorMessageMap_; - - -}; -} // namespace AppExecFwk -} // namespace OHOS -#endif // FOUNDATION_APPEXECFWK_OHOS_FORM_ERRORS_H \ No newline at end of file diff --git a/interfaces/innerkits/fmskit/native/include/form_mgr.h b/interfaces/innerkits/fmskit/native/include/form_mgr.h index ec455552e483cf19ee8f2772804020bc57c676fb..4eaca5087e5ccc0b738caa37b40ca7ed4461bae3 100644 --- a/interfaces/innerkits/fmskit/native/include/form_mgr.h +++ b/interfaces/innerkits/fmskit/native/include/form_mgr.h @@ -51,7 +51,7 @@ public: * @param formInfo Form info. * @return Returns ERR_OK on success, others on failure. */ - int AddForm(const int64_t formId, const Want &want, const sptr &callerToken, + virtual int AddForm(const int64_t formId, const Want &want, const sptr &callerToken, FormJsInfo &formInfo); /** @@ -197,13 +197,6 @@ public: */ bool CheckIsDeathCallbackRegistered(const std::shared_ptr &formDeathCallback); - /** - * @brief Get the error message content. - * - * @param errCode Error code. - * @return Message content. - */ - std::string GetErrorMessage(int errCode); private: /** * @brief Connect form manager service. diff --git a/interfaces/innerkits/fmskit/native/src/form_errors.cpp b/interfaces/innerkits/fmskit/native/src/form_errors.cpp deleted file mode 100644 index 25861a6a41d297157709e5f3789d18d56a0f3114..0000000000000000000000000000000000000000 --- a/interfaces/innerkits/fmskit/native/src/form_errors.cpp +++ /dev/null @@ -1,139 +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 "appexecfwk_errors.h" -#include "form_errors.h" - -namespace OHOS { -namespace AppExecFwk { -FormErrors::FormErrors() -{ - InitErrorMessageMap(); -} -FormErrors::~FormErrors() -{ -} - -/** - * @brief Get the error message content. - * - * @param errCode Error code. - * @return Message content. - */ -std::string FormErrors::GetErrorMessage(int errCode) -{ - if(errorMessageMap_.find(errCode) != errorMessageMap_.end()) { - return errorMessageMap_[errCode]; - } - else { - return errorMessageMap_[ERR_APPEXECFWK_FORM_COMMON_CODE]; - } -} - -/** - * @brief Init error message map object. - * - */ -void FormErrors::InitErrorMessageMap() -{ - errorMessageMap_ = { // error + message - { - ERR_APPEXECFWK_FORM_COMMON_CODE, "some internal server error occurs.", - }, - { - ERR_APPEXECFWK_FORM_PERMISSION_DENY, - "check permission deny, need to request ohos.permission.REQUIRE_FORM.", - }, - { - ERR_APPEXECFWK_FORM_GET_INFO_FAILED, "can't get form info by the formName.", - }, - { - ERR_APPEXECFWK_FORM_GET_BUNDLE_FAILED, "the requested bundle name does not exist.", - }, - { - ERR_APPEXECFWK_FORM_INVALID_PARAM, "invalid params received on operating form.", - }, - { - ERR_APPEXECFWK_FORM_CFG_NOT_MATCH_ID, "the form id and form config are not matched.", - }, - { - ERR_APPEXECFWK_FORM_NOT_EXIST_ID, "the requested form id is not existed on fms.", - }, - { - ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED, "fms bind provider failed.", - }, - { - ERR_APPEXECFWK_FORM_MAX_SYSTEM_FORMS, "exceed max forms in system, current limit is 512.", - }, - { - ERR_APPEXECFWK_FORM_EXCEED_INSTANCES_PER_FORM, "exceed max instances per form, limit is 32.", - }, - { - ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF, - "the form to be operated is not self-owned or has been deleted already.", - }, - { - ERR_APPEXECFWK_FORM_PROVIDER_DEL_FAIL, "fms notify provider to delete failed.", - }, - { - ERR_APPEXECFWK_FORM_MAX_FORMS_PER_CLIENT, "exceed max forms per client, limit is 256.", - }, - { - ERR_APPEXECFWK_FORM_MAX_SYSTEM_TEMP_FORMS, "exceed max temp forms in system, limit is 256.", - }, - { - ERR_APPEXECFWK_FORM_NO_SUCH_MODULE, "the module not exist in the bundle.", - }, - { - ERR_APPEXECFWK_FORM_NO_SUCH_ABILITY, "the ability not exist in the module.", - }, - { - ERR_APPEXECFWK_FORM_NO_SUCH_DIMENSION, "the dimension not exist in the form.", - }, - { - ERR_APPEXECFWK_FORM_FA_NOT_INSTALLED, "the ability not installed,need install first.", - }, - { - ERR_APPEXECFWK_FORM_MAX_REQUEST, "too many request,try again later.", - }, - { - ERR_APPEXECFWK_FORM_MAX_REFRESH, "already refresh 50 times.", - }, - { - ERR_APPEXECFWK_FORM_GET_BMS_FAILED, "get bms rpc failed.", - }, - { - ERR_APPEXECFWK_FORM_GET_FMS_FAILED, "get fms rpc failed.", - }, - { - ERR_APPEXECFWK_FORM_SEND_FMS_MSG, "send request to fms failed.", - }, - { - ERR_APPEXECFWK_FORM_FORM_DUPLICATE_ADDED, "form do not support acquire same id twice.", - }, - { - ERR_APPEXECFWK_FORM_IN_RECOVER, "form is in recover status, can't do action on form.", - }, - { - ERR_APPEXECFWK_FORM_GET_SYSMGR_FAILED, "get system manager failed.", - }, - { - ERR_APPEXECFWK_PARCEL_ERROR, "read parcelable info failed.", - }, - }; -} - -} // namespace AppExecFwk -} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/fmskit/native/src/form_host_client.cpp b/interfaces/innerkits/fmskit/native/src/form_host_client.cpp index f3a48d6e760e8b293723ddb2df18913c5def0891..2187e886b6eceb72216f5914b733b329266eacdb 100755 --- a/interfaces/innerkits/fmskit/native/src/form_host_client.cpp +++ b/interfaces/innerkits/fmskit/native/src/form_host_client.cpp @@ -105,7 +105,7 @@ void FormHostClient::RemoveForm(std::shared_ptr formCallb { std::lock_guard lock(lockMutex_); int64_t key = FindKeyByCallback(formCallback); - if (key == -1) { + if(key == -1) { APP_LOGE("%{public}s, failed to find callback.", __func__); return; } @@ -167,8 +167,7 @@ void FormHostClient::OnAcquired(const FormJsInfo &formJsInfo) APP_LOGE("%{public}s error, can't find target callback. formId: %{public}" PRId64 ".", __func__, formId); return; } - APP_LOGI("%{public}s, formId: %{public}" PRId64 ", jspath: %{public}s, data: %{public}s", __func__, formId, - formJsInfo.jsFormCodePath.c_str(), formJsInfo.formData.c_str()); + APP_LOGI("%{public}s, formId: %{public}" PRId64 ", data: %{public}s", __func__, formId, formJsInfo.formData.c_str()); targetCallback->ProcessFormUpdate(formJsInfo); } @@ -207,8 +206,8 @@ void FormHostClient::OnUninstall(const std::vector &formIds) APP_LOGE("%{public}s error, formIds is empty.", __func__); return; } - for (auto &formId : formIds) { - if (formId < 0) { + for(auto &formId : formIds) { + if (formId < 0) { APP_LOGE("%{public}s error, the passed form id can't be negative.", __func__); continue; } diff --git a/interfaces/innerkits/fmskit/native/src/form_mgr.cpp b/interfaces/innerkits/fmskit/native/src/form_mgr.cpp index b728408bb40fcda1279f829295e011411675cc1c..6531c5afe7dec6ecf8a7e44ecf98b5aad293aabc 100644 --- a/interfaces/innerkits/fmskit/native/src/form_mgr.cpp +++ b/interfaces/innerkits/fmskit/native/src/form_mgr.cpp @@ -16,7 +16,6 @@ #include #include "appexecfwk_errors.h" #include "app_log_wrapper.h" -#include "form_errors.h" #include "form_mgr.h" #include "if_system_ability_manager.h" #include "ipc_skeleton.h" @@ -44,11 +43,8 @@ FormMgr::~FormMgr() * @param formInfo Form info. * @return Returns ERR_OK on success, others on failure. */ -int FormMgr::AddForm( - const int64_t formId, - const Want &want, - const sptr &callerToken, - FormJsInfo &formInfo) +int FormMgr::AddForm(const int64_t formId, const Want &want, const sptr &callerToken, +FormJsInfo &formInfo) { APP_LOGI("%{public}s called.", __func__); @@ -146,10 +142,8 @@ int FormMgr::RequestForm(const int64_t formId, const sptr &caller * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. * @return Returns ERR_OK on success, others on failure. */ -int FormMgr::NotifyWhetherVisibleForms( - const std::vector &formIds, - const sptr &callerToken, - const int32_t formVisibleType) +int FormMgr::NotifyWhetherVisibleForms(const std::vector &formIds, const sptr &callerToken, +const int32_t formVisibleType) { int errCode = Connect(); if (errCode != ERR_OK) { @@ -262,10 +256,8 @@ int FormMgr::SetNextRefreshTime(const int64_t formId, const int64_t nextTime) * @param updateType Next refresh time. * @return Returns ERR_OK on success, others on failure. */ -int FormMgr::LifecycleUpdate( - const std::vector &formIds, - const sptr &callerToken, - const int32_t updateType) +int FormMgr::LifecycleUpdate(const std::vector &formIds, const sptr &callerToken, +const int32_t updateType) { int errCode = Connect(); if (errCode != ERR_OK) { @@ -298,17 +290,6 @@ void FormMgr::SetRecoverStatus(int recoverStatus) recoverStatus_ = recoverStatus; } -/** - * @brief Get the error message content. - * - * @param errCode Error code. - * @return Message content. - */ -std::string FormMgr::GetErrorMessage(int errCode) -{ - return FormErrors::GetInstance().GetErrorMessage(errCode); -} - /** * @brief Register death callback. * @@ -457,11 +438,11 @@ ErrCode FormMgr::Connect() deathRecipient_ = sptr(new FormMgrDeathRecipient()); if (deathRecipient_ == nullptr) { APP_LOGE("%{public}s :Failed to create FormMgrDeathRecipient!", __func__); - return ERR_APPEXECFWK_FORM_COMMON_CODE; + return ERR_NO_MEMORY; } if ((remoteObject->IsProxyObject()) && (!remoteObject->AddDeathRecipient(deathRecipient_))) { APP_LOGE("%{public}s :Add death recipient to FormMgrService failed.", __func__); - return ERR_APPEXECFWK_FORM_COMMON_CODE; + return ERR_APPEXECFWK_FORM_ADD_DEATH_RECIPIENT_FAILED; } remoteProxy_ = iface_cast(remoteObject); diff --git a/interfaces/innerkits/libeventhandler/include/inner_event.h b/interfaces/innerkits/libeventhandler/include/inner_event.h index 0cd2e3f1aea2d3b2617c5ec31060fa9465bcaa8b..ca13bf30a7e703c46aed1163871819f8326e3ad8 100644 --- a/interfaces/innerkits/libeventhandler/include/inner_event.h +++ b/interfaces/innerkits/libeventhandler/include/inner_event.h @@ -67,7 +67,7 @@ public: * @param param Basic parameter of the event, default is 0. * @return Returns the pointer of InnerEvent instance. */ - template + template static inline Pointer Get(uint32_t innerEventId, const std::shared_ptr &object, int64_t param = 0) { auto event = Get(innerEventId, param); @@ -83,7 +83,7 @@ public: * @param param Basic parameter of the event, default is 0. * @return Returns the pointer of InnerEvent instance. */ - template + template static inline Pointer Get(uint32_t innerEventId, const std::weak_ptr &object, int64_t param = 0) { auto event = Get(innerEventId, param); @@ -99,7 +99,7 @@ public: * @param param Basic parameter of the event, default is 0. * @return Returns the pointer of InnerEvent instance. */ - template + template static inline Pointer Get(uint32_t innerEventId, std::unique_ptr &&object, int64_t param = 0) { auto event = Get(innerEventId, param); @@ -115,7 +115,7 @@ public: * @param param Basic parameter of the event, default is 0. * @return Returns the pointer of InnerEvent instance. */ - template + template static inline Pointer Get(uint32_t innerEventId, std::unique_ptr &object, int64_t param = 0) { auto event = Get(innerEventId, param); @@ -131,7 +131,7 @@ public: * @param object Shared pointer of the object. * @return Returns the pointer of InnerEvent instance. */ - template + template static inline Pointer Get(uint32_t innerEventId, int64_t param, const std::shared_ptr &object) { auto event = Get(innerEventId, param); @@ -147,7 +147,7 @@ public: * @param object Weak pointer of the object. * @return Returns the pointer of InnerEvent instance. */ - template + template static inline Pointer Get(uint32_t innerEventId, int64_t param, const std::weak_ptr &object) { auto event = Get(innerEventId, param); @@ -163,7 +163,7 @@ public: * @param object Unique pointer of the object. * @return Returns the pointer of InnerEvent instance. */ - template + template static inline Pointer Get(uint32_t innerEventId, int64_t param, std::unique_ptr &&object) { auto event = Get(innerEventId, param); @@ -179,7 +179,7 @@ public: * @param object Unique pointer of the object. * @return Returns the pointer of InnerEvent instance. */ - template + template static inline Pointer Get(uint32_t innerEventId, int64_t param, std::unique_ptr &object) { auto event = Get(innerEventId, param); @@ -290,7 +290,7 @@ public: * * @return Returns shared pointer of saved object. */ - template + template std::shared_ptr GetSharedObject() const { const std::shared_ptr &sharedObject = *reinterpret_cast *>(smartPtr_); @@ -312,7 +312,7 @@ public: * * @return Returns unique pointer of saved object. */ - template + template std::unique_ptr GetUniqueObject() const { std::unique_ptr &object = *reinterpret_cast *>(smartPtr_); @@ -329,7 +329,7 @@ public: * * @return Returns unique pointer of saved object. */ - template + template std::unique_ptr GetUniqueObject() const { std::unique_ptr &object = *reinterpret_cast *>(smartPtr_); @@ -401,7 +401,7 @@ private: static void WarnSmartPtrCastMismatch(); - template + template static void ReleaseSmartPtr(void *smartPtr) { if (smartPtr != nullptr) { @@ -409,7 +409,7 @@ private: } } - template + template inline void SaveSharedPtr(const T &object) { smartPtr_ = new T(object); @@ -417,7 +417,7 @@ private: smartPtrTypeId_ = CalculateSmartPtrTypeId(object); } - template + template inline void SaveUniquePtr(T &object) { smartPtr_ = new T(std::move(object)); @@ -430,7 +430,7 @@ private: */ #ifdef __GXX_RTTI // If RTTI(Run-Time Type Info) is enabled, use hash code of type info. - template + template static inline size_t CalculateSmartPtrTypeId(const T &) { return typeid(T).hash_code(); @@ -442,25 +442,25 @@ private: static const size_t UNIQUE_PTR_TYPE = 0x30000000; static const size_t UNIQUE_PTR_ARRAY_TYPE = 0x40000000; - template + template static inline size_t CalculateSmartPtrTypeId(const std::shared_ptr &) { return (sizeof(T) | SHARED_PTR_TYPE); } - template + template static inline size_t CalculateSmartPtrTypeId(const std::weak_ptr &) { return (sizeof(T) | WEAK_PTR_TYPE); } - template + template static inline size_t CalculateSmartPtrTypeId(const std::unique_ptr &) { return (sizeof(T) | (sizeof(D) - 1) | UNIQUE_PTR_TYPE); } - template + template static inline size_t CalculateSmartPtrTypeId(const std::unique_ptr &) { return (sizeof(T) | (sizeof(D) - 1) | UNIQUE_PTR_ARRAY_TYPE); diff --git a/interfaces/innerkits/task_dispatcher/include/dispatcher/base_task_dispatcher.h b/interfaces/innerkits/task_dispatcher/include/dispatcher/base_task_dispatcher.h index 106b6619b9654307381ed05ca1fcb3b97d27c248..96326fb7fd18ef0d41168f8c3cec626a7283069b 100644 --- a/interfaces/innerkits/task_dispatcher/include/dispatcher/base_task_dispatcher.h +++ b/interfaces/innerkits/task_dispatcher/include/dispatcher/base_task_dispatcher.h @@ -28,7 +28,7 @@ namespace OHOS { namespace AppExecFwk { /** - *Base implementation for interface of TaskDispatcher. + * Base implementation for interface of TaskDispatcher. */ class BaseTaskDispatcher : public TaskDispatcher { diff --git a/interfaces/innerkits/task_dispatcher/include/dispatcher/serial_task_dispatcher.h b/interfaces/innerkits/task_dispatcher/include/dispatcher/serial_task_dispatcher.h index 9388e9ce0c9619f08469b99a27133732320d5f23..af3847c8caf7c64d45ccae9f15ff976ef4a45870 100644 --- a/interfaces/innerkits/task_dispatcher/include/dispatcher/serial_task_dispatcher.h +++ b/interfaces/innerkits/task_dispatcher/include/dispatcher/serial_task_dispatcher.h @@ -35,51 +35,7 @@ namespace AppExecFwk { * Dispatcher for serial thread model. */ class SerialTaskDispatcher : public BaseTaskDispatcher, public std::enable_shared_from_this { -private: - static std::string DISPATCHER_TAG; - static std::string ASYNC_DISPATCHER_TAG; - static std::string SYNC_DISPATCHER_TAG; - static std::string DELAY_DISPATCHER_TAG; - - std::atomic running_; - ConcurrentQueue> workingTasks_; - - std::shared_ptr executor_; - std::mutex mutex_; - -private: - ErrCode OnNewTaskIn(std::shared_ptr &task); - - ErrCode Prepare(std::shared_ptr &task); - - /** - * Callback for task when finish. - * - */ - void OnTaskDone(); - - bool Schedule(); - - /** - * Do task in turn, until the task queue is empty. - * - * @param isExhausted is an inaccurate judge indicate that the workingTasks is empty. If true, do double-check. - * @return true if has work remain to do else false. - * - */ - bool DoNext(bool isExhausted); - - void DoWork(std::shared_ptr &task); - public: - /** - * Constructs a serial TaskDispatcher using priority. - * - * @param dispatcherName is the identity for dispatcher. It's for debug purpose. - * @param priority is the priority for tasks dispatched by this Dispatcher. - * @param executor contains thread pool(s) for executing tasks concurrently. - * - */ SerialTaskDispatcher( const std::string &dispatcherName, const TaskPriority priority, const std::shared_ptr &executor); ~SerialTaskDispatcher(){}; @@ -127,6 +83,40 @@ public: * */ std::shared_ptr DelayDispatch(const std::shared_ptr &runnable, long delayMs); +private: + ErrCode OnNewTaskIn(std::shared_ptr &task); + + ErrCode Prepare(std::shared_ptr &task); + + /** + * Callback for task when finish. + * + */ + void OnTaskDone(); + + bool Schedule(); + + /** + * Do task in turn, until the task queue is empty. + * + * @param isExhausted is an inaccurate judge indicate that the workingTasks is empty. If true, do double-check. + * @return true if has work remain to do else false. + * + */ + bool DoNext(bool isExhausted); + + void DoWork(std::shared_ptr &task); +private: + static std::string DISPATCHER_TAG; + static std::string ASYNC_DISPATCHER_TAG; + static std::string SYNC_DISPATCHER_TAG; + static std::string DELAY_DISPATCHER_TAG; + + std::atomic running_; + ConcurrentQueue> workingTasks_; + + std::shared_ptr executor_; + std::mutex mutex_; }; } // namespace AppExecFwk diff --git a/interfaces/innerkits/task_dispatcher/include/task/task.h b/interfaces/innerkits/task_dispatcher/include/task/task.h index 82a5c0d4a8877941b57c8d13ee87dfd5c64d604f..4d58c0e9b44d70e53b7ac99a3d429d86a0d111cc 100644 --- a/interfaces/innerkits/task_dispatcher/include/task/task.h +++ b/interfaces/innerkits/task_dispatcher/include/task/task.h @@ -37,52 +37,52 @@ public: virtual ~Task(); /** - *@brief invoke the function to execute the task + * @brief invoke the function to execute the task */ virtual void Run(); /** - * @brief Gets the priority. - * @return The priority. + * @brief Gets the priority. + * @return The priority. */ TaskPriority GetPriority() const; /** - * @brief Sets the sequence. - * @param sequence The sequence + * @brief Sets the sequence. + * @param sequence The sequence */ void SetSequence(long sequence); /** - *@brief Gets the sequence. - *@return The sequence. + * @brief Gets the sequence. + * @return The sequence. */ long GetSequence() const; /** - *@brief Revoke this task if hasn't run. - *@return true if set revoked or already revoked. False if the task has start executing. + * @brief Revoke this task if hasn't run. + * @return true if set revoked or already revoked. False if the task has start executing. */ bool Revoke() override; /** - *@brief Adds a task listener. - *@param listener The listener + * @brief Adds a task listener. + * @param listener The listener */ void AddTaskListener(const std::shared_ptr &listener); /** - *@brief Called when task is about to run. + * @brief Called when task is about to run. */ void BeforeTaskExecute(); /** - *@brief Called when task is done. + * @brief Called when task is done. */ void AfterTaskExecute(); /** - *@brief Called when task is canceled. + * @brief Called when task is canceled. */ void OnTaskCanceled(); @@ -102,9 +102,9 @@ private: }; /** - *@brief Return true if not executed or revoked, and if not executed or revoked, ensure |EXECUTED| to be set. - *@param - - *@return bool + * @brief Return true if not executed or revoked, and if not executed or revoked, ensure |EXECUTED| to be set. + * @param - + * @return bool */ bool EnterExecute(); diff --git a/interfaces/innerkits/task_dispatcher/include/task/task_listener.h b/interfaces/innerkits/task_dispatcher/include/task/task_listener.h index 4ba73a96b61cce7f19bde0abb6a1643ac5a76e9e..27ff313fffcb70f78e1c3c1b611d083047ab96c9 100644 --- a/interfaces/innerkits/task_dispatcher/include/task/task_listener.h +++ b/interfaces/innerkits/task_dispatcher/include/task/task_listener.h @@ -27,9 +27,9 @@ class TaskListener { public: virtual ~TaskListener(){}; /** - *@brief Called when task stage changed. - *@param stage The stage - *@return void + * @brief Called when task stage changed. + * @param stage The stage + * @return void */ virtual void OnChanged(const TaskStage &stage) = 0; }; diff --git a/interfaces/innerkits/task_dispatcher/include/threading/concurrent_queue.h b/interfaces/innerkits/task_dispatcher/include/threading/concurrent_queue.h index 76090d0e4cdfc4f32f6fe6dae14fae6322ff94bf..6126745ee0422a347a8c931192e8f8c491e182fc 100644 --- a/interfaces/innerkits/task_dispatcher/include/threading/concurrent_queue.h +++ b/interfaces/innerkits/task_dispatcher/include/threading/concurrent_queue.h @@ -24,7 +24,7 @@ namespace OHOS { namespace AppExecFwk { -template +template class ConcurrentQueue { public: ConcurrentQueue() : empty_(){}; diff --git a/interfaces/innerkits/task_dispatcher/include/threading/worker_pool.h b/interfaces/innerkits/task_dispatcher/include/threading/worker_pool.h index eee772130055a408da163b6e7be15d4d3cb2e53f..edf8a97adc088c81bcae6b0da232cf41d16ee3af 100644 --- a/interfaces/innerkits/task_dispatcher/include/threading/worker_pool.h +++ b/interfaces/innerkits/task_dispatcher/include/threading/worker_pool.h @@ -80,7 +80,7 @@ private: static bool IsRunning(int ctl); - static int GetStateFromControl(unsigned int ctl); + static int GetStateFromControl(int ctl); static int CombineToControl(unsigned int state, unsigned int count); diff --git a/interfaces/innerkits/task_dispatcher/src/dispatcher/group_impl.cpp b/interfaces/innerkits/task_dispatcher/src/dispatcher/group_impl.cpp index ed3b982aca4b115e217a776d030c419018657b6f..578b4132722c19191bb91312bb3cf5cb58fa678c 100644 --- a/interfaces/innerkits/task_dispatcher/src/dispatcher/group_impl.cpp +++ b/interfaces/innerkits/task_dispatcher/src/dispatcher/group_impl.cpp @@ -111,7 +111,7 @@ bool GroupImpl::AddNotification(const std::shared_ptr ¬ification) return true; } /** - * @brief Notify all tasks and remove from queue. + * @brief Notify all tasks and remove from queue. * Attention: Notifications added after all tasks done is not guaranteed. */ void GroupImpl::DrainNotifications() diff --git a/interfaces/innerkits/task_dispatcher/src/dispatcher/parallel_task_dispatcher_base.cpp b/interfaces/innerkits/task_dispatcher/src/dispatcher/parallel_task_dispatcher_base.cpp index de9e3e011b20b3043b639690e0260b189ecf0951..ddce41c646bac8f8742499b33f3bea021804824b 100644 --- a/interfaces/innerkits/task_dispatcher/src/dispatcher/parallel_task_dispatcher_base.cpp +++ b/interfaces/innerkits/task_dispatcher/src/dispatcher/parallel_task_dispatcher_base.cpp @@ -122,8 +122,7 @@ std::shared_ptr ParallelTaskDispatcherBase::DelayDispatch( return nullptr; } TracePointBeforePost(innerTask, true, DELAY_DISPATCHER_TAG); - std::function callback = - std::bind(&ParallelTaskDispatcherBase::InterceptedExecute, shared_from_this(), innerTask); + std::function < void()> callback = std::bind(&ParallelTaskDispatcherBase::InterceptedExecute, shared_from_this(), innerTask); bool executeFlag = executor_->DelayExecute(callback, delayMs); if (!executeFlag) { APP_LOGE("ParallelTaskDispatcherBase::DelayDispatch execute failed"); diff --git a/interfaces/innerkits/task_dispatcher/src/dispatcher/serial_task_dispatcher.cpp b/interfaces/innerkits/task_dispatcher/src/dispatcher/serial_task_dispatcher.cpp index 48e37f068ef063c144b9a35af6d466a9853dd858..42fc5720c7a3e2dbb2293b25113748066096953b 100644 --- a/interfaces/innerkits/task_dispatcher/src/dispatcher/serial_task_dispatcher.cpp +++ b/interfaces/innerkits/task_dispatcher/src/dispatcher/serial_task_dispatcher.cpp @@ -108,7 +108,7 @@ std::shared_ptr SerialTaskDispatcher::DelayDispatch(const std::shared } TracePointBeforePost(innerTask, true, DELAY_DISPATCHER_TAG); // bind parameter to avoid deconstruct. - std::function callback = std::bind(&SerialTaskDispatcher::OnNewTaskIn, this, innerTask); + std::function < void()> callback = std::bind(&SerialTaskDispatcher::OnNewTaskIn, this, innerTask); bool executeFlag = executor_->DelayExecute(callback, delayMs); if (!executeFlag) { APP_LOGE("SerialTaskDispatcher::DelayDispatch execute failed"); diff --git a/interfaces/innerkits/task_dispatcher/src/dispatcher/task_dispatcher_context.cpp b/interfaces/innerkits/task_dispatcher/src/dispatcher/task_dispatcher_context.cpp index 9e22e53a262b679e845cfa591503af978625e593..e2c737e8914e4a08b270f61ef3dd1d1043c8a568 100644 --- a/interfaces/innerkits/task_dispatcher/src/dispatcher/task_dispatcher_context.cpp +++ b/interfaces/innerkits/task_dispatcher/src/dispatcher/task_dispatcher_context.cpp @@ -128,6 +128,8 @@ int TaskDispatcherContext::MapPriorityIndex(TaskPriority priority) const return DEFAULT_PRIORITY_INDEX; case TaskPriority::LOW: return LOW_PRIORITY_INDEX; + default: + return DEFAULT_PRIORITY_INDEX; } APP_LOGE("TaskDispatcherContext.mapPriorityIndex unhandled priority=%{public}d", priority); diff --git a/interfaces/innerkits/task_dispatcher/src/task/barrier_handler.cpp b/interfaces/innerkits/task_dispatcher/src/task/barrier_handler.cpp index a8d0c7a42f4dae87d84caf7959f6a70c019fa7b3..0f4706ac1abbd1a1cee09166eeed1ce0ceb86957 100644 --- a/interfaces/innerkits/task_dispatcher/src/task/barrier_handler.cpp +++ b/interfaces/innerkits/task_dispatcher/src/task/barrier_handler.cpp @@ -171,9 +171,9 @@ bool BarrierHandler::HasTask(const std::set> &tasks) std::set> BarrierHandler::CreateTaskSet(std::shared_ptr &firstTask) { - std::set> newSet; - newSet.insert(firstTask); - return newSet; + std::set> taskSet; + taskSet.insert(firstTask); + return taskSet; } } // namespace AppExecFwk diff --git a/interfaces/innerkits/task_dispatcher/src/task/task.cpp b/interfaces/innerkits/task_dispatcher/src/task/task.cpp index dd23ef89d615203af10abce79e6924d646deeb24..6f73cfc53f54db4add6838e27b3120808629a72c 100644 --- a/interfaces/innerkits/task_dispatcher/src/task/task.cpp +++ b/interfaces/innerkits/task_dispatcher/src/task/task.cpp @@ -37,9 +37,9 @@ Task::~Task() {} /** - *@brief invoke the function to execute the task - *@param None - *@return None + * @brief invoke the function to execute the task + * @param None + * @return None */ void Task::Run() { @@ -57,9 +57,9 @@ void Task::Run() } /** - * @brief Gets the priority. - * @param None - * @return The priority. + * @brief Gets the priority. + * @param None + * @return The priority. */ TaskPriority Task::GetPriority() const { @@ -67,10 +67,10 @@ TaskPriority Task::GetPriority() const } /** - * @brief Sets the sequence. - * @param None - * @param sequence The sequence - * @return None + * @brief Sets the sequence. + * @param None + * @param sequence The sequence + * @return None */ void Task::SetSequence(long sequence) { @@ -78,9 +78,9 @@ void Task::SetSequence(long sequence) } /** - *@brief Gets the sequence. - *@param None - *@return The sequence. + * @brief Gets the sequence. + * @param None + * @return The sequence. */ long Task::GetSequence() const { @@ -88,9 +88,9 @@ long Task::GetSequence() const } /** - *@brief Revoke this task if hasn't run. - *@param None - *@return true if set revoked or already revoked. False if the task has start executing. + * @brief Revoke this task if hasn't run. + * @param None + * @return true if set revoked or already revoked. False if the task has start executing. */ bool Task::Revoke() { @@ -107,9 +107,9 @@ bool Task::Revoke() } /** - *@brief Adds a task listener. - *@param listener The listener - *@return None + * @brief Adds a task listener. + * @param listener The listener + * @return None */ void Task::AddTaskListener(const std::shared_ptr &listener) { @@ -118,9 +118,9 @@ void Task::AddTaskListener(const std::shared_ptr &listener) } /** - *@brief Called when task is about to run. - *@param None - *@return None + * @brief Called when task is about to run. + * @param None + * @return None */ void Task::BeforeTaskExecute() { @@ -130,9 +130,9 @@ void Task::BeforeTaskExecute() } /** - *@brief Called when task is done. - *@param None - *@return None + * @brief Called when task is done. + * @param None + * @return None */ void Task::AfterTaskExecute() { @@ -143,9 +143,9 @@ void Task::AfterTaskExecute() } /** - *@brief Called when task is canceled. - *@param None - *@return None + * @brief Called when task is canceled. + * @param None + * @return None */ void Task::OnTaskCanceled() { @@ -154,9 +154,9 @@ void Task::OnTaskCanceled() } /** - *@brief Return true if not executed or revoked, and if not executed or revoked, ensure |EXECUTED| to be set. - *@param None - *@return bool + * @brief Return true if not executed or revoked, and if not executed or revoked, ensure |EXECUTED| to be set. + * @param None + * @return bool */ bool Task::EnterExecute() { diff --git a/interfaces/innerkits/task_dispatcher/src/threading/task_executor.cpp b/interfaces/innerkits/task_dispatcher/src/threading/task_executor.cpp index 406f79dd31a2506163532de044de66a5838cd0cc..197f1ae4e528b9103cb62bbc8287c379ed06e849 100644 --- a/interfaces/innerkits/task_dispatcher/src/threading/task_executor.cpp +++ b/interfaces/innerkits/task_dispatcher/src/threading/task_executor.cpp @@ -94,7 +94,7 @@ std::shared_ptr TaskExecutor::GetTask(const std::shared_ptr std::shared_ptr nullRunnable = nullptr; std::shared_ptr next = nullptr; - for (;;) { + for(;;) { if (terminated_.load() && pendingTasks_->Empty()) { APP_LOGI("TaskExecutor::GetTask end: loop thread %{public}s is terminated", workerThread->GetThreadName().c_str()); @@ -204,7 +204,7 @@ bool TaskExecutor::EnsureConsumeStarted() void TaskExecutor::Consume() { - for (;;) { + for(;;) { if (terminated_.load() && delayTasks_->Empty()) { APP_LOGI("TaskExecutor::Consume delay task is empty"); break; diff --git a/interfaces/innerkits/task_dispatcher/src/threading/worker_pool.cpp b/interfaces/innerkits/task_dispatcher/src/threading/worker_pool.cpp index 957c392fbddd48a4255774edc539d49857bb38d5..137644970613b9da76e4abe79c47645dec7da7eb 100644 --- a/interfaces/innerkits/task_dispatcher/src/threading/worker_pool.cpp +++ b/interfaces/innerkits/task_dispatcher/src/threading/worker_pool.cpp @@ -237,32 +237,44 @@ bool WorkerPool::AddWorker(const std::shared_ptr &delegate, const std: return added; } std::unique_lock mLock(poolLock_); - std::shared_ptr workerThread = nullptr; - for(;;) { + std::shared_ptr newThread = nullptr; + + for (;;) { unsigned int value = control_.load(); int num = GetWorkingThreadNum(value); if (num >= thread_limit_) { - APP_LOGI("WorkerPool::AddWorker thread count exceed limits, num=%{public}d", num); + APP_LOGI("WorkerPool::AddWorker thread count exceed limits, num=%{public}d, limits=%{public}d", + num, + thread_limit_); break; } if (!IsRunning(value)) { - APP_LOGI("WorkerPool::AddWorker thread pool is not running. value=%{public}d, closing=%{public}d, ", + APP_LOGI("WorkerPool::AddWorker thread pool is not running. value=%{public}d, closing=%{public}d, " + "count_bits=%{public}d", value, - CLOSING); + CLOSING, + COUNT_BITS); break; } + if (CompareAndIncThreadNum(num)) { - workerThread = std::make_shared(delegate, task, factory_); - if (workerThread == nullptr) { + newThread = std::make_shared(delegate, task, factory_); + if (newThread == nullptr) { APP_LOGE("WorkerPool::AddWorker create thread fail"); break; } - workerThread->CreateThread(); - pool_.emplace_back(workerThread); + + newThread->CreateThread(); + + APP_LOGI("WorkerPool::AddWorker create new thread"); + + pool_.emplace_back(newThread); APP_LOGI("WorkerPool::AddWorker pool_ add thread ,POOL SIZE: %{public}zu", pool_.size()); + added = true; break; } + APP_LOGW("WorkerPool::AddWorker set thread state error. retry. "); } return added; @@ -307,7 +319,7 @@ bool WorkerPool::IsRunning(int ctl) return ctl < CLOSING; } -int WorkerPool::GetStateFromControl(unsigned int ctl) +int WorkerPool::GetStateFromControl(int ctl) { return ctl & ~CAPACITY; } @@ -315,7 +327,7 @@ int WorkerPool::GetStateFromControl(unsigned int ctl) void WorkerPool::AdvanceStateTo(unsigned int target) { APP_LOGI("WorkerPool::AdvanceStateTo begin"); - for(;;) { + for (;;) { unsigned int current = control_.load(); if ((current >= target) || CompareAndSet(control_, current, CombineToControl(target, GetWorkingThreadNum(current)))) { @@ -333,7 +345,7 @@ int WorkerPool::CombineToControl(unsigned int state, unsigned int count) bool WorkerPool::CompareAndIncThreadNum(int expect) { - unsigned int ctl = control_.load(); + int ctl = control_.load(); int state = GetStateFromControl(ctl); return CompareAndSet(control_, ctl, CombineToControl(state, expect + 1)); } @@ -355,7 +367,7 @@ bool WorkerPool::CompareAndDecThreadNum(int expect) bool WorkerPool::CompareAndDecNum(int expectCount) { - unsigned int curr = control_.load(); + int curr = control_.load(); int state = GetStateFromControl(curr); int expectControl = CombineToControl(state, expectCount); return CompareAndDecThreadNum(expectControl); diff --git a/interfaces/innerkits/task_dispatcher/test/unittest/barrier_handler_test/barrier_handler_test.cpp b/interfaces/innerkits/task_dispatcher/test/unittest/barrier_handler_test/barrier_handler_test.cpp index 90a170230aeecf83d69f2370c060a6d3f5f18aeb..57eedb0cf9657977627c8e13fc5f1893f1f6e89a 100644 --- a/interfaces/innerkits/task_dispatcher/test/unittest/barrier_handler_test/barrier_handler_test.cpp +++ b/interfaces/innerkits/task_dispatcher/test/unittest/barrier_handler_test/barrier_handler_test.cpp @@ -76,7 +76,6 @@ HWTEST(BarrierHandlerTest, BarrierHandler_interceptTest_001, TestSize.Level0) auto name = std::string("BarrierHandler_interceptTest_001"); GTEST_LOG_(INFO) << name << " start"; std::shared_ptr barrierHandler = CreateBarrierHandler(); - //每次添加组任务, 给任务添加监听,当任务完成时候。。。。。判断任务是否应该执行(前面有屏障时候,不立即执行)。 std::shared_ptr runnable = std::make_shared([&]() { GTEST_LOG_(INFO) << name << " Runnable"; }); std::shared_ptr task = std::make_shared(runnable, TaskPriority::DEFAULT, nullptr); ErrCode result = barrierHandler->Intercept(task); diff --git a/interfaces/innerkits/task_dispatcher/test/unittest/groupImpl_test/groupImpl_test.cpp b/interfaces/innerkits/task_dispatcher/test/unittest/groupImpl_test/groupImpl_test.cpp index 0daf94b2784c4f5bb94ac7cb21f7097c15266113..2a9931d164d40993ff0c34db86bde717061e9bdc 100644 --- a/interfaces/innerkits/task_dispatcher/test/unittest/groupImpl_test/groupImpl_test.cpp +++ b/interfaces/innerkits/task_dispatcher/test/unittest/groupImpl_test/groupImpl_test.cpp @@ -175,9 +175,9 @@ HWTEST(GroupImplTest, AppExecFwk_GroupImpl_AddNotification_002, TestSize.Level0) std::make_shared([&]() { GTEST_LOG_(INFO) << "GroupImpl AddNotification"; }); groupPtr->AddNotification(notification); } - std::shared_ptr newNotification = + std::shared_ptr notificationTask = std::make_shared([&]() { GTEST_LOG_(INFO) << "GroupImpl AddNotification"; }); - bool result = groupPtr->AddNotification(newNotification); + bool result = groupPtr->AddNotification(notificationTask); EXPECT_TRUE(result); GTEST_LOG_(INFO) << name << " end"; } @@ -198,9 +198,9 @@ HWTEST(GroupImplTest, AppExecFwk_GroupImpl_AddNotification_003, TestSize.Level0) std::make_shared([&]() { GTEST_LOG_(INFO) << "GroupImpl AddNotification"; }); groupPtr->AddNotification(notification); } - std::shared_ptr newNotification = + std::shared_ptr notificationTask = std::make_shared([&]() { GTEST_LOG_(INFO) << "GroupImpl AddNotification"; }); - bool result = groupPtr->AddNotification(newNotification); + bool result = groupPtr->AddNotification(notificationTask); EXPECT_FALSE(result); GTEST_LOG_(INFO) << name << " end"; } diff --git a/interfaces/innerkits/task_dispatcher/test/unittest/parallel_task_dispatcher_base_test/parallel_task_dispatcher_base_test.cpp b/interfaces/innerkits/task_dispatcher/test/unittest/parallel_task_dispatcher_base_test/parallel_task_dispatcher_base_test.cpp index 5347daaca1ff5357f1c146140a5356e7f9d4636c..a7e924cf0234769f389676492b8b6b03d87e4b14 100644 --- a/interfaces/innerkits/task_dispatcher/test/unittest/parallel_task_dispatcher_base_test/parallel_task_dispatcher_base_test.cpp +++ b/interfaces/innerkits/task_dispatcher/test/unittest/parallel_task_dispatcher_base_test/parallel_task_dispatcher_base_test.cpp @@ -194,7 +194,6 @@ HWTEST(ParallelTaskDispatcherBaseTest, ParallelTaskDispatcherBase_AsyncGroupDisp CreateParallelTaskDispatcherBase(name, TaskPriority::DEFAULT); std::atomic count(0); EXPECT_EQ(count.load(), 0); - //添加个group1 std::shared_ptr group1 = parallelTaskDispatcherBase->CreateDispatchGroup(); std::shared_ptr group1Run1 = std::make_shared([&]() { std::this_thread::sleep_for(std::chrono::milliseconds(800)); @@ -209,7 +208,6 @@ HWTEST(ParallelTaskDispatcherBaseTest, ParallelTaskDispatcherBase_AsyncGroupDisp GTEST_LOG_(INFO) << name << " Group1 : Runnable2"; }); parallelTaskDispatcherBase->AsyncGroupDispatch(group1, group1Run2); - //添加group2 std::shared_ptr group2 = parallelTaskDispatcherBase->CreateDispatchGroup(); std::shared_ptr group2Run = std::make_shared([&]() { count.fetch_add(1); diff --git a/interfaces/innerkits/task_dispatcher/test/unittest/spec_task_dispatcher_test/spec_task_dispatcher_test.cpp b/interfaces/innerkits/task_dispatcher/test/unittest/spec_task_dispatcher_test/spec_task_dispatcher_test.cpp index 8c4ad4db71213c977e0af2d1bfb6469eec01996b..07212360d09691672937333f42bf650d061381d0 100644 --- a/interfaces/innerkits/task_dispatcher/test/unittest/spec_task_dispatcher_test/spec_task_dispatcher_test.cpp +++ b/interfaces/innerkits/task_dispatcher/test/unittest/spec_task_dispatcher_test/spec_task_dispatcher_test.cpp @@ -59,17 +59,10 @@ void SpecTaskDispatcherTest::SetUp() void SpecTaskDispatcherTest::TearDown() {} -std::string Now() -{ - time_t now = std::time(0); - char mbstr[10]; - std::strftime(mbstr, sizeof(mbstr), "%T", std::localtime(&now)); - return mbstr; -} const std::string Prefix(const std::string &name) { - return std::string(">>> ") + Now() + std::string(" ") + name + std::string(": "); + return std::string(">>> prefix :") + std::string(" ") + name + std::string(": "); } std::shared_ptr CreateSpecTaskDispatcher() diff --git a/interfaces/innerkits/test/moduletest/task_dispatcher/global_task_dispatcher_module_test/global_task_dispatcher_module_test.cpp b/interfaces/innerkits/test/moduletest/task_dispatcher/global_task_dispatcher_module_test/global_task_dispatcher_module_test.cpp index b86f8b04693b658a729b98acb28c86a3a5bb83a3..6abe4204c16ef42f57e99d1b945f2e8798c004ca 100644 --- a/interfaces/innerkits/test/moduletest/task_dispatcher/global_task_dispatcher_module_test/global_task_dispatcher_module_test.cpp +++ b/interfaces/innerkits/test/moduletest/task_dispatcher/global_task_dispatcher_module_test/global_task_dispatcher_module_test.cpp @@ -55,6 +55,7 @@ void GlobalTaskDispatcherModuleTest::TearDown() std::shared_ptr GlobalTaskDispatcherModuleTest::GetMtGlobalTaskDispatcher(TaskPriority priority) const { + // TaskDispatcherContext context; std::shared_ptr ptrGlobalTaskDispatcher = context->GetGlobalTaskDispatcher(priority); return ptrGlobalTaskDispatcher; } diff --git a/interfaces/innerkits/test/moduletest/task_dispatcher/serial_task_dispatcher_module_test/serial_task_dispatcher_module_test.cpp b/interfaces/innerkits/test/moduletest/task_dispatcher/serial_task_dispatcher_module_test/serial_task_dispatcher_module_test.cpp index 21e0da663c9fe20cc37ade115d4c89149b487bf0..ee540863f7bea3473a55fb9d1ed25d8b7618f0dd 100644 --- a/interfaces/innerkits/test/moduletest/task_dispatcher/serial_task_dispatcher_module_test/serial_task_dispatcher_module_test.cpp +++ b/interfaces/innerkits/test/moduletest/task_dispatcher/serial_task_dispatcher_module_test/serial_task_dispatcher_module_test.cpp @@ -203,35 +203,6 @@ HWTEST_F(SerialTaskDispatcherModuleTest, SerialTaskDispatcher_AsyncDispatchTest_ GTEST_LOG_(INFO) << name + " end"; } -void DelayDispatchTestWait (std::atomic &count){ - { - long wait = 100; - auto time = std::chrono::milliseconds(wait); - std::this_thread::sleep_for(time); - } - { - long wait = 1000; - GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); - auto time = std::chrono::milliseconds(wait); - std::this_thread::sleep_for(time); - EXPECT_TRUE(count.load() == 2); - } - { - long wait = 500; - GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); - auto time = std::chrono::milliseconds(wait); - std::this_thread::sleep_for(time); - EXPECT_TRUE(count.load() == 2); - } - { - long wait = 1000; - GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); - auto time = std::chrono::milliseconds(wait); - std::this_thread::sleep_for(time); - EXPECT_TRUE(count.load() == 3); - } -} - /** * @tc.number: SerialTaskDispatcher_DelayDispatchTest_001 * @tc.name: DelayDispatch @@ -272,7 +243,33 @@ HWTEST_F(SerialTaskDispatcherModuleTest, SerialTaskDispatcher_DelayDispatchTest_ }), sleep3); EXPECT_TRUE(count.load() == 0); - DelayDispatchTestWait(count); + + { + long wait = 100; + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + } + { + long wait = 1000; + GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 2); + } + { + long wait = 500; + GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 2); + } + { + long wait = 1000; + GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 3); + } GTEST_LOG_(INFO) << name + " end"; } diff --git a/interfaces/innerkits/test/moduletest/task_dispatcher/spec_task_dispatcher_module_test/spec_task_dispatcher_module_test.cpp b/interfaces/innerkits/test/moduletest/task_dispatcher/spec_task_dispatcher_module_test/spec_task_dispatcher_module_test.cpp index ce6b5b3336e06a337b5b9118e45fab4778a90369..d251f276ddc7fe8429f51db6ea7b744b7d33e7d6 100644 --- a/interfaces/innerkits/test/moduletest/task_dispatcher/spec_task_dispatcher_module_test/spec_task_dispatcher_module_test.cpp +++ b/interfaces/innerkits/test/moduletest/task_dispatcher/spec_task_dispatcher_module_test/spec_task_dispatcher_module_test.cpp @@ -130,35 +130,6 @@ HWTEST_F(SpecTaskDispatcherModuleTest, SpecTaskDispatcher_AsyncDispatchTest_001, GTEST_LOG_(INFO) << name + " end"; } -void DelayDispatcherTestWait(std::atomic &count){ - { - long wait = 100; - auto time = std::chrono::milliseconds(wait); - std::this_thread::sleep_for(time); - } - { - long wait = 1000; - GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); - auto time = std::chrono::milliseconds(wait); - std::this_thread::sleep_for(time); - EXPECT_TRUE(count.load() == 2); - } - { - long wait = 500; - GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); - auto time = std::chrono::milliseconds(wait); - std::this_thread::sleep_for(time); - EXPECT_TRUE(count.load() == 2); - } - { - long wait = 1000; - GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); - auto time = std::chrono::milliseconds(wait); - std::this_thread::sleep_for(time); - EXPECT_TRUE(count.load() == 3); - } -} - /** * @tc.number: SpecTaskDispatcher_DelayDispatchTest_001 * @tc.name: DelayDispatch @@ -199,7 +170,33 @@ HWTEST_F(SpecTaskDispatcherModuleTest, SpecTaskDispatcher_DelayDispatchTest_001, }), sleep3); EXPECT_TRUE(count.load() == 0); - DelayDispatcherTestWait(count); + + { + long wait = 100; + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + } + { + long wait = 1000; + GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 2); + } + { + long wait = 500; + GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 2); + } + { + long wait = 1000; + GTEST_LOG_(INFO) << ("wait for task, wait= " + std::to_string(wait) + " ms"); + auto time = std::chrono::milliseconds(wait); + std::this_thread::sleep_for(time); + EXPECT_TRUE(count.load() == 3); + } GTEST_LOG_(INFO) << name + " end"; } diff --git a/kits/appkit/napi/bundlemgr/bundle_mgr.cpp b/kits/appkit/napi/bundlemgr/bundle_mgr.cpp index 2f02deeccf5a892a76ffc88ffc02bc8085a76a08..1f7d91b5b684e12ed1aaf5f6605c030a6dcc4135 100644 --- a/kits/appkit/napi/bundlemgr/bundle_mgr.cpp +++ b/kits/appkit/napi/bundlemgr/bundle_mgr.cpp @@ -956,7 +956,7 @@ static napi_value ParseInt(napi_env env, int ¶m, napi_value args) NAPI_CALL(env, napi_typeof(env, args, &valuetype)); HILOG_INFO("param=%{public}d.", valuetype); NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. int32 expected."); - int32_t value; + int32_t value = 0; napi_get_value_int32(env, args, &value); HILOG_INFO("param=%{public}d.", value); param = value; @@ -1031,7 +1031,7 @@ napi_value GetApplicationInfos(napi_env env, napi_callback_info info) applicationFlag = ApplicationFlag::GET_BASIC_APPLICATION_INFO; } - AsyncApplicationInfosCallbackInfo *asyncCallbackInfo = new AsyncApplicationInfosCallbackInfo{ + AsyncApplicationInfosCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncApplicationInfosCallbackInfo{ .env = env, .asyncWork = nullptr, .deferred = nullptr, .applicationFlag = applicationFlag, .userId = userId}; if (asyncCallbackInfo == nullptr) { return nullptr; @@ -1363,7 +1363,7 @@ napi_value GetApplicationInfo(napi_env env, napi_callback_info info) if (flag == static_cast(ApplicationFlag::GET_BASIC_APPLICATION_INFO)) { applicationFlag = ApplicationFlag::GET_BASIC_APPLICATION_INFO; } - AsyncApplicationInfoCallbackInfo *asyncCallbackInfo = new AsyncApplicationInfoCallbackInfo{.env = env, + AsyncApplicationInfoCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncApplicationInfoCallbackInfo{.env = env, .asyncWork = nullptr, .deferred = nullptr, .bundleName = bundleName, @@ -1533,7 +1533,7 @@ napi_value GetBundleInfos(napi_env env, napi_callback_info info) if (flag == static_cast(BundleFlag::GET_BUNDLE_DEFAULT)) { bundleFlag = BundleFlag::GET_BUNDLE_DEFAULT; } - AsyncBundleInfosCallbackInfo *asyncCallbackInfo = new AsyncBundleInfosCallbackInfo{ + AsyncBundleInfosCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncBundleInfosCallbackInfo{ .env = env, .asyncWork = nullptr, .deferred = nullptr, .bundleFlag = bundleFlag}; if (asyncCallbackInfo == nullptr) { return nullptr; @@ -1665,7 +1665,7 @@ napi_value GetBundleInfo(napi_env env, napi_callback_info info) if (flag == static_cast(BundleFlag::GET_BUNDLE_DEFAULT)) { bundleFlag = BundleFlag::GET_BUNDLE_DEFAULT; } - AsyncBundleInfoCallbackInfo *asyncCallbackInfo = new AsyncBundleInfoCallbackInfo{ + AsyncBundleInfoCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncBundleInfoCallbackInfo{ .env = env, .asyncWork = nullptr, .deferred = nullptr, .param = bundleName, .bundleFlag = bundleFlag}; if (asyncCallbackInfo == nullptr) { return nullptr; @@ -1798,7 +1798,7 @@ napi_value GetBundleArchiveInfo(napi_env env, napi_callback_info info) if (flag == static_cast(BundleFlag::GET_BUNDLE_DEFAULT)) { bundleFlag = BundleFlag::GET_BUNDLE_DEFAULT; } - AsyncBundleInfoCallbackInfo *asyncCallbackInfo = new AsyncBundleInfoCallbackInfo{ + AsyncBundleInfoCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncBundleInfoCallbackInfo{ .env = env, .asyncWork = nullptr, .deferred = nullptr, .param = hapFilePath, .bundleFlag = bundleFlag}; if (asyncCallbackInfo == nullptr) { return nullptr; @@ -1983,7 +1983,7 @@ napi_value GetPermissionDef(napi_env env, napi_callback_info info) HILOG_INFO("argc = [%{public}zu]", argc); std::string permissionName; ParseString(env, permissionName, argv[PARAM0]); - AsyncPermissionDefCallbackInfo *asyncCallbackInfo = new AsyncPermissionDefCallbackInfo{ + AsyncPermissionDefCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncPermissionDefCallbackInfo{ .env = env, .asyncWork = nullptr, .deferred = nullptr, .permissionName = permissionName}; if (asyncCallbackInfo == nullptr) { return nullptr; @@ -2391,7 +2391,7 @@ napi_value Install(napi_env env, napi_callback_info info) ParseStringArray(env, bundleFilePaths, argv[PARAM0]); InstallParam installParam; ParseInstallParam(env, installParam, argv[PARAM1]); - AsyncInstallCallbackInfo *asyncCallbackInfo = new AsyncInstallCallbackInfo{ + AsyncInstallCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncInstallCallbackInfo{ .env = env, .asyncWork = nullptr, .deferred = nullptr, @@ -2553,7 +2553,7 @@ napi_value Uninstall(napi_env env, napi_callback_info info) ParseString(env, bundleName, argv[PARAM0]); InstallParam installParam; ParseInstallParam(env, installParam, argv[PARAM1]); - AsyncInstallCallbackInfo *asyncCallbackInfo = new AsyncInstallCallbackInfo{ + AsyncInstallCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncInstallCallbackInfo{ .env = env, .asyncWork = nullptr, .deferred = nullptr, @@ -2845,7 +2845,7 @@ napi_value GetFormsInfoByModule(napi_env env, napi_callback_info info) ParseString(env, bundleName, argv[PARAM0]); ParseString(env, moduleName, argv[PARAM1]); - AsyncFormInfosByModuleCallbackInfo *asyncCallbackInfo = new AsyncFormInfosByModuleCallbackInfo{ + AsyncFormInfosByModuleCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncFormInfosByModuleCallbackInfo{ .env = env, .asyncWork = nullptr, .deferred = nullptr, .bundleName = bundleName, .moduleName = moduleName}; if (asyncCallbackInfo == nullptr) { return nullptr; @@ -2969,7 +2969,7 @@ napi_value GetFormsInfoByApp(napi_env env, napi_callback_info info) std::string bundleName; ParseString(env, bundleName, argv[PARAM0]); - AsyncFormInfosByAppCallbackInfo *asyncCallbackInfo = new AsyncFormInfosByAppCallbackInfo{ + AsyncFormInfosByAppCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncFormInfosByAppCallbackInfo{ .env = env, .asyncWork = nullptr, .deferred = nullptr, .bundleName = bundleName}; if (asyncCallbackInfo == nullptr) { return nullptr; @@ -3111,7 +3111,7 @@ napi_value GetShortcutInfos(napi_env env, napi_callback_info info) HILOG_INFO("ARGCSIZE is =%{public}zu.", argc); std::string bundleName; ParseString(env, bundleName, argv[PARAM0]); - AsyncShortcutInfosCallbackInfo *asyncCallbackInfo = new AsyncShortcutInfosCallbackInfo{ + AsyncShortcutInfosCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncShortcutInfosCallbackInfo{ .env = env, .asyncWork = nullptr, .deferred = nullptr, .bundleName = bundleName}; if (asyncCallbackInfo == nullptr) { return nullptr; @@ -3253,7 +3253,7 @@ napi_value GetModuleUsageRecords(napi_env env, napi_callback_info info) HILOG_INFO("ARGCSIZE is =%{public}zu.", argc); int number; ParseInt(env, number, argv[PARAM0]); - AsyncModuleUsageRecordsCallbackInfo *asyncCallbackInfo = new AsyncModuleUsageRecordsCallbackInfo{ + AsyncModuleUsageRecordsCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncModuleUsageRecordsCallbackInfo{ .env = env, .asyncWork = nullptr, .deferred = nullptr, .number = number}; if (asyncCallbackInfo == nullptr) { return nullptr; @@ -3495,6 +3495,9 @@ napi_value RegisterAllPermissionsChanged(napi_env env, napi_callback_info info) } else if (permissionEvent == ANY_PERMISSION_CHANGE && argc == ARGS_SIZE_TWO) { AsyncRegisterAllPermissions *asyncCallbackInfo = new AsyncRegisterAllPermissions{.env = env, .asyncWork = nullptr}; + if (asyncCallbackInfo == nullptr) { + return nullptr; + } HILOG_INFO("RegisterAllPermissionsChanged anyPermissionChange asyncCallback."); napi_valuetype valuetype = napi_undefined; napi_typeof(env, argv[ARGS_SIZE_ONE], &valuetype); @@ -3616,7 +3619,7 @@ napi_value UnregisterPermissionsChanged(napi_env env, napi_callback_info info) ParseString(env, permissionEvent, argv[PARAM0]); if (permissionEvent == ANY_PERMISSION_CHANGE && argc == ARGS_SIZE_TWO) { - AsyncUnregisterPermissions *asyncCallbackInfo = new AsyncUnregisterPermissions{ + AsyncUnregisterPermissions *asyncCallbackInfo = new (std::nothrow) AsyncUnregisterPermissions{ .env = env, .asyncWork = nullptr, }; @@ -3756,7 +3759,7 @@ napi_value CheckPermission(napi_env env, napi_callback_info info) std::string permission; ParseString(env, permission, argv[PARAM1]); - AsyncPermissionCallbackInfo *asyncCallbackInfo = new AsyncPermissionCallbackInfo{ + AsyncPermissionCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncPermissionCallbackInfo{ .env = env, .asyncWork = nullptr, .deferred = nullptr, .bundleName = bundleName, .permission = permission}; if (asyncCallbackInfo == nullptr) { return nullptr; diff --git a/kits/appkit/napi/bundlemgr/permission_callback.cpp b/kits/appkit/napi/bundlemgr/permission_callback.cpp index 57d65185bd703dcb5317f3eb5cb51111b9d3c1cc..3b8d3b4f955da7a232fdb9e40298ae000d538f51 100644 --- a/kits/appkit/napi/bundlemgr/permission_callback.cpp +++ b/kits/appkit/napi/bundlemgr/permission_callback.cpp @@ -18,6 +18,7 @@ #include "hilog_wrapper.h" namespace { + constexpr size_t ARGS_SIZE_TWO = 2; } @@ -38,23 +39,16 @@ void PermissionCallback::OnChanged(const int32_t uid) napi_get_uv_event_loop(env_, &loop); #endif // NAPI_VERSION >= 2 - uv_work_t *work = new (std::nothrow) uv_work_t; - if (work == nullptr) { - HILOG_ERROR("new uv_work_t failed"); - return; - } - CallbackInfo *callbackInfo = new (std::nothrow) CallbackInfo { + uv_work_t *work = new uv_work_t; + CallbackInfo *callbackInfo = new (std::nothrow) CallbackInfo{ .env = env_, .callback = callback_, .uid = uid, }; - if (callbackInfo == nullptr) { - HILOG_ERROR("new CallbackInfo failed"); - return; - } + work->data = (void *)callbackInfo; - int rev = uv_queue_work( + uv_queue_work( loop, work, [](uv_work_t *work) {}, @@ -82,13 +76,6 @@ void PermissionCallback::OnChanged(const int32_t uid) delete event; delete work; }); - if (rev != 0) { - if (callbackInfo != nullptr) { - delete callbackInfo; - } - if (work != nullptr) { - delete work; - } - } + HILOG_INFO("OnChanged, end"); } \ No newline at end of file diff --git a/kits/appkit/native/app/include/task_dispatcher.h b/kits/appkit/native/app/include/task_dispatcher.h index ad06df59eaaef82f64d2164e337864277e2cf3dd..4ddee5b9834a4da0693ac826be2a3504b8d28c2e 100644 --- a/kits/appkit/native/app/include/task_dispatcher.h +++ b/kits/appkit/native/app/include/task_dispatcher.h @@ -25,7 +25,7 @@ namespace OHOS { namespace AppExecFwk { -template +template using IteratableTask = std::function; class TaskDispatcher { @@ -33,31 +33,15 @@ public: virtual ~TaskDispatcher() = default; /** - * Dispatches a task and waits until the task is complete in the current thread. + * @brief Dispatches a task and waits until the task is complete in the current thread. * - *

The current thread is blocked before the given task is complete. Therefore, a deadlock occurs in the - * following cases: - *

- *
    - *
  1. - * {@code SyncDispatch} is cyclically called on a serial task dispatcher or a task dispatcher that is dedicated - * to a specific thread. For example, {@code SyncDispatch} is called to dispatch a task from dispatcher A to - * dispatcher A, or to dispatch a task from dispatcher A to dispatcher B and then back to dispatcher A. - *
  2. - *
  3. - * Too many threads are blocked on {@code SyncDispatch}. As a result, the internal thread pool is used up and - * cannot process other tasks any more. - *
  4. - *
- *
* @param runnable Indicates the task to be executed. This parameter includes all information required for the task * execution. - * @since 1 */ virtual ErrCode SyncDispatch(const std::shared_ptr &runnable) = 0; /** - * Asynchronously dispatches a task. + * @brief Asynchronously dispatches a task. * *

This method dispatches a task and returns a value immediately without waiting for the task to execute.

* @@ -65,12 +49,11 @@ public: * execution. * @return Returns a {@link std::shared_ptr} instance used for revoking the given task * if it has not been invoked. - * @since 1 */ virtual std::shared_ptr AsyncDispatch(const std::shared_ptr &runnable) = 0; /** - * Dispatches a task after the given delay. + * @brief Dispatches a task after the given delay. * *

This is an asynchronous execution and returns a value immediately without waiting. The task will be * dispatched to the queue after the given delay specified by {@code delayMs}, and its actual execution time @@ -83,12 +66,11 @@ public: * @param delayMs Indicates the time period that the given task has to wait before being dispatched. * @return Returns a {@link std::shared_ptr} instance used for revoking the given task * if it has not been invoked. - * @since 1 */ virtual std::shared_ptr DelayDispatch(const std::shared_ptr &runnable, long delayMs) = 0; /** - * Sets an execution barrier in a task group for the given task and waits for the task to be executed after all + * @brief Sets an execution barrier in a task group for the given task and waits for the task to be executed after all * tasks in the task group are finished. * *

The current thread is blocked until the given task is complete. Incorrect use of this method may cause a @@ -96,12 +78,11 @@ public: * If too many threads are blocked, resources in the thread pool will be used up.

* * @param runnable Indicates the task to be executed. - * @since 1 */ virtual ErrCode SyncDispatchBarrier(const std::shared_ptr &runnable) = 0; /** - * Sets an execution barrier for the given task to be executed only after all tasks in the task group are + * @brief Sets an execution barrier for the given task to be executed only after all tasks in the task group are * finished. This method does not wait for the given task to execute. * *

Task execution barriers are unavailable on global task dispatchers. Example code for setting a task @@ -122,21 +103,17 @@ public: * std::cout << "after barrier" << std::endl; * })); * - * // Result will be: - * // before barrier - * // Barrier - * // after barrier + * // Result will be: 1.before barrier; 2.Barrier; 3.after barrier. * } * * * @param runnable Indicates the task to be executed. This parameter includes all information required for the task * execution. - * @since 1 */ virtual ErrCode AsyncDispatchBarrier(const std::shared_ptr &runnable) = 0; /** - * Creates a task group. + * @brief Creates a task group. * *

The {@link std::shared_ptr} object returned by this method does not contain any task. * If you need to dispatch tasks asynchronously, you can use {@link #asyncGroupDispatch} to associate this object @@ -170,21 +147,12 @@ public: * std::cout << "2" << std::endl; * } * - * //Possible results are as follows: - * // 1 - * // 2 - * // Finished downloading URL 2 - * // Finished downloading URL 1 - * // All tasks finished. Do shutdown. - * } - * * @return Returns a {@link std::shared_ptr} object. - * @since 1 */ virtual std::shared_ptr CreateDispatchGroup() = 0; /** - * Adds a task to a task group asynchronously. + * @brief Adds a task to a task group asynchronously. * *

This method returns a value immediately without waiting for the task to execute.

* @@ -193,55 +161,34 @@ public: * execution. * @return Returns a {@link std::shared_ptr} instance used for revoking the given task * if it has not been invoked. - * @since 1 */ virtual std::shared_ptr AsyncGroupDispatch( const std::shared_ptr &group, const std::shared_ptr &runnable) = 0; /** - * Waits all tasks in a task group to finish. + * @brief Waits all tasks in a task group to finish. * * @param group Indicates the task group containing the waiting tasks. * @param timeout Indicates the maximum waiting time for a task. * @return Returns {@code true} if all tasks are correctly executed; returns {@code false} if any task times out. - * @since 1 */ virtual bool GroupDispatchWait(const std::shared_ptr &group, long timeout) = 0; /** - * Executes a task after all tasks in the task group are finished. + * @brief Executes a task after all tasks in the task group are finished. * * @param group Indicates the task group containing the waiting tasks. * @param runnable Indicates the task to be executed after all tasks are finished. - * @since 1 */ virtual ErrCode GroupDispatchNotify( const std::shared_ptr &group, const std::shared_ptr &runnable) = 0; /** - * Executes a task multiple times without waiting. - * - *

Example code: - *

{@code
-     * std::string names[] = {"Rafael Nadal", "Novak Djokovic",
-     *         "Stanislas Wawrinka",
-     *         "David Ferrer","Roger Federer",
-     *         "Andy Murray","Tomas Berdych",
-     *         "Juan Martin Del Potro"};
-     * int num = atp.length;
-     * std::shared_ptr dispatcher = context.getGlobalTaskDispatcher(TaskPriority.DEFAULT);
-     * // Concurrently dispatches tasks using names in |names|.
-     * dispatcher->ApplyDispatch([](i) {
-     *     std::cout << names[i] << std::endl;
-     * }, num);
-     * // The result to be returned depends on thread scheduling of the system.
-     * }
-     * 
+ * @brief Executes a task multiple times without waiting. * * @param task Indicates the task to be executed. This parameter includes all information required for the task * execution. * @param iterations Indicates the number of times the task is executed. The value must be a positive integer. - * @since 1 */ virtual ErrCode ApplyDispatch(const std::shared_ptr> &task, long iterations) = 0; }; diff --git a/libs/libeventhandler/src/event_queue.cpp b/libs/libeventhandler/src/event_queue.cpp index c426aef047aca6c65b40d7309eba253fe577d472..dc1fc3d957a1dab6896a3ecb5de80c15a7eadd2f 100644 --- a/libs/libeventhandler/src/event_queue.cpp +++ b/libs/libeventhandler/src/event_queue.cpp @@ -48,7 +48,7 @@ void RemoveFileDescriptorListenerLocked(std::mapsecond)) { ioWaiter->RemoveFileDescriptor(it->first); it = listeners.erase(it); diff --git a/libs/libeventhandler/src/event_runner.cpp b/libs/libeventhandler/src/event_runner.cpp index 10cb96c76a397a93f11675c2b8f799e92a6cb3df..1c635df8ca3e529745924f9c45c686c2c58cb7f1 100644 --- a/libs/libeventhandler/src/event_runner.cpp +++ b/libs/libeventhandler/src/event_runner.cpp @@ -248,8 +248,8 @@ private: static Avatar avatar_; }; -ThreadCollector::ThreadCollector() - : collectorLock_(), condition_(), reclaims_(), depositMap_(), threadLock_(), thread_(nullptr) +ThreadCollector::ThreadCollector() : + collectorLock_(), condition_(), reclaims_(), depositMap_(), threadLock_(), thread_(nullptr) { // Thread collector is created, so enable avatar. avatarEnabled_ = true; @@ -372,8 +372,8 @@ private: }; } // unnamed namespace -EventInnerRunner::EventInnerRunner(const std::shared_ptr &runner) - : queue_(nullptr), owner_(runner), logger_(nullptr), threadName_(""), threadId_() +EventInnerRunner::EventInnerRunner(const std::shared_ptr &runner) : + queue_(nullptr), owner_(runner), logger_(nullptr), threadName_(""), threadId_() {} std::shared_ptr EventInnerRunner::GetCurrentEventRunner() diff --git a/libs/libeventhandler/src/thread_local_data.h b/libs/libeventhandler/src/thread_local_data.h index 1b2655fdcca0fb8cd33fed3329e7c88e0c1fc3eb..1fd69b8d1f16561c9e8cf4f3fe71ed61b9e239fd 100644 --- a/libs/libeventhandler/src/thread_local_data.h +++ b/libs/libeventhandler/src/thread_local_data.h @@ -27,7 +27,7 @@ namespace AppExecFwk { /* * Tool class, used to save thread local data. */ -template +template class ThreadLocalData { public: ThreadLocalData() = default; diff --git a/services/appmgr/src/lmks/lmks_utils.cpp b/services/appmgr/src/lmks/lmks_utils.cpp index e64ff67a94b3ff28b39679d74058ac2cdb4dbedc..6c0ea2af75f395bc48d10392f801470c226951fb 100644 --- a/services/appmgr/src/lmks/lmks_utils.cpp +++ b/services/appmgr/src/lmks/lmks_utils.cpp @@ -108,7 +108,7 @@ std::string LmksUtils::GetProcName(pid_t pid) return name; } - if (strlen(line) < PROC_LINE_MAX && strlen(line) != 0) { + if (strlen(line) + 1 <= PROC_LINE_MAX && strlen(line) != 0) { name = line; } else { HiLog::Error(LABEL, "cmdline no data"); @@ -160,7 +160,7 @@ int LmksUtils::GetProcSize(pid_t pid) return -1; } - if ((strlen(line) < PROC_LINE_MAX && strlen(line) != 0) && (sscanf_s(line, "%d %d ", &total, &rss) > 0)) { + if ((strlen(line) + 1 <= PROC_LINE_MAX && strlen(line) != 0) && (sscanf_s(line, "%d %d ", &total, &rss) > 0)) { HiLog::Info(LABEL, "pid %{public}d total %{public}d rss %{public}d", pid, total, rss); } else { HiLog::Error(LABEL, "strlen or sscanf_s err %{public}s", strerror(errno)); diff --git a/services/appmgr/src/process_optimizer.cpp b/services/appmgr/src/process_optimizer.cpp index 92607f83779af36f13366e67ced0f192ee48c19e..bc5c3dca6d01747237606d7c77946e1967668e73 100644 --- a/services/appmgr/src/process_optimizer.cpp +++ b/services/appmgr/src/process_optimizer.cpp @@ -709,11 +709,6 @@ void ProcessOptimizer::SetAppFreezingTime(int time) suspendTimeout_ = time; // convert seconds to milliseconds suspendTimeout_ *= TIME_ADVANCE_RATE; - if (suspendTimeout_ > INT_MAX) { - suspendTimeout_ = APP_SUSPEND_TIMEOUT_DEFAULT; - APP_LOGE("data overflow"); - return; - } } void ProcessOptimizer::GetAppFreezingTime(int &time) diff --git a/services/appmgr/test/unittest/ams_service_load_ability_process_test/ams_service_load_ability_process_test.cpp b/services/appmgr/test/unittest/ams_service_load_ability_process_test/ams_service_load_ability_process_test.cpp index 2ef83591008e1ab45242096875fa7d6ea983b5e6..65fd2f308ab0de9b1989520ee00f3e5138ad7bce 100644 --- a/services/appmgr/test/unittest/ams_service_load_ability_process_test/ams_service_load_ability_process_test.cpp +++ b/services/appmgr/test/unittest/ams_service_load_ability_process_test/ams_service_load_ability_process_test.cpp @@ -129,12 +129,12 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, LoadAbility_001, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record = service_->GetAppRunningRecordByAppName(GetTestAppName()); - EXPECT_NE(record, nullptr); + ASSERT_NE(record, nullptr); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto &abilityMap = record->GetAbilities(); EXPECT_EQ(abilityMap.size(), (uint32_t)1); auto abilityRecord = record->GetAbilityRunningRecordByToken(token); - EXPECT_NE(abilityRecord, nullptr); + ASSERT_NE(abilityRecord, nullptr); EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); APP_LOGI("AmsServiceLoadAbilityProcessTest LoadAbility_001 end"); } @@ -171,13 +171,13 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, LoadAbility_002, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record = service_->GetAppRunningRecordByAppName(GetTestAppName()); - EXPECT_NE(record, nullptr); + ASSERT_NE(record, nullptr); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto &abilityMap = record->GetAbilities(); EXPECT_EQ(abilityMap.size(), (uint32_t)1); auto abilityRecord = record->GetAbilityRunningRecordByToken(token); - EXPECT_NE(abilityRecord, nullptr); + ASSERT_NE(abilityRecord, nullptr); EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); sptr token2 = GetMockToken(); @@ -195,10 +195,10 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, LoadAbility_002, TestSize.Level1) const uint32_t EXPECT_MAP_SIZE = 2; EXPECT_EQ(recordMap.size(), EXPECT_MAP_SIZE); auto record2 = service_->GetAppRunningRecordByAppName(GetTestAppName() + "_1"); - EXPECT_NE(record2, nullptr); + ASSERT_NE(record2, nullptr); EXPECT_EQ(record2->GetState(), ApplicationState::APP_STATE_CREATE); auto abilityRecord2 = record2->GetAbilityRunningRecordByToken(token2); - EXPECT_NE(abilityRecord2, nullptr); + ASSERT_NE(abilityRecord2, nullptr); EXPECT_EQ(abilityRecord2->GetState(), AbilityState::ABILITY_STATE_CREATE); APP_LOGI("AmsServiceLoadAbilityProcessTest LoadAbility_002 end"); } @@ -348,12 +348,12 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, LoadAbility_007, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record = service_->GetAppRunningRecordByAppName(GetTestAppName()); - EXPECT_NE(record, nullptr); + ASSERT_NE(record, nullptr); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto &abilityMap = record->GetAbilities(); EXPECT_EQ(abilityMap.size(), (uint32_t)1); auto abilityRecord = record->GetAbilityRunningRecordByToken(token); - EXPECT_NE(abilityRecord, nullptr); + ASSERT_NE(abilityRecord, nullptr); EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); std::shared_ptr mockClientPtr = std::make_shared(); EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(0); @@ -394,12 +394,12 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, LoadAbility_008, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record = service_->GetAppRunningRecordByAppName(GetTestAppName()); - EXPECT_NE(record, nullptr); + ASSERT_NE(record, nullptr); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto &abilityMap = record->GetAbilities(); EXPECT_EQ(abilityMap.size(), (uint32_t)1); auto abilityRecord = record->GetAbilityRunningRecordByToken(token); - EXPECT_NE(abilityRecord, nullptr); + ASSERT_NE(abilityRecord, nullptr); EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); sptr token2 = new MockAbilityToken(); sptr preToken = token; @@ -418,7 +418,7 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, LoadAbility_008, TestSize.Level1) const auto &abilityMap2 = record2->GetAbilities(); EXPECT_EQ(abilityMap2.size(), EXPECT_MAP_SIZE); auto abilityRecord2 = record2->GetAbilityRunningRecordByToken(token2); - EXPECT_NE(abilityRecord2, nullptr); + ASSERT_NE(abilityRecord2, nullptr); EXPECT_EQ(abilityRecord2->GetState(), AbilityState::ABILITY_STATE_CREATE); EXPECT_EQ(abilityRecord2->GetPreToken(), token); APP_LOGI("AmsServiceLoadAbilityProcessTest LoadAbility_008 end"); @@ -455,7 +455,7 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, RequestProcess_001, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record = service_->GetAppRunningRecordByAppName(GetTestAppName()); - EXPECT_NE(record, nullptr); + ASSERT_NE(record, nullptr); EXPECT_EQ(record->GetPriorityObject()->GetPid(), PID); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); APP_LOGI("AmsServiceLoadAbilityProcessTest RequestProcess_001 end"); @@ -582,12 +582,12 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, LaunchMode_001, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record = service_->GetAppRunningRecordByAppName(GetTestAppName()); - EXPECT_NE(record, nullptr); + ASSERT_NE(record, nullptr); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto &abilityMap = record->GetAbilities(); EXPECT_EQ(abilityMap.size(), (uint32_t)1); auto abilityRecord = record->GetAbilityRunningRecordByToken(token); - EXPECT_NE(abilityRecord, nullptr); + ASSERT_NE(abilityRecord, nullptr); EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); APP_LOGI("AmsServiceLoadAbilityProcessTest LaunchMode_001 end"); } @@ -619,12 +619,12 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, LaunchMode_002, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record = service_->GetAppRunningRecordByAppName(GetTestAppName()); - EXPECT_NE(record, nullptr); + ASSERT_NE(record, nullptr); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto &abilityMap = record->GetAbilities(); EXPECT_EQ(abilityMap.size(), (uint32_t)1); auto abilityRecord = record->GetAbilityRunningRecordByToken(token); - EXPECT_NE(abilityRecord, nullptr); + ASSERT_NE(abilityRecord, nullptr); EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); std::shared_ptr mockClientPtr = std::make_shared(); EXPECT_CALL(*mockClientPtr, StartProcess(_, _)).Times(0); @@ -666,12 +666,12 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_001, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record = service_->GetAppRunningRecordByAppName(GetTestAppName()); - EXPECT_NE(record, nullptr); + ASSERT_NE(record, nullptr); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto &abilityMap = record->GetAbilities(); EXPECT_EQ(abilityMap.size(), (uint32_t)1); auto abilityRecord = record->GetAbilityRunningRecordByToken(token); - EXPECT_NE(abilityRecord, nullptr); + ASSERT_NE(abilityRecord, nullptr); EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); sptr token2 = new MockAbilityToken(); auto abilityInfo2 = std::make_shared(); @@ -690,7 +690,7 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_001, TestSize.Level1) const auto &abilityMap1 = record1->GetAbilities(); EXPECT_EQ(abilityMap1.size(), (uint32_t)2); auto abilityrecord1 = record1->GetAbilityRunningRecordByToken(token2); - EXPECT_NE(abilityrecord1, nullptr); + ASSERT_NE(abilityrecord1, nullptr); EXPECT_EQ(abilityrecord1->GetState(), AbilityState::ABILITY_STATE_READY); APP_LOGI("AmsServiceLoadAbilityProcessTest StartAbility_001 end"); } @@ -720,12 +720,12 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_002, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record = service_->GetAppRunningRecordByAppName(GetTestAppName()); - EXPECT_NE(record, nullptr); + ASSERT_NE(record, nullptr); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto &abilityMap = record->GetAbilities(); EXPECT_EQ(abilityMap.size(), (uint32_t)1); auto abilityRecord = record->GetAbilityRunningRecordByToken(token); - EXPECT_NE(abilityRecord, nullptr); + ASSERT_NE(abilityRecord, nullptr); EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); sptr token2 = new MockAbilityToken(); auto abilityInfo2 = std::make_shared(); @@ -773,12 +773,12 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_003, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record = service_->GetAppRunningRecordByAppName(GetTestAppName()); - EXPECT_NE(record, nullptr); + ASSERT_NE(record, nullptr); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto &abilityMap = record->GetAbilities(); EXPECT_EQ(abilityMap.size(), (uint32_t)1); auto abilityRecord = record->GetAbilityRunningRecordByToken(token); - EXPECT_NE(abilityRecord, nullptr); + ASSERT_NE(abilityRecord, nullptr); EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); sptr token2 = new MockAbilityToken(); @@ -825,12 +825,12 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_004, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record = service_->GetAppRunningRecordByAppName(GetTestAppName()); - EXPECT_NE(record, nullptr); + ASSERT_NE(record, nullptr); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto &abilityMap = record->GetAbilities(); EXPECT_EQ(abilityMap.size(), (uint32_t)1); auto abilityRecord = record->GetAbilityRunningRecordByToken(token); - EXPECT_NE(abilityRecord, nullptr); + ASSERT_NE(abilityRecord, nullptr); EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); auto abilityInfo2 = std::make_shared(); abilityInfo2->name = GetTestAbilityName() + "_1"; @@ -876,12 +876,12 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_005, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record = service_->GetAppRunningRecordByAppName(GetTestAppName()); - EXPECT_NE(record, nullptr); + ASSERT_NE(record, nullptr); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto &abilityMap = record->GetAbilities(); EXPECT_EQ(abilityMap.size(), (uint32_t)1); auto abilityRecord = record->GetAbilityRunningRecordByToken(token); - EXPECT_NE(abilityRecord, nullptr); + ASSERT_NE(abilityRecord, nullptr); EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); sptr token2 = new MockAbilityToken(); auto abilityInfo2 = std::make_shared(); @@ -898,7 +898,7 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_005, TestSize.Level1) const auto &abilityMap1 = record1->GetAbilities(); EXPECT_EQ(abilityMap1.size(), (uint32_t)2); auto abilityrecord1 = record1->GetAbilityRunningRecordByToken(token2); - EXPECT_NE(abilityrecord1, nullptr); + ASSERT_NE(abilityrecord1, nullptr); EXPECT_EQ(abilityrecord1->GetState(), AbilityState::ABILITY_STATE_READY); APP_LOGI("AmsServiceLoadAbilityProcessTest StartAbility_005 end"); } @@ -928,12 +928,12 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartAbility_006, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record = service_->GetAppRunningRecordByAppName(GetTestAppName()); - EXPECT_NE(record, nullptr); + ASSERT_NE(record, nullptr); EXPECT_EQ(record->GetState(), ApplicationState::APP_STATE_CREATE); const auto &abilityMap = record->GetAbilities(); EXPECT_EQ(abilityMap.size(), (uint32_t)1); auto abilityRecord = record->GetAbilityRunningRecordByToken(token); - EXPECT_NE(abilityRecord, nullptr); + ASSERT_NE(abilityRecord, nullptr); EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); auto abilityInfo2 = std::make_shared(); abilityInfo2->name = GetTestAbilityName() + "_1"; @@ -983,12 +983,12 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartProcess001, TestSize.Level1) EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record1 = service_->GetAppRunningRecordByAppName(GetTestAppName()); EXPECT_EQ(record1->GetPriorityObject()->GetPid(), PID); - EXPECT_NE(record1, nullptr); + ASSERT_NE(record1, nullptr); EXPECT_EQ(record1->GetState(), ApplicationState::APP_STATE_CREATE); const auto &abilityMap = record1->GetAbilities(); EXPECT_EQ(abilityMap.size(), (uint32_t)1); auto abilityRecord = record1->GetAbilityRunningRecordByToken(token); - EXPECT_NE(abilityRecord, nullptr); + ASSERT_NE(abilityRecord, nullptr); EXPECT_EQ(abilityRecord->GetState(), AbilityState::ABILITY_STATE_CREATE); APP_LOGI("AmsServiceLoadAbilityProcessTest StartProcess001 end"); } @@ -1019,7 +1019,7 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartProcess002, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record1 = service_->GetAppRunningRecordByAppName(GetTestAppName()); - EXPECT_NE(record1, nullptr); + ASSERT_NE(record1, nullptr); APP_LOGI("AmsServiceLoadAbilityProcessTest StartProcess002 end"); } @@ -1050,7 +1050,7 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartProcess003, TestSize.Level1) const auto &recordMap = service_->GetRecordMap(); EXPECT_EQ(recordMap.size(), (uint32_t)1); auto record1 = service_->GetAppRunningRecordByAppName(GetTestAppName()); - EXPECT_NE(record1, nullptr); + ASSERT_NE(record1, nullptr); APP_LOGI("AmsServiceLoadAbilityProcessTest StartProcess003 end"); } @@ -1083,7 +1083,7 @@ HWTEST_F(AmsServiceLoadAbilityProcessTest, StartProcess004, TestSize.Level1) .WillOnce(DoAll(SetArgReferee<1>(PID), Return(ERR_TIMED_OUT))); std::shared_ptr record = service_->GetOrCreateAppRunningRecord(token, appInfo, abilityInfo, GetTestAppName(), 0, result); - EXPECT_NE(record, nullptr); + ASSERT_NE(record, nullptr); service_->StartProcess(abilityInfo->applicationName, GetTestAppName(), record); auto record1 = service_->GetAppRunningRecordByAppRecordId(record->GetRecordId()); EXPECT_EQ(record1, nullptr); diff --git a/services/bundlemgr/include/bundle_data_storage.h b/services/bundlemgr/include/bundle_data_storage.h index 22e46e9b4fee24bae61d7518a782a2489f3ae2e0..13a7cf551b4abbcacd7df0586b9ac899e3a5c968 100644 --- a/services/bundlemgr/include/bundle_data_storage.h +++ b/services/bundlemgr/include/bundle_data_storage.h @@ -47,11 +47,7 @@ public: */ virtual bool DeleteStorageBundleInfo(const std::string &deviceId, const InnerBundleInfo &innerBundleInfo); - virtual bool ResetKvStore() - { - return true; - } - + virtual bool ResetKvStore() { return true;} private: bool KeyToDeviceAndName(const std::string &key, std::string &deviceId, std::string &bundleName) const; void DeviceAndNameToKey(const std::string &deviceId, const std::string &bundleName, std::string &key) const; diff --git a/services/bundlemgr/include/bundle_data_storage_database.h b/services/bundlemgr/include/bundle_data_storage_database.h index 221aad0eef91e7d0151a06d1cfb60e51ab4f9c75..201116725631f48771b7e3297ce1dd6098c91b78 100644 --- a/services/bundlemgr/include/bundle_data_storage_database.h +++ b/services/bundlemgr/include/bundle_data_storage_database.h @@ -69,6 +69,7 @@ private: void DeviceAndNameToKey(const std::string &deviceId, const std::string &bundleName, std::string &key) const; DistributedKv::DistributedKvDataManager dataManager_; std::unique_ptr kvStorePtr_; + // std::shared_ptr dataChangeListener_; mutable std::mutex kvStorePtrMutex_; }; diff --git a/services/bundlemgr/include/bundle_mgr_host_impl.h b/services/bundlemgr/include/bundle_mgr_host_impl.h index 6b2b02264247d793c0e8f3b68d8d98404341215a..8c2b84b3afd8a1186bf0dbaf85dffb197fb9bd91 100644 --- a/services/bundlemgr/include/bundle_mgr_host_impl.h +++ b/services/bundlemgr/include/bundle_mgr_host_impl.h @@ -364,14 +364,13 @@ public: * @return Returns true if GetShortcutInfos successfully; returns false otherwise. */ virtual bool GetShortcutInfos(const std::string &bundleName, std::vector &shortcutInfos) override; - /** + /** * @brief Get module usage record list in descending order of lastLaunchTime. * @param maxNum the return size of the records, must be in range of 1 to 1000. * @param moduleUsageRecords List of ModuleUsageRecord objects if obtained. * @return Returns true if this function is successfully called; returns false otherwise. */ - virtual bool GetModuleUsageRecords( - const int32_t number, std::vector &moduleUsageRecords) override; + virtual bool GetModuleUsageRecords(const int32_t number, std::vector &moduleUsageRecords) override; /** * @brief Notify a specified ability for activity. * @param bundleName Indicates the bundle name of the ability to activity. diff --git a/services/bundlemgr/include/bundle_permissions_changed_monitor.h b/services/bundlemgr/include/bundle_permissions_changed_monitor.h index e3912891c06d71aba869bf9695e361ace4c9296a..ff4bb61f418f01566bfbbd5866f73c51ec9fd1aa 100644 --- a/services/bundlemgr/include/bundle_permissions_changed_monitor.h +++ b/services/bundlemgr/include/bundle_permissions_changed_monitor.h @@ -28,6 +28,7 @@ #include "json_serializer.h" #include "app_log_wrapper.h" + #include "bundle_parser.h" #include "installd_client.h" #include "bundle_permission_mgr.h" @@ -36,15 +37,13 @@ namespace OHOS { namespace AppExecFwk { class BundlePermissionsChangedMonitor : public EventFwk::CommonEventSubscriber { public: - BundlePermissionsChangedMonitor( - const std::shared_ptr &dataMgr, const EventFwk::CommonEventSubscribeInfo &sp) - : CommonEventSubscriber(sp) + BundlePermissionsChangedMonitor(const std::shared_ptr &dataMgr, + const EventFwk::CommonEventSubscribeInfo& sp):CommonEventSubscriber(sp) { dataMgr_ = dataMgr; } - ~BundlePermissionsChangedMonitor() - { - if (!dataMgr_) { + ~BundlePermissionsChangedMonitor(){ + if(!dataMgr_){ dataMgr_.reset(); } } @@ -53,11 +52,10 @@ public: OHOS::AAFwk::Want want = data.GetWant(); std::string action = want.GetAction(); int32_t uid = data.GetCode(); - if (dataMgr_ != nullptr && uid >= 0) { + if ( dataMgr_ != nullptr && uid >=0 ) { dataMgr_->NotifyPermissionsChanged(uid); } } - private: std::shared_ptr dataMgr_; }; diff --git a/services/bundlemgr/include/inner_bundle_info.h b/services/bundlemgr/include/inner_bundle_info.h index 838a37b8dda544c155a8b724b747aeff94771b9d..437c66faa7982ead1c3f287aae18c3ba21a6202c 100644 --- a/services/bundlemgr/include/inner_bundle_info.h +++ b/services/bundlemgr/include/inner_bundle_info.h @@ -893,7 +893,7 @@ public: void SetProvisionId(const std::string &provisionId) { - baseBundleInfo_.appId = provisionId; + baseBundleInfo_.appId = baseBundleInfo_.name + Constants::FILE_UNDERLINE + provisionId; } std::string GetProvisionId() const diff --git a/services/bundlemgr/include/kvstore_death_recipient_callback.h b/services/bundlemgr/include/kvstore_death_recipient_callback.h index 83e5b287f184c5e94aff0b508ffbfacbb1a4b7d0..9b575b3ac24d183a2273de3e7ea9ce6d8b6009c1 100644 --- a/services/bundlemgr/include/kvstore_death_recipient_callback.h +++ b/services/bundlemgr/include/kvstore_death_recipient_callback.h @@ -27,8 +27,9 @@ public: virtual ~KvStoreDeathRecipientCallback(); virtual void OnRemoteDied() override; + }; -} // namespace AppExecFwk -} // namespace OHOS -#endif // FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_INCLUDE_KVSTORE_DEATH_RECIPIENT_CALLBACK_H \ No newline at end of file +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_INCLUDE_KVSTORE_DEATH_RECIPIENT_CALLBACK_H \ No newline at end of file diff --git a/services/bundlemgr/include/module_usage_data_storage.h b/services/bundlemgr/include/module_usage_data_storage.h index d9259a57a0b604b646356d9f922f05954407ccb9..d8c7e6a1598341f67666e3f1f25c441a5d32181b 100644 --- a/services/bundlemgr/include/module_usage_data_storage.h +++ b/services/bundlemgr/include/module_usage_data_storage.h @@ -25,6 +25,7 @@ #include "distributed_kv_data_manager.h" #include "inner_bundle_info.h" + namespace OHOS { namespace AppExecFwk { class DataMgr; @@ -35,36 +36,36 @@ public: virtual ~ModuleUsageRecordStorage(); // add&update - bool AddOrUpdateRecord(ModuleUsageRecord &data, const std::string &deviceId, int32_t userId); + bool AddOrUpdateRecord(ModuleUsageRecord& data, const std::string& deviceId, int32_t userId); bool DeleteRecordByUserId(int32_t userId); - bool DeleteUsageRecord(const InnerBundleInfo &data, int32_t userId); + bool DeleteUsageRecord(const InnerBundleInfo& data, int32_t userId); bool MarkUsageRecordRemoved(const InnerBundleInfo &data, int32_t userId); - bool QueryRecordByNum(int32_t maxNum, std::vector &records, int32_t userId); - void SetDataMgr(const std::weak_ptr &dataMgr) const; + bool QueryRecordByNum(int32_t maxNum, std::vector& records, int32_t userId); + void SetDataMgr(const std::weak_ptr& dataMgr) const; void OnKvStoreDeath(); void RegisterKvStoreDeathListener(); - private: - bool DeleteRecordByKeys(const std::string &bundleName, std::vector &keys); - bool QueryRecordByCondition(DistributedKv::DataQuery &query, std::vector &records); - void AbilityRecordToKey(const std::string &userId, const std::string &deviceId, const std::string &bundleName, - const std::string &moduleName, std::string &key) const; - void InnerBundleInfoToKeys( - const InnerBundleInfo &data, int32_t userId, std::vector &keys) const; - void FillDataStorageKeys(const std::string &userId, const std::string &bundleName, const std::string &moduleName, - std::vector &keys) const; - bool ParseKey(const std::string &key, ModuleUsageRecord &record) const; - void UpdateUsageRecord(const std::string &jsonString, ModuleUsageRecord &data); - void SaveEntries( - const std::vector &allEntries, std::vector &records) const; - void TryTwice(const std::function &func) const; + + bool DeleteRecordByKeys(const std::string& bundleName, std::vector& keys); + bool QueryRecordByCondition(DistributedKv::DataQuery& query, std::vector& records); + void AbilityRecordToKey(const std::string& userId, const std::string& deviceId, + const std::string& bundleName, const std::string& moduleName, std::string& key) const; + void InnerBundleInfoToKeys(const InnerBundleInfo& data, int32_t userId, + std::vector& keys) const; + void FillDataStorageKeys(const std::string& userId, const std::string& bundleName, + const std::string& moduleName, std::vector& keys) const; + bool ParseKey(const std::string& key, ModuleUsageRecord& record) const; + void UpdateUsageRecord(const std::string& jsonString, ModuleUsageRecord& data); + void SaveEntries(const std::vector& allEntries, + std::vector& records) const; + void TryTwice(const std::function& func) const; bool CheckKvStore(); DistributedKv::Status GetKvStore(); bool ResetKvStore(); private: - const DistributedKv::AppId appId_{Constants::APP_ID}; - const DistributedKv::StoreId storeId_{Constants::ABILITY_USAGE_STORE_ID}; + const DistributedKv::AppId appId_ { Constants::APP_ID }; + const DistributedKv::StoreId storeId_ { Constants::ABILITY_USAGE_STORE_ID }; DistributedKv::DistributedKvDataManager dataManager_; std::unique_ptr kvStorePtr_; mutable std::mutex kvStorePtrMutex_; @@ -77,6 +78,6 @@ private: }; }; -} // namespace AppExecFwk -} // namespace OHOS -#endif // FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_INCLUDE_MODULE_USAGE_DATA_STORAGE_H \ No newline at end of file +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_INCLUDE_MODULE_USAGE_DATA_STORAGE_H \ No newline at end of file diff --git a/services/bundlemgr/include/permission_changed_death_recipient.h b/services/bundlemgr/include/permission_changed_death_recipient.h index 8c9b0aab416eb39b527f7f7252485cba68e7dc7f..1f4e04072fbf3be8a4ceebf133acdeeab898a291 100644 --- a/services/bundlemgr/include/permission_changed_death_recipient.h +++ b/services/bundlemgr/include/permission_changed_death_recipient.h @@ -26,9 +26,9 @@ namespace AppExecFwk { class PermissionChangedDeathRecipient : public IRemoteObject::DeathRecipient { public: - virtual void OnRemoteDied(const wptr &object) override; + virtual void OnRemoteDied(const wptr& object) override; }; -} // namespace AppExecFwk -} // namespace OHOS -#endif // FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_INCLUDE_PERMISSION_CHANGED_DEATH_RECIPIENT_H \ No newline at end of file +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_INCLUDE_PERMISSION_CHANGED_DEATH_RECIPIENT_H \ No newline at end of file diff --git a/services/bundlemgr/src/bundle_data_mgr.cpp b/services/bundlemgr/src/bundle_data_mgr.cpp index 4b210e214c53acdf0f21eb13a4bbed666e82a1b6..1c61ef23952b1c590e001b34c1031709b134bf85 100755 --- a/services/bundlemgr/src/bundle_data_mgr.cpp +++ b/services/bundlemgr/src/bundle_data_mgr.cpp @@ -1620,8 +1620,7 @@ bool BundleDataMgr::UnregisterPermissionsChanged(const sptr lock(allPermissionsChangedLock_); - for (auto allPermissionsItem = allPermissionsCallbacks_.begin(); - allPermissionsItem != allPermissionsCallbacks_.end();) { + for (auto allPermissionsItem = allPermissionsCallbacks_.begin(); allPermissionsItem != allPermissionsCallbacks_.end();) { if ((*allPermissionsItem)->AsObject() == callback->AsObject()) { allPermissionsItem = allPermissionsCallbacks_.erase(allPermissionsItem); APP_LOGI("unregister from all permissions callbacks success!"); diff --git a/services/bundlemgr/src/bundle_mgr_host_impl.cpp b/services/bundlemgr/src/bundle_mgr_host_impl.cpp index 03c8fed2c3cc9f33bea72200778eb9621db9807f..a68c60b46b0c5566af8bd5f4734690e4605c7627 100755 --- a/services/bundlemgr/src/bundle_mgr_host_impl.cpp +++ b/services/bundlemgr/src/bundle_mgr_host_impl.cpp @@ -486,8 +486,8 @@ bool BundleMgrHostImpl::RequestPermissionFromUser( APP_LOGI("send Permissions Changed event"); BundleInfo info; bool ret_getInfo = GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_DEFAULT, info); - APP_LOGI("ret_getInfo = %{public}d", ret_getInfo); - if (ret && ret_getInfo) { + APP_LOGI("ret_getInfo = %{public}d",ret_getInfo); + if ( ret && ret_getInfo) { Want want; want.SetAction("PERMISSIONS_CHANGED_EVENT"); EventFwk::CommonEventData commonData; @@ -516,7 +516,7 @@ bool BundleMgrHostImpl::RegisterPermissionsChanged( APP_LOGE("DataMgr is nullptr"); return false; } - return dataMgr->RegisterPermissionsChanged(uids, callback); + return dataMgr->RegisterPermissionsChanged(uids,callback); } bool BundleMgrHostImpl::UnregisterPermissionsChanged(const sptr &callback) diff --git a/services/bundlemgr/src/bundle_permission_mgr.cpp b/services/bundlemgr/src/bundle_permission_mgr.cpp index 524d2e9bb3cecd62010fb8ac1e185670e8916db7..91a84da1179df22393513352609afd6987dfe6ab 100644 --- a/services/bundlemgr/src/bundle_permission_mgr.cpp +++ b/services/bundlemgr/src/bundle_permission_mgr.cpp @@ -59,15 +59,15 @@ bool ConvertPermissionDef( permDef.availableScope = [&defPermission]() -> int { unsigned flag = 0; if (std::find(defPermission.availableScope.begin(), - defPermission.availableScope.end(), - ProfileReader::BUNDLE_MODULE_PROFILE_KEY_DEF_PERMISSIONS_AVAILABLESCOPE_SIGNATURE) != - defPermission.availableScope.end()) { + defPermission.availableScope.end(), + ProfileReader::BUNDLE_MODULE_PROFILE_KEY_DEF_PERMISSIONS_AVAILABLESCOPE_SIGNATURE) != + defPermission.availableScope.end()) { flag |= Permission::AvailableScope::AVAILABLE_SCOPE_SIGNATURE; } if (std::find(defPermission.availableScope.begin(), - defPermission.availableScope.end(), - ProfileReader::BUNDLE_MODULE_PROFILE_KEY_DEF_PERMISSIONS_AVAILABLESCOPE_RESTRICTED) != - defPermission.availableScope.end()) { + defPermission.availableScope.end(), + ProfileReader::BUNDLE_MODULE_PROFILE_KEY_DEF_PERMISSIONS_AVAILABLESCOPE_RESTRICTED) != + defPermission.availableScope.end()) { flag |= Permission::AvailableScope::AVAILABLE_SCOPE_RESTRICTED; } if (flag == 0) { @@ -300,8 +300,8 @@ bool BundlePermissionMgr::CheckCallingPermission(const std::string &permissionNa APP_LOGI( "get app bundleName %{public}s and permissionName %{public}s", bundleName.c_str(), permissionName.c_str()); ApplicationInfo appInfo; - bool ret = dataMgr->GetApplicationInfo( - bundleName, ApplicationFlag::GET_BASIC_APPLICATION_INFO, Constants::DEFAULT_USERID, appInfo); + bool ret = dataMgr->GetApplicationInfo(bundleName, ApplicationFlag::GET_BASIC_APPLICATION_INFO, + Constants::DEFAULT_USERID, appInfo); if (ret && appInfo.isLauncherApp && (permissionName == Constants::PERMISSION_INSTALL_BUNDLE)) { APP_LOGE("launcher app %{public}s pass through", bundleName.c_str()); return true; diff --git a/services/bundlemgr/src/bundle_profile.cpp b/services/bundlemgr/src/bundle_profile.cpp index 9986fc133fcc78c924588b10dd71104528833939..952bcdf57ebad6b58daedeb3de2aea787bbe932e 100644 --- a/services/bundlemgr/src/bundle_profile.cpp +++ b/services/bundlemgr/src/bundle_profile.cpp @@ -1684,11 +1684,11 @@ bool CheckBundleNameIsValid(const std::string &bundleName) return false; } char head = bundleName.at(0); - if (head < 'A' || (head > 'Z' && head < 'a') || head > 'z') { + if (head < 'A' || ('Z' < head && head < 'a') || head > 'z') { return false; } for (const auto &c : bundleName) { - if (c < '.' || c == '/' || (c > '9' && c < 'A') || (c > 'Z' && c < '_') || c == '`' || c > 'z') { + if (c < '.' || c == '/' || ('9' < c && c < 'A') || ('Z' < c && c < '_') || c == '`' || c > 'z') { return false; } } diff --git a/services/bundlemgr/src/bundle_util.cpp b/services/bundlemgr/src/bundle_util.cpp index c6500946ff128a758644479c90d0c1b5f4db4f72..9dd08b4590d02aa9e53fd805bb1831cd5b0d32cc 100644 --- a/services/bundlemgr/src/bundle_util.cpp +++ b/services/bundlemgr/src/bundle_util.cpp @@ -44,7 +44,7 @@ ErrCode BundleUtil::CheckFilePath(const std::string &bundlePath, std::string &re APP_LOGE("can not access the bundle file path: %{private}s", realPath.c_str()); return ERR_APPEXECFWK_INSTALL_INVALID_BUNDLE_FILE; } - if (!CheckFileSize(realPath, Constants::MAX_HAP_SIZE)) { + if(!CheckFileSize(realPath, Constants::MAX_HAP_SIZE)) { APP_LOGE("file size is larger than max size Max size is: %{public}d", Constants::MAX_HAP_SIZE); return ERR_APPEXECFWK_INSTALL_INVALID_HAP_SIZE; } @@ -83,11 +83,11 @@ bool BundleUtil::CheckFileName(const std::string &fileName) bool BundleUtil::CheckFileSize(const std::string &bundlePath, const int32_t fileSize) { - struct stat fileInfo = {0}; - if (stat(bundlePath.c_str(), &fileInfo) != 0) { + struct stat fileInfo = { 0 }; + if (stat(bundlePath.c_str(), &fileInfo) != 0) { APP_LOGE("call stat error"); - return false; - } + return false; + } if (fileInfo.st_size > fileSize) { return false; } diff --git a/services/bundlemgr/src/inner_bundle_info.cpp b/services/bundlemgr/src/inner_bundle_info.cpp index fe8119bca3ade73a9f6ce9720e70d85152b9f851..0e4b1182f750385ff5a7fb6a2066057164b79f13 100644 --- a/services/bundlemgr/src/inner_bundle_info.cpp +++ b/services/bundlemgr/src/inner_bundle_info.cpp @@ -74,40 +74,48 @@ InnerBundleInfo::~InnerBundleInfo() void to_json(nlohmann::json &jsonObject, const Distro &distro) { - jsonObject = - nlohmann::json{{ProfileReader::BUNDLE_MODULE_PROFILE_KEY_DELIVERY_WITH_INSTALL, distro.deliveryWithInstall}, + jsonObject = nlohmann::json{ + {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_DELIVERY_WITH_INSTALL, distro.deliveryWithInstall}, {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_MODULE_NAME, distro.moduleName}, {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_MODULE_TYPE, distro.moduleType}, - {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_MODULE_INSTALLATION_FREE, distro.installationFree}}; + {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_MODULE_INSTALLATION_FREE, distro.installationFree} + }; } void to_json(nlohmann::json &jsonObject, const UsedScene &usedScene) { - jsonObject = nlohmann::json{{ProfileReader::BUNDLE_MODULE_PROFILE_KEY_REQ_PERMISSIONS_ABILITY, usedScene.ability}, - {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_REQ_PERMISSIONS_WHEN, usedScene.when}}; + jsonObject = nlohmann::json{ + {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_REQ_PERMISSIONS_ABILITY, usedScene.ability}, + {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_REQ_PERMISSIONS_WHEN, usedScene.when} + }; } void to_json(nlohmann::json &jsonObject, const ReqPermission &reqPermission) { - jsonObject = nlohmann::json{{ProfileReader::BUNDLE_MODULE_PROFILE_KEY_REQ_PERMISSIONS_NAME, reqPermission.name}, + jsonObject = nlohmann::json{ + {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_REQ_PERMISSIONS_NAME, reqPermission.name}, {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_REQ_PERMISSIONS_REASON, reqPermission.reason}, - {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_REQ_PERMISSIONS_USEDSCENE, reqPermission.usedScene}}; + {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_REQ_PERMISSIONS_USEDSCENE, reqPermission.usedScene} + }; } void to_json(nlohmann::json &jsonObject, const DefPermission &defPermission) { - jsonObject = nlohmann::json{{ProfileReader::BUNDLE_MODULE_PROFILE_KEY_DEF_PERMISSIONS_NAME, defPermission.name}, + jsonObject = nlohmann::json{ + {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_DEF_PERMISSIONS_NAME, defPermission.name}, {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_DEF_PERMISSIONS_GRANTMODE, defPermission.grantMode}, {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_DEF_PERMISSIONS_AVAILABLESCOPE, defPermission.availableScope}, {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_DEF_PERMISSIONS_LABEL, defPermission.label}, {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_DEF_PERMISSIONS_LABEL_ID, defPermission.labelId}, {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_DEF_PERMISSIONS_DESCRIPTION, defPermission.description}, - {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_DEF_PERMISSIONS_DESCRIPTION_ID, defPermission.descriptionId}}; + {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_DEF_PERMISSIONS_DESCRIPTION_ID, defPermission.descriptionId} + }; } void to_json(nlohmann::json &jsonObject, const InnerModuleInfo &info) { - jsonObject = nlohmann::json{{MODULE_PACKAGE, info.modulePackage}, + jsonObject = nlohmann::json{ + {MODULE_PACKAGE, info.modulePackage}, {MODULE_NAME, info.moduleName}, {MODULE_PATH, info.modulePath}, {MODULE_DATA_DIR, info.moduleDataDir}, @@ -126,23 +134,28 @@ void to_json(nlohmann::json &jsonObject, const InnerModuleInfo &info) {MODULE_DEF_PERMS, info.defPermissions}, {MODULE_ABILITY_KEYS, info.abilityKeys}, {MODULE_SKILL_KEYS, info.skillKeys}, - {MODULE_MAIN_ABILITY, info.mainAbility}}; + {MODULE_MAIN_ABILITY, info.mainAbility} + }; } void to_json(nlohmann::json &jsonObject, const SkillUri &uri) { - jsonObject = nlohmann::json{{ProfileReader::BUNDLE_MODULE_PROFILE_KEY_SCHEME, uri.scheme}, + jsonObject = nlohmann::json{ + {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_SCHEME, uri.scheme}, {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_HOST, uri.host}, {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_PORT, uri.port}, {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_PATH, uri.path}, - {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_TYPE, uri.type}}; + {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_TYPE, uri.type} + }; } void to_json(nlohmann::json &jsonObject, const Skill &skill) { - jsonObject = nlohmann::json{{ProfileReader::BUNDLE_MODULE_PROFILE_KEY_ACTIONS, skill.actions}, + jsonObject = nlohmann::json{ + {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_ACTIONS, skill.actions}, {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_ENTITIES, skill.entities}, - {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_URIS, skill.uris}}; + {ProfileReader::BUNDLE_MODULE_PROFILE_KEY_URIS, skill.uris} + }; } void InnerBundleInfo::ToJson(nlohmann::json &jsonObject) const @@ -163,7 +176,7 @@ void InnerBundleInfo::ToJson(nlohmann::json &jsonObject) const jsonObject[MAIN_ABILITY] = mainAbility_; jsonObject[APP_FEATURE] = appFeature_; jsonObject[HAS_ENTRY] = hasEntry_; - jsonObject[MODULE_FORMS] = formInfos_; + jsonObject[MODULE_FORMS] = formInfos_; jsonObject[MODULE_SHORTCUT] = shortcutInfos_; } @@ -578,10 +591,22 @@ int32_t InnerBundleInfo::FromJson(const nlohmann::json &jsonObject) true, ProfileReader::parseResult, ArrayType::NOT_ARRAY); - GetValueIfFindKey( - jsonObject, jsonObjectEnd, UID, uid_, JsonType::NUMBER, true, ProfileReader::parseResult, ArrayType::NOT_ARRAY); - GetValueIfFindKey( - jsonObject, jsonObjectEnd, GID, gid_, JsonType::NUMBER, true, ProfileReader::parseResult, ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + UID, + uid_, + JsonType::NUMBER, + true, + ProfileReader::parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey(jsonObject, + jsonObjectEnd, + GID, + gid_, + JsonType::NUMBER, + true, + ProfileReader::parseResult, + ArrayType::NOT_ARRAY); GetValueIfFindKey(jsonObject, jsonObjectEnd, BASE_DATA_DIR, @@ -670,15 +695,15 @@ int32_t InnerBundleInfo::FromJson(const nlohmann::json &jsonObject) true, ProfileReader::parseResult, ArrayType::NOT_ARRAY); - GetValueIfFindKey>>(jsonObject, - jsonObjectEnd, - MODULE_FORMS, - formInfos_, - JsonType::OBJECT, - true, - ProfileReader::parseResult, - ArrayType::NOT_ARRAY); - GetValueIfFindKey>(jsonObject, + GetValueIfFindKey>>(jsonObject, + jsonObjectEnd, + MODULE_FORMS, + formInfos_, + JsonType::OBJECT, + true, + ProfileReader::parseResult, + ArrayType::NOT_ARRAY); + GetValueIfFindKey>(jsonObject, jsonObjectEnd, MODULE_SHORTCUT, shortcutInfos_, @@ -710,7 +735,7 @@ std::optional> InnerBundleInfo::FindSkills(const std::string if (skills.empty()) { return std::nullopt; } - return std::optional>{skills}; + return std::optional> {skills}; } std::optional InnerBundleInfo::FindHapModuleInfo(const std::string &modulePackage) const @@ -935,14 +960,14 @@ void InnerBundleInfo::GetBundleInfo(const BundleFlag flag, BundleInfo &bundleInf [](const auto &p) { return p.name; }); bundleInfo.hapModuleNames.emplace_back(info.second.modulePackage); auto hapmoduleinfo = FindHapModuleInfo(info.second.modulePackage); - if (!hapmoduleinfo) { - APP_LOGE("can not find hapmoduleinfo %{public}s", info.second.moduleName.c_str()); - } else { + if (hapmoduleinfo) { bundleInfo.hapModuleInfos.emplace_back(*hapmoduleinfo); bundleInfo.moduleNames.emplace_back(info.second.moduleName); bundleInfo.moduleDirs.emplace_back(info.second.modulePath); bundleInfo.modulePublicDirs.emplace_back(info.second.moduleDataDir); bundleInfo.moduleResPaths.emplace_back(info.second.moduleResPath); + } else { + APP_LOGE("can not find hapmoduleinfo %{public}s", info.second.moduleName.c_str()); } if (info.second.isEntry) { bundleInfo.mainEntry = info.second.modulePackage; @@ -974,29 +999,29 @@ bool InnerBundleInfo::CheckSpecialMetaData(const std::string &metaData) const void InnerBundleInfo::GetFormsInfoByModule(const std::string &moduleName, std::vector &formInfos) const { - for (const auto &data : formInfos_) { - for (auto &form : data.second) { - if (form.moduleName == moduleName) { - formInfos.emplace_back(form); - } - } - } + for (const auto &data : formInfos_) { + for (auto &form : data.second) { + if (form.moduleName == moduleName) { + formInfos.emplace_back(form); + } + } + } } void InnerBundleInfo::GetFormsInfoByApp(std::vector &formInfos) const { - for (const auto &data : formInfos_) { - for (auto &form : data.second) { - formInfos.emplace_back(form); - } - } + for (const auto &data : formInfos_) { + for (auto &form : data.second) { + formInfos.emplace_back(form); + } + } } void InnerBundleInfo::GetShortcutInfos(std::vector &shortcutInfos) const { for (const auto &shortcut : shortcutInfos_) { - shortcutInfos.emplace_back(shortcut.second); - } + shortcutInfos.emplace_back(shortcut.second); + } } std::optional InnerBundleInfo::GetInnerModuleInfoByModuleName(const std::string &moduleName) const diff --git a/services/bundlemgr/src/installd/installd_host_impl.cpp b/services/bundlemgr/src/installd/installd_host_impl.cpp index e12775312a225d0ea23a30a1f9e025c44bdbb0e7..b850b712abb444dd6dc3fe21a55ee7c6a67f4e13 100644 --- a/services/bundlemgr/src/installd/installd_host_impl.cpp +++ b/services/bundlemgr/src/installd/installd_host_impl.cpp @@ -173,15 +173,24 @@ ErrCode InstalldHostImpl::CreateModuleDataDir( for (auto &abilityDir : abilityDirs) { if (!InstalldOperator::MkOwnerDir( - createDir + abilityDir + Constants::PATH_SEPARATOR + Constants::DATA_DIR, true, uid, gid)) { + createDir + abilityDir + Constants::PATH_SEPARATOR + Constants::DATA_DIR, + true, + uid, + gid)) { return ERR_APPEXECFWK_INSTALLD_CREATE_DIR_FAILED; } if (!InstalldOperator::MkOwnerDir( - createDir + abilityDir + Constants::PATH_SEPARATOR + Constants::CACHE_DIR, true, uid, gid)) { + createDir + abilityDir + Constants::PATH_SEPARATOR + Constants::CACHE_DIR, + true, + uid, + gid)) { return ERR_APPEXECFWK_INSTALLD_CREATE_DIR_FAILED; } if (!InstalldOperator::MkOwnerDir( - createDir + abilityDir + Constants::PATH_SEPARATOR + Constants::DATA_BASE_DIR, true, uid, gid)) { + createDir + abilityDir + Constants::PATH_SEPARATOR + Constants::DATA_BASE_DIR, + true, + uid, + gid)) { return ERR_APPEXECFWK_INSTALLD_CREATE_DIR_FAILED; } if (!InstalldOperator::MkOwnerDir( diff --git a/services/bundlemgr/src/kvstore_death_recipient_callback.cpp b/services/bundlemgr/src/kvstore_death_recipient_callback.cpp index f44f619917be036ad5330d5100f97369217997ac..3b1eb834f4b88b23da6b25156fb37dd1cb254896 100644 --- a/services/bundlemgr/src/kvstore_death_recipient_callback.cpp +++ b/services/bundlemgr/src/kvstore_death_recipient_callback.cpp @@ -27,9 +27,9 @@ namespace AppExecFwk { namespace { const int32_t CHECK_TIMES = 300; -const int32_t CHECK_INTERVAL = 100000; // 100ms +const int32_t CHECK_INTERVAL = 100000; // 100ms -} // namespace +} // namespace KvStoreDeathRecipientCallback::KvStoreDeathRecipientCallback() { @@ -63,7 +63,7 @@ void KvStoreDeathRecipientCallback::OnRemoteDied() // init kvStore. if (dataStorage && dataStorage->ResetKvStore()) { // register data change listener again. - // dataStorage->RegisterChangeListener(); + //dataStorage->RegisterChangeListener(); APP_LOGI("current times is %{public}d", times); // auto service = DelayedSingleton::GetInstance(); // std::shared_ptr handler = service->GetEventHandler(); @@ -79,5 +79,5 @@ void KvStoreDeathRecipientCallback::OnRemoteDied() APP_LOGI("OnRemoteDied, register data change listener end"); } -} // namespace AppExecFwk -} // namespace OHOS \ No newline at end of file +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/bundlemgr/src/module_usage_data_storage.cpp b/services/bundlemgr/src/module_usage_data_storage.cpp index 049dd08db23344be1b2c22204a416a6c5dc3cb94..5044b12a8f23c9e0e55051b3471ddbddd2efdedf 100644 --- a/services/bundlemgr/src/module_usage_data_storage.cpp +++ b/services/bundlemgr/src/module_usage_data_storage.cpp @@ -31,6 +31,7 @@ using namespace OHOS::DistributedKv; namespace OHOS { namespace AppExecFwk { namespace { + const int32_t MAX_TIMES = 6000; // tem min const int32_t SLEEP_INTERVAL = 100 * 1000; // 100ms const std::string POUND_KEY_SEPARATOR = "#"; @@ -320,8 +321,8 @@ Status ModuleUsageRecordStorage::GetKvStore() { Status status; Options options = { - .createIfMissing = true, .encrypt = false, .autoSync = true, .kvStoreType = KvStoreType::SINGLE_VERSION - }; + .createIfMissing = true, .encrypt = false, .autoSync = true, .kvStoreType = KvStoreType::SINGLE_VERSION}; + options.schema = SCHEMA_DEFINE; dataManager_.GetSingleKvStore( options, appId_, storeId_, [this, &status](Status paramStatus, std::unique_ptr singleKvStore) { diff --git a/services/bundlemgr/test/mock/include/json_constants.h b/services/bundlemgr/test/mock/include/json_constants.h index 6a9af870d25d68086af83d49be976c3a7d7475b2..7019d89acf34eeadbbb7e47eef3e63608ee9cbdf 100644 --- a/services/bundlemgr/test/mock/include/json_constants.h +++ b/services/bundlemgr/test/mock/include/json_constants.h @@ -21,6 +21,7 @@ namespace OHOS { namespace AppExecFwk { namespace JsonConstants { + const nlohmann::json NOT_STRING_TYPE = R"( { "number": 234, @@ -64,6 +65,7 @@ const nlohmann::json NOT_ARRAY_TYPE = R"( "object": {} } )"_json; + } // namespace JsonConstants } // namespace AppExecFwk } // namespace OHOS diff --git a/services/bundlemgr/test/mock/include/mock_ability_mgr_host.h b/services/bundlemgr/test/mock/include/mock_ability_mgr_host.h index e4fe336ac08f2251b91eb8d6d08a96829a26b0cc..df955fb47263a5e3626369d68303e92d2459305a 100644 --- a/services/bundlemgr/test/mock/include/mock_ability_mgr_host.h +++ b/services/bundlemgr/test/mock/include/mock_ability_mgr_host.h @@ -180,7 +180,7 @@ public: } int SetMissionDescriptionInfo( - const sptr &token, const MissionDescriptionInfo &missionDescInfo) override + const sptr &token, const MissionDescriptionInfo &missionDescriptionInfo) override { return 0; } diff --git a/services/bundlemgr/test/mock/include/mock_bundle_status.h b/services/bundlemgr/test/mock/include/mock_bundle_status.h index 4ee00dce9985d236233cb0f781244d0e761a5c3f..fb7057b08b99e9fd06bc48b6587bd7d76adc7d86 100644 --- a/services/bundlemgr/test/mock/include/mock_bundle_status.h +++ b/services/bundlemgr/test/mock/include/mock_bundle_status.h @@ -24,6 +24,7 @@ namespace OHOS { namespace AppExecFwk { + class MockBundleStatus : public IBundleStatusCallback { public: MockBundleStatus() = default; @@ -31,9 +32,9 @@ public: virtual void OnBundleStateChanged(const uint8_t installType, const int32_t resultCode, const std::string &resultMsg, const std::string &bundleName) override; - virtual void OnBundleAdded(const std::string &bundleName, const int userId) override{}; - virtual void OnBundleUpdated(const std::string &bundleName, const int userId) override{}; - virtual void OnBundleRemoved(const std::string &bundleName, const int userId) override{}; + virtual void OnBundleAdded(const std::string &bundleName, const int userId) override {}; + virtual void OnBundleUpdated(const std::string &bundleName, const int userId) override {}; + virtual void OnBundleRemoved(const std::string &bundleName, const int userId) override {}; virtual sptr AsObject() override; int32_t GetResultCode(); @@ -42,6 +43,7 @@ private: DISALLOW_COPY_AND_MOVE(MockBundleStatus); }; + } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_TEST_MOCK_INCLUDE_MOCK_BUNDLE_STATUS_H \ No newline at end of file diff --git a/services/bundlemgr/test/mock/include/mock_clean_cache.h b/services/bundlemgr/test/mock/include/mock_clean_cache.h index 337513455db62d023951b5fb782fbc660dce0a5e..9dfa562afa0f86dbc0b5793518be6ebb4dfb4887 100644 --- a/services/bundlemgr/test/mock/include/mock_clean_cache.h +++ b/services/bundlemgr/test/mock/include/mock_clean_cache.h @@ -24,6 +24,7 @@ namespace OHOS { namespace AppExecFwk { + class MockCleanCache : public ICleanCacheCallback { public: MockCleanCache() = default; @@ -38,6 +39,7 @@ private: DISALLOW_COPY_AND_MOVE(MockCleanCache); }; + } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_TEST_MOCK_INCLUDE_MOCK_CLEAN_CACHE_H \ No newline at end of file diff --git a/services/bundlemgr/test/mock/include/mock_status_receiver.h b/services/bundlemgr/test/mock/include/mock_status_receiver.h index 2eaceceed38ab6fc83e5d404c723cb959224103a..1085c272fc78175113298703d2dc084f5d958179 100644 --- a/services/bundlemgr/test/mock/include/mock_status_receiver.h +++ b/services/bundlemgr/test/mock/include/mock_status_receiver.h @@ -24,6 +24,7 @@ namespace OHOS { namespace AppExecFwk { + class MockStatusReceiver : public IStatusReceiver { public: MockStatusReceiver() = default; @@ -39,6 +40,7 @@ private: DISALLOW_COPY_AND_MOVE(MockStatusReceiver); }; + } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_SERVICES_BUNDLEMGR_TEST_MOCK_INCLUDE_MOCK_STATUS_RECEIVER_H \ No newline at end of file diff --git a/services/bundlemgr/test/mock/src/mock_bundle_status.cpp b/services/bundlemgr/test/mock/src/mock_bundle_status.cpp index f9c356db8a633307e9d453dbc27c986c3790cc5a..6797ae08162a9b590a27ef7b70588a399e9ece1e 100644 --- a/services/bundlemgr/test/mock/src/mock_bundle_status.cpp +++ b/services/bundlemgr/test/mock/src/mock_bundle_status.cpp @@ -17,6 +17,7 @@ namespace OHOS { namespace AppExecFwk { + void MockBundleStatus::OnBundleStateChanged( const uint8_t installType, const int32_t resultCode, const std::string &resultMsg, const std::string &bundleName) { @@ -38,5 +39,6 @@ int32_t MockBundleStatus::GetResultCode() return future.get(); } } + } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/bundlemgr/test/mock/src/mock_clean_cache.cpp b/services/bundlemgr/test/mock/src/mock_clean_cache.cpp index 374009c4d0d7632e7a1e31885d373970f2ecd181..4440d44bea95179a6ba355d45dd4797f2448872f 100644 --- a/services/bundlemgr/test/mock/src/mock_clean_cache.cpp +++ b/services/bundlemgr/test/mock/src/mock_clean_cache.cpp @@ -17,6 +17,7 @@ namespace OHOS { namespace AppExecFwk { + void MockCleanCache::OnCleanCacheFinished(bool succeeded) { signal_.set_value(succeeded); @@ -33,5 +34,6 @@ bool MockCleanCache::GetResultCode() future.wait(); return future.get(); } + } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/bundlemgr/test/mock/src/mock_status_receiver.cpp b/services/bundlemgr/test/mock/src/mock_status_receiver.cpp index 3e843a6d68b2d55760ce6f2f1c75df6b64cecf97..cd8b57538f6d9e8c6ed6f7b61ceffd5616c5f161 100644 --- a/services/bundlemgr/test/mock/src/mock_status_receiver.cpp +++ b/services/bundlemgr/test/mock/src/mock_status_receiver.cpp @@ -17,6 +17,7 @@ namespace OHOS { namespace AppExecFwk { + void MockStatusReceiver::OnFinished(const int32_t resultCode, [[maybe_unused]] const std::string &resultMsg) { signal_.set_value(resultCode); @@ -38,5 +39,6 @@ int32_t MockStatusReceiver::GetResultCode() future.wait(); return future.get(); } + } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/bundlemgr/test/mock/src/system_ability_helper.cpp b/services/bundlemgr/test/mock/src/system_ability_helper.cpp index 87df614aeaf2c37c07da4c365e8898b49962beea..92c65c289034cb8f3a72484530e1c67dc7241b79 100644 --- a/services/bundlemgr/test/mock/src/system_ability_helper.cpp +++ b/services/bundlemgr/test/mock/src/system_ability_helper.cpp @@ -24,7 +24,9 @@ namespace OHOS { namespace AppExecFwk { namespace { + std::map> g_abilities; + } // namespace sptr SystemAbilityHelper::GetSystemAbility(const int32_t systemAbilityId) @@ -60,5 +62,6 @@ bool SystemAbilityHelper::RemoveSystemAbility(const int32_t systemAbilityId) // mock helper always return true. return true; } + } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/bundlemgr/test/unittest/bms_bundle_installer_test/bms_bundle_installer_test.cpp b/services/bundlemgr/test/unittest/bms_bundle_installer_test/bms_bundle_installer_test.cpp index 34eaf96110272c5598ef500ab0375d54800d278a..58cc1e42ef71fd48cabd3cb30dd563c1e83620aa 100755 --- a/services/bundlemgr/test/unittest/bms_bundle_installer_test/bms_bundle_installer_test.cpp +++ b/services/bundlemgr/test/unittest/bms_bundle_installer_test/bms_bundle_installer_test.cpp @@ -42,6 +42,7 @@ using namespace OHOS; using OHOS::DelayedSingleton; namespace { + const std::string BUNDLE_NAME = "com.example.l3jsdemo"; const std::string RESOURCE_ROOT_PATH = "/data/test/resource/bms/install_bundle/"; const std::string INVALID_PATH = "/install_bundle/"; @@ -56,6 +57,7 @@ const std::string ROOT_DIR = "/data/accounts"; const int32_t ROOT_UID = 0; const int32_t USERID = 0; const std::string INSTALL_THREAD = "TestInstall"; + } // namespace class BmsBundleInstallerTest : public testing::Test { diff --git a/services/bundlemgr/test/unittest/bms_bundle_parser_test/bms_bundle_parser_test.cpp b/services/bundlemgr/test/unittest/bms_bundle_parser_test/bms_bundle_parser_test.cpp index b2bab7ae5b1e8b713459a87b52a5c6a360bc6288..8f1aa7514c2417f95768b403b00701f92cf7daca 100755 --- a/services/bundlemgr/test/unittest/bms_bundle_parser_test/bms_bundle_parser_test.cpp +++ b/services/bundlemgr/test/unittest/bms_bundle_parser_test/bms_bundle_parser_test.cpp @@ -32,6 +32,7 @@ using namespace OHOS::AppExecFwk::Constants; using namespace OHOS::AppExecFwk::ProfileReader; namespace { + const std::string RESOURCE_ROOT_PATH = "/data/test/resource/bms/parse_bundle/"; const std::string NEW_APP = "new"; const std::string BREAK_ZIP = "break_zip"; @@ -190,6 +191,7 @@ const nlohmann::json CONFIG_JSON = R"( } } )"_json; + } // namespace class BmsBundleParserTest : public testing::Test { @@ -207,7 +209,6 @@ protected: void CheckProfilePermission(const nlohmann::json &checkedProfileJson) const; void CheckProfileForms(const nlohmann::json &checkedProfileJson) const; void CheckProfileShortcut(const nlohmann::json &checkedProfileJson) const; - protected: std::ostringstream pathStream_; }; @@ -893,7 +894,7 @@ HWTEST_F(BmsBundleParserTest, TestParse_2300, Function | SmallTest | Level1) HWTEST_F(BmsBundleParserTest, TestParse_2400, Function | SmallTest | Level1) { nlohmann::json errorFormsJson = CONFIG_JSON; - errorFormsJson[BUNDLE_PROFILE_KEY_MODULE][BUNDLE_MODULE_PROFILE_KEY_ABILITIES] = R"( + errorFormsJson[BUNDLE_PROFILE_KEY_MODULE][BUNDLE_MODULE_PROFILE_KEY_ABILITIES]= R"( [{ "skills": [ { diff --git a/services/bundlemgr/test/unittest/bms_bundle_permission_test/bms_bundle_permission_test.cpp b/services/bundlemgr/test/unittest/bms_bundle_permission_test/bms_bundle_permission_test.cpp index fa94fae3617236c8a4bc4fa4d55bbc2c7e8fc995..a0046249e04518656f44d2538c757eae24b102ba 100644 --- a/services/bundlemgr/test/unittest/bms_bundle_permission_test/bms_bundle_permission_test.cpp +++ b/services/bundlemgr/test/unittest/bms_bundle_permission_test/bms_bundle_permission_test.cpp @@ -93,62 +93,78 @@ const std::string DEFPERMISSION_NAME18 = "com.myability.permission.MYPERMISSION1 const std::string DEF_LABEL1 = "MockDefPermissionBundleSystemGrant"; const std::string DEF_LABEL2 = "MockDefPermissionBundleUserGrant"; const std::string DEF_LABEL3 = "MockSameDefPermissionNameBundleSystemGrant"; -const DefPermission DEFPERMISSION_SYSTEM1 = {.name = DEFPERMISSION_NAME1, +const DefPermission DEFPERMISSION_SYSTEM1 = { + .name = DEFPERMISSION_NAME1, .grantMode = "system_grant", .availableScope = {"signature"}, .label = DEF_LABEL1, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1}; -const DefPermission DEFPERMISSION_SYSTEM2 = {.name = DEFPERMISSION_NAME2, + .descriptionId = 1 +}; +const DefPermission DEFPERMISSION_SYSTEM2 = { + .name = DEFPERMISSION_NAME2, .grantMode = "system_grant", .availableScope = {"signature"}, .label = DEF_LABEL1, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1}; -const DefPermission DEFPERMISSION_SYSTEM3 = {.name = DEFPERMISSION_NAME3, + .descriptionId = 1 +}; +const DefPermission DEFPERMISSION_SYSTEM3 = { + .name = DEFPERMISSION_NAME3, .grantMode = "system_grant", .availableScope = {"signature"}, .label = DEF_LABEL1, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1}; -const DefPermission DEFPERMISSION_UPDATE1 = {.name = DEFPERMISSION_NAME1, + .descriptionId = 1 +}; +const DefPermission DEFPERMISSION_UPDATE1 = { + .name = DEFPERMISSION_NAME1, .grantMode = "user_grant", .availableScope = {"signature"}, .label = DEF_LABEL2, .labelId = 10, .description = DEF_LABEL2, - .descriptionId = 10}; -const DefPermission DEFPERMISSION_UPDATE2 = {.name = DEFPERMISSION_NAME2, + .descriptionId = 10 +}; +const DefPermission DEFPERMISSION_UPDATE2 = { + .name = DEFPERMISSION_NAME2, .grantMode = "user_grant", .availableScope = {"signature"}, .label = DEF_LABEL2, .labelId = 10, .description = DEF_LABEL2, - .descriptionId = 10}; -const DefPermission DEFPERMISSION_UPDATE3 = {.name = DEFPERMISSION_NAME3, + .descriptionId = 10 +}; +const DefPermission DEFPERMISSION_UPDATE3 = { + .name = DEFPERMISSION_NAME3, .grantMode = "user_grant", .availableScope = {"signature"}, .label = DEF_LABEL2, .labelId = 10, .description = DEF_LABEL2, - .descriptionId = 10}; -const DefPermission DEFPERMISSION_EMAIL = {.name = DEFPERMISSION_NAME_EMAIL, + .descriptionId = 10 +}; +const DefPermission DEFPERMISSION_EMAIL = { + .name = DEFPERMISSION_NAME_EMAIL, .grantMode = "system_grant", .availableScope = {""}, .label = DEF_LABEL1, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1}; -const DefPermission DEFPERMISSION_MUSIC = {.name = DEFPERMISSION_NAME_MUSIC, + .descriptionId = 1 +}; +const DefPermission DEFPERMISSION_MUSIC = { + .name = DEFPERMISSION_NAME_MUSIC, .grantMode = "system_grant", .availableScope = {""}, .label = DEF_LABEL1, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1}; + .descriptionId = 1 +}; const DefPermission DEFPERMISSION_APP = {.name = DEFPERMISSION_NAME_APP, .grantMode = "system_grant", .availableScope = {""}, @@ -156,119 +172,173 @@ const DefPermission DEFPERMISSION_APP = {.name = DEFPERMISSION_NAME_APP, .labelId = 1, .description = DEF_LABEL1, .descriptionId = 1}; -const DefPermission DEFPERMISSION_WECHAT = {.name = DEFPERMISSION_NAME_WECHAT, +const DefPermission DEFPERMISSION_WECHAT = { + .name = DEFPERMISSION_NAME_WECHAT, .grantMode = "system_grant", .availableScope = {""}, .label = DEF_LABEL1, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1}; -const DefPermission DEFPERMISSION_NOAVAILIAVLE1 = {.name = DEFPERMISSION_NAME4, + .descriptionId = 1 +}; +const DefPermission DEFPERMISSION_NOAVAILIAVLE1 = { + .name = DEFPERMISSION_NAME4, .grantMode = "system_grant", .availableScope = {""}, .label = DEF_LABEL1, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1}; -const DefPermission DEFPERMISSION_NOAVAILIAVLE2 = {.name = DEFPERMISSION_NAME5, + .descriptionId = 1 +}; +const DefPermission DEFPERMISSION_NOAVAILIAVLE2 = { + .name = DEFPERMISSION_NAME5, .grantMode = "system_grant", .availableScope = {""}, .label = DEF_LABEL1, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1}; -const DefPermission DEFPERMISSION_NOAVAILIAVLE3 = {.name = DEFPERMISSION_NAME6, + .descriptionId = 1 +}; +const DefPermission DEFPERMISSION_NOAVAILIAVLE3 = { + .name = DEFPERMISSION_NAME6, .grantMode = "system_grant", .availableScope = {""}, .label = DEF_LABEL1, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1}; -const DefPermission DEFPERMISSION_USERGRANT1 = {.name = DEFPERMISSION_NAME10, + .descriptionId = 1 +}; +const DefPermission DEFPERMISSION_USERGRANT1 = { + .name = DEFPERMISSION_NAME10, .grantMode = "user_grant", .availableScope = {"signature"}, .label = DEF_LABEL2, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1}; -const DefPermission DEFPERMISSION_USERGRANT2 = {.name = DEFPERMISSION_NAME11, + .descriptionId = 1 +}; +const DefPermission DEFPERMISSION_USERGRANT2 = { + .name = DEFPERMISSION_NAME11, .grantMode = "user_grant", .availableScope = {"signature"}, .label = DEF_LABEL2, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1}; -const DefPermission DEFPERMISSION_USERGRANT3 = {.name = DEFPERMISSION_NAME12, + .descriptionId = 1 +}; +const DefPermission DEFPERMISSION_USERGRANT3 = { + .name = DEFPERMISSION_NAME12, .grantMode = "user_grant", .availableScope = {"signature"}, .label = DEF_LABEL2, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1}; -const DefPermission DEFPERMISSION_USERGRANT4 = {.name = DEFPERMISSION_NAME13, + .descriptionId = 1 +}; +const DefPermission DEFPERMISSION_USERGRANT4 = { + .name = DEFPERMISSION_NAME13, .grantMode = "user_grant", .availableScope = {"signature"}, .label = DEF_LABEL2, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1}; -const DefPermission DEFPERMISSION_USERGRANT5 = {.name = DEFPERMISSION_NAME14, + .descriptionId = 1 +}; +const DefPermission DEFPERMISSION_USERGRANT5 = { + .name = DEFPERMISSION_NAME14, .grantMode = "user_grant", .availableScope = {"signature"}, .label = DEF_LABEL2, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1}; -const DefPermission DEFPERMISSION_USERGRANT6 = {.name = DEFPERMISSION_NAME15, + .descriptionId = 1 +}; +const DefPermission DEFPERMISSION_USERGRANT6 = { + .name = DEFPERMISSION_NAME15, .grantMode = "user_grant", .availableScope = {"signature"}, .label = DEF_LABEL2, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1}; -const DefPermission DEFPERMISSION_SAMENAME1 = {.name = DEFPERMISSION_NAME10, + .descriptionId = 1 +}; +const DefPermission DEFPERMISSION_SAMENAME1 = { + .name = DEFPERMISSION_NAME10, .grantMode = "system_grant", .availableScope = {"signature"}, .label = DEF_LABEL3, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1}; -const DefPermission DEFPERMISSION_SAMENAME2 = {.name = DEFPERMISSION_NAME11, + .descriptionId = 1 +}; +const DefPermission DEFPERMISSION_SAMENAME2 = { + .name = DEFPERMISSION_NAME11, .grantMode = "system_grant", .availableScope = {"signature"}, .label = DEF_LABEL3, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1}; -const DefPermission DEFPERMISSION_SAME2 = {.name = DEFPERMISSION_NAME17, + .descriptionId = 1 +}; +const DefPermission DEFPERMISSION_SAME2 = { + .name = DEFPERMISSION_NAME17, .grantMode = "system_grant", .availableScope = {"signature"}, .label = DEF_LABEL3, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1}; -const DefPermission DEFPERMISSION_SAME1 = {.name = DEFPERMISSION_NAME16, + .descriptionId = 1 +}; +const DefPermission DEFPERMISSION_SAME1 = { + .name = DEFPERMISSION_NAME16, .grantMode = "system_grant", .availableScope = {"signature"}, .label = DEF_LABEL3, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1}; -const DefPermission DEFPERMISSION_SAME3 = {.name = DEFPERMISSION_NAME18, + .descriptionId = 1 +}; +const DefPermission DEFPERMISSION_SAME3 = { + .name = DEFPERMISSION_NAME18, .grantMode = "system_grant", .availableScope = {"signature"}, .label = DEF_LABEL3, .labelId = 1, .description = DEF_LABEL1, - .descriptionId = 1}; + .descriptionId = 1 +}; const ReqPermission REQPERMISSION1 = { - .name = DEFPERMISSION_NAME_EMAIL, .reason = "reason", .usedScene = {.ability = {"ability"}, .when = "when"}}; + .name = DEFPERMISSION_NAME_EMAIL, + .reason = "reason", + .usedScene = { + .ability = {"ability"}, + .when = "when" + } +}; const ReqPermission REQPERMISSION2 = { - .name = DEFPERMISSION_NAME_WECHAT, .reason = "reason", .usedScene = {.ability = {"ability"}, .when = "when"}}; + .name = DEFPERMISSION_NAME_WECHAT, + .reason = "reason", + .usedScene = { + .ability = {"ability"}, + .when = "when" + } +}; const ReqPermission REQPERMISSION3 = { - .name = DEFPERMISSION_NAME_APP, .reason = "reason", .usedScene = {.ability = {"ability"}, .when = "when"}}; + .name = DEFPERMISSION_NAME_APP, + .reason = "reason", + .usedScene = { + .ability = {"ability"}, + .when = "when" + } +}; const ReqPermission REQPERMISSION4 = { - .name = DEFPERMISSION_NAME_MUSIC, .reason = "reason", .usedScene = {.ability = {"ability"}, .when = "when"}}; + .name = DEFPERMISSION_NAME_MUSIC, + .reason = "reason", + .usedScene = { + .ability = {"ability"}, + .when = "when" + } +}; } // namespace class BmsBundlePermissionTest : public testing::Test { diff --git a/services/bundlemgr/test/unittest/bms_bundle_uninstaller_test/bms_bundle_uninstaller_test.cpp b/services/bundlemgr/test/unittest/bms_bundle_uninstaller_test/bms_bundle_uninstaller_test.cpp index 46e5dad9c0007fb8a9a88530f1881f4c42b0e485..4de4e6cd5921e536244eccdee2d361815f515894 100755 --- a/services/bundlemgr/test/unittest/bms_bundle_uninstaller_test/bms_bundle_uninstaller_test.cpp +++ b/services/bundlemgr/test/unittest/bms_bundle_uninstaller_test/bms_bundle_uninstaller_test.cpp @@ -38,6 +38,7 @@ using namespace OHOS; using namespace OHOS::AppExecFwk; namespace { + const std::string BUNDLE_NAME = "com.example.l3jsdemo"; const std::string MODULE_PACKAGE = "com.example.l3jsdemo"; const std::string MODULE_PACKAGE1 = "com.example.l3jsdemo1"; @@ -54,6 +55,7 @@ const std::string MODULE_CODE_DIR1 = "/data/accounts/account_0/applications/com. const std::string ROOT_DIR = "/data/accounts"; const std::string DB_FILE_PATH = "/data/bundlemgr"; const int32_t ROOT_UID = 0; + } // namespace class BmsBundleUninstallerTest : public testing::Test { @@ -83,7 +85,6 @@ public: const std::shared_ptr GetBundleMgrService() const; void ClearBundleInfoInDb(); void DeleteInstallFiles(); - private: std::shared_ptr installdService_ = std::make_unique(); std::shared_ptr bundleMgrService_ = DelayedSingleton::GetInstance(); @@ -295,11 +296,11 @@ void BmsBundleUninstallerTest::ClearBundleInfoInDb() return; } auto dataMgt = bundleMgrService_->GetDataMgr(); - if (dataMgt == nullptr) { + if(dataMgt == nullptr) { return; } auto dataStorage = dataMgt->GetDataStorage(); - if (dataStorage == nullptr) { + if(dataStorage == nullptr) { return; } InnerBundleInfo innerBundleInfo; diff --git a/services/bundlemgr/test/unittest/bms_bundle_updater_test/bms_bundle_updater_test.cpp b/services/bundlemgr/test/unittest/bms_bundle_updater_test/bms_bundle_updater_test.cpp index 9a17ea4f6fa5ec8449381f3afb3759f6e3b4e163..c305f3712c39bd35016e14abe7f70d4f75b3f619 100755 --- a/services/bundlemgr/test/unittest/bms_bundle_updater_test/bms_bundle_updater_test.cpp +++ b/services/bundlemgr/test/unittest/bms_bundle_updater_test/bms_bundle_updater_test.cpp @@ -49,7 +49,7 @@ const std::string BUNDLE_CODE_DIR = "/data/accounts/account_0/applications/com.e const std::string ROOT_DIR = "/data/accounts"; const std::string PROFILE_FILE = "config.json"; const std::string SEPARATOR = "/"; -const std::chrono::seconds SLEEP_TIME{2}; +const std::chrono::seconds SLEEP_TIME {2}; const int32_t ROOT_UID = 0; const int32_t USERID = 0; const uint32_t VERSION_1 = 1; diff --git a/services/bundlemgr/test/unittest/bms_data_mgr_test/bms_data_mgr_test.cpp b/services/bundlemgr/test/unittest/bms_data_mgr_test/bms_data_mgr_test.cpp index 7248511b66d4f0baef57a67dc015de997e8ccb66..f276ed52dc02fa2306074dac2da6d27263a9a043 100755 --- a/services/bundlemgr/test/unittest/bms_data_mgr_test/bms_data_mgr_test.cpp +++ b/services/bundlemgr/test/unittest/bms_data_mgr_test/bms_data_mgr_test.cpp @@ -30,6 +30,7 @@ using OHOS::Parcel; using OHOS::AAFwk::Want; namespace { + const std::string BUNDLE_NAME = "com.example.l3jsdemo"; const std::string APP_NAME = "com.example.l3jsdemo"; const std::string ABILITY_NAME = "com.example.l3jsdemo.MainAbility"; @@ -47,6 +48,7 @@ const std::string RESOURCE_PATH = "/data/accounts/account_/com.example.l3jsdemo" const std::string LIB_PATH = "/data/accounts/account_/com.example.l3jsdemo"; const bool VISIBLE = true; const int32_t USERID = 0; + } // namespace class BmsDataMgrTest : public testing::Test { diff --git a/services/bundlemgr/test/unittest/bms_install_daemon_test/bms_install_daemon_test.cpp b/services/bundlemgr/test/unittest/bms_install_daemon_test/bms_install_daemon_test.cpp index e13df47c01673eb239660ca17fabb9609cdc9ffc..b8c87eb818c94cad76075914e36c464a78b5dd80 100755 --- a/services/bundlemgr/test/unittest/bms_install_daemon_test/bms_install_daemon_test.cpp +++ b/services/bundlemgr/test/unittest/bms_install_daemon_test/bms_install_daemon_test.cpp @@ -27,6 +27,7 @@ using namespace OHOS::AppExecFwk; using namespace OHOS; namespace { + const std::string BUNDLE_FILE = "/data/test/resource/bms/install_daemon/right.hap"; const std::string SYSTEM_DIR = "/sys/com.example.l3jsdemo"; const std::string TEMP_DIR = "/data/accounts/account_0/applications/com.example.l3jsdemo/temp"; @@ -37,6 +38,7 @@ const std::string ROOT_DIR = "/data/accounts"; const int32_t ROOT_UID = 0; const int32_t UID = 1000; const int32_t GID = 1000; + } // namespace class BmsInstallDaemonTest : public testing::Test { diff --git a/services/bundlemgr/test/unittest/bms_service_bundle_scan_test/bms_service_bundle_scan_test.cpp b/services/bundlemgr/test/unittest/bms_service_bundle_scan_test/bms_service_bundle_scan_test.cpp index 822bd0f0bd9a2e20a26399a5c18ddf00aac9e6f9..b7fbba7d28ce534b5282194dfd1949a21a122ed8 100755 --- a/services/bundlemgr/test/unittest/bms_service_bundle_scan_test/bms_service_bundle_scan_test.cpp +++ b/services/bundlemgr/test/unittest/bms_service_bundle_scan_test/bms_service_bundle_scan_test.cpp @@ -30,6 +30,7 @@ using namespace OHOS::AppExecFwk; using OHOS::DelayedSingleton; namespace { + const std::string TEST_DIR = "/data/test/resource"; const std::string BUNDLE_FILENAME_1 = "app1.hap"; const std::string BUNDLE_FILENAME_2 = "app2.hap"; @@ -37,6 +38,7 @@ const std::string BUNDLE_FILENAME_3 = "app3.hap"; const std::string BUNDLE_FILENAME_4 = "app1.ha"; const std::string BUNDLE_FILENAME_5 = "app2..ap"; const std::string BUNDLE_FILENAME_6 = "app3"; + } // namespace class BmsServiceBundleScanTest : public testing::Test { @@ -147,11 +149,11 @@ bool BmsServiceBundleScanTest::IsScanResultContain(const std::string name) const return true; } /** - * @tc.number: BundleScan_0100 - * @tc.name: Scan - * @tc.desc: 1. scan dir not exist - * 2. verify scan result file number is 0 - */ +* @tc.number: BundleScan_0100 +* @tc.name: Scan +* @tc.desc: 1. scan dir not exist +* 2. verify scan result file number is 0 +*/ HWTEST_F(BmsServiceBundleScanTest, BundleScan_0100, Function | SmallTest | Level0) { DeleteDir(TEST_DIR); @@ -159,22 +161,22 @@ HWTEST_F(BmsServiceBundleScanTest, BundleScan_0100, Function | SmallTest | Level EXPECT_EQ(0, number); } /** - * @tc.number: BundleScan_0200 - * @tc.name: Scan - * @tc.desc: 1. scan dir exist, no bundle file - * 2. verify scan result file number is 0 - */ +* @tc.number: BundleScan_0200 +* @tc.name: Scan +* @tc.desc: 1. scan dir exist, no bundle file +* 2. verify scan result file number is 0 +*/ HWTEST_F(BmsServiceBundleScanTest, BundleScan_0200, Function | SmallTest | Level0) { int number = static_cast(TriggerScan()); EXPECT_EQ(0, number); } /** - * @tc.number: BundleScan_0300 - * @tc.name: Scan - * @tc.desc: 1. scan dir exist, 3 legal file exist - * 2. verify scan result file number is 3 and file name correct - */ +* @tc.number: BundleScan_0300 +* @tc.name: Scan +* @tc.desc: 1. scan dir exist, 3 legal file exist +* 2. verify scan result file number is 3 and file name correct +*/ HWTEST_F(BmsServiceBundleScanTest, BundleScan_0300, Function | SmallTest | Level0) { CreateDir(TEST_DIR); @@ -197,11 +199,11 @@ HWTEST_F(BmsServiceBundleScanTest, BundleScan_0300, Function | SmallTest | Level DeleteFile(TEST_FILE_NAME_3); } /** - * @tc.number: BundleScan_0400 - * @tc.name: Scan - * @tc.desc: 1. scan dir exist, 3 illegal file exist - * 2. verify scan result file number is 0 - */ +* @tc.number: BundleScan_0400 +* @tc.name: Scan +* @tc.desc: 1. scan dir exist, 3 illegal file exist +* 2. verify scan result file number is 0 +*/ HWTEST_F(BmsServiceBundleScanTest, BundleScan_0400, Function | SmallTest | Level0) { const std::string TEST_FILE_NAME_4 = TEST_DIR + "/" + BUNDLE_FILENAME_4; @@ -220,11 +222,11 @@ HWTEST_F(BmsServiceBundleScanTest, BundleScan_0400, Function | SmallTest | Level DeleteFile(TEST_FILE_NAME_6); } /** - * @tc.number: BundleScan_0500 - * @tc.name: Scan - * @tc.desc: 1. scan dir exist, 3 illegal and 3 legal file exist - * 2. verify scan result file number is 3 and file name correct - */ +* @tc.number: BundleScan_0500 +* @tc.name: Scan +* @tc.desc: 1. scan dir exist, 3 illegal and 3 legal file exist +* 2. verify scan result file number is 3 and file name correct +*/ HWTEST_F(BmsServiceBundleScanTest, BundleScan_0500, Function | SmallTest | Level0) { const std::string TEST_FILE_NAME_1 = TEST_DIR + "/" + BUNDLE_FILENAME_1; diff --git a/services/bundlemgr/test/unittest/bms_service_startup_test/bms_service_startup_test.cpp b/services/bundlemgr/test/unittest/bms_service_startup_test/bms_service_startup_test.cpp index 9acf9200ec5c35dcee293bd54978095c6102a5a4..5605132d410dc0c6433568a766684140db264aa3 100755 --- a/services/bundlemgr/test/unittest/bms_service_startup_test/bms_service_startup_test.cpp +++ b/services/bundlemgr/test/unittest/bms_service_startup_test/bms_service_startup_test.cpp @@ -46,11 +46,11 @@ void BmsServiceStartupTest::TearDown() } /** - * @tc.number: Startup_0100 - * @tc.name: test the start function of the BMS service when service is not ready - * @tc.desc: 1. the service is not initialized - * 2. the non initialized BMS service can be started - */ +* @tc.number: Startup_0100 +* @tc.name: test the start function of the BMS service when service is not ready +* @tc.desc: 1. the service is not initialized +* 2. the non initialized BMS service can be started +*/ HWTEST_F(BmsServiceStartupTest, Startup_0100, Function | SmallTest | Level0) { std::shared_ptr bms = DelayedSingleton::GetInstance(); @@ -62,12 +62,12 @@ HWTEST_F(BmsServiceStartupTest, Startup_0100, Function | SmallTest | Level0) } /** - * @tc.number: Startup_0200 - * @tc.name: test the stop function of the BMS service when service is ready - * @tc.desc: 1. the service is already initialized - * 2. the initialized BMS service can be stopped - */ -HWTEST_F(BmsServiceStartupTest, Startup_0200, Function | SmallTest | Level0) +* @tc.number: Startup_0200 +* @tc.name: test the stop function of the BMS service when service is ready +* @tc.desc: 1. the service is already initialized +* 2. the initialized BMS service can be stopped +*/ +HWTEST_F(BmsServiceStartupTest, Startup_0200,Function | SmallTest | Level0) { std::shared_ptr bms = DelayedSingleton::GetInstance(); bms->OnStart(); @@ -79,12 +79,12 @@ HWTEST_F(BmsServiceStartupTest, Startup_0200, Function | SmallTest | Level0) } /** - * @tc.number: Startup_0300 - * @tc.name: test the restart function of the BMS service - * @tc.desc: 1. the service is already initialized - * 2. the stopped BMS service can be restarted - */ -HWTEST_F(BmsServiceStartupTest, Startup_0300, Function | SmallTest | Level0) +* @tc.number: Startup_0300 +* @tc.name: test the restart function of the BMS service +* @tc.desc: 1. the service is already initialized +* 2. the stopped BMS service can be restarted +*/ +HWTEST_F(BmsServiceStartupTest, Startup_0300,Function | SmallTest | Level0) { std::shared_ptr bms = DelayedSingleton::GetInstance(); bms->OnStart(); @@ -99,12 +99,12 @@ HWTEST_F(BmsServiceStartupTest, Startup_0300, Function | SmallTest | Level0) } /** - * @tc.number: Startup_0400 - * @tc.name: test the restart function of the BMS service which is already initialized - * @tc.desc: 1. the service is already initialized - * 2. the recall start function will not affect the initialized BMS service - */ -HWTEST_F(BmsServiceStartupTest, Startup_0400, Function | SmallTest | Level0) +* @tc.number: Startup_0400 +* @tc.name: test the restart function of the BMS service which is already initialized +* @tc.desc: 1. the service is already initialized +* 2. the recall start function will not affect the initialized BMS service +*/ +HWTEST_F(BmsServiceStartupTest, Startup_0400,Function | SmallTest | Level0) { std::shared_ptr bms = DelayedSingleton::GetInstance(); bms->OnStart(); @@ -116,12 +116,12 @@ HWTEST_F(BmsServiceStartupTest, Startup_0400, Function | SmallTest | Level0) } /** - * @tc.number: GetDataMgr_0100 - * @tc.name: test the dataMgr can be obtained - * @tc.desc: 1. the service is already initialized - * 2. the dataMgr can be obtained - */ -HWTEST_F(BmsServiceStartupTest, GetDataMgr_0100, Function | SmallTest | Level0) +* @tc.number: GetDataMgr_0100 +* @tc.name: test the dataMgr can be obtained +* @tc.desc: 1. the service is already initialized +* 2. the dataMgr can be obtained +*/ +HWTEST_F(BmsServiceStartupTest, GetDataMgr_0100,Function | SmallTest | Level0) { std::shared_ptr bms = DelayedSingleton::GetInstance(); bms->OnStart(); @@ -131,12 +131,12 @@ HWTEST_F(BmsServiceStartupTest, GetDataMgr_0100, Function | SmallTest | Level0) } /** - * @tc.number: GetBundleInstaller_0100 - * @tc.name: test the installer can be obtained - * @tc.desc: 1. the service is already initialized - * 2. the installer can be obtained - */ -HWTEST_F(BmsServiceStartupTest, GetBundleInstaller_0100, Function | SmallTest | Level0) +* @tc.number: GetBundleInstaller_0100 +* @tc.name: test the installer can be obtained +* @tc.desc: 1. the service is already initialized +* 2. the installer can be obtained +*/ +HWTEST_F(BmsServiceStartupTest, GetBundleInstaller_0100,Function | SmallTest | Level0) { std::shared_ptr bms = DelayedSingleton::GetInstance(); bms->OnStart(); diff --git a/services/formmgr/BUILD.gn b/services/formmgr/BUILD.gn index 1ea0f1282196c4a211a6ac9684ecf7344db72ddb..9036ae87b33c76b545e193eaaee5fa0418013de1 100644 --- a/services/formmgr/BUILD.gn +++ b/services/formmgr/BUILD.gn @@ -19,8 +19,6 @@ config("formmgr_config") { "include", "//third_party/json/include", "//utils/system/safwk/native/include", - - # "//base/miscservices/time/interfaces/innerkits/include", ] cflags_cc = [ "-fexceptions" ] } @@ -85,31 +83,27 @@ ohos_shared_library("libfms") { } deps = [ "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "${libs_path}/libeventhandler:libeventhandler_target", - "//base/miscservices/time/services:time_service", - "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", - "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr:distributedschedsvr", + "//base/powermgr/power_manager/interfaces/innerkits:powermgr_client", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//utils/native/base:utils", # "//third_party/libuuid:libuuid_static", ] external_deps = [ - "aafwk_standard:base", - "aafwk_standard:want", - "appexecfwk_standard:appexecfwk_base", - "appexecfwk_standard:appexecfwk_core", "ces_standard:cesfwk_core", "ces_standard:cesfwk_innerkits", - "dmsfwk_standard:zuri", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "os_account_standard:libaccountkits", - "os_account_standard:libaccountkits", - "permission_standard:libpermissionsdk_standard", - "power_manager_native:powermgr_client", - "safwk:system_ability_fwk", - "samgr_L2:samgr_proxy", ] subsystem_name = "appexecfwk" diff --git a/services/formmgr/include/form_ability_connection.h b/services/formmgr/include/form_ability_connection.h index 0cf36c49c5d58b2888dcdffe1173cbcefc74fd0a..8794c9ffa754e2a9b38d7c838e106fed6a531a71 100644 --- a/services/formmgr/include/form_ability_connection.h +++ b/services/formmgr/include/form_ability_connection.h @@ -1,97 +1,86 @@ -/* - * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_ABILITY_CONNECTION_H -#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_ABILITY_CONNECTION_H - -#include "event_handler.h" -#include "form_item_info.h" -#include "provider_connect_stub.h" -#include "want.h" - -namespace OHOS { -namespace AppExecFwk { -using WantParams = OHOS::AAFwk::WantParams; - -/** - * @class FormAbilityConnection - * Form Ability Connection Stub. - */ -class FormAbilityConnection : public ProviderConnectStub { -public: - FormAbilityConnection() = default; - virtual ~FormAbilityConnection() = default; - - /** - * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. - * @param element service ability's ElementName. - * @param remoteObject the session proxy of service ability. - * @param resultCode ERR_OK on success, others on failure. - */ - virtual void OnAbilityConnectDone( - const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; - - /** - * @brief OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. - * @param element service ability's ElementName. - * @param resultCode ERR_OK on success, others on failure. - */ - virtual void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override; - - /** - * @brief remote object died event. - * @param remoteObject the remote object of service ability. - */ - void OnConnectDied(const wptr &remoteObject); - - /** - * @brief Get connectId. - * @return The ability connection id. - */ - long GetConnectId(); - - /** - * @brief Set connectId. - * @param connectId The ability connection id. - */ - void SetConnectId(long connectId); - /** - * @brief Get the provider Key - * - * @return The provider Key - */ - std::string GetProviderKey(); - /** - * @brief Set the Provider Key - * - * @param bundleName bundleName - * @param abilityName abilityName - */ - void SetProviderKey(const std::string &bundleName, const std::string &abilityName); - -private: - int64_t formId_ = 0; - std::string deviceId_ = ""; - std::string bundleName_ = ""; - std::string abilityName_ = ""; - bool isFreeInstall_ = false; - long connectId_ = 0; - - DISALLOW_COPY_AND_MOVE(FormAbilityConnection); -}; -} // namespace AppExecFwk -} // namespace OHOS - +/* + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_ABILITY_CONNECTION_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_ABILITY_CONNECTION_H + +#include "event_handler.h" +#include "form_item_info.h" +#include "provider_connect_stub.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using WantParams = OHOS::AAFwk::WantParams; + +/** + * @class FormAbilityConnection + * Form Ability Connection Stub. + */ +class FormAbilityConnection : public ProviderConnectStub { +public: + FormAbilityConnection() = default; + virtual ~FormAbilityConnection() = default; + + /** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ + virtual void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + + /** + * @brief OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. + * @param element service ability's ElementName. + * @param resultCode ERR_OK on success, others on failure. + */ + virtual void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override; + + /** + * @brief remote object died event. + * @param remoteObject the remote object of service ability. + */ + void OnConnectDied(const wptr &remoteObject); + + /** + * @brief Get connectId. + * @return The ability connection id. + */ + long GetConnectId(); + + /** + * @brief Set connectId. + * @param connectId The ability connection id. + */ + void SetConnectId(long connectId); + + // std::string GetProviderKey(); + +private: + int64_t formId_; + std::string deviceId_; + std::string bundleName_; + std::string abilityName_; + bool isFreeInstall_; + long connectId_ = 0; + + DISALLOW_COPY_AND_MOVE(FormAbilityConnection); +}; +} // namespace AppExecFwk +} // namespace OHOS + #endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_ABILITY_CONNECTION_H \ No newline at end of file diff --git a/services/formmgr/include/form_ams_helper.h b/services/formmgr/include/form_ams_helper.h index effd42988ebcc115da1cadd16b48fc37a0bd55a8..1d554279be383ef37223b2c09dda5b37572b1003 100644 --- a/services/formmgr/include/form_ams_helper.h +++ b/services/formmgr/include/form_ams_helper.h @@ -20,13 +20,13 @@ #include #include "ability_connect_callback_interface.h" #include "ability_manager_interface.h" -#include "event_handler.h" #include "iremote_object.h" #include "uri.h" namespace OHOS { namespace AppExecFwk { using IAbilityConnection = OHOS::AAFwk::IAbilityConnection; +using IAbilityManager = OHOS::AAFwk::IAbilityManager; using Want = OHOS::AAFwk::Want; /** * @class FormAmsHelper @@ -36,19 +36,12 @@ class FormAmsHelper final : public DelayedRefSingleton { DECLARE_DELAYED_REF_SINGLETON(FormAmsHelper) public: DISALLOW_COPY_AND_MOVE(FormAmsHelper); - /** - * @brief SetEventHandler. - * @param handler event handler - */ - inline void SetEventHandler(const std::shared_ptr &handler) - { - eventHandler_ = handler; - } + /** * @brief acquire a form ability manager if it not existed, * @return returns the ability manager ipc object or nullptr for failed. */ - sptr GetAbilityManager(); + sptr GetAbilityManager(); /** * @brief Connect session with service ability. * @param want Special want for service type's ability. @@ -56,36 +49,21 @@ public: * @return Returns ERR_OK on success, others on failure. */ ErrCode ConnectServiceAbility( - const Want &want, const sptr &connect); + const Want &want, const sptr &connect); /** * @brief Disconnect session with service ability. * @param want Special want for service type's ability. * @param connect Callback used to notify caller the result of connecting or disconnecting. * @return Returns ERR_OK on success, others on failure. */ - ErrCode DisConnectServiceAbility(const sptr &connect); - /** - * @brief Disconnect ability delay, disconnect session with service ability. - * @param want Special want for service type's ability. - * @param connect Callback used to notify caller the result of connecting or disconnecting. - * @return Returns ERR_OK on success, others on failure. - */ - ErrCode DisConnectServiceAbilityDelay(const sptr &connect); + ErrCode DisConnectServiceAbility(const sptr &connect); /** * @brief Add the ability manager instance for debug. * @param abilityManager the ability manager ipc object. */ void SetAbilityManager(const sptr &abilityManager); -private: - /** - * @brief Disconnect ability task, disconnect session with service ability. - * @param want Special want for service type's ability. - * @param connect Callback used to notify caller the result of connecting or disconnecting. - */ - void DisConnectAbilityTask(const sptr &connect); private: sptr abilityManager_ = nullptr; - std::shared_ptr eventHandler_ = nullptr; }; } // namespace AppExecFwk } // namespace OHOS diff --git a/services/formmgr/include/form_batch_delete_connection.h b/services/formmgr/include/form_batch_delete_connection.h index 2f0ca0bafb4bd3450affd2ac37dc2692de7e623d..93dcf7cda997dad7912c3c5db239a265dd16e568 100644 --- a/services/formmgr/include/form_batch_delete_connection.h +++ b/services/formmgr/include/form_batch_delete_connection.h @@ -32,8 +32,7 @@ using WantParams = OHOS::AAFwk::WantParams; */ class FormBatchDeleteConnection : public FormAbilityConnection { public: - FormBatchDeleteConnection(const std::set &formIds, const std::string &bundleName, - const std::string &abilityName); + FormBatchDeleteConnection(const std::set &formIds); virtual ~FormBatchDeleteConnection() = default; /** diff --git a/services/formmgr/include/form_bms_helper.h b/services/formmgr/include/form_bms_helper.h index 4e5523ba3bc681a495af091c8a76ca6f767a5ad7..8d377a18261503489b0f98a534fabc9bfedaef8d 100644 --- a/services/formmgr/include/form_bms_helper.h +++ b/services/formmgr/include/form_bms_helper.h @@ -24,6 +24,8 @@ namespace OHOS { namespace AppExecFwk { +using IAbilityConnection = OHOS::AAFwk::IAbilityConnection; +using IAbilityManager = OHOS::AAFwk::IAbilityManager; using Want = OHOS::AAFwk::Want; /** diff --git a/services/formmgr/include/form_cast_temp_connection.h b/services/formmgr/include/form_cast_temp_connection.h index 6a930ceca8a75c31d3f4d27e5134804c114af1eb..d0892a79548e09afa115202a2e5185aed65493d9 100644 --- a/services/formmgr/include/form_cast_temp_connection.h +++ b/services/formmgr/include/form_cast_temp_connection.h @@ -1,50 +1,49 @@ -/* - * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_CAST_TEMP_CONNECTION_H -#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_CAST_TEMP_CONNECTION_H - -#include "event_handler.h" -#include "form_ability_connection.h" - -namespace OHOS { -namespace AppExecFwk { -/** - * @class FormCastTempConnection - * Cast temp form Connection Stub. - */ -class FormCastTempConnection : public FormAbilityConnection { -public: - FormCastTempConnection(const int64_t formId, const std::string &bundleName, - const std::string &abilityName); - virtual ~FormCastTempConnection() = default; - - /** - * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. - * @param element service ability's ElementName. - * @param remoteObject the session proxy of service ability. - * @param resultCode ERR_OK on success, others on failure. - */ - void OnAbilityConnectDone( - const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; - -private: - int64_t formId_; - DISALLOW_COPY_AND_MOVE(FormCastTempConnection); -}; -} // namespace AppExecFwk -} // namespace OHOS - +/* + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_CAST_TEMP_CONNECTION_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_CAST_TEMP_CONNECTION_H + +#include "event_handler.h" +#include "form_ability_connection.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormCastTempConnection + * Cast temp form Connection Stub. + */ +class FormCastTempConnection : public FormAbilityConnection { +public: + FormCastTempConnection(const int64_t formId); + virtual ~FormCastTempConnection() = default; + + /** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + +private: + int64_t formId_; + DISALLOW_COPY_AND_MOVE(FormCastTempConnection); +}; +} // namespace AppExecFwk +} // namespace OHOS + #endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_CAST_TEMP_CONNECTION_H \ No newline at end of file diff --git a/services/formmgr/include/form_data_mgr.h b/services/formmgr/include/form_data_mgr.h index b8114dc3aef1b031452e52c456c7caf66760a8a2..d4eb6d02cb72333e4e1afdd22a3686c2d74dcae3 100644 --- a/services/formmgr/include/form_data_mgr.h +++ b/services/formmgr/include/form_data_mgr.h @@ -68,6 +68,23 @@ public: * @param removedFormIds The id list of the forms. */ void CleanHostRemovedForms(const std::vector &removedFormIds); + /** + * @brief Delete form js info by form record. + * @return Returns all form records map. + */ + std::map &GetAllFormRecord(); + + /** + * @brief Get all form client host record. + * @return Returns all form client host record. + */ + std::vector &GetClientRecords(); + + /** + * @brief Get all form host records. + * @return Returns all form host records vector. + */ + std::vector &GetAllFormHostRecord(); /** * @brief Allot form host record by caller token. * @param info The form item info. @@ -322,14 +339,7 @@ public: * @param foundFormsMap Form Id list. */ void GetNoHostTempForms(const int uid, std::map> &noHostTempFormsMap, - std::map &foundFormsMap); - - /** - * @brief Update form for host clients. - * @param formId The Id of the form. - * @param formProviderInfo FormProviderInfo object - */ - void UpdateFormProviderInfo(const int64_t formId, const FormProviderInfo &formProviderInfo); + std::map &foundFormsMap); private: /** * @brief Create form record. @@ -366,7 +376,7 @@ private: * @param record The form record. * @param info form item info. */ - void ParseAtTimerConfig(FormRecord &record, const FormItemInfo &info) const; + void ParseAtTimerConfig(FormRecord record, const FormItemInfo &info) const; /** * @brief Get the temp forms from host and delete temp form in cache. * @param record The form record. diff --git a/services/formmgr/include/form_delete_connection.h b/services/formmgr/include/form_delete_connection.h index 329b56d677377cb2d57893b95d779c1e4c934e2a..4da0e284061263ea6f9f370153e3ed5e5a01fd90 100644 --- a/services/formmgr/include/form_delete_connection.h +++ b/services/formmgr/include/form_delete_connection.h @@ -1,51 +1,51 @@ -/* - * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_DELETE_CONNECTION_H -#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_DELETE_CONNECTION_H - -#include "event_handler.h" -#include "form_ability_connection.h" - -namespace OHOS { -namespace AppExecFwk { - -/** - * @class FormDeleteConnection - * Form Delete Connection Stub. - */ -class FormDeleteConnection : public FormAbilityConnection { -public: - FormDeleteConnection(const int64_t formId, const std::string &bundleName, const std::string &abilityName); - virtual ~FormDeleteConnection() = default; - - /** - * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. - * @param element service ability's ElementName. - * @param remoteObject the session proxy of service ability. - * @param resultCode ERR_OK on success, others on failure. - */ - void OnAbilityConnectDone( - const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; - -private: - int64_t formId_; - DISALLOW_COPY_AND_MOVE(FormDeleteConnection); -}; - -} // namespace AppExecFwk -} // namespace OHOS - +/* + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_DELETE_CONNECTION_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_DELETE_CONNECTION_H + +#include "event_handler.h" +#include "form_ability_connection.h" + +namespace OHOS { +namespace AppExecFwk { + +/** + * @class FormDeleteConnection + * Form Delete Connection Stub. + */ +class FormDeleteConnection : public FormAbilityConnection { +public: + FormDeleteConnection(const int64_t formId); + virtual ~FormDeleteConnection() = default; + + /** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + +private: + int64_t formId_; + DISALLOW_COPY_AND_MOVE(FormDeleteConnection); +}; + +} // namespace AppExecFwk +} // namespace OHOS + #endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_DELETE_CONNECTION_H \ No newline at end of file diff --git a/services/formmgr/include/form_event_notify_connection.h b/services/formmgr/include/form_event_notify_connection.h index 88a51f43da110e7047d7bd34bd68314edbd737bb..f06043a118fb0d6e97daffa69791431037b09ba4 100644 --- a/services/formmgr/include/form_event_notify_connection.h +++ b/services/formmgr/include/form_event_notify_connection.h @@ -1,54 +1,53 @@ -/* - * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_EVENT_NOTIFY_CONNECTION_H -#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_EVENT_NOTIFY_CONNECTION_H - -#include "event_handler.h" -#include "form_ability_connection.h" -#include "want.h" - -namespace OHOS { -namespace AppExecFwk { -using Want = OHOS::AAFwk::Want; -/** - * @class FormEventNotifyConnection - * Form Event Notify Connection Stub. - */ -class FormEventNotifyConnection : public FormAbilityConnection { -public: - FormEventNotifyConnection(const std::vector formEvents, const int32_t formVisibleType, - const std::string &bundleName, const std::string &abilityName); - virtual ~FormEventNotifyConnection() = default; - - /** - * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. - * - * @param element service ability's ElementName. - * @param remoteObject the session proxy of service ability. - * @param resultCode ERR_OK on success, others on failure. - */ - void OnAbilityConnectDone( - const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; - -private: - std::vector formEvents_; - int32_t formVisibleType_; - DISALLOW_COPY_AND_MOVE(FormEventNotifyConnection); -}; -} // namespace AppExecFwk -} // namespace OHOS - +/* + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_EVENT_NOTIFY_CONNECTION_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_EVENT_NOTIFY_CONNECTION_H + +#include "event_handler.h" +#include "form_ability_connection.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using Want = OHOS::AAFwk::Want; +/** + * @class FormEventNotifyConnection + * Form Event Notify Connection Stub. + */ +class FormEventNotifyConnection : public FormAbilityConnection { +public: + FormEventNotifyConnection(const std::vector formEvents, const int32_t formVisibleType); + virtual ~FormEventNotifyConnection() = default; + + /** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + +private: + std::vector formEvents_; + int32_t formVisibleType_; + DISALLOW_COPY_AND_MOVE(FormEventNotifyConnection); +}; +} // namespace AppExecFwk +} // namespace OHOS + #endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_EVENT_NOTIFY_CONNECTION_H \ No newline at end of file diff --git a/services/formmgr/include/form_host_record.h b/services/formmgr/include/form_host_record.h index 4d4b5ee895858af2cfedb97328f436ad1367429f..79e0869f7ba97a426680d979d15f8a89b1fbd025 100644 --- a/services/formmgr/include/form_host_record.h +++ b/services/formmgr/include/form_host_record.h @@ -1,202 +1,202 @@ -/* - * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_HOST_RECORD_H -#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_HOST_RECORD_H - -#include -#include -#include -#include "app_log_wrapper.h" -#include "form_host_callback.h" -#include "form_item_info.h" -#include "form_record.h" -#include "iremote_object.h" - -namespace OHOS { -namespace AppExecFwk { -/** - * @class FormHostRecord - * Form host data. - */ -class FormHostRecord { -public: - /** - * @brief Create form host record. - * @param callback remote object. - * @param callingUid Calling uid. - */ - static FormHostRecord CreateRecord(const FormItemInfo &info, const sptr &callback, int callingUid); - /** - * @brief Add form id. - * @param formId The Id of the form. - */ - void AddForm(int64_t formId); - /** - * @brief Delete form id. - * @param formId The Id of the form. - */ - void DelForm(int64_t formId); - /** - * @brief forms_ is empty or not. - * @return forms_ is empty or not. - */ - bool IsEmpty() const; - /** - * @brief formId is in forms_ or not. - * @param formId The Id of the form. - * @return formId is in forms_ or not. - */ - bool Contains(int64_t formId) const; - - /** - * @brief Set refresh enable flag. - * @param formId The Id of the form. - * @param flag True for enbale, false for disable. - */ - void SetEnableRefresh(int64_t formId, bool flag); - - /** - * @brief Refresh enable or not. - * @param formId The Id of the form. - * @return true on enbale, false on disable.. - */ - bool IsEnableRefresh(int64_t formId) const; - - /** - * @brief Set need refresh enable flag. - * @param formId The Id of the form. - * @param flag True for enbale, false for disable. - */ - void SetNeedRefresh(int64_t formId, bool flag); - /** - * @brief Need Refresh enable or not. - * @param formId The Id of the form. - * @return true on enbale, false on disable.. - */ - bool IsNeedRefresh(int64_t formId) const; - - /** - * @brief Send form data to form host. - * @param id The Id of the form. - * @param record Form record. - */ - void OnAcquire(int64_t id, const FormRecord &record); - - /** - * @brief Update form data to form host. - * @param id The Id of the form. - * @param record Form record. - */ - void OnUpdate(int64_t id, const FormRecord &record); - /** - * Send form uninstall message to form host. - * - * @param id The Id of the form. - * @param record Form record. - */ - void OnFormUninstalled(std::vector &formIds); - - /** - * @brief Release resource. - * @param id The Id of the form. - * @param record Form record. - */ - void CleanResource(); - /** - * @brief Get callerUid_. - * @return callerUid_. - */ - int GetCallerUid() const - { - return callerUid_; - } - /** - * @brief Get clientStub_. - * @return clientStub_. - */ - sptr GetClientStub() const; - /** - * @brief Get deathRecipient_. - * @return deathRecipient_. - */ - sptr GetDeathRecipient() const; - /** - * @brief Set value of callerUid_. - * @param callerUid Caller uid. - */ - void SetCallerUid(const int callerUid); - /** - * @brief Set value of clientStub_. - * @param clientStub remote object. - */ - void SetClientStub(const sptr &clientStub); - /** - * @brief Set value of clientImpl_. - * @param clientImpl Form host callback object. - */ - void SetClientImpl(const std::shared_ptr &clientImpl); - /** - * @brief Set value of deathRecipient_. - * @param clientImpl DeathRecipient object. - */ - void SetDeathRecipient(const sptr &deathRecipient); - /** - * @brief Add deathRecipient object to clientStub_. - * @param deathRecipient DeathRecipient object. - */ - void AddDeathRecipient(const sptr& deathRecipient); - /** - * @brief Get hostBundleName_. - * @return hostBundleName_. - */ - std::string GetHostBundleName() const; - /** - * @brief Set hostBundleName_. - * @param hostBandleName Host bundle name. - */ - void SetHostBundleName(const std::string &hostBundleName); - -private: - int callerUid_ = 0; - sptr clientStub_ = nullptr; - std::shared_ptr clientImpl_ = nullptr; - sptr deathRecipient_ = nullptr; - std::unordered_map forms_; - std::unordered_map needRefresh_; - std::string hostBundleName_ = ""; - - /** - * @class ClientDeathRecipient - * notices IRemoteBroker died. - */ - class ClientDeathRecipient : public IRemoteObject::DeathRecipient { - public: - /** - * @brief Constructor - */ - ClientDeathRecipient() = default; - ~ClientDeathRecipient() = default; - /** - * @brief handle remote object died event. - * @param remote remote object. - */ - void OnRemoteDied(const wptr &remote) override; - }; -}; -} // namespace AppExecFwk -} // namespace OHOS - +/* + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_HOST_RECORD_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_HOST_RECORD_H + +#include +#include +#include +#include "app_log_wrapper.h" +#include "form_host_callback.h" +#include "form_item_info.h" +#include "form_record.h" +#include "iremote_object.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormHostRecord + * Form host data. + */ +class FormHostRecord { +public: + /** + * @brief Create form host record. + * @param callback remote object. + * @param callingUid Calling uid. + */ + static FormHostRecord CreateRecord(const FormItemInfo &info, const sptr &callback, int callingUid); + /** + * @brief Add form id. + * @param formId The Id of the form. + */ + void AddForm(int64_t formId); + /** + * @brief Delete form id. + * @param formId The Id of the form. + */ + void DelForm(int64_t formId); + /** + * @brief forms_ is empty or not. + * @return forms_ is empty or not. + */ + bool IsEmpty() const; + /** + * @brief formId is in forms_ or not. + * @param formId The Id of the form. + * @return formId is in forms_ or not. + */ + bool Contains(int64_t formId) const; + + /** + * @brief Set refresh enable flag. + * @param formId The Id of the form. + * @param flag True for enbale, false for disable. + */ + void SetEnableRefresh(int64_t formId, bool flag); + + /** + * @brief Refresh enable or not. + * @param formId The Id of the form. + * @return true on enbale, false on disable.. + */ + bool IsEnableRefresh(int64_t formId) const; + + /** + * @brief Set need refresh enable flag. + * @param formId The Id of the form. + * @param flag True for enbale, false for disable. + */ + void SetNeedRefresh(int64_t formId, bool flag); + /** + * @brief Need Refresh enable or not. + * @param formId The Id of the form. + * @return true on enbale, false on disable.. + */ + bool IsNeedRefresh(int64_t formId) const; + + /** + * @brief Send form data to form host. + * @param id The Id of the form. + * @param record Form record. + */ + void OnAcquire(int64_t id, const FormRecord &record); + + /** + * @brief Update form data to form host. + * @param id The Id of the form. + * @param record Form record. + */ + void OnUpdate(int64_t id, const FormRecord &record); + /** + * Send form uninstall message to form host. + * + * @param id The Id of the form. + * @param record Form record. + */ + void OnFormUninstalled(std::vector &formIds); + + /** + * @brief Release resource. + * @param id The Id of the form. + * @param record Form record. + */ + void CleanResource(); + /** + * @brief Get callerUid_. + * @return callerUid_. + */ + int GetCallerUid() const + { + return callerUid_; + } + /** + * @brief Get clientStub_. + * @return clientStub_. + */ + sptr GetClientStub() const; + /** + * @brief Get deathRecipient_. + * @return deathRecipient_. + */ + sptr GetDeathRecipient() const; + /** + * @brief Set value of callerUid_. + * @param callerUid Caller uid. + */ + void SetCallerUid(const int callerUid); + /** + * @brief Set value of clientStub_. + * @param clientStub remote object. + */ + void SetClientStub(const sptr &clientStub); + /** + * @brief Set value of clientImpl_. + * @param clientImpl Form host callback object. + */ + void SetClientImpl(const std::shared_ptr &clientImpl); + /** + * @brief Set value of deathRecipient_. + * @param clientImpl DeathRecipient object. + */ + void SetDeathRecipient(const sptr &deathRecipient); + /** + * @brief Add deathRecipient object to clientStub_. + * @param deathRecipient DeathRecipient object. + */ + void AddDeathRecipient(const sptr& deathRecipient); + /** + * @brief Get hostBundleName_. + * @return hostBundleName_. + */ + std::string GetHostBundleName() const; + /** + * @brief Set hostBundleName_. + * @param hostBandleName Host bundle name. + */ + void SetHostBundleName(const std::string &hostBundleName); + +private: + int callerUid_; + sptr clientStub_ = nullptr; + std::shared_ptr clientImpl_ = nullptr; + sptr deathRecipient_ = nullptr; + std::unordered_map forms_; + std::unordered_map needRefresh_; + std::string hostBundleName_; + + /** + * @class ClientDeathRecipient + * notices IRemoteBroker died. + */ + class ClientDeathRecipient : public IRemoteObject::DeathRecipient { + public: + /** + * @brief Constructor + */ + ClientDeathRecipient() = default; + ~ClientDeathRecipient() = default; + /** + * @brief handle remote object died event. + * @param remote remote object. + */ + void OnRemoteDied(const wptr &remote) override; + }; +}; +} // namespace AppExecFwk +} // namespace OHOS + #endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_HOST_RECORD_H \ No newline at end of file diff --git a/services/formmgr/include/form_item_info.h b/services/formmgr/include/form_item_info.h index 3106ed83c82e0e4c08ceac03e5cf6540028e7615..aa0a499ea0f80f6664da862396abb9a4a9e4738b 100644 --- a/services/formmgr/include/form_item_info.h +++ b/services/formmgr/include/form_item_info.h @@ -231,22 +231,22 @@ private: private: int64_t formId_ = -1; - std::string packageName_ = ""; - std::string providerBundleName_ = ""; - std::string hostBundleName_ = ""; - std::string moduleName_ = ""; - std::string abilityName_ = ""; - std::string formName_ = ""; - int32_t specificationId_ = 0; - bool updateFlag_ = false; - int32_t updateDuration_ = 0; - std::string scheduledUpdateTime_ = ""; + std::string packageName_; + std::string providerBundleName_; + std::string hostBundleName_; + std::string moduleName_; + std::string abilityName_; + std::string formName_; + int32_t specificationId_; + bool updateFlag_; + int32_t updateDuration_; + std::string scheduledUpdateTime_; std::vector hapSourceDirs_; - bool temporaryFlag_ = false; - bool formVisibleNotify_ = false; + bool temporaryFlag_; + bool formVisibleNotify_; - std::string jsComponentName_ = ""; - std::string abilityModuleName_ = ""; + std::string jsComponentName_; + std::string abilityModuleName_; std::unordered_map moduleInfoMap_; }; } // namespace AppExecFwk diff --git a/services/formmgr/include/form_mgr_adapter.h b/services/formmgr/include/form_mgr_adapter.h index 2ac902fc6f4ee5a37c9eebdc719c11fa5f649f9f..b795fb900f38fe25f45a2090f04d2d7c9b0242a0 100644 --- a/services/formmgr/include/form_mgr_adapter.h +++ b/services/formmgr/include/form_mgr_adapter.h @@ -17,7 +17,6 @@ #define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_MGR_ADAPTER_H #include -#include #include "bundle_info.h" #include "bundle_mgr_interface.h" @@ -39,10 +38,10 @@ using WantParams = OHOS::AAFwk::WantParams; * @class FormMgrAdapter * Form request handler from form host. */ -class FormMgrAdapter final : public DelayedRefSingleton { -DECLARE_DELAYED_REF_SINGLETON(FormMgrAdapter) +class FormMgrAdapter { public: - DISALLOW_COPY_AND_MOVE(FormMgrAdapter); + FormMgrAdapter(){}; + virtual ~FormMgrAdapter(){}; /** * @brief Add form with want, send want to form manager service. @@ -162,22 +161,6 @@ public: * @return Returns true if execute success, false otherwise. */ int MessageEvent(const int64_t formId, const Want &want, const sptr &callerToken); - - /** - * @brief Acquire form data from form provider. - * @param formId The Id of the from. - * @param want The want of the request. - * @param remoteObject Form provider proxy object. - */ - void AcquireProviderFormInfo(const int64_t formId, const Want &want, const sptr &remoteObject); - /** - * @brief Notify form provider for delete form. - * @param formId The Id of the from. - * @param want The want of the form. - * @param remoteObject Form provider proxy object. - * @return none. - */ - void NotifyFormDelete(const int64_t formId, const Want &want, const sptr &remoteObject); private: /** * @brief Get form configure info. diff --git a/services/formmgr/include/form_mgr_service.h b/services/formmgr/include/form_mgr_service.h index ac10b21ae6a2a392f596c3e16d6dca6550335edc..a2cd4970a0f0153f0eabce755f0f9142331a11ea 100644 --- a/services/formmgr/include/form_mgr_service.h +++ b/services/formmgr/include/form_mgr_service.h @@ -24,6 +24,7 @@ #include #include "event_handler.h" +#include "form_mgr_adapter.h" #include "form_mgr_stub.h" #include "form_provider_data.h" #include "iremote_object.h" @@ -193,6 +194,8 @@ private: std::shared_ptr runner_ = nullptr; std::shared_ptr handler_ = nullptr; + + std::unique_ptr formMgrAdapter_ = nullptr; bool resetFlag = false; diff --git a/services/formmgr/include/form_msg_event_connection.h b/services/formmgr/include/form_msg_event_connection.h index 1aefe943954c21e19249aa3af8e601d00665f363..6fd0981744c3a5e90b1a3d4b4ee00582d907ca58 100644 --- a/services/formmgr/include/form_msg_event_connection.h +++ b/services/formmgr/include/form_msg_event_connection.h @@ -1,54 +1,53 @@ -/* - * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_MSG_EVENT_CONNECTION_H -#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_MSG_EVENT_CONNECTION_H - -#include "event_handler.h" -#include "form_ability_connection.h" -#include "want.h" - -namespace OHOS { -namespace AppExecFwk { -using Want = OHOS::AAFwk::Want; -/** - * @class FormMsgEventConnection - * Form Refresh Connection Stub. - */ -class FormMsgEventConnection : public FormAbilityConnection { -public: - FormMsgEventConnection(const int64_t formId, const Want &want, - const std::string &bundleName, const std::string &abilityName); - virtual ~FormMsgEventConnection() = default; - - /** - * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. - * - * @param element service ability's ElementName. - * @param remoteObject the session proxy of service ability. - * @param resultCode ERR_OK on success, others on failure. - */ - void OnAbilityConnectDone( - const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; - -private: - int64_t formId_; - Want want_; - DISALLOW_COPY_AND_MOVE(FormMsgEventConnection); -}; -} // namespace AppExecFwk -} // namespace OHOS - +/* + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_MSG_EVENT_CONNECTION_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_MSG_EVENT_CONNECTION_H + +#include "event_handler.h" +#include "form_ability_connection.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using Want = OHOS::AAFwk::Want; +/** + * @class FormMsgEventConnection + * Form Refresh Connection Stub. + */ +class FormMsgEventConnection : public FormAbilityConnection { +public: + FormMsgEventConnection(const int64_t formId, const Want &want); + virtual ~FormMsgEventConnection() = default; + + /** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + +private: + int64_t formId_; + Want want_; + DISALLOW_COPY_AND_MOVE(FormMsgEventConnection); +}; +} // namespace AppExecFwk +} // namespace OHOS + #endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_MSG_EVENT_CONNECTION_H \ No newline at end of file diff --git a/services/formmgr/include/form_refresh_connection.h b/services/formmgr/include/form_refresh_connection.h index a847be922893c1ba524949925668f9a7ebfdc6d4..142c06ae99db54408fc76667255359fdc7121cd3 100644 --- a/services/formmgr/include/form_refresh_connection.h +++ b/services/formmgr/include/form_refresh_connection.h @@ -1,54 +1,53 @@ -/* - * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_REFRESH_CONNECTION_H -#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_REFRESH_CONNECTION_H - -#include "event_handler.h" -#include "form_ability_connection.h" -#include "want.h" - -namespace OHOS { -namespace AppExecFwk { -using Want = OHOS::AAFwk::Want; -/** - * @class FormRefreshConnection - * Form Refresh Connection Stub. - */ -class FormRefreshConnection : public FormAbilityConnection { -public: - FormRefreshConnection(const int64_t formId, const Want &want, - const std::string &bundleName, const std::string &abilityName); - virtual ~FormRefreshConnection() = default; - - /** - * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. - * - * @param element service ability's ElementName. - * @param remoteObject the session proxy of service ability. - * @param resultCode ERR_OK on success, others on failure. - */ - void OnAbilityConnectDone( - const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; - -private: - int64_t formId_; - Want want_; - DISALLOW_COPY_AND_MOVE(FormRefreshConnection); -}; -} // namespace AppExecFwk -} // namespace OHOS - +/* + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_REFRESH_CONNECTION_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_REFRESH_CONNECTION_H + +#include "event_handler.h" +#include "form_ability_connection.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using Want = OHOS::AAFwk::Want; +/** + * @class FormRefreshConnection + * Form Refresh Connection Stub. + */ +class FormRefreshConnection : public FormAbilityConnection { +public: + FormRefreshConnection(const int64_t formId, const Want &want); + virtual ~FormRefreshConnection() = default; + + /** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ + void OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override; + +private: + int64_t formId_; + Want want_; + DISALLOW_COPY_AND_MOVE(FormRefreshConnection); +}; +} // namespace AppExecFwk +} // namespace OHOS + #endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_REFRESH_CONNECTION_H \ No newline at end of file diff --git a/services/formmgr/include/form_supply_callback.h b/services/formmgr/include/form_supply_callback.h index 38487b5fa1b967e23cae2f1adb405c636292695c..031ff49c12bf1e6b5a2c26f5c492c4a40ef1f602 100644 --- a/services/formmgr/include/form_supply_callback.h +++ b/services/formmgr/include/form_supply_callback.h @@ -1,76 +1,69 @@ -/* - * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORMMGR_FORM_SUPPLY_CALLBACK_H -#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORMMGR_FORM_SUPPLY_CALLBACK_H - -#include "form_ability_connection.h" -#include "form_supply_stub.h" - -namespace OHOS { -namespace AppExecFwk { -/** - * @class FormSupplyCallback - * form supply service stub. - */ -class FormSupplyCallback : public FormSupplyStub { -public: - FormSupplyCallback() = default; - virtual ~FormSupplyCallback() = default; - static sptr GetInstance(); - - /** - * @brief Accept form binding data from form provider. - * @param providerFormInfo Form binding data. - * @param want input data. - * @return Returns ERR_OK on success, others on failure. - */ - int OnAcquire(const FormProviderInfo &formInfo, const Want &want) override; - - /** - * @brief Accept other event. - * @param want input data. - * @return Returns ERR_OK on success, others on failure. - */ - int OnEventHandle(const Want &want) override; - - /** - * @brief Save ability Connection for the callback. - * @param connection ability connection. - */ - void AddConnection(sptr connection); - /** - * @brief Delete ability connection after the callback come. - * @param connectId The ability connection id generated when save. - */ - void RemoveConnection(long connectId); - -private: - /** - * @brief check if disconnect ability or not. - * @param connection The ability connection. - */ - bool CanDisConnect(sptr &connection); -private: - static std::mutex mutex_; - static sptr instance_; - - mutable std::mutex conMutex_; - std::map> connections_; - DISALLOW_COPY_AND_MOVE(FormSupplyCallback); -}; -} // namespace AppExecFwk -} // namespace OHOS -#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORMMGR_FORM_SUPPLY_CALLBACK_H +/* + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORMMGR_FORM_SUPPLY_CALLBACK_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORMMGR_FORM_SUPPLY_CALLBACK_H + +#include "form_ability_connection.h" +#include "form_supply_stub.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @class FormSupplyCallback + * form supply service stub. + */ +class FormSupplyCallback : public FormSupplyStub { +public: + FormSupplyCallback() = default; + virtual ~FormSupplyCallback() = default; + static sptr GetInstance(); + + /** + * @brief Accept form binding data from form provider. + * @param providerFormInfo Form binding data. + * @param want input data. + * @return Returns ERR_OK on success, others on failure. + */ + int OnAcquire(const FormProviderInfo &formInfo, const Want &want) override; + + /** + * @brief Accept other event. + * @param want input data. + * @return Returns ERR_OK on success, others on failure. + */ + int OnEventHandle(const Want &want) override; + + /** + * @brief Save ability Connection for the callback. + * @param connection ability connection. + */ + void AddConnection(sptr connection); + /** + * @brief Delete ability connection after the callback come. + * @param connectId The ability connection id generated when save. + */ + void RemoveConnection(long connectId); +private: + static std::mutex mutex_; + static sptr instance_; + + mutable std::mutex conMutex_; + std::map> connections_; + DISALLOW_COPY_AND_MOVE(FormSupplyCallback); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORMMGR_FORM_SUPPLY_CALLBACK_H diff --git a/services/formmgr/include/form_timer.h b/services/formmgr/include/form_timer.h index cec511f4f4a7be46636ffd088eea2b8620ab268f..94cf7ffcff9b0f6f88bec011eb9cefd3fd16937e 100644 --- a/services/formmgr/include/form_timer.h +++ b/services/formmgr/include/form_timer.h @@ -14,7 +14,6 @@ */ #ifndef FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TIMER_TASK_H #define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TIMER_TASK_H - namespace OHOS { namespace AppExecFwk { /** @@ -42,7 +41,7 @@ public: int64_t refreshTime; bool isEnable = true; bool isCountTimer = false; - UpdateType type = UpdateType::TYPE_INTERVAL_CHANGE; + UpdateType type; FormTimer() { @@ -52,8 +51,6 @@ public: min = -1; isUpdateAt = false; isCountTimer = false; - refreshTime = 0; - type = UpdateType::TYPE_INTERVAL_CHANGE; } FormTimer(int64_t id, bool countTimer) @@ -64,8 +61,6 @@ public: min = -1; isUpdateAt = false; isCountTimer = countTimer; - refreshTime = 0; - type = UpdateType::TYPE_INTERVAL_CHANGE; } FormTimer(int64_t id, long repeatTime) @@ -76,8 +71,6 @@ public: min = -1; isUpdateAt = false; isCountTimer = true; - refreshTime = 0; - type = UpdateType::TYPE_INTERVAL_CHANGE; } FormTimer(int64_t id, int hourTime, int minTime) @@ -88,10 +81,6 @@ public: period = -1; isUpdateAt = true; isCountTimer = false; - refreshTime = 0; - type = UpdateType::TYPE_INTERVAL_CHANGE; - } - ~FormTimer(void){ } }; /** @@ -119,8 +108,6 @@ public: formId = id; settedTime = time; } - ~DynamicRefreshItem(void){ - } }; /** * @struct LimitInfo @@ -143,6 +130,57 @@ struct FormTimerCfg { int updateAtMin = -1; }; +// class TimerInfo : public ITimerInfo { +// public: +// TimerInfo(); +// virtual ~TimerInfo(); +// virtual void OnTrigger() override; +// virtual void SetType(const int &type) override; +// virtual void SetRepeat(bool repeat) override; +// virtual void SetInterval(const uint64_t &interval) override; +// virtual void SetWantAgent(std::shared_ptr wantAgent) override; +// void SetCallbackInfo(std::function callBack); + +// private: +// std::function callBack_; +// }; + +// TimerInfo::TimerInfo() +// { +// } + +// TimerInfo::~TimerInfo() +// { +// } + +// void TimerInfo::OnTrigger() +// { +// callBack_(); +// } + +// void TimerInfo::SetCallbackInfo(std::function callBack) +// { +// callBack_ = callBack; +// } + +// void TimerInfo::SetType(const int &_type) +// { +// type = _type; +// } + +// void TimerInfo::SetRepeat(bool _repeat) +// { +// repeat = _repeat; +// } +// void TimerInfo::SetInterval(const uint64_t &_interval) +// { +// interval = _interval; +// } +// void TimerInfo::SetWantAgent(std::shared_ptr _wantAgent) +// { +// wantAgent = _wantAgent; +// } + } // namespace AppExecFwk } // namespace OHOS #endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TIMER_TASK_H diff --git a/services/formmgr/include/form_timer_mgr.h b/services/formmgr/include/form_timer_mgr.h index 1ff69380079bdb562a21b9d0e7305aad3ef7901c..b710a2a07995b760074c3c8422bdeeeb6b036a13 100644 --- a/services/formmgr/include/form_timer_mgr.h +++ b/services/formmgr/include/form_timer_mgr.h @@ -33,8 +33,9 @@ #include "common_event_subscribe_info.h" #include "form_refresh_limiter.h" #include "form_timer.h" + #include "thread_pool.h" -// #include "timer.h" +#include "timer.h" namespace OHOS { namespace AppExecFwk { @@ -114,26 +115,22 @@ public: /** * @brief Handle system time changed. - * @return Returns true on success, false on failure. */ - bool HandleSystemTimeChanged(); + void HandleSystemTimeChanged(); /** * @brief Reset form limiter. - * @return Returns true on success, false on failure. */ - bool HandleResetLimiter(); + void HandleResetLimiter(); /** * @brief Update attime trigger. * @param updateTime Update time. - * @return Returns true on success, false on failure. */ - bool OnUpdateAtTrigger(long updateTime); + void OnUpdateAtTrigger(long updateTime); /** * @brief Dynamic time trigger. * @param updateTime Update time. - * @return Returns true on success, false on failure. */ - bool OnDynamicTimeTrigger(long updateTime); + void OnDynamicTimeTrigger(long updateTime); private: /** @@ -157,7 +154,6 @@ private: * @brief interval timer task timeout. */ void OnIntervalTimeOut(); - /** * @brief Get remind tasks. * @param remindTasks Remind tasks. @@ -207,9 +203,8 @@ private: /** * @brief Delete update at timer. * @param formId The Id of the form. - * @return Returns true on success, false on failure. */ - bool DeleteUpdateAtTimer(const int64_t formId); + void DeleteUpdateAtTimer(const int64_t formId); /** * @brief Update at timer task alarm. * @return Returns true on success, false on failure. @@ -220,16 +215,11 @@ private: * @return Returns true on success, false on failure. */ bool UpdateLimiterAlarm(); - /** - * @brief Clear limiter timer resource. - */ - void ClearLimiterTimerResource(); /** * @brief Delete dynamic refresh item. * @param formId The Id of the form. - * @return Returns true on success, false on failure. */ - bool DeleteDynamicItem(const int64_t formId); + void DeleteDynamicItem(const int64_t formId); /** * @brief Update dynamic refresh task alarm. * @return Returns true on success, false on failure. @@ -313,18 +303,14 @@ private: std::list updateAtTimerTasks_; std::vector dynamicRefreshTasks_; - std::shared_ptr timerReceiver_ = nullptr; - OHOS::ThreadPool* taskExecutor_ = nullptr; - - uint64_t intervalTimerId_ = 0L; - uint64_t updateAtTimerId_ = 0L; - uint64_t dynamicAlarmTimerId_ = 0L; - uint64_t limiterTimerId_= 0L; - + std::shared_ptr timerReceiver_; + OHOS::ThreadPool* taskExecutor_; + Utils::Timer* intervalTimer_; + long dynamicWakeUpTime_ = LONG_MAX; + long atTimerWakeUpTime_ = LONG_MAX; }; - } // namespace AppExecFwk } // namespace OHOS diff --git a/services/formmgr/include/form_timer_option.h b/services/formmgr/include/form_timer_option.h deleted file mode 100644 index d026163ee46779b03b3e08f36f4e6b75e34d86aa..0000000000000000000000000000000000000000 --- a/services/formmgr/include/form_timer_option.h +++ /dev/null @@ -1,81 +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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TIMER_INFO_H -#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TIMER_INFO_H - -#include "itimer_info.h" - -namespace OHOS { -namespace AppExecFwk { -/** - * @class FormTimerOption - * form timer option. - */ -class FormTimerOption : public OHOS::MiscServices::ITimerInfo { -public: - FormTimerOption(); - virtual ~FormTimerOption(); - virtual void OnTrigger() override; - virtual void SetType(const int &type) override; - virtual void SetRepeat(bool repeat) override; - virtual void SetInterval(const uint64_t &interval) override; - virtual void SetWantAgent(std::shared_ptr wantAgent) override; - void SetCallbackInfo(std::function callBack); - - private: - std::function callBack; -}; - -FormTimerOption::FormTimerOption() -{ -} - -FormTimerOption::~FormTimerOption() -{ -} - -void FormTimerOption::OnTrigger() -{ - callBack(); -} - -void FormTimerOption::SetCallbackInfo(std::function callBack) -{ - this->callBack = callBack; -} - -void FormTimerOption::SetType(const int &type) -{ - this->type = type; -} - -void FormTimerOption::SetRepeat(bool repeat) -{ - this->repeat = repeat; -} -void FormTimerOption::SetInterval(const uint64_t &interval) -{ - this->interval = interval; -} -void FormTimerOption::SetWantAgent(std::shared_ptr _wantAgent) -{ - this->wantAgent = _wantAgent; -} - -} // namespace AppExecFwk -} // namespace OHOS - -#endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_TIMER_INFO_H diff --git a/services/formmgr/include/form_util.h b/services/formmgr/include/form_util.h index d31b79dda6d239a0cb485b977bd6cb3e7df1570e..d043693889bcbd385f65318a8998f27ed0b7e056 100644 --- a/services/formmgr/include/form_util.h +++ b/services/formmgr/include/form_util.h @@ -1,101 +1,101 @@ -/* - * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_UTIL_H -#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_UTIL_H - -#include "want.h" - -namespace OHOS { -namespace AppExecFwk { -using Want = OHOS::AAFwk::Want; -/** - * @class FormUtil - * form utils. - */ -class FormUtil { -public: - /** - * @brief create want for form. - * @param formName The name of the form. - * @param specificationId specification id. - * @param isTemporaryForm temporary form or not. - * @param want The want of the form. - */ - static void CreateFormWant(const std::string &formName, const int32_t specificationId, const bool isTemporaryForm, - Want &want); - /** - * @brief create default want for form. - * @param want The want of the form.. - * @param uri The uri. - * @param userId user id. - */ - static void CreateDefaultFormWant(Want &want, const std::string &uri, const int32_t userId); - - /** - * @brief create udid for form. - * @return udid. - */ - static std::string GenerateUdid(); - - /** - * @brief create form id for form. - * @param udidHash udid hash - * @return new form id. - */ - static int64_t GenerateFormId(int64_t udidHash); - - /** - * @brief padding form id. - * @param formId The id of the form. - * @param udidHash udid hash. - * @return new form id. - */ - static int64_t PaddingUDIDHash(uint64_t formId, uint64_t udidHash); - - /** - * @brief create udid hash. - * @param udidHash udid hash. - * @return Returns true on success, false on failure. - */ - static bool GenerateUdidHash(int64_t &udidHash); - /** - * @brief Get current system nanosecond. - * @return Current system nanosecond. - */ - static long GetCurrentNanosecond(); - /** - * @brief Get current system millisecond. - * @return Current system millisecond. - */ - static long GetCurrentMillisecond(); - /** - * @brief Get millisecond from tm. - * @param tmAtTime tm time. - * @return Millisecond. - */ - static long GetMillisecondFromTm(struct tm &tmAtTime); - - /** - * @brief split string. - * @param in string. - * @param delim delimiter. - * @return string list. - */ - static std::vector StringSplit(const std::string &in, const std::string &delim); -}; -} // namespace AppExecFwk -} // namespace OHOS +/* + * 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 FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_UTIL_H +#define FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_UTIL_H + +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +using Want = OHOS::AAFwk::Want; +/** + * @class FormUtil + * form utils. + */ +class FormUtil { +public: + /** + * @brief create want for form. + * @param formName The name of the form. + * @param specificationId specification id. + * @param isTemporaryForm temporary form or not. + * @param want The want of the form. + */ + static void CreateFormWant(const std::string &formName, const int32_t specificationId, const bool isTemporaryForm, + Want &want); + /** + * @brief create default want for form. + * @param want The want of the form.. + * @param uri The uri. + * @param userId user id. + */ + static void CreateDefaultFormWant(Want &want, const std::string &uri, const int32_t userId); + + /** + * @brief create udid for form. + * @return udid. + */ + static std::string GenerateUdid(); + + /** + * @brief create form id for form. + * @param udidHash udid hash + * @return new form id. + */ + static int64_t GenerateFormId(int64_t udidHash); + + /** + * @brief padding form id. + * @param formId The id of the form. + * @param udidHash udid hash. + * @return new form id. + */ + static int64_t PaddingUDIDHash(int64_t formId, int64_t udidHash); + + /** + * @brief create udid hash. + * @param udidHash udid hash. + * @return Returns true on success, false on failure. + */ + static bool GenerateUdidHash(int64_t &udidHash); + /** + * @brief Get current system nanosecond. + * @return Current system nanosecond. + */ + static long GetCurrentNanosecond(); + /** + * @brief Get current system millisecond. + * @return Current system millisecond. + */ + static long GetCurrentMillisecond(); + /** + * @brief Get millisecond from tm. + * @param tmAtTime tm time. + * @return Millisecond. + */ + static long GetMillisecondFromTm(struct tm &tmAtTime); + + /** + * @brief split string. + * @param in string. + * @param delim delimiter. + * @return string list. + */ + static std::vector StringSplit(const std::string &in, const std::string &delim); +}; +} // namespace AppExecFwk +} // namespace OHOS #endif // FOUNDATION_APPEXECFWK_SERVICES_FORMMGR_INCLUDE_FORM_UTIL_H \ No newline at end of file diff --git a/services/formmgr/src/form_ability_connection.cpp b/services/formmgr/src/form_ability_connection.cpp index 35c58ca9ea98c75892555179ba81b52e76c49b22..2550f42fb4732daffacb005d1196812621de8bd7 100644 --- a/services/formmgr/src/form_ability_connection.cpp +++ b/services/formmgr/src/form_ability_connection.cpp @@ -37,10 +37,13 @@ void FormAbilityConnection::OnAbilityConnectDone( const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) { if (resultCode != ERR_OK) { - APP_LOGE("%{public}s, formId:%{public}" PRId64 ", resultCode:%{public}d", - __func__, formId_, resultCode); + APP_LOGE("%{public}s, abilityName:%{public}s, formId:%{public}" PRId64 ", resultCode:%{public}d", + __func__, element.GetAbilityName().c_str(), formId_, resultCode); return; } + // deviceId_ = element.GetDeviceID(); + // bundleName_ = element.GetBundleName(); + // abilityName_ = element.GetAbilityName(); if (isFreeInstall_) { // Handle free install for form provider app @@ -90,29 +93,12 @@ long FormAbilityConnection::GetConnectId() { return connectId_; } -/** - * @brief Get the provider Key - * - * @return The provider Key - */ -std::string FormAbilityConnection::GetProviderKey() -{ - if(bundleName_.empty() || abilityName_.empty()) { - return ""; - } - return bundleName_ + "::" + abilityName_; -} - -/** - * @brief Set the Provider Key - * - * @param bundleName bundleName - * @param abilityName abilityName - */ -void FormAbilityConnection::SetProviderKey(const std::string &bundleName, const std::string &abilityName) -{ - bundleName_ = bundleName; - abilityName_ = abilityName; -} +// std::string FormAbilityConnection::GetProviderKey() +// { +// if(deviceId_.empty() || bundleName_.empty() || abilityName_.empty()) { +// return ""; +// } +// return deviceId_ + "::" + bundleName_ + "::" + abilityName_; +// } } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_acquire_connection.cpp b/services/formmgr/src/form_acquire_connection.cpp index 3cd1770f269ea7642e4e52e5850075f489534c8b..282dd320de5659ea8404a4856c03fc7ee5955031 100644 --- a/services/formmgr/src/form_acquire_connection.cpp +++ b/services/formmgr/src/form_acquire_connection.cpp @@ -1,71 +1,67 @@ - -/* - * 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 "appexecfwk_errors.h" -#include "app_log_wrapper.h" -#include "form_acquire_connection.h" -#include "form_constants.h" -#include "form_supply_callback.h" -#include "form_task_mgr.h" -#include "form_util.h" -#include "ipc_types.h" -#include "message_parcel.h" -#include "want.h" - -namespace OHOS { -namespace AppExecFwk { -FormAcquireConnection::FormAcquireConnection( - const int64_t formId, - const FormItemInfo &info, - const WantParams &wantParams) - :formId_(formId), - info_(info), - wantParams_(wantParams) -{ - SetProviderKey(info.GetProviderBundleName(), info.GetAbilityName()); -} -/** - * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. - * @param element service ability's ElementName. - * @param remoteObject the session proxy of service ability. - * @param resultCode ERR_OK on success, others on failure. - */ -void FormAcquireConnection::OnAbilityConnectDone( - const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) -{ - APP_LOGI("%{public}s called.", __func__); - - if (resultCode != ERR_OK) { - APP_LOGE("%{public}s, abilityName:%{public}s, formId:%{public}" PRId64 ", resultCode:%{public}d", - __func__, element.GetAbilityName().c_str(), formId_, resultCode); - return; - } - FormSupplyCallback::GetInstance()->AddConnection(this); - Want want; - want.SetParams(wantParams_); - FormUtil::CreateFormWant(info_.GetFormName(), info_.GetSpecificationId(), info_.IsTemporaryForm(), want); - if (want.GetBoolParam(Constants::RECREATE_FORM_KEY, false)) { - want.SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_RECREATE_FORM); - } else { - want.SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_CREATE_FORM); - } - want.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); - FormTaskMgr::GetInstance().PostAcquireTask(formId_, want, remoteObject); -} -} // namespace AppExecFwk + +/* + * 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_acquire_connection.h" +#include "form_constants.h" +#include "form_supply_callback.h" +#include "form_task_mgr.h" +#include "form_util.h" +#include "ipc_types.h" +#include "message_parcel.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +FormAcquireConnection::FormAcquireConnection(const int64_t formId, const FormItemInfo &info, +const WantParams &wantParams) + :formId_(formId), + info_(info), + wantParams_(wantParams) +{ +} +/** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ +void FormAcquireConnection::OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{ + APP_LOGI("%{public}s called.", __func__); + if (resultCode != ERR_OK) { + APP_LOGE("%{public}s, abilityName:%{public}s, formId:%{public}" PRId64 ", resultCode:%{public}d", + __func__, element.GetAbilityName().c_str(), formId_, resultCode); + return; + } + FormSupplyCallback::GetInstance()->AddConnection(this); + Want want; + want.SetParams(wantParams_); + FormUtil::CreateFormWant(info_.GetFormName(), info_.GetSpecificationId(), info_.IsTemporaryForm(), want); + if (want.GetBoolParam(Constants::RECREATE_FORM_KEY, false)) { + want.SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_RECREATE_FORM); + } else { + want.SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_CREATE_FORM); + } + want.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); + FormTaskMgr::GetInstance().PostAcquireTask(formId_, want, remoteObject); +} +} // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_ams_helper.cpp b/services/formmgr/src/form_ams_helper.cpp index 7588442f149637b44f0a691b6096a44980cc19b6..7a393c4aa0e349f92c51a56f9bc7fd85f5a0719d 100644 --- a/services/formmgr/src/form_ams_helper.cpp +++ b/services/formmgr/src/form_ams_helper.cpp @@ -24,7 +24,6 @@ namespace OHOS { namespace AppExecFwk { -const int FORM_DISCONNECT_DELAY_TIME = 100; // ms FormAmsHelper::FormAmsHelper(){} FormAmsHelper::~FormAmsHelper(){} @@ -60,10 +59,10 @@ sptr FormAmsHelper::GetAbilityManager() * @return Returns ERR_OK on success, others on failure. */ ErrCode FormAmsHelper::ConnectServiceAbility( - const Want &want, const sptr &connect) + const Want &want, const sptr &connect) { APP_LOGI("%{public}s called.", __func__); - sptr ams = GetAbilityManager(); + sptr ams = GetAbilityManager(); if (ams == nullptr) { APP_LOGE("%{public}s:ability service not connect", __func__); return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED; @@ -71,42 +70,20 @@ ErrCode FormAmsHelper::ConnectServiceAbility( return ams->ConnectAbility(want, connect, nullptr); } /** - * @brief Disconnect ability, disconnect session with service ability. + * @brief DisConnectAbility, disconnect session with service ability. * @param want Special want for service type's ability. * @param connect Callback used to notify caller the result of connecting or disconnecting. * @return Returns ERR_OK on success, others on failure. */ -ErrCode FormAmsHelper::DisConnectServiceAbility(const sptr &connect) -{ APP_LOGI("%{public}s called.", __func__); - sptr ams = GetAbilityManager(); +ErrCode FormAmsHelper::DisConnectServiceAbility(const sptr &connect) +{ + sptr ams = GetAbilityManager(); if (ams == nullptr) { APP_LOGE("%{public}s:ability service not connect", __func__); return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED; } return ams->DisconnectAbility(connect); } -/** - * @brief Disconnect ability delay, disconnect session with service ability. - * @param want Special want for service type's ability. - * @param connect Callback used to notify caller the result of connecting or disconnecting. - * @return Returns ERR_OK on success, others on failure. - */ -ErrCode FormAmsHelper::DisConnectServiceAbilityDelay(const sptr &connect) -{ - if (eventHandler_ == nullptr) { - APP_LOGE("%{public}s fail, eventhandler invalidate", __func__); - return ERR_INVALID_OPERATION; - } - std::function disConnectAbilityFunc = std::bind( - &FormAmsHelper::DisConnectAbilityTask, - this, - connect); - if(!eventHandler_->PostTask(disConnectAbilityFunc, FORM_DISCONNECT_DELAY_TIME)) { - APP_LOGE("%{public}s, failed to disconnect ability", __func__); - return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED; - } - return ERR_OK; -} /** * @brief Add the ability manager instance for debug. * @param abilityManager the ability manager ipc object. @@ -115,20 +92,5 @@ void FormAmsHelper::SetAbilityManager(const sptr &abilit { abilityManager_ = abilityManager; } - -/** - * @brief Disconnect ability task, disconnect session with service ability. - * @param want Special want for service type's ability. - * @param connect Callback used to notify caller the result of connecting or disconnecting. - */ -void FormAmsHelper::DisConnectAbilityTask(const sptr &connect) -{ - sptr ams = GetAbilityManager(); - if (ams == nullptr) { - APP_LOGE("%{public}s, ability service not connect", __func__); - return; - } - ams->DisconnectAbility(connect); -} } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_batch_delete_connection.cpp b/services/formmgr/src/form_batch_delete_connection.cpp index 72935c04c17edbea20160a1abf9646940be2b71f..6da3a394eac36c6415e258d88a4a613fc7d020d0 100644 --- a/services/formmgr/src/form_batch_delete_connection.cpp +++ b/services/formmgr/src/form_batch_delete_connection.cpp @@ -27,11 +27,9 @@ namespace OHOS { namespace AppExecFwk { -FormBatchDeleteConnection::FormBatchDeleteConnection(const std::set &formIds, - const std::string &bundleName, const std::string &abilityName) +FormBatchDeleteConnection::FormBatchDeleteConnection(const std::set &formIds) :formIds_(formIds) { - SetProviderKey(bundleName, abilityName); } /** * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. diff --git a/services/formmgr/src/form_bms_helper.cpp b/services/formmgr/src/form_bms_helper.cpp index 2f2a0d8e53a6e02350a4610dc2f9aad7d0e2a100..22180d22631947ba5e665089e42185fe9b17df52 100644 --- a/services/formmgr/src/form_bms_helper.cpp +++ b/services/formmgr/src/form_bms_helper.cpp @@ -73,8 +73,8 @@ void FormBmsHelper::SetBundleManager(const sptr &bundleManager) */ void FormBmsHelper::NotifyModuleRemovable(const std::string &bundleName, const std::string &moduleName) { - APP_LOGI("%{public}s, bundleName:%{public}s, moduleName:%{public}s", - __func__, bundleName.c_str(), moduleName.c_str()); + APP_LOGI("%{public}s, bundleName:%{public}s, moduleName:%{public}s", __func__, bundleName.c_str(), + moduleName.c_str()); if (bundleName.empty() || moduleName.empty()) { return; } @@ -88,6 +88,7 @@ void FormBmsHelper::NotifyModuleRemovable(const std::string &bundleName, const s } std::string originId = IPCSkeleton::ResetCallingIdentity(); + // iBundleMgr->UpdateModuleRemovableFlag(bundleName, moduleName, FLAG_MODULE_NOT_USED_BY_FORM); IPCSkeleton::SetCallingIdentity(originId); } diff --git a/services/formmgr/src/form_cast_temp_connection.cpp b/services/formmgr/src/form_cast_temp_connection.cpp index e39ae1f08fe26152904d78e798e9d4d0e4e84a04..32b833d5304c06367518efc52f9718ce59675e53 100644 --- a/services/formmgr/src/form_cast_temp_connection.cpp +++ b/services/formmgr/src/form_cast_temp_connection.cpp @@ -1,58 +1,56 @@ - -/* - * 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 "appexecfwk_errors.h" -#include "app_log_wrapper.h" -#include "form_cast_temp_connection.h" -#include "form_constants.h" -#include "form_supply_callback.h" -#include "form_task_mgr.h" -#include "ipc_types.h" -#include "message_parcel.h" - -namespace OHOS { -namespace AppExecFwk { -FormCastTempConnection::FormCastTempConnection(const int64_t formId, const std::string &bundleName, - const std::string &abilityName) - :formId_(formId) -{ - SetProviderKey(bundleName, abilityName); -} -/** - * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. - * @param element service ability's ElementName. - * @param remoteObject the session proxy of service ability. - * @param resultCode ERR_OK on success, others on failure. - */ -void FormCastTempConnection::OnAbilityConnectDone( - const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) -{ - APP_LOGI("%{public}s called.", __func__); - if (resultCode != ERR_OK) { - APP_LOGE("%{public}s, abilityName:%{public}s, formId:%{public}" PRId64 ", resultCode:%{public}d", - __func__, element.GetAbilityName().c_str(), formId_, resultCode); - return; - } - FormSupplyCallback::GetInstance()->AddConnection(this); - - Want want; - want.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); - FormTaskMgr::GetInstance().PostCastTempTask(formId_, want, remoteObject); -} -} // namespace AppExecFwk + +/* + * 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_cast_temp_connection.h" +#include "form_constants.h" +#include "form_supply_callback.h" +#include "form_task_mgr.h" +#include "ipc_types.h" +#include "message_parcel.h" + +namespace OHOS { +namespace AppExecFwk { +FormCastTempConnection::FormCastTempConnection(const int64_t formId) + :formId_(formId) +{ +} +/** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ +void FormCastTempConnection::OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{ + APP_LOGI("%{public}s called.", __func__); + if (resultCode != ERR_OK) { + APP_LOGE("%{public}s, abilityName:%{public}s, formId:%{public}" PRId64 ", resultCode:%{public}d", + __func__, element.GetAbilityName().c_str(), formId_, resultCode); + return; + } + FormSupplyCallback::GetInstance()->AddConnection(this); + + Want want; + want.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); + FormTaskMgr::GetInstance().PostCastTempTask(formId_, want, remoteObject); +} +} // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_data_mgr.cpp b/services/formmgr/src/form_data_mgr.cpp index d845fc5760b438fdd940c45c35e2b3be7e12b892..de464fcaddda7461120a49cb4c233d231caf64c0 100644 --- a/services/formmgr/src/form_data_mgr.cpp +++ b/services/formmgr/src/form_data_mgr.cpp @@ -37,6 +37,32 @@ FormDataMgr::~FormDataMgr() APP_LOGI("destroy form data manager instance"); } +/** + * @brief Delete form js info by form record. + * @return Returns all form records map. + */ +std::map& FormDataMgr::GetAllFormRecord() +{ + return formRecords_; +} + +/** + * @brief Get all form client host record. + * @return Returns all form client host record. + */ +std::vector& FormDataMgr::GetClientRecords() +{ + return clientRecords_; +} + +/** + * @brief Get all form host records. + * @return Returns all form host records vector. + */ +std::vector& FormDataMgr::GetAllFormHostRecord() +{ + return clientRecords_; +} /** * @brief Allot form info by item info. * @param formId The Id of the form. @@ -77,8 +103,7 @@ FormRecord FormDataMgr::AllotFormRecord(const FormItemInfo &formInfo, const int * @param formId The Id of the form. * @return Returns true if this function is successfully called; returns false otherwise. */ -bool FormDataMgr::DeleteFormRecord(const int64_t formId) -{ +bool FormDataMgr::DeleteFormRecord(const int64_t formId) { APP_LOGI("%{public}s, delete form info", __func__); std::lock_guard lock(formRecordMutex_); auto iter = formRecords_.find(formId); @@ -130,8 +155,7 @@ bool FormDataMgr::AllotFormHostRecord(const FormItemInfo &info, const sptr &callerToken, - const int callingUid, FormHostRecord& record) -{ + const int callingUid, FormHostRecord& record) { if (callerToken == nullptr) { APP_LOGE("%{public}s, invalid param", __func__); return false; @@ -187,6 +211,7 @@ void FormDataMgr::CreateFormInfo(const int64_t formId, const FormRecord &record, formInfo.abilityName = record.abilityName; formInfo.formName = record.formName; formInfo.formTempFlg = record.formTempFlg; + // formInfo.setInstantProvider(record.instantProvider); } /** * @brief Check temp form count is max. @@ -196,7 +221,8 @@ int FormDataMgr::CheckTempEnoughForm() const { if (tempForms_.size() >= Constants::MAX_TEMP_FORMS) { APP_LOGW("%{public}s, already exist %{public}d temp forms in system", __func__, Constants::MAX_TEMP_FORMS); - return ERR_APPEXECFWK_FORM_MAX_SYSTEM_TEMP_FORMS; + // HiViewUtil.sendAddFormExceedLimitEvent(); + return ERR_MAX_SYSTEM_TEMP_FORMS; } return ERR_OK; } @@ -207,11 +233,11 @@ int FormDataMgr::CheckTempEnoughForm() const */ int FormDataMgr::CheckEnoughForm(const int callingUid) const { - APP_LOGI("%{public}s, callingUid: %{public}d", __func__, callingUid); + APP_LOGI("%{public}s, callingUid: %{public}d", __func__, callingUid); if (formRecords_.size() - tempForms_.size() >= Constants::MAX_FORMS) { APP_LOGW("%{public}s, already exist %{public}d forms in system", __func__, Constants::MAX_FORMS); - return ERR_APPEXECFWK_FORM_MAX_SYSTEM_FORMS; + return ERR_MAX_SYSTEM_FORMS; } int callingUidFormCounts = 0; @@ -220,9 +246,10 @@ int FormDataMgr::CheckEnoughForm(const int callingUid) const if (IsCallingUidValid(record.formUserUids) && !record.formTempFlg) { for (auto &userUid : record.formUserUids) { if (userUid == callingUid) { - if (++callingUidFormCounts >= Constants::MAX_RECORD_PER_APP) { + if (++callingUidFormCounts >= Constants::MAX_RECORD_PER_APP) + { APP_LOGW("%{public}s, already use %{public}d forms", __func__, Constants::MAX_RECORD_PER_APP); - return ERR_APPEXECFWK_FORM_MAX_FORMS_PER_CLIENT; + return ERR_MAX_RECORDS_PER_APP; } } } @@ -241,7 +268,7 @@ bool FormDataMgr::DeleteTempForm(const int64_t formId) auto iter = std::find(tempForms_.begin(), tempForms_.end(), formId); if (iter == tempForms_.end()) { APP_LOGE("%{public}s, temp form is not exist", __func__); - return false; + return true; } tempForms_.erase(iter); return true; @@ -319,8 +346,8 @@ bool FormDataMgr::DeleteFormUserUid(const int64_t formId, const int32_t uid) APP_LOGI("%{public}s, delete form user uid from form record", __func__); std::lock_guard lock(formRecordMutex_); if (ExistFormRecord(formId)) { - auto iter = std::find(formRecords_.at(formId).formUserUids.begin(), - formRecords_.at(formId).formUserUids.end(), uid); + auto iter = std::find(formRecords_.at(formId).formUserUids.begin(), formRecords_.at(formId).formUserUids.end(), + uid); if (iter != formRecords_.at(formId).formUserUids.end()) { formRecords_.at(formId).formUserUids.erase(iter); } @@ -378,7 +405,7 @@ bool FormDataMgr::GetFormRecord(const std::string &bundleName, std::vector lock(formRecordMutex_); std::map::iterator itFormRecord; - for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end(); itFormRecord++) { + for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end();itFormRecord++) { if (bundleName == itFormRecord->second.bundleName) { formInfos.emplace_back(itFormRecord->second); } @@ -468,7 +495,7 @@ void FormDataMgr::CleanHostRemovedForms(const std::vector &removedFormI std::vector matchedIds; std::lock_guard lock(formHostRecordMutex_); std::vector::iterator itHostRecord; - for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end(); itHostRecord++) { + for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end();itHostRecord++) { for (const int64_t& formId : removedFormIds) { if (itHostRecord->Contains(formId)) { matchedIds.emplace_back(formId); @@ -493,7 +520,7 @@ void FormDataMgr::HandleHostDied(const sptr &remoteHost) { std::lock_guard lock(formHostRecordMutex_); std::vector::iterator itHostRecord; - for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end(); ) { + for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end();) { if (remoteHost == itHostRecord->GetClientStub()) { HandleHostDiedForTempForms(*itHostRecord, recordTempForms); APP_LOGI("find died client, remove it"); @@ -508,7 +535,7 @@ void FormDataMgr::HandleHostDied(const sptr &remoteHost) { std::lock_guard lock(formRecordMutex_); std::map::iterator itFormRecord; - for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end(); ) { + for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end();) { int64_t formId = itFormRecord->first; // if temp form, remove it if (std::find(recordTempForms.begin(), recordTempForms.end(), formId) != recordTempForms.end()) { @@ -531,7 +558,7 @@ void FormDataMgr::HandleHostDiedForTempForms(const FormHostRecord &record, std:: { std::lock_guard lock(formTempMutex_); std::vector::iterator itForm; - for (itForm = tempForms_.begin(); itForm != tempForms_.end(); ) { + for (itForm = tempForms_.begin(); itForm != tempForms_.end();) { if (record.Contains(*itForm)) { recordTempForms.emplace_back(*itForm); itForm = tempForms_.erase(itForm); @@ -563,11 +590,6 @@ bool FormDataMgr::IsEnableRefresh(int64_t formId) */ int64_t FormDataMgr::GenerateFormId() { - // generate udidHash_ - if (udidHash_ < 0) { - APP_LOGE("%{public}s fail, generateFormId no invalid udidHash_", __func__); - return ERR_APPEXECFWK_FORM_COMMON_CODE; - } return FormUtil::GenerateFormId(udidHash_); } /** @@ -666,10 +688,8 @@ void FormDataMgr::SetCountTimerRefresh(const int64_t formId, const bool countTim * @param updatedForm Updated formnfo. * @return Returns true on success, false on failure. */ -bool FormDataMgr::GetUpdatedForm( - const FormRecord &record, - const std::vector &targetForms, - FormInfo &updatedForm) +bool FormDataMgr::GetUpdatedForm(const FormRecord &record, const std::vector &targetForms, +FormInfo &updatedForm) { if (targetForms.empty()) { APP_LOGE("%{public}s error, targetForms is empty.", __func__); @@ -708,12 +728,8 @@ void FormDataMgr::SetEnableUpdate(const int64_t formId, const bool enableUpdate) * @param updateAtHour Update at hour. * @param updateAtMin Update at minute. */ -void FormDataMgr::SetUpdateInfo( - const int64_t formId, - const bool enableUpdate, - const long updateDuration, - const int updateAtHour, - const int updateAtMin) +void FormDataMgr::SetUpdateInfo(const int64_t formId, const bool enableUpdate, const long updateDuration, +const int updateAtHour, const int updateAtMin) { std::lock_guard lock(formRecordMutex_); auto itFormRecord = formRecords_.find(formId); @@ -755,11 +771,12 @@ void FormDataMgr::CleanRemovedFormRecords(const std::string &bundleName, std::se APP_LOGI("%{public}s, clean removed form records", __func__); std::lock_guard lock(formRecordMutex_); std::map::iterator itFormRecord; - for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end(); ) { + for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end();) { auto itForm = std::find(removedForms.begin(), removedForms.end(), itFormRecord->first); if (itForm != removedForms.end()) { itFormRecord = formRecords_.erase(itFormRecord); - } else { + } + else { itFormRecord++; } } @@ -776,11 +793,12 @@ void FormDataMgr::CleanRemovedTempFormRecords(const std::string &bundleName, std { std::lock_guard lock(formRecordMutex_); std::map::iterator itFormRecord; - for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end(); ) { + for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end();) { if (itFormRecord->second.formTempFlg && bundleName == itFormRecord->second.bundleName) { removedTempForms.emplace(itFormRecord->second.formId); itFormRecord = formRecords_.erase(itFormRecord); - } else { + } + else { itFormRecord++; } } @@ -789,8 +807,8 @@ void FormDataMgr::CleanRemovedTempFormRecords(const std::string &bundleName, std if (removedTempForms.size() > 0) { std::lock_guard lock(formTempMutex_); std::vector::iterator itTemp; - for (itTemp = tempForms_.begin();itTemp != tempForms_.end(); ) { - if (removedTempForms.find(*itTemp) != removedTempForms.end()) { + for(itTemp = tempForms_.begin();itTemp != tempForms_.end();) { + if(removedTempForms.find(*itTemp) != removedTempForms.end()) { itTemp = tempForms_.erase(itTemp); } else { itTemp++; @@ -807,7 +825,7 @@ void FormDataMgr::GetReCreateFormRecordsByBundleName(const std::string &bundleNa { std::lock_guard lock(formRecordMutex_); std::map::iterator itFormRecord; - for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end(); itFormRecord++) { + for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end();itFormRecord++) { if (bundleName == itFormRecord->second.bundleName) { reCreateForms.emplace(itFormRecord->second.formId); } @@ -853,28 +871,12 @@ void FormDataMgr::UpdateHostNeedRefresh(const int64_t formId, const bool needRef { std::lock_guard lock(formHostRecordMutex_); std::vector::iterator itHostRecord; - for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end(); itHostRecord++) { + for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end();itHostRecord++) { if (itHostRecord->Contains(formId)) { itHostRecord->SetNeedRefresh(formId, needRefresh); } } } - -/** - * @brief Update form for host clients. - * @param formId The Id of the form. - * @param formProviderInfo FormProviderInfo object - */ -void FormDataMgr::UpdateFormProviderInfo(const int64_t formId, const FormProviderInfo &formProviderInfo) -{ - std::lock_guard lock(formRecordMutex_); - auto itFormRecord = formRecords_.find(formId); - if (itFormRecord == formRecords_.end()) { - APP_LOGE("%{public}s, form info not find", __func__); - return; - } - itFormRecord->second.formProviderInfo = formProviderInfo; -} /** * @brief Update form for host clients. * @param formId The Id of the form. @@ -886,7 +888,7 @@ bool FormDataMgr::UpdateHostForm(const int64_t formId, const FormRecord &formRec bool isUpdated = false; std::lock_guard lock(formHostRecordMutex_); std::vector::iterator itHostRecord; - for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end(); itHostRecord++) { + for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end();itHostRecord++) { if (itHostRecord->IsEnableRefresh(formId)) { // update form itHostRecord->OnUpdate(formId, formRecord); @@ -905,16 +907,13 @@ bool FormDataMgr::UpdateHostForm(const int64_t formId, const FormRecord &formRec * @param refreshForms Refresh forms * @return Returns ERR_OK on success, others on failure. */ -int32_t FormDataMgr::UpdateHostFormFlag( - std::vector formIds, - const sptr &callerToken, - const bool flag, - std::vector &refreshForms) +int32_t FormDataMgr::UpdateHostFormFlag(std::vector formIds, const sptr &callerToken, +const bool flag, std::vector &refreshForms) { APP_LOGI("%{public}s start, flag: %{public}d", __func__, flag); std::lock_guard lock(formHostRecordMutex_); std::vector::iterator itHostRecord; - for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end(); itHostRecord++) { + for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end();itHostRecord++) { if (callerToken == itHostRecord->GetClientStub()) { for (const int64_t formId : formIds) { if (formId <= 0) { @@ -968,7 +967,7 @@ int32_t FormDataMgr::UpdateHostFormFlag( } } APP_LOGE("%{public}s, can't find target client", __func__); - return ERR_APPEXECFWK_FORM_INVALID_PARAM; + return ERR_FORM_INVALID_PARAM; } /** * @brief Find matched form id. @@ -977,16 +976,13 @@ int32_t FormDataMgr::UpdateHostFormFlag( */ int64_t FormDataMgr::FindMatchedFormId(const int64_t formId) { - uint64_t unsignedFormId = static_cast(formId); - if ((unsignedFormId & 0xffffffff00000000L) != 0) { + if ((formId & 0xffffffff00000000L) != 0) { return formId; } std::lock_guard lock(formRecordMutex_); std::map::iterator itFormRecord; - for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end(); itFormRecord++) { - uint64_t unsignedFormId = static_cast(formId); - uint64_t unsignedItFormRecordFirst = static_cast(itFormRecord->first); - if ((unsignedItFormRecordFirst & 0x00000000ffffffffL) == (unsignedFormId & 0x00000000ffffffffL)) { + for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end();itFormRecord++) { + if ((itFormRecord->first & 0x00000000ffffffffL) == (formId & 0x00000000ffffffffL)) { return itFormRecord->first; } } @@ -1001,7 +997,7 @@ void FormDataMgr::ClearHostDataByUId(const int uId) { std::lock_guard lock(formHostRecordMutex_); std::vector::iterator itHostRecord; - for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end(); ) { + for (itHostRecord = clientRecords_.begin(); itHostRecord != clientRecords_.end();) { if (itHostRecord->GetCallerUid() == uId) { itHostRecord->CleanResource(); itHostRecord = clientRecords_.erase(itHostRecord); @@ -1016,27 +1012,21 @@ void FormDataMgr::ClearHostDataByUId(const int uId) * @param noHostTempFormsMap no host temp forms. * @param foundFormsMap Form Id list. */ -void FormDataMgr::GetNoHostTempForms( - const int uid, std::map> &noHostTempFormsMap, - std::map &foundFormsMap) +void FormDataMgr::GetNoHostTempForms(const int uid, std::map> &noHostTempFormsMap, +std::map &foundFormsMap) { std::lock_guard lock(formRecordMutex_); std::map::iterator itFormRecord; - for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end(); itFormRecord++) { + for (itFormRecord = formRecords_.begin(); itFormRecord != formRecords_.end();itFormRecord++) { if (itFormRecord->second.formTempFlg) { - auto itUid = std::find(itFormRecord->second.formUserUids.begin(), - itFormRecord->second.formUserUids.end(), uid); + auto itUid = std::find(itFormRecord->second.formUserUids.begin(), itFormRecord->second.formUserUids.end(), + uid); if (itUid != itFormRecord->second.formUserUids.end()) { itFormRecord->second.formUserUids.erase(itUid); if (itFormRecord->second.formUserUids.empty()) { FormIdKey formIdKey; formIdKey.bundleName = itFormRecord->second.bundleName; formIdKey.abilityName = itFormRecord->second.abilityName; - formIdKey.moduleName = ""; - formIdKey.formName = ""; - formIdKey.specificationId = 0; - formIdKey.orientation = 0; auto itIdsSet = noHostTempFormsMap.find(formIdKey); if (itIdsSet == noHostTempFormsMap.end()) { std::set formIdsSet; @@ -1089,8 +1079,7 @@ void FormDataMgr::ParseIntervalConfig(FormRecord &record, const int configDurati * @param record The form record. * @param info form item info. */ -void FormDataMgr::ParseAtTimerConfig(FormRecord &record, const FormItemInfo &info) const -{ +void FormDataMgr::ParseAtTimerConfig(FormRecord record, const FormItemInfo &info) const { record.isEnableUpdate = false; record.updateDuration = 0; std::string configAtTime = info.GetScheduledUpdateTime(); @@ -1114,7 +1103,7 @@ void FormDataMgr::ParseAtTimerConfig(FormRecord &record, const FormItemInfo &inf } if (hour < Constants::MIN_TIME || hour > Constants::MAX_HOUR || min < Constants::MIN_TIME || min > - Constants::MAX_MININUTE) { + Constants::MAX_MININUTE) { APP_LOGE("%{public}s, time is invalid", __func__); return; } diff --git a/services/formmgr/src/form_db_cache.cpp b/services/formmgr/src/form_db_cache.cpp index 1625e676ecb3846927d9455dcf13606a3ee893f5..a866048f6fa5622dd828c73af757682414b17062 100644 --- a/services/formmgr/src/form_db_cache.cpp +++ b/services/formmgr/src/form_db_cache.cpp @@ -56,6 +56,12 @@ void FormDbCache::Start() } } +// void FormDbCache::Stop() +// { +// APP_LOGI("stop"); +// dataStorage_->Stop(); +// } + /** * @brief Save or update form data to DbCache and DB. * @param formDBInfo Form data. @@ -128,7 +134,7 @@ ErrCode FormDbCache::DeleteFormInfo(int64_t formId) if (dataStorage_->DeleteStorageFormInfo(std::to_string(formId)) == ERR_OK) { return ERR_OK; } else { - return ERR_APPEXECFWK_FORM_COMMON_CODE; + return ERR_APPEXECFWK_FORM_JSON_DELETE_FAIL; } } /** @@ -141,7 +147,7 @@ ErrCode FormDbCache::DeleteFormInfoByBundleName(const std::string &bundleName, s { std::lock_guard lock(formDBInfosMutex_); std::vector::iterator itRecord; - for (itRecord = formDBInfos_.begin(); itRecord != formDBInfos_.end(); ) { + for (itRecord = formDBInfos_.begin(); itRecord != formDBInfos_.end();) { if (bundleName == itRecord->bundleName) { int64_t formId = itRecord->formId; if (dataStorage_->DeleteStorageFormInfo(std::to_string(formId)) == ERR_OK) { @@ -156,6 +162,19 @@ ErrCode FormDbCache::DeleteFormInfoByBundleName(const std::string &bundleName, s } return ERR_OK; } +// bool FormDbCache::BatchDeleteForms(std::vector formIds) +// { +// std::lock_guard lock(formDBInfosMutex_); +// for (const auto& formId : formIds) { +// FormDBInfo tmpForm; +// tmpForm.formId_ = formId; +// auto iter = find(formDBInfos_.begin(), formDBInfos_.end(), tmpForm); +// if (iter != formDBInfos_.end()) { +// formDBInfos_.erase(iter); +// } +// } +// return dataStorage_->BatchDeleteForms(formIds); +// } /** * @brief Get all form data from DbCache. @@ -189,7 +208,7 @@ ErrCode FormDbCache::GetDBRecord(const int64_t formId, FormRecord &record) const } } APP_LOGE("%{public}s, not find formId[%{public}" PRId64 "]", __func__, formId); - return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + return ERR_APPEXECFWK_FORM_DBCACHE_FIND_FAIL; } /** * @brief Get record from DB cache with formId @@ -207,7 +226,7 @@ ErrCode FormDbCache::GetDBRecord(const int64_t formId, FormDBInfo &record) const } } APP_LOGE("%{public}s, not find formId[%{public}" PRId64 "]", __func__, formId); - return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + return ERR_APPEXECFWK_FORM_DBCACHE_FIND_FAIL; } /** * @brief Use record save or update DB data and DB cache with formId @@ -219,6 +238,7 @@ ErrCode FormDbCache::UpdateDBRecord(const int64_t formId, const FormRecord &reco { FormDBInfo formDBInfo(formId, record); return FormDbCache::GetInstance().SaveFormInfo(formDBInfo); + // FormBmsHelper::GetInstance().NotifyModuleNotRemovable(formDBInfo.bundleName, formDBInfo.moduleName); } /** * @brief Get no host db record. @@ -227,8 +247,8 @@ ErrCode FormDbCache::UpdateDBRecord(const int64_t formId, const FormRecord &reco * @param foundFormsMap Form Id list. * @return Returns ERR_OK on success, others on failure. */ -ErrCode FormDbCache::GetNoHostDBForms(const int uid, std::map> &noHostFormDBList, std::map &foundFormsMap) +ErrCode FormDbCache::GetNoHostDBForms(const int uid, std::map> &noHostFormDBList, +std::map &foundFormsMap) { std::lock_guard lock(formDBInfosMutex_); for (FormDBInfo& dbInfo : formDBInfos_) { @@ -238,10 +258,6 @@ ErrCode FormDbCache::GetNoHostDBForms(const int uid, std::map formIdsSet; diff --git a/services/formmgr/src/form_db_info.cpp b/services/formmgr/src/form_db_info.cpp index f47f45c4f75f789c13fe28dee49f1ad376f98ba4..4846b9bf795b361060a1411c929149d0d1a08cc0 100644 --- a/services/formmgr/src/form_db_info.cpp +++ b/services/formmgr/src/form_db_info.cpp @@ -1,79 +1,135 @@ -/* - * 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 "app_log_wrapper.h" -#include "form_db_info.h" -namespace OHOS { -namespace AppExecFwk { -namespace { -const std::string FORM_ID = "formId"; -const std::string FORM_NAME = "formName"; -const std::string BUNDLE_NAME = "bundleName"; -const std::string MODULE_NAME = "moduleName"; -const std::string ABILITY_NAME = "abilityName"; -const std::string FORM_USER_UIDS = "formUserUids"; -} - -/** - * @brief Transform the InnerFormInfo object to json. - * @param jsonObject Indicates the obtained json object. - * @return - */ -void InnerFormInfo::ToJson(nlohmann::json &jsonObject) const -{ - jsonObject[FORM_ID] = formDBInfo_.formId; - jsonObject[FORM_NAME] = formDBInfo_.formName; - jsonObject[BUNDLE_NAME] = formDBInfo_.bundleName; - jsonObject[MODULE_NAME] = formDBInfo_.moduleName; - jsonObject[ABILITY_NAME] = formDBInfo_.abilityName; - jsonObject[FORM_USER_UIDS] = formDBInfo_.formUserUids; -} - -/** - * @brief Transform the json object to InnerFormInfo object. - * @param jsonObject Indicates the obtained json object. - * @return - */ -bool InnerFormInfo::FromJson(const nlohmann::json &jsonObject) -{ - formDBInfo_.formId = jsonObject.at(FORM_ID).get(); - formDBInfo_.formName = jsonObject.at(FORM_NAME).get(); - formDBInfo_.bundleName = jsonObject.at(BUNDLE_NAME).get(); - formDBInfo_.moduleName = jsonObject.at(MODULE_NAME).get(); - formDBInfo_.abilityName = jsonObject.at(ABILITY_NAME).get(); - formDBInfo_.formUserUids = jsonObject.at(FORM_USER_UIDS).get>(); - - return true; -} - -void InnerFormInfo::AddUserUid(const int callingUid) -{ - auto iter = std::find(formDBInfo_.formUserUids.begin(), formDBInfo_.formUserUids.end(), callingUid); - if (iter == formDBInfo_.formUserUids.end()) { - formDBInfo_.formUserUids.push_back(callingUid); - } -} - -bool InnerFormInfo::DeleteUserUid(const int callingUid) -{ - auto iter = std::find(formDBInfo_.formUserUids.begin(), formDBInfo_.formUserUids.end(), callingUid); - if (iter == formDBInfo_.formUserUids.end()) { - return false; - } - formDBInfo_.formUserUids.erase(iter); - return true; -} -} // namespace AppExecFwk +/* + * 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 "app_log_wrapper.h" +#include "form_db_info.h" +namespace OHOS { +namespace AppExecFwk { +namespace { +const std::string FORM_ID = "formId"; +const std::string FORM_NAME = "formName"; +const std::string BUNDLE_NAME = "bundleName"; +const std::string MODULE_NAME = "moduleName"; +const std::string ABILITY_NAME = "abilityName"; +const std::string FORM_USER_UIDS = "formUserUids"; +} + +// void to_json(nlohmann::json &jsonObject, const FormDBInfo &info) +// { +// jsonObject = nlohmann::json{ +// {FORM_ID, info.formId}, +// {USER_ID, info.userId}, +// {BUNDLE_NAME, info.bundleName}, +// {MODULE_NAME, info.moduleName}, +// {ABILITY_NAME, info.abilityName}, +// {FORM_USER_UIDS, info.formUserUids} +// }; +// } + +/** + * @brief Transform the InnerFormInfo object to json. + * @param jsonObject Indicates the obtained json object. + * @return + */ +void InnerFormInfo::ToJson(nlohmann::json &jsonObject) const +{ + jsonObject[FORM_ID] = formDBInfo_.formId; + jsonObject[FORM_NAME] = formDBInfo_.formName; + jsonObject[BUNDLE_NAME] = formDBInfo_.bundleName; + jsonObject[MODULE_NAME] = formDBInfo_.moduleName; + jsonObject[ABILITY_NAME] = formDBInfo_.abilityName; + jsonObject[FORM_USER_UIDS] = formDBInfo_.formUserUids; +} + +// void from_json(const nlohmann::json &jsonObject, FormDBInfo &info) +// { +// const auto &jsonObjectEnd = jsonObject.end(); +// if (jsonObject.find(FORM_ID) != jsonObjectEnd) { +// info.formId = jsonObject.at(FORM_ID).get(); +// } + +// if (jsonObject.find(USER_ID) != jsonObjectEnd) { +// info.userId = jsonObject.at(USER_ID).get(); +// } + +// if (jsonObject.find(BUNDLE_NAME) != jsonObjectEnd) { +// info.bundleName = jsonObject.at(BUNDLE_NAME).get(); +// } + +// if (jsonObject.find(MODULE_NAME) != jsonObjectEnd) { +// info.moduleName = jsonObject.at(MODULE_NAME).get(); +// } + +// if (jsonObject.find(ABILITY_NAME) != jsonObjectEnd) { +// info.abilityName = jsonObject.at(ABILITY_NAME).get(); +// } + +// if (jsonObject.find(FORM_USER_UIDS) != jsonObjectEnd) { +// info.formUserUids = jsonObject.at(FORM_USER_UIDS).get>(); +// } +// } + +/** + * @brief Transform the json object to InnerFormInfo object. + * @param jsonObject Indicates the obtained json object. + * @return + */ +bool InnerFormInfo::FromJson(const nlohmann::json &jsonObject) +{ + // try { + formDBInfo_.formId = jsonObject.at(FORM_ID).get(); + formDBInfo_.formName = jsonObject.at(FORM_NAME).get(); + formDBInfo_.bundleName = jsonObject.at(BUNDLE_NAME).get(); + formDBInfo_.moduleName = jsonObject.at(MODULE_NAME).get(); + formDBInfo_.abilityName = jsonObject.at(ABILITY_NAME).get(); + formDBInfo_.formUserUids = jsonObject.at(FORM_USER_UIDS).get>(); + + // } catch (nlohmann::detail::parse_error &exception) { + // APP_LOGE("%{public}s, has a parse_error:%{public}s", __func__, exception.what()); + // return false; + // } catch (nlohmann::detail::type_error &exception) { + // APP_LOGE("%{public}s, has a type_error:%{public}s.", __func__, exception.what()); + // return false; + // } catch (nlohmann::detail::out_of_range &exception) { + // APP_LOGE("%{public}s, has an out_of_range exception:%{public}s.", __func__, exception.what()); + // return false; + // } catch(...) { + // APP_LOGE("%{public}s, other exception", __func__); + // return false; + // } + return true; +} + +void InnerFormInfo::AddUserUid(const int callingUid) +{ + // std::lock_guard lock(mutex_); + auto iter = std::find(formDBInfo_.formUserUids.begin(), formDBInfo_.formUserUids.end(), callingUid); + if (iter == formDBInfo_.formUserUids.end()) { + formDBInfo_.formUserUids.push_back(callingUid); + } +} + +bool InnerFormInfo::DeleteUserUid(const int callingUid) +{ + // std::lock_guard lock(mutex_); + auto iter = std::find(formDBInfo_.formUserUids.begin(), formDBInfo_.formUserUids.end(), callingUid); + if (iter == formDBInfo_.formUserUids.end()) { + return false; + } + formDBInfo_.formUserUids.erase(iter); + return true; +} +} // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_delete_connection.cpp b/services/formmgr/src/form_delete_connection.cpp index 77e3ea378936cb8c57ec61c6259a9f698c48427c..40312f1beeccb37689204681b6486c3280ebfb38 100755 --- a/services/formmgr/src/form_delete_connection.cpp +++ b/services/formmgr/src/form_delete_connection.cpp @@ -1,60 +1,58 @@ - -/* - * 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 "appexecfwk_errors.h" -#include "app_log_wrapper.h" -#include "form_constants.h" -#include "form_delete_connection.h" -#include "form_supply_callback.h" -#include "form_task_mgr.h" -#include "ipc_types.h" -#include "message_parcel.h" -#include "want.h" - -namespace OHOS { -namespace AppExecFwk { -FormDeleteConnection::FormDeleteConnection(const int64_t formId, const std::string &bundleName, - const std::string &abilityName) - :formId_(formId) -{ - SetProviderKey(bundleName, abilityName); -} -/** - * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. - * @param element service ability's ElementName. - * @param remoteObject the session proxy of service ability. - * @param resultCode ERR_OK on success, others on failure. - */ -void FormDeleteConnection::OnAbilityConnectDone( - const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) -{ - APP_LOGI("%{public}s called.", __func__); - if (resultCode != ERR_OK) { - APP_LOGE("%{public}s, abilityName:%{public}s, formId:%{public}" PRId64 ", resultCode:%{public}d", - __func__, element.GetAbilityName().c_str(), formId_, resultCode); - return; - } - FormSupplyCallback::GetInstance()->AddConnection(this); - - Want want; - want.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); - APP_LOGD("%{public}s, connectId :%{public}ld", __func__, this->GetConnectId()); - FormTaskMgr::GetInstance().PostDeleteTask(formId_, want, remoteObject); -} -} // namespace AppExecFwk + +/* + * 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_constants.h" +#include "form_delete_connection.h" +#include "form_supply_callback.h" +#include "form_task_mgr.h" +#include "ipc_types.h" +#include "message_parcel.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +FormDeleteConnection::FormDeleteConnection(const int64_t formId) + :formId_(formId) +{ +} +/** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * @param element service ability's ElementName. + * @param remoteObject the session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + */ +void FormDeleteConnection::OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{ + APP_LOGI("%{public}s called.", __func__); + if (resultCode != ERR_OK) { + APP_LOGE("%{public}s, abilityName:%{public}s, formId:%{public}" PRId64 ", resultCode:%{public}d", + __func__, element.GetAbilityName().c_str(), formId_, resultCode); + return; + } + FormSupplyCallback::GetInstance()->AddConnection(this); + + Want want; + want.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); + APP_LOGD("%{public}s, connectId :%{public}ld", __func__, this->GetConnectId()); + FormTaskMgr::GetInstance().PostDeleteTask(formId_, want, remoteObject); +} +} // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_dump_mgr.cpp b/services/formmgr/src/form_dump_mgr.cpp index 1961cc2ff567e81ad602ff5d431a8607d19c1320..0f89ca359dc4b799450e191d1f5a8a6e5648ef29 100644 --- a/services/formmgr/src/form_dump_mgr.cpp +++ b/services/formmgr/src/form_dump_mgr.cpp @@ -146,7 +146,7 @@ void FormDumpMgr::DumpFormInfo(const FormRecord &formRecordInfo, std::string &fo if (formRecordInfo.formUserUids.size() > 0) { formInfo += " formUserUids ["; for (auto &uId : formRecordInfo.formUserUids) { - formInfo += " Uid [" + std::to_string(uId) + "]"; + formInfo +=" Uid [" + std::to_string(uId) + "]"; } formInfo += "]"; } diff --git a/services/formmgr/src/form_event_notify_connection.cpp b/services/formmgr/src/form_event_notify_connection.cpp index 6933e3887e49ab5066893b3adc6719ad917ca930..cea26ab8e3ff06a79d7343523a70ae7476862f77 100644 --- a/services/formmgr/src/form_event_notify_connection.cpp +++ b/services/formmgr/src/form_event_notify_connection.cpp @@ -1,60 +1,60 @@ - -/* - * 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 "appexecfwk_errors.h" -#include "app_log_wrapper.h" -#include "form_constants.h" -#include "form_event_notify_connection.h" -#include "form_supply_callback.h" -#include "form_task_mgr.h" -#include "ipc_types.h" -#include "message_parcel.h" -#include "want.h" - -namespace OHOS { -namespace AppExecFwk { -FormEventNotifyConnection::FormEventNotifyConnection(const std::vector formEvents, - const int32_t formVisibleType, const std::string &bundleName, const std::string &abilityName) - :formEvents_(formEvents), - formVisibleType_(formVisibleType) -{ - SetProviderKey(bundleName, abilityName); -} -/** - * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. - * - * @param element Service ability's ElementName. - * @param remoteObject The session proxy of service ability. - * @param resultCode ERR_OK on success, others on failure. - * @return none. - */ -void FormEventNotifyConnection::OnAbilityConnectDone( - const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) -{ - APP_LOGI("%{public}s called.", __func__); - if (resultCode != ERR_OK) { - APP_LOGE("%{public}s, abilityName:%{public}s, resultCode:%{public}d", - __func__, element.GetAbilityName().c_str(), resultCode); - return; - } - FormSupplyCallback::GetInstance()->AddConnection(this); - - Want want; - want.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); - FormTaskMgr::GetInstance().PostEventNotifyTask(formEvents_, formVisibleType_, want, remoteObject); -} -} // namespace AppExecFwk + +/* + * 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_constants.h" +#include "form_event_notify_connection.h" +#include "form_supply_callback.h" +#include "form_task_mgr.h" +#include "ipc_types.h" +#include "message_parcel.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +FormEventNotifyConnection::FormEventNotifyConnection(const std::vector formEvents, +const int32_t formVisibleType) + :formEvents_(formEvents), + formVisibleType_(formVisibleType) +{ +} +/** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element Service ability's ElementName. + * @param remoteObject The session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + * @return none. + */ +void FormEventNotifyConnection::OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{ + APP_LOGI("%{public}s called.", __func__); + + if (resultCode != ERR_OK) { + APP_LOGE("%{public}s, abilityName:%{public}s, resultCode:%{public}d", + __func__, element.GetAbilityName().c_str(), resultCode); + return; + } + FormSupplyCallback::GetInstance()->AddConnection(this); + + Want want; + want.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); + FormTaskMgr::GetInstance().PostEventNotifyTask(formEvents_, formVisibleType_, want, remoteObject); +} +} // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_host_callback.cpp b/services/formmgr/src/form_host_callback.cpp index 6348112c8112b8d0a394314fd785b88985619862..2bcae1eb5906fb2f89a8a1581891982cc390d6fa 100644 --- a/services/formmgr/src/form_host_callback.cpp +++ b/services/formmgr/src/form_host_callback.cpp @@ -32,7 +32,7 @@ namespace AppExecFwk { * @return Returns ERR_OK on success, others on failure. */ void FormHostCallback::OnAcquired(const int64_t formId, const FormRecord& record, - const sptr &callerToken) +const sptr &callerToken) { APP_LOGD("FormHostCallback OnAcquired, formId:%{public}" PRId64 "", formId); FormTaskMgr::GetInstance().PostAcquireTaskToHost(formId, record, callerToken); diff --git a/services/formmgr/src/form_host_record.cpp b/services/formmgr/src/form_host_record.cpp index 2644d0273c280c46033eaaccd1db0547d996dbe2..7b276a1c8b7bface38ece447b3a13c09c3f949ec 100644 --- a/services/formmgr/src/form_host_record.cpp +++ b/services/formmgr/src/form_host_record.cpp @@ -1,270 +1,270 @@ -/* - * 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 "form_host_record.h" -#include "form_task_mgr.h" - -namespace OHOS { -namespace AppExecFwk { -/** - * @brief Add form id. - * @param formId The Id of the form. - */ -void FormHostRecord::AddForm(int64_t formId) -{ - if (forms_.find(formId) != forms_.end()) { - return; - } - forms_[formId] = true; -} -/** - * @brief Delete form id. - * @param formId The Id of the form. - */ -void FormHostRecord::DelForm(int64_t formId) -{ - forms_.erase(formId); -} -/** - * @brief forms_ is empty or not. - * @return forms_ is empty or not. - */ -bool FormHostRecord::IsEmpty() const -{ - return forms_.empty(); -} -/** - * @brief formId is in forms_ or not. - * @param formId The Id of the form. - * @return formId is in forms_ or not. - */ -bool FormHostRecord::Contains(int64_t formId) const -{ - return forms_.find(formId) != forms_.end(); -} - -/** - * @brief Set refresh enable flag. - * @param formId The Id of the form. - * @param flag True for enbale, false for disable. - */ -void FormHostRecord::SetEnableRefresh(int64_t formId, bool flag) -{ - if (forms_.find(formId) == forms_.end()) { - return; - } - forms_[formId] = flag; -} -/** - * @brief Refresh enable or not. - * @param formId The Id of the form. - * @return true on enbale, false on disable.. - */ -bool FormHostRecord::IsEnableRefresh(int64_t formId) const -{ - auto result = forms_.find(formId); - if (result != forms_.end()) { - return result->second; - } - return false; -} -/** - * @brief Set need refresh enable flag. - * @param formId The Id of the form. - * @param flag True for enbale, false for disable. - */ -void FormHostRecord::SetNeedRefresh(int64_t formId, bool flag) -{ - needRefresh_[formId] = flag; -} -/** - * @brief Need Refresh enable or not. - * @param formId The Id of the form. - * @return true on enbale, false on disable.. - */ -bool FormHostRecord::IsNeedRefresh(int64_t formId) const -{ - auto result = needRefresh_.find(formId); - if (result != needRefresh_.end()) { - return result->second; - } - return false; -} -/** - * @brief Get clientStub_. - * @return clientStub_. - */ -sptr FormHostRecord::GetClientStub() const -{ - return clientStub_; -} - -/** - * @brief Send form data to form host. - * @param id The Id of the form. - * @param record Form record. - */ -void FormHostRecord::OnAcquire(int64_t id, const FormRecord &record) -{ - APP_LOGD("FormHostRecord OnAcquire"); - if (clientImpl_ == nullptr) { - APP_LOGE("%{public}s: clientImpl_ can not be NULL", __func__); - return; - } - - clientImpl_->OnAcquired(id, record, clientStub_); -} - -/** - * @brief Update form data to form host. - * @param id The Id of the form. - * @param record Form record. - */ -void FormHostRecord::OnUpdate(int64_t id, const FormRecord &record) -{ - APP_LOGI("%{public}s start.", __func__); - - if (clientImpl_ == nullptr) { - APP_LOGE("%{public}s: clientImpl_ can not be null.", __func__); - return; - } - - clientImpl_->OnUpdate(id, record, clientStub_); -} - -/** - * @brief Send form uninstall message to form host. - * @param id The Id of the form. - * @param record Form record. - */ -void FormHostRecord::OnFormUninstalled(std::vector &formIds) -{ - APP_LOGI("%{public}s start.", __func__); - - if (clientImpl_ == nullptr) { - APP_LOGE("%{public}s: clientImpl_ can not be null.", __func__); - return; - } - clientImpl_->OnUninstall(formIds, clientStub_); -} -/** - * @brief Release resource. - * @param id The Id of the form. - * @param record Form record. - */ -void FormHostRecord::CleanResource() -{ - if (clientStub_ != nullptr && deathRecipient_ != nullptr) { - clientStub_->RemoveDeathRecipient(deathRecipient_); - clientStub_ = nullptr; - deathRecipient_ = nullptr; - } -} -/** - * @brief Set value of callerUid_. - * @param callerUid Caller uid. - */ -void FormHostRecord::SetCallerUid(const int callerUid) -{ - callerUid_ = callerUid; -} -/** - * @brief Set value of clientStub_. - * @param clientStub remote object. - */ -void FormHostRecord::SetClientStub(const sptr &clientStub) -{ - clientStub_ = clientStub; -} -/** - * @brief Set value of clientImpl_. - * @param clientImpl Form host callback object. - */ -void FormHostRecord::SetClientImpl(const std::shared_ptr &clientImpl) -{ - clientImpl_ = clientImpl; -} -/** - * @brief Get deathRecipient_. - * @return deathRecipient_. - */ -sptr FormHostRecord::GetDeathRecipient() const -{ - return deathRecipient_; -} -/** - * @brief Set value of deathRecipient_. - * @param clientImpl DeathRecipient object. - */ -void FormHostRecord::SetDeathRecipient(const sptr &deathRecipient) -{ - deathRecipient_ = deathRecipient; -} -/** - * @brief Add deathRecipient object to clientStub_. - * @param deathRecipient DeathRecipient object. - */ -void FormHostRecord::AddDeathRecipient(const sptr &deathRecipient) -{ - clientStub_->AddDeathRecipient(deathRecipient); -} - -/** - * @brief Create form host record. - * @param info The form item info. - * @param callback remote object. - * @param callingUid Calling uid. - */ -FormHostRecord FormHostRecord::CreateRecord(const FormItemInfo &info, - const sptr &callback, int callingUid) -{ - FormHostRecord record; - record.SetHostBundleName(info.GetHostBundleName()); - record.SetCallerUid(callingUid); - record.SetClientStub(callback); - record.SetClientImpl(std::make_shared()); - record.SetDeathRecipient(new FormHostRecord::ClientDeathRecipient()); - record.AddDeathRecipient(record.GetDeathRecipient()); - - return record; -} - -/** - * @brief handle remote object died event. - * @param remote remote object. - */ -void FormHostRecord::ClientDeathRecipient::OnRemoteDied(const wptr &remote) -{ - APP_LOGD("Form remote died"); - FormTaskMgr::GetInstance().PostHostDiedTask(remote.promote()); -} - -/** - * @brief Get hostBundleName_. - * @return hostBundleName_. - */ -std::string FormHostRecord::GetHostBundleName() const -{ - return hostBundleName_; -} -/** - * @brief Set hostBundleName_. - * @param hostBandleName Host bundle name. - */ -void FormHostRecord::SetHostBundleName(const std::string &hostBundleName) -{ - hostBundleName_ = hostBundleName; -} -} // namespace AppExecFwk -} // namespace OHOS +/* + * 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 "form_host_record.h" +#include "form_task_mgr.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * @brief Add form id. + * @param formId The Id of the form. + */ +void FormHostRecord::AddForm(int64_t formId) +{ + if (forms_.find(formId) != forms_.end()) { + return; + } + forms_[formId] = true; +} +/** + * @brief Delete form id. + * @param formId The Id of the form. + */ +void FormHostRecord::DelForm(int64_t formId) +{ + forms_.erase(formId); +} +/** + * @brief forms_ is empty or not. + * @return forms_ is empty or not. + */ +bool FormHostRecord::IsEmpty() const +{ + return forms_.empty(); +} +/** + * @brief formId is in forms_ or not. + * @param formId The Id of the form. + * @return formId is in forms_ or not. + */ +bool FormHostRecord::Contains(int64_t formId) const +{ + return forms_.find(formId) != forms_.end(); +} + +/** + * @brief Set refresh enable flag. + * @param formId The Id of the form. + * @param flag True for enbale, false for disable. + */ +void FormHostRecord::SetEnableRefresh(int64_t formId, bool flag) +{ + if (forms_.find(formId) == forms_.end()) { + return; + } + forms_[formId] = flag; +} +/** + * @brief Refresh enable or not. + * @param formId The Id of the form. + * @return true on enbale, false on disable.. + */ +bool FormHostRecord::IsEnableRefresh(int64_t formId) const +{ + auto result = forms_.find(formId); + if (result != forms_.end()) { + return result->second; + } + return false; +} +/** + * @brief Set need refresh enable flag. + * @param formId The Id of the form. + * @param flag True for enbale, false for disable. + */ +void FormHostRecord::SetNeedRefresh(int64_t formId, bool flag) +{ + needRefresh_[formId] = flag; +} +/** + * @brief Need Refresh enable or not. + * @param formId The Id of the form. + * @return true on enbale, false on disable.. + */ +bool FormHostRecord::IsNeedRefresh(int64_t formId) const +{ + auto result = needRefresh_.find(formId); + if (result != needRefresh_.end()) { + return result->second; + } + return false; +} +/** + * @brief Get clientStub_. + * @return clientStub_. + */ +sptr FormHostRecord::GetClientStub() const +{ + return clientStub_; +} + +/** + * @brief Send form data to form host. + * @param id The Id of the form. + * @param record Form record. + */ +void FormHostRecord::OnAcquire(int64_t id, const FormRecord &record) +{ + APP_LOGD("FormHostRecord OnAcquire"); + if (clientImpl_ == nullptr) { + APP_LOGE("%{public}s: clientImpl_ can not be NULL", __func__); + return; + } + + clientImpl_->OnAcquired(id, record, clientStub_); +} + +/** + * @brief Update form data to form host. + * @param id The Id of the form. + * @param record Form record. + */ +void FormHostRecord::OnUpdate(int64_t id, const FormRecord &record) +{ + APP_LOGI("%{public}s start.", __func__); + + if (clientImpl_ == nullptr) { + APP_LOGE("%{public}s: clientImpl_ can not be null.", __func__); + return; + } + + clientImpl_->OnUpdate(id, record, clientStub_); +} + +/** + * @brief Send form uninstall message to form host. + * @param id The Id of the form. + * @param record Form record. + */ +void FormHostRecord::OnFormUninstalled(std::vector &formIds) +{ + APP_LOGI("%{public}s start.", __func__); + + if (clientImpl_ == nullptr) { + APP_LOGE("%{public}s: clientImpl_ can not be null.", __func__); + return; + } + clientImpl_->OnUninstall(formIds, clientStub_); +} +/** + * @brief Release resource. + * @param id The Id of the form. + * @param record Form record. + */ +void FormHostRecord::CleanResource() +{ + if (clientStub_ != nullptr && deathRecipient_ != nullptr) { + clientStub_->RemoveDeathRecipient(deathRecipient_); + clientStub_ = nullptr; + deathRecipient_ = nullptr; + } +} +/** + * @brief Set value of callerUid_. + * @param callerUid Caller uid. + */ +void FormHostRecord::SetCallerUid(const int callerUid) +{ + callerUid_ = callerUid; +} +/** + * @brief Set value of clientStub_. + * @param clientStub remote object. + */ +void FormHostRecord::SetClientStub(const sptr &clientStub) +{ + clientStub_ = clientStub; +} +/** + * @brief Set value of clientImpl_. + * @param clientImpl Form host callback object. + */ +void FormHostRecord::SetClientImpl(const std::shared_ptr &clientImpl) +{ + clientImpl_ = clientImpl; +} +/** + * @brief Get deathRecipient_. + * @return deathRecipient_. + */ +sptr FormHostRecord::GetDeathRecipient() const +{ + return deathRecipient_; +} +/** + * @brief Set value of deathRecipient_. + * @param clientImpl DeathRecipient object. + */ +void FormHostRecord::SetDeathRecipient(const sptr &deathRecipient) +{ + deathRecipient_ = deathRecipient; +} +/** + * @brief Add deathRecipient object to clientStub_. + * @param deathRecipient DeathRecipient object. + */ +void FormHostRecord::AddDeathRecipient(const sptr &deathRecipient) +{ + clientStub_->AddDeathRecipient(deathRecipient); +} + +/** + * @brief Create form host record. + * @param info The form item info. + * @param callback remote object. + * @param callingUid Calling uid. + */ +FormHostRecord FormHostRecord::CreateRecord(const FormItemInfo &info, const sptr &callback, +int callingUid) +{ + FormHostRecord record; + record.SetHostBundleName(info.GetHostBundleName()); + record.SetCallerUid(callingUid); + record.SetClientStub(callback); + record.SetClientImpl(std::make_shared()); + record.SetDeathRecipient(new FormHostRecord::ClientDeathRecipient()); + record.AddDeathRecipient(record.GetDeathRecipient()); + + return record; +} + +/** + * @brief handle remote object died event. + * @param remote remote object. + */ +void FormHostRecord::ClientDeathRecipient::OnRemoteDied(const wptr &remote) +{ + APP_LOGD("Form remote died"); + FormTaskMgr::GetInstance().PostHostDiedTask(remote.promote()); +} + +/** + * @brief Get hostBundleName_. + * @return hostBundleName_. + */ +std::string FormHostRecord::GetHostBundleName() const +{ + return hostBundleName_; +} +/** + * @brief Set hostBundleName_. + * @param hostBandleName Host bundle name. + */ +void FormHostRecord::SetHostBundleName(const std::string &hostBundleName) +{ + hostBundleName_ = hostBundleName; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/src/form_mgr_adapter.cpp b/services/formmgr/src/form_mgr_adapter.cpp index fbb58c77909314b6c952a733bce87ce9c54240a8..e04e546bc9e971812fb40ee733f0ac8197ea600a 100644 --- a/services/formmgr/src/form_mgr_adapter.cpp +++ b/services/formmgr/src/form_mgr_adapter.cpp @@ -31,9 +31,7 @@ #include "form_event_notify_connection.h" #include "form_mgr_adapter.h" #include "form_provider_info.h" -#include "form_provider_interface.h" #include "form_provider_mgr.h" -#include "form_supply_callback.h" #include "form_refresh_connection.h" #include "form_timer_mgr.h" #include "if_system_ability_manager.h" @@ -45,12 +43,23 @@ namespace OHOS { namespace AppExecFwk { -FormMgrAdapter::FormMgrAdapter() -{ -}; -FormMgrAdapter::~FormMgrAdapter() -{ -}; +// /** +// * @brief Get moduleName from packageName and abilityName. +// * @param packageName Package name. +// * @param abilityName Ability name. +// * @return ModuleName. +// */ +// std::string GetFullClassName(const std::string& packageName, const std::string& abilityName) +// { +// std::string fullName; +// if (!abilityName.empty() && abilityName[0] == '.') { +// fullName = packageName + abilityName; +// } else { +// fullName = abilityName; +// } +// return fullName; +// } + /** * @brief Add form with want, send want to form manager service. * @param formId The Id of the forms to add. @@ -59,8 +68,8 @@ FormMgrAdapter::~FormMgrAdapter() * @param formInfo Form info. * @return Returns ERR_OK on success, others on failure. */ -int FormMgrAdapter::AddForm(const int64_t formId, const Want &want, - const sptr &callerToken, FormJsInfo &formInfo) +int FormMgrAdapter::AddForm(const int64_t formId, const Want &want, const sptr &callerToken, +FormJsInfo &formInfo) { if (formId < 0 || callerToken == nullptr) { APP_LOGE("%{public}s fail, callerToken can not be NULL", __func__); @@ -120,8 +129,9 @@ int FormMgrAdapter::DeleteForm(const int64_t formId, const sptr & { if (formId <= 0 || callerToken == nullptr) { APP_LOGE("%{public}s, deleteForm invalid param", __func__); - return ERR_APPEXECFWK_FORM_INVALID_PARAM; + return ERR_FORM_INVALID_PARAM; } + int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId); if (FormDataMgr::GetInstance().ExistTempForm(matchedFormId)) { // delete temp form if receive delete form call @@ -143,8 +153,9 @@ int FormMgrAdapter::ReleaseForm(const int64_t formId, const sptr if (formId <= 0 || callerToken == nullptr) { APP_LOGE("%{public}s, releaseForm invalid param", __func__); - return ERR_APPEXECFWK_FORM_INVALID_PARAM; + return ERR_FORM_INVALID_PARAM; } + int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId); if (FormDataMgr::GetInstance().ExistTempForm(matchedFormId)) { // delete temp form if receive release form call @@ -164,7 +175,7 @@ int FormMgrAdapter::ReleaseForm(const int64_t formId, const sptr } if (!FormTimerMgr::GetInstance().RemoveFormTimer(matchedFormId)) { APP_LOGE("%{public}s, remove timer error", __func__); - return ERR_APPEXECFWK_FORM_COMMON_CODE; + return ERR_DELETE_FORM_TIMER; } return ERR_OK; } @@ -180,7 +191,7 @@ ErrCode FormMgrAdapter::HandleReleaseForm(const int64_t formId, const sptr iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr(); if (iBundleMgr == nullptr) { APP_LOGE("%{public}s error, failed to get IBundleMgr.", __func__); - return ERR_APPEXECFWK_FORM_GET_BMS_FAILED; + return ERR_APPEXECFWK_FORM_GET_BUNDLE_FAILED; } // check bundle uid for permission @@ -379,7 +391,7 @@ int FormMgrAdapter::UpdateForm(const int64_t formId, int32_t bundleUid = iBundleMgr->GetUidByBundleName(bundleName, userId); if (bundleUid != callingUid) { APP_LOGE("%{public}s error, permission denied, the updated form is not your own.", __func__); - return ERR_APPEXECFWK_FORM_INVALID_PARAM; + return ERR_FORM_INVALID_PARAM; } // find matched formId @@ -389,19 +401,19 @@ int FormMgrAdapter::UpdateForm(const int64_t formId, FormRecord formRecord; if (!FormDataMgr::GetInstance().GetFormRecord(matchedFormId, formRecord)) { APP_LOGE("%{public}s error, not exist such form:%{public}" PRId64 ".", __func__, matchedFormId); - return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + return ERR_NOT_EXIST_ID; } // check then form under current user if (!FormDataMgr::GetInstance().IsCallingUidValid(formRecord.formUserUids)) { APP_LOGE("%{public}s error, not under current user, formId:%{public}" PRId64 ".", __func__, matchedFormId); - return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + return ERR_NOT_EXIST_ID; } // check bundleName match if (formRecord.bundleName.compare(bundleName) != 0) { APP_LOGE("%{public}s error, not match bundleName:%{public}s.", __func__, bundleName.c_str()); - return ERR_APPEXECFWK_FORM_INVALID_PARAM; + return ERR_FORM_INVALID_PARAM; } // update Form @@ -419,7 +431,7 @@ int FormMgrAdapter::RequestForm(const int64_t formId, const sptr { APP_LOGI("%{public}s called.", __func__); - if (formId <= 0 || callerToken == nullptr) { + if (callerToken == nullptr) { APP_LOGE("%{public}s fail, callerToken can not be NULL.", __func__); return ERR_APPEXECFWK_FORM_INVALID_PARAM; } @@ -428,19 +440,19 @@ int FormMgrAdapter::RequestForm(const int64_t formId, const sptr if (!FormDataMgr::GetInstance().ExistFormRecord(matchedFormId)) { APP_LOGE("%{public}s fail, not exist such formId:%{public}" PRId64 ".", __func__, matchedFormId); - return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + return ERR_NOT_EXIST_ID; } FormHostRecord formHostRecord; bool isHostExist = FormDataMgr::GetInstance().GetMatchedHostClient(callerToken, formHostRecord); if (!isHostExist) { APP_LOGE("%{public}s fail, cannot find target client.", __func__); - return ERR_APPEXECFWK_FORM_INVALID_PARAM; + return ERR_FORM_INVALID_PARAM; } if (!formHostRecord.Contains(matchedFormId)) { APP_LOGE("%{public}s fail, form is not self-owned.", __func__); - return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF; + return ERR_OPERATION_FORM_NOT_SELF; } APP_LOGI("%{public}s, find target client.", __func__); @@ -456,7 +468,8 @@ int FormMgrAdapter::RequestForm(const int64_t formId, const sptr * @return Returns ERR_OK on success, others on failure. */ ErrCode FormMgrAdapter::NotifyWhetherVisibleForms(const std::vector &formIds, - const sptr &callerToken, const int32_t formVisibleType) +const sptr &callerToken, + const int32_t formVisibleType) { APP_LOGI("%{public}s called.", __func__); @@ -468,7 +481,7 @@ ErrCode FormMgrAdapter::NotifyWhetherVisibleForms(const std::vector &fo sptr iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr(); if (iBundleMgr == nullptr) { APP_LOGE("%{public}s fail, failed to get IBundleMgr.", __func__); - return ERR_APPEXECFWK_FORM_GET_BMS_FAILED; + return ERR_APPEXECFWK_FORM_GET_BUNDLE_FAILED; } int64_t matchedFormId; @@ -515,8 +528,7 @@ ErrCode FormMgrAdapter::NotifyWhetherVisibleForms(const std::vector &fo if (iBundleMgr->GetBundleInfo(formRecord.bundleName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo)) { APP_LOGD("%{public}s, get bundle uid success", __func__); if (!iBundleMgr->CheckIsSystemAppByUid(bundleInfo.uid)) { - APP_LOGW("%{public}s fail, form provider is not system app, formId:%{public}" PRId64 ".", - __func__, matchedFormId); + APP_LOGW("%{public}s fail, form provider is not system app, formId:%{public}" PRId64 ".", __func__, matchedFormId); continue; } } else { @@ -557,21 +569,21 @@ int FormMgrAdapter::CastTempForm(const int64_t formId, const sptr { if (formId <= 0 || callerToken == nullptr) { APP_LOGE("%{public}s, invalid param", __func__); - return ERR_APPEXECFWK_FORM_INVALID_PARAM; + return ERR_FORM_INVALID_PARAM; } int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId); if (!FormDataMgr::GetInstance().ExistFormRecord(matchedFormId) || !FormDataMgr::GetInstance().ExistTempForm(matchedFormId)) { APP_LOGE("%{public}s, not exist such temp form:%{public}" PRId64 "", __func__, matchedFormId); - return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + return ERR_NOT_EXIST_ID; } FormHostRecord record; bool hasHostRec = FormDataMgr::GetInstance().GetFormHostRecord(matchedFormId, record); if (!hasHostRec || !record.Contains(matchedFormId)) { APP_LOGE("%{public}s, not self form:%{public}" PRId64 "", __func__, matchedFormId); - return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF; + return ERR_OPERATION_FORM_NOT_SELF; } int callingUid = IPCSkeleton::GetCallingUid(); @@ -584,7 +596,7 @@ int FormMgrAdapter::CastTempForm(const int64_t formId, const sptr FormRecord formRecord; if (!FormDataMgr::GetInstance().GetFormRecord(matchedFormId, formRecord)) { APP_LOGE("%{public}s fail, not exist such form:%{public}" PRId64 ".", __func__, matchedFormId); - return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + return ERR_NOT_EXIST_ID; } int bindSupplierCheckCode = HandleCastTempForm(matchedFormId, formRecord); if (bindSupplierCheckCode != 0) { @@ -594,15 +606,15 @@ int FormMgrAdapter::CastTempForm(const int64_t formId, const sptr if (!FormDataMgr::GetInstance().DeleteTempForm(matchedFormId)) { APP_LOGE("%{public}s fail, delete temp form error, formId:%{public}" PRId64 ".", __func__, matchedFormId); - return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + return ERR_APPEXECFWK_FORM_INFO_NOT_EXIST; } if (!FormDataMgr::GetInstance().ModifyFormTempFlg(matchedFormId, false)) { APP_LOGE("%{public}s fail, modify form temp flag error, formId:%{public}" PRId64 ".", __func__, matchedFormId); - return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + return ERR_APPEXECFWK_FORM_INFO_NOT_EXIST; } if (!FormDataMgr::GetInstance().AddFormUserUid(matchedFormId, callingUid)) { APP_LOGE("%{public}s fail, add form user uid error, formId:%{public}" PRId64 ".", __func__, matchedFormId); - return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + return ERR_APPEXECFWK_FORM_INFO_NOT_EXIST; } if (std::find(formRecord.formUserUids.begin(), formRecord.formUserUids.end(), callingUid) == formRecord.formUserUids.end()) { @@ -626,18 +638,12 @@ ErrCode FormMgrAdapter::HandleCastTempForm(const int64_t formId, const FormRecor { APP_LOGD("%{public}s, cast temp form to normal form, notify supplier, package:%{public}s, class:%{public}s", __func__, record.bundleName.c_str(), record.abilityName.c_str()); - sptr castTempConnection = new FormCastTempConnection(formId, - record.bundleName, record.abilityName); + sptr castTempConnection = new FormCastTempConnection(formId); Want want; want.AddFlags(Want::FLAG_ABILITY_FORM_ENABLED); want.SetElementName(record.bundleName, record.abilityName); - ErrCode errorCode = FormAmsHelper::GetInstance().ConnectServiceAbility(want, castTempConnection); - if (errorCode != ERR_OK) { - APP_LOGE("%{public}s fail, ConnectServiceAbility failed.", __func__); - return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED; - } - return ERR_OK; + return FormAmsHelper::GetInstance().ConnectServiceAbility(want, castTempConnection); } /** * @brief Dump all of form storage infos. @@ -648,15 +654,14 @@ int FormMgrAdapter::DumpStorageFormInfos(std::string &formInfos) const { std::vector formDBInfos; FormDbCache::GetInstance().GetAllFormInfo(formDBInfos); - if (formDBInfos.size() > 0) { - std::sort(formDBInfos.begin(), formDBInfos.end(), - [] (FormDBInfo &formDBInfoA, FormDBInfo &formDBInfoB) -> bool { + if(formDBInfos.size() > 0) { + std::sort(formDBInfos.begin(), formDBInfos.end(), [] (FormDBInfo &formDBInfoA, FormDBInfo &formDBInfoB) -> bool { return formDBInfoA.formId < formDBInfoB.formId; }); FormDumpMgr::GetInstance().DumpStorageFormInfos(formDBInfos, formInfos); return ERR_OK; } else { - return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + return ERR_APPEXECFWK_FORM_INFO_NOT_EXIST; } } /** @@ -673,7 +678,7 @@ int FormMgrAdapter::DumpFormInfoByBundleName(const std::string &bundleName, std: FormDumpMgr::GetInstance().DumpFormInfos(formRecordInfos, formInfos); return ERR_OK; } else { - return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + return ERR_APPEXECFWK_FORM_INFO_NOT_EXIST; } } /** @@ -685,7 +690,7 @@ int FormMgrAdapter::DumpFormInfoByBundleName(const std::string &bundleName, std: int FormMgrAdapter::DumpFormInfoByFormId(const std::int64_t formId, std::string &formInfo) const { APP_LOGI("%{public}s called.", __func__); - int reply = ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + int reply = ERR_APPEXECFWK_FORM_INFO_NOT_EXIST; FormRecord formRecord; if (FormDataMgr::GetInstance().GetFormRecord(formId, formRecord)) { @@ -744,8 +749,8 @@ ErrCode FormMgrAdapter::GetFormConfigInfo(const Want &want, FormItemInfo &formCo * @param formInfo Form info for form host. * @return Returns ERR_OK on success, others on failure. */ -ErrCode FormMgrAdapter::AllotFormById(const FormItemInfo &info, - const sptr &callerToken, const WantParams &wantParams, FormJsInfo &formInfo) +ErrCode FormMgrAdapter::AllotFormById(const FormItemInfo &info, const sptr &callerToken, +const WantParams &wantParams, FormJsInfo &formInfo) { int64_t formId = PaddingUDIDHash(info.GetFormId()); FormRecord record; @@ -758,7 +763,7 @@ ErrCode FormMgrAdapter::AllotFormById(const FormItemInfo &info, if (hasRecord && FormDataMgr::GetInstance().IsCallingUidValid(record.formUserUids)) { if (!info.IsMatch(record)) { APP_LOGE("%{public}s, formId and item info not match:%{public}" PRId64 "", __func__, formId); - return ERR_APPEXECFWK_FORM_CFG_NOT_MATCH_ID; + return ERR_CFG_NOT_MATCH_ID; } return AddExistFormRecord(info, callerToken, record, formId, wantParams); } @@ -778,13 +783,12 @@ ErrCode FormMgrAdapter::AllotFormById(const FormItemInfo &info, delRecord.abilityName = info.GetAbilityName(); FormProviderMgr::GetInstance().NotifyProviderFormDelete(formId, delRecord); - return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + return ERR_NOT_EXIST_ID; } int64_t FormMgrAdapter::PaddingUDIDHash(const int64_t formId) const { // Compatible with int form id. - uint64_t unsignedFormId = static_cast(formId); - if ((unsignedFormId & 0xffffffff00000000L) == 0) { + if ((formId & 0xffffffff00000000L) == 0) { return FormDataMgr::GetInstance().GetUdidHash() | formId; } return formId; @@ -802,7 +806,6 @@ ErrCode FormMgrAdapter::AddExistFormRecord(const FormItemInfo &info, const sptr< } FormRecord newRecord(record); - if (newRecord.needRefresh) { newRecord.isInited = false; FormDataMgr::GetInstance().SetFormCacheInited(formId, false); @@ -839,8 +842,8 @@ ErrCode FormMgrAdapter::AddExistFormRecord(const FormItemInfo &info, const sptr< * @param formInfo Form info for form host. * @return Returns ERR_OK on success, others on failure. */ -ErrCode FormMgrAdapter::AllotFormByInfo(const FormItemInfo &info, - const sptr &callerToken, const WantParams &wantParams, FormJsInfo &formInfo) +ErrCode FormMgrAdapter::AllotFormByInfo(const FormItemInfo &info, const sptr &callerToken, +const WantParams &wantParams, FormJsInfo &formInfo) { // generate formId int64_t newFormId = FormDataMgr::GetInstance().GenerateFormId(); @@ -912,7 +915,7 @@ ErrCode FormMgrAdapter::AddFormTimer(const FormRecord &formRecord) timerRet = FormTimerMgr::GetInstance().AddFormTimer(formRecord.formId, formRecord.updateDuration); } else { timerRet = FormTimerMgr::GetInstance().AddFormTimer(formRecord.formId, formRecord.updateAtHour, - formRecord.updateAtMin); + formRecord.updateAtMin); } if (!timerRet) { APP_LOGE("%{public}s fail, add form timer failed", __func__); @@ -935,20 +938,19 @@ ErrCode FormMgrAdapter::HandleEventNotify(const std::string &providerKey, const const int32_t formVisibleType) { APP_LOGI("%{public}s called.", __func__); - size_t position = providerKey.find(Constants::NAME_DELIMITER); - std::string bundleName = providerKey.substr(0, position); - std::string abilityName = providerKey.substr(position + Constants::NAME_DELIMITER.size()); + sptr formEventNotifyConnection = new FormEventNotifyConnection(formIdsByProvider, - formVisibleType, bundleName, abilityName); + formVisibleType); Want connectWant; connectWant.AddFlags(Want::FLAG_ABILITY_FORM_ENABLED); - - connectWant.SetElementName(bundleName, abilityName); + size_t position = providerKey.find(Constants::NAME_DELIMITER); + connectWant.SetElementName(providerKey.substr(0, position), + providerKey.substr(position + Constants::NAME_DELIMITER.size())); ErrCode errorCode = FormAmsHelper::GetInstance().ConnectServiceAbility(connectWant, formEventNotifyConnection); if (errorCode != ERR_OK) { APP_LOGE("%{public}s fail, ConnectServiceAbility failed.", __func__); - return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED; + return errorCode; } return ERR_OK; @@ -961,8 +963,8 @@ ErrCode FormMgrAdapter::HandleEventNotify(const std::string &providerKey, const * @param wantParams WantParams of the request. * @return Returns ERR_OK on success, others on failure. */ -ErrCode FormMgrAdapter::AcquireProviderFormInfoAsync(const int64_t formId, - const FormItemInfo &info, const WantParams &wantParams) +ErrCode FormMgrAdapter::AcquireProviderFormInfoAsync(const int64_t formId, const FormItemInfo &info, +const WantParams &wantParams) { if (formId <= 0) { APP_LOGE("%{public}s fail, formId should be greater than 0", __func__); @@ -974,12 +976,7 @@ ErrCode FormMgrAdapter::AcquireProviderFormInfoAsync(const int64_t formId, Want want; want.SetElementName(info.GetProviderBundleName(), info.GetAbilityName()); want.AddFlags(Want::FLAG_ABILITY_FORM_ENABLED); - ErrCode errorCode = FormAmsHelper::GetInstance().ConnectServiceAbility(want, formAcquireConnection); - if (errorCode != ERR_OK) { - APP_LOGE("%{public}s fail, ConnectServiceAbility failed.", __func__); - return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED; - } - return ERR_OK; + return FormAmsHelper::GetInstance().ConnectServiceAbility(want, formAcquireConnection); } /** @@ -1004,7 +1001,7 @@ ErrCode FormMgrAdapter::GetBundleInfo(const AAFwk::Want &want, BundleInfo &bundl sptr iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr(); if (iBundleMgr == nullptr) { APP_LOGE("GetBundleMgr, failed to get IBundleMgr."); - return ERR_APPEXECFWK_FORM_GET_BMS_FAILED; + return ERR_APPEXECFWK_FORM_GET_BUNDLE_FAILED; } if (iBundleMgr->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo) != true) { @@ -1026,12 +1023,16 @@ ErrCode FormMgrAdapter::GetBundleInfo(const AAFwk::Want &want, BundleInfo &bundl } for (const auto &abilityInfo : bundleInfo.abilityInfos) { - if (abilityInfo.bundleName == bundleName && abilityInfo.moduleName == moduleName ) { - packageName = bundleName + moduleName; + // if (abilityInfo.moduleName.compare(GetFullClassName(abilityInfo.package, abilityName)) == 0) { + // packageName = abilityInfo.package; + // break; + // } + if (abilityInfo.deviceId == deviceId) { + packageName = abilityInfo.package; break; } } - + if (packageName.empty()) { APP_LOGE("GetBundleInfo can not find target ability %{public}s", abilityName.c_str()); return ERR_APPEXECFWK_FORM_NO_SUCH_ABILITY; @@ -1059,7 +1060,7 @@ ErrCode FormMgrAdapter::GetFormInfo(const AAFwk::Want &want, FormInfo &formInfo) sptr iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr(); if (iBundleMgr == nullptr) { APP_LOGE("GetFormInfo, failed to get IBundleMgr."); - return ERR_APPEXECFWK_FORM_GET_BMS_FAILED; + return ERR_APPEXECFWK_FORM_GET_BUNDLE_FAILED; } std::vector formInfos; @@ -1109,9 +1110,16 @@ ErrCode FormMgrAdapter::GetFormItemInfo(const AAFwk::Want &want, const BundleInf return ERR_APPEXECFWK_FORM_NO_SUCH_DIMENSION; } + // int32_t orientation = want.GetIntParam(Constants::PARAM_FORM_ORIENTATION_KEY, Constants::ORIENTATION_PORTRAIT); + // if (orientation != Constants::ORIENTATION_PORTRAIT && orientation != Constants::ORIENTATION_LANDSCAPE) { + // orientation = Constants::ORIENTATION_PORTRAIT; + // } + if (ErrCode ret = CreateFormItemInfo(bundleInfo, formInfo, formItemInfo); ret != ERR_OK) { return ret; } + // formItemInfo.SetFormId(formId); + // formItemInfo.orientation_ = orientation; formItemInfo.SetSpecificationId(dimensionId); formItemInfo.SetTemporaryFlag(want.GetBoolParam(Constants::PARAM_FORM_TEMPORARY_KEY, false)); @@ -1147,14 +1155,14 @@ bool FormMgrAdapter::IsDimensionValid(const FormInfo &formInfo, int dimensionId) * @param formInfo Form info. * @param itemInfo Form configure info. */ -ErrCode FormMgrAdapter::CreateFormItemInfo(const BundleInfo &bundleInfo, - const FormInfo &formInfo, FormItemInfo &itemInfo) +ErrCode FormMgrAdapter::CreateFormItemInfo(const BundleInfo &bundleInfo, const FormInfo &formInfo, +FormItemInfo &itemInfo) { itemInfo.SetProviderBundleName(bundleInfo.name); sptr iBundleMgr = FormBmsHelper::GetInstance().GetBundleMgr(); if (iBundleMgr == nullptr) { APP_LOGE("GetFormInfo, failed to get IBundleMgr."); - return ERR_APPEXECFWK_FORM_GET_BMS_FAILED; + return ERR_APPEXECFWK_FORM_GET_BUNDLE_FAILED; } std::string hostBundleName {}; if (!iBundleMgr->GetBundleNameForUid(IPCSkeleton::GetCallingUid(), hostBundleName)) { @@ -1176,11 +1184,9 @@ ErrCode FormMgrAdapter::CreateFormItemInfo(const BundleInfo &bundleInfo, itemInfo.SetAbilityModuleName(abilityInfo.moduleName); } } - APP_LOGI("%{public}s moduleInfos size: %{public}zu", __func__, bundleInfo.applicationInfo.moduleInfos.size()); for (const auto &item : bundleInfo.applicationInfo.moduleInfos) { - APP_LOGI("%{public}s moduleInfos, moduleName: %{public}s, moduleSourceDir: %{public}s", __func__, - item.moduleName.c_str(), item.moduleSourceDir.c_str()); + APP_LOGI("%{public}s moduleInfos, moduleName: %{public}s, moduleSourceDir: %{public}s", __func__, item.moduleName.c_str(), item.moduleSourceDir.c_str()); if (formInfo.moduleName == item.moduleName) { itemInfo.AddHapSourceDirs(item.moduleSourceDir); } @@ -1200,24 +1206,24 @@ int FormMgrAdapter::SetNextRefreshTime(const int64_t formId, const int64_t nextT APP_LOGI("%{public}s begin here, formId:%{public}" PRId64 ",nextTime:%{public}" PRId64 "", __func__, formId, nextTime); if (formId <= 0) { APP_LOGE("%{public}s form formId or bundleName is invalid", __func__); - return ERR_APPEXECFWK_FORM_INVALID_PARAM; + return ERR_FORM_INVALID_PARAM; } int64_t matchedFormId = FormDataMgr::GetInstance().FindMatchedFormId(formId); std::string bundleName; if (!GetBundleName(bundleName)) { - return ERR_APPEXECFWK_FORM_GET_BUNDLE_FAILED; + return ERR_APPEXECFWK_FORM_INFO_NOT_EXIST; } FormRecord formRecord; if (!FormDataMgr::GetInstance().GetFormRecord(matchedFormId, formRecord)) { APP_LOGE("%{public}s, not found in formrecord.", __func__); - return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + return ERR_APPEXECFWK_FORM_INFO_NOT_EXIST; } // check bundleName if (bundleName != formRecord.bundleName) { APP_LOGE("%{public}s, not match bundleName:%{public}s", __func__, bundleName.c_str()); - return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF; + return ERR_OPERATION_FORM_NOT_SELF; } return SetNextRefreshtTimeLocked(matchedFormId, nextTime); @@ -1263,12 +1269,12 @@ int FormMgrAdapter::SetNextRefreshtTimeLocked(const int64_t formId, const int64_ if (timerRefreshedCount >= Constants::LIMIT_COUNT) { APP_LOGE("%{public}s, already refresh times:%{public}d", __func__, timerRefreshedCount); FormTimerMgr::GetInstance().MarkRemind(formId); - return ERR_APPEXECFWK_FORM_MAX_REFRESH; + return ERR_MAX_REFRESH; } if (!FormTimerMgr::GetInstance().SetNextRefreshTime(formId, nextTime)) { APP_LOGE("%{public}s failed", __func__); - return ERR_APPEXECFWK_FORM_COMMON_CODE; + return ERR_CODE_COMMON; } return ERR_OK; @@ -1342,32 +1348,32 @@ int FormMgrAdapter::MessageEvent(const int64_t formId, const Want &want, const s bool bGetRecord = FormDataMgr::GetInstance().GetFormRecord(matchedFormId, record); if (!bGetRecord) { APP_LOGE("%{public}s fail, not exist such form:%{public}" PRId64 "", __func__, matchedFormId); - return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + return ERR_APPEXECFWK_FORM_INFO_NOT_EXIST; } FormHostRecord formHostRecord; bool isHostExist = FormDataMgr::GetInstance().GetMatchedHostClient(callerToken, formHostRecord); if (!isHostExist) { APP_LOGE("%{public}s failed, cannot find target client.", __func__); - return ERR_APPEXECFWK_FORM_COMMON_CODE; + return ERR_APPEXECFWK_FORM_HOST_INFO_NOT_EXIST; } if (!formHostRecord.Contains(matchedFormId)) { APP_LOGE("%{public}s failed, form is not self-owned.", __func__); - return ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF; + return ERR_OPERATION_FORM_NOT_SELF; } APP_LOGI("%{public}s, find target client.", __func__); return FormProviderMgr::GetInstance().MessageEvent(matchedFormId, record, want); } -int FormMgrAdapter::HandleUpdateFormFlag(std::vector formIds, - const sptr &callerToken, bool flag) +int FormMgrAdapter::HandleUpdateFormFlag(std::vector formIds, const sptr &callerToken, +bool flag) { APP_LOGI("%{public}s called.", __func__); if (formIds.empty() || callerToken == nullptr) { APP_LOGE("%{public}s, invalid param", __func__); - return ERR_APPEXECFWK_FORM_INVALID_PARAM; + return ERR_FORM_INVALID_PARAM; } std::vector refreshForms; int errCode = FormDataMgr::GetInstance().UpdateHostFormFlag(formIds, callerToken, flag, refreshForms); @@ -1386,66 +1392,13 @@ int FormMgrAdapter::HandleUpdateFormFlag(std::vector formIds, * @param formIDs The id of the forms. * @param callerToken Caller ability token. * @param flag form flag. - * @return Returns true on success, false on failure. + * @return Returns ERR_OK on success, others on failure. */ -bool FormMgrAdapter::IsFormCached(const FormRecord record) -{ +bool FormMgrAdapter::IsFormCached(const FormRecord record) { if (record.versionUpgrade) { return false; } return true; } - -/** - * @brief Acquire form data from form provider. - * @param formId The Id of the from. - * @param want The want of the request. - * @param remoteObject Form provider proxy object. - */ -void FormMgrAdapter::AcquireProviderFormInfo(const int64_t formId, const Want &want, -const sptr &remoteObject) -{ - APP_LOGI("%{public}s called.", __func__); - - long connectId = want.GetLongParam(Constants::FORM_CONNECT_ID, 0); - sptr formProviderProxy = iface_cast(remoteObject); - if (formProviderProxy == nullptr) { - FormSupplyCallback::GetInstance()->RemoveConnection(connectId); - APP_LOGE("%{public}s fail, Failed to get formProviderProxy", __func__); - return; - } - - int error = formProviderProxy->AcquireProviderFormInfo(formId, want, FormSupplyCallback::GetInstance()); - if (error != ERR_OK) { - FormSupplyCallback::GetInstance()->RemoveConnection(connectId); - APP_LOGE("%{public}s fail, Failed to get acquire provider form info", __func__); - } -} - -/** - * @brief Notify form provider for delete form. - * - * @param formId The Id of the from. - * @param want The want of the form. - * @param remoteObject Form provider proxy object. - * @return none. - */ -void FormMgrAdapter::NotifyFormDelete(const int64_t formId, const Want &want, const sptr &remoteObject) -{ - APP_LOGI("%{public}s called.", __func__); - - long connectId = want.GetLongParam(Constants::FORM_CONNECT_ID, 0); - sptr formProviderProxy = iface_cast(remoteObject); - if (formProviderProxy == nullptr) { - FormSupplyCallback::GetInstance()->RemoveConnection(connectId); - APP_LOGE("%{public}s fail, Failed to get formProviderProxy", __func__); - return; - } - int error = formProviderProxy->NotifyFormDelete(formId, want, FormSupplyCallback::GetInstance()); - if (error != ERR_OK) { - FormSupplyCallback::GetInstance()->RemoveConnection(connectId); - APP_LOGE("%{public}s fail, Failed to get acquire provider form info", __func__); - } -} } // namespace AppExecFwk } // namespace OHOS diff --git a/services/formmgr/src/form_mgr_service.cpp b/services/formmgr/src/form_mgr_service.cpp index 7fb4a8e61fdbcb7b6968a1a1dcd7b841625f5f07..8eb194ba678001d6fb32a7fb9bba2e716bad3a77 100644 --- a/services/formmgr/src/form_mgr_service.cpp +++ b/services/formmgr/src/form_mgr_service.cpp @@ -19,13 +19,11 @@ #include "appexecfwk_errors.h" #include "app_log_wrapper.h" -#include "form_ams_helper.h" #include "form_bms_helper.h" #include "form_constants.h" #include "form_data_mgr.h" #include "form_db_cache.h" #include "form_mgr_service.h" -#include "form_mgr_adapter.h" #include "form_task_mgr.h" #include "form_timer_mgr.h" #include "ipc_skeleton.h" @@ -50,7 +48,8 @@ FormMgrService::FormMgrService() : SystemAbility(FORM_MGR_SERVICE_ID, true), state_(ServiceRunningState::STATE_NOT_START), runner_(nullptr), - handler_(nullptr) + handler_(nullptr), + formMgrAdapter_(std::make_unique()) { } @@ -78,14 +77,14 @@ bool FormMgrService::IsReady() const * @param formInfo Form info. * @return Returns ERR_OK on success, others on failure. */ -int FormMgrService::AddForm(const int64_t formId, const Want &want, - const sptr &callerToken, FormJsInfo &formInfo) +int FormMgrService::AddForm(const int64_t formId, const Want &want, const sptr &callerToken, +FormJsInfo &formInfo) { if (!CheckFormPermission()) { APP_LOGE("%{public}s fail, add form permission denied", __func__); return ERR_APPEXECFWK_FORM_PERMISSION_DENY; } - return FormMgrAdapter::GetInstance().AddForm(formId, want, callerToken, formInfo); + return formMgrAdapter_->AddForm(formId, want, callerToken, formInfo); } /** @@ -101,7 +100,7 @@ int FormMgrService::DeleteForm(const int64_t formId, const sptr & return ERR_APPEXECFWK_FORM_PERMISSION_DENY; } - return FormMgrAdapter::GetInstance().DeleteForm(formId, callerToken); + return formMgrAdapter_->DeleteForm(formId, callerToken); } /** @@ -118,7 +117,7 @@ int FormMgrService::ReleaseForm(const int64_t formId, const sptr return ERR_APPEXECFWK_FORM_PERMISSION_DENY; } - return FormMgrAdapter::GetInstance().ReleaseForm(formId, callerToken, delCache); + return formMgrAdapter_->ReleaseForm(formId, callerToken, delCache); } /** @@ -128,14 +127,14 @@ int FormMgrService::ReleaseForm(const int64_t formId, const sptr * @param formBindingData Form binding data. * @return Returns ERR_OK on success, others on failure. */ -int FormMgrService::UpdateForm(const int64_t formId, - const std::string &bundleName, const FormProviderData &formBindingData) +int FormMgrService::UpdateForm(const int64_t formId, const std::string &bundleName, +const FormProviderData &formBindingData) { if (!CheckFormPermission()) { APP_LOGE("%{public}s fail, update form permission denied", __func__); return ERR_APPEXECFWK_FORM_PERMISSION_DENY; } - return FormMgrAdapter::GetInstance().UpdateForm(formId, bundleName, formBindingData); + return formMgrAdapter_->UpdateForm(formId, bundleName, formBindingData); } /** @@ -154,7 +153,7 @@ int FormMgrService::RequestForm(const int64_t formId, const sptr return ERR_APPEXECFWK_FORM_PERMISSION_DENY; } - return FormMgrAdapter::GetInstance().RequestForm(formId, callerToken, want); + return formMgrAdapter_->RequestForm(formId, callerToken, want); } /** @@ -168,7 +167,7 @@ int FormMgrService::SetNextRefreshTime(const int64_t formId, const int64_t nextT { APP_LOGI("%{public}s called.", __func__); - return FormMgrAdapter::GetInstance().SetNextRefreshTime(formId, nextTime); + return formMgrAdapter_->SetNextRefreshTime(formId, nextTime); } @@ -180,14 +179,14 @@ int FormMgrService::SetNextRefreshTime(const int64_t formId, const int64_t nextT * @return Returns ERR_OK on success, others on failure. */ int FormMgrService::NotifyWhetherVisibleForms(const std::vector &formIds, - const sptr &callerToken, const int32_t formVisibleType) +const sptr &callerToken, const int32_t formVisibleType) { if (!CheckFormPermission()) { APP_LOGE("%{public}s fail, event notify visible permission denied", __func__); return ERR_APPEXECFWK_FORM_PERMISSION_DENY; } - return FormMgrAdapter::GetInstance().NotifyWhetherVisibleForms(formIds, callerToken, formVisibleType); + return formMgrAdapter_->NotifyWhetherVisibleForms(formIds, callerToken, formVisibleType); } /** @@ -203,7 +202,7 @@ int FormMgrService::CastTempForm(const int64_t formId, const sptr return ERR_APPEXECFWK_FORM_PERMISSION_DENY; } - return FormMgrAdapter::GetInstance().CastTempForm(formId, callerToken); + return formMgrAdapter_->CastTempForm(formId, callerToken); } /** @@ -213,8 +212,8 @@ int FormMgrService::CastTempForm(const int64_t formId, const sptr * @param updateType update type,enable or disable. * @return Returns true on success, false on failure. */ -int FormMgrService::LifecycleUpdate(const std::vector &formIds, - const sptr &callerToken, const int32_t updateType) +int FormMgrService::LifecycleUpdate(const std::vector &formIds, const sptr &callerToken, +const int32_t updateType) { APP_LOGI("lifecycleUpdate."); @@ -224,9 +223,9 @@ int FormMgrService::LifecycleUpdate(const std::vector &formIds, } if (updateType == ENABLE_FORM_UPDATE) { - return FormMgrAdapter::GetInstance().EnableUpdateForm(formIds, callerToken); + return formMgrAdapter_->EnableUpdateForm(formIds, callerToken); } else { - return FormMgrAdapter::GetInstance().DisableUpdateForm(formIds, callerToken); + return formMgrAdapter_->DisableUpdateForm(formIds, callerToken); } } /** @@ -236,7 +235,7 @@ int FormMgrService::LifecycleUpdate(const std::vector &formIds, */ int FormMgrService::DumpStorageFormInfos(std::string &formInfos) { - return FormMgrAdapter::GetInstance().DumpStorageFormInfos(formInfos); + return formMgrAdapter_->DumpStorageFormInfos(formInfos); } /** * @brief Dump form info by a bundle name. @@ -246,7 +245,7 @@ int FormMgrService::DumpStorageFormInfos(std::string &formInfos) */ int FormMgrService::DumpFormInfoByBundleName(const std::string &bundleName, std::string &formInfos) { - return FormMgrAdapter::GetInstance().DumpFormInfoByBundleName(bundleName, formInfos); + return formMgrAdapter_->DumpFormInfoByBundleName(bundleName, formInfos); } /** * @brief Dump form info by a bundle name. @@ -256,7 +255,7 @@ int FormMgrService::DumpFormInfoByBundleName(const std::string &bundleName, std: */ int FormMgrService::DumpFormInfoByFormId(const std::int64_t formId, std::string &formInfo) { - return FormMgrAdapter::GetInstance().DumpFormInfoByFormId(formId, formInfo); + return formMgrAdapter_->DumpFormInfoByFormId(formId, formInfo); } /** * @brief Process js message event. @@ -274,7 +273,7 @@ int FormMgrService::MessageEvent(const int64_t formId, const Want &want, const s return ERR_APPEXECFWK_FORM_PERMISSION_DENY; } - return FormMgrAdapter::GetInstance().MessageEvent(formId, want, callerToken); + return formMgrAdapter_->MessageEvent(formId, want, callerToken); } /** * @brief Start envent for the form manager service. @@ -330,7 +329,6 @@ ErrCode FormMgrService::Init() return ERR_INVALID_OPERATION; } FormTaskMgr::GetInstance().SetEventHandler(handler_); - FormAmsHelper::GetInstance().SetEventHandler(handler_); /* Publish service maybe failed, so we need call this function at the last, * so it can't affect the TDD test program */ bool ret = Publish(DelayedSingleton::GetInstance().get()); @@ -382,7 +380,7 @@ bool FormMgrService::CheckFormPermission(const std::string &bundleName) const int result = PermissionKit::VerifyPermission(bundleName, Constants::PERMISSION_REQUIRE_FORM, 0); if (result != PermissionState::PERMISSION_GRANTED) { APP_LOGW("permission = %{public}s, bundleName = %{public}s, result = %{public}d", - Constants::PERMISSION_REQUIRE_FORM.c_str(), bundleName.c_str(), result); + Constants::PERMISSION_REQUIRE_FORM.c_str(), bundleName.c_str(), result); } return result == PermissionState::PERMISSION_GRANTED; } diff --git a/services/formmgr/src/form_msg_event_connection.cpp b/services/formmgr/src/form_msg_event_connection.cpp index 570e77e9794c5ffdb3ca19a3e18f5c1816ecde58..3b3c13dc414f01470aba64628974623e24f13044 100644 --- a/services/formmgr/src/form_msg_event_connection.cpp +++ b/services/formmgr/src/form_msg_event_connection.cpp @@ -1,67 +1,66 @@ - -/* - * 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 "appexecfwk_errors.h" -#include "app_log_wrapper.h" -#include "form_constants.h" -#include "form_msg_event_connection.h" -#include "form_supply_callback.h" -#include "form_task_mgr.h" -#include "ipc_types.h" -#include "message_parcel.h" -#include "want.h" - -namespace OHOS { -namespace AppExecFwk { -FormMsgEventConnection::FormMsgEventConnection(const int64_t formId, const Want& want, - const std::string &bundleName, const std::string &abilityName) - :formId_(formId), - want_(want) -{ - SetProviderKey(bundleName, abilityName); -} -/** - * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. - * - * @param element Service ability's ElementName. - * @param remoteObject The session proxy of service ability. - * @param resultCode ERR_OK on success, others on failure. - * @return none. - */ -void FormMsgEventConnection::OnAbilityConnectDone( - const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) -{ - APP_LOGI("%{public}s called.", __func__); - if (resultCode != ERR_OK) { - APP_LOGE("%{public}s, abilityName:%{public}s, formId:%{public}" PRId64 ", resultCode:%{public}d", - __func__, element.GetAbilityName().c_str(), formId_, resultCode); - return; - } - FormSupplyCallback::GetInstance()->AddConnection(this); - - if (want_.HasParameter(Constants::PARAM_MESSAGE_KEY)) { - std::string message = want_.GetStringParam(Constants::PARAM_MESSAGE_KEY); - Want eventWant = Want(want_); - eventWant.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); - FormTaskMgr::GetInstance().PostFormEventTask(formId_, message, eventWant, remoteObject); - } else { - APP_LOGE("%{public}s error, message info is not exist", __func__); - } -} -} // namespace AppExecFwk + +/* + * 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_constants.h" +#include "form_msg_event_connection.h" +#include "form_supply_callback.h" +#include "form_task_mgr.h" +#include "ipc_types.h" +#include "message_parcel.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +FormMsgEventConnection::FormMsgEventConnection(const int64_t formId, const Want& want) + :formId_(formId), + want_(want) +{ +} +/** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element Service ability's ElementName. + * @param remoteObject The session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + * @return none. + */ +void FormMsgEventConnection::OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{ + APP_LOGI("%{public}s called.", __func__); + + if (resultCode != ERR_OK) { + APP_LOGE("%{public}s, abilityName:%{public}s, formId:%{public}" PRId64 ", resultCode:%{public}d", + __func__, element.GetAbilityName().c_str(), formId_, resultCode); + return; + } + FormSupplyCallback::GetInstance()->AddConnection(this); + + if (want_.HasParameter(Constants::PARAM_MESSAGE_KEY)) { + std::string message = want_.GetStringParam(Constants::PARAM_MESSAGE_KEY); + Want eventWant = Want(want_); + eventWant.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); + FormTaskMgr::GetInstance().PostFormEventTask(formId_, message, eventWant, remoteObject); + } else { + APP_LOGE("%{public}s error, message info is not exist", __func__); + } +} +} // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_provider_mgr.cpp b/services/formmgr/src/form_provider_mgr.cpp index 3712752d68c9a9de0f26899d66461897b5eea5a2..129597ad6da801c242cf0604b40765109d43e871 100644 --- a/services/formmgr/src/form_provider_mgr.cpp +++ b/services/formmgr/src/form_provider_mgr.cpp @@ -46,21 +46,21 @@ ErrCode FormProviderMgr::AcquireForm(const int64_t formId, const FormProviderInf if (formId <= 0) { APP_LOGE("%{public}s fail, formId should be greater than 0", __func__); - return ERR_APPEXECFWK_FORM_INVALID_PARAM; + return ERR_FORM_INVALID_PARAM; } FormRecord formRecord; bool isGetFormRecord = FormDataMgr::GetInstance().GetFormRecord(formId, formRecord); if (!isGetFormRecord) { APP_LOGE("%{public}s fail, not exist such form, formId:%{public}" PRId64 "", __func__, formId); - return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + return ERR_APPEXECFWK_FORM_INFO_NOT_EXIST; } FormHostRecord clientHost; bool isGetFormHostRecord = FormDataMgr::GetInstance().GetFormHostRecord(formId, clientHost); if (!isGetFormHostRecord) { APP_LOGE("%{public}s fail, clientHost is null", __func__); - return ERR_APPEXECFWK_FORM_COMMON_CODE; + return ERR_APPEXECFWK_FORM_HOST_INFO_NOT_EXIST; } if (formRecord.isInited) { @@ -108,7 +108,7 @@ ErrCode FormProviderMgr::RefreshForm(const int64_t formId, const Want &want) bool bGetRecord = FormDataMgr::GetInstance().GetFormRecord(formId, record); if (!bGetRecord) { APP_LOGE("%{public}s fail, not exist such form:%{public}" PRId64 "", __func__, formId); - return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + return ERR_APPEXECFWK_FORM_INFO_NOT_EXIST; } bool isTimerRefresh = want.GetBoolParam(Constants::KEY_IS_TIMER, false); @@ -149,14 +149,13 @@ ErrCode FormProviderMgr::RefreshForm(const int64_t formId, const Want &want) * @param isTimerRefresh The flag of timer refresh. * @return Returns ERR_OK on success, others on failure. */ -ErrCode FormProviderMgr::ConnectAmsForRefresh(const int64_t formId, - const FormRecord &record, const Want &want, const bool isTimerRefresh) +ErrCode FormProviderMgr::ConnectAmsForRefresh(const int64_t formId, const FormRecord &record, const Want &want, +const bool isTimerRefresh) { APP_LOGD("%{public}s called, bundleName:%{public}s, abilityName:%{public}s.", __func__, record.bundleName.c_str(), record.abilityName.c_str()); - sptr formRefreshConnection = new FormRefreshConnection(formId, want, - record.bundleName, record.abilityName); + sptr formRefreshConnection = new FormRefreshConnection(formId, want); Want connectWant; connectWant.AddFlags(Want::FLAG_ABILITY_FORM_ENABLED); connectWant.SetElementName(record.bundleName, record.abilityName); @@ -164,14 +163,14 @@ ErrCode FormProviderMgr::ConnectAmsForRefresh(const int64_t formId, if (isTimerRefresh) { if (!FormTimerMgr::GetInstance().IsLimiterEnableRefresh(formId)) { APP_LOGE("%{public}s, timer refresh, already limit.", __func__); - return ERR_APPEXECFWK_FORM_PROVIDER_DEL_FAIL; + return ERR_APPEXECFWK_FORM_SUPPLIER_DEL_FAIL; } } ErrCode errorCode = FormAmsHelper::GetInstance().ConnectServiceAbility(connectWant, formRefreshConnection); if (errorCode != ERR_OK) { APP_LOGE("%{public}s, ConnectServiceAbility failed.", __func__); - return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED; + return errorCode; } if (record.isCountTimerRefresh) { @@ -191,28 +190,21 @@ ErrCode FormProviderMgr::NotifyProviderFormDelete(const int64_t formId, const Fo { if (formRecord.abilityName.empty()) { APP_LOGE("%{public}s, formRecord.abilityName is empty.", __func__); - return ERR_APPEXECFWK_FORM_INVALID_PARAM; + return ERR_CODE_COMMON; } if (formRecord.bundleName.empty()) { APP_LOGE("%{public}s, formRecord.bundleName is empty.", __func__); - return ERR_APPEXECFWK_FORM_INVALID_PARAM; + return ERR_CODE_COMMON; } APP_LOGD("%{public}s, connectAbility,bundleName:%{public}s, abilityName:%{public}s", __func__, formRecord.bundleName.c_str(), formRecord.abilityName.c_str()); - sptr formDeleteConnection = new FormDeleteConnection(formId, - formRecord.bundleName, formRecord.abilityName); + sptr formDeleteConnection = new FormDeleteConnection(formId); Want want; want.SetElementName(formRecord.bundleName, formRecord.abilityName); want.SetFlags(Want::FLAG_ABILITY_FORM_ENABLED); - - ErrCode errorCode = FormAmsHelper::GetInstance().ConnectServiceAbility(want, formDeleteConnection); - if (errorCode != ERR_OK) { - APP_LOGE("%{public}s, ConnectServiceAbility failed.", __func__); - return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED; - } - return ERR_OK; + return FormAmsHelper::GetInstance().ConnectServiceAbility(want, formDeleteConnection); } /** @@ -222,8 +214,8 @@ ErrCode FormProviderMgr::NotifyProviderFormDelete(const int64_t formId, const Fo * @param formIds form id list. * @return Returns ERR_OK on success, others on failure. */ -ErrCode FormProviderMgr::NotifyProviderFormsBatchDelete(const std::string &bundleName, - const std::string &abilityName, const std::set &formIds) +ErrCode FormProviderMgr::NotifyProviderFormsBatchDelete(const std::string &bundleName, const std::string &abilityName, +const std::set &formIds) { if (abilityName.empty()) { APP_LOGE("%{public}s error, abilityName is empty.", __func__); @@ -235,9 +227,9 @@ ErrCode FormProviderMgr::NotifyProviderFormsBatchDelete(const std::string &bundl return ERR_APPEXECFWK_FORM_INVALID_PARAM; } - APP_LOGD("%{public}s, bundleName:%{public}s, abilityName:%{public}s", - __func__, bundleName.c_str(), abilityName.c_str()); - sptr batchDeleteConnection = new FormBatchDeleteConnection(formIds, bundleName, abilityName); + APP_LOGD("%{public}s, bundleName:%{public}s, abilityName:%{public}s", __func__, bundleName.c_str(), + abilityName.c_str()); + sptr batchDeleteConnection = new FormBatchDeleteConnection(formIds); Want want; want.AddFlags(Want::FLAG_ABILITY_FORM_ENABLED); want.SetElementName(bundleName, abilityName); @@ -245,7 +237,7 @@ ErrCode FormProviderMgr::NotifyProviderFormsBatchDelete(const std::string &bundl ErrCode errorCode = FormAmsHelper::GetInstance().ConnectServiceAbility(want, batchDeleteConnection); if (errorCode != ERR_OK) { APP_LOGE("%{public}s, ConnectServiceAbility failed.", __func__); - return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED; + return errorCode; } return ERR_OK; } @@ -262,7 +254,7 @@ ErrCode FormProviderMgr::UpdateForm(const int64_t formId, const FormProviderInfo FormRecord formRecord; if (!FormDataMgr::GetInstance().GetFormRecord(formId, formRecord)) { APP_LOGE("%{public}s error, not exist such form:%{public}" PRId64 ".", __func__, formId); - return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; + return ERR_NOT_EXIST_ID; } return UpdateForm(formId, formRecord, formProviderInfo.GetFormData()); } @@ -274,14 +266,13 @@ ErrCode FormProviderMgr::UpdateForm(const int64_t formId, const FormProviderInfo * @param formProviderData provider form info. * @return Returns ERR_OK on success, others on failure. */ -ErrCode FormProviderMgr::UpdateForm(const int64_t formId, - FormRecord &formRecord, const FormProviderData &formProviderData) +ErrCode FormProviderMgr::UpdateForm(const int64_t formId, FormRecord &formRecord, +const FormProviderData &formProviderData) { APP_LOGI("%{public}s start", __func__); if (formRecord.versionUpgrade) { formRecord.formProviderInfo.SetFormData(formProviderData); - formRecord.formProviderInfo.SetUpgradeFlg(true); } else { nlohmann::json addJsonData = formProviderData.GetData(); formRecord.formProviderInfo.MergeData(addJsonData); @@ -299,11 +290,8 @@ ErrCode FormProviderMgr::UpdateForm(const int64_t formId, if (screenOnFlag) { if (FormDataMgr::GetInstance().UpdateHostForm(formId, formRecord)) { FormDataMgr::GetInstance().SetVersionUpgrade(formId, false); - formRecord.formProviderInfo.SetUpgradeFlg(false); } } - // update formProviderInfo to formRecord - FormDataMgr::GetInstance().UpdateFormProviderInfo(formId, formRecord.formProviderInfo); // check if cache data size is less than 1k or not std::string jsonData = formRecord.formProviderInfo.GetFormDataString(); // get json data APP_LOGD("%{public}s , jsonData is %{public}s.", __func__, jsonData.c_str()); @@ -332,8 +320,7 @@ int FormProviderMgr::MessageEvent(const int64_t formId, const FormRecord &record return ERR_APPEXECFWK_FORM_COMMON_CODE; } - sptr formMsgEventConnection = new FormMsgEventConnection(formId, want, - record.bundleName, record.abilityName); + sptr formMsgEventConnection = new FormMsgEventConnection(formId, want); Want connectWant; connectWant.AddFlags(Want::FLAG_ABILITY_FORM_ENABLED); connectWant.SetElementName(record.bundleName, record.abilityName); @@ -341,7 +328,7 @@ int FormProviderMgr::MessageEvent(const int64_t formId, const FormRecord &record ErrCode errorCode = FormAmsHelper::GetInstance().ConnectServiceAbility(connectWant, formMsgEventConnection); if (errorCode != ERR_OK) { APP_LOGE("%{public}s, ConnectServiceAbility failed.", __func__); - return ERR_APPEXECFWK_FORM_BIND_PROVIDER_FAILED; + return errorCode; } return ERR_OK; diff --git a/services/formmgr/src/form_refresh_connection.cpp b/services/formmgr/src/form_refresh_connection.cpp index 7fd2ecf6141335a17711001b4b5bbb1cb2101712..8c676b204bc6cb09e40ae2811c31e6c5e02ec3f6 100644 --- a/services/formmgr/src/form_refresh_connection.cpp +++ b/services/formmgr/src/form_refresh_connection.cpp @@ -1,72 +1,72 @@ - -/* - * 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 "appexecfwk_errors.h" -#include "app_log_wrapper.h" -#include "form_constants.h" -#include "form_refresh_connection.h" -#include "form_supply_callback.h" -#include "form_task_mgr.h" -#include "ipc_types.h" -#include "message_parcel.h" -#include "want.h" - -namespace OHOS { -namespace AppExecFwk { -FormRefreshConnection::FormRefreshConnection(const int64_t formId, const Want& want, - const std::string &bundleName, const std::string &abilityName) - :formId_(formId), - want_(want) -{ - SetProviderKey(bundleName, abilityName); -} -/** - * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. - * - * @param element Service ability's ElementName. - * @param remoteObject The session proxy of service ability. - * @param resultCode ERR_OK on success, others on failure. - * @return none. - */ -void FormRefreshConnection::OnAbilityConnectDone( - const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) -{ - APP_LOGI("%{public}s called.", __func__); - if (resultCode != ERR_OK) { - APP_LOGE("%{public}s, abilityName:%{public}s, formId:%{public}" PRId64 ", resultCode:%{public}d", - __func__, element.GetAbilityName().c_str(), formId_, resultCode); - return; - } - FormSupplyCallback::GetInstance()->AddConnection(this); - - if (want_.HasParameter(Constants::PARAM_MESSAGE_KEY)) { - std::string message = want_.GetStringParam(Constants::PARAM_MESSAGE_KEY); - } else if (want_.HasParameter(Constants::RECREATE_FORM_KEY)) { - Want cloneWant = Want(want_); - cloneWant.RemoveParam(Constants::RECREATE_FORM_KEY); - cloneWant.SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_RECREATE_FORM); - cloneWant.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); - FormTaskMgr::GetInstance().PostAcquireTask(formId_, cloneWant, remoteObject); - } else { - Want want; - want.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); - FormTaskMgr::GetInstance().PostRefreshTask(formId_, want, remoteObject); - } -} -} // namespace AppExecFwk + +/* + * 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_constants.h" +#include "form_refresh_connection.h" +#include "form_supply_callback.h" +#include "form_task_mgr.h" +#include "ipc_types.h" +#include "message_parcel.h" +#include "want.h" + +namespace OHOS { +namespace AppExecFwk { +FormRefreshConnection::FormRefreshConnection(const int64_t formId, const Want& want) + :formId_(formId), + want_(want) +{ +} +/** + * @brief OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. + * + * @param element Service ability's ElementName. + * @param remoteObject The session proxy of service ability. + * @param resultCode ERR_OK on success, others on failure. + * @return none. + */ +void FormRefreshConnection::OnAbilityConnectDone( + const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) +{ + APP_LOGI("%{public}s called.", __func__); + + if (resultCode != ERR_OK) { + APP_LOGE("%{public}s, abilityName:%{public}s, formId:%{public}" PRId64 ", resultCode:%{public}d", + __func__, element.GetAbilityName().c_str(), formId_, resultCode); + return; + } + FormSupplyCallback::GetInstance()->AddConnection(this); + + if (want_.HasParameter(Constants::PARAM_MESSAGE_KEY)) { + std::string message = want_.GetStringParam(Constants::PARAM_MESSAGE_KEY); + // FormTaskMgr::GetInstance()->FireFormEvent(formId, message, BuildDefaultWant(null, this), remoteObject); + } else if (want_.HasParameter(Constants::RECREATE_FORM_KEY)) { + Want cloneWant = Want(want_); + cloneWant.RemoveParam(Constants::RECREATE_FORM_KEY); + cloneWant.SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_RECREATE_FORM); + cloneWant.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); + FormTaskMgr::GetInstance().PostAcquireTask(formId_, cloneWant, remoteObject); + } else { + Want want; + want.SetParam(Constants::FORM_CONNECT_ID, this->GetConnectId()); + FormTaskMgr::GetInstance().PostRefreshTask(formId_, want, remoteObject); + } +} +} // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/src/form_storage_mgr.cpp b/services/formmgr/src/form_storage_mgr.cpp index 7c3745ba00bc310b1f6a8cfbbae27615b797be1e..6f329ff712a0c3dca9ae071b5cf774530d7185be 100644 --- a/services/formmgr/src/form_storage_mgr.cpp +++ b/services/formmgr/src/form_storage_mgr.cpp @@ -1,255 +1,315 @@ -/* - * 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 -#include -#include -#include -#include -#include - -#include "securec.h" -#include "app_log_wrapper.h" -#include "form_storage_mgr.h" -#include "string_ex.h" - -namespace OHOS { -namespace AppExecFwk { -namespace { -const char* FORM_DB_DATA_BASE_FILE_DIR = "/data/formmgr"; -const int32_t FORM_DB_DATA_BASE_FILE_PATH_LEN = 255; -} - -/** - * @brief Load form data from fileNamePath to innerFormInfos. - * @param fileNamePath load file path. - * @param innerFormInfos Save form data. - * @return Returns true if the data is successfully loaded; returns false otherwise. - */ -static bool LoadFormDataFile(const char* fileNamePath, std::vector &innerFormInfos) -{ - bool ret = false; - std::ifstream i(fileNamePath); - if (!i.is_open()) { - APP_LOGE("%{public}s, failed to open file[%{public}s]", __func__, fileNamePath); - return false; - } - - nlohmann::json jParse; - i.seekg(0, std::ios::end); - int len = static_cast(i.tellg()); - if (len != 0) { - i.seekg(0, std::ios::beg); - i >> jParse; - for (auto &it : jParse.items()) { - InnerFormInfo innerFormInfo; - if (innerFormInfo.FromJson(it.value())) { - innerFormInfos.emplace_back(innerFormInfo); - } else { - APP_LOGE("%{public}s, failed to parse json, formId[%{public}s]", __func__, it.key().c_str()); - } - } - ret = true; - } else { - APP_LOGE("%{public}s, file[%{public}s] is empty", __func__, fileNamePath); - ret = false; - } - i.close(); - return ret; -} - -/** - * @brief Load all form data from DB to innerFormInfos. - * @param innerFormInfos Storage all form data. - * @return Returns ERR_OK on success, others on failure. - */ -ErrCode FormStorageMgr::LoadFormData(std::vector &innerFormInfos) const -{ - APP_LOGI("%{public}s called.", __func__); - DIR *dirptr = opendir(FORM_DB_DATA_BASE_FILE_DIR); - if (dirptr == NULL) { - APP_LOGE("%{public}s, opendir failed, should no formmgr dir", __func__); - return ERR_APPEXECFWK_FORM_COMMON_CODE; - } - - struct dirent *ptr; - while ((ptr = readdir(dirptr)) != NULL) { - APP_LOGI("%{public}s, readdir fileName[%{public}s]", __func__, ptr->d_name); - if ((strcmp(ptr->d_name, ".") == 0) || (strcmp(ptr->d_name, "..") == 0)) { - continue; - } - char fileNamePath[FORM_DB_DATA_BASE_FILE_PATH_LEN] = {0}; - sprintf_s(fileNamePath, FORM_DB_DATA_BASE_FILE_PATH_LEN, "%s/%s", FORM_DB_DATA_BASE_FILE_DIR, ptr->d_name); - if (!LoadFormDataFile(fileNamePath, innerFormInfos)) { - APP_LOGE("%{public}s, LoadFormDataFile failed, file[%{public}s]", __func__, ptr->d_name); - } - } - APP_LOGI("%{public}s, readdir over", __func__); - closedir(dirptr); - return ERR_OK; -} - -/** - * @brief Get form data from DB to innerFormInfo with formId. - * @param innerFormInfo Storage form data. - * @return Returns ERR_OK on success, others on failure. - */ -ErrCode FormStorageMgr::GetStorageFormInfoById(const std::string &formId, InnerFormInfo &innerFormInfo) const -{ - ErrCode ret = ERR_OK; - APP_LOGD("%{public}s called, formId[%{public}s]", __func__, formId.c_str()); - char fileNamePath[FORM_DB_DATA_BASE_FILE_PATH_LEN] = {0}; - sprintf_s(fileNamePath, FORM_DB_DATA_BASE_FILE_PATH_LEN, "%s/%s.json", FORM_DB_DATA_BASE_FILE_DIR, formId.c_str()); - std::ifstream i(fileNamePath); - nlohmann::json jParse; - if (!i.is_open()) { - APP_LOGE("%{public}s, open failed, should no this file[%{public}s.json]", __func__, formId.c_str()); - return ERR_APPEXECFWK_FORM_COMMON_CODE; - } - APP_LOGD("%{public}s, open success file[%{public}s.json]", __func__, formId.c_str()); - i.seekg(0, std::ios::end); - int len = static_cast(i.tellg()); - if (len != 0) { - i.seekg(0, std::ios::beg); - i >> jParse; - auto it = jParse.find(formId); - if (it != jParse.end()) { - if (innerFormInfo.FromJson(it.value()) == false) { - APP_LOGE("%{public}s, fromJson parse failed formId[%{public}s]", __func__, it.key().c_str()); - ret = ERR_APPEXECFWK_FORM_COMMON_CODE; - } else { - ret = ERR_OK; - } - } else { - APP_LOGE("%{public}s, not find formId[%{public}s]", __func__, formId.c_str()); - ret = ERR_APPEXECFWK_FORM_COMMON_CODE; - } - } else { - APP_LOGE("%{public}s, file is empty formId[%{public}s]", __func__, formId.c_str()); - ret = ERR_APPEXECFWK_FORM_COMMON_CODE; - } - i.close(); - - return ret; -} - -/** - * @brief Save or update the form data in DB. - * @param innerFormInfo Indicates the InnerFormInfo object to be save. - * @return Returns ERR_OK on success, others on failure. - */ -ErrCode FormStorageMgr::SaveStorageFormInfo(const InnerFormInfo &innerFormInfo) const -{ - APP_LOGI("%{public}s called, formId[%{public}" PRId64 "]", __func__, innerFormInfo.GetFormId()); - ErrCode ret = ERR_OK; - std::string formId = std::to_string(innerFormInfo.GetFormId()); - - DIR *dirptr = opendir(FORM_DB_DATA_BASE_FILE_DIR); - if (dirptr == NULL) { - APP_LOGW("%{public}s, failed to open dir", __func__); - if (-1 == mkdir(FORM_DB_DATA_BASE_FILE_DIR, S_IRWXU)) { - APP_LOGE("%{public}s, failed to create dir", __func__); - return ERR_APPEXECFWK_FORM_COMMON_CODE; - } - } else { - closedir(dirptr); - } - char tmpFilePath[FORM_DB_DATA_BASE_FILE_PATH_LEN] = {0}; - sprintf_s(tmpFilePath, FORM_DB_DATA_BASE_FILE_PATH_LEN, "%s/%s.json", FORM_DB_DATA_BASE_FILE_DIR, formId.c_str()); - std::fstream f(tmpFilePath); - nlohmann::json jParse; - if (!f.is_open()) { - std::ofstream o(tmpFilePath); // if file not exist, should create file here - if (!o.is_open()) { - APP_LOGE("%{public}s, touch new file[%{public}s] failed", __func__, tmpFilePath); - return ERR_APPEXECFWK_FORM_COMMON_CODE; - } - o.close(); - APP_LOGI("%{public}s, touch new file[%{public}s.json]", __func__, formId.c_str()); - f.open(tmpFilePath); - } - bool isExist = f.good(); - if (isExist) { - nlohmann::json innerInfo; - innerFormInfo.ToJson(innerInfo); - f.seekg(0, std::ios::end); - int len = static_cast(f.tellg()); - if (len == 0) { - nlohmann::json formRoot; - formRoot[formId] = innerInfo; - f << formRoot << std::endl; - } else { - APP_LOGE("%{public}s, file[%{public}s.json] is not empty", __func__, formId.c_str()); - } - } else { - APP_LOGE("%{public}s, touch new file[%{public}s] failed", __func__, formId.c_str()); - ret = ERR_APPEXECFWK_FORM_COMMON_CODE; - } - f.close(); - return ret; -} - -/** - * @brief Modify the form data in DB. - * @param innerFormInfo Indicates the InnerFormInfo object to be Modify. - * @return Returns ERR_OK on success, others on failure. - */ -ErrCode FormStorageMgr::ModifyStorageFormInfo(const InnerFormInfo &innerFormInfo) const -{ - APP_LOGI("%{public}s called, formId[%{public}" PRId64 "]", __func__, innerFormInfo.GetFormId()); - char fileNamePath[FORM_DB_DATA_BASE_FILE_PATH_LEN] = {0}; - sprintf_s(fileNamePath, FORM_DB_DATA_BASE_FILE_PATH_LEN, "%s/%" PRId64 ".json", FORM_DB_DATA_BASE_FILE_DIR, innerFormInfo.GetFormId()); - - std::ofstream o(fileNamePath, std::ios_base::trunc | std::ios_base::out); - if (!o.is_open()) { - APP_LOGE("%{public}s, open failed file[%{public}s]", __func__, fileNamePath); - return ERR_APPEXECFWK_FORM_COMMON_CODE; - } - - nlohmann::json innerInfo; - innerFormInfo.ToJson(innerInfo); - nlohmann::json formRoot; - std::string formId = std::to_string(innerFormInfo.GetFormId()); - - formRoot[formId] = innerInfo; - o << formRoot << std::endl; - - o.close(); - return ERR_OK; -} - -/** - * @brief Delete the form data in DB. - * @param formId The form data Id. - * @return Returns ERR_OK on success, others on failure. - */ -ErrCode FormStorageMgr::DeleteStorageFormInfo(const std::string &formId) const -{ - APP_LOGI("%{public}s called, formId[%{public}s]", __func__, formId.c_str()); - char fileNamePath[FORM_DB_DATA_BASE_FILE_PATH_LEN] = {0}; - sprintf_s(fileNamePath, FORM_DB_DATA_BASE_FILE_PATH_LEN, "%s/%s.json", FORM_DB_DATA_BASE_FILE_DIR, formId.c_str()); - - if (std::remove(fileNamePath) != 0) { - APP_LOGE("%{public}s, delete failed file[%{public}s]", __func__, fileNamePath); - return ERR_APPEXECFWK_FORM_COMMON_CODE; - } - - return ERR_OK; -} -} // namespace AppExecFwk -} // namespace OHOS +/* + * 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 +#include +#include +#include +#include + +#include "app_log_wrapper.h" +#include "form_storage_mgr.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +const char* FORM_DB_DATA_BASE_FILE_DIR = "/data/formmgr"; +const int32_t FORM_DB_DATA_BASE_FILE_PATH_LEN = 255; +} + +// bool FormStorageMgr::KeyToDeviceAndName(const std::string &key, std::string &deviceId, std::string &bundleName) const +// { +// bool ret = false; +// std::vector splitStrs; +// const std::string::size_type EXPECT_SPLIT_SIZE = 2; +// OHOS::SplitStr(key, Constants::FILE_UNDERLINE, splitStrs); +// // the expect split size should be 2. +// // key rule is _ +// if (splitStrs.size() == EXPECT_SPLIT_SIZE) { +// deviceId = splitStrs[0]; +// bundleName = splitStrs[1]; +// ret = true; +// } +// APP_LOGD("key = %{private}s, bundleName = %{public}s", key.c_str(), bundleName.c_str()); +// return ret; +// } + +// void FormStorageMgr::DeviceAndNameToKey( +// const std::string &deviceId, const std::string &bundleName, std::string &key) const +// { +// key.append(deviceId); +// key.append(Constants::FILE_UNDERLINE); +// key.append(bundleName); +// APP_LOGD("key = %{private}s, bundleName = %{public}s", key.c_str(), bundleName.c_str()); +// } + +// bool FormStorageMgr::bool LoadAllData(std::map> &infos) const +// { +// bool ret = false; +// APP_LOGI("load all installed bundle data to map"); + +// std::fstream i(Constants::BUNDLE_DATA_BASE_FILE); +// nlohmann::json jParse; +// if (!i.is_open()) { +// APP_LOGE("failed to open bundle database file"); +// // if file not exist, should create file here +// std::ofstream o(Constants::BUNDLE_DATA_BASE_FILE); +// o.close(); +// return false; +// } +// APP_LOGI("open bundle database file success"); +// i.seekg(0, std::ios::end); +// int len = static_cast(i.tellg()); +// if (len > 0) { +// i.seekg(0, std::ios::beg); +// i >> jParse; +// for (auto &app : jParse.items()) { +// std::map deviceMap; +// for (auto &device : app.value().items()) { +// InnerBundleInfo innerBundleInfo; +// ret = innerBundleInfo.FromJson(device.value()); +// deviceMap.emplace(device.key(), innerBundleInfo); +// } +// auto pair = infos.emplace(app.key(), deviceMap); +// ret = pair.second; +// } +// } +// i.close(); +// return ret; +// } + +/** + * @brief Load form data from fileNamePath to innerFormInfos. + * @param fileNamePath load file path. + * @param innerFormInfos Save form data. + * @return Returns true if the data is successfully loaded; returns false otherwise. + */ +static bool LoadFormDataFile(const char* fileNamePath, std::vector &innerFormInfos) +{ + bool ret = false; + std::ifstream i(fileNamePath); + if (!i.is_open()) { + APP_LOGE("%{public}s, failed to open file[%{public}s]", __func__, fileNamePath); + return false; + } + + nlohmann::json jParse; + i.seekg(0, std::ios::end); + int len = static_cast(i.tellg()); + if (len != 0) { + i.seekg(0, std::ios::beg); + i >> jParse; + for (auto &it : jParse.items()) { + InnerFormInfo innerFormInfo; + if (innerFormInfo.FromJson(it.value())) { + innerFormInfos.emplace_back(innerFormInfo); + } else { + APP_LOGE("%{public}s, failed to parse json, formId[%{public}s]", __func__, it.key().c_str()); + } + } + ret = true; + } else { + APP_LOGE("%{public}s, file[%{public}s] is empty", __func__, fileNamePath); + ret = false; + } + i.close(); + return ret; +} + +/** + * @brief Load all form data from DB to innerFormInfos. + * @param innerFormInfos Storage all form data. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormStorageMgr::LoadFormData(std::vector &innerFormInfos) const +{ + APP_LOGI("%{public}s called.", __func__); + DIR *dirptr = opendir(FORM_DB_DATA_BASE_FILE_DIR); + if (dirptr == NULL) { + APP_LOGE("%{public}s, opendir failed, should no formmgr dir", __func__); + return ERR_APPEXECFWK_FORM_JSON_NO_DIR; + } + + struct dirent *ptr; + while ((ptr = readdir(dirptr)) != NULL) { + APP_LOGI("%{public}s, readdir fileName[%{public}s]", __func__, ptr->d_name); + if ((strcmp(ptr->d_name, ".") == 0) || (strcmp(ptr->d_name, "..") == 0)) { + continue; + } + char fileNamePath[FORM_DB_DATA_BASE_FILE_PATH_LEN] = {0}; + sprintf(fileNamePath, "%s/%s", FORM_DB_DATA_BASE_FILE_DIR, ptr->d_name); + if (!LoadFormDataFile(fileNamePath, innerFormInfos)) { + APP_LOGE("%{public}s, LoadFormDataFile failed, file[%{public}s]", __func__, ptr->d_name); + } + } + APP_LOGI("%{public}s, readdir over", __func__); + closedir(dirptr); + return ERR_OK; +} + +/** + * @brief Get form data from DB to innerFormInfo with formId. + * @param innerFormInfo Storage form data. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormStorageMgr::GetStorageFormInfoById(const std::string &formId, InnerFormInfo &innerFormInfo) const +{ + ErrCode ret = ERR_OK; + APP_LOGD("%{public}s called, formId[%{public}s]", __func__, formId.c_str()); + char fileNamePath[FORM_DB_DATA_BASE_FILE_PATH_LEN] = {0}; + sprintf(fileNamePath, "%s/%s.json", FORM_DB_DATA_BASE_FILE_DIR, formId.c_str()); + std::ifstream i(fileNamePath); + nlohmann::json jParse; + if (!i.is_open()) { + APP_LOGE("%{public}s, open failed, should no this file[%{public}s.json]", __func__, formId.c_str()); + return ERR_APPEXECFWK_FORM_JSON_OPEN_FAIL; + } + APP_LOGD("%{public}s, open success file[%{public}s.json]", __func__, formId.c_str()); + i.seekg(0, std::ios::end); + int len = static_cast(i.tellg()); + if (len != 0) { + i.seekg(0, std::ios::beg); + i >> jParse; + auto it = jParse.find(formId); + if (it != jParse.end()) { + if (innerFormInfo.FromJson(it.value()) == false) { + APP_LOGE("%{public}s, fromJson parse failed formId[%{public}s]", __func__, it.key().c_str()); + ret = ERR_APPEXECFWK_FORM_JSON_PARSE_FAIL; + } else { + ret = ERR_OK; + } + } else { + APP_LOGE("%{public}s, not find formId[%{public}s]", __func__, formId.c_str()); + ret = ERR_APPEXECFWK_FORM_JSON_FIND_FAIL; + } + } else { + APP_LOGE("%{public}s, file is empty formId[%{public}s]", __func__, formId.c_str()); + ret = ERR_APPEXECFWK_FORM_JSON_FILE_EMPTY; + } + i.close(); + + return ret; +} + +/** + * @brief Save or update the form data in DB. + * @param innerFormInfo Indicates the InnerFormInfo object to be save. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormStorageMgr::SaveStorageFormInfo(const InnerFormInfo &innerFormInfo) const +{ + APP_LOGI("%{public}s called, formId[%{public}" PRId64 "]", __func__, innerFormInfo.GetFormId()); + ErrCode ret = ERR_OK; + std::string formId = std::to_string(innerFormInfo.GetFormId()); + + DIR *dirptr = opendir(FORM_DB_DATA_BASE_FILE_DIR); + if (dirptr == NULL) { + APP_LOGW("%{public}s, failed to open dir", __func__); + if (-1 == mkdir(FORM_DB_DATA_BASE_FILE_DIR, S_IRWXU)) { + APP_LOGE("%{public}s, failed to create dir", __func__); + return ERR_APPEXECFWK_FORM_JSON_CREATE_DIR_FAIL; + } + } else { + closedir(dirptr); + } + char tmpFilePath[FORM_DB_DATA_BASE_FILE_PATH_LEN] = {0}; + sprintf(tmpFilePath, "%s/%s.json", FORM_DB_DATA_BASE_FILE_DIR, formId.c_str()); + + std::fstream f(tmpFilePath); + nlohmann::json jParse; + if (!f.is_open()) { + std::ofstream o(tmpFilePath); // if file not exist, should create file here + if (!o.is_open()) { + APP_LOGE("%{public}s, touch new file[%{public}s] failed", __func__, tmpFilePath); + return ERR_APPEXECFWK_FORM_JSON_NEW_FILE_FAIL; + } + o.close(); + APP_LOGI("%{public}s, touch new file[%{public}s.json]", __func__, formId.c_str()); + f.open(tmpFilePath); + } + bool isExist = f.good(); + if (isExist) { + nlohmann::json innerInfo; + innerFormInfo.ToJson(innerInfo); + f.seekg(0, std::ios::end); + int len = static_cast(f.tellg()); + if (len == 0) { + nlohmann::json formRoot; + formRoot[formId] = innerInfo; + f << formRoot << std::endl; + } else { + APP_LOGE("%{public}s, file[%{public}s.json] is not empty", __func__, formId.c_str()); + } + } else { + APP_LOGE("%{public}s, touch new file[%{public}s] failed", __func__, formId.c_str()); + ret = ERR_APPEXECFWK_FORM_JSON_OPEN_FAIL; + } + f.close(); + return ret; +} + +/** + * @brief Modify the form data in DB. + * @param innerFormInfo Indicates the InnerFormInfo object to be Modify. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormStorageMgr::ModifyStorageFormInfo(const InnerFormInfo &innerFormInfo) const +{ + APP_LOGI("%{public}s called, formId[%{public}" PRId64 "]", __func__, innerFormInfo.GetFormId()); + char fileNamePath[FORM_DB_DATA_BASE_FILE_PATH_LEN] = {0}; + sprintf(fileNamePath, "%s/%" PRId64 ".json", FORM_DB_DATA_BASE_FILE_DIR, innerFormInfo.GetFormId()); + + std::ofstream o(fileNamePath, std::ios_base::trunc | std::ios_base::out); + if (!o.is_open()) { + APP_LOGE("%{public}s, open failed file[%{public}s]", __func__, fileNamePath); + return ERR_APPEXECFWK_FORM_JSON_OPEN_FAIL; + } + + nlohmann::json innerInfo; + innerFormInfo.ToJson(innerInfo); + nlohmann::json formRoot; + std::string formId = std::to_string(innerFormInfo.GetFormId()); + + formRoot[formId] = innerInfo; + o << formRoot << std::endl; + + o.close(); + return ERR_OK; +} + +/** + * @brief Delete the form data in DB. + * @param formId The form data Id. + * @return Returns ERR_OK on success, others on failure. + */ +ErrCode FormStorageMgr::DeleteStorageFormInfo(const std::string &formId) const +{ + APP_LOGI("%{public}s called, formId[%{public}s]", __func__, formId.c_str()); + char fileNamePath[FORM_DB_DATA_BASE_FILE_PATH_LEN] = {0}; + sprintf(fileNamePath, "%s/%s.json", FORM_DB_DATA_BASE_FILE_DIR, formId.c_str()); + + if (std::remove(fileNamePath) != 0) { + APP_LOGE("%{public}s, delete failed file[%{public}s]", __func__, fileNamePath); + return ERR_APPEXECFWK_FORM_JSON_DELETE_FAIL; + } + + return ERR_OK; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/src/form_supply_callback.cpp b/services/formmgr/src/form_supply_callback.cpp index 3fef6de0c6574e725202e0f71cd41817f45d641e..9a240bf1d57918b3e9d80d6c2d4f4fd981a88dcf 100644 --- a/services/formmgr/src/form_supply_callback.cpp +++ b/services/formmgr/src/form_supply_callback.cpp @@ -1,156 +1,120 @@ -/* - * 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 "appexecfwk_errors.h" -#include "app_log_wrapper.h" -#include "form_ams_helper.h" -#include "form_constants.h" -#include "form_provider_mgr.h" -#include "form_supply_callback.h" -#include "form_util.h" -#include "string_ex.h" - -namespace OHOS { -namespace AppExecFwk { -sptr FormSupplyCallback::instance_ = nullptr; -std::mutex FormSupplyCallback::mutex_; - -sptr FormSupplyCallback::GetInstance() -{ - if (instance_ == nullptr) { - std::lock_guard lock_l(mutex_); - if (instance_ == nullptr) { - instance_ = new FormSupplyCallback(); - } - } - return instance_; -} - -/** - * @brief Accept form binding data from form provider. - * @param providerFormInfo Form binding data. - * @param want input data. - * @return Returns ERR_OK on success, others on failure. - */ -int FormSupplyCallback::OnAcquire(const FormProviderInfo &formProviderInfo, const Want &want) -{ - APP_LOGI("%{public}s called.", __func__); - long connectId = want.GetLongParam(Constants::FORM_CONNECT_ID, 0); - int errCode = want.GetIntParam(Constants::PROVIDER_FLAG, ERR_OK); - if (errCode != ERR_OK) { - RemoveConnection(connectId); - return errCode; - } - - std::string strFormId = want.GetStringParam(Constants::PARAM_FORM_IDENTITY_KEY); - int64_t formId = std::stoll(strFormId); - int type = want.GetIntParam(Constants::ACQUIRE_TYPE, 0); - APP_LOGD("%{public}s come: %{public}" PRId64 ", %{public}ld, %{public}d", __func__, - formId, connectId, type); - RemoveConnection(connectId); - - switch (type) { - case Constants::ACQUIRE_TYPE_CREATE_FORM: - return FormProviderMgr::GetInstance().AcquireForm(formId, formProviderInfo); - case Constants::ACQUIRE_TYPE_RECREATE_FORM: - return FormProviderMgr::GetInstance().UpdateForm(formId, formProviderInfo); - default: - APP_LOGW("%{public}s warning, onAcquired type: %{public}d", __func__, type); - } - APP_LOGI("%{public}s end.", __func__); - return ERR_APPEXECFWK_FORM_INVALID_PARAM; -} - -/** - * @brief Accept other event. - * @param want input data. - * @return Returns ERR_OK on success, others on failure. - */ -int FormSupplyCallback::OnEventHandle(const Want &want) -{ - APP_LOGI("%{public}s called.", __func__); - long connectId = want.GetLongParam(Constants::FORM_CONNECT_ID, 0); - std::string supplyInfo = want.GetStringParam(Constants::FORM_SUPPLY_INFO); - APP_LOGD("%{public}s come: %{public}ld, %{public}s", __func__, connectId, supplyInfo.c_str()); - RemoveConnection(connectId); - APP_LOGI("%{public}s end.", __func__); - return ERR_OK; -} -/** - * @brief Save ability Connection for the callback. - * @param connection ability connection. - */ -void FormSupplyCallback::AddConnection(sptr connection) -{ - APP_LOGI("%{public}s called.", __func__); - std::lock_guard lock_l(conMutex_); - long connectKey = FormUtil::GetCurrentMillisecond(); - while (connections_.find(connectKey) != connections_.end()) { - connectKey++; - } - connection->SetConnectId(connectKey); - connections_.emplace(connectKey, connection); - APP_LOGI("%{public}s end.", __func__); -} - -/** - * @brief Delete ability connection after the callback come. - * @param connectId The ability connection id generated when save. - */ -void FormSupplyCallback::RemoveConnection(long connectId) -{ - APP_LOGI("%{public}s called.", __func__); - std::lock_guard lock_l(conMutex_); - auto conIterator = connections_.find(connectId); - if (conIterator != connections_.end()) { - sptr connection = conIterator->second; - if (connection != nullptr) { - if(CanDisConnect(connection)) { - FormAmsHelper::GetInstance().DisConnectServiceAbility(connection); - APP_LOGI("%{public}s end, disconnect service ability", __func__); - } else { - FormAmsHelper::GetInstance().DisConnectServiceAbilityDelay(connection); - APP_LOGI("%{public}s end, disconnect service ability delay", __func__); - } - } - connections_.erase(connectId); - } - APP_LOGI("%{public}s end.", __func__); -} -/** - * @brief check if disconnect ability or not. - * @param connection The ability connection. - */ -bool FormSupplyCallback::CanDisConnect(sptr &connection) -{ - APP_LOGI("%{public}s called.", __func__); - int count = 0; - for(auto &conn : connections_) { - if(connection->GetProviderKey() == conn.second->GetProviderKey()) { - APP_LOGI("%{public}s, key: %{public}s", __func__, conn.second->GetProviderKey().c_str()); - count++; - if(count > 1) { - APP_LOGI("%{public}s end, true.", __func__); - return true; - } - } - } - APP_LOGI("%{public}s end, false.", __func__); - return false; -} -} // namespace AppExecFwk -} // namespace OHOS +/* + * 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "form_ams_helper.h" +#include "form_constants.h" +#include "form_provider_mgr.h" +#include "form_supply_callback.h" +#include "form_util.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +sptr FormSupplyCallback::instance_ = nullptr; +std::mutex FormSupplyCallback::mutex_; + +sptr FormSupplyCallback::GetInstance() +{ + if (instance_ == nullptr) { + std::lock_guard lock_l(mutex_); + if (instance_ == nullptr) { + instance_ = new FormSupplyCallback(); + } + } + return instance_; +} + +/** + * @brief Accept form binding data from form provider. + * @param providerFormInfo Form binding data. + * @param want input data. + * @return Returns ERR_OK on success, others on failure. + */ +int FormSupplyCallback::OnAcquire(const FormProviderInfo &formProviderInfo, const Want &want) +{ + long connectId = want.GetLongParam(Constants::FORM_CONNECT_ID, 0); + int errCode = want.GetIntParam(Constants::PROVIDER_FLAG, ERR_OK); + if (errCode != ERR_OK) { + RemoveConnection(connectId); + return errCode; + } + + int64_t formId = formProviderInfo.GetFormId(); + int type = want.GetIntParam(Constants::ACQUIRE_TYPE, 0); + APP_LOGD("%{public}s come: %{public}" PRId64 ", %{public}ld, %{public}d", __func__, + formId, connectId, type); + RemoveConnection(connectId); + + switch (type) { + case Constants::ACQUIRE_TYPE_CREATE_FORM: + return FormProviderMgr::GetInstance().AcquireForm(formId, formProviderInfo); + case Constants::ACQUIRE_TYPE_RECREATE_FORM: + return FormProviderMgr::GetInstance().UpdateForm(formId, formProviderInfo); + default: + APP_LOGW("%{public}s warning, onAcquired type: %{public}d", __func__, type); + } + return ERR_APPEXECFWK_FORM_INVALID_PARAM; +} + +/** + * @brief Accept other event. + * @param want input data. + * @return Returns ERR_OK on success, others on failure. + */ +int FormSupplyCallback::OnEventHandle(const Want &want) +{ + long connectId = want.GetLongParam(Constants::FORM_CONNECT_ID, 0); + std::string supplyInfo = want.GetStringParam(Constants::FORM_SUPPLY_INFO); + APP_LOGD("%{public}s come: %{public}ld, %{public}s", __func__, connectId, supplyInfo.c_str()); + RemoveConnection(connectId); + return ERR_OK; +} +/** + * @brief Save ability Connection for the callback. + * @param connection ability connection. + */ +void FormSupplyCallback::AddConnection(sptr connection) +{ + std::lock_guard lock_l(conMutex_); + long connectKey = FormUtil::GetCurrentMillisecond(); + while (connections_.find(connectKey) != connections_.end()) { + connectKey++; + } + connection->SetConnectId(connectKey); + connections_.emplace(connectKey, connection); +} + +/** + * @brief Delete ability connection after the callback come. + * @param connectId The ability connection id generated when save. + */ +void FormSupplyCallback::RemoveConnection(long connectId) +{ + std::lock_guard lock_l(conMutex_); + auto conIterator = connections_.find(connectId); + if (conIterator != connections_.end()) { + sptr connection = conIterator->second; + if (connection != nullptr) { + FormAmsHelper::GetInstance().DisConnectServiceAbility(connection); + } + connections_.erase(connectId); + } +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/src/form_sys_event_receiver.cpp b/services/formmgr/src/form_sys_event_receiver.cpp index 0fd6edcd7af5f3a947fd82dc5911b18e221b5c57..33f940538007f2984671cb412e6d4af89329fe11 100644 --- a/services/formmgr/src/form_sys_event_receiver.cpp +++ b/services/formmgr/src/form_sys_event_receiver.cpp @@ -52,9 +52,10 @@ void FormSysEventReceiver::OnReceiveEvent(const EventFwk::CommonEventData &event AAFwk::Want want = eventData.GetWant(); std::string action = want.GetAction(); std::string bundleName = want.GetStringParam(KEY_BUNDLE_NAME); + if (action.empty() || bundleName.empty()) { - APP_LOGE("%{public}s failed, invalid param, action: %{public}s, bundleName: %{public}s", - __func__, action.c_str(), bundleName.c_str()); + APP_LOGE("%{public}s failed, invalid param, action: %{public}s, bundleName: %{public}s", __func__, + action.c_str(), bundleName.c_str()); return; } APP_LOGI("%{public}s, action:%{public}s.", __func__, action.c_str()); @@ -171,8 +172,8 @@ void FormSysEventReceiver::HandleProviderRemoved(const std::string &bundleName) } } -bool FormSysEventReceiver::ProviderFormUpdated(const int64_t formId, - const FormRecord &formRecord, const std::vector &targetForms) +bool FormSysEventReceiver::ProviderFormUpdated(const int64_t formId, const FormRecord &formRecord, +const std::vector &targetForms) { APP_LOGI("%{public}s start", __func__); if (targetForms.empty()) { @@ -269,7 +270,7 @@ void FormSysEventReceiver::ClearTempFormRecordData(const int uid, std::map> &noHostFormDbMap, std::map &removedFormsMap) +std::set> &noHostFormDbMap, std::map &removedFormsMap) { std::set removableModuleSet; for (const auto &element: noHostFormDbMap) { @@ -279,8 +280,7 @@ void FormSysEventReceiver::BatchDeleteNoHostDBForms(const int uid, std::map
> &noHostTempFormsMap, std::map &foundFormsMap) +std::set> &noHostTempFormsMap, std::map &foundFormsMap) { for (const auto &element : noHostTempFormsMap) { std::set formIds = element.second; @@ -330,8 +330,7 @@ void FormSysEventReceiver::BatchDeleteNoHostTempForms(const int uid, std::map Constants::MAX_HOUR || min < Constants::MIN_TIME || min > - Constants::MAX_MININUTE) { + Constants::MAX_MININUTE) { APP_LOGE("%{public}s, time is invalid", __func__); return; } @@ -427,8 +426,8 @@ void FormSysEventReceiver::GetTimerCfg(const bool updateEnabled, } } -void FormSysEventReceiver::HandleTimerUpdate(const int64_t formId, - const FormRecord &record, const FormTimerCfg &timerCfg) +void FormSysEventReceiver::HandleTimerUpdate(const int64_t formId, const FormRecord &record, +const FormTimerCfg &timerCfg) { // both disable if (!record.isEnableUpdate && !timerCfg.enableUpdate) { @@ -444,14 +443,14 @@ void FormSysEventReceiver::HandleTimerUpdate(const int64_t formId, // disable to enable if (!record.isEnableUpdate && timerCfg.enableUpdate) { - FormDataMgr::GetInstance().SetUpdateInfo(formId, true, - timerCfg.updateDuration, timerCfg.updateAtHour, timerCfg.updateAtMin); + FormDataMgr::GetInstance().SetUpdateInfo(formId, true, timerCfg.updateDuration, timerCfg.updateAtHour, + timerCfg.updateAtMin); if (timerCfg.updateDuration > 0) { APP_LOGI("%{public}s, add interval timer:%{public}" PRId64 "", __func__, timerCfg.updateDuration); FormTimerMgr::GetInstance().AddFormTimer(formId, timerCfg.updateDuration); } else { - APP_LOGI("%{public}s, add at timer:%{public}d, %{public}d", __func__, - timerCfg.updateAtHour, timerCfg.updateAtMin); + APP_LOGI("%{public}s, add at timer:%{public}d, %{public}d", __func__, timerCfg.updateAtHour, + timerCfg.updateAtMin); FormTimerMgr::GetInstance().AddFormTimer(formId, timerCfg.updateAtHour, timerCfg.updateAtMin); } @@ -486,8 +485,8 @@ void FormSysEventReceiver::HandleTimerUpdate(const int64_t formId, } } - FormDataMgr::GetInstance().SetUpdateInfo(formId, true, - timerCfg.updateDuration, timerCfg.updateAtHour, timerCfg.updateAtMin); + FormDataMgr::GetInstance().SetUpdateInfo(formId, true, timerCfg.updateDuration, timerCfg.updateAtHour, + timerCfg.updateAtMin); FormTimerMgr::GetInstance().UpdateFormTimer(formId, type, timerCfg); } } // namespace AppExecFwk diff --git a/services/formmgr/src/form_task_mgr.cpp b/services/formmgr/src/form_task_mgr.cpp index cbaa7fa32fd2b5308990b800b20333bde68f2361..bcd4376d94d373c04c86c0851c841f9f0a4bf7f8 100644 --- a/services/formmgr/src/form_task_mgr.cpp +++ b/services/formmgr/src/form_task_mgr.cpp @@ -20,7 +20,6 @@ #include "form_data_mgr.h" #include "form_host_interface.h" #include "form_item_info.h" -#include "form_mgr_adapter.h" #include "form_provider_interface.h" #include "form_supply_callback.h" #include "form_task_mgr.h" @@ -28,7 +27,6 @@ namespace OHOS { namespace AppExecFwk { -const int FORM_TASK_DELAY_TIME = 6; // ms FormTaskMgr::FormTaskMgr() {} FormTaskMgr::~FormTaskMgr() {} /** @@ -43,9 +41,13 @@ void FormTaskMgr::PostAcquireTask(const int64_t formId, const Want &want, const APP_LOGE("%{public}s fail, eventhandler invalidate", __func__); return; } - std::function acquireProviderFormInfoFunc = std::bind(&FormTaskMgr::AcquireProviderFormInfo, - this, formId, want, remoteObject); - eventHandler_->PostTask(acquireProviderFormInfoFunc, FORM_TASK_DELAY_TIME); + std::function acquireProviderFormInfoFunc = std::bind( + &FormTaskMgr::AcquireProviderFormInfo, + this, + formId, + want, + remoteObject); + eventHandler_->PostTask(acquireProviderFormInfoFunc); } /** * @brief Delete form data from form provider(task). @@ -59,9 +61,13 @@ void FormTaskMgr::PostDeleteTask(const int64_t formId, const Want &want, const s APP_LOGE("%{public}s fail, eventhandler invalidate", __func__); return; } - std::function notifyFormDeleteFunc = std::bind(&FormTaskMgr::NotifyFormDelete, - this, formId, want, remoteObject); - eventHandler_->PostTask(notifyFormDeleteFunc, FORM_TASK_DELAY_TIME); + std::function notifyFormDeleteFunc = std::bind ( + &FormTaskMgr::NotifyFormDelete, + this, + formId, + want, + remoteObject); + eventHandler_->PostTask(notifyFormDeleteFunc); } /** @@ -78,9 +84,13 @@ void FormTaskMgr::PostRefreshTask(const int64_t formId, const Want &want, const APP_LOGE("%{public}s fail, eventhandler invalidate.", __func__); return; } - std::function notifyFormUpdateFunc = std::bind(&FormTaskMgr::NotifyFormUpdate, - this, formId, want, remoteObject); - eventHandler_->PostTask(notifyFormUpdateFunc, FORM_TASK_DELAY_TIME); + std::function notifyFormUpdateFunc = std::bind ( + &FormTaskMgr::NotifyFormUpdate, + this, + formId, + want, + remoteObject); + eventHandler_->PostTask(notifyFormUpdateFunc); } /** @@ -97,9 +107,13 @@ void FormTaskMgr::PostCastTempTask(const int64_t formId, const Want &want, const APP_LOGE("%{public}s fail, eventhandler invalidate", __func__); return; } - std::function notifyCastTempFunc = std::bind(&FormTaskMgr::NotifyCastTemp, - this, formId, want, remoteObject); - eventHandler_->PostTask(notifyCastTempFunc, FORM_TASK_DELAY_TIME); + std::function notifyCastTempFunc = std::bind ( + &FormTaskMgr::NotifyCastTemp, + this, + formId, + want, + remoteObject); + eventHandler_->PostTask(notifyCastTempFunc); } /** @@ -111,15 +125,19 @@ void FormTaskMgr::PostCastTempTask(const int64_t formId, const Want &want, const * @param remoteObject Form provider proxx object. */ void FormTaskMgr::PostAcquireTaskToHost(const int64_t formId, const FormRecord &record, - const sptr &remoteObject) +const sptr &remoteObject) { if (eventHandler_ == nullptr) { APP_LOGE("%{public}s fail, eventhandler invalidate", __func__); return; } - std::function acquireTaskToHostFunc = std::bind(&FormTaskMgr::AcquireTaskToHost, - this, formId, record, remoteObject); - eventHandler_->PostTask(acquireTaskToHostFunc, FORM_TASK_DELAY_TIME); + std::function acquireTaskToHostFunc = std::bind ( + &FormTaskMgr::AcquireTaskToHost, + this, + formId, + record, + remoteObject); + eventHandler_->PostTask(acquireTaskToHostFunc); } /** @@ -131,7 +149,7 @@ void FormTaskMgr::PostAcquireTaskToHost(const int64_t formId, const FormRecord & * @param remoteObject Form provider proxx object. */ void FormTaskMgr::PostUpdateTaskToHost(const int64_t formId, const FormRecord &record, - const sptr &remoteObject) +const sptr &remoteObject) { APP_LOGI("%{public}s called.", __func__); @@ -141,9 +159,13 @@ void FormTaskMgr::PostUpdateTaskToHost(const int64_t formId, const FormRecord &r } APP_LOGD("%{public}s, post the task of updateTaskToHostFunc.", __func__); - std::function updateTaskToHostFunc = std::bind(&FormTaskMgr::UpdateTaskToHost, - this, formId, record, remoteObject); - eventHandler_->PostTask(updateTaskToHostFunc, FORM_TASK_DELAY_TIME); + std::function updateTaskToHostFunc = std::bind ( + &FormTaskMgr::UpdateTaskToHost, + this, + formId, + record, + remoteObject); + eventHandler_->PostTask(updateTaskToHostFunc); } /** @@ -163,9 +185,11 @@ void FormTaskMgr::PostHostDiedTask(const sptr &remoteHost) APP_LOGE("%{public}s fail, eventhandler invalidate", __func__); return; } - std::function postTaskFunc = std::bind(&FormTaskMgr::HostDied, - this, remoteHost); - eventHandler_->PostTask(postTaskFunc, FORM_TASK_DELAY_TIME); + std::function postTaskFunc = std::bind ( + &FormTaskMgr::HostDied, + this, + remoteHost); + eventHandler_->PostTask(postTaskFunc); } /** @@ -178,15 +202,20 @@ void FormTaskMgr::PostHostDiedTask(const sptr &remoteHost) * @return none. */ void FormTaskMgr::PostEventNotifyTask(const std::vector &formEvent, const int32_t formVisibleType, - const Want &want, const sptr &remoteObject) +const Want &want, const sptr &remoteObject) { if (eventHandler_ == nullptr) { APP_LOGE("%{public}s fail, eventhandler invalidate.", __func__); return; } - std::function eventNotifyFunc = std::bind(&FormTaskMgr::EventNotify, - this, formEvent, formVisibleType, want, remoteObject); - eventHandler_->PostTask(eventNotifyFunc, FORM_TASK_DELAY_TIME); + std::function eventNotifyFunc = std::bind ( + &FormTaskMgr::EventNotify, + this, + formEvent, + formVisibleType, + want, + remoteObject); + eventHandler_->PostTask(eventNotifyFunc); } /** * @brief Post provider batch delete. @@ -195,15 +224,19 @@ void FormTaskMgr::PostEventNotifyTask(const std::vector &formEvent, con * @param remoteObject Form provider proxy object. */ void FormTaskMgr::PostProviderBatchDeleteTask(std::set &formIds, const Want &want, - const sptr &remoteObject) +const sptr &remoteObject) { if (eventHandler_ == nullptr) { APP_LOGE("%{public}s fail, eventhandler invalidate.", __func__); return; } - std::function batchDeleteFunc = std::bind(&FormTaskMgr::ProviderBatchDelete, - this, formIds, want, remoteObject); - eventHandler_->PostTask(batchDeleteFunc, FORM_TASK_DELAY_TIME); + std::function batchDeleteFunc = std::bind ( + &FormTaskMgr::ProviderBatchDelete, + this, + formIds, + want, + remoteObject); + eventHandler_->PostTask(batchDeleteFunc); } /** * @brief Post message event to form provider. @@ -212,16 +245,21 @@ void FormTaskMgr::PostProviderBatchDeleteTask(std::set &formIds, const * @param want The want of the request. * @param remoteObject Form provider proxy object. */ -void FormTaskMgr::PostFormEventTask(const int64_t formId, const std::string &message, - const Want &want, const sptr &remoteObject) +void FormTaskMgr::PostFormEventTask(const int64_t formId, const std::string &message, const Want &want, +const sptr &remoteObject) { if (eventHandler_ == nullptr) { APP_LOGE("%{public}s fail, eventhandler invalidate.", __func__); return; } - std::function formEventFunc = std::bind(&FormTaskMgr::FireFormEvent, - this, formId, message, want, remoteObject); - eventHandler_->PostTask(formEventFunc, FORM_TASK_DELAY_TIME); + std::function formEventFunc = std::bind ( + &FormTaskMgr::FireFormEvent, + this, + formId, + message, + want, + remoteObject); + eventHandler_->PostTask(formEventFunc); } /** @@ -236,9 +274,12 @@ void FormTaskMgr::PostUninstallTaskToHost(const std::vector &formIds, c APP_LOGE("%{public}s fail, eventhandler invalidate.", __func__); return; } - std::function uninstallFunc = std::bind(&FormTaskMgr::FormUninstall, - this, formIds, remoteObject); - eventHandler_->PostTask(uninstallFunc, FORM_TASK_DELAY_TIME); + std::function uninstallFunc = std::bind ( + &FormTaskMgr::FormUninstall, + this, + formIds, + remoteObject); + eventHandler_->PostTask(uninstallFunc); APP_LOGI("%{public}s end", __func__); } @@ -249,9 +290,20 @@ void FormTaskMgr::PostUninstallTaskToHost(const std::vector &formIds, c * @param remoteObject Form provider proxy object. */ void FormTaskMgr::AcquireProviderFormInfo(const int64_t formId, const Want &want, - const sptr &remoteObject) +const sptr &remoteObject) { - FormMgrAdapter::GetInstance().AcquireProviderFormInfo(formId, want, remoteObject); + long connectId = want.GetLongParam(Constants::FORM_CONNECT_ID, 0); + sptr formProviderProxy = iface_cast(remoteObject); + if (formProviderProxy == nullptr) { + FormSupplyCallback::GetInstance()->RemoveConnection(connectId); + APP_LOGE("%{public}s fail, Failed to get formProviderProxy", __func__); + return; + } + int error = formProviderProxy->AcquireProviderFormInfo(formId, want, FormSupplyCallback::GetInstance()); + if (error != ERR_OK) { + FormSupplyCallback::GetInstance()->RemoveConnection(connectId); + APP_LOGE("%{public}s fail, Failed to get acquire provider form info", __func__); + } } /** @@ -264,7 +316,18 @@ void FormTaskMgr::AcquireProviderFormInfo(const int64_t formId, const Want &want */ void FormTaskMgr::NotifyFormDelete(const int64_t formId, const Want &want, const sptr &remoteObject) { - FormMgrAdapter::GetInstance().NotifyFormDelete(formId, want, remoteObject); + long connectId = want.GetLongParam(Constants::FORM_CONNECT_ID, 0); + sptr formProviderProxy = iface_cast(remoteObject); + if (formProviderProxy == nullptr) { + FormSupplyCallback::GetInstance()->RemoveConnection(connectId); + APP_LOGE("%{public}s fail, Failed to get formProviderProxy", __func__); + return; + } + int error = formProviderProxy->NotifyFormDelete(formId, want, FormSupplyCallback::GetInstance()); + if (error != ERR_OK) { + FormSupplyCallback::GetInstance()->RemoveConnection(connectId); + APP_LOGE("%{public}s fail, Failed to get acquire provider form info", __func__); + } } /** @@ -286,6 +349,7 @@ void FormTaskMgr::NotifyFormUpdate(const int64_t formId, const Want &want, const APP_LOGE("%{public}s fail, failed to get formProviderProxy", __func__); return; } + int error = formProviderProxy->NotifyFormUpdate(formId, want, FormSupplyCallback::GetInstance()); if (error != ERR_OK) { FormSupplyCallback::GetInstance()->RemoveConnection(connectId); @@ -302,8 +366,8 @@ void FormTaskMgr::NotifyFormUpdate(const int64_t formId, const Want &want, const * @param remoteObject The form provider proxy object. * @return none. */ -void FormTaskMgr::EventNotify(const std::vector &formEvents, const int32_t formVisibleType, - const Want &want, const sptr &remoteObject) +void FormTaskMgr::EventNotify(const std::vector &formEvents, const int32_t formVisibleType, const Want &want, +const sptr &remoteObject) { APP_LOGI("%{public}s called.", __func__); @@ -358,7 +422,7 @@ void FormTaskMgr::NotifyCastTemp(const int64_t formId, const Want &want, const s * @param remoteObject Form provider proxx object. */ void FormTaskMgr::AcquireTaskToHost(const int64_t formId, const FormRecord &record, - const sptr &remoteObject) +const sptr &remoteObject) { APP_LOGI("FormTaskMgr AcquireTaskToHost, formId:%{public}" PRId64 "", formId); @@ -381,7 +445,7 @@ void FormTaskMgr::AcquireTaskToHost(const int64_t formId, const FormRecord &reco * @param remoteObject Form provider proxx object. */ void FormTaskMgr::UpdateTaskToHost(const int64_t formId, const FormRecord &record, - const sptr &remoteObject) +const sptr &remoteObject) { APP_LOGI("%{public}s start.", __func__); @@ -417,7 +481,7 @@ void FormTaskMgr::HostDied(const sptr &remoteHost) * @param remoteObject Form provider proxy object. */ void FormTaskMgr::ProviderBatchDelete(std::set &formIds, const Want &want, - const sptr &remoteObject) +const sptr &remoteObject) { APP_LOGI("%{public}s called.", __func__); long connectId = want.GetLongParam(Constants::FORM_CONNECT_ID, 0); @@ -499,9 +563,9 @@ FormJsInfo FormTaskMgr::CreateFormJsInfo(const int64_t formId, const FormRecord form.formTempFlg = record.formTempFlg; form.jsFormCodePath = record.jsFormCodePath; form.formData = record.formProviderInfo.GetFormDataString(); + form.formProviderData = record.formProviderInfo.GetFormData(); - APP_LOGI("%{public}s end, jsPath: %{public}s, data: %{public}s", __func__, - form.jsFormCodePath.c_str(), form.formData.c_str()); + APP_LOGI("%{public}s end, jsPath: %{public}s, data: %{public}s", __func__, form.jsFormCodePath.c_str(), form.formData.c_str()); return form; } } // namespace AppExecFwk diff --git a/services/formmgr/src/form_timer_mgr.cpp b/services/formmgr/src/form_timer_mgr.cpp index 886cef74cc4f0a5dc65a47ca46c3e5052316a599..9d13f7c2e140a663947b27193fef855a98b1d4ea 100644 --- a/services/formmgr/src/form_timer_mgr.cpp +++ b/services/formmgr/src/form_timer_mgr.cpp @@ -14,7 +14,7 @@ */ #include -#include "ability_context.h" + #include "appexecfwk_errors.h" #include "app_log_wrapper.h" #include "common_event_manager.h" @@ -22,14 +22,12 @@ #include "form_constants.h" #include "form_provider_mgr.h" #include "form_refresh_limiter.h" -#include "form_timer_option.h" #include "form_timer_mgr.h" #include "form_util.h" #include "want.h" namespace OHOS { namespace AppExecFwk { - FormTimerMgr::FormTimerMgr() { Init(); @@ -48,7 +46,7 @@ bool FormTimerMgr::AddFormTimer(const FormTimer &task) APP_LOGI("%{public}s, formId: %{public}" PRId64 "", __func__, task.formId); if (task.isUpdateAt) { if (task.hour >= Constants::MIN_TIME && task.hour <= Constants::MAX_HOUR && task.min >= Constants::MIN_TIME && - task.min <= Constants::MAX_MININUTE) { + task.min <= Constants::MAX_MININUTE) { return AddUpdateAtTimer(task); } else { APP_LOGE("%{public}s failed, update at time is invalid", __func__); @@ -56,7 +54,7 @@ bool FormTimerMgr::AddFormTimer(const FormTimer &task) } } else { if (task.period >= Constants::MIN_PERIOD && task.period <= Constants::MAX_PERIOD && - (task.period % Constants::MIN_PERIOD) == 0) { + (task.period % Constants::MIN_PERIOD) == 0) { return AddIntervalTimer(task); } else { APP_LOGE("%{public}s failed, interval time is invalid", __func__); @@ -97,16 +95,10 @@ bool FormTimerMgr::RemoveFormTimer(const int64_t formId) APP_LOGI("%{public}s, task: %{public}" PRId64 "", __func__, formId); if (!DeleteIntervalTimer(formId)) { - if (!DeleteUpdateAtTimer(formId)) { - APP_LOGE("%{public}s, failed to DeleteUpdateAtTimer", __func__); - return false; - } + DeleteUpdateAtTimer(formId); } - if (!DeleteDynamicItem(formId)) { - APP_LOGE("%{public}s, failed to DeleteDynamicItem", __func__); - return false; - } + DeleteDynamicItem(formId); refreshLimiter_.DeleteItem(formId); return true; @@ -203,10 +195,7 @@ bool FormTimerMgr::UpdateAtTimerValue(const int64_t formId, const FormTimerCfg & AddUpdateAtItem(changedItem); } - if (!UpdateAtTimerAlarm()) { - APP_LOGE("%{public}s, failed to update attimer alarm.", __func__); - return false; - } + UpdateAtTimerAlarm(); return true; } /** @@ -270,10 +259,7 @@ bool FormTimerMgr::AtTimerToIntervalTimer(const int64_t formId, const FormTimerC } } - if (!UpdateAtTimerAlarm()) { - APP_LOGE("%{public}s, failed to update attimer alarm.", __func__); - return false; - } + UpdateAtTimerAlarm(); if (targetItem.refreshTask.formId == 0) { APP_LOGE("%{public}s failed, the update at timer is not exist", __func__); @@ -400,7 +386,7 @@ bool FormTimerMgr::AddUpdateAtTimer(const FormTimer &task) } if (!UpdateAtTimerAlarm()) { - APP_LOGE("%{public}s, failed to update attimer alarm.", __func__); + APP_LOGE("%{public}s, failed to update alarm.", __func__); return false; } @@ -423,10 +409,7 @@ bool FormTimerMgr::AddIntervalTimer(const FormTimer &task) } intervalTimerTasks_.emplace(task.formId, task); } - if(!UpdateLimiterAlarm()) { - APP_LOGE("%{public}s, failed to UpdateLimiterAlarm", __func__); - return false; - } + UpdateLimiterAlarm(); return refreshLimiter_.AddItem(task.formId); } /** @@ -462,23 +445,19 @@ void FormTimerMgr::AddUpdateAtItem(const UpdateAtItem &atItem) } /** * @brief Handle system time changed. - * @return Returns true on success, false on failure. */ -bool FormTimerMgr::HandleSystemTimeChanged() +void FormTimerMgr::HandleSystemTimeChanged() { APP_LOGI("%{public}s start", __func__); if (!updateAtTimerTasks_.empty()) { - return UpdateAtTimerAlarm(); + UpdateAtTimerAlarm(); } - APP_LOGI("%{public}s end", __func__); - return true; } /** * @brief Reset form limiter. - * @return Returns true on success, false on failure. */ -bool FormTimerMgr::HandleResetLimiter() +void FormTimerMgr::HandleResetLimiter() { APP_LOGI("%{public}s start", __func__); @@ -490,16 +469,13 @@ bool FormTimerMgr::HandleResetLimiter() ExecTimerTask(task); } } - APP_LOGI("%{public}s end", __func__); - return true; } /** * @brief Update attime trigger. * @param updateTime Update time. - * @return Returns true on success, false on failure. */ -bool FormTimerMgr::OnUpdateAtTrigger(long updateTime) +void FormTimerMgr::OnUpdateAtTrigger(long updateTime) { APP_LOGI("%{public}s start, updateTime:%{public}ld", __func__, updateTime); std::vector updateList; @@ -513,10 +489,7 @@ bool FormTimerMgr::OnUpdateAtTrigger(long updateTime) } } - if (!UpdateAtTimerAlarm()) { - APP_LOGE("%{public}s, failed to update attimer alarm.", __func__); - return false; - } + UpdateAtTimerAlarm(); if (!updateList.empty()) { APP_LOGI("%{public}s, update at timer triggered, trigged time: %{public}ld", __func__, updateTime); @@ -524,16 +497,13 @@ bool FormTimerMgr::OnUpdateAtTrigger(long updateTime) ExecTimerTask(item.refreshTask); } } - APP_LOGI("%{public}s end", __func__); - return true; } /** * @brief Dynamic time trigger. * @param updateTime Update time. - * @return Returns true on success, false on failure. */ -bool FormTimerMgr::OnDynamicTimeTrigger(long updateTime) +void FormTimerMgr::OnDynamicTimeTrigger(long updateTime) { APP_LOGI("%{public}s start, updateTime:%{public}ld", __func__, updateTime); std::vector updateList; @@ -558,20 +528,14 @@ bool FormTimerMgr::OnDynamicTimeTrigger(long updateTime) std::sort(dynamicRefreshTasks_.begin(), dynamicRefreshTasks_.end(), CompareDynamicRefreshItem); } - if (!UpdateDynamicAlarm()) { - APP_LOGE("%{public}s, failed to update dynamic alarm.", __func__); - return false; - } - + UpdateDynamicAlarm(); if (!updateList.empty()) { APP_LOGI("%{public}s triggered, trigged time: %{public}ld", __func__, updateTime); for (auto &task : updateList) { ExecTimerTask(task); } } - APP_LOGI("%{public}s end", __func__); - return true; } /** * @brief Get remind tasks. @@ -587,18 +551,14 @@ bool FormTimerMgr::GetRemindTasks(std::vector &remindTasks) remindTasks.emplace_back(formTimer); } - if(!UpdateLimiterAlarm()) { - APP_LOGE("%{public}s, failed to UpdateLimiterAlarm", __func__); - return false; - } + UpdateLimiterAlarm(); if(remindTasks.size() > 0) { - APP_LOGI("%{public}s end", __func__); return true; } else { - APP_LOGI("%{public}s end, remindTasks is empty", __func__); return false; } + APP_LOGI("%{public}s end", __func__); } /** * @brief Set enableFlag for interval timer task. @@ -641,9 +601,8 @@ bool FormTimerMgr::DeleteIntervalTimer(const int64_t formId) /** * @brief Delete update at timer. * @param formId The Id of the form. - * @return Returns true on success, false on failure. */ -bool FormTimerMgr::DeleteUpdateAtTimer(const int64_t formId) +void FormTimerMgr::DeleteUpdateAtTimer(const int64_t formId) { APP_LOGI("%{public}s start", __func__); { @@ -657,18 +616,15 @@ bool FormTimerMgr::DeleteUpdateAtTimer(const int64_t formId) } } - if (!UpdateAtTimerAlarm()) { - APP_LOGE("%{public}s, failed to update attimer alarm.", __func__); - return false; - } - return true; + UpdateAtTimerAlarm(); + APP_LOGI("%{public}s end", __func__); } /** * @brief Delete dynamic refresh item. * @param formId The Id of the form. */ -bool FormTimerMgr::DeleteDynamicItem(const int64_t formId) +void FormTimerMgr::DeleteDynamicItem(const int64_t formId) { APP_LOGI("%{public}s start", __func__); std::lock_guard lock(dynamicMutex_); @@ -681,12 +637,8 @@ bool FormTimerMgr::DeleteDynamicItem(const int64_t formId) } } std::sort(dynamicRefreshTasks_.begin(), dynamicRefreshTasks_.end(), CompareDynamicRefreshItem); - - if (!UpdateDynamicAlarm()) { - APP_LOGE("%{public}s, failed to UpdateDynamicAlarm", __func__); - return false; - } - return true; + + UpdateDynamicAlarm(); APP_LOGI("%{public}s end", __func__); } /** @@ -715,7 +667,6 @@ void FormTimerMgr::OnIntervalTimeOut() } APP_LOGI("%{public}s end", __func__); } - /** * @brief Update at timer task alarm. * @return Returns true on success, false on failure. @@ -723,41 +674,92 @@ void FormTimerMgr::OnIntervalTimeOut() bool FormTimerMgr::UpdateAtTimerAlarm() { APP_LOGI("%{public}s start", __func__); + // AlarmManager* alarm = GetAlarmManagerLocked(); + // if (alarm == nullptr) { + // APP_LOGE("%{public}s failed, failed to get alarm manager, can not updateAlarm", __func__); + // return false; + // } + struct tm tmAtTime = {0}; + auto tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); + struct tm* ptm = localtime_r(&tt, &tmAtTime); + if (ptm == nullptr) { + APP_LOGE("%{public}s failed, localtime error", __func__); + return false; + } - APP_LOGI("%{public}s end", __func__); - return true; -} + int nowAtTime = tmAtTime.tm_hour * Constants::MIN_PER_HOUR + tmAtTime.tm_min; + long currentTime = FormUtil::GetCurrentMillisecond(); + UpdateAtItem findedItem; + bool bFinded = FindNextAtTimerItem(nowAtTime, findedItem); + if (!bFinded) { + ClearUpdateAtTimerResource(); + APP_LOGI("%{public}s, no update at task in system now.", __func__); + return true; + } + int nextWakeUpTime = findedItem.updateAtTime; + tmAtTime.tm_sec = 0; + tmAtTime.tm_hour = findedItem.refreshTask.hour; + tmAtTime.tm_min = findedItem.refreshTask.min; + long selectTime = FormUtil::GetMillisecondFromTm(tmAtTime); + if (selectTime < currentTime) { + tmAtTime.tm_mday += 1; + nextWakeUpTime += (Constants::HOUR_PER_DAY * Constants::MIN_PER_HOUR); + } -/** - * @brief Clear update at timer resource. - */ -void FormTimerMgr::ClearUpdateAtTimerResource() -{ - APP_LOGI("%{public}s start", __func__); + if (nextWakeUpTime == atTimerWakeUpTime_) { + APP_LOGW("%{public}s end, wakeUpTime not change, no need update alarm.", __func__); + return true; + } + + // PendingIntent pendingIntent = getPendingIntent(findedItem.updateAtTime); + // if (pendingIntent == null) { + // HiLog.error(LABEL_LOG, "create pendingIntent failed."); + // return false; + // } + atTimerWakeUpTime_ = nextWakeUpTime; + // if (currentPendingIntent != null) { + // alarm.cancel(currentPendingIntent); + // } + // currentPendingIntent = pendingIntent; + // alarm.setExact(AlarmManager.RTC_WAKEUP, FormUtil::GetMillisecondFromTm(tmAtTime), pendingIntent); APP_LOGI("%{public}s end", __func__); + return true; } - /** * @brief Update limiter task alarm. * @return Returns true on success, false on failure. */ bool FormTimerMgr::UpdateLimiterAlarm() -{ - APP_LOGI("%{public}s start", __func__); - - return true; -} -/** - * @brief Clear limiter timer resource. - */ -void FormTimerMgr::ClearLimiterTimerResource() { APP_LOGI("%{public}s start", __func__); + // AlarmManager alarm = getAlarmManagerLocked(); + // if (alarm == null) { + // HiLog.error(LABEL_LOG, "faied to get alarm manager, can not updateLimiterAlarm"); + // return false; + // } + + // PendingIntent pendingIntent = getLimiterPendingIntent(); + // if (pendingIntent == null) { + // HiLog.error(LABEL_LOG, "create limiterPendingIntent failed."); + // return false; + // } + + // if (limiterPendingIntent != null) { + // alarm.cancel(limiterPendingIntent); + // } + // limiterPendingIntent = pendingIntent; + + // Calendar calendar = Calendar.getInstance(); + // calendar.set(Calendar.DATE, Calendar.getInstance().get(Calendar.DATE)); + // calendar.set(Calendar.HOUR_OF_DAY, MAX_HOUR); + // calendar.set(Calendar.MINUTE, MAX_MININUTE); + // calendar.set(Calendar.SECOND, MAX_SECOND); + // calendar.set(Calendar.MILLISECOND, LIMIT_MS); + // alarm.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent); APP_LOGI("%{public}s end", __func__); + return true; } - - /** * @brief Update dynamic refresh task alarm. * @return Returns true on success, false on failure. @@ -765,18 +767,59 @@ void FormTimerMgr::ClearLimiterTimerResource() bool FormTimerMgr::UpdateDynamicAlarm() { APP_LOGI("%{public}s start", __func__); + if (dynamicRefreshTasks_.empty()) { + ClearDynamicResource(); + return true; + } + + bool needUpdate = false; + DynamicRefreshItem firstTask = dynamicRefreshTasks_.at(0); + if (dynamicWakeUpTime_ != firstTask.settedTime) { + dynamicWakeUpTime_ = firstTask.settedTime; + needUpdate = true; + } + + if (!needUpdate) { + APP_LOGE("%{public}s failed, no need to UpdateDynamicAlarm.", __func__); + return true; + } + // AlarmManager alarm = getAlarmManagerLocked(); + // if (alarm == null) { + // HiLog.error(LABEL_LOG, "faied to get alarm manager, can not UpdateDynamicAlarm."); + // return false; + // } + + // PendingIntent pendingIntent = getDynamicPendingIntent(dynamicWakeUpTime); + // if (pendingIntent == null) { + // HiLog.error(LABEL_LOG, "create dynamic pendingIntent failed.", __func__); + // return false; + // } + // if (dynamicPendingIntent != null) { + // alarm.cancel(dynamicPendingIntent); + // } + // dynamicPendingIntent = pendingIntent; + // alarm.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, dynamicWakeUpTime, pendingIntent); APP_LOGI("%{public}s end", __func__); return true; } - /** * @brief Clear dynamic refresh resource. */ void FormTimerMgr::ClearDynamicResource() { APP_LOGI("%{public}s start", __func__); + // AlarmManager alarm = getAlarmManagerLocked(); + // if (alarm == null) { + // return; + // } + + // if (dynamicPendingIntent != null) { + // alarm.cancel(dynamicPendingIntent); + // dynamicPendingIntent = null; + // } + dynamicWakeUpTime_ = LONG_MAX; APP_LOGI("%{public}s end", __func__); } /** @@ -808,17 +851,49 @@ bool FormTimerMgr::FindNextAtTimerItem(const int nowTime, UpdateAtItem &updateAt APP_LOGI("%{public}s end", __func__); return true; } +/** + * @brief Clear update at timer resource. + */ +void FormTimerMgr::ClearUpdateAtTimerResource() +{ + APP_LOGI("%{public}s start", __func__); + if (!updateAtTimerTasks_.empty()) { + APP_LOGW("%{public}s, updateAtTimerTasks_ is not empty", __func__); + return; + } + + // AlarmManager alarm = getAlarmManagerLocked(); + // if (alarm == null) { + // return; + // } + + // if (currentPendingIntent != null) { + // alarm.cancel(currentPendingIntent); + // currentPendingIntent = null; + // } + atTimerWakeUpTime_ = LONG_MAX; + APP_LOGI("%{public}s end", __func__); +} /** * @brief Ensure init interval timer resource. */ void FormTimerMgr::EnsureInitIntervalTimer() { - if (intervalTimerId_ != 0L) { + if (intervalTimer_ != NULL) { return; } APP_LOGI("%{public}s, init base timer task", __func__); + intervalTimer_ = new Utils::Timer("interval timer"); + uint32_t iResult = intervalTimer_->Setup(); + if (iResult != ERR_OK) { + APP_LOGE("%{public}s failed, init base timer task error", __func__); + return; + } + auto timeCallback = std::bind(&FormTimerMgr::OnIntervalTimeOut, this); + intervalTimer_->Register(timeCallback, Constants::MIN_PERIOD); + APP_LOGI("%{public}s end", __func__); } /** @@ -827,6 +902,13 @@ void FormTimerMgr::EnsureInitIntervalTimer() void FormTimerMgr::ClearIntervalTimer() { APP_LOGI("%{public}s start", __func__); + if (intervalTimer_ != nullptr) { + APP_LOGI("%{public}s clear interval timer start", __func__); + intervalTimer_->Shutdown(); + delete intervalTimer_; + intervalTimer_ = nullptr; + APP_LOGI("%{public}s clear interval timer end", __func__); + } APP_LOGI("%{public}s end", __func__); } /** @@ -881,10 +963,7 @@ void FormTimerMgr::Init() timerReceiver_ = std::make_shared(subscribeInfo); EventFwk::CommonEventManager::SubscribeCommonEvent(timerReceiver_); - intervalTimerId_ = 0L; - updateAtTimerId_ = 0L; - dynamicAlarmTimerId_ = 0L; - limiterTimerId_ = 0L; + intervalTimer_ = nullptr; taskExecutor_ = nullptr; APP_LOGI("%{public}s end", __func__); diff --git a/services/formmgr/src/form_util.cpp b/services/formmgr/src/form_util.cpp index d033818a1bf2addffede4129143fa14cfb905b98..a4d3d30f76fa9811c8bc6d0c189e7d5bec4806bf 100644 --- a/services/formmgr/src/form_util.cpp +++ b/services/formmgr/src/form_util.cpp @@ -1,191 +1,203 @@ -/* - * 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 -#include -#include - -#include "app_log_wrapper.h" -#include "form_constants.h" -#include "form_util.h" -#include "ohos_account_kits.h" - -namespace OHOS { -namespace AppExecFwk { -using namespace std; -using namespace std::chrono; - -constexpr int64_t SEC_TO_NANOSEC = 1000000000; -constexpr int64_t SEC_TO_MILLISEC = 1000; -constexpr int64_t MILLISEC_TO_NANOSEC = 1000000; -constexpr int64_t INVALID_UDID_HASH = 0; -/** - * @brief create want for form. - * @param formName The name of the form. - * @param specificationId specification id. - * @param isTemporaryForm temporary form or not. - * @param want The want of the form. - */ -void FormUtil::CreateFormWant(const std::string &formName, - const int32_t specificationId, const bool isTemporaryForm, Want &want) -{ - want.SetParam(Constants::PARAM_FORM_NAME_KEY, formName); - want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, specificationId); - want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, isTemporaryForm); -} - -/** - * @brief create default want for form. - * @param want The want of the form.. - * @param uri The uri. - * @param connectId connect id. - */ -void FormUtil::CreateDefaultFormWant(Want &want, const std::string &uri, const int32_t connectId) -{ - want.SetParam(Constants::FORM_CONNECT_ID, connectId); - want.SetParam(Constants::FORM_SUPPLY_INFO, uri); -} - -/** - * @brief create udid for form. - * @return udid. - */ -std::string FormUtil::GenerateUdid() -{ - char buf[256] = {0}; - return buf; -} - -/** - * @brief create form id for form. - * @param udidHash udid hash - * @return new form id. - */ -int64_t FormUtil::GenerateFormId(int64_t udidHash) -{ - struct timespec t; - t.tv_sec = 0; - t.tv_nsec = 0; - clock_gettime(CLOCK_REALTIME, &t); - - int64_t elapsedTime { ((t.tv_sec) * SEC_TO_NANOSEC + t.tv_nsec) }; - size_t elapsedHash = std::hash()(std::to_string(elapsedTime)); - APP_LOGI("%{public}s, GenerateFormId generate elapsed hash %{public}zu", __func__, elapsedHash); - uint64_t unsignedudidHash = static_cast(udidHash); - uint64_t formId = unsignedudidHash | (int32_t)(elapsedHash & 0x000000007fffffffL); - APP_LOGI("%{public}s, GenerateFormId generate formId %{public}" PRId64 "", __func__, formId); - return formId; -} - -/** - * @brief padding form id. - * @param formId The id of the form. - * @param udidHash udid hash - * @return new form id. - */ -int64_t FormUtil::PaddingUDIDHash(uint64_t formId, uint64_t udidHash) -{ - // Compatible with int form id. - if ((formId & 0xffffffff00000000L) == 0) { - return udidHash | formId; - } - - return formId; -} -/** - * @brief create udid hash. - * @param udidHash udid hash. - * @return Returns true on success, false on failure. - */ -bool FormUtil::GenerateUdidHash(int64_t &udidHash) -{ - APP_LOGI("%{public}s start, udidHash: %{public}" PRId64 "", __func__, udidHash); - if (udidHash != INVALID_UDID_HASH) { - return true; - } - - u_int64_t hashId = 0L; - const int32_t thirtyTwo = 32; - udidHash = (hashId & 0x0000000000ffffffL) << thirtyTwo; - if (udidHash < 0) { - udidHash = 0L; - } - APP_LOGI("%{public}s, FormAdapter generate hash %{public}" PRId64 "", __func__, udidHash); - - return true; -} -/** - * @brief Get current system nanosecond. - * @return Current system nanosecond. - */ -long FormUtil::GetCurrentNanosecond() -{ - struct timespec ts; - ts.tv_sec = 0; - ts.tv_nsec = 0; - clock_gettime(CLOCK_REALTIME, &ts); - return (ts.tv_sec * SEC_TO_NANOSEC + ts.tv_nsec); -} -/** - * @brief Get current system millisecond. - * @return Current system millisecond. - */ -long FormUtil::GetCurrentMillisecond() -{ - struct timespec ts; - clock_gettime(CLOCK_REALTIME, &ts); - return (ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC); -} -/** - * @brief Get millisecond from tm. - * @param tmAtTime tm time. - * @return Millisecond. - */ -long FormUtil::GetMillisecondFromTm(struct tm &tmAtTime) -{ - time_t inputTime = mktime(&tmAtTime); - if (inputTime == -1) { - APP_LOGE("%{public}s fail, mktime failed.", __func__); - return -1; - } - system_clock::time_point pointTime = system_clock::from_time_t(inputTime); - auto timeMilliseconds = chrono::duration_cast(pointTime.time_since_epoch()); - return timeMilliseconds.count(); -} - -/** -* @brief split string. - * @param in string. - * @param delim delimiter. - * @return string list. - */ -std::vector FormUtil::StringSplit(const std::string &in, const std::string &delim) -{ - std::vector vEmpty; - try { - std::regex reg { delim }; - return std::vector { - std::sregex_token_iterator(in.begin(), in.end(), reg, -1), - std::sregex_token_iterator() - }; - } catch (const std::exception& e) { - APP_LOGE("%{public}s, failed to split string.", __func__); - } - return vEmpty; -} -} // namespace AppExecFwk +/* + * 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 +// #include +#include +#include +// #include + +#include "app_log_wrapper.h" +#include "form_constants.h" +#include "form_util.h" +#include "ohos_account_kits.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace std; +using namespace std::chrono; + +constexpr int64_t SEC_TO_NANOSEC = 1000000000; +constexpr int64_t SEC_TO_MILLISEC = 1000; +constexpr int64_t MILLISEC_TO_NANOSEC = 1000000; +constexpr int64_t INVALID_UDID_HASH = 0; +/** + * @brief create want for form. + * @param formName The name of the form. + * @param specificationId specification id. + * @param isTemporaryForm temporary form or not. + * @param want The want of the form. + */ +void FormUtil::CreateFormWant(const std::string &formName, const int32_t specificationId, const bool isTemporaryForm, +Want &want) +{ + want.SetParam(Constants::PARAM_FORM_NAME_KEY, formName); + want.SetParam(Constants::PARAM_FORM_DIMENSION_KEY, specificationId); + want.SetParam(Constants::PARAM_FORM_TEMPORARY_KEY, isTemporaryForm); +} + +/** + * @brief create default want for form. + * @param want The want of the form.. + * @param uri The uri. + * @param connectId connect id. + */ +void FormUtil::CreateDefaultFormWant(Want &want, const std::string &uri, const int32_t connectId) +{ + want.SetParam(Constants::FORM_CONNECT_ID, connectId); + want.SetParam(Constants::FORM_SUPPLY_INFO, uri); +} + +/** + * @brief create udid for form. + * @return udid. + */ +std::string FormUtil::GenerateUdid() +{ + // uuid_t uuid; + char buf[256] = {0}; + // uuid_generate(uuid); + + // uuid_unparse(uuid, buf); + return buf; +} + +/** + * @brief create form id for form. + * @param udidHash udid hash + * @return new form id. + */ +int64_t FormUtil::GenerateFormId(int64_t udidHash) +{ + struct timespec t; + t.tv_sec = 0; + t.tv_nsec = 0; + clock_gettime(CLOCK_REALTIME, &t); + + int64_t elapsedTime { ((t.tv_sec) * SEC_TO_NANOSEC + t.tv_nsec) }; + size_t elapsedHash = std::hash()(std::to_string(elapsedTime)); + APP_LOGI("%{public}s, GenerateFormId generate elapsed hash %{public}zu", __func__, elapsedHash); + int64_t formId = udidHash | (int32_t)(elapsedHash & 0x000000007fffffffL); + APP_LOGI("%{public}s, GenerateFormId generate formId %{public}" PRId64 "", __func__, formId); + return formId; +} + +/** + * @brief padding form id. + * @param formId The id of the form. + * @param udidHash udid hash + * @return new form id. + */ +int64_t FormUtil::PaddingUDIDHash(int64_t formId, int64_t udidHash) +{ + // Compatible with int form id. + if ((formId & 0xffffffff00000000L) == 0) { + return udidHash | formId; + } + + return formId; +} +/** + * @brief create udid hash. + * @param udidHash udid hash. + * @return Returns true on success, false on failure. + */ +bool FormUtil::GenerateUdidHash(int64_t &udidHash) +{ + APP_LOGI("%{public}s start, udidHash: %{public}" PRId64 "", __func__, udidHash); + if (udidHash != INVALID_UDID_HASH) { + return true; + } + + // std::string deviceId = GenerateUdid(); + // if (deviceId.empty()) { + // APP_LOGE("%{public}s fail, get udid failed.", __func__); + // return false; + // } + + // u_int64_t hashId = std::hash()(deviceId); + u_int64_t hashId = 0L; + const int32_t thirtyTwo = 32; + udidHash = (hashId & 0x0000000000ffffffL) << thirtyTwo; + if(udidHash < 0) { + udidHash = 0L; + } + APP_LOGI("%{public}s, FormAdapter generate hash %{public}" PRId64 "", __func__, udidHash); + + return true; +} +/** + * @brief Get current system nanosecond. + * @return Current system nanosecond. + */ +long FormUtil::GetCurrentNanosecond() +{ + struct timespec ts; + ts.tv_sec = 0; + ts.tv_nsec = 0; + clock_gettime(CLOCK_REALTIME, &ts); + return (ts.tv_sec * SEC_TO_NANOSEC + ts.tv_nsec); +} +/** + * @brief Get current system millisecond. + * @return Current system millisecond. + */ +long FormUtil::GetCurrentMillisecond() +{ + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + return (ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC); +} +/** + * @brief Get millisecond from tm. + * @param tmAtTime tm time. + * @return Millisecond. + */ +long FormUtil::GetMillisecondFromTm(struct tm &tmAtTime) +{ + time_t inputTime = mktime(&tmAtTime); + if (inputTime == -1) { + APP_LOGE("%{public}s fail, mktime failed.", __func__); + return -1; + } + system_clock::time_point pointTime = system_clock::from_time_t(inputTime); + auto timeMilliseconds = chrono::duration_cast(pointTime.time_since_epoch()); + return timeMilliseconds.count(); +} + +/** +* @brief split string. + * @param in string. + * @param delim delimiter. + * @return string list. + */ +std::vector FormUtil::StringSplit(const std::string &in, const std::string &delim) +{ + std::vector vEmpty; + try { + std::regex reg { delim }; + return std::vector { + std::sregex_token_iterator(in.begin(), in.end(), reg, -1), + std::sregex_token_iterator() + }; + } catch (const std::exception& e) { + APP_LOGE("%{public}s, failed to split string.", __func__); + } + return vEmpty; +} +} // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/services/formmgr/test/BUILD.gn b/services/formmgr/test/BUILD.gn index 5ab060b4507e3cd058f90ba026214edd74486efa..ffbcd46101e85956762e903ab73d4e2aaaa1602c 100644 --- a/services/formmgr/test/BUILD.gn +++ b/services/formmgr/test/BUILD.gn @@ -48,7 +48,6 @@ group("unittest") { "unittest/fms_form_host_record_test:unittest", "unittest/fms_form_mgr_add_form_test:unittest", "unittest/fms_form_mgr_cast_temp_form_test:unittest", - "unittest/fms_form_mgr_death_callback_test:unittest", "unittest/fms_form_mgr_delete_form_test:unittest", "unittest/fms_form_mgr_lifecycle_update_test:unittest", "unittest/fms_form_mgr_message_event_test:unittest", diff --git a/services/formmgr/test/mock/include/mock_form_death_callback.h b/services/formmgr/test/mock/include/mock_form_death_callback.h index 55bc225a85dfd9c4938b22da6797fb077fcb84cd..2563698580783f0e12d037f88958f0e071577f2e 100644 --- a/services/formmgr/test/mock/include/mock_form_death_callback.h +++ b/services/formmgr/test/mock/include/mock_form_death_callback.h @@ -26,7 +26,7 @@ #include "app_log_wrapper.h" #include "event_handler.h" #include "form_constants.h" -#include "form_callback_interface.h" +#include "form_death_callback.h" #include "form_mgr_stub.h" #include "form_js_info.h" #include "form_provider_data.h" @@ -39,7 +39,7 @@ namespace AppExecFwk { * @class MockFormDeathCallback. * The MockFormDeathCallback for form mgr test. */ -class MockFormDeathCallback : public FormCallbackInterface { +class MockFormDeathCallback : public FormDeathCallback { public: MockFormDeathCallback() = default; virtual ~MockFormDeathCallback() = default; @@ -49,22 +49,7 @@ public: APP_LOGI("%{public}s called.", __func__); } - /** - * @brief Update form. - * - * @param formJsInfo Indicates the obtained {@code FormJsInfo} instance. - */ - void ProcessFormUpdate(const FormJsInfo &formJsInfo) - { - APP_LOGI("%{public}s called.", __func__); - } - - /** - * @brief Uninstall form. - * - * @param formId Indicates the ID of the form to uninstall. - */ - void ProcessFormUninstall(const int64_t formId) + void OnReconnectFailed() { APP_LOGI("%{public}s called.", __func__); } diff --git a/services/formmgr/test/mock/src/mock_bundle_manager.cpp b/services/formmgr/test/mock/src/mock_bundle_manager.cpp index 4555049f67ee15708c5c05b90ca54422afe80d5b..4905e226128237654beeb5e4eac41b12840d4420 100644 --- a/services/formmgr/test/mock/src/mock_bundle_manager.cpp +++ b/services/formmgr/test/mock/src/mock_bundle_manager.cpp @@ -53,7 +53,7 @@ bool BundleMgrProxy::GetFormsInfoByApp(const std::string &bundleName, std::vecto return true; } bool BundleMgrProxy::GetFormsInfoByModule(const std::string &bundleName, const std::string &moduleName, - std::vector &formInfo) +std::vector &formInfo) { return true; } @@ -135,7 +135,7 @@ bool BundleMgrService::GetFormsInfoByApp(const std::string &bundleName, std::vec return true; } bool BundleMgrService::GetFormsInfoByModule(const std::string &bundleName, const std::string &moduleName, - std::vector &formInfo) +std::vector &formInfo) { FormInfo form; form.bundleName = bundleName; diff --git a/services/formmgr/test/mock/src/mock_form_host_client.cpp b/services/formmgr/test/mock/src/mock_form_host_client.cpp index 92dd97e82e58d6eded8fee20138b2210fde30b46..ad90b9ad4c6e7a0874c391b33f68012696ce8153 100644 --- a/services/formmgr/test/mock/src/mock_form_host_client.cpp +++ b/services/formmgr/test/mock/src/mock_form_host_client.cpp @@ -1,64 +1,76 @@ -/* - * 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 "appexecfwk_errors.h" -#include "app_log_wrapper.h" -#include "errors.h" -#include "mock_form_host_client.h" -#include "string_ex.h" - -namespace OHOS { -namespace AppExecFwk { - -/** - * Request to give back a Form. - * - * @param formInfo, Form info. - * @return none. - */ -void MockFormHostClient::OnAcquired(const FormJsInfo &formInfo) -{ - APP_LOGD("MockFormHostClient OnAcquired"); - - int64_t formId = formInfo.formId; - ASSERT_FALSE(formId == 0); - PostVoid(); -} - -/** -* Form is updated. -* -* @param bundleName, Provider ability bundleName. -* @return none. -*/ -void MockFormHostClient::OnUpdate(const FormJsInfo &formInfo) -{ - APP_LOGD("MockFormHostClient OnUpdate"); - PostVoid(); -} - -/** - * Form provider is uninstalled - * - * @param formIds, The Id list of the forms. - * @return none. - */ -void MockFormHostClient::OnUninstall(const std::vector &formIds) -{ - APP_LOGD("MockFormHostClient OnUnInstall"); - PostVoid(); -} -} // namespace AppExecFwk -} // namespace OHOS +/* + * 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 "appexecfwk_errors.h" +#include "app_log_wrapper.h" +#include "errors.h" +#include "mock_form_host_client.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +// void MockFormHostClient::AddForm(const Ability& slice, int64_t formId){ + +// } + +// void MockFormHostClient::RemoveForm(const Ability& slice, int64_t formId{ + +// } + +// bool MockFormHostClient::ContainsForm(int64_t formId){ +// return false; +// } + +/** + * Request to give back a Form. + * + * @param formInfo, Form info. + * @return none. + */ +void MockFormHostClient::OnAcquired(const FormJsInfo &formInfo) +{ + APP_LOGD("MockFormHostClient OnAcquired"); + + int64_t formId = formInfo.formId; + ASSERT_FALSE(formId == 0); + PostVoid(); +} + +/** +* Form is updated. +* +* @param bundleName, Provider ability bundleName. +* @return none. +*/ +void MockFormHostClient::OnUpdate(const FormJsInfo &formInfo) +{ + APP_LOGD("MockFormHostClient OnUpdate"); + PostVoid(); +} + + +/** + * Form provider is uninstalled + * + * @param formIds, The Id list of the forms. + * @return none. + */ +void MockFormHostClient::OnUninstall(const std::vector &formIds) +{ + APP_LOGD("MockFormHostClient OnUnInstall"); + PostVoid(); +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/test/mock/src/mock_form_provider_client.cpp b/services/formmgr/test/mock/src/mock_form_provider_client.cpp index ff1e3a499a2e7743c5cb8d634840378d32da3558..2b94d46ec1df787e6f0f045ac58248443d70c401 100644 --- a/services/formmgr/test/mock/src/mock_form_provider_client.cpp +++ b/services/formmgr/test/mock/src/mock_form_provider_client.cpp @@ -1,134 +1,142 @@ -/* - * 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 "app_log_wrapper.h" -#include "errors.h" -#include "form_constants.h" -#include "form_supply_interface.h" -#include "mock_form_provider_client.h" -#include "string_ex.h" - -namespace OHOS { -namespace AppExecFwk { -/** - * Acquire to give back an ProviderFormInfo. This is sync API. - * - * @param want, The want of the form to create. - * @param callerToken, Caller ability token. - * @return none. - */ -int MockFormProviderClient::AcquireProviderFormInfo(const int64_t formId, const Want &want, - const sptr &callerToken) -{ - // avoid the user modify the number in onCreate - - APP_LOGD("Acquire provider form info"); - - sptr formSupply = iface_cast(callerToken); - if (formSupply == nullptr) { - APP_LOGE("failed to get formSupplyProxy"); - } - - FormProviderInfo formProviderInfo; - formSupply->OnAcquire(formProviderInfo, want); - return ERR_OK; -} - -/** - * Notify provider when the form was deleted. - * - * @param formId, The Id of the form. - * @param callerToken, Caller ability token. - * @return none. - */ -int MockFormProviderClient::NotifyFormDelete(const int64_t formId, const Want &want, - const sptr &callerToken) -{ - APP_LOGD("Notify form delete"); - return ERR_OK; -} -/** - * Notify provider when the forms was deleted. - * - * @param formIds, The id list of forms. - * @param want Indicates the structure containing form info. - * @param callerToken, Caller ability token. - * @return none. - */ -int MockFormProviderClient::NotifyFormsDelete(const std::vector &formIds, const Want &want, - const sptr &callerToken) -{ - APP_LOGD("Notify forms delete"); - return ERR_OK; -} - -/** - * @brief Notify provider when the form need update. - * @param formId The Id of the form. - * @param want Indicates the structure containing form info. - * @param callerToken Caller ability token. - */ -int MockFormProviderClient::NotifyFormUpdate(const int64_t formId, const Want &want, - const sptr &callerToken) -{ - APP_LOGD("Notify form update"); - return ERR_OK; -} - -/** - * @brief Event notify when change the form visible. - * - * @param formEvents The vector of form ids. - * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. - * @param want Indicates the structure containing form info. - * @param callerToken Caller ability token. - * @return Returns ERR_OK on success, others on failure. - */ -int MockFormProviderClient::EventNotify(const std::vector &formIds, const int32_t formVisibleType, - const Want &want, const sptr &callerToken) -{ - APP_LOGD("Event notify"); - return ERR_OK; -} - -/** - * Notify provider when the temp form was cast to normal form. - * - * @param formId, The Id of the form to update. - * @param callerToken, Caller ability token. - * @return none. - */ -int MockFormProviderClient::NotifyFormCastTempForm(const int64_t formId, const Want &want, - const sptr &callerToken) -{ - APP_LOGD("Notify cast temp form"); - return ERR_OK; -} -/** - * @brief Fire message event to form provider. - * @param formId The Id of the from. - * @param message Event message. - * @param want The want of the request. - * @param callerToken Form provider proxy object. - * @return Returns ERR_OK on success, others on failure. - */ -int MockFormProviderClient::FireFormEvent(const int64_t formId, const std::string &message, const Want &want, - const sptr &callerToken) -{ - APP_LOGD("Fire form event"); - return ERR_OK; -} -} // namespace AppExecFwk -} // namespace OHOS +/* + * 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 "app_log_wrapper.h" +#include "errors.h" +#include "form_constants.h" +#include "form_supply_interface.h" +#include "mock_form_provider_client.h" +#include "string_ex.h" + +namespace OHOS { +namespace AppExecFwk { +/** + * Acquire to give back an ProviderFormInfo. This is sync API. + * + * @param want, The want of the form to create. + * @param callerToken, Caller ability token. + * @return none. + */ +int MockFormProviderClient::AcquireProviderFormInfo(const int64_t formId, const Want &want, +const sptr &callerToken) +{ + // avoid the user modify the number in onCreate + + APP_LOGD("Acquire provider form info"); + + sptr formSupply = iface_cast(callerToken); + if (formSupply == nullptr) { + APP_LOGE("failed to get formSupplyProxy"); + } + // Want newWant; + // newWant.SetElement(want.GetElement()); + // long formId = want.GetLongParam(Constants::PARAM_FORM_IDENTITY_KEY, 0); + // APP_LOGD("AcquireProviderFormInfo, formId:%{public}ld", formId); + + // newWant.SetParam(Constants::PARAM_FORM_IDENTITY_KEY, formId); + + // int type = want.GetIntParam(Constants::ACQUIRE_TYPE, 0); + // newWant.SetParam(Constants::ACQUIRE_TYPE, type); + FormProviderInfo formProviderInfo; + formSupply->OnAcquire(formProviderInfo, want); + return ERR_OK; +} + +/** + * Notify provider when the form was deleted. + * + * @param formId, The Id of the form. + * @param callerToken, Caller ability token. + * @return none. + */ +int MockFormProviderClient::NotifyFormDelete(const int64_t formId, const Want &want, +const sptr &callerToken) +{ + APP_LOGD("Notify form delete"); + return ERR_OK; +} +/** + * Notify provider when the forms was deleted. + * + * @param formIds, The id list of forms. + * @param want Indicates the structure containing form info. + * @param callerToken, Caller ability token. + * @return none. + */ +int MockFormProviderClient::NotifyFormsDelete(const std::vector &formIds, const Want &want, +const sptr &callerToken) +{ + APP_LOGD("Notify forms delete"); + return ERR_OK; +} + +/** + * @brief Notify provider when the form need update. + * @param formId The Id of the form. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + */ +int MockFormProviderClient::NotifyFormUpdate(const int64_t formId, const Want &want, +const sptr &callerToken) +{ + APP_LOGD("Notify form update"); + return ERR_OK; +} + +/** + * @brief Event notify when change the form visible. + * + * @param formEvents The vector of form ids. + * @param formVisibleType The form visible type, including FORM_VISIBLE and FORM_INVISIBLE. + * @param want Indicates the structure containing form info. + * @param callerToken Caller ability token. + * @return Returns ERR_OK on success, others on failure. + */ +int MockFormProviderClient::EventNotify(const std::vector &formIds, const int32_t formVisibleType, + const Want &want, const sptr &callerToken) +{ + APP_LOGD("Event notify"); + return ERR_OK; +} + +/** + * Notify provider when the temp form was cast to normal form. + * + * @param formId, The Id of the form to update. + * @param callerToken, Caller ability token. + * @return none. + */ +int MockFormProviderClient::NotifyFormCastTempForm(const int64_t formId, const Want &want, +const sptr &callerToken) +{ + APP_LOGD("Notify cast temp form"); + return ERR_OK; +} +/** + * @brief Fire message event to form provider. + * @param formId The Id of the from. + * @param message Event message. + * @param want The want of the request. + * @param callerToken Form provider proxy object. + * @return Returns ERR_OK on success, others on failure. + */ +int MockFormProviderClient::FireFormEvent(const int64_t formId, const std::string &message, const Want &want, +const sptr &callerToken) +{ + APP_LOGD("Fire form event"); + return ERR_OK; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/formmgr/test/unittest/fms_form_cache_mgr_test/fms_form_cache_mgr_test.cpp b/services/formmgr/test/unittest/fms_form_cache_mgr_test/fms_form_cache_mgr_test.cpp index 4416792dee3eabc4ed712d2155b47b72d8b97569..5942712a56984e81f3c5b0475871d376fc20dd26 100644 --- a/services/formmgr/test/unittest/fms_form_cache_mgr_test/fms_form_cache_mgr_test.cpp +++ b/services/formmgr/test/unittest/fms_form_cache_mgr_test/fms_form_cache_mgr_test.cpp @@ -124,7 +124,7 @@ HWTEST_F(FmsFormCacheMgrTest, FmsFormCacheMgrTest_004, TestSize.Level0) std::string dataResult2 = "{'a':'2','b':'2'}"; formCacheMgr_.AddData(PARAM_FORM_ID_FIRST, dataResult1); EXPECT_TRUE(formCacheMgr_.AddData(PARAM_FORM_ID_SECOND, dataResult2)); - EXPECT_EQ(formCacheMgr_.cacheData_[PARAM_FORM_ID_SECOND], dataResult2); + EXPECT_EQ(formCacheMgr_.cacheData_[PARAM_FORM_ID_SECOND],dataResult2); GTEST_LOG_(INFO) << "fms_form_cache_mgr_test_004 end"; } diff --git a/services/formmgr/test/unittest/fms_form_data_mgr_test/fms_form_data_mgr_test.cpp b/services/formmgr/test/unittest/fms_form_data_mgr_test/fms_form_data_mgr_test.cpp index c76f6e4c3c476e3b867bd41cd7df05a3867050e5..9864114ed6bcc22e2b3b9fa7995c60b52d61ff4f 100644 --- a/services/formmgr/test/unittest/fms_form_data_mgr_test/fms_form_data_mgr_test.cpp +++ b/services/formmgr/test/unittest/fms_form_data_mgr_test/fms_form_data_mgr_test.cpp @@ -95,7 +95,7 @@ HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormRecord_001, TestSize.Le FormItemInfo form_item_info; InitFormItemInfo(formId, form_item_info); - FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid); + FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid ); EXPECT_EQ(formId, recordResult.formId); GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_001 end"; @@ -123,7 +123,7 @@ HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormRecord_002, TestSize.Le FormRecord record = formDataMgr_.CreateFormRecord(form_item_info, callingUid); formDataMgr_.formRecords_.emplace(formId, record); - FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid); + FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid ); EXPECT_EQ(formId, recordResult.formId); GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_002 end"; @@ -156,7 +156,7 @@ HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormRecord_003, TestSize.Le FormRecord record = formDataMgr_.CreateFormRecord(otherFormItemInfo, callingUid); formDataMgr_.formRecords_.emplace(otherformId, record); - FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid); + FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid ); EXPECT_EQ(formId, recordResult.formId); GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_003 end"; @@ -182,7 +182,7 @@ HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormRecord_004, TestSize.Le InitFormItemInfo(formId, form_item_info); form_item_info.SetUpdateDuration(Constants::MAX_CONFIG_DURATION); - FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid); + FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid ); EXPECT_EQ(formId, recordResult.formId); GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_004 end"; @@ -208,7 +208,7 @@ HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormRecord_005, TestSize.Le InitFormItemInfo(formId, form_item_info); form_item_info.SetUpdateDuration(Constants::MAX_CONFIG_DURATION-2); - FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid); + FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid ); EXPECT_EQ(formId, recordResult.formId); GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_005 end"; @@ -235,7 +235,7 @@ HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormRecord_006, TestSize.Le form_item_info.SetUpdateDuration(0); form_item_info.scheduledUpdateTime_.clear(); - FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid); + FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid ); EXPECT_EQ(formId, recordResult.formId); GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_006 end"; @@ -262,7 +262,7 @@ HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormRecord_007, TestSize.Le form_item_info.SetUpdateDuration(0); form_item_info.SetScheduledUpdateTime("10:30:10"); - FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid); + FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid ); EXPECT_EQ(formId, recordResult.formId); GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_007 end"; @@ -291,7 +291,7 @@ HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormRecord_008, TestSize.Le form_item_info.SetScheduledUpdateTime("10:70"); form_item_info.hapSourceDirs_.clear(); - FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid); + FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid ); EXPECT_EQ(formId, recordResult.formId); GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_008 end"; @@ -317,7 +317,7 @@ HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormRecord_009, TestSize.Le InitFormItemInfo(formId, form_item_info); form_item_info.SetUpdateDuration(0); - FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid); + FormRecord recordResult = formDataMgr_.AllotFormRecord(form_item_info, callingUid ); EXPECT_EQ(formId, recordResult.formId); GTEST_LOG_(INFO) << "FmsFormDataMgrTest_AllotFormRecord_009 end"; @@ -368,7 +368,7 @@ HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_AllotFormHostRecord_002, TestSiz int64_t formId = 2; int callingUid = 0; - // create FormItemInfo + //create FormItemInfo FormItemInfo formItemInfo; InitFormItemInfo(formId, formItemInfo); @@ -462,7 +462,7 @@ HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_CheckTempEnoughForm_002, TestSiz for (int index = 0; index < Constants::MAX_TEMP_FORMS; index++) { formDataMgr_.tempForms_.emplace_back(index); } - EXPECT_EQ(ERR_APPEXECFWK_FORM_MAX_SYSTEM_TEMP_FORMS, formDataMgr_.CheckTempEnoughForm()); + EXPECT_EQ(ERR_MAX_SYSTEM_TEMP_FORMS, formDataMgr_.CheckTempEnoughForm()); GTEST_LOG_(INFO) << "FmsFormDataMgrTest_CheckTempEnoughForm_002 end"; } @@ -489,7 +489,7 @@ HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_CheckEnoughForm_001, TestSize.Le formDataMgr_.formRecords_.emplace(formId_index, record); } - EXPECT_EQ(ERR_APPEXECFWK_FORM_MAX_SYSTEM_FORMS, formDataMgr_.CheckEnoughForm(callingUid)); + EXPECT_EQ(ERR_MAX_SYSTEM_FORMS, formDataMgr_.CheckEnoughForm(callingUid)); GTEST_LOG_(INFO) << "FmsFormDataMgrTest_CheckEnoughForm_001 end"; } @@ -534,7 +534,7 @@ HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_CheckEnoughForm_003, TestSize.Le formDataMgr_.formRecords_.emplace(formId_index, record); } - EXPECT_EQ(ERR_APPEXECFWK_FORM_MAX_FORMS_PER_CLIENT, formDataMgr_.CheckEnoughForm(callingUid)); + EXPECT_EQ(ERR_MAX_RECORDS_PER_APP, formDataMgr_.CheckEnoughForm(callingUid)); GTEST_LOG_(INFO) << "FmsFormDataMgrTest_CheckEnoughForm_003 end"; } @@ -1349,12 +1349,6 @@ HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_GetUpdatedForm_001, TestSize.Lev GTEST_LOG_(INFO) << "FmsFormDataMgrTest_GetUpdatedForm_001 start"; FormRecord record; - record.bundleName = ""; - record.moduleName = ""; - record.abilityName = ""; - record.formName = ""; - record.specification = 0; - std::vector targetForms; FormInfo updatedForm; @@ -1774,7 +1768,7 @@ HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_SetVersionUpgrade_001, TestSize. /** * @tc.number: FmsFormDataMgrTest_SetVersionUpgrade_002 - * @tc.name: SetFormCacheInited + * @tc.name: SetFormCacheInitedTrue * @tc.desc: Verify that the return value is correct. * @tc.details: * formRecords_ is found. @@ -1862,7 +1856,7 @@ HWTEST_F(FmsFormDataMgrTest, FmsFormDataMgrTest_UpdateHostFormFlag_001, TestSize std::vector refreshForms; - EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, formDataMgr_.UpdateHostFormFlag(formIds, token_, flag, refreshForms)); + EXPECT_EQ(ERR_FORM_INVALID_PARAM, formDataMgr_.UpdateHostFormFlag(formIds, token_, flag, refreshForms)); GTEST_LOG_(INFO) << "FmsFormDataMgrTest_UpdateHostFormFlag_001 end"; } diff --git a/services/formmgr/test/unittest/fms_form_db_record_test/fms_form_db_record_test.cpp b/services/formmgr/test/unittest/fms_form_db_record_test/fms_form_db_record_test.cpp index b91066b8351acee81e1b170c42f15f2fff1368ca..944bfb5e83bd889aa6558b0d86698aa4690b2c36 100644 --- a/services/formmgr/test/unittest/fms_form_db_record_test/fms_form_db_record_test.cpp +++ b/services/formmgr/test/unittest/fms_form_db_record_test/fms_form_db_record_test.cpp @@ -189,7 +189,7 @@ HWTEST_F(FmsFormDbRecordTest, FmsFormDbRecordTest_010, TestSize.Level0) // Delet HWTEST_F(FmsFormDbRecordTest, FmsFormDbRecordTest_011, TestSize.Level0) // DeleteDbRecord not exist { GTEST_LOG_(INFO) << "FmsFormDbRecordTest_011 start"; - EXPECT_EQ(ERR_APPEXECFWK_FORM_COMMON_CODE, FormDbCache::GetInstance().DeleteFormInfo(2)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_JSON_DELETE_FAIL, FormDbCache::GetInstance().DeleteFormInfo(2)); GTEST_LOG_(INFO) << "FmsFormDbRecordTest_011 end"; } } 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 e062b3f41cd0b93b935d97aec6fcfb81ac5ac230..c9956ac308e4695956474ed43298c718fe58ccf0 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 @@ -104,8 +104,8 @@ void FmsFormHostRecordTest::SetUp() permDef.descriptionId = 1; permList.emplace_back(permDef); Permission::PermissionKit::AddDefPermissions(permList); - Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, - {PERMISSION_NAME_REQUIRE_FORM}, 0); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, + 0); Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); } 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 1d7f2c0a86549a5644f4784fc3b1071c7389994f..2213089b19d1b04143eb57ade603dfa6790ed8ee 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 @@ -110,8 +110,8 @@ void FmsFormMgrAddFormTest::SetUp() permDef.descriptionId = 1; permList.emplace_back(permDef); Permission::PermissionKit::AddDefPermissions(permList); - Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, - {PERMISSION_NAME_REQUIRE_FORM}, 0); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, + 0); Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); } @@ -417,7 +417,7 @@ HWTEST_F(FmsFormMgrAddFormTest, AddForm_006, TestSize.Level0) want.SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_CREATE_FORM); GTEST_LOG_(INFO) << "formId :"<Wait(); FormDataMgr::GetInstance().DeleteFormRecord(formId); @@ -470,7 +470,7 @@ HWTEST_F(FmsFormMgrAddFormTest, AddForm_007, TestSize.Level0) want.SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_CREATE_FORM); GTEST_LOG_(INFO) << "formId :"<Wait(); FormDataMgr::GetInstance().DeleteFormRecord(formId); @@ -530,7 +530,7 @@ HWTEST_F(FmsFormMgrAddFormTest, AddForm_008, TestSize.Level0) want.SetParam(Constants::ACQUIRE_TYPE, Constants::ACQUIRE_TYPE_CREATE_FORM); GTEST_LOG_(INFO) << "formId :"<Wait(); FormDataMgr::GetInstance().DeleteFormRecord(formId); 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 6bd87bac092088030d1c40491f806f8c1ad80931..7c848885f80db64ab3c353310a03556a30a56546 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 @@ -106,8 +106,8 @@ void FmsFormMgrCastTempFormTest::SetUp() permDef.descriptionId = 1; permList.emplace_back(permDef); Permission::PermissionKit::AddDefPermissions(permList); - Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, - {PERMISSION_NAME_REQUIRE_FORM}, 0); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, + 0); Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); } @@ -182,10 +182,10 @@ HWTEST_F(FmsFormMgrCastTempFormTest, CastTempForm_002, TestSize.Level0) { GTEST_LOG_(INFO) << "fms_form_mgr_cast_temp_form_test_002 start"; // form id <= 0 - ASSERT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().CastTempForm(0L, token_)); + ASSERT_EQ(ERR_FORM_INVALID_PARAM, FormMgr::GetInstance().CastTempForm(0L, token_)); // Caller ability token is nullptr int64_t formId {FormDataMgr::GetInstance().GenerateFormId()}; - ASSERT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().CastTempForm(formId, nullptr)); + ASSERT_EQ(ERR_FORM_INVALID_PARAM, FormMgr::GetInstance().CastTempForm(formId, nullptr)); GTEST_LOG_(INFO) << "fms_form_mgr_cast_temp_form_test_002 end"; } @@ -202,7 +202,7 @@ HWTEST_F(FmsFormMgrCastTempFormTest, CastTempForm_003, TestSize.Level0) GTEST_LOG_(INFO) << "fms_form_mgr_cast_temp_form_test_003 start"; int64_t formId {FormDataMgr::GetInstance().GenerateFormId()}; // form is not exist in cache - ASSERT_EQ(ERR_APPEXECFWK_FORM_NOT_EXIST_ID, FormMgr::GetInstance().CastTempForm(formId, token_)); + ASSERT_EQ(ERR_NOT_EXIST_ID, FormMgr::GetInstance().CastTempForm(formId, token_)); GTEST_LOG_(INFO) << "fms_form_mgr_cast_temp_form_test_003 end"; } @@ -231,7 +231,7 @@ HWTEST_F(FmsFormMgrCastTempFormTest, CastTempForm_004, TestSize.Level0) record1.SetTemporaryFlag(true); FormRecord retFormRec = FormDataMgr::GetInstance().AllotFormRecord(record1, callingUid); - ASSERT_EQ(ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF, FormMgr::GetInstance().CastTempForm(formId, token_)); + ASSERT_EQ(ERR_OPERATION_FORM_NOT_SELF, FormMgr::GetInstance().CastTempForm(formId, token_)); FormDataMgr::GetInstance().DeleteFormRecord(formId); FormDbCache::GetInstance().DeleteFormInfo(formId); diff --git a/services/formmgr/test/unittest/fms_form_mgr_death_callback_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_mgr_death_callback_test/BUILD.gn index 0ab6a7845a3eb295280c9feb5833ee71089d8752..35100ba0d244e7404d6d8cfe235cb58d3ff9f8a3 100644 --- a/services/formmgr/test/unittest/fms_form_mgr_death_callback_test/BUILD.gn +++ b/services/formmgr/test/unittest/fms_form_mgr_death_callback_test/BUILD.gn @@ -15,74 +15,3 @@ import("//build/test.gni") import("//foundation/appexecfwk/standard/appexecfwk.gni") module_output_path = "appexecfwk_standard/formmgrservice" - -ohos_unittest("FmsFormMgrDeathCallbackTest") { - module_out_path = module_output_path - - sources = [ - "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit/native/src/form_mgr.cpp", - "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_bundle_manager.cpp", - "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_form_host_client.cpp", - - # "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_form_death_callback.cpp", - "//foundation/appexecfwk/standard/services/formmgr/test/mock/src/mock_form_provider_client.cpp", - ] - sources += [ "fms_form_mgr_death_callback_test.cpp" ] - - include_dirs = [ - "//third_party/zlib/contrib/minizip", - "//third_party/zlib", - "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", - "//foundation/appexecfwk/standard/interfaces/innerkits/fmskit/native/include/", - "//foundation/appexecfwk/standard/common/log/include/", - "//foundation/appexecfwk/standard/services/formmgr/include", - "//foundation/appexecfwk/standard/services/bundlemgr/include", - "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/formmgr/", - "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include/", - "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", - ] - - configs = [ - "${services_path}/formmgr/test:formmgr_test_config", - "//foundation/aafwk/standard/services/abilitymgr:abilityms_config", - - # "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:bundlemgr_sdk_config", - "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:formmgr_sdk_config", - ] - cflags = [] - if (target_cpu == "arm") { - cflags += [ "-DBINDER_IPC_32BIT" ] - } - deps = [ - "${appexecfwk_path}/common:libappexecfwk_common", - "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", - "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", - "${appexecfwk_path}/interfaces/innerkits/fmskit:fmskit_native", - "${libs_path}/libeventhandler:libeventhandler_target", - "${services_path}/formmgr:fms_target", - "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", - "//base/startup/appspawn_standard:appspawn_socket_client", - "//foundation/aafwk/standard/interfaces/innerkits/base:base", - "//foundation/aafwk/standard/interfaces/innerkits/want:want", - - #"${services_path}/bundlemgr:bms_target", - "//foundation/aafwk/standard/services/abilitymgr:abilityms_target", - "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", - "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", - "//third_party/googletest:gmock_main", - "//utils/native/base:utils", - ] - - external_deps = [ - "hiviewdfx_hilog_native:libhilog", - "ipc:ipc_core", - ] -} - -group("unittest") { - testonly = true - - deps = [ ":FmsFormMgrDeathCallbackTest" ] -} 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 3b78d9aa083889c50627c54de0efea44b1b0205e..e18f830ad221d64bba3116b69eb3a62c66945d62 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 @@ -111,8 +111,8 @@ void FmsFormMgrDeathCallbackTest::SetUp() permDef.descriptionId = 1; permList.emplace_back(permDef); Permission::PermissionKit::AddDefPermissions(permList); - Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, - {PERMISSION_NAME_REQUIRE_FORM}, 0); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, + 0); Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); } @@ -144,7 +144,7 @@ HWTEST_F(FmsFormMgrDeathCallbackTest, OnRemoteDied_001, TestSize.Level0) EXPECT_EQ(ERR_OK, FormMgr::GetInstance().AddForm(0L, want, token_, formJsInfo)); token_->Wait(); - std::shared_ptr deathCallback = std::make_shared(); + std::shared_ptr deathCallback = std::make_shared(); FormMgr::GetInstance().RegisterDeathCallback(deathCallback); EXPECT_EQ(true, FormMgr::GetInstance().CheckIsDeathCallbackRegistered(deathCallback)); FormMgr::GetInstance().GetDeathRecipient()->OnRemoteDied(formyMgrServ_->AsObject()); @@ -191,7 +191,7 @@ HWTEST_F(FmsFormMgrDeathCallbackTest, OnRemoteDied_002, TestSize.Level0) EXPECT_EQ(ERR_OK, FormMgr::GetInstance().AddForm(0L, want, token_, formJsInfo)); token_->Wait(); - std::shared_ptr deathCallback = std::make_shared(); + std::shared_ptr deathCallback = std::make_shared(); FormMgr::GetInstance().RegisterDeathCallback(deathCallback); EXPECT_EQ(true, FormMgr::GetInstance().CheckIsDeathCallbackRegistered(deathCallback)); 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 fee5463c9d5c77a913e439bd774e3bfa5d144ff9..05bc3c5e86740b4ee912dabe79d48c6e566be4ba 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 @@ -104,8 +104,8 @@ void FmsFormMgrDeleteFormTest::SetUp() permDef.descriptionId = 1; permList.emplace_back(permDef); Permission::PermissionKit::AddDefPermissions(permList); - Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, - {PERMISSION_NAME_REQUIRE_FORM}, 0); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, + 0); Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); } @@ -232,9 +232,9 @@ HWTEST_F(FmsFormMgrDeleteFormTest, DeleteForm_003, TestSize.Level0) { GTEST_LOG_(INFO) << "fms_form_mgr_delete_form_test_003 start"; // case when formId<=0 - EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().DeleteForm(0, token_)); + EXPECT_EQ(ERR_FORM_INVALID_PARAM, FormMgr::GetInstance().DeleteForm(0, token_)); // case when token is nullptr - EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().DeleteForm(123L, nullptr)); + EXPECT_EQ(ERR_FORM_INVALID_PARAM, FormMgr::GetInstance().DeleteForm(123L, nullptr)); GTEST_LOG_(INFO) << "fms_form_mgr_delete_form_test_003 end"; } @@ -325,7 +325,7 @@ HWTEST_F(FmsFormMgrDeleteFormTest, DeleteForm_006, TestSize.Level0) FormItemInfo info; FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); - EXPECT_EQ(ERR_APPEXECFWK_FORM_NOT_EXIST_ID, FormMgr::GetInstance().DeleteForm(formId, token_)); + EXPECT_EQ(ERR_NOT_EXIST_ID, FormMgr::GetInstance().DeleteForm(formId, token_)); FormDataMgr::GetInstance().DeleteFormRecord(formId); FormDbCache::GetInstance().DeleteFormInfo(formId); @@ -362,7 +362,7 @@ HWTEST_F(FmsFormMgrDeleteFormTest, DeleteForm_007, TestSize.Level0) FormItemInfo info; FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); - ASSERT_EQ(ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF, FormMgr::GetInstance().DeleteForm(formId, token_)); + ASSERT_EQ(ERR_OPERATION_FORM_NOT_SELF, FormMgr::GetInstance().DeleteForm(formId, token_)); // Cache uid is not deleted yet. FormRecord formInfo; @@ -415,7 +415,7 @@ HWTEST_F(FmsFormMgrDeleteFormTest, DeleteForm_008, TestSize.Level0) FormItemInfo info; FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); - ASSERT_EQ(ERR_APPEXECFWK_FORM_COMMON_CODE, FormMgr::GetInstance().DeleteForm(formId, token_)); + ASSERT_EQ(ERR_CODE_COMMON, FormMgr::GetInstance().DeleteForm(formId, token_)); // Cache uid is not deleted yet. FormRecord formInfo; @@ -441,7 +441,7 @@ HWTEST_F(FmsFormMgrDeleteFormTest, DeleteForm_008, TestSize.Level0) FormDBInfo formDBInfo1(formId, retFormRec); FormDbCache::GetInstance().SaveFormInfo(formDBInfo1); - EXPECT_EQ(ERR_APPEXECFWK_FORM_COMMON_CODE, FormMgr::GetInstance().DeleteForm(formId, token_)); + EXPECT_EQ(ERR_CODE_COMMON, FormMgr::GetInstance().DeleteForm(formId, token_)); // Cache uid is not deleted yet. ret = FormDataMgr::GetInstance().GetFormRecord(formId, formInfo); 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 01e862d910d339eafe0170c70e175d2ccbe96dbd..86deffae18a98f1e43868560cafd5a2d08a85f1d 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 @@ -92,8 +92,8 @@ void FmsFormMgrLifecycleUpdateTest::SetUp() permDef.descriptionId = 1; permList.emplace_back(permDef); Permission::PermissionKit::AddDefPermissions(permList); - Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, - {PERMISSION_NAME_REQUIRE_FORM}, 0); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, + 0); Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); } @@ -151,7 +151,7 @@ HWTEST_F(FmsFormMgrLifecycleUpdateTest, FmsFormMgrLifecycleUpdateTest_LifecycleU std::vector formIds; int32_t updateType = OHOS::AppExecFwk::FormMgrService::ENABLE_FORM_UPDATE; - EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().LifecycleUpdate(formIds, token_, updateType)); + EXPECT_EQ(ERR_FORM_INVALID_PARAM, FormMgr::GetInstance().LifecycleUpdate(formIds, token_, updateType)); GTEST_LOG_(INFO) << "FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_002 end"; } @@ -171,7 +171,7 @@ HWTEST_F(FmsFormMgrLifecycleUpdateTest, FmsFormMgrLifecycleUpdateTest_LifecycleU int32_t updateType = OHOS::AppExecFwk::FormMgrService::ENABLE_FORM_UPDATE; - EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().LifecycleUpdate(formIds, token_, updateType)); + EXPECT_EQ(ERR_FORM_INVALID_PARAM, FormMgr::GetInstance().LifecycleUpdate(formIds, token_, updateType)); GTEST_LOG_(INFO) << "FmsFormMgrLifecycleUpdateTest_LifecycleUpdate_003 end"; } 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 27a72210b4dc61f1f0f7b8564e36121862bbf529..12d4e8395f8bd64594bc64db8d987c258e4531e6 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 @@ -106,8 +106,8 @@ void FmsFormMgrMessageEventTest::SetUp() permDef.descriptionId = 1; permList.emplace_back(permDef); Permission::PermissionKit::AddDefPermissions(permList); - Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, - {PERMISSION_NAME_REQUIRE_FORM}, 0); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, + 0); Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); } @@ -284,7 +284,7 @@ HWTEST_F(FmsFormMgrMessageEventTest, MessageEvent_006, TestSize.Level0) want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME); want.SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, FORM_PROVIDER_ABILITY_NAME); want.SetParam(Constants::PARAM_MESSAGE_KEY, FORM_MESSAGE_EVENT_VALUE_1); - EXPECT_EQ(ERR_APPEXECFWK_FORM_NOT_EXIST_ID, FormMgr::GetInstance().MessageEvent(formId, want, token_)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_INFO_NOT_EXIST, FormMgr::GetInstance().MessageEvent(formId, want, token_)); GTEST_LOG_(INFO) << "fms_form_mgr_message_event_test_006 end"; } /* @@ -306,7 +306,7 @@ HWTEST_F(FmsFormMgrMessageEventTest, MessageEvent_007, TestSize.Level0) want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME); want.SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, FORM_PROVIDER_ABILITY_NAME); want.SetParam(Constants::PARAM_MESSAGE_KEY, FORM_MESSAGE_EVENT_VALUE_1); - EXPECT_EQ(ERR_APPEXECFWK_FORM_COMMON_CODE, FormMgr::GetInstance().MessageEvent(formId, want, + EXPECT_EQ(ERR_APPEXECFWK_FORM_HOST_INFO_NOT_EXIST, FormMgr::GetInstance().MessageEvent(formId, want, new (std::nothrow) MockFormHostClient())); GTEST_LOG_(INFO) << "fms_form_mgr_message_event_test_007 end"; } @@ -350,7 +350,7 @@ HWTEST_F(FmsFormMgrMessageEventTest, MessageEvent_008, TestSize.Level0) want.SetParam(Constants::PARAM_FORM_NAME_KEY, PARAM_FORM_NAME); want.SetElementName(DEVICE_ID, FORM_PROVIDER_BUNDLE_NAME, FORM_PROVIDER_ABILITY_NAME); want.SetParam(Constants::PARAM_MESSAGE_KEY, FORM_MESSAGE_EVENT_VALUE_1); - EXPECT_EQ(ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF, FormMgr::GetInstance().MessageEvent(formId2, want, token_)); + EXPECT_EQ(ERR_OPERATION_FORM_NOT_SELF, FormMgr::GetInstance().MessageEvent(formId2, want, token_)); GTEST_LOG_(INFO) << "fms_form_mgr_message_event_test_008 end"; } } \ No newline at end of file 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 16f74195dccb53b829eda5afecf54e57bc88c687..d1d1d1d1dc3a954c39eaff20cf20e2da71659687 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 @@ -91,12 +91,10 @@ void FmsFormMgrNotifyInvisibleFormsTest::SetUp(void) permDef.descriptionId = 1; permList.emplace_back(permDef); OHOS::Security::Permission::PermissionKit::AddDefPermissions(permList); - std::vector permnameList; - permnameList.emplace_back(PERMISSION_NAME_REQUIRE_FORM); OHOS::Security::Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_HOST_BUNDLE_NAME, - permnameList, 0); + {PERMISSION_NAME_REQUIRE_FORM}, 0); OHOS::Security::Permission::PermissionKit::GrantUserGrantedPermission(FORM_HOST_BUNDLE_NAME, - PERMISSION_NAME_REQUIRE_FORM, 0); + PERMISSION_NAME_REQUIRE_FORM, 0); } void FmsFormMgrNotifyInvisibleFormsTest::TearDown(void) @@ -122,8 +120,8 @@ TestSize.Level0) OHOS::Security::Permission::PermissionKit::RemoveUserGrantedReqPermissions(FORM_HOST_BUNDLE_NAME, 0); OHOS::Security::Permission::PermissionKit::RemoveSystemGrantedReqPermissions(FORM_HOST_BUNDLE_NAME); - EXPECT_EQ(ERR_APPEXECFWK_FORM_PERMISSION_DENY, FormMgr::GetInstance().NotifyWhetherVisibleForms(formIds, - token_, Constants::FORM_INVISIBLE)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_PERMISSION_DENY, FormMgr::GetInstance().NotifyWhetherVisibleForms( formIds, + token_, Constants::FORM_INVISIBLE )); GTEST_LOG_(INFO) << "FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_001 end"; } @@ -147,14 +145,13 @@ TestSize.Level0) iteminfo.formId_ = formId; iteminfo.providerBundleName_ = FORM_HOST_BUNDLE_NAME; iteminfo.abilityName_ = FORM_PROVIDER_ABILITY_NAME; - iteminfo.temporaryFlag_ = true; FormDataMgr::GetInstance().AllotFormRecord(iteminfo, 0); // clear callerToken token_ = nullptr; - EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().NotifyWhetherVisibleForms(formIds, - token_, Constants::FORM_INVISIBLE)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().NotifyWhetherVisibleForms( formIds, + token_, Constants::FORM_INVISIBLE )); GTEST_LOG_(INFO) << "FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_002 end"; } @@ -173,7 +170,7 @@ TestSize.Level0) std::vector formIds; formIds.push_back(formId); - EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms(formIds, token_, Constants::FORM_INVISIBLE)); + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms( formIds, token_, Constants::FORM_INVISIBLE )); GTEST_LOG_(INFO) << "FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_003 end"; } @@ -197,10 +194,9 @@ TestSize.Level0) iteminfo.formId_ = formId; iteminfo.providerBundleName_ = FORM_HOST_BUNDLE_NAME; iteminfo.abilityName_ = FORM_PROVIDER_ABILITY_NAME; - iteminfo.temporaryFlag_ = true; FormDataMgr::GetInstance().AllotFormRecord(iteminfo, 0); - EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms(formIds, token_, Constants::FORM_INVISIBLE)); + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms( formIds, token_, Constants::FORM_INVISIBLE )); GTEST_LOG_(INFO) << "FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_004 end"; } @@ -225,13 +221,12 @@ TestSize.Level0) iteminfo.providerBundleName_ = FORM_HOST_BUNDLE_NAME; iteminfo.abilityName_ = FORM_PROVIDER_ABILITY_NAME; iteminfo.formVisibleNotify_ = false; - iteminfo.temporaryFlag_ = true; FormDataMgr::GetInstance().AllotFormRecord(iteminfo, 0); // creat clientRecords_ FormDataMgr::GetInstance().AllotFormHostRecord(iteminfo, token_, formId, 0); - EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms(formIds, token_, Constants::FORM_INVISIBLE)); + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms( formIds, token_, Constants::FORM_INVISIBLE )); GTEST_LOG_(INFO) << "FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_005 end"; } @@ -256,13 +251,12 @@ TestSize.Level0) iteminfo.providerBundleName_ = FORM_HOST_BUNDLE_NAME; iteminfo.abilityName_ = FORM_PROVIDER_ABILITY_NAME; iteminfo.formVisibleNotify_ = true; - iteminfo.temporaryFlag_ = true; FormDataMgr::GetInstance().AllotFormRecord(iteminfo, 0); // creat clientRecords_ FormDataMgr::GetInstance().AllotFormHostRecord(iteminfo, token_, formId, 0); - EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms(formIds, token_, Constants::FORM_INVISIBLE)); + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms( formIds, token_, Constants::FORM_INVISIBLE )); GTEST_LOG_(INFO) << "FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_006 end"; } @@ -288,7 +282,6 @@ TestSize.Level0) iteminfo.providerBundleName_ = mockBundleName; iteminfo.abilityName_ = FORM_PROVIDER_ABILITY_NAME; iteminfo.formVisibleNotify_ = true; - iteminfo.temporaryFlag_ = true; FormDataMgr::GetInstance().AllotFormRecord(iteminfo, 0); // creat clientRecords_ @@ -312,7 +305,7 @@ TestSize.Level0) OHOS::Security::Permission::PermissionKit::GrantUserGrantedPermission(mockBundleName, PERMISSION_NAME_REQUIRE_FORM, 0); - EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms(formIds, token_, Constants::FORM_INVISIBLE)); + EXPECT_EQ(ERR_OK, FormMgr::GetInstance().NotifyWhetherVisibleForms( formIds, token_, Constants::FORM_INVISIBLE )); GTEST_LOG_(INFO) << "FmsFormMgrNotifyInvisibleFormsTest_NotifyInvisibleForms_007 end"; } } 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 b9cd43b3bb131b03759347a209b79421ba55b076..83f9d5a58807d54af200400610d38512280aacf6 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 @@ -88,12 +88,10 @@ void FmsFormMgrNotifyVisibleFormsTest::SetUp(void) permDef.descriptionId = 1; permList.emplace_back(permDef); OHOS::Security::Permission::PermissionKit::AddDefPermissions(permList); - std::vector permnameList; - permnameList.emplace_back(PERMISSION_NAME_REQUIRE_FORM); OHOS::Security::Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, - permnameList, 0); + {PERMISSION_NAME_REQUIRE_FORM}, 0); OHOS::Security::Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, - PERMISSION_NAME_REQUIRE_FORM, 0); + PERMISSION_NAME_REQUIRE_FORM, 0); } void FmsFormMgrNotifyVisibleFormsTest::TearDown(void) 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 30a5b3673c285f24401dfdcfa932f9c028a60bb1..1ec263f000f801931dec8394a2b587445ca34c94 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 @@ -91,8 +91,8 @@ void FmsFormMgrReleaseFormTest::SetUp() permDef.descriptionId = 1; permList.emplace_back(permDef); Permission::PermissionKit::AddDefPermissions(permList); - Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, - {PERMISSION_NAME_REQUIRE_FORM}, 0); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, + 0); Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); } @@ -206,9 +206,9 @@ HWTEST_F(FmsFormMgrReleaseFormTest, ReleaseForm_003, TestSize.Level0) GTEST_LOG_(INFO) << "fms_form_mgr_release_test_003 start"; int64_t formId = FormDataMgr::GetInstance().GenerateFormId(); // formId<=0 - EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().ReleaseForm(0L, token_, false)); + EXPECT_EQ(ERR_FORM_INVALID_PARAM, FormMgr::GetInstance().ReleaseForm(0L, token_, false)); // sptr is nullptr - EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().ReleaseForm(formId, nullptr, false)); + EXPECT_EQ(ERR_FORM_INVALID_PARAM, FormMgr::GetInstance().ReleaseForm(formId, nullptr, false)); // Remove Permission OHOS::Security::Permission::PermissionKit::RemoveDefPermissions(FORM_PROVIDER_BUNDLE_NAME); @@ -246,7 +246,7 @@ HWTEST_F(FmsFormMgrReleaseFormTest, ReleaseForm_004, TestSize.Level0) { GTEST_LOG_(INFO) << "fms_form_mgr_release_test_004 start"; int64_t formId = FormDataMgr::GetInstance().GenerateFormId(); - EXPECT_EQ(ERR_APPEXECFWK_FORM_NOT_EXIST_ID, FormMgr::GetInstance().ReleaseForm(formId, token_, true)); + EXPECT_EQ(ERR_NOT_EXIST_ID, FormMgr::GetInstance().ReleaseForm(formId, token_, true)); GTEST_LOG_(INFO) << "fms_form_mgr_release_test_004 end"; } @@ -268,7 +268,7 @@ HWTEST_F(FmsFormMgrReleaseFormTest, ReleaseForm_005, TestSize.Level0) record.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); record.SetTemporaryFlag(false); FormDataMgr::GetInstance().AllotFormRecord(record, 0); - EXPECT_EQ(ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF, FormMgr::GetInstance().ReleaseForm(formId, token_, true)); + EXPECT_EQ(ERR_OPERATION_FORM_NOT_SELF, FormMgr::GetInstance().ReleaseForm(formId, token_, true)); GTEST_LOG_(INFO) << "fms_form_mgr_release_test_005 end"; } } \ No newline at end of file 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 cef35f47929c5cac8ff3c1786f6711937eb53133..f6d4824741384a3c12eddad993ff143dc248d1d6 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 @@ -94,8 +94,8 @@ void FmsFormMgrRequestFormTest::SetUp() permDef.descriptionId = 1; permList.emplace_back(permDef); Permission::PermissionKit::AddDefPermissions(permList); - Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, - {PERMISSION_NAME_REQUIRE_FORM}, 0); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, + 0); Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); } @@ -202,7 +202,7 @@ HWTEST_F(FmsFormMgrRequestFormTest, RequestForm_003, TestSize.Level0) FormRecord retFormRec = FormDataMgr::GetInstance().AllotFormRecord(record, callingUid); Want want; - EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().RequestForm(formId, token_, want)); + EXPECT_EQ(ERR_FORM_INVALID_PARAM, FormMgr::GetInstance().RequestForm(formId, token_, want)); token_->Wait(); FormDataMgr::GetInstance().DeleteFormRecord(formId); @@ -235,7 +235,7 @@ HWTEST_F(FmsFormMgrRequestFormTest, RequestForm_004, TestSize.Level0) FormDataMgr::GetInstance().AllotFormHostRecord(itemInfo, token_, fakeFormId, 0); Want want; - EXPECT_EQ(ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF, FormMgr::GetInstance().RequestForm(formId, token_, want)); + EXPECT_EQ(ERR_OPERATION_FORM_NOT_SELF, FormMgr::GetInstance().RequestForm(formId, token_, want)); token_->Wait(); FormDataMgr::GetInstance().DeleteFormRecord(formId); 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 bde926b055812207a4470dfcf43484a65f5cddbf..0f051fc1b05a2f63a58dd0b69a24de67774c3167 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 @@ -102,8 +102,8 @@ void FmsFormMgrUpdateFormTest::SetUp() permDef.descriptionId = 1; permList.emplace_back(permDef); Permission::PermissionKit::AddDefPermissions(permList); - Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, - {PERMISSION_NAME_REQUIRE_FORM}, 0); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, + 0); Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); } @@ -231,7 +231,7 @@ HWTEST_F(FmsFormMgrUpdateFormTest, UpdateForm_003, TestSize.Level0) FormDataMgr::GetInstance().AllotFormHostRecord(itemInfo, token_, formId, callingUid); // test exec - EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().UpdateForm(formId, bandleName, formProviderData)); + EXPECT_EQ(ERR_FORM_INVALID_PARAM, FormMgr::GetInstance().UpdateForm(formId, bandleName, formProviderData)); GTEST_LOG_(INFO) << "fms_form_mgr_client_updateForm_test_003 end"; } @@ -267,7 +267,7 @@ HWTEST_F(FmsFormMgrUpdateFormTest, UpdateForm_004, TestSize.Level0) FormDataMgr::GetInstance().AllotFormHostRecord(itemInfo, token_, formId, callingUid); // test exec - EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().UpdateForm(formId, bandleName, formProviderData)); + EXPECT_EQ(ERR_FORM_INVALID_PARAM, FormMgr::GetInstance().UpdateForm(formId, bandleName, formProviderData)); GTEST_LOG_(INFO) << "fms_form_mgr_client_updateForm_test_004 end"; } @@ -303,7 +303,7 @@ HWTEST_F(FmsFormMgrUpdateFormTest, UpdateForm_005, TestSize.Level0) FormDataMgr::GetInstance().AllotFormHostRecord(itemInfo, token_, formId, callingUid); // test exec - EXPECT_EQ(ERR_APPEXECFWK_FORM_NOT_EXIST_ID, FormMgr::GetInstance().UpdateForm(formId, bandleName, formProviderData)); + EXPECT_EQ(ERR_NOT_EXIST_ID, FormMgr::GetInstance().UpdateForm(formId, bandleName, formProviderData)); GTEST_LOG_(INFO) << "fms_form_mgr_client_updateForm_test_005 end"; } @@ -339,7 +339,7 @@ HWTEST_F(FmsFormMgrUpdateFormTest, UpdateForm_006, TestSize.Level0) FormDataMgr::GetInstance().AllotFormHostRecord(itemInfo, token_, formId, callingUid); // test exec - EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormMgr::GetInstance().UpdateForm(formId, bandleName, formProviderData)); + EXPECT_EQ(ERR_FORM_INVALID_PARAM, FormMgr::GetInstance().UpdateForm(formId, bandleName, formProviderData)); GTEST_LOG_(INFO) << "fms_form_mgr_client_updateForm_test_006 end"; } diff --git a/services/formmgr/test/unittest/fms_form_provider_data_test/fms_form_provider_data_test.cpp b/services/formmgr/test/unittest/fms_form_provider_data_test/fms_form_provider_data_test.cpp index f20fec9b9bc0b10186e0d7d008e10208b1d1814b..31c9bd4191f960d53bce3e53c04eb5fc4656ad9b 100644 --- a/services/formmgr/test/unittest/fms_form_provider_data_test/fms_form_provider_data_test.cpp +++ b/services/formmgr/test/unittest/fms_form_provider_data_test/fms_form_provider_data_test.cpp @@ -31,7 +31,7 @@ using namespace OHOS; using namespace OHOS::AppExecFwk; namespace { -const std::string FORM_DB_DATA_BASE_FILE_DIR = "/data/formmgr"; +const char* FORM_DB_DATA_BASE_FILE_DIR = "/data/formmgr"; const int32_t four = 4; const int32_t ten = 10; const int32_t eleven = 11; @@ -45,15 +45,16 @@ public: bool CreateJsonFileByJsonData1(const nlohmann::json &jsonData); bool CreateJsonFileByJsonData2(const nlohmann::json &jsonData); bool CreateMergeJsonFileByJsonData3(const nlohmann::json &jsonData); + // bool createJsonFileByStringData(); nlohmann::json jsonData_; }; void FmsFormProviderDataTest::SetUp() { - DIR *dirptr = opendir(FORM_DB_DATA_BASE_FILE_DIR.c_str()); + DIR *dirptr = opendir(FORM_DB_DATA_BASE_FILE_DIR); if (dirptr == nullptr) { APP_LOGW("%{public}s, opendir is fail", __func__); - if (-1 == mkdir(FORM_DB_DATA_BASE_FILE_DIR.c_str(), S_IRWXU)) { + if (-1 == mkdir(FORM_DB_DATA_BASE_FILE_DIR, S_IRWXU)) { APP_LOGE("%{public}s, dir create fail", __func__); return; } @@ -86,7 +87,7 @@ bool FmsFormProviderDataTest::CreateJsonFileByJsonData1(const nlohmann::json &js o.close(); std::fstream f("/data/formmgr/ByJsonFile1.json"); - if (f.good() == false) { + if(f.good() == false) { return false; } @@ -102,7 +103,7 @@ bool FmsFormProviderDataTest::CreateJsonFileByJsonData2(const nlohmann::json &js o.close(); std::fstream f("/data/formmgr/ByJsonFile2.json"); - if (f.good() == false) { + if(f.good() == false) { return false; } @@ -118,7 +119,7 @@ bool FmsFormProviderDataTest::CreateMergeJsonFileByJsonData3(const nlohmann::jso o.close(); std::fstream f("/data/formmgr/ByJsonFile3.json"); - if (f.good() == false) { + if(f.good() == false) { return false; } 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 742782f7ec6e546512f0e8ce8f319fa3dd4c9b74..c8a7d78eccec5d6b7a11d03e23aaeb485e9de4bd 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 @@ -108,8 +108,8 @@ void FmsFormProviderMgrTest::SetUp() permDef.descriptionId = 1; permList.emplace_back(permDef); Permission::PermissionKit::AddDefPermissions(permList); - Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, - {PERMISSION_NAME_REQUIRE_FORM}, 0); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, + 0); Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); } @@ -130,7 +130,7 @@ HWTEST_F(FmsFormProviderMgrTest, AcquireForm_001, TestSize.Level0) GTEST_LOG_(INFO) << "fms_form_mgr_provider_test_001 start"; int64_t formId = 0x114514aa00000000; FormProviderInfo formProviderInfo; - EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, FormProviderMgr::GetInstance().AcquireForm(-114514L, formProviderInfo)); + EXPECT_EQ(ERR_FORM_INVALID_PARAM, FormProviderMgr::GetInstance().AcquireForm(-114514L, formProviderInfo)); int callingUid {0}; FormItemInfo record; record.SetFormId(formId); @@ -154,7 +154,7 @@ HWTEST_F(FmsFormProviderMgrTest, AcquireForm_002, TestSize.Level0) GTEST_LOG_(INFO) << "fms_form_mgr_provider_test_002 start"; int64_t formId = 0x11451aaa00000000; FormProviderInfo formProviderInfo; - EXPECT_EQ(ERR_APPEXECFWK_FORM_NOT_EXIST_ID, FormProviderMgr::GetInstance().AcquireForm(formId, formProviderInfo)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_INFO_NOT_EXIST,FormProviderMgr::GetInstance().AcquireForm(formId,formProviderInfo)); int callingUid {0}; FormItemInfo record; record.SetFormId(formId); @@ -183,8 +183,8 @@ HWTEST_F(FmsFormProviderMgrTest, AcquireForm_003, TestSize.Level0) FormItemInfo record; record.SetFormId(formId); FormRecord realFormRecord = FormDataMgr::GetInstance().AllotFormRecord(record, callingUid); - EXPECT_EQ(ERR_APPEXECFWK_FORM_COMMON_CODE, - FormProviderMgr::GetInstance().AcquireForm(formId, formProviderInfo)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_HOST_INFO_NOT_EXIST, + FormProviderMgr::GetInstance().AcquireForm(formId,formProviderInfo)); FormItemInfo info; FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); GTEST_LOG_(INFO) << "fms_form_mgr_provider_test_003 end"; @@ -206,7 +206,7 @@ HWTEST_F(FmsFormProviderMgrTest, RefreshForm_001, TestSize.Level0) int64_t formId = 0x1145aaaa00001200; Want want; int callingUid {0}; - EXPECT_EQ(ERR_APPEXECFWK_FORM_NOT_EXIST_ID, FormProviderMgr::GetInstance().RefreshForm(formId, want)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_INFO_NOT_EXIST, FormProviderMgr::GetInstance().RefreshForm(formId, want)); FormItemInfo record; record.SetFormId(formId); record.SetModuleName(PARAM_FORM_NAME); @@ -240,7 +240,7 @@ HWTEST_F(FmsFormProviderMgrTest, RefreshForm_002, TestSize.Level0) FormRecord realFormRecord = FormDataMgr::GetInstance().AllotFormRecord(record, callingUid); FormItemInfo info; FormDataMgr::GetInstance().AllotFormHostRecord(info, token_, formId, callingUid); - EXPECT_EQ(ERR_APPEXECFWK_FORM_PROVIDER_DEL_FAIL, FormProviderMgr::GetInstance().RefreshForm(formId, want)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_SUPPLIER_DEL_FAIL, FormProviderMgr::GetInstance().RefreshForm(formId, want)); GTEST_LOG_(INFO) << "fms_form_mgr_provider_test_005 end"; } } \ No newline at end of file diff --git a/services/formmgr/test/unittest/fms_form_set_next_refresh_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_set_next_refresh_test/BUILD.gn index 705667c2aadaa5bcb977d4cac7344760722a60fb..16adef3efec1680e7ddf8501ba56d4a741feaefa 100644 --- a/services/formmgr/test/unittest/fms_form_set_next_refresh_test/BUILD.gn +++ b/services/formmgr/test/unittest/fms_form_set_next_refresh_test/BUILD.gn @@ -58,15 +58,12 @@ ohos_unittest("FmsFormSetNextRefreshTest") { "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "${appexecfwk_path}/interfaces/innerkits/fmskit:fmskit_native", "${services_path}/formmgr:fms_target", - "//base/miscservices/time/services:time_service", - "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", #"${libs_path}/libeventhandler:libeventhandler_target", #"//base/startup/appspawn_standard:appspawn_socket_client", "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//foundation/aafwk/standard/interfaces/innerkits/want:want", - "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr:distributedschedsvr", "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gmock_main", 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 d6e661b62e6006ce51257d88f0f3a24594690306..76a978a7892529a009499e1663b0c128ac5a00db 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 @@ -86,7 +86,7 @@ HWTEST_F(FmsFormSetNextRefreshTest, FmsFormSetNextRefreshTest_SetNextRefreshTime int64_t formId = 0; // invalid formId int64_t nextTime = Constants::MIN_NEXT_TIME; - EXPECT_EQ(ERR_APPEXECFWK_FORM_INVALID_PARAM, formSetNextRefresh_->SetNextRefreshTime(formId, nextTime)); + EXPECT_EQ(ERR_FORM_INVALID_PARAM, formSetNextRefresh_->SetNextRefreshTime(formId, nextTime)); GTEST_LOG_(INFO) << "FmsFormSetNextRefreshTest_SetNextRefreshTime_001 end"; } @@ -101,7 +101,7 @@ HWTEST_F(FmsFormSetNextRefreshTest, FmsFormSetNextRefreshTest_SetNextRefreshTime int64_t formId = 2; int64_t nextTime = Constants::MIN_NEXT_TIME; - EXPECT_EQ(ERR_APPEXECFWK_FORM_NOT_EXIST_ID, formSetNextRefresh_->SetNextRefreshTime(formId, nextTime)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_INFO_NOT_EXIST, formSetNextRefresh_->SetNextRefreshTime(formId, nextTime)); GTEST_LOG_(INFO) << "FmsFormSetNextRefreshTest_SetNextRefreshTime_002 end"; } @@ -124,7 +124,6 @@ HWTEST_F(FmsFormSetNextRefreshTest, FmsFormSetNextRefreshTest_SetNextRefreshTime iteminfo.formId_ = formId; iteminfo.providerBundleName_ = FORM_HOST_BUNDLE_NAME; iteminfo.abilityName_ = FORM_PROVIDER_ABILITY_NAME; - iteminfo.temporaryFlag_ = true; FormDataMgr::GetInstance().AllotFormRecord(iteminfo, 0); EXPECT_EQ(ERR_OK, formSetNextRefresh_->SetNextRefreshTime(formId, nextTime)); @@ -151,10 +150,9 @@ HWTEST_F(FmsFormSetNextRefreshTest, FmsFormSetNextRefreshTest_SetNextRefreshTime iteminfo.formId_ = formId; iteminfo.providerBundleName_ = "other_bundleName"; iteminfo.abilityName_ = FORM_PROVIDER_ABILITY_NAME; - iteminfo.temporaryFlag_ = true; FormDataMgr::GetInstance().AllotFormRecord(iteminfo, 0); - EXPECT_EQ(ERR_APPEXECFWK_FORM_OPERATION_NOT_SELF, formSetNextRefresh_->SetNextRefreshTime(formId, nextTime)); + EXPECT_EQ(ERR_OPERATION_FORM_NOT_SELF, formSetNextRefresh_->SetNextRefreshTime(formId, nextTime)); GTEST_LOG_(INFO) << "FmsFormSetNextRefreshTest_SetNextRefreshTime_004 end"; } @@ -174,7 +172,6 @@ HWTEST_F(FmsFormSetNextRefreshTest, FmsFormSetNextRefreshTest_SetNextRefreshTime iteminfo.formId_ = formId; iteminfo.providerBundleName_ = FORM_HOST_BUNDLE_NAME; iteminfo.abilityName_ = FORM_PROVIDER_ABILITY_NAME; - iteminfo.temporaryFlag_ = true; FormDataMgr::GetInstance().AllotFormRecord(iteminfo, 0); // Creat dynamicRefreshTasks_ @@ -216,7 +213,6 @@ HWTEST_F(FmsFormSetNextRefreshTest, FmsFormSetNextRefreshTest_SetNextRefreshTime iteminfo.formId_ = formId; iteminfo.providerBundleName_ = FORM_HOST_BUNDLE_NAME; iteminfo.abilityName_ = FORM_PROVIDER_ABILITY_NAME; - iteminfo.temporaryFlag_ = true; FormDataMgr::GetInstance().AllotFormRecord(iteminfo, 0); // set timerRefreshedCount @@ -227,7 +223,7 @@ HWTEST_F(FmsFormSetNextRefreshTest, FmsFormSetNextRefreshTest_SetNextRefreshTime } else { iter->second.refreshCount = Constants::LIMIT_COUNT; } - EXPECT_EQ(ERR_APPEXECFWK_FORM_MAX_REFRESH, formSetNextRefresh_->SetNextRefreshTime(formId, nextTime)); + EXPECT_EQ(ERR_MAX_REFRESH, formSetNextRefresh_->SetNextRefreshTime(formId, nextTime)); GTEST_LOG_(INFO) << "FmsFormSetNextRefreshTest_SetNextRefreshTime_006 end"; } diff --git a/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/BUILD.gn index ef6b82067dd485bce5010185d5e564b8962a2d20..e2ef82595509819b4c79a915dea1a99bd56fcef8 100644 --- a/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/BUILD.gn +++ b/services/formmgr/test/unittest/fms_form_sys_event_receiver_test/BUILD.gn @@ -60,8 +60,6 @@ ohos_unittest("FmsFormSysEventReceiverTest") { "${appexecfwk_path}/interfaces/innerkits/fmskit:fmskit_native", "${libs_path}/libeventhandler:libeventhandler_target", "${services_path}/formmgr:fms_target", - "//base/miscservices/time/services:time_service", - "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", "//base/startup/appspawn_standard:appspawn_socket_client", "//foundation/aafwk/standard/interfaces/innerkits/base:base", @@ -69,7 +67,6 @@ ohos_unittest("FmsFormSysEventReceiverTest") { #"${services_path}/bundlemgr:bms_target", "//foundation/aafwk/standard/services/abilitymgr:abilityms_target", - "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr:distributedschedsvr", "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gmock_main", 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 2b094e5940ea45bcfe11a965c994497da4124fa8..66aaa586a5ca0c8d619ef6245469997f7bfa59f8 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 @@ -73,8 +73,7 @@ public: static void TearDownTestCase(); void SetUp(); void TearDown(); - void CreateEventData(std::string bundle, int64_t formId, - int callingUid, std::string actionType, EventFwk::CommonEventData &eventData); + void CreateEventData(std::string bundle, int64_t formId, int callingUid, std::string actionType, EventFwk::CommonEventData &eventData); void CreateFormRecordAndFormInfo(std::string bundle, int64_t formId, int callingUid); void ClearFormRecord(int64_t formId); @@ -120,16 +119,15 @@ void FmsFormSysEventReceiverTest::SetUp() permDef.descriptionId = 1; permList.emplace_back(permDef); Permission::PermissionKit::AddDefPermissions(permList); - Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, - {PERMISSION_NAME_REQUIRE_FORM}, 0); + Permission::PermissionKit::AddUserGrantedReqPermissions(FORM_PROVIDER_BUNDLE_NAME, {PERMISSION_NAME_REQUIRE_FORM}, + 0); Permission::PermissionKit::GrantUserGrantedPermission(FORM_PROVIDER_BUNDLE_NAME, PERMISSION_NAME_REQUIRE_FORM, 0); } void FmsFormSysEventReceiverTest::TearDown() {} -void FmsFormSysEventReceiverTest::CreateEventData(std::string bundle, int64_t formId, - int callingUid, std::string actionType, EventFwk::CommonEventData &eventData) +void FmsFormSysEventReceiverTest::CreateEventData(std::string bundle, int64_t formId, int callingUid, std::string actionType, EventFwk::CommonEventData &eventData) { Want want; want.SetAction(actionType); @@ -207,7 +205,7 @@ HWTEST_F(FmsFormSysEventReceiverTest, OnReceiveEvent_001, TestSize.Level0) FormSysEventReceiver testCase; testCase.OnReceiveEvent(eventData); FormDbCache::GetInstance().GetAllFormInfo(allFormInfo); - EXPECT_EQ(ERR_APPEXECFWK_FORM_COMMON_CODE, FormDbCache::GetInstance().DeleteFormInfo(formId)); + EXPECT_EQ(ERR_APPEXECFWK_FORM_JSON_DELETE_FAIL, FormDbCache::GetInstance().DeleteFormInfo(formId)); FormDataMgr::GetInstance().DeleteFormRecord(formId); FormDbCache::GetInstance().DeleteFormInfo(formId); FormDataMgr::GetInstance().DeleteHostRecord(token_, formId); @@ -354,7 +352,7 @@ HWTEST_F(FmsFormSysEventReceiverTest, OnReceiveEvent_006, TestSize.Level0) EventFwk::CommonEventData eventData; CreateEventData(bundle, formId, callingUid, actionType, eventData); - // CreateFormRecordAndFormInfo + //CreateFormRecordAndFormInfo FormItemInfo record; record.SetFormId(formId); record.SetProviderBundleName(bundle); @@ -364,7 +362,7 @@ HWTEST_F(FmsFormSysEventReceiverTest, OnReceiveEvent_006, TestSize.Level0) record.SetSpecificationId(PARAM_FORM_DIMENSION_VALUE); record.SetTemporaryFlag(true); FormDataMgr::GetInstance().AllotFormRecord(record, callingUid); - // AddFormUserUid + ////AddFormUserUid int new_callingUid = 150; FormDataMgr::GetInstance().AddFormUserUid(formId, new_callingUid); FormRecord realFormRecord; @@ -442,13 +440,13 @@ HWTEST_F(FmsFormSysEventReceiverTest, OnReceiveEvent_008, TestSize.Level0) EventFwk::CommonEventData eventData; CreateEventData(bundle, formId, callingUid, actionType, eventData); - // CreateFormRecordAndFormInfo + //CreateFormRecordAndFormInfo FormItemInfo record; record.SetFormId(formId); record.SetProviderBundleName(bundle); record.SetModuleName(PARAM_PROVIDER_MODULE_NAME); // model name - record.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); // ability name - record.SetFormName(PARAM_FORM_NAME); // form name + record.SetAbilityName(FORM_PROVIDER_ABILITY_NAME); //ability name + record.SetFormName(PARAM_FORM_NAME); //form name record.SetSpecificationId(PARAM_FORM_DIMENSION_VALUE); record.SetTemporaryFlag(true); @@ -471,4 +469,5 @@ HWTEST_F(FmsFormSysEventReceiverTest, OnReceiveEvent_008, TestSize.Level0) GTEST_LOG_(INFO) << "fms_form_sys_event_receiver_test_008 end"; } + } \ No newline at end of file diff --git a/services/formmgr/test/unittest/fms_form_timer_mgr_test/BUILD.gn b/services/formmgr/test/unittest/fms_form_timer_mgr_test/BUILD.gn index 93ef619b6164f6a1b85cb4239bd27f508cfafd34..6cf9c8dbff8483f7caff7d10f8e795e5d8644242 100644 --- a/services/formmgr/test/unittest/fms_form_timer_mgr_test/BUILD.gn +++ b/services/formmgr/test/unittest/fms_form_timer_mgr_test/BUILD.gn @@ -27,7 +27,6 @@ ohos_unittest("FmsFormTimerMgrTest") { "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/formmgr/", - "//base/miscservices/time/interfaces/innerkits/include", ] configs = [ @@ -40,21 +39,17 @@ ohos_unittest("FmsFormTimerMgrTest") { } deps = [ "${appexecfwk_path}/common:libappexecfwk_common", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "${services_path}/formmgr:fms_target", - "//base/miscservices/time/services:time_service", - "//base/notification/ans_standard/frameworks/wantagent:wantagent_innerkits", - "//base/notification/ces_standard/frameworks/common:libevent_common", - "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr:distributedschedsvr", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", "//third_party/googletest:gmock_main", "//utils/native/base:utils", ] external_deps = [ - "aafwk_standard:base", - "aafwk_standard:want", - "appexecfwk_standard:appexecfwk_base", - "appexecfwk_standard:appexecfwk_core", - "appexecfwk_standard:libeventhandler", "ces_standard:cesfwk_core", "ces_standard:cesfwk_innerkits", "hiviewdfx_hilog_native:libhilog", 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 b8c72fada0bdf4c63b64d51f83e292d832c0a0ba..efb9fe31a78ceb24f815c8e1a2da83c9ad84e3de 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 @@ -178,16 +178,26 @@ HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0007, Function | MediumTest | Lev } /** * @tc.number: Fms_FormTimerMgr_0008 - * @tc.name: HandleSystemTimeChanged. - * @tc.desc: Handle system time changed. + * @tc.name: TimerReceiver::OnReceiveEvent. + * @tc.desc: Receive common event(COMMON_EVENT_TIME_CHANGED). */ HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0008, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0008 start"; bool isAddOk5 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_1, 11, 30); EXPECT_EQ(isAddOk5, true); - bool isAddOk6 = FormTimerMgr::GetInstance().HandleSystemTimeChanged(); - EXPECT_EQ(isAddOk6, true); + + /* Publish */ + + // make a want + AAFwk::Want want; + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_TIME_CHANGED); + // make common event data + EventFwk::CommonEventData data; + data.SetWant(want); + // publish a common event + bool publishResult = EventFwk::CommonEventManager::PublishCommonEvent(data); + EXPECT_EQ(publishResult, true); GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0008 end"; } @@ -202,31 +212,52 @@ HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0009, Function | MediumTest | Lev GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0009 start"; bool isAddOk5 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_2, 11, 30); EXPECT_EQ(isAddOk5, true); - bool isAddOk6 = FormTimerMgr::GetInstance().HandleSystemTimeChanged(); - EXPECT_EQ(isAddOk6, true); + + /* Publish */ + + // make a want + AAFwk::Want want; + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_TIMEZONE_CHANGED); + // make common event data + EventFwk::CommonEventData data; + data.SetWant(want); + // publish a common event + bool publishResult = EventFwk::CommonEventManager::PublishCommonEvent(data); + EXPECT_EQ(publishResult, true); GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0009 end"; } /** * @tc.number: Fms_FormTimerMgr_0010 - * @tc.name: HandleResetLimiter. - * @tc.desc: Handle reset limiter. + * @tc.name: TimerReceiver::OnReceiveEvent. + * @tc.desc: Receive common event(ACTION_UPDATEATTIMER - TYPE_RESET_LIMIT). */ HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0010, Function | MediumTest | Level1) { GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0010 start"; - bool isAddOk5 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_3, 16, 30); + bool isAddOk5 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_3, 11, 30); EXPECT_EQ(isAddOk5, true); - bool isAddOk6 = FormTimerMgr::GetInstance().HandleResetLimiter(); - EXPECT_EQ(isAddOk6, true); + + /* Publish */ + + // make a want + AAFwk::Want want; + want.SetAction(Constants::ACTION_UPDATEATTIMER); + want.SetParam(Constants::KEY_ACTION_TYPE, Constants::TYPE_RESET_LIMIT); + // make common event data + EventFwk::CommonEventData data; + data.SetWant(want); + // publish a common event + bool publishResult = EventFwk::CommonEventManager::PublishCommonEvent(data); + EXPECT_EQ(publishResult, true); GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0010 end"; } /** * @tc.number: Fms_FormTimerMgr_0011 - * @tc.name: OnUpdateAtTrigger. - * @tc.desc:handle attimer update. + * @tc.name: TimerReceiver::OnReceiveEvent. + * @tc.desc: Receive common event(ACTION_UPDATEATTIMER - TYPE_STATIC_UPDATE). */ HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0011, Function | MediumTest | Level1) { @@ -234,15 +265,26 @@ HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0011, Function | MediumTest | Lev bool isAddOk5 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_4, 11, 30); EXPECT_EQ(isAddOk5, true); - bool isAddOk6 = FormTimerMgr::GetInstance().OnUpdateAtTrigger(90L); - EXPECT_EQ(isAddOk6, true); + /* Publish */ + + // make a want + AAFwk::Want want; + want.SetAction(Constants::ACTION_UPDATEATTIMER); + want.SetParam(Constants::KEY_ACTION_TYPE, Constants::TYPE_STATIC_UPDATE); + want.SetParam(Constants::KEY_WAKEUP_TIME, 90L); + // make common event data + EventFwk::CommonEventData data; + data.SetWant(want); + // publish a common event + bool publishResult = EventFwk::CommonEventManager::PublishCommonEvent(data); + EXPECT_EQ(publishResult, true); GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0011 end"; } /** * @tc.number: Fms_FormTimerMgr_0012 - * @tc.name: OnDynamicTimeTrigger. - * @tc.desc: handle dynamic update. + * @tc.name: TimerReceiver::OnReceiveEvent. + * @tc.desc: Receive common event(ACTION_UPDATEATTIMER - TYPE_DYNAMIC_UPDATE). */ HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0012, Function | MediumTest | Level1) { @@ -250,8 +292,19 @@ HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0012, Function | MediumTest | Lev bool isAddOk5 = FormTimerMgr::GetInstance().AddFormTimer(PARAM_FORM_ID_VALUE_5, 11, 30); EXPECT_EQ(isAddOk5, true); - bool isAddOk6 = FormTimerMgr::GetInstance().OnDynamicTimeTrigger(90L); - EXPECT_EQ(isAddOk6, true); + /* Publish */ + + // make a want + AAFwk::Want want; + want.SetAction(Constants::ACTION_UPDATEATTIMER); + want.SetParam(Constants::KEY_ACTION_TYPE, Constants::TYPE_DYNAMIC_UPDATE); + want.SetParam(Constants::KEY_WAKEUP_TIME, 90L); + // make common event data + EventFwk::CommonEventData data; + data.SetWant(want); + // publish a common event + bool publishResult = EventFwk::CommonEventManager::PublishCommonEvent(data); + EXPECT_EQ(publishResult, true); GTEST_LOG_(INFO) << "Fms_FormTimerMgr_0012 end"; } @@ -473,7 +526,7 @@ HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0024, Function | MediumTest | Lev FormRefreshLimiter refreshLimiter; bool isAddOk = refreshLimiter.AddItem(PARAM_FORM_ID_VALUE_6); EXPECT_EQ(isAddOk, true); - for (int iIndex = 0; iIndex < Constants::LIMIT_COUNT; iIndex++) { + for(int iIndex = 0; iIndex < Constants::LIMIT_COUNT; iIndex++){ refreshLimiter.Increase(PARAM_FORM_ID_VALUE_6); } @@ -495,7 +548,7 @@ HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0025, Function | MediumTest | Lev FormRefreshLimiter refreshLimiter; bool isAddOk = refreshLimiter.AddItem(PARAM_FORM_ID_VALUE_6); EXPECT_EQ(isAddOk, true); - for (int iIndex = 0; iIndex < Constants::LIMIT_COUNT + 1; iIndex++) { + for(int iIndex = 0; iIndex < Constants::LIMIT_COUNT + 1; iIndex++) { refreshLimiter.Increase(PARAM_FORM_ID_VALUE_6); } @@ -517,7 +570,7 @@ HWTEST_F(FmsFormTimerMgrTest, Fms_FormTimerMgr_0026, Function | MediumTest | Lev FormRefreshLimiter refreshLimiter; bool isAddOk = refreshLimiter.AddItem(PARAM_FORM_ID_VALUE_6); EXPECT_EQ(isAddOk, true); - for (int iIndex = 0; iIndex < Constants::LIMIT_COUNT + 1; iIndex++) { + for(int iIndex = 0; iIndex < Constants::LIMIT_COUNT + 1; iIndex++) { refreshLimiter.Increase(PARAM_FORM_ID_VALUE_6); } 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 cbfb126eddc819145cb5965dc30f4bbfdb3cc774..20e10a2cb4575781565d8d08b6368436d0ff6b70 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 @@ -216,7 +216,7 @@ void AmsAppLifeCycleModuleTest::ChangeAbilityStateToForegroud(const sptrUpdateAbilityState(token, AbilityState::ABILITY_STATE_FOREGROUND); if (!isChange) { - EXPECT_NE(appRunningRecord, nullptr); + ASSERT_NE(appRunningRecord, nullptr); int32_t recordId = appRunningRecord->GetRecordId(); serviceInner_->ApplicationForegrounded(recordId); } @@ -235,7 +235,7 @@ void AmsAppLifeCycleModuleTest::ChangeAbilityStateToBackGroud(const sptrUpdateAbilityState(token, AbilityState::ABILITY_STATE_BACKGROUND); if (!isChange) { - EXPECT_NE(appRunningRecord, nullptr); + ASSERT_NE(appRunningRecord, nullptr); int32_t recordId = appRunningRecord->GetRecordId(); serviceInner_->ApplicationBackgrounded(recordId); } @@ -251,7 +251,7 @@ void AmsAppLifeCycleModuleTest::ChangeAppToTerminate(const sptrAbilityTerminated(token); - EXPECT_NE(appRunningRecord, nullptr); + ASSERT_NE(appRunningRecord, nullptr); int32_t recordId = appRunningRecord->GetRecordId(); serviceInner_->ApplicationTerminated(recordId); } else { @@ -269,11 +269,11 @@ void AmsAppLifeCycleModuleTest::ChangeAbilityStateToTerminate( void AmsAppLifeCycleModuleTest::CheckState(const std::shared_ptr &appRunningRecord, const sptr &token, const AbilityState abilityState, const ApplicationState appState) const { - EXPECT_NE(appRunningRecord, nullptr); + ASSERT_NE(appRunningRecord, nullptr); auto abilityRunningRecord = appRunningRecord->GetAbilityRunningRecordByToken(token); ApplicationState getAppState = appRunningRecord->GetState(); EXPECT_EQ(appState, getAppState); - EXPECT_NE(abilityRunningRecord, nullptr); + ASSERT_NE(abilityRunningRecord, nullptr); AbilityState getAbilityState = abilityRunningRecord->GetState(); EXPECT_EQ(abilityState, getAbilityState); } @@ -371,7 +371,7 @@ sptr AmsAppLifeCycleModuleTest::GetAbilityToken() */ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_001, TestSize.Level2) { - EXPECT_NE(serviceInner_, nullptr); + ASSERT_NE(serviceInner_, nullptr); pid_t pid = 1024; sptr token = GetAbilityToken(); auto abilityInfo = GetAbilityInfo("0", "MainAbility", "p1", "com.ohos.test.helloworld"); @@ -416,7 +416,7 @@ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_001, TestSize.Level2) HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_002, TestSize.Level3) { pid_t pid = 1023; - EXPECT_NE(serviceInner_, nullptr); + ASSERT_NE(serviceInner_, nullptr); std::shared_ptr appRunningRecord = nullptr; std::vector> tokens; auto abilityInfo = std::make_shared(); @@ -525,7 +525,7 @@ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_003, TestSize.Level3) */ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_004, TestSize.Level3) { - EXPECT_NE(serviceInner_, nullptr); + ASSERT_NE(serviceInner_, nullptr); pid_t pid = 1024; sptr token = GetAbilityToken(); auto abilityInfo = GetAbilityInfo("0", "MainAbility", "p3", "com.ohos.test.helloworld"); @@ -572,7 +572,7 @@ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_004, TestSize.Level3) */ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_005, TestSize.Level2) { - EXPECT_NE(serviceInner_, nullptr); + ASSERT_NE(serviceInner_, nullptr); pid_t pid = 1024; sptr token0 = new (std::nothrow) MockAbilityToken(); @@ -635,7 +635,7 @@ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_005, TestSize.Level2) */ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_006, TestSize.Level2) { - EXPECT_NE(serviceInner_, nullptr); + ASSERT_NE(serviceInner_, nullptr); pid_t pid = fork(); if (pid == 0) { @@ -692,7 +692,7 @@ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_006, TestSize.Level2) */ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_007, TestSize.Level2) { - EXPECT_NE(serviceInner_, nullptr); + ASSERT_NE(serviceInner_, nullptr); pid_t pid = 1024; sptr token = GetAbilityToken(); auto abilityInfo = GetAbilityInfo("0", "MainAbility", "p1", "com.ohos.test.helloworld"); @@ -741,7 +741,7 @@ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_007, TestSize.Level2) */ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_008, TestSize.Level2) { - EXPECT_NE(serviceInner_, nullptr); + ASSERT_NE(serviceInner_, nullptr); pid_t pid_0 = 1024; pid_t pid_1 = 2048; sptr token_0 = new (std::nothrow) MockAbilityToken(); @@ -811,7 +811,7 @@ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_008, TestSize.Level2) HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_009, TestSize.Level3) { pid_t pid = 1025; - EXPECT_NE(serviceInner_, nullptr); + ASSERT_NE(serviceInner_, nullptr); std::shared_ptr appRunningRecord = nullptr; auto abilityInfo = std::make_shared(); auto appInfo = std::make_shared(); @@ -857,7 +857,7 @@ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_009, TestSize.Level3) HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_010, TestSize.Level3) { pid_t pid = 1025; - EXPECT_NE(serviceInner_, nullptr); + ASSERT_NE(serviceInner_, nullptr); std::shared_ptr appRunningRecord = nullptr; int32_t recordId[APPLICATION_NUM]; sptr mockAppScheduler[APPLICATION_NUM]; @@ -979,7 +979,7 @@ HWTEST_F(AmsAppLifeCycleModuleTest, StateChange_013, TestSize.Level3) EXPECT_CALL(*mockAppSpawnSocket, OpenAppSpawnConnection()).Times(1).WillOnce(Return(0)); int ret = serviceInner_->OpenAppSpawnConnection(); - EXPECT_EQ(ret, 0); + ASSERT_EQ(ret, 0); EXPECT_EQ(serviceInner_->QueryAppSpawnConnectionState(), SpawnConnectionState::STATE_CONNECTED); EXPECT_CALL(*mockAppSpawnSocket, CloseAppSpawnConnection()).Times(1); diff --git a/services/test/moduletest/common/ams/app_running_record_test/ams_app_running_record_module_test.cpp b/services/test/moduletest/common/ams/app_running_record_test/ams_app_running_record_module_test.cpp index e28e909dc3cbc56333e9cc6e897bbd4c2663593f..f565d0ef49b9bb0e33115fc4c098be6f5d7ee4d2 100644 --- a/services/test/moduletest/common/ams/app_running_record_test/ams_app_running_record_module_test.cpp +++ b/services/test/moduletest/common/ams/app_running_record_test/ams_app_running_record_module_test.cpp @@ -171,7 +171,7 @@ HWTEST_F(AmsAppRunningRecordModuleTest, ApplicationStart_001, TestSize.Level0) RecordQueryResult result; auto record = service_->GetOrCreateAppRunningRecord(GetMockToken(), appInfo, abilityInfo, processName, 0, result); EXPECT_TRUE(record != nullptr) << ",create apprunningrecord fail!"; - EXPECT_FALSE(result.appExists) << ",result is wrong!"; + ASSERT_FALSE(result.appExists) << ",result is wrong!"; // check apprunningrecord int32_t id = record->GetRecordId(); @@ -231,7 +231,7 @@ HWTEST_F(AmsAppRunningRecordModuleTest, MultiApplicationStart_002, TestSize.Leve auto record = service_->GetOrCreateAppRunningRecord(GetMockToken(), appInfo, abilityInfo, processName, 0, result); EXPECT_TRUE(record != nullptr) << "create apprunningrecord fail!"; - EXPECT_FALSE(result.appExists) << "result is wrong!"; + ASSERT_FALSE(result.appExists) << "result is wrong!"; // check abilityrunningrecord & apprunningrecord int32_t id = record->GetRecordId(); @@ -274,7 +274,7 @@ HWTEST_F(AmsAppRunningRecordModuleTest, ScheduleTrimMemory_003, TestSize.Level1) RecordQueryResult result; auto record = service_->GetOrCreateAppRunningRecord(GetMockToken(), appInfo, abilityInfo, processName, 0, result); EXPECT_TRUE(record != nullptr) << "create apprunningrecord fail!"; - EXPECT_FALSE(result.appExists) << "result is wrong!"; + ASSERT_FALSE(result.appExists) << "result is wrong!"; // LaunchApplication sptr mockApplication(new MockApplication()); @@ -322,7 +322,7 @@ HWTEST_F(AmsAppRunningRecordModuleTest, LowMemoryWarning_004, TestSize.Level1) RecordQueryResult result; auto record = service_->GetOrCreateAppRunningRecord(GetMockToken(), appInfo, abilityInfo, processName, 0, result); EXPECT_TRUE(record != nullptr) << "create apprunningrecord fail!"; - EXPECT_FALSE(result.appExists) << "result is wrong!"; + ASSERT_FALSE(result.appExists) << "result is wrong!"; // LaunchApplication sptr mockApplication(new MockApplication()); diff --git a/services/test/moduletest/common/ams/ipc_app_scheduler_test/ams_ipc_app_scheduler_module_test.cpp b/services/test/moduletest/common/ams/ipc_app_scheduler_test/ams_ipc_app_scheduler_module_test.cpp index 7b1f332f9f666ce9f5cc22158fb0579e86b443af..356d2ba86ee67b79c248a662f2c1dcfe69898e2c 100644 --- a/services/test/moduletest/common/ams/ipc_app_scheduler_test/ams_ipc_app_scheduler_module_test.cpp +++ b/services/test/moduletest/common/ams/ipc_app_scheduler_test/ams_ipc_app_scheduler_module_test.cpp @@ -265,7 +265,7 @@ HWTEST_F(AmsIpcAppSchedulerModuleTest, ExcuteApplicationIPCInterface_008, TestSi mockApplication->Wait(); bool isEqual = mockApplication->CompareAppLaunchData(launchData); - EXPECT_EQ(true, isEqual) << "excute fail, index is " << i; + ASSERT_EQ(true, isEqual) << "excute fail, index is " << i; } } diff --git a/services/test/moduletest/common/ams/service_app_spawn_client_test/ams_service_app_spawn_client_module_test.cpp b/services/test/moduletest/common/ams/service_app_spawn_client_test/ams_service_app_spawn_client_module_test.cpp index 2080bbeb1fa54b50406ff1cbfee5201e4755b603..d50d759ce6af828b33b0fb0ccc08996f93330180 100644 --- a/services/test/moduletest/common/ams/service_app_spawn_client_test/ams_service_app_spawn_client_module_test.cpp +++ b/services/test/moduletest/common/ams/service_app_spawn_client_test/ams_service_app_spawn_client_module_test.cpp @@ -208,8 +208,8 @@ HWTEST_F(AmsServiceAppSpawnClientModuleTest, ConnectAppSpawnDaemon_001, TestSize for (uint32_t i = 0; i < CYCLE_NUMBER; i++) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); appMgrService->OnStart(); - EXPECT_EQ(SpawnConnectionState::STATE_CONNECTED, appMgrService->QueryServiceState().connectionState); - EXPECT_EQ(SpawnConnectionState::STATE_CONNECTED, amsInner->QueryAppSpawnConnectionState()); + ASSERT_EQ(SpawnConnectionState::STATE_CONNECTED, appMgrService->QueryServiceState().connectionState); + ASSERT_EQ(SpawnConnectionState::STATE_CONNECTED, amsInner->QueryAppSpawnConnectionState()); appMgrService->OnStop(); EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, appMgrService->QueryServiceState().connectionState); EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, amsInner->QueryAppSpawnConnectionState()); @@ -243,8 +243,8 @@ HWTEST_F(AmsServiceAppSpawnClientModuleTest, ConnectAppSpawnDaemon_002, TestSize EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, amsInner->QueryAppSpawnConnectionState()); MockedAppSpawnSocket::gConnectSuccess_ = true; appMgrService->OnStart(); - EXPECT_EQ(SpawnConnectionState::STATE_CONNECTED, appMgrService->QueryServiceState().connectionState); - EXPECT_EQ(SpawnConnectionState::STATE_CONNECTED, amsInner->QueryAppSpawnConnectionState()); + ASSERT_EQ(SpawnConnectionState::STATE_CONNECTED, appMgrService->QueryServiceState().connectionState); + ASSERT_EQ(SpawnConnectionState::STATE_CONNECTED, amsInner->QueryAppSpawnConnectionState()); appMgrService->OnStop(); EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, appMgrService->QueryServiceState().connectionState); EXPECT_EQ(SpawnConnectionState::STATE_NOT_CONNECT, amsInner->QueryAppSpawnConnectionState()); @@ -270,8 +270,8 @@ HWTEST_F(AmsServiceAppSpawnClientModuleTest, ConnectAppSpawnDaemon_003, TestSize for (uint32_t i = 0; i < CYCLE_NUMBER; i++) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); appMgrService->OnStart(); - EXPECT_EQ(SpawnConnectionState::STATE_CONNECTED, appMgrService->QueryServiceState().connectionState); - EXPECT_EQ(SpawnConnectionState::STATE_CONNECTED, amsInner->QueryAppSpawnConnectionState()); + ASSERT_EQ(SpawnConnectionState::STATE_CONNECTED, appMgrService->QueryServiceState().connectionState); + ASSERT_EQ(SpawnConnectionState::STATE_CONNECTED, amsInner->QueryAppSpawnConnectionState()); appMgrService->OnStart(); EXPECT_EQ(SpawnConnectionState::STATE_CONNECTED, appMgrService->QueryServiceState().connectionState); EXPECT_EQ(SpawnConnectionState::STATE_CONNECTED, amsInner->QueryAppSpawnConnectionState()); diff --git a/test/resource/amssystemtestability/abilitySrc/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/BUILD.gn index f8459bf203aa6947909c105bd20e1c27ba24082d..f583aff6456955f30da23a691294f598e85819f6 100644 --- a/test/resource/amssystemtestability/abilitySrc/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/BUILD.gn @@ -13,53 +13,52 @@ group("ams_system_test_app") { deps = [ - "amsAbilityAppendTestA:amsAbilityAppendTestA", - "amsAbilityAppendTestB:amsAbilityAppendTestB", - "amsAbilityVisibleTestPageA:amsAbilityVisibleTestPageA", - "amsAbilityVisibleTestServiceB:amsAbilityVisibleTestServiceB", - "amsConfigurationUpdatedTest:amsConfigurationUpdatedTest", - "amsDataSystemTestA:amsDataSystemTestA", - "amsDataSystemTestB:amsDataSystemTestB", - "amsDataSystemTestC:amsDataSystemTestC", - "amsKitSTAbilityManager:amsKitSTAbilityManager", - "amsKitSystemTest:amsKitSystemTest", - "amsKitSystemTestA:amsKitSystemTestA", - "amsKitSystemTestB:amsKitSystemTestB", - "amsKitSystemTestDataA:amsKitSystemTestDataA", - "amsKitSystemTestDataB:amsKitSystemTestDataB", - "amsKitSystemTestPageA:amsKitSystemTestPageA", - "amsKitSystemTestService:amsKitSystemTestService", - "amsMissionStackTest:amsMissionStackTest", - "amsMissionStackTestSubsidiary:amsMissionStackTestSubsidiary", - "amsSystemTestA:amsSystemTestA", - "amsSystemTestB:amsSystemTestB", - "amsSystemTestC:amsSystemTestC", - "amsSystemTestD:amsSystemTestD", - "amsSystemTestDFX:amsSystemTestDFX", - "amsSystemTestE:amsSystemTestE", - "amsSystemTestErrorK:amsSystemTestErrorK", - "amsSystemTestErrorL:amsSystemTestErrorL", - "amsSystemTestF:amsSystemTestF", - "amsSystemTestG:amsSystemTestG", - "amsSystemTestH:amsSystemTestH", - "amsSystemTestI:amsSystemTestI", - "amsSystemTestM:amsSystemTestM", - "amsSystemTestN:amsSystemTestN", - "amsSystemTestO:amsSystemTestO", - "amsSystemTestP:amsSystemTestP", - "amsSystemTestQ:amsSystemTestQ", - "amsSystemTestR:amsSystemTestR", - "amsSystemTestServiceA:amsSystemTestServiceA", - "amsSystemTestServiceB:amsSystemTestServiceB", - "amsSystemTestServiceC:amsSystemTestServiceC", - - # "amsSystemTestServiceD:amsSystemTestServiceD", - "amsSystemTestServiceE:amsSystemTestServiceE", - "amsSystemTestServiceF:amsSystemTestServiceF", - "amsSystemTestServiceG:amsSystemTestServiceG", - "amsSystemTestServiceH:amsSystemTestServiceH", - "serviceAbilityA:serviceAbilityA", - "taskDispatcherTestA:taskDispatcherTestA", - "taskDispatcherTestB:taskDispatcherTestB", + #"amsAbilityAppendTestA:amsAbilityAppendTestA", + #"amsAbilityAppendTestB:amsAbilityAppendTestB", + #"amsAbilityVisibleTestPageA:amsAbilityVisibleTestPageA", + #"amsAbilityVisibleTestServiceB:amsAbilityVisibleTestServiceB", + #"amsConfigurationUpdatedTest:amsConfigurationUpdatedTest", + #"amsDataSystemTestA:amsDataSystemTestA", + #"amsDataSystemTestB:amsDataSystemTestB", + #"amsDataSystemTestC:amsDataSystemTestC", + #"amsKitSTAbilityManager:amsKitSTAbilityManager", + #"amsKitSystemTest:amsKitSystemTest", + #"amsKitSystemTestA:amsKitSystemTestA", + #"amsKitSystemTestB:amsKitSystemTestB", + #"amsKitSystemTestDataA:amsKitSystemTestDataA", + #"amsKitSystemTestDataB:amsKitSystemTestDataB", + #"amsKitSystemTestPageA:amsKitSystemTestPageA", + #"amsKitSystemTestService:amsKitSystemTestService", + #"amsMissionStackTest:amsMissionStackTest", + #"amsMissionStackTestSubsidiary:amsMissionStackTestSubsidiary", + #"amsSystemTestA:amsSystemTestA", + #"amsSystemTestB:amsSystemTestB", + #"amsSystemTestC:amsSystemTestC", + #"amsSystemTestD:amsSystemTestD", + #"amsSystemTestDFX:amsSystemTestDFX", + #"amsSystemTestE:amsSystemTestE", + #"amsSystemTestErrorK:amsSystemTestErrorK", + #"amsSystemTestErrorL:amsSystemTestErrorL", + #"amsSystemTestF:amsSystemTestF", + #"amsSystemTestG:amsSystemTestG", + #"amsSystemTestH:amsSystemTestH", + #"amsSystemTestI:amsSystemTestI", + #"amsSystemTestM:amsSystemTestM", + #"amsSystemTestN:amsSystemTestN", + #"amsSystemTestO:amsSystemTestO", + #"amsSystemTestP:amsSystemTestP", + #"amsSystemTestQ:amsSystemTestQ", + #"amsSystemTestR:amsSystemTestR", + #"amsSystemTestServiceA:amsSystemTestServiceA", + #"amsSystemTestServiceB:amsSystemTestServiceB", + #"amsSystemTestServiceC:amsSystemTestServiceC", + ## "amsSystemTestServiceD:amsSystemTestServiceD", + #"amsSystemTestServiceE:amsSystemTestServiceE", + #"amsSystemTestServiceF:amsSystemTestServiceF", + #"amsSystemTestServiceG:amsSystemTestServiceG", + #"amsSystemTestServiceH:amsSystemTestServiceH", + #"serviceAbilityA:serviceAbilityA", + #"taskDispatcherTestA:taskDispatcherTestA", + #"taskDispatcherTestB:taskDispatcherTestB", ] } diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/BUILD.gn index 959cca097bb82084ddf7062b7c554d1c84b2fbcd..d9fbfd025ba42dcaefc29b825397d21fdbcea7c5 100755 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/BUILD.gn @@ -56,6 +56,8 @@ ohos_shared_library("amsAbilityAppendTestA") { "${innerkits_path}/appexecfwk_core:appexecfwk_core", "${kits_path}:appkit_native", "${services_path}/bundlemgr:libbms", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_dataability:native_dataability", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb:native_rdb", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/include/main_ability.h b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/include/main_ability.h index ec396c21dea02f6d24e14b6bd96c6200ebbb3545..fcbe2e0786af1dc0e02fe931e9f03b3027d7bc15 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/include/main_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/include/main_ability.h @@ -47,35 +47,35 @@ public: { [this](int code) { OnSetCallerCase1(code); }, }}, - {(int)AppendApi::TerminateAndRemoveMisson, + {(int)AppendApi::TerminateAndRemoveMisson, { [this](int code) { TerminateAndRemoveMissonCase1(code); }, }}, - {(int)AppendApi::TerminateAbilityResult, + {(int)AppendApi::TerminateAbilityResult, { [this](int code) { TerminateAbilityResultCase1(code); }, }}, - {(int)AppendApi::GetDispalyOrientation, + {(int)AppendApi::GetDispalyOrientation, { [this](int code) { GetDispalyOrientationCase1(code); }, }}, - {(int)AppendApi::GetPreferencesDir, + {(int)AppendApi::GetPreferencesDir, { [this](int code) { GetPreferencesDirCase1(code); }, }}, - {(int)AppendApi::StartAbilities, + {(int)AppendApi::StartAbilities, { [this](int code) { StartAbilitiesCase1(code); }, }}, - {(int)AppendApi::GetColorMode, + {(int)AppendApi::GetColorMode, { [this](int code) { GetColorModeCase1(code); }, }}, - {(int)AppendApi::SetColorMode, + {(int)AppendApi::SetColorMode, { [this](int code) { SetColorModeCase1(code); }, }}, - {(int)AppendApi::IsFirstInMission, + {(int)AppendApi::IsFirstInMission, { [this](int code) { IsFirstInMissionCase1(code); }, }}, diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/src/main_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/src/main_ability.cpp index 437d310c7b3b3ad0de7c19e9e7a21e310d4e81a0..0ee77556032cf9665bdb9fdb11d577b6b4a88e10 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/src/main_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/src/main_ability.cpp @@ -20,12 +20,6 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; -namespace { -constexpr int paramCnt = 3; -constexpr int index_f = 0; -constexpr int index_s = 1; -constexpr int index_t = 2; -} // namespace void MainAbility::Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, @@ -116,11 +110,11 @@ void FirstEventSubscriber::OnReceiveEvent(const CommonEventData &data) if (std::strcmp(eventName.c_str(), g_EVENT_REQU_FIRST.c_str()) == 0) { auto target = data.GetData(); auto caseInfo = TestUtils::split(target, "_"); - if (caseInfo.size() < paramCnt) { + if (caseInfo.size() < 3) { return; } - if (mapTestFunc_.find(caseInfo[index_f]) != mapTestFunc_.end()) { - mapTestFunc_[caseInfo[index_f]](std::stoi(caseInfo[index_s]), std::stoi(caseInfo[index_t]), data.GetCode()); + if (mapTestFunc_.find(caseInfo[0]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[0]](std::stoi(caseInfo[1]), std::stoi(caseInfo[2]), data.GetCode()); } else { APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); } @@ -166,11 +160,11 @@ void MainAbility::GetDispalyOrientationCase1(int code) void MainAbility::GetPreferencesDirCase1(int code) { - unsigned int result = true; + bool result = true; string preferencesDir = GetPreferencesDir(); result = !preferencesDir.empty(); - result = result & (unsigned int)preferencesDir.find(this->GetBundleName()); - result = result & (unsigned int)preferencesDir.find("com.ohos.amsst.AppAppendA/files/MainAbility/preferences"); + result = result & (bool)preferencesDir.find(this->GetBundleName()); + result = result & (bool)preferencesDir.find("com.ohos.amsst.AppAppendA/files/MainAbility/preferences"); TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); } diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/src/second_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/src/second_ability.cpp index e34a7a3a6588cd90cf2ea233d96698b2f0ce8336..74d9768f8a42a4b3cc9f4e70f2cbcb85330f1a98 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/src/second_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestA/src/second_ability.cpp @@ -20,12 +20,6 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; -namespace { -constexpr int paramCnt = 3; -constexpr int index_f = 0; -constexpr int index_s = 1; -constexpr int index_t = 2; -} // namespace void SecondAbility::Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, @@ -133,11 +127,11 @@ void SecondEventSubscriber::OnReceiveEvent(const CommonEventData &data) if (std::strcmp(eventName.c_str(), g_EVENT_REQU_SECOND.c_str()) == 0) { auto target = data.GetData(); auto caseInfo = TestUtils::split(target, "_"); - if (caseInfo.size() < paramCnt) { + if (caseInfo.size() < 3) { return; } - if (mapTestFunc_.find(caseInfo[index_f]) != mapTestFunc_.end()) { - mapTestFunc_[caseInfo[index_f]](std::stoi(caseInfo[index_s]), std::stoi(caseInfo[index_t]), data.GetCode()); + if (mapTestFunc_.find(caseInfo[0]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[0]](std::stoi(caseInfo[1]), std::stoi(caseInfo[2]), data.GetCode()); } else { APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); } diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/BUILD.gn index 94db70137542f2660dd2eae0ce219ccc1ed7424d..c510161b409741c5ed49b41194b4706022a31b73 100755 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/BUILD.gn @@ -55,6 +55,8 @@ ohos_shared_library("amsAbilityAppendTestB") { "${innerkits_path}/appexecfwk_core:appexecfwk_core", "${kits_path}:appkit_native", "${services_path}/bundlemgr:libbms", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_dataability:native_dataability", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb:native_rdb", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/src/main_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/src/main_ability.cpp index 8cbcdfb0c3beb5a9bceb6867852a90be753cbcfa..db038f3117a282e90f5ef9b2e9c5681325531547 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/src/main_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/src/main_ability.cpp @@ -20,12 +20,6 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; -namespace { -static const int paramCnt = 3; -static const int index_f = 0; -static const int index_s = 1; -static const int index_t = 2; -} // namespace void MainAbility::Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, @@ -109,11 +103,11 @@ void FirstEventSubscriber::OnReceiveEvent(const CommonEventData &data) if (std::strcmp(eventName.c_str(), g_EVENT_REQU_FIRSTB.c_str()) == 0) { auto target = data.GetData(); auto caseInfo = TestUtils::split(target, "_"); - if (caseInfo.size() < paramCnt) { + if (caseInfo.size() < 3) { return; } - if (mapTestFunc_.find(caseInfo[index_f]) != mapTestFunc_.end()) { - mapTestFunc_[caseInfo[index_f]](std::stoi(caseInfo[index_s]), std::stoi(caseInfo[index_t]), data.GetCode()); + if (mapTestFunc_.find(caseInfo[0]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[0]](std::stoi(caseInfo[1]), std::stoi(caseInfo[2]), data.GetCode()); } else { APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); } diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/src/test_utils.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/src/test_utils.cpp index 29dca59b94bd6f02146ee5b2944b1709b93f37fc..07ebf00c47128276f0e83d0aa5783fec0a417147 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/src/test_utils.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityAppendTestB/src/test_utils.cpp @@ -47,7 +47,7 @@ Want TestUtils::MakeWant( std::vector TestUtils::split(const std::string &in, const std::string &delim) { - std::regex reg { delim}; + std::regex reg{delim}; return std::vector{ std::sregex_token_iterator(in.begin(), in.end(), reg, -1), std::sregex_token_iterator()}; } diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/BUILD.gn index 47d0c6613f81ff009a68a58ef0ded978ea8ce16d..edea9e7b8463bf365cd7d920a2d6dc691877375d 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/BUILD.gn @@ -52,6 +52,8 @@ ohos_shared_library("amsAbilityVisibleTestPageA") { "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_dataability:native_dataability", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb:native_rdb", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//utils/native/base:utilsbase", ] diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea1.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea1.cpp index b54bb086d55ed747d90d7c4cd0db86f2705069c1..0c0e041b426fa9634a1ee7baf65b51dd4302e683 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea1.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea1.cpp @@ -17,6 +17,7 @@ namespace OHOS { namespace AppExecFwk { +using namespace OHOS::NativeRdb; void AmsAbilityVisibleTestPageA1::Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, const sptr &token) @@ -89,7 +90,7 @@ void AmsAbilityVisibleTestPageA1::OnActive() if (startAbilityType == "Data") { Uri dataAbilityUri("dataability:///" + startBundleName + "." + startAbilityName); std::shared_ptr helper = DataAbilityHelper::Creator(GetContext()); - AppExecFwk::ValuesBucket bucket; + NativeRdb::ValuesBucket bucket; helper->Insert(dataAbilityUri, bucket); } } diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea2.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea2.cpp index 1dd32126b946cda35b2ac232d21b8b27e6e43d00..169897284c4c5885d78b51e19f615971a1d680fb 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea2.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea2.cpp @@ -17,6 +17,7 @@ namespace OHOS { namespace AppExecFwk { + void AmsAbilityVisibleTestPageA2::Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, const sptr &token) @@ -89,7 +90,7 @@ void AmsAbilityVisibleTestPageA2::OnActive() if (startAbilityType == "Data") { Uri dataAbilityUri("dataability:///" + startBundleName + "." + startAbilityName); std::shared_ptr helper = DataAbilityHelper::Creator(GetContext()); - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; helper->Insert(dataAbilityUri, bucket); } if (startAbilityType == "TriggerWantAgentPageAbility") { diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea3.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea3.cpp index 8a041eb3f6e44221064dc13fa106cf7c0befe6ba..3a10f80656d8a96d4885999ec4696d179971f613 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea3.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea3.cpp @@ -17,6 +17,7 @@ namespace OHOS { namespace AppExecFwk { + void AmsAbilityVisibleTestPageA3::OnStart(const Want &want) { GetWantInfo(want); @@ -79,7 +80,7 @@ void AmsAbilityVisibleTestPageA3::OnActive() if (startAbilityType == "Data") { Uri dataAbilityUri("dataability:///" + startBundleName + "." + startAbilityName); std::shared_ptr helper = DataAbilityHelper::Creator(GetContext()); - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; helper->Insert(dataAbilityUri, bucket); } } diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea4.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea4.cpp index 22816749749d1e9e1a705d255b7bba96f06550e1..c122ba32b9be2aad813ad493c9ae23aa697a7d6d 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea4.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestPageA/src/amsabilityvisibletestpagea4.cpp @@ -17,6 +17,7 @@ namespace OHOS { namespace AppExecFwk { + void AmsAbilityVisibleTestPageA4::OnStart(const Want &want) { GetWantInfo(want); @@ -80,7 +81,7 @@ void AmsAbilityVisibleTestPageA4::OnActive() if (startAbilityType == "Data") { Uri dataAbilityUri("dataability:///" + startBundleName + "." + startAbilityName); std::shared_ptr helper = DataAbilityHelper::Creator(GetContext()); - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; helper->Insert(dataAbilityUri, bucket); } } diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/BUILD.gn index 4985c58073318cad1478ccb0cd79d16f6902c2d0..0eafd1b592e649e793df8f50579dde01c57faf43 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/BUILD.gn @@ -53,6 +53,8 @@ ohos_shared_library("amsAbilityVisibleTestServiceB") { "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_dataability:native_dataability", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb:native_rdb", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//utils/native/base:utilsbase", ] diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestpageb1.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestpageb1.cpp index c3ab87e077f7acef41090264caecca2285d7a8e7..29a044e5b841a98b81f856b72908d27a1272fe0d 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestpageb1.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestpageb1.cpp @@ -17,6 +17,7 @@ namespace OHOS { namespace AppExecFwk { + void AmsAbilityVisibleTestPageB1::Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, const sptr &token) @@ -89,7 +90,7 @@ void AmsAbilityVisibleTestPageB1::OnActive() if (startAbilityType == "Data") { Uri dataAbilityUri("dataability:///" + startBundleName + "." + startAbilityName); std::shared_ptr helper = DataAbilityHelper::Creator(GetContext()); - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; helper->Insert(dataAbilityUri, bucket); } } diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestpageb2.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestpageb2.cpp index 2caba9013d0579c77da46623421b7e3049325ce2..36516ae9a5df48605e3201efe6b5bb7daabc9d94 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestpageb2.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestpageb2.cpp @@ -17,6 +17,7 @@ namespace OHOS { namespace AppExecFwk { + void AmsAbilityVisibleTestPageB2::Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, const sptr &token) @@ -90,7 +91,7 @@ void AmsAbilityVisibleTestPageB2::OnActive() if (startAbilityType == "Data" || startAbilityType == "DataRelease") { Uri dataAbilityUri("dataability:///" + startBundleName + "." + startAbilityName); std::shared_ptr helper = DataAbilityHelper::Creator(GetContext()); - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; helper->Insert(dataAbilityUri, bucket); if (startAbilityType == "DataRelease") { helper->Release(); diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestservice.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestservice.cpp index a4ee376ae8f281ad5f7d0f8abb3d4a80afc38d78..d6c3935407a9967842649eb5dede4332b1a5fd65 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestservice.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestservice.cpp @@ -116,7 +116,7 @@ sptr AmsAbilityVisibleTestService::OnConnect(const Want &want) if (startAbilityType == "Data") { Uri dataAbilityUri("dataability:///" + startBundleName + "." + startAbilityName); std::shared_ptr helper = DataAbilityHelper::Creator(GetContext()); - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; helper->Insert(dataAbilityUri, bucket); } } diff --git a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestservicea1.cpp b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestservicea1.cpp index 208056c5250385a7970fe6fa753c02aa120e8fdb..a7bb23c23067f378f13c300df8e679abf6a3df1e 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestservicea1.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsAbilityVisibleTestServiceB/src/amsabilityvisibletestservicea1.cpp @@ -116,7 +116,7 @@ sptr AmsAbilityVisibleTestServiceA1::OnConnect(const Want &want) if (startAbilityType == "Data") { Uri dataAbilityUri("dataability:///" + startBundleName + "." + startAbilityName); std::shared_ptr helper = DataAbilityHelper::Creator(GetContext()); - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; helper->Insert(dataAbilityUri, bucket); } } diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/BUILD.gn index 901930e78c5f561df13734ef94c74c59e2b41e69..ed06c53138da221155adb084fc48d6026938d5ab 100755 --- a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/BUILD.gn @@ -57,6 +57,8 @@ ohos_shared_library("amsDataSystemTestA") { "${innerkits_path}/appexecfwk_core:appexecfwk_core", "${kits_path}:appkit_native", "${services_path}/bundlemgr:libbms", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_dataability:native_dataability", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb:native_rdb", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/src/ams_st_data_ability_data_a.cpp b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/src/ams_st_data_ability_data_a.cpp index c71b154d3e2e8cf1aa89f62ee4fa6c13e3d69f5e..e930e4b026e83d51e2237a4366e272891719cfe0 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/src/ams_st_data_ability_data_a.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/src/ams_st_data_ability_data_a.cpp @@ -25,7 +25,6 @@ namespace OHOS { namespace AppExecFwk { -namespace { static const int ABILITY_DATA_A_CODE = 210; static const std::string OPERATOR_INSERT = "Insert"; static const std::string OPERATOR_DELETE = "Delete"; @@ -39,8 +38,6 @@ static const int DEFAULT_UPDATE_RESULT = 3333; static const std::string ABILITY_TYPE_PAGE = "0"; static const std::string ABILITY_TYPE_SERVICE = "1"; static const std::string ABILITY_TYPE_DATA = "2"; -static const int charCnt = 5; -} // namespace bool AmsStDataAbilityDataA::PublishEvent(const std::string &eventName, const int &code, const std::string &data) { @@ -165,7 +162,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt Uri dataAbilityUri, string &result) { AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); @@ -190,9 +187,9 @@ static void GetResult(std::shared_ptr child, std::shared_pt return; } result = std::to_string(fd); - char str[charCnt]; + char str[5]; if (!feof(file)) - fgets(str, charCnt, file); + fgets(str, 5, file); result = str; fclose(file); } diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/src/ams_st_data_ability_page_a.cpp b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/src/ams_st_data_ability_page_a.cpp index bc87bd356b17186c06017e7b0bb9c6768e4a4480..83c3d4752a94e4189720e4e0e078f67cc06411d2 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/src/ams_st_data_ability_page_a.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestA/src/ams_st_data_ability_page_a.cpp @@ -26,7 +26,6 @@ namespace OHOS { namespace AppExecFwk { -namespace { static const int ABILITY_PAGE_A_CODE = 110; static const std::string OPERATOR_INSERT = "Insert"; static const std::string OPERATOR_DELETE = "Delete"; @@ -34,8 +33,6 @@ static const std::string OPERATOR_UPDATE = "Update"; static const std::string OPERATOR_QUERY = "Query"; static const std::string OPERATOR_GETFILETYPES = "GetFileTypes"; static const std::string OPERATOR_OPENFILE = "OpenFile"; -static const int charCnt = 5; -} // namespace bool AmsStDataAbilityPageA::PublishEvent(const std::string &eventName, const int &code, const std::string &data) { @@ -152,7 +149,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt Uri dataAbilityUri, string &result) { AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); @@ -179,9 +176,9 @@ static void GetResult(std::shared_ptr child, std::shared_pt return; } result = std::to_string(fd); - char str[charCnt]; + char str[5]; if (!feof(file)) - fgets(str, charCnt, file); + fgets(str, 5, file); result = str; fclose(file); } diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/BUILD.gn index 0397152f27eb6d55345a486ae357e1a42e7b7c07..99440ff945f619d3edcbd7eaed9e8251069aa5c0 100755 --- a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/BUILD.gn @@ -56,6 +56,8 @@ ohos_shared_library("amsDataSystemTestB") { "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_dataability:native_dataability", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb:native_rdb", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/src/ams_st_data_ability_data_b.cpp b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/src/ams_st_data_ability_data_b.cpp index 42b50324f63fb2c653794a2ebf52140dbd2fd214..8b0a9509b04186fe70e0d6546f5969b057f1540a 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/src/ams_st_data_ability_data_b.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/src/ams_st_data_ability_data_b.cpp @@ -23,7 +23,6 @@ namespace OHOS { namespace AppExecFwk { -namespace { static const int ABILITY_DATA_B_CODE = 220; static const std::string OPERATOR_INSERT = "Insert"; static const std::string OPERATOR_DELETE = "Delete"; @@ -37,8 +36,6 @@ static const int DEFAULT_UPDATE_RESULT = 3333; static const std::string ABILITY_TYPE_PAGE = "0"; static const std::string ABILITY_TYPE_SERVICE = "1"; static const std::string ABILITY_TYPE_DATA = "2"; -static const int charCnt = 5; -} // namespace bool AmsStDataAbilityDataB::PublishEvent(const std::string &eventName, const int &code, const std::string &data) { @@ -153,7 +150,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt Uri dataAbilityUri, string &result) { AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); @@ -178,10 +175,9 @@ static void GetResult(std::shared_ptr child, std::shared_pt return; } result = std::to_string(fd); - char str[charCnt]; - if (!feof(file)) { - fgets(str, charCnt, file); - } + char str[5]; + if (!feof(file)) + fgets(str, 5, file); result = str; fclose(file); } diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/src/ams_st_data_ability_page_b.cpp b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/src/ams_st_data_ability_page_b.cpp index 4b883d863e73413e5d9d2ee110d85fcc21d9559b..5d03834da1ad231a14729e526652568b8093fbaf 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/src/ams_st_data_ability_page_b.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestB/src/ams_st_data_ability_page_b.cpp @@ -26,7 +26,6 @@ namespace OHOS { namespace AppExecFwk { -namespace { static const int ABILITY_PAGE_B_CODE = 120; static const std::string OPERATOR_INSERT = "Insert"; static const std::string OPERATOR_DELETE = "Delete"; @@ -34,8 +33,6 @@ static const std::string OPERATOR_UPDATE = "Update"; static const std::string OPERATOR_QUERY = "Query"; static const std::string OPERATOR_GETFILETYPES = "GetFileTypes"; static const std::string OPERATOR_OPENFILE = "OpenFile"; -static const int charCnt = 5; -} // namespace bool AmsStDataAbilityPageB::PublishEvent(const std::string &eventName, const int &code, const std::string &data) { @@ -154,7 +151,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt Uri dataAbilityUri, string &result) { AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); @@ -179,10 +176,9 @@ static void GetResult(std::shared_ptr child, std::shared_pt return; } result = std::to_string(fd); - char str[charCnt]; - if (!feof(file)) { - fgets(str, charCnt, file); - } + char str[5]; + if (!feof(file)) + fgets(str, 5, file); result = str; fclose(file); } diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/BUILD.gn index 84231830d3a5eaf60aa8044569f6359e82cfc540..84116a2f76d062578358d0c8bb062d639237cdfc 100755 --- a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/BUILD.gn @@ -56,6 +56,8 @@ ohos_shared_library("amsDataSystemTestC") { "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/appexecfwk/standard/services/bundlemgr:libbms", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_dataability:native_dataability", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb:native_rdb", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/src/ams_st_data_ability_data_c1.cpp b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/src/ams_st_data_ability_data_c1.cpp index e661ad629278946bf36dcf721362476fdc95f42b..6a71906f6645ab7534036933f4e8460efced6e22 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/src/ams_st_data_ability_data_c1.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/src/ams_st_data_ability_data_c1.cpp @@ -23,7 +23,6 @@ namespace OHOS { namespace AppExecFwk { -namespace { static const int ABILITY_DATA_C1_CODE = 230; static const std::string OPERATOR_INSERT = "Insert"; static const std::string OPERATOR_DELETE = "Delete"; @@ -38,7 +37,6 @@ static const std::string ABILITY_TYPE_PAGE = "0"; static const std::string ABILITY_TYPE_SERVICE = "1"; static const std::string ABILITY_TYPE_DATA = "2"; constexpr int charCnt = 5; -} // namespace bool AmsStDataAbilityDataC1::PublishEvent(const std::string &eventName, const int &code, const std::string &data) { @@ -151,7 +149,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt Uri dataAbilityUri, string &result) { AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); @@ -177,9 +175,8 @@ static void GetResult(std::shared_ptr child, std::shared_pt } result = std::to_string(fd); char str[charCnt]; - if (!feof(file)) { + if (!feof(file)) fgets(str, charCnt, file); - } result = str; fclose(file); } @@ -190,7 +187,7 @@ void DataTestDataC1EventSubscriber::GetResultBySelf( { if (child->GetOperatorName() == OPERATOR_INSERT) { APP_LOGI("---------------------Insert--------------------"); - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; result = std::to_string(mainAbility->Insert(dataAbilityUri, bucket)); } else if (child->GetOperatorName() == OPERATOR_DELETE) { APP_LOGI("---------------------Delete--------------------"); @@ -198,7 +195,7 @@ void DataTestDataC1EventSubscriber::GetResultBySelf( result = std::to_string(mainAbility->Delete(dataAbilityUri, predicates)); } else if (child->GetOperatorName() == OPERATOR_UPDATE) { APP_LOGI("---------------------Update--------------------"); - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; AppExecFwk::DataAbilityPredicates predicates; result = std::to_string(mainAbility->Update(dataAbilityUri, bucket, predicates)); } else if (child->GetOperatorName() == OPERATOR_QUERY) { @@ -228,9 +225,8 @@ void DataTestDataC1EventSubscriber::GetResultBySelf( mainAbility_->PublishEvent(abilityEventName, ABILITY_DATA_C1_CODE, "OpenFile"); char str[charCnt]; - if (!feof(file)) { + if (!feof(file)) fgets(str, charCnt, file); - } result = str; fclose(file); } diff --git a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/src/ams_st_data_ability_data_c2.cpp b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/src/ams_st_data_ability_data_c2.cpp index deccd502079ed0e119a2e95463a45dbe39031fcf..c8bd58b4382aa152b51ba980fdb7ad4287fa9f11 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/src/ams_st_data_ability_data_c2.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsDataSystemTestC/src/ams_st_data_ability_data_c2.cpp @@ -23,7 +23,6 @@ namespace OHOS { namespace AppExecFwk { -namespace { static const int ABILITY_DATA_C2_CODE = 240; static const std::string OPERATOR_INSERT = "Insert"; static const std::string OPERATOR_DELETE = "Delete"; @@ -37,8 +36,6 @@ static const int DEFAULT_UPDATE_RESULT = 3333; static const std::string ABILITY_TYPE_PAGE = "0"; static const std::string ABILITY_TYPE_SERVICE = "1"; static const std::string ABILITY_TYPE_DATA = "2"; -constexpr int charCnt = 5; -} // namespace bool AmsStDataAbilityDataC2::PublishEvent(const std::string &eventName, const int &code, const std::string &data) { @@ -153,7 +150,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt Uri dataAbilityUri, string &result) { AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); @@ -178,10 +175,9 @@ static void GetResult(std::shared_ptr child, std::shared_pt return; } result = std::to_string(fd); - char str[charCnt]; - if (!feof(file)) { - fgets(str, charCnt, file); - } + char str[5]; + if (!feof(file)) + fgets(str, 5, file); result = str; fclose(file); } diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManager/include/kit_test_ability_manager_second.h b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManager/include/kit_test_ability_manager_second.h index f6b888f665709c0fe09fe584605dcf8cd82e9420..b3f37084fe0d11d6749853837c52f7274051e9da 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManager/include/kit_test_ability_manager_second.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManager/include/kit_test_ability_manager_second.h @@ -139,6 +139,7 @@ public: void KitTerminateAbility(); KitTestAbilityManagerSecond *kitTestAbility_; }; + } // namespace AppExecFwk } // namespace OHOS #endif // _KIT_TEST_ABILITY_MANAGER_SECOND_H_ diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManager/src/kit_test_ability_manager_second.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManager/src/kit_test_ability_manager_second.cpp index 62025acc4042004bdfc0f4c75a6be4830e98abc6..009b1c10c2a637fd6a655d187ac75b275e0a42bc 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManager/src/kit_test_ability_manager_second.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSTAbilityManager/src/kit_test_ability_manager_second.cpp @@ -36,8 +36,6 @@ bool isMoveMissionToTop = false; int moveMissionToTopCode = -1; bool isClearUpApplicationData = false; int clearUpApplicationDataCode = -1; -int numTwo = 2; -int numThree = 3; } // namespace bool KitTestAbilityManagerSecond::PublishEvent(const std::string &eventName, const int &code, const std::string &data) @@ -112,7 +110,8 @@ void KitTestAbilityManagerSecond::ProcessStateNotEqual( void KitTestAbilityManagerSecond::GetAllStackInfo(MissionStackInfo &missionStackInfo, int stackID) { - StackInfo stackInfo = AbilityManager::GetInstance().GetAllStackInfo(); + StackInfo stackInfo; + stackInfo = AbilityManager::GetInstance().GetAllStackInfo(); for (const auto &stackInfo : stackInfo.missionStackInfos) { if (stackInfo.id == stackID) { missionStackInfo = stackInfo; @@ -207,7 +206,7 @@ void KitTestAbilityManagerSecond::AbilityManagerGetAllStackInfoCase4(int code) GetAllStackInfo(missionStackInfo, 1); bool result = false; if (missionStackInfo.missionRecords.size() == 1) { - result = (missionStackInfo.missionRecords[0].abilityRecordInfos.size() == numTwo); + result = (missionStackInfo.missionRecords[0].abilityRecordInfos.size() == 2); } PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); } @@ -229,9 +228,9 @@ void KitTestAbilityManagerSecond::AbilityManagerQueryRecentAbilityMissionInfoCas { APP_LOGI("KitTestAbilityManagerSecond::AbilityManagerQueryRecentAbilityMissionInfoCase1"); std::vector info; - info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(numThree, RECENT_WITH_EXCLUDED); + info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(3, RECENT_WITH_EXCLUDED); bool result = false; - if (info.size() == 1 && info[0].size == numTwo) { + if (1 == info.size() && 2 == info[0].size) { if (info[0].baseAbility.GetBundleName() == bundleName) { result = true; } @@ -243,9 +242,9 @@ void KitTestAbilityManagerSecond::AbilityManagerQueryRecentAbilityMissionInfoCas { APP_LOGI("KitTestAbilityManagerSecond::AbilityManagerQueryRecentAbilityMissionInfoCase2"); std::vector info; - info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(numThree, RECENT_WITH_EXCLUDED); + info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(3, RECENT_WITH_EXCLUDED); bool result = false; - if (info.size() == 1 && info[0].size == numTwo) { + if (1 == info.size() && 2 == info[0].size) { result = true; } PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); @@ -255,9 +254,9 @@ void KitTestAbilityManagerSecond::AbilityManagerQueryRecentAbilityMissionInfoCas { APP_LOGI("KitTestAbilityManagerSecond::AbilityManagerQueryRecentAbilityMissionInfoCase3"); std::vector info; - info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(numThree, RECENT_WITH_EXCLUDED); + info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(3, RECENT_WITH_EXCLUDED); bool result = false; - if (info.size() == 1 && info[0].size == numTwo) { + if (1 == info.size() && 2 == info[0].size) { if (info[0].baseAbility.GetBundleName() == bundleName && info[0].baseAbility.GetAbilityName() == topAbilityName) { result = true; @@ -271,9 +270,9 @@ void KitTestAbilityManagerSecond::AbilityManagerQueryRunningAbilityMissionInfoCa { APP_LOGI("KitTestAbilityManagerSecond::AbilityManagerQueryRunningAbilityMissionInfoCase1"); std::vector info; - info = AbilityManager::GetInstance().QueryRunningAbilityMissionInfo(numThree); + info = AbilityManager::GetInstance().QueryRunningAbilityMissionInfo(3); bool result = false; - if (info.size() == 1 && info[0].size == numTwo) { + if (1 == info.size() && 2 == info[0].size) { if (info[0].baseAbility.GetBundleName() == bundleName) { result = true; } @@ -285,9 +284,9 @@ void KitTestAbilityManagerSecond::AbilityManagerQueryRunningAbilityMissionInfoCa { APP_LOGI("KitTestAbilityManagerSecond::AbilityManagerQueryRunningAbilityMissionInfoCase2"); std::vector info; - info = AbilityManager::GetInstance().QueryRunningAbilityMissionInfo(numThree); + info = AbilityManager::GetInstance().QueryRunningAbilityMissionInfo(3); bool result = false; - if (info.size() == 1 && info[0].size == numTwo) { + if (1 == info.size() && 2 == info[0].size) { result = true; } PublishEvent(g_respPageManagerAbilityST, code, std::to_string(result)); @@ -297,9 +296,9 @@ void KitTestAbilityManagerSecond::AbilityManagerQueryRunningAbilityMissionInfoCa { APP_LOGI("KitTestAbilityManagerSecond::AbilityManagerQueryRunningAbilityMissionInfoCase3"); std::vector info; - info = AbilityManager::GetInstance().QueryRunningAbilityMissionInfo(numThree); + info = AbilityManager::GetInstance().QueryRunningAbilityMissionInfo(3); bool result = false; - if (info.size() == 1 && info[0].size == numTwo) { + if (1 == info.size() && 2 == info[0].size) { if (info[0].baseAbility.GetBundleName() == bundleName && info[0].baseAbility.GetAbilityName() == topAbilityName) { result = true; @@ -353,7 +352,7 @@ void KitTestAbilityManagerSecond::OnActive() { APP_LOGI("KitTestAbilityManagerSecond::OnActive"); Ability::OnActive(); - if (isMoveMissionToTop == true) { + if (true == isMoveMissionToTop) { PublishEvent(g_respPageManagerAbilityST, moveMissionToTopCode, "1"); isMoveMissionToTop = false; moveMissionToTopCode = -1; @@ -379,10 +378,10 @@ void KitTestAbilityManagerSecond::OnBackground() { APP_LOGI("KitTestAbilityManagerSecond::OnBackground"); Ability::OnBackground(); - if (isMoveMissionToTop == true) { + if (true == isMoveMissionToTop) { std::vector info; - info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(numThree, RECENT_WITH_EXCLUDED); - if (info.size() == 1 && info[0].size == numTwo) { + info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(3, RECENT_WITH_EXCLUDED); + if (1 == info.size() && 2 == info[0].size) { GetAbilityManager()->MoveMissionToTop(info[0].id); APP_LOGI("GetAbilityManager()->MoveMissionToTop(info[0].id);%{public}d", static_cast(info[0].id)); } diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/fifth_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/fifth_ability.h index 45ee85ed58563188e40a036a6e23baece5649037..310b4dfb4c6cd2a114836d5bca7876128bd9d1e8 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/fifth_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/fifth_ability.h @@ -239,6 +239,7 @@ public: FifthAbility *fifthAbility; std::unordered_map> mapTestFunc_; }; + } // namespace AppExecFwk } // namespace OHOS #endif // _SECOND_ABILITY_H_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/fourth_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/fourth_ability.h index c9b3d45e1e95ecbf90176b237e90caee0994aeb1..903d71ac9a7c323868f181f79cf673d33d588536 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/fourth_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/fourth_ability.h @@ -43,7 +43,7 @@ public: bool CompareType(const AAFwk::Skills &skills1, const AAFwk::Skills &skills2); bool CompareWantParams(const AAFwk::Skills &skills1, const AAFwk::Skills &skills2); bool CompareSkills(const AAFwk::Skills &skills1, const AAFwk::Skills &skills2); - template + template void SkillsGetWantParams(M params, int code) { AAFwk::Skills skill; @@ -778,6 +778,7 @@ public: private: std::unordered_map> mapTestFunc_; }; + } // namespace AppExecFwk } // namespace OHOS #endif // _THIRD_ABILITY_H_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/kit_test_ability_manager.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/kit_test_ability_manager.h index 5bdd1a448951d3f760ee841c9ba504485ede99d8..1bc3c529ed1d2eec1a368058024516d4802b4e4b 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/kit_test_ability_manager.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/kit_test_ability_manager.h @@ -189,6 +189,7 @@ private: std::unordered_map> mapTestFunc_; KitTestAbilityManager *kitTestAbility_; }; + } // namespace AppExecFwk } // namespace OHOS -#endif // _KIT_TEST_ABILITY_MANAGER_H_ +#endif //_KIT_TEST_ABILITY_MANAGER_H_ diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/main_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/main_ability.h index ec3e1ed23742f4211ec6b87151860cf7d4313888..268205e3660aff79414556e752ffa3cfc2da0173 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/main_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/main_ability.h @@ -23,6 +23,7 @@ namespace OHOS { namespace AppExecFwk { + class FirstEventSubscriber; class MainAbility : public Ability { public: diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/second_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/second_ability.h index 385591ba2615eeb89a4438756a7ec7d2b8517d7b..d00a9d128cf4f02f8a300db15061ba6809f58b28 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/second_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/second_ability.h @@ -1534,6 +1534,7 @@ public: SecondAbility *secondAbility; std::unordered_map> mapTestFunc_; }; + } // namespace AppExecFwk } // namespace OHOS #endif // _AMS_KIT_SYSTEM_TEST_SECOND_ABILITY_H_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/sixth_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/sixth_ability.h index cf145f0a098b859321a56fff020026d90eafd9bd..cafc175ccd93a09b67aa9625a9d51f199a1d66c8 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/sixth_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/sixth_ability.h @@ -254,6 +254,7 @@ public: private: CallbackCount callbackCount_; }; + } // namespace AppExecFwk } // namespace OHOS #endif // _Six_ABILITY_H_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/test_utils.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/test_utils.h index 0af55daf4ded4319a4da63849373fcf9ba3d4b03..741c48789435a96eabc28bd1306749d03209d116 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/test_utils.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/test_utils.h @@ -34,6 +34,9 @@ public: static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); static Want MakeWant(std::string deviceId, std::string abilityName, std::string bundleName, std::map params); + static std::string ApplicationInfoToString(std::shared_ptr applicationInfo); + static std::string AbilityInfoToString(std::shared_ptr abilityInfo); + static std::string ProcessInfoToString(std::shared_ptr processInfo); static std::vector split(const std::string &in, const std::string &delim); }; } // namespace AppExecFwk diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/third_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/third_ability.h index f83e7bb013421d718a97b190d761cc8ca85cddad..4ce2399a1f747b1b199b72eeb1933df24f9af30a 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/third_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/include/third_ability.h @@ -162,6 +162,7 @@ public: private: std::unordered_map> mapTestFunc_; }; + } // namespace AppExecFwk } // namespace OHOS #endif // _THIRD_ABILITY_H_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/fifth_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/fifth_ability.cpp index a2a1df81f8b7247901bdde73a7256a4830afb7e4..13294bba9686516da807451d333719e798d2de54 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/fifth_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/fifth_ability.cpp @@ -248,7 +248,7 @@ void FifthAbility::WantParamsSetParamCase9(int code) TestUtils::PublishEvent(g_EVENT_RESP_FIFTH, code, std::to_string(result)); } -template +template static void SetArray(const InterfaceID &id, const std::vector &value, sptr &ao) { typename std::vector::size_type size = value.size(); @@ -258,7 +258,7 @@ static void SetArray(const InterfaceID &id, const std::vector &value, sptr +template static void FillArray(IArray *ao, std::vector &array) { auto func = [&](IInterface *object) { array.push_back(T2::Unbox(T3::Query(object))); }; diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/fourth_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/fourth_ability.cpp index c1054ae2265aa4ba65513975bd8d069a500c923f..9a17782414b37c68978c09626939de7c343c109c 100755 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/fourth_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/fourth_ability.cpp @@ -34,6 +34,7 @@ namespace AppExecFwk { using namespace OHOS::EventFwk; using namespace OHOS::AAFwk; namespace { + const std::string normalString = "kitapp.system.test"; // Special string const std::string specialString = "@#¥#//\\%&*_=+[]^:!~();,.'?3243adsafdf_中文"; diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/kit_test_ability_manager.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/kit_test_ability_manager.cpp index 484d0c62b7a7468b0c416d5aa328f957d8e71495..121c03c7696bb58beb078f251156ce2ff66f2ad4 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/kit_test_ability_manager.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/kit_test_ability_manager.cpp @@ -21,8 +21,10 @@ namespace OHOS { namespace AppExecFwk { + using namespace OHOS::EventFwk; using namespace OHOS::AAFwk; + namespace { const std::string bundleName = "com.ohos.amsst.AppKitAbilityManager"; const std::string abilityName = "KitTestAbilityManagerSecond"; @@ -33,7 +35,6 @@ const std::string launchProcessInfo = "com.ix.launcher"; bool isMoveMissionToTop = false; int moveMissionToTopCode = -1; int isClearUpApplicationData = false; -int numThree = 3; } // namespace void KitTestAbilityManager::SubscribeEvent(const vector_conststr &eventList) @@ -533,8 +534,8 @@ void KitTestAbilityManager::OnBackground() Ability::OnBackground(); if (isMoveMissionToTop) { std::vector info; - info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(numThree, RECENT_WITH_EXCLUDED); - if (info.size() == 1 && info[0].size == 1) { + info = AbilityManager::GetInstance().QueryRecentAbilityMissionInfo(3, RECENT_WITH_EXCLUDED); + if (1 == info.size() && 1 == info[0].size) { GetAbilityManager()->MoveMissionToTop(info[0].id); } } diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/main_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/main_ability.cpp index cfd54c7116f9ef39a5078997851729a45e407011..8847d2be14333c1638ae5c070a5f2d6ccc844bc9 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/main_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/main_ability.cpp @@ -162,6 +162,7 @@ void MainAbility::GetAbilityPackageCase1(int code) // get want from empty Want void MainAbility::GetWantCase1(int code) { + Want want; auto getWant = Ability::GetWant(); bool result = getWant == nullptr; TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); @@ -171,6 +172,7 @@ void MainAbility::GetWantCase1(int code) void MainAbility::GetWantCase2(int code) { std::string action = "action"; + Want want; Want setWant; setWant.SetAction(action); Ability::SetWant(setWant); @@ -182,6 +184,7 @@ void MainAbility::GetWantCase2(int code) void MainAbility::GetWantCase3(int code) { std::string action = "action"; + Want want; bool result = true; std::string tmpAction; for (int i = 0; i < pressureTimes; i++) { @@ -214,6 +217,7 @@ void MainAbility::DumpCase1(int code) void MainAbility::SetWantCase1(int code) { std::string empty; + Want want; Want setWant; Ability::SetWant(setWant); bool result = Ability::GetWant()->GetAction() == empty; @@ -224,6 +228,7 @@ void MainAbility::SetWantCase1(int code) void MainAbility::SetWantCase2(int code) { std::string action = "action"; + Want want; std::string tmpAction; for (int i = 0; i < pressureTimes; i++) { Want setWant; diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/second_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/second_ability.cpp index 2f2a3710e19377507e3536aef93df5de7fcfe9d2..1955898e7d234c620a4a4ed20d354f4b80f5fec4 100755 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/second_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/second_ability.cpp @@ -35,7 +35,7 @@ namespace OHOS { namespace AppExecFwk { using namespace AAFwk; using namespace OHOS::EventFwk; -namespace { + constexpr size_t ARRAY_SIZE = 10000; constexpr int LARGE_STR_LEN = 65534; constexpr int SMALL_INT = 5; @@ -46,7 +46,6 @@ constexpr int even = 2; constexpr int index_f = 0; constexpr int index_s = 1; constexpr int index_t = 2; -} bool SecondAbility::CompareWantNoParams(const Want &source, const Want &target) { @@ -1294,7 +1293,7 @@ void SecondAbility::WantRemoveEntityCase2(int code) void SecondAbility::WantRemoveEntityCase3(int code) { Want want; - std::vector entities {"entity1", "entity2", "entity3"}; + std::vector entities{"entity1", "entity2", "entity3"}; bool result = true; for (const auto &entity : entities) { want.AddEntity(entity); @@ -1946,7 +1945,7 @@ void SecondAbility::WantParseUriCase23(int code) bool result = (want != nullptr); if (want != nullptr) { auto parsedValue = want->GetStringArrayParam(key); - result = result && (parsedValue == (std::vector {"aa", "bb", "cc"})); + result = result && (parsedValue == (std::vector{"aa", "bb", "cc"})); delete want; } TestUtils::PublishEvent(g_EVENT_RESP_SECOND, code, std::to_string(result)); @@ -5143,24 +5142,24 @@ void SecondAbility::WantOperationEqualsCase2(int code) OperationBuilder opBuilder; std::vector vec = {"entities1", "entities2"}; auto operation = opBuilder.WithAbilityName("abilityName") - .WithBundleName("bundleName") - .WithDeviceId("deviceId") - .WithAction("action") - .WithEntities(vec) - .WithFlags(1) - .WithUri(Uri("uri")) - .build(); + .WithBundleName("bundleName") + .WithDeviceId("deviceId") + .WithAction("action") + .WithEntities(vec) + .WithFlags(1) + .WithUri(Uri("uri")) + .build(); Want wantOne; wantOne.SetOperation(*operation); OperationBuilder opBuilderTwo; auto operationTwo = opBuilderTwo.WithAbilityName("abilityName2") - .WithBundleName("bundleName") - .WithDeviceId("deviceId") - .WithAction("action") - .WithEntities(vec) - .WithFlags(1) - .WithUri(Uri("uri")) - .build(); + .WithBundleName("bundleName") + .WithDeviceId("deviceId") + .WithAction("action") + .WithEntities(vec) + .WithFlags(1) + .WithUri(Uri("uri")) + .build(); Want wantTwo; wantTwo.SetOperation(*operationTwo); bool result = !wantOne.OperationEquals(wantTwo); @@ -5172,18 +5171,18 @@ void SecondAbility::WantOperationEqualsCase3(int code) { OperationBuilder opBuilder; auto operation = opBuilder.WithAbilityName("abilityName") - .WithBundleName("bundleName") - .WithDeviceId("deviceId") - .WithAction("action") - .build(); + .WithBundleName("bundleName") + .WithDeviceId("deviceId") + .WithAction("action") + .build(); Want wantOne; wantOne.SetOperation(*operation); OperationBuilder opBuilderTwo; auto operationTwo = opBuilderTwo.WithAbilityName("abilityName") - .WithBundleName("bundleName") - .WithDeviceId("deviceId") - .WithAction("action") - .build(); + .WithBundleName("bundleName") + .WithDeviceId("deviceId") + .WithAction("action") + .build(); Want wantTwo; wantTwo.SetOperation(*operationTwo); bool result = wantOne.OperationEquals(wantTwo); @@ -5195,10 +5194,10 @@ void SecondAbility::WantOperationEqualsCase4(int code) { OperationBuilder opBuilder; auto operation = opBuilder.WithAbilityName("abilityName" + std::to_string(pressureTimes - 1)) - .WithBundleName("bundleName") - .WithDeviceId("deviceId") - .WithAction("action") - .build(); + .WithBundleName("bundleName") + .WithDeviceId("deviceId") + .WithAction("action") + .build(); Want wantOne; wantOne.SetOperation(*operation); Want wantTwo; @@ -5207,10 +5206,10 @@ void SecondAbility::WantOperationEqualsCase4(int code) bool result = true; for (int i = 0; i < pressureTimes; i++) { operationTwo = opBuilderTwo.WithAbilityName("abilityName" + std::to_string(i)) - .WithBundleName("bundleName") - .WithDeviceId("deviceId") - .WithAction("action") - .build(); + .WithBundleName("bundleName") + .WithDeviceId("deviceId") + .WithAction("action") + .build(); wantTwo.SetOperation(*operationTwo); if (i == pressureTimes - 1) { result = result && wantOne.OperationEquals(wantTwo); @@ -5239,10 +5238,10 @@ void SecondAbility::WantCloneOperationCase2(int code) { OperationBuilder opBuilder; auto operation = opBuilder.WithAbilityName("abilityName") - .WithBundleName("bundleName") - .WithDeviceId("deviceId") - .WithAction("action") - .build(); + .WithBundleName("bundleName") + .WithDeviceId("deviceId") + .WithAction("action") + .build(); Want want; want.SetOperation(*operation); Want *wantClone = want.CloneOperation(); diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/sixth_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/sixth_ability.cpp index e47f52510313182dac419e7c7eb224ab34391b03..4b61a8c75357304e0ce910ff4aea54f85d97d546 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/sixth_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/sixth_ability.cpp @@ -26,8 +26,6 @@ using namespace OHOS::EventFwk; namespace { const int cycleCount = 1000; -const int paramCnt = 3; -const int caseIndx = 2; } // namespace #define APPREGISTERABILITYLIFECYCALLBACK(onAbilityFunctionName, getAbilityCountFunction, expected, code) \ @@ -468,9 +466,9 @@ void KitTestSixEventSubscriber::OnReceiveEvent(const CommonEventData &data) auto target = data.GetData(); vector_str splitResult = TestUtils::split(target, "_"); auto keyMap = splitResult.at(0); - if (mapTestFunc_.find(keyMap) != mapTestFunc_.end() && splitResult.size() >= paramCnt) { + if (mapTestFunc_.find(keyMap) != mapTestFunc_.end() && splitResult.size() >= 3) { auto apiIndex = atoi(splitResult.at(1).c_str()); - auto caseIndex = atoi(splitResult.at(caseIndx).c_str()); + auto caseIndex = atoi(splitResult.at(2).c_str()); mapTestFunc_[keyMap](apiIndex, caseIndex, data.GetCode()); } else { if (keyMap == "TerminateAbility") { diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/test_utils.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/test_utils.cpp index 1f7fa556737647aecddbe3a8190286ad772fbb23..b9d744c1e6d8458333507c763ca7ce47487e382d 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/test_utils.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTest/src/test_utils.cpp @@ -45,12 +45,85 @@ Want TestUtils::MakeWant( return want; } +std::string TestUtils::ApplicationInfoToString(std::shared_ptr applicationInfo) +{ + std::stringstream sstream; + sstream << "name:" << applicationInfo->name << ","; + sstream << "bundleName:" << applicationInfo->bundleName << ","; + sstream << "description:" << applicationInfo->description << ","; + sstream << "iconPath:" << applicationInfo->iconPath << ","; + sstream << "label:" << applicationInfo->label << ","; + sstream << "deviceId:" << applicationInfo->deviceId << ","; + sstream << "signatureKey:" << applicationInfo->signatureKey << ","; + sstream << "isSystemApp:" << std::boolalpha << applicationInfo->isSystemApp << ","; + sstream << "isLauncherApp:" << applicationInfo->isLauncherApp << ","; + sstream << "supportedModes:" << applicationInfo->supportedModes << ","; + sstream << "process:" << applicationInfo->process << ","; + std::string permissions = + std::accumulate(applicationInfo->permissions.begin(), applicationInfo->permissions.end(), std::string(",")); + sstream << "permissions:" << permissions << ","; + std::string moduleSourceDirs = std::accumulate( + applicationInfo->moduleSourceDirs.begin(), applicationInfo->moduleSourceDirs.end(), std::string(",")); + sstream << "moduleSourceDirs:" << moduleSourceDirs << ","; + sstream << "entryDir:" << applicationInfo->entryDir << ","; + sstream << "codePath:" << applicationInfo->codePath << ","; + sstream << "dataDir:" << applicationInfo->dataDir << ","; + sstream << "dataBaseDir:" << applicationInfo->dataBaseDir << ","; + sstream << "cacheDir:" << applicationInfo->cacheDir; + return sstream.str(); +} + +std::string TestUtils::AbilityInfoToString(std::shared_ptr abilityInfo) +{ + std::stringstream sstream; + sstream << "name:" << abilityInfo->name << ","; + sstream << "label:" << abilityInfo->label << ","; + sstream << "description:" << abilityInfo->description << ","; + sstream << "iconPath:" << abilityInfo->iconPath << ","; + sstream << "visible:" << std::boolalpha << abilityInfo->visible << ","; + sstream << "kind:" << abilityInfo->kind << ","; + auto type = static_cast::type>(abilityInfo->type); + sstream << "type:" << type << ","; + auto orientation = + static_cast::type>(abilityInfo->orientation); + sstream << "orientation:" << orientation << ","; + auto launchMode = static_cast::type>(abilityInfo->launchMode); + sstream << "launchMode:" << launchMode << ","; + std::string permissions = + std::accumulate(abilityInfo->permissions.begin(), abilityInfo->permissions.end(), std::string(",")); + sstream << "permissions:" << permissions << ","; + sstream << "process:" << abilityInfo->process << ","; + std::string deviceTypes = + std::accumulate(abilityInfo->deviceTypes.begin(), abilityInfo->deviceTypes.end(), std::string(",")); + sstream << "deviceTypes:" << deviceTypes << ","; + std::string deviceCapabilities = std::accumulate( + abilityInfo->deviceCapabilities.begin(), abilityInfo->deviceCapabilities.end(), std::string(",")); + sstream << "deviceCapabilities:" << deviceCapabilities << ","; + sstream << "uri:" << abilityInfo->uri << ","; + sstream << "package:" << abilityInfo->package << ","; + sstream << "bundleName:" << abilityInfo->bundleName << ","; + sstream << "moduleName:" << abilityInfo->moduleName << ","; + sstream << "applicationName:" << abilityInfo->applicationName << ","; + sstream << "deviceId:" << abilityInfo->deviceId << ","; + sstream << "codePath:" << abilityInfo->codePath << ","; + sstream << "resourcePath:" << abilityInfo->resourcePath << ","; + sstream << "libPath:" << abilityInfo->libPath; + return sstream.str(); +} + +std::string TestUtils::ProcessInfoToString(std::shared_ptr processInfo) +{ + std::stringstream sstream; + sstream << "pid:" << processInfo->GetPid() << ","; + sstream << "processName:" << processInfo->GetProcessName(); + return sstream.str(); +} + std::vector TestUtils::split(const std::string &in, const std::string &delim) { std::regex reg(delim); std::vector res = { - std::sregex_token_iterator(in.begin(), in.end(), reg, -1), std::sregex_token_iterator() - }; + std::sregex_token_iterator(in.begin(), in.end(), reg, -1), std::sregex_token_iterator()}; return res; } } // namespace AppExecFwk diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/main_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/main_ability.h index cec4a093d9e97579b656e85fec1e7c5a6788c0d6..f77383f16b8aca1809e2c3573e09ace3dff92cfc 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/main_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/main_ability.h @@ -113,11 +113,9 @@ public: void GetApplicationContextCase1(int code); - std::unordered_map>> mapCase_; - ~MainAbility(); - - void initCaseFirst() { - std::unordered_map>> first = { + MainAbility() + { + mapCase_ = { {(int)AbilityContextApi::GetApplicationInfo, { [this](int code) { GetApplicationInfoCase1(code); }, @@ -148,12 +146,6 @@ public: [this](int code) { GetDataDirCase2(code); }, [this](int code) { GetDataDirCase3(code); }, }}, - }; - mapCase_.insert(first.begin(), first.end()); - } - - void initCaseSecond() { - std::unordered_map>> second = { {(int)AbilityContextApi::GetDir, { [this](int code) { GetDirCase1(code); }, @@ -196,12 +188,6 @@ public: { [this](int code) { GetContextCase1(code); }, }}, - }; - mapCase_.insert(second.begin(), second.end()); - } - - void initCaseThird() { - std::unordered_map>> third = { {(int)AbilityContextApi::GetAbilityManager, { [this](int code) { GetAbilityManagerCase1(code); }, @@ -246,15 +232,10 @@ public: [this](int code) { GetHapModuleInfoCase3(code); }, }}, }; - mapCase_.insert(third.begin(), third.end()); } - MainAbility() - { - initCaseFirst(); - initCaseSecond(); - initCaseThird(); - } + std::unordered_map>> mapCase_; + ~MainAbility(); protected: void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/second_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/second_ability.h index aa64ae6499c1fbfeda7139581bbf41881f315aca..2070529579d563e5202623790d100cd374851610 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/second_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/second_ability.h @@ -115,13 +115,7 @@ public: SecondAbility() { - initCaseFirst(); - initCaseSecond(); - initCaseThird(); - } - - void initCaseFirst() { - std::unordered_map>> first = { + mapCase_ = { {(int)AbilityContextApi::GetApplicationInfo, { [this](int code) { GetApplicationInfoCase1(code); }, @@ -152,12 +146,12 @@ public: [this](int code) { GetDataDirCase2(code); }, [this](int code) { GetDataDirCase3(code); }, }}, - }; - mapCase_.insert(first.begin(), first.end()); - } - - void initCaseSecond() { - std::unordered_map>> second = { + {(int)AbilityContextApi::GetDir, + { + [this](int code) { GetDirCase1(code); }, + [this](int code) { GetDirCase2(code); }, + [this](int code) { GetDirCase3(code); }, + }}, {(int)AbilityContextApi::GetBundleManager, { [this](int code) { GetBundleManagerCase1(code); }, @@ -194,12 +188,6 @@ public: { [this](int code) { GetContextCase1(code); }, }}, - }; - mapCase_.insert(second.begin(), second.end()); - } - - void initCaseThird() { - std::unordered_map>> third = { {(int)AbilityContextApi::GetAbilityManager, { [this](int code) { GetAbilityManagerCase1(code); }, @@ -244,8 +232,8 @@ public: [this](int code) { GetHapModuleInfoCase3(code); }, }}, }; - mapCase_.insert(third.begin(), third.end()); } + std::unordered_map>> mapCase_; int callingTime = 0; ~SecondAbility(); diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/test_utils.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/test_utils.h index 64b40f888ec52c9ea73da85d972d20bc734ad447..8d2303da0503acfcbbc8b45d187b11003da431b9 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/test_utils.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/include/test_utils.h @@ -34,6 +34,9 @@ public: static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); static Want MakeWant(std::string deviceId, std::string abilityName, std::string bundleName, std::map params); + static std::string ApplicationInfoToString(std::shared_ptr applicationInfo); + static std::string AbilityInfoToString(std::shared_ptr abilityInfo); + static std::string ProcessInfoToString(std::shared_ptr processInfo); static std::vector split(const std::string &in, const std::string &delim); }; } // namespace AppExecFwk diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/main_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/main_ability.cpp index 241f5a44d2d365ad3eb31f4e323afae00b6bb164..a4f3df5d30f4137f0d0c29a4e009327afb472098 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/main_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/main_ability.cpp @@ -20,13 +20,8 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; -namespace { + const int MainAbilityACode = 100; -constexpr int index_f = 0; -constexpr int index_s = 1; -constexpr int index_t = 2; -constexpr int numThree = 3; -} void MainAbility::Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, @@ -131,11 +126,11 @@ void FirstEventSubscriber::OnReceiveEvent(const CommonEventData &data) if (std::strcmp(eventName.c_str(), g_EVENT_REQU_FIRST.c_str()) == 0) { auto target = data.GetData(); auto caseInfo = TestUtils::split(target, "_"); - if (caseInfo.size() < numThree) { + if (caseInfo.size() < 3) { return; } - if (mapTestFunc_.find(caseInfo[index_f]) != mapTestFunc_.end()) { - mapTestFunc_[caseInfo[index_f]](std::stoi(caseInfo[index_s]), std::stoi(caseInfo[index_t]), data.GetCode()); + if (mapTestFunc_.find(caseInfo[0]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[0]](std::stoi(caseInfo[1]), std::stoi(caseInfo[2]), data.GetCode()); } else { APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); } @@ -155,8 +150,10 @@ void MainAbility::TestAbility(int apiIndex, int caseIndex, int code) void MainAbility::GetApplicationInfoCase1(int code) { auto appInfo = AbilityContext::GetApplicationInfo(); + string appInfoStr = ""; string result = ""; if (appInfo != nullptr) { + appInfoStr = TestUtils::ApplicationInfoToString(appInfo); result = appInfo->name; } @@ -165,8 +162,10 @@ void MainAbility::GetApplicationInfoCase1(int code) void MainAbility::GetApplicationInfoCase2(int code) { auto appInfo = AbilityContext::GetApplicationInfo(); + string appInfoStr = ""; string result = ""; if (appInfo != nullptr) { + appInfoStr = TestUtils::ApplicationInfoToString(appInfo); result = appInfo->name; } @@ -175,8 +174,10 @@ void MainAbility::GetApplicationInfoCase2(int code) void MainAbility::GetApplicationInfoCase3(int code) { auto appInfo = AbilityContext::GetApplicationInfo(); + string appInfoStr = ""; string result = ""; if (appInfo != nullptr) { + appInfoStr = TestUtils::ApplicationInfoToString(appInfo); result = appInfo->name; } @@ -391,8 +392,10 @@ void MainAbility::GetAbilityManagerCase1(int code) void MainAbility::GetProcessInfoCase1(int code) { auto processInfo = AbilityContext::GetProcessInfo(); + string processInfoStr = ""; string result = ""; if (processInfo != nullptr) { + processInfoStr = TestUtils::ProcessInfoToString(processInfo); result = processInfo->GetProcessName(); } @@ -402,8 +405,10 @@ void MainAbility::GetProcessInfoCase1(int code) void MainAbility::GetProcessInfoCase2(int code) { auto processInfo = AbilityContext::GetProcessInfo(); + string processInfoStr = ""; string result = ""; if (processInfo != nullptr) { + processInfoStr = TestUtils::ProcessInfoToString(processInfo); result = processInfo->GetProcessName(); } @@ -413,8 +418,10 @@ void MainAbility::GetProcessInfoCase2(int code) void MainAbility::GetProcessInfoCase3(int code) { auto processInfo = AbilityContext::GetProcessInfo(); + string processInfoStr = ""; string result = ""; if (processInfo != nullptr) { + processInfoStr = TestUtils::ProcessInfoToString(processInfo); result = processInfo->GetProcessName(); } diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/second_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/second_ability.cpp index 70aa48177ed9dcee0083fe94206c63455d30d707..775f91de81484de99ad075cd034e7c56464fa541 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/second_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/second_ability.cpp @@ -20,13 +20,8 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; -namespace { + const int SecondAbilityACode = 200; -constexpr int index_f = 0; -constexpr int index_s = 1; -constexpr int index_t = 2; -constexpr int numThree = 3; -} void SecondAbility::Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, @@ -131,11 +126,11 @@ void SecondEventSubscriber::OnReceiveEvent(const CommonEventData &data) if (std::strcmp(eventName.c_str(), g_EVENT_REQU_SECOND.c_str()) == 0) { auto target = data.GetData(); auto caseInfo = TestUtils::split(target, "_"); - if (caseInfo.size() < numThree) { + if (caseInfo.size() < 3) { return; } - if (mapTestFunc_.find(caseInfo[index_f]) != mapTestFunc_.end()) { - mapTestFunc_[caseInfo[index_f]](std::stoi(caseInfo[index_s]), std::stoi(caseInfo[index_t]), data.GetCode()); + if (mapTestFunc_.find(caseInfo[0]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[0]](std::stoi(caseInfo[1]), std::stoi(caseInfo[2]), data.GetCode()); } else { APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); } @@ -157,8 +152,10 @@ void SecondAbility::GetApplicationInfoCase1(int code) void SecondAbility::GetApplicationInfoCase2(int code) { auto appInfo = AbilityContext::GetApplicationInfo(); + string appInfoStr = ""; string result = ""; if (appInfo != nullptr) { + appInfoStr = TestUtils::ApplicationInfoToString(appInfo); result = appInfo->name; } @@ -308,8 +305,10 @@ void SecondAbility::GetProcessInfoCase1(int code) void SecondAbility::GetProcessInfoCase2(int code) { auto processInfo = AbilityContext::GetProcessInfo(); + string processInfoStr = ""; string result = ""; if (processInfo != nullptr) { + processInfoStr = TestUtils::ProcessInfoToString(processInfo); result = processInfo->GetProcessName(); } diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/test_utils.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/test_utils.cpp index 3e75bdf815379f71af430ad9d5c979da62400675..48a7ea6b0e9e382b37cda3da859643a0f2928093 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/test_utils.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestA/src/test_utils.cpp @@ -45,12 +45,85 @@ Want TestUtils::MakeWant( return want; } +std::string TestUtils::ApplicationInfoToString(std::shared_ptr applicationInfo) +{ + std::stringstream sstream; + sstream << "name:" << applicationInfo->name << ","; + sstream << "bundleName:" << applicationInfo->bundleName << ","; + sstream << "description:" << applicationInfo->description << ","; + sstream << "iconPath:" << applicationInfo->iconPath << ","; + sstream << "label:" << applicationInfo->label << ","; + sstream << "deviceId:" << applicationInfo->deviceId << ","; + sstream << "signatureKey:" << applicationInfo->signatureKey << ","; + sstream << "isSystemApp:" << std::boolalpha << applicationInfo->isSystemApp << ","; + sstream << "isLauncherApp:" << applicationInfo->isLauncherApp << ","; + sstream << "supportedModes:" << applicationInfo->supportedModes << ","; + sstream << "process:" << applicationInfo->process << ","; + std::string permissions = + std::accumulate(applicationInfo->permissions.begin(), applicationInfo->permissions.end(), std::string(",")); + sstream << "permissions:" << permissions << ","; + std::string moduleSourceDirs = std::accumulate( + applicationInfo->moduleSourceDirs.begin(), applicationInfo->moduleSourceDirs.end(), std::string(",")); + sstream << "moduleSourceDirs:" << moduleSourceDirs << ","; + sstream << "entryDir:" << applicationInfo->entryDir << ","; + sstream << "codePath:" << applicationInfo->codePath << ","; + sstream << "dataDir:" << applicationInfo->dataDir << ","; + sstream << "dataBaseDir:" << applicationInfo->dataBaseDir << ","; + sstream << "cacheDir:" << applicationInfo->cacheDir; + return sstream.str(); +} + +std::string TestUtils::AbilityInfoToString(std::shared_ptr abilityInfo) +{ + std::stringstream sstream; + sstream << "name:" << abilityInfo->name << ","; + sstream << "label:" << abilityInfo->label << ","; + sstream << "description:" << abilityInfo->description << ","; + sstream << "iconPath:" << abilityInfo->iconPath << ","; + sstream << "visible:" << std::boolalpha << abilityInfo->visible << ","; + sstream << "kind:" << abilityInfo->kind << ","; + auto type = static_cast::type>(abilityInfo->type); + sstream << "type:" << type << ","; + auto orientation = + static_cast::type>(abilityInfo->orientation); + sstream << "orientation:" << orientation << ","; + auto launchMode = static_cast::type>(abilityInfo->launchMode); + sstream << "launchMode:" << launchMode << ","; + std::string permissions = + std::accumulate(abilityInfo->permissions.begin(), abilityInfo->permissions.end(), std::string(",")); + sstream << "permissions:" << permissions << ","; + sstream << "process:" << abilityInfo->process << ","; + std::string deviceTypes = + std::accumulate(abilityInfo->deviceTypes.begin(), abilityInfo->deviceTypes.end(), std::string(",")); + sstream << "deviceTypes:" << deviceTypes << ","; + std::string deviceCapabilities = std::accumulate( + abilityInfo->deviceCapabilities.begin(), abilityInfo->deviceCapabilities.end(), std::string(",")); + sstream << "deviceCapabilities:" << deviceCapabilities << ","; + sstream << "uri:" << abilityInfo->uri << ","; + sstream << "package:" << abilityInfo->package << ","; + sstream << "bundleName:" << abilityInfo->bundleName << ","; + sstream << "moduleName:" << abilityInfo->moduleName << ","; + sstream << "applicationName:" << abilityInfo->applicationName << ","; + sstream << "deviceId:" << abilityInfo->deviceId << ","; + sstream << "codePath:" << abilityInfo->codePath << ","; + sstream << "resourcePath:" << abilityInfo->resourcePath << ","; + sstream << "libPath:" << abilityInfo->libPath; + return sstream.str(); +} + +std::string TestUtils::ProcessInfoToString(std::shared_ptr processInfo) +{ + std::stringstream sstream; + sstream << "pid:" << processInfo->GetPid() << ","; + sstream << "processName:" << processInfo->GetProcessName(); + return sstream.str(); +} + std::vector TestUtils::split(const std::string &in, const std::string &delim) { - std::regex reg {delim}; - return std::vector { - std::sregex_token_iterator(in.begin(), in.end(), reg, -1), std::sregex_token_iterator() - }; + std::regex reg{delim}; + return std::vector{ + std::sregex_token_iterator(in.begin(), in.end(), reg, -1), std::sregex_token_iterator()}; } } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/include/main_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/include/main_ability.h index b68fb8b68e98a7f228740a8d63dd1791fd6ae511..a14c52c2f06a74ba810052457e9dfa8e9bd34477 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/include/main_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/include/main_ability.h @@ -112,14 +112,7 @@ public: MainAbility() { - initCaseFirst(); - initCaseSecond(); - initCaseThird(); - } - - void initCaseFirst() - { - std::unordered_map>> testCase = { + mapCase_ = { {(int)AbilityContextApi::GetApplicationInfo, { [this](int code) { GetApplicationInfoCase1(code); }, @@ -150,13 +143,6 @@ public: [this](int code) { GetDataDirCase2(code); }, [this](int code) { GetDataDirCase3(code); }, }}, - }; - mapCase_.insert(testCase.begin(), testCase.end()); - } - - void initCaseSecond() - { - std::unordered_map>> testCase = { {(int)AbilityContextApi::GetDir, { [this](int code) { GetDirCase1(code); }, @@ -199,13 +185,6 @@ public: { [this](int code) { GetContextCase1(code); }, }}, - }; - mapCase_.insert(testCase.begin(), testCase.end()); - } - - void initCaseThird() - { - std::unordered_map>> testCase = { {(int)AbilityContextApi::GetAbilityManager, { [this](int code) { GetAbilityManagerCase1(code); }, @@ -250,7 +229,6 @@ public: [this](int code) { GetHapModuleInfoCase3(code); }, }}, }; - mapCase_.insert(testCase.begin(), testCase.end()); } void SubscribeEvent(); void TestAbility(int apiIndex, int caseIndex, int code); diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/include/test_utils.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/include/test_utils.h index 64b40f888ec52c9ea73da85d972d20bc734ad447..8d2303da0503acfcbbc8b45d187b11003da431b9 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/include/test_utils.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/include/test_utils.h @@ -34,6 +34,9 @@ public: static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); static Want MakeWant(std::string deviceId, std::string abilityName, std::string bundleName, std::map params); + static std::string ApplicationInfoToString(std::shared_ptr applicationInfo); + static std::string AbilityInfoToString(std::shared_ptr abilityInfo); + static std::string ProcessInfoToString(std::shared_ptr processInfo); static std::vector split(const std::string &in, const std::string &delim); }; } // namespace AppExecFwk diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/src/main_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/src/main_ability.cpp index c2411fd614d05c2998f280ec91b46e92bf1fd754..aa08cabf14c914211188697cd65e00572460f8ea 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/src/main_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/src/main_ability.cpp @@ -20,13 +20,8 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; -namespace { + const int MainAbilityBCode = 300; -constexpr int index_f = 0; -constexpr int index_s = 1; -constexpr int index_t = 2; -constexpr int numThree = 3; -} void MainAbility::Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, @@ -131,11 +126,11 @@ void FirstEventSubscriber::OnReceiveEvent(const CommonEventData &data) if (std::strcmp(eventName.c_str(), g_EVENT_REQU_FIRSTB.c_str()) == 0) { auto target = data.GetData(); auto caseInfo = TestUtils::split(target, "_"); - if (caseInfo.size() < numThree) { + if (caseInfo.size() < 3) { return; } - if (mapTestFunc_.find(caseInfo[index_f]) != mapTestFunc_.end()) { - mapTestFunc_[caseInfo[index_f]](std::stoi(caseInfo[index_s]), std::stoi(caseInfo[index_t]), data.GetCode()); + if (mapTestFunc_.find(caseInfo[0]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[0]](std::stoi(caseInfo[1]), std::stoi(caseInfo[2]), data.GetCode()); } else { APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); } @@ -163,8 +158,10 @@ void MainAbility::GetApplicationInfoCase2(int code) void MainAbility::GetApplicationInfoCase3(int code) { auto appInfo = AbilityContext::GetApplicationInfo(); + string appInfoStr = ""; string result = ""; if (appInfo != nullptr) { + appInfoStr = TestUtils::ApplicationInfoToString(appInfo); result = appInfo->name; } @@ -360,8 +357,10 @@ void MainAbility::GetProcessInfoCase2(int code) void MainAbility::GetProcessInfoCase3(int code) { auto processInfo = AbilityContext::GetProcessInfo(); + string processInfoStr = ""; string result = ""; if (processInfo != nullptr) { + processInfoStr = TestUtils::ProcessInfoToString(processInfo); result = processInfo->GetProcessName(); } diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/src/test_utils.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/src/test_utils.cpp index 07ebf00c47128276f0e83d0aa5783fec0a417147..48a7ea6b0e9e382b37cda3da859643a0f2928093 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/src/test_utils.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestB/src/test_utils.cpp @@ -45,6 +45,80 @@ Want TestUtils::MakeWant( return want; } +std::string TestUtils::ApplicationInfoToString(std::shared_ptr applicationInfo) +{ + std::stringstream sstream; + sstream << "name:" << applicationInfo->name << ","; + sstream << "bundleName:" << applicationInfo->bundleName << ","; + sstream << "description:" << applicationInfo->description << ","; + sstream << "iconPath:" << applicationInfo->iconPath << ","; + sstream << "label:" << applicationInfo->label << ","; + sstream << "deviceId:" << applicationInfo->deviceId << ","; + sstream << "signatureKey:" << applicationInfo->signatureKey << ","; + sstream << "isSystemApp:" << std::boolalpha << applicationInfo->isSystemApp << ","; + sstream << "isLauncherApp:" << applicationInfo->isLauncherApp << ","; + sstream << "supportedModes:" << applicationInfo->supportedModes << ","; + sstream << "process:" << applicationInfo->process << ","; + std::string permissions = + std::accumulate(applicationInfo->permissions.begin(), applicationInfo->permissions.end(), std::string(",")); + sstream << "permissions:" << permissions << ","; + std::string moduleSourceDirs = std::accumulate( + applicationInfo->moduleSourceDirs.begin(), applicationInfo->moduleSourceDirs.end(), std::string(",")); + sstream << "moduleSourceDirs:" << moduleSourceDirs << ","; + sstream << "entryDir:" << applicationInfo->entryDir << ","; + sstream << "codePath:" << applicationInfo->codePath << ","; + sstream << "dataDir:" << applicationInfo->dataDir << ","; + sstream << "dataBaseDir:" << applicationInfo->dataBaseDir << ","; + sstream << "cacheDir:" << applicationInfo->cacheDir; + return sstream.str(); +} + +std::string TestUtils::AbilityInfoToString(std::shared_ptr abilityInfo) +{ + std::stringstream sstream; + sstream << "name:" << abilityInfo->name << ","; + sstream << "label:" << abilityInfo->label << ","; + sstream << "description:" << abilityInfo->description << ","; + sstream << "iconPath:" << abilityInfo->iconPath << ","; + sstream << "visible:" << std::boolalpha << abilityInfo->visible << ","; + sstream << "kind:" << abilityInfo->kind << ","; + auto type = static_cast::type>(abilityInfo->type); + sstream << "type:" << type << ","; + auto orientation = + static_cast::type>(abilityInfo->orientation); + sstream << "orientation:" << orientation << ","; + auto launchMode = static_cast::type>(abilityInfo->launchMode); + sstream << "launchMode:" << launchMode << ","; + std::string permissions = + std::accumulate(abilityInfo->permissions.begin(), abilityInfo->permissions.end(), std::string(",")); + sstream << "permissions:" << permissions << ","; + sstream << "process:" << abilityInfo->process << ","; + std::string deviceTypes = + std::accumulate(abilityInfo->deviceTypes.begin(), abilityInfo->deviceTypes.end(), std::string(",")); + sstream << "deviceTypes:" << deviceTypes << ","; + std::string deviceCapabilities = std::accumulate( + abilityInfo->deviceCapabilities.begin(), abilityInfo->deviceCapabilities.end(), std::string(",")); + sstream << "deviceCapabilities:" << deviceCapabilities << ","; + sstream << "uri:" << abilityInfo->uri << ","; + sstream << "package:" << abilityInfo->package << ","; + sstream << "bundleName:" << abilityInfo->bundleName << ","; + sstream << "moduleName:" << abilityInfo->moduleName << ","; + sstream << "applicationName:" << abilityInfo->applicationName << ","; + sstream << "deviceId:" << abilityInfo->deviceId << ","; + sstream << "codePath:" << abilityInfo->codePath << ","; + sstream << "resourcePath:" << abilityInfo->resourcePath << ","; + sstream << "libPath:" << abilityInfo->libPath; + return sstream.str(); +} + +std::string TestUtils::ProcessInfoToString(std::shared_ptr processInfo) +{ + std::stringstream sstream; + sstream << "pid:" << processInfo->GetPid() << ","; + sstream << "processName:" << processInfo->GetProcessName(); + return sstream.str(); +} + std::vector TestUtils::split(const std::string &in, const std::string &delim) { std::regex reg{delim}; diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/BUILD.gn index be5a60832a5414c421b41a781a3742cc1bb7749a..a93204d5740e197743574aa84e5ecb10dda1976b 100755 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/BUILD.gn @@ -60,6 +60,8 @@ ohos_shared_library("amsKitSystemTestDataA") { "${innerkits_path}/appexecfwk_core:appexecfwk_core", "${kits_path}:appkit_native", "${services_path}/bundlemgr:libbms", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_dataability:native_dataability", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb:native_rdb", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a1.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a1.cpp index 621ddef3b4703611779d11fdafeeda052f66b9ce..0f7422cd9c360e4c484eef845855c2953ef7cce2 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a1.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a1.cpp @@ -23,7 +23,6 @@ namespace OHOS { namespace AppExecFwk { -namespace { static const int ABILITY_DATA_CODE = 250; static const int LIFECYCLE_CALLBACKS = 251; static const int LIFECYCLE_OBSERVER = 252; @@ -41,8 +40,6 @@ static const int DEFAULT_DELETE_RESULT = 2222; static const int DEFAULT_UPDATE_RESULT = 3333; static const std::string ABILITY_TYPE_PAGE = "0"; static const std::string ABILITY_TYPE_DATA = "2"; -constexpr int charCnt = 5; -} void AmsStKitDataAbilityDataA1LifecycleCallbacks::OnAbilityStart(const std::shared_ptr &ability) { @@ -302,7 +299,7 @@ std::vector AmsStKitDataAbilityDataA1::GetFileTypes(const Uri &uri, { APP_LOGI("AmsStKitDataAbilityDataA1 <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_CODE, "GetFileTypes"); - std::vector fileType {"filetypes"}; + std::vector fileType{"filetypes"}; return fileType; } @@ -338,7 +335,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt AmsStKitDataAbilityDataA1 *mainAbility, Uri dataAbilityUri, string &result) { AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); @@ -363,10 +360,9 @@ static void GetResult(std::shared_ptr child, std::shared_pt return; } result = std::to_string(fd); - char str[charCnt]; - if (!feof(file)) { - fgets(str, charCnt, file); - } + char str[5]; + if (!feof(file)) + fgets(str, 5, file); result = str; fclose(file); } else if (child->GetOperatorName() == OPERATOR_GETTYPE) { @@ -384,7 +380,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt void KitTestDataA1EventSubscriber::TestPost(const std::string funName) { - STtools::StOperator allOperator {}; + STtools::StOperator allOperator{}; STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); std::shared_ptr helper = DataAbilityHelper::Creator(mainAbility_->GetContext()); for (auto child : allOperator.GetChildOperator()) { diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a2.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a2.cpp index 9153f1ed291cdc3e66583ccaee2ad3cc980b670a..14a461985112bcb31c0984d7676199910a0c9dd5 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a2.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a2.cpp @@ -23,7 +23,6 @@ namespace OHOS { namespace AppExecFwk { -namespace { static const int ABILITY_DATA_CODE = 260; static const int LIFECYCLE_CALLBACKS = 261; static const int LIFECYCLE_OBSERVER = 262; @@ -39,8 +38,6 @@ static const int DEFAULT_DELETE_RESULT = 2222; static const int DEFAULT_UPDATE_RESULT = 3333; static const std::string ABILITY_TYPE_PAGE = "0"; static const std::string ABILITY_TYPE_DATA = "2"; -constexpr int charCnt = 5; -} void AmsStKitDataAbilityDataA2LifecycleCallbacks::OnAbilityStart(const std::shared_ptr &ability) { @@ -299,7 +296,7 @@ std::vector AmsStKitDataAbilityDataA2::GetFileTypes(const Uri &uri, { APP_LOGI("AmsStKitDataAbilityDataA2 <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_CODE, "GetFileTypes"); - std::vector fileType {"filetypes"}; + std::vector fileType{"filetypes"}; return fileType; } @@ -337,7 +334,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt AmsStKitDataAbilityDataA2 *mainAbility, Uri dataAbilityUri, string &result) { AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); @@ -362,10 +359,9 @@ static void GetResult(std::shared_ptr child, std::shared_pt return; } result = std::to_string(fd); - char str[charCnt]; - if (!feof(file)) { - fgets(str, charCnt, file); - } + char str[5]; + if (!feof(file)) + fgets(str, 5, file); result = str; fclose(file); } else if (child->GetOperatorName() == OPERATOR_GETTYPE) { @@ -376,7 +372,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt void KitTestDataA2EventSubscriber::TestPost(const std::string funName) { - STtools::StOperator allOperator {}; + STtools::StOperator allOperator{}; STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); std::shared_ptr helper = DataAbilityHelper::Creator(mainAbility_->GetContext()); for (auto child : allOperator.GetChildOperator()) { diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a3.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a3.cpp index 4ba9c1f21c97c90d38ebe8595b1f13e2fa485589..fb6599f935e07b4814f38f9aa8dd9637271a641f 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a3.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_data_a3.cpp @@ -23,7 +23,6 @@ namespace OHOS { namespace AppExecFwk { -namespace { static const int ABILITY_DATA_CODE = 290; static const int LIFECYCLE_CALLBACKS = 291; static const int LIFECYCLE_OBSERVER = 292; @@ -39,8 +38,6 @@ static const int DEFAULT_DELETE_RESULT = 2222; static const int DEFAULT_UPDATE_RESULT = 3333; static const std::string ABILITY_TYPE_PAGE = "0"; static const std::string ABILITY_TYPE_DATA = "2"; -constexpr int charCnt = 5; -} void AmsStKitDataAbilityDataA3LifecycleCallbacks::OnAbilityStart(const std::shared_ptr &ability) { @@ -302,7 +299,7 @@ std::vector AmsStKitDataAbilityDataA3::GetFileTypes(const Uri &uri, { APP_LOGI("AmsStKitDataAbilityDataA3 <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_CODE, "GetFileTypes"); - std::vector fileType {"filetypes"}; + std::vector fileType{"filetypes"}; return fileType; } @@ -340,7 +337,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt AmsStKitDataAbilityDataA3 *mainAbility, Uri dataAbilityUri, string &result) { AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); @@ -365,10 +362,9 @@ static void GetResult(std::shared_ptr child, std::shared_pt return; } result = std::to_string(fd); - char str[charCnt]; - if (!feof(file)) { - fgets(str, charCnt, file); - } + char str[5]; + if (!feof(file)) + fgets(str, 5, file); result = str; fclose(file); } else if (child->GetOperatorName() == OPERATOR_GETTYPE) { @@ -379,7 +375,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt void KitTestDataA3EventSubscriber::TestPost(const std::string funName) { - STtools::StOperator allOperator {}; + STtools::StOperator allOperator{}; STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); std::shared_ptr helper = DataAbilityHelper::Creator(mainAbility_->GetContext()); for (auto child : allOperator.GetChildOperator()) { diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_page_a.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_page_a.cpp index 31fa67ba3c2ed5593fda35b756ea10bfb2de7a5f..54d19ca0a234361125aaa5900b14432633c75ad8 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_page_a.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_page_a.cpp @@ -26,7 +26,6 @@ namespace OHOS { namespace AppExecFwk { -namespace { static const int ABILITY_PAGE_CODE = 130; static const std::string OPERATOR_INSERT = "Insert"; static const std::string OPERATOR_DELETE = "Delete"; @@ -35,8 +34,6 @@ static const std::string OPERATOR_QUERY = "Query"; static const std::string OPERATOR_GETFILETYPES = "GetFileTypes"; static const std::string OPERATOR_OPENFILE = "OpenFile"; static const std::string OPERATOR_GETTYPE = "GetType"; -constexpr int charCnt = 5; -} bool AmsStKitDataAbilityPageA::PublishEvent(const std::string &eventName, const int &code, const std::string &data) { @@ -73,7 +70,7 @@ AmsStKitDataAbilityPageA::~AmsStKitDataAbilityPageA() void AmsStKitDataAbilityPageA::SubscribeEvent(const Want &want) { - Want mwant {want}; + Want mwant{want}; std::vector eventList = { "event_data_test_action", }; @@ -136,7 +133,7 @@ void AmsStKitDataAbilityPageA::OnBackground() void AmsStKitDataAbilityPageA::GetWantInfo(const Want &want) { Want mWant(want); - STtools::StOperator allOperator {}; + STtools::StOperator allOperator{}; std::vector vectorOperator = mWant.GetStringArrayParam("operator"); STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator); @@ -153,7 +150,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt AmsStKitDataAbilityPageA *mainAbility, Uri dataAbilityUri, string &result) { AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); @@ -178,10 +175,9 @@ static void GetResult(std::shared_ptr child, std::shared_pt return; } result = std::to_string(fd); - char str[charCnt]; - if (!feof(file)) { - fgets(str, charCnt, file); - } + char str[5]; + if (!feof(file)) + fgets(str, 5, file); result = str; fclose(file); } else if (child->GetOperatorName() == OPERATOR_GETTYPE) { @@ -193,7 +189,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt void KitTestPageAEventSubscriber::TestPost(const std::string funName) { APP_LOGI("KitTestPageAEventSubscriber::TestPost %{public}s", funName.c_str()); - STtools::StOperator allOperator {}; + STtools::StOperator allOperator{}; STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); for (auto child : allOperator.GetChildOperator()) { diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_service_a.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_service_a.cpp index a19b5908fb7a31265d424634204915982bedf2a3..4a799c09bf2343acb9d04e02cf8157e42554c928 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_service_a.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataA/src/ams_st_kit_data_ability_service_a.cpp @@ -26,7 +26,6 @@ namespace OHOS { namespace AppExecFwk { -namespace { static const int ABILITY_SERVICE_CODE = 310; static const std::string OPERATOR_INSERT = "Insert"; static const std::string OPERATOR_DELETE = "Delete"; @@ -35,8 +34,6 @@ static const std::string OPERATOR_QUERY = "Query"; static const std::string OPERATOR_GETFILETYPES = "GetFileTypes"; static const std::string OPERATOR_OPENFILE = "OpenFile"; static const std::string OPERATOR_GETTYPE = "GetType"; -constexpr int charCnt = 5; -} bool AmsStKitDataAbilityServiceA::PublishEvent(const std::string &eventName, const int &code, const std::string &data) { @@ -73,7 +70,7 @@ AmsStKitDataAbilityServiceA::~AmsStKitDataAbilityServiceA() void AmsStKitDataAbilityServiceA::SubscribeEvent(const Want &want) { - Want mwant {want}; + Want mwant{want}; std::vector eventList = { "event_data_test_action", }; @@ -162,7 +159,7 @@ void AmsStKitDataAbilityServiceA::OnDisconnect(const Want &want) void AmsStKitDataAbilityServiceA::GetWantInfo(const Want &want) { Want mWant(want); - STtools::StOperator allOperator {}; + STtools::StOperator allOperator{}; std::vector vectorOperator = mWant.GetStringArrayParam("operator"); STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator); @@ -179,7 +176,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt AmsStKitDataAbilityServiceA *mainAbility, Uri dataAbilityUri, string &result) { AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); @@ -204,9 +201,9 @@ static void GetResult(std::shared_ptr child, std::shared_pt return; } result = std::to_string(fd); - char str[charCnt]; + char str[5]; if (!feof(file)) - fgets(str, charCnt, file); + fgets(str, 5, file); result = str; fclose(file); } else if (child->GetOperatorName() == OPERATOR_GETTYPE) { @@ -218,7 +215,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt void KitTestServiceAEventSubscriber::TestPost(const std::string funName) { APP_LOGI("KitTestServiceAEventSubscriber::TestPost %{public}s", funName.c_str()); - STtools::StOperator allOperator {}; + STtools::StOperator allOperator{}; STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); std::shared_ptr helper = DataAbilityHelper::Creator(mainAbility_->GetContext()); for (auto child : allOperator.GetChildOperator()) { diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/BUILD.gn b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/BUILD.gn index 84cfa990b8f864771329875cfcb5cdd1e47eb71a..6b0bd12020f032563c46a00ab4e45506b16a7844 100755 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/BUILD.gn +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/BUILD.gn @@ -58,6 +58,8 @@ ohos_shared_library("amsKitSystemTestDataB") { "${innerkits_path}/appexecfwk_core:appexecfwk_core", "${kits_path}:appkit_native", "${services_path}/bundlemgr:libbms", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_dataability:native_dataability", + "//foundation/distributeddatamgr/appdatamgr/interfaces/innerkits/native_rdb:native_rdb", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utilsbase", diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/include/ams_st_kit_data_ability_page_b.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/include/ams_st_kit_data_ability_page_b.h index d52b7ef6ce72247748f3b459600f90106a3fed2c..7a355e5d75a21626c64f055579ee8570126e791d 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/include/ams_st_kit_data_ability_page_b.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/include/ams_st_kit_data_ability_page_b.h @@ -58,13 +58,11 @@ public: KitTestPageBEventSubscriber(const CommonEventSubscribeInfo &sp, AmsStKitDataAbilityPageB *ability) : CommonEventSubscriber(sp) { - mapTestFunc_ = { - {"OnStart", [this]() { TestPost("OnStart"); }}, + mapTestFunc_ = {{"OnStart", [this]() { TestPost("OnStart"); }}, {"OnStop", [this]() { TestPost("OnStop"); }}, {"OnActive", [this]() { TestPost("OnActive"); }}, {"OnInactive", [this]() { TestPost("OnInactive"); }}, - {"OnBackground", [this]() { TestPost("OnBackground"); }} - }; + {"OnBackground", [this]() { TestPost("OnBackground"); }}}; mainAbility_ = ability; }; virtual void OnReceiveEvent(const CommonEventData &data); diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_data_b.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_data_b.cpp index 0d7e1d4c45bcfdc34b4e36a9c2deec3b396f8cfb..f27cb6f928a323feb7afb92b640364cd824937b8 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_data_b.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_data_b.cpp @@ -23,7 +23,6 @@ namespace OHOS { namespace AppExecFwk { -namespace { static const int ABILITY_DATA_CODE = 270; static const int LIFECYCLE_CALLBACKS = 271; static const int LIFECYCLE_OBSERVER = 272; @@ -39,8 +38,6 @@ static const int DEFAULT_DELETE_RESULT = 2222; static const int DEFAULT_UPDATE_RESULT = 3333; static const std::string ABILITY_TYPE_PAGE = "0"; static const std::string ABILITY_TYPE_DATA = "2"; -constexpr int charCnt = 5; -} void AmsStKitDataAbilityDataBLifecycleCallbacks::OnAbilityStart(const std::shared_ptr &ability) { @@ -299,7 +296,7 @@ std::vector AmsStKitDataAbilityDataB::GetFileTypes(const Uri &uri, { APP_LOGI("AmsStKitDataAbilityDataB <<<>>>"); PublishEvent(abilityEventName, ABILITY_DATA_CODE, "GetFileTypes"); - std::vector fileType {"filetypes"}; + std::vector fileType{"filetypes"}; return fileType; } @@ -320,7 +317,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt AmsStKitDataAbilityDataB *mainAbility, Uri dataAbilityUri, string &result) { AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); @@ -345,10 +342,9 @@ static void GetResult(std::shared_ptr child, std::shared_pt return; } result = std::to_string(fd); - char str[charCnt]; - if (!feof(file)) { - fgets(str, charCnt, file); - } + char str[5]; + if (!feof(file)) + fgets(str, 5, file); result = str; fclose(file); } else if (child->GetOperatorName() == OPERATOR_GETTYPE) { @@ -360,7 +356,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt void KitTestDataBEventSubscriber::TestPost(const std::string funName) { APP_LOGI("KitTestDataBEventSubscriber::TestPost %{public}s", funName.c_str()); - STtools::StOperator allOperator {}; + STtools::StOperator allOperator{}; STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); std::shared_ptr helper = DataAbilityHelper::Creator(mainAbility_->GetContext()); for (auto child : allOperator.GetChildOperator()) { diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_page_b.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_page_b.cpp index 1dd6fd902512522d24a86eb2491f7e2a1eb663b5..15b5dc857bd905faea9bc74466b67be7862c9faf 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_page_b.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_page_b.cpp @@ -26,7 +26,6 @@ namespace OHOS { namespace AppExecFwk { -namespace { static const int ABILITY_PAGE_CODE = 140; static const std::string OPERATOR_INSERT = "Insert"; static const std::string OPERATOR_DELETE = "Delete"; @@ -35,8 +34,6 @@ static const std::string OPERATOR_QUERY = "Query"; static const std::string OPERATOR_GETFILETYPES = "GetFileTypes"; static const std::string OPERATOR_OPENFILE = "OpenFile"; static const std::string OPERATOR_GETTYPE = "GetType"; -constexpr int charCnt = 5; -} bool AmsStKitDataAbilityPageB::PublishEvent(const std::string &eventName, const int &code, const std::string &data) { @@ -73,7 +70,7 @@ AmsStKitDataAbilityPageB::~AmsStKitDataAbilityPageB() void AmsStKitDataAbilityPageB::SubscribeEvent(const Want &want) { - Want mwant {want}; + Want mwant{want}; std::vector eventList = { "event_data_test_action", }; @@ -136,7 +133,7 @@ void AmsStKitDataAbilityPageB::OnBackground() void AmsStKitDataAbilityPageB::GetWantInfo(const Want &want) { Want mWant(want); - STtools::StOperator allOperator {}; + STtools::StOperator allOperator{}; std::vector vectorOperator = mWant.GetStringArrayParam("operator"); STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator); @@ -153,7 +150,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt AmsStKitDataAbilityPageB *mainAbility, Uri dataAbilityUri, string &result) { AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); @@ -178,10 +175,9 @@ static void GetResult(std::shared_ptr child, std::shared_pt return; } result = std::to_string(fd); - char str[charCnt]; - if (!feof(file)) { - fgets(str, charCnt, file); - } + char str[5]; + if (!feof(file)) + fgets(str, 5, file); result = str; fclose(file); } else if (child->GetOperatorName() == OPERATOR_GETTYPE) { @@ -193,7 +189,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt void KitTestPageBEventSubscriber::TestPost(const std::string funName) { APP_LOGI("KitTestPageBEventSubscriber::TestPost %{public}s", funName.c_str()); - STtools::StOperator allOperator {}; + STtools::StOperator allOperator{}; STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); std::shared_ptr helper = DataAbilityHelper::Creator(mainAbility_->GetContext()); for (auto child : allOperator.GetChildOperator()) { diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_service_b.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_service_b.cpp index 3761d8412f1d8b6f4b1b557e4fa75fc3dce09585..64da2d7418da906e157f215bcad7b665298d71b5 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_service_b.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestDataB/src/ams_st_kit_data_ability_service_b.cpp @@ -26,7 +26,6 @@ namespace OHOS { namespace AppExecFwk { -namespace { static const int ABILITY_SERVICE_CODE = 320; static const std::string OPERATOR_INSERT = "Insert"; static const std::string OPERATOR_DELETE = "Delete"; @@ -35,8 +34,6 @@ static const std::string OPERATOR_QUERY = "Query"; static const std::string OPERATOR_GETFILETYPES = "GetFileTypes"; static const std::string OPERATOR_OPENFILE = "OpenFile"; static const std::string OPERATOR_GETTYPE = "GetType"; -constexpr int charCnt = 5; -} bool AmsStKitDataAbilityServiceB::PublishEvent(const std::string &eventName, const int &code, const std::string &data) { @@ -73,7 +70,7 @@ AmsStKitDataAbilityServiceB::~AmsStKitDataAbilityServiceB() void AmsStKitDataAbilityServiceB::SubscribeEvent(const Want &want) { - Want mwant {want}; + Want mwant{want}; std::vector eventList = { "event_data_test_action", }; @@ -162,7 +159,7 @@ void AmsStKitDataAbilityServiceB::OnDisconnect(const Want &want) void AmsStKitDataAbilityServiceB::GetWantInfo(const Want &want) { Want mWant(want); - STtools::StOperator allOperator {}; + STtools::StOperator allOperator{}; std::vector vectorOperator = mWant.GetStringArrayParam("operator"); STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator); @@ -179,7 +176,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt AmsStKitDataAbilityServiceB *mainAbility, Uri dataAbilityUri, string &result) { AppExecFwk::DataAbilityPredicates predicates; - AppExecFwk::ValuesBucket bucket; + ValuesBucket bucket; result = "failed"; if (child->GetOperatorName() == OPERATOR_INSERT) { result = std::to_string(helper->Insert(dataAbilityUri, bucket)); @@ -204,10 +201,9 @@ static void GetResult(std::shared_ptr child, std::shared_pt return; } result = std::to_string(fd); - char str[charCnt]; - if (!feof(file)) { - fgets(str, charCnt, file); - } + char str[5]; + if (!feof(file)) + fgets(str, 5, file); result = str; fclose(file); } else if (child->GetOperatorName() == OPERATOR_GETTYPE) { @@ -219,7 +215,7 @@ static void GetResult(std::shared_ptr child, std::shared_pt void KitTestServiceBEventSubscriber::TestPost(const std::string funName) { APP_LOGI("KitTestServiceAEventSubscriber::TestPost %{public}s", funName.c_str()); - STtools::StOperator allOperator {}; + STtools::StOperator allOperator{}; STtools::DeserializationStOperatorFromVector(allOperator, vectorOperator_); std::shared_ptr helper = DataAbilityHelper::Creator(mainAbility_->GetContext()); for (auto child : allOperator.GetChildOperator()) { diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/ability_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/ability_ability.h index 718947b23185185e16edccb4cb22e552b489e69e..f44e0b2f3da20ae0c371d5f7751ff5528c591fbf 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/ability_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/ability_ability.h @@ -87,8 +87,7 @@ public: bool SubscribeEvent(); void DoTestCase(); void StopSelfAbility(); - void caseIndexOne(); - void caseIndexTwo(); + protected: virtual void Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/life_cycle_call_backs_ability.h b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/life_cycle_call_backs_ability.h index 73bd3364feef69df4a5cad290b3f8a9a910faab7..066c3eb55bd293fc92c93c75b476955daba8f827 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/life_cycle_call_backs_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/include/life_cycle_call_backs_ability.h @@ -23,6 +23,7 @@ namespace OHOS { namespace AppExecFwk { + class ServiceLifecycleCallbacks : public AbilityLifecycleCallbacks { public: ServiceLifecycleCallbacks() = default; diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/ability_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/ability_ability.cpp index f08aeff55b00611e962d1a36d3cde6f40980dc7d..0060598daaf505785786a261d9e5cc0399dc428d 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/ability_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/ability_ability.cpp @@ -709,28 +709,6 @@ void AbilityAbility::TestAbilityGetLifecycle() } } -void AbilityAbility::caseIndexOne() { - stub_ = new (std::nothrow) AbilityConnectCallback(); - connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); - bool ret = ConnectAbility(want_, connCallback_); - TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityDisconnectAbility"); - sleep(1); - DisconnectAbility(connCallback_); -} - -void AbilityAbility::caseIndexTwo() { - MAP_STR_STR params; - Want want = - TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); - stub_ = new (std::nothrow) AbilityConnectCallback(); - connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); - bool ret = ConnectAbility(want, connCallback_); - TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityDisconnectAbility"); - sleep(1); - DisconnectAbility(connCallback_); - -} - void AbilityAbility::TestAbilityDisconnectAbility() { APP_LOGI("AbilityAbility::OnStart sequenceNumber_ = %{public}s %{public}d", @@ -739,10 +717,23 @@ void AbilityAbility::TestAbilityDisconnectAbility() switch ((CaseIndex)std::stoi(AbilityAbility::sequenceNumber_)) { case CaseIndex::ONE: { - caseIndexOne(); + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want_, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityDisconnectAbility"); + sleep(1); + DisconnectAbility(connCallback_); } break; case CaseIndex::TWO: { - caseIndexTwo(); + MAP_STR_STR params; + Want want = + TestUtils::MakeWant("", "LifecycleCallbacksAbility", "com.ohos.amsst.service.AppKit", params); + stub_ = new (std::nothrow) AbilityConnectCallback(); + connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); + bool ret = ConnectAbility(want, connCallback_); + TestUtils::PublishEvent(APP_ABILITY_RESP_EVENT_NAME, ret, "TestAbilityDisconnectAbility"); + sleep(1); + DisconnectAbility(connCallback_); } break; case CaseIndex::THREE: { MAP_STR_STR params; diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/ability_life_cycle_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/ability_life_cycle_ability.cpp index c2552fa710c22685e4eb5522b129f6a26d306081..08ef9ee33f6c7062c3dd4ed8948a80f9e7b0fe77 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/ability_life_cycle_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/ability_life_cycle_ability.cpp @@ -21,9 +21,6 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; -namespace { -constexpr int loopCnt = 3; -} // namespace AbilityLifeCycleAbility::~AbilityLifeCycleAbility() { @@ -231,7 +228,7 @@ void AbilityLifeCycleAbility::TestStopAbility() TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestStopAbility"); } break; case CaseIndex::FOUR: { - for (int i = 0; i < loopCnt; i++) { + for (int i = 0; i < 3; i++) { bool ret = BaseAbility::GetContext()->StopAbility(want_); TestUtils::PublishEvent(APP_ABILITY_CONTEXT_RESP_EVENT_NAME, ret, "TestStopAbility"); } diff --git a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/life_cycle_observer_ability.cpp b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/life_cycle_observer_ability.cpp index 5ae57412319b7807964d5405c0d3e27c6077a904..4653d6331658f05a5129de9aa650f8bde6772b8f 100644 --- a/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/life_cycle_observer_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/amsKitSystemTestPageA/src/life_cycle_observer_ability.cpp @@ -21,9 +21,7 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; -namespace { -constexpr int loopCnt = 100; -} + void LifecycleObserverLifecycleObserver::DoTask() { switch ((CaseIndex)LifeCycleObserverAbility::sequenceNumber_) { @@ -494,7 +492,7 @@ void LifeCycleObserverAbility::TestLifeCycleGetLifecycle() TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycle"); } break; case CaseIndex::TWO: { - for (int i = 0; i < loopCnt; i++) { + for (int i = 0; i < 100; i++) { auto lifecycle = GetLifecycle(); } TestUtils::PublishEvent(APP_LIFE_CYCLE_OBSERVER_RESP_EVENT_NAME, 1, "TestLifeCycleGetLifecycle"); diff --git a/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/include/verify_act_first_ability.h b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/include/verify_act_first_ability.h index 4f4926ec6edd4af63bb20633492e08f47b994fee..c13a82e29e87f954555119bb80dd24b3f8e70028 100644 --- a/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/include/verify_act_first_ability.h +++ b/test/resource/amssystemtestability/abilitySrc/serviceAbilityA/include/verify_act_first_ability.h @@ -55,7 +55,6 @@ class AbilityContextStartAbilityTest : public EventFwk::CommonEventSubscriber { public: AbilityContextStartAbilityTest(const EventFwk::CommonEventSubscribeInfo &sp) : EventFwk::CommonEventSubscriber(sp){}; - virtual ~AbilityContextStartAbilityTest() = default; virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); }; class ConnectServiceAbilityTest : public EventFwk::CommonEventSubscriber { @@ -67,7 +66,6 @@ public: abilityContext_ = abilityContext; conne_ = conne; }; - virtual ~ConnectServiceAbilityTest() = default; virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; std::shared_ptr abilityContext_ = nullptr; diff --git a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/main_ability.cpp b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/main_ability.cpp index cd1ad9aae0224f465a5bfd66f992b5a8092284da..af5f914a38845d242af4ba3e827e95d9a2afe44a 100644 --- a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/main_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/main_ability.cpp @@ -27,7 +27,7 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; using namespace OHOS::STtools; - +namespace { int terminated_task_num = 0; std::condition_variable cv; std::mutex cv_mutex; @@ -48,6 +48,11 @@ std::string innerDelimiter = "-"; std::string task_execution_sequence = delimiter; std::vector> allDispatchers; std::mutex dispatcher_mutex; +constexpr int numZero = 0; +constexpr int numOne = 1; +constexpr int numTwo = 2; +constexpr int numThree = 3; +} bool Wait(const int task_num) { @@ -360,14 +365,11 @@ void FirstEventSubscriber::OnReceiveEvent(const CommonEventData &data) auto target = data.GetData(); auto caseInfo = TestUtils::split(target, "_"); APP_LOGI("FirstEventSubscriber::OnReceiveEvent:caseInfo.size()=%{public}zu", caseInfo.size()); - if (caseInfo.size() < 3) { + if (caseInfo.size() < numThree) { return; } - APP_LOGI("FirstEventSubscriber::OnReceiveEvent:caseInfo[0]=%{public}s", caseInfo[0].c_str()); - APP_LOGI("FirstEventSubscriber::OnReceiveEvent:caseInfo[1]=%{public}s", caseInfo[1].c_str()); - APP_LOGI("FirstEventSubscriber::OnReceiveEvent:caseInfo[2]=%{public}s", caseInfo[2].c_str()); - if (mapTestFunc_.find(caseInfo[0]) != mapTestFunc_.end()) { - mapTestFunc_[caseInfo[0]](std::stoi(caseInfo[1]), std::stoi(caseInfo[2]), data.GetCode()); + if (mapTestFunc_.find(caseInfo[numZero]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[numZero]](std::stoi(caseInfo[numOne]), std::stoi(caseInfo[numTwo]), data.GetCode()); } else { APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); } @@ -383,72 +385,41 @@ void MainAbility::TestDispatcher(int apiIndex, int caseIndex, int code) } } -int MainAbility::Dispatch(TestSetting outerSetting, TestSetting innerSetting) -{ - APP_LOGI("-- -- -- -- -- --MainAbility::Dispatch begin"); - std::string outerName = "outerDispatcher"; - std::string innerName = "innerDispatcher"; +void SetInnerTask(TaskList innerDispatcher, TestSetting innerSetting, std::string outerTaskId, int innerTaskSeq) { + std::string innerTaskId = outerTaskId + innerDelimiter + std::to_string(innerTaskSeq); + auto innerTask = std::make_shared([=]() { TestTask(innerTaskId); }); + innerDispatcher.addOperation(innerSetting.op); + if (innerSetting.op == TestOperation::APPLY && innerSetting.apply > 0) { + innerDispatcher.addApply(innerSetting.apply); + } + if (innerSetting.op == TestOperation::DELAY && innerSetting.delay > 0) { + innerDispatcher.addDelay(innerSetting.delay); + } + innerDispatcher.addFunc(innerTask); +} - std::string outerTaskId; - auto context = GetContext(); - TaskList outerDispatcher{outerSetting.dispatcher, context, outerName}; - if (outerSetting.create_group) { - outerDispatcher.addOperation(TestOperation::CREATE_GROUP); +void SetInnerTaskOther(TaskList innerDispatcher, TestSetting innerSetting, int outerTaskSeq) { + if (innerSetting.sync_barrier) { + std::string taskId = innerSyncBarrierId + std::to_string(outerTaskSeq); + auto task = std::make_shared([=]() { TestTask(taskId); }); + innerDispatcher.addOperation(TestOperation::SYNC_BARRIER).addFunc(task); } - for (int i = 0; i < testTaskCount; i++) { - outerTaskId = std::to_string(i); - auto outerTask = std::make_shared([=]() { - auto context = this->GetContext(); - TaskList innerDispatcher{innerSetting.dispatcher, context, innerName + std::to_string(i)}; - if (innerSetting.create_group) { - innerDispatcher.addOperation(TestOperation::CREATE_GROUP); - } - for (int j = 0; j < testTaskCount; j++) { - std::string innerTaskId = outerTaskId + innerDelimiter + std::to_string(j); - auto innerTask = std::make_shared([=]() { TestTask(innerTaskId); }); - innerDispatcher.addOperation(innerSetting.op); - if (innerSetting.op == TestOperation::APPLY && innerSetting.apply > 0) { - innerDispatcher.addApply(innerSetting.apply); - } - if (innerSetting.op == TestOperation::DELAY && innerSetting.delay > 0) { - innerDispatcher.addDelay(innerSetting.delay); - } - innerDispatcher.addFunc(innerTask); - } - if (innerSetting.sync_barrier) { - std::string taskId = innerSyncBarrierId + std::to_string(i); - auto task = std::make_shared([=]() { TestTask(taskId); }); - innerDispatcher.addOperation(TestOperation::SYNC_BARRIER).addFunc(task); - } - if (innerSetting.async_barrier) { - std::string taskId = innerAsyncBarrierId + std::to_string(i); - auto task = std::make_shared([=]() { TestTask(taskId); }); - innerDispatcher.addOperation(TestOperation::ASYNC_BARRIER).addFunc(task); - } - if (innerSetting.group_wait) { - innerDispatcher.addOperation(TestOperation::GROUP_WAIT).addWaitTime(innerSetting.group_timeout); - } - if (innerSetting.group_notify) { - std::string taskId = innerGroupNotifyId + std::to_string(i); - auto task = std::make_shared([=]() { TestTask(taskId); }); - innerDispatcher.addOperation(TestOperation::GROUP_NOTIFY).addFunc(task); - } - innerDispatcher.executedTask(); - { - std::lock_guard lock(dispatcher_mutex); - allDispatchers.push_back(innerDispatcher.getDispatcher()); - } - TestTask(outerTaskId); - }); - outerDispatcher.addOperation(outerSetting.op); - if (outerSetting.op == TestOperation::APPLY && outerSetting.apply > 0) { - outerDispatcher.addApply(outerSetting.apply); - } - if (outerSetting.op == TestOperation::DELAY && outerSetting.delay > 0) { - outerDispatcher.addDelay(outerSetting.delay); - } - outerDispatcher.addFunc(outerTask); + if (innerSetting.async_barrier) { + std::string taskId = innerAsyncBarrierId + std::to_string(outerTaskSeq); + auto task = std::make_shared([=]() { TestTask(taskId); }); + innerDispatcher.addOperation(TestOperation::ASYNC_BARRIER).addFunc(task); } + if (innerSetting.group_wait) { + innerDispatcher.addOperation(TestOperation::GROUP_WAIT).addWaitTime(innerSetting.group_timeout); + } + if (innerSetting.group_notify) { + std::string taskId = innerGroupNotifyId + std::to_string(outerTaskSeq); + auto task = std::make_shared([=]() { TestTask(taskId); }); + innerDispatcher.addOperation(TestOperation::GROUP_NOTIFY).addFunc(task); + } +} + +void SetOuterTaskOther(TaskList outerDispatcher, TestSetting outerSetting) { if (outerSetting.sync_barrier) { auto task = std::make_shared([=]() { TestTask(outerSyncBarrierId); }); outerDispatcher.addOperation(TestOperation::SYNC_BARRIER).addFunc(task); @@ -464,11 +435,9 @@ int MainAbility::Dispatch(TestSetting outerSetting, TestSetting innerSetting) auto task = std::make_shared([=]() { TestTask(outerGroupNotifyId); }); outerDispatcher.addOperation(TestOperation::GROUP_NOTIFY).addFunc(task); } - outerDispatcher.executedTask(); - { - std::lock_guard lock(dispatcher_mutex); - allDispatchers.push_back(outerDispatcher.getDispatcher()); - } +} + +int CountTask(TestSetting outerSetting, TestSetting innerSetting) { int taskCount = 0; taskCount = (innerSetting.op == TestOperation::APPLY) ? (innerSetting.apply * testTaskCount) : testTaskCount; if (innerSetting.sync_barrier) { @@ -492,7 +461,54 @@ int MainAbility::Dispatch(TestSetting outerSetting, TestSetting innerSetting) if (outerSetting.group_notify) { taskCount++; } - APP_LOGI("-- -- -- -- -- --MainAbility::Dispatch end taskCount:%{public}d", taskCount); + return taskCount; +} + +int MainAbility::Dispatch(TestSetting outerSetting, TestSetting innerSetting) +{ + std::string outerName = "outerDispatcher"; + std::string innerName = "innerDispatcher"; + std::string outerTaskId; + auto context = GetContext(); + TaskList outerDispatcher {outerSetting.dispatcher, context, outerName}; + if (outerSetting.create_group) { + outerDispatcher.addOperation(TestOperation::CREATE_GROUP); + } + for (int i = 0; i < testTaskCount; i++) { + outerTaskId = std::to_string(i); + auto outerTask = std::make_shared([=]() { + auto context = this->GetContext(); + TaskList innerDispatcher {innerSetting.dispatcher, context, innerName + std::to_string(i)}; + if (innerSetting.create_group) { + innerDispatcher.addOperation(TestOperation::CREATE_GROUP); + } + for (int j = 0; j < testTaskCount; j++) { + SetInnerTask(innerDispatcher, innerSetting, outerTaskId, j); + } + SetInnerTaskOther(innerDispatcher, innerSetting, i); + innerDispatcher.executedTask(); + { + std::lock_guard lock(dispatcher_mutex); + allDispatchers.push_back(innerDispatcher.getDispatcher()); + } + TestTask(outerTaskId); + }); + outerDispatcher.addOperation(outerSetting.op); + if (outerSetting.op == TestOperation::APPLY && outerSetting.apply > 0) { + outerDispatcher.addApply(outerSetting.apply); + } + if (outerSetting.op == TestOperation::DELAY && outerSetting.delay > 0) { + outerDispatcher.addDelay(outerSetting.delay); + } + outerDispatcher.addFunc(outerTask); + } + SetOuterTaskOther(outerDispatcher, outerSetting); + outerDispatcher.executedTask(); + { + std::lock_guard lock(dispatcher_mutex); + allDispatchers.push_back(outerDispatcher.getDispatcher()); + } + int taskCount = CountTask(outerSetting, innerSetting); return taskCount; } @@ -1820,7 +1836,6 @@ void MainAbility::GlobalCase50(int code) // level1:global, group level2:serial, delay void MainAbility::GlobalCase51(int code) { - APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); TestSetting outerSetting; @@ -8973,7 +8988,7 @@ void MainAbility::HybridCase1(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; std::vector operationList = { TestOperation::SYNC, TestOperation::ASYNC, @@ -9003,7 +9018,7 @@ void MainAbility::HybridCase2(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList parallelDispatcher = TaskList{TestDispatcher::PARALLEL, context, "parallel"}; + TaskList parallelDispatcher = TaskList {TestDispatcher::PARALLEL, context, "parallel"}; std::vector operationList = { TestOperation::SYNC, TestOperation::ASYNC, @@ -9037,7 +9052,7 @@ void MainAbility::HybridCase3(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList serialDispatcher = TaskList{TestDispatcher::SERIAL, context, "serial"}; + TaskList serialDispatcher = TaskList {TestDispatcher::SERIAL, context, "serial"}; std::vector operationList = { TestOperation::SYNC, TestOperation::ASYNC, @@ -9064,7 +9079,7 @@ void MainAbility::HybridCase4(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; std::vector operationList = { TestOperation::SYNC, TestOperation::ASYNC, @@ -9091,12 +9106,12 @@ void MainAbility::HybridCase5(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; globalDispatcher.addOperation(TestOperation::SYNC) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) @@ -9137,12 +9152,12 @@ void MainAbility::HybridCase6(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; globalDispatcher.addOperation(TestOperation::ASYNC) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) @@ -9183,12 +9198,12 @@ void MainAbility::HybridCase7(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; const long delay = 10; globalDispatcher.addOperation(TestOperation::DELAY) @@ -9236,12 +9251,12 @@ void MainAbility::HybridCase8(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; globalDispatcher.addOperation(TestOperation::CREATE_GROUP) .addOperation(TestOperation::ASYNC_GROUP) @@ -9285,12 +9300,12 @@ void MainAbility::HybridCase9(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; globalDispatcher.addOperation(TestOperation::CREATE_GROUP) .addOperation(TestOperation::ASYNC_GROUP) @@ -9334,12 +9349,12 @@ void MainAbility::HybridCase10(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; const long delay = 10; globalDispatcher.addOperation(TestOperation::CREATE_GROUP) @@ -9387,12 +9402,12 @@ void MainAbility::HybridCase11(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; globalDispatcher.addOperation(TestOperation::CREATE_GROUP) .addOperation(TestOperation::ASYNC_GROUP) @@ -9400,21 +9415,21 @@ void MainAbility::HybridCase11(int code) .addOperation(TestOperation::GROUP_NOTIFY) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) .executedTask(); - taskId += 2; + taskId += numTwo; parallelDispatcher1.addOperation(TestOperation::CREATE_GROUP) .addOperation(TestOperation::ASYNC_GROUP) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) .addOperation(TestOperation::GROUP_NOTIFY) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) .executedTask(); - taskId += 2; + taskId += numTwo; parallelDispatcher2.addOperation(TestOperation::CREATE_GROUP) .addOperation(TestOperation::ASYNC_GROUP) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) .addOperation(TestOperation::GROUP_NOTIFY) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) .executedTask(); - taskId += 2; + taskId += numTwo; serialDispatcher1.addOperation(TestOperation::ASYNC) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) .executedTask(); @@ -9442,12 +9457,12 @@ void MainAbility::HybridCase12(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 2; @@ -9502,12 +9517,12 @@ void MainAbility::HybridCase13(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 1; @@ -9559,12 +9574,12 @@ void MainAbility::HybridCase14(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 2; @@ -9618,12 +9633,12 @@ void MainAbility::HybridCase15(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 2; @@ -9635,7 +9650,7 @@ void MainAbility::HybridCase15(int code) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) .executedTask(); taskId++; - taskCount += 2; + taskCount += numTwo; parallelDispatcher1.addOperation(TestOperation::SYNC) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) .executedTask(); @@ -9679,12 +9694,12 @@ void MainAbility::HybridCase16(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 2; @@ -9707,7 +9722,7 @@ void MainAbility::HybridCase16(int code) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) .executedTask(); taskId++; - taskCount += 2; + taskCount += numTwo; serialDispatcher1.addOperation(TestOperation::ASYNC) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) .executedTask(); @@ -9740,12 +9755,12 @@ void MainAbility::HybridCase17(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 2; @@ -9795,12 +9810,12 @@ void MainAbility::HybridCase18(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 2; @@ -9852,12 +9867,12 @@ void MainAbility::HybridCase19(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 2; @@ -9910,12 +9925,12 @@ void MainAbility::HybridCase20(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 2; @@ -9938,7 +9953,7 @@ void MainAbility::HybridCase20(int code) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) .executedTask(); taskId++; - taskCount += 2; + taskCount += numTwo; serialDispatcher1.addOperation(TestOperation::DELAY) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) .addDelay(delay) @@ -9971,12 +9986,12 @@ void MainAbility::HybridCase21(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 2; @@ -9988,7 +10003,7 @@ void MainAbility::HybridCase21(int code) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) .executedTask(); taskId++; - taskCount += 2; + taskCount += numTwo; parallelDispatcher1.addOperation(TestOperation::ASYNC) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) .executedTask(); @@ -10031,12 +10046,12 @@ void MainAbility::HybridCase22(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 2; @@ -10091,12 +10106,12 @@ void MainAbility::HybridCase23(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 2; @@ -10120,7 +10135,7 @@ void MainAbility::HybridCase23(int code) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) .executedTask(); taskId++; - taskCount += 2; + taskCount += numTwo; serialDispatcher1.addOperation(TestOperation::APPLY) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) .executedTask(); @@ -10153,12 +10168,12 @@ void MainAbility::HybridCase24(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const long apply = 2; @@ -10169,8 +10184,8 @@ void MainAbility::HybridCase24(int code) .addOperation(TestOperation::GROUP_NOTIFY) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) .executedTask(); - taskId += 2; - taskCount += 2; + taskId += numTwo; + taskCount += numTwo; parallelDispatcher1.addOperation(TestOperation::DELAY) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) .addDelay(delay) @@ -10219,12 +10234,12 @@ void MainAbility::HybridCase25(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; globalDispatcher.addOperation(TestOperation::ASYNC) @@ -10245,7 +10260,7 @@ void MainAbility::HybridCase25(int code) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) .executedTask(); taskId++; - taskCount += 2; + taskCount += numTwo; serialDispatcher1.addOperation(TestOperation::ASYNC) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) .executedTask(); @@ -10276,12 +10291,12 @@ void MainAbility::HybridCase26(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 2; @@ -10332,12 +10347,12 @@ void MainAbility::HybridCase27(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; - TaskList parallelDispatcher1 = TaskList{TestDispatcher::PARALLEL, context, "parallel1"}; - TaskList parallelDispatcher2 = TaskList{TestDispatcher::PARALLEL, context, "parallel2"}; - TaskList serialDispatcher1 = TaskList{TestDispatcher::SERIAL, context, "serial1"}; - TaskList serialDispatcher2 = TaskList{TestDispatcher::SERIAL, context, "serial2"}; - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; + TaskList parallelDispatcher1 = TaskList {TestDispatcher::PARALLEL, context, "parallel1"}; + TaskList parallelDispatcher2 = TaskList {TestDispatcher::PARALLEL, context, "parallel2"}; + TaskList serialDispatcher1 = TaskList {TestDispatcher::SERIAL, context, "serial1"}; + TaskList serialDispatcher2 = TaskList {TestDispatcher::SERIAL, context, "serial2"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; int taskId = 0; int taskCount = 0; const int apply = 2; @@ -10354,7 +10369,7 @@ void MainAbility::HybridCase27(int code) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId + 1)); })) .executedTask(); taskId++; - taskCount += 2; + taskCount += numTwo; parallelDispatcher2.addOperation(TestOperation::APPLY) .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) .addApply(apply) @@ -10395,7 +10410,7 @@ void MainAbility::MultiAppCase1(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; std::vector operationList = { TestOperation::ASYNC, TestOperation::ASYNC, @@ -10427,7 +10442,7 @@ void MainAbility::MultiAppCase2(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList parallelDispatcher = TaskList{TestDispatcher::PARALLEL, context, "parallel"}; + TaskList parallelDispatcher = TaskList {TestDispatcher::PARALLEL, context, "parallel"}; std::vector operationList = { TestOperation::ASYNC, TestOperation::ASYNC, @@ -10459,7 +10474,7 @@ void MainAbility::MultiAppCase3(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList serialDispatcher = TaskList{TestDispatcher::SERIAL, context, "serial"}; + TaskList serialDispatcher = TaskList {TestDispatcher::SERIAL, context, "serial"}; std::vector operationList = { TestOperation::ASYNC, TestOperation::ASYNC, @@ -10491,7 +10506,7 @@ void MainAbility::MultiAppCase4(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList mainDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList mainDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; std::vector operationList = { TestOperation::ASYNC, TestOperation::ASYNC, @@ -10524,17 +10539,17 @@ void MainAbility::ExtraCase1(int code) Reset(); auto context = GetContext(); int taskId = 0; - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; bool result = globalDispatcher.addOperation(TestOperation::SYNC) - .addFunc(std::make_shared([=]() { - std::string targetBundleName = "com.ohos.TaskDispatcherA"; - std::string targetAbility = "SecondAbility"; - Want want; - want.SetElementName(targetBundleName, targetAbility); - StartAbility(want); - TestTask(std::to_string(taskId)); - })) - .executedTask(); + .addFunc(std::make_shared([=]() { + std::string targetBundleName = "com.ohos.TaskDispatcherA"; + std::string targetAbility = "SecondAbility"; + Want want; + want.SetElementName(targetBundleName, targetAbility); + StartAbility(want); + TestTask(std::to_string(taskId)); + })) + .executedTask(); taskId++; Wait(taskId); result = task_execution_sequence.size() > 1; @@ -10547,7 +10562,7 @@ void MainAbility::FillInDispathcer() const int fullThreadNum = 32; const int waitTime = 2; auto context = GetContext(); - TaskList parallelDispatcher = TaskList{TestDispatcher::PARALLEL, context, "parallel"}; + TaskList parallelDispatcher = TaskList {TestDispatcher::PARALLEL, context, "parallel"}; parallelDispatcher.setTaskPriority(AppExecFwk::TaskPriority::HIGH); parallelDispatcher.addOperation(TestOperation::ASYNC).addFunc(std::make_shared([=]() { sleep(waitTime - 1); @@ -10565,9 +10580,9 @@ void MainAbility::PriorityCase1(int code) FillInDispathcer(); Reset(); auto context = GetContext(); - TaskList globalDispatcherLow = TaskList{TestDispatcher::GLOBAL, context, "globalLow"}; - TaskList globalDispatcherDefault = TaskList{TestDispatcher::GLOBAL, context, "globalDefault"}; - TaskList globalDispatcherHigh = TaskList{TestDispatcher::GLOBAL, context, "globalHigh"}; + TaskList globalDispatcherLow = TaskList {TestDispatcher::GLOBAL, context, "globalLow"}; + TaskList globalDispatcherDefault = TaskList {TestDispatcher::GLOBAL, context, "globalDefault"}; + TaskList globalDispatcherHigh = TaskList {TestDispatcher::GLOBAL, context, "globalHigh"}; int taskId = 0; globalDispatcherLow.setTaskPriority(AppExecFwk::TaskPriority::LOW) .addOperation(TestOperation::ASYNC) @@ -10592,7 +10607,7 @@ void MainAbility::PriorityCase1(int code) for (auto index : outerTaskIndex) { result = result && (index != std::string::npos); } - result = result && (outerTaskIndex[0] > outerTaskIndex[1]) && (outerTaskIndex[1] > outerTaskIndex[2]); + result = result && (outerTaskIndex[numZero] > outerTaskIndex[numOne]) && (outerTaskIndex[numOne] > outerTaskIndex[numTwo]); TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); } void MainAbility::PriorityCase2(int code) @@ -10601,9 +10616,9 @@ void MainAbility::PriorityCase2(int code) FillInDispathcer(); Reset(); auto context = GetContext(); - TaskList parallelDispatcherLow = TaskList{TestDispatcher::PARALLEL, context, "parallelLow"}; - TaskList parallelDispatcherDefault = TaskList{TestDispatcher::PARALLEL, context, "parallelDefault"}; - TaskList parallelDispatcherHigh = TaskList{TestDispatcher::PARALLEL, context, "parallelHigh"}; + TaskList parallelDispatcherLow = TaskList {TestDispatcher::PARALLEL, context, "parallelLow"}; + TaskList parallelDispatcherDefault = TaskList {TestDispatcher::PARALLEL, context, "parallelDefault"}; + TaskList parallelDispatcherHigh = TaskList {TestDispatcher::PARALLEL, context, "parallelHigh"}; int taskId = 0; parallelDispatcherLow.setTaskPriority(AppExecFwk::TaskPriority::LOW) .addOperation(TestOperation::ASYNC) @@ -10628,7 +10643,7 @@ void MainAbility::PriorityCase2(int code) for (auto index : outerTaskIndex) { result = result && (index != std::string::npos); } - result = result && (outerTaskIndex[0] > outerTaskIndex[1]) && (outerTaskIndex[1] > outerTaskIndex[2]); + result = result && (outerTaskIndex[numZero] > outerTaskIndex[numOne]) && (outerTaskIndex[numOne] > outerTaskIndex[numTwo]); TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); } void MainAbility::PriorityCase3(int code) @@ -10637,9 +10652,9 @@ void MainAbility::PriorityCase3(int code) FillInDispathcer(); Reset(); auto context = GetContext(); - TaskList serialDispatcherLow = TaskList{TestDispatcher::SERIAL, context, "serialLow"}; - TaskList serialDispatcherDefault = TaskList{TestDispatcher::SERIAL, context, "serialDefault"}; - TaskList serialDispatcherHigh = TaskList{TestDispatcher::SERIAL, context, "serialHigh"}; + TaskList serialDispatcherLow = TaskList {TestDispatcher::SERIAL, context, "serialLow"}; + TaskList serialDispatcherDefault = TaskList {TestDispatcher::SERIAL, context, "serialDefault"}; + TaskList serialDispatcherHigh = TaskList {TestDispatcher::SERIAL, context, "serialHigh"}; int taskId = 0; serialDispatcherLow.setTaskPriority(AppExecFwk::TaskPriority::LOW) .addOperation(TestOperation::ASYNC) @@ -10664,7 +10679,7 @@ void MainAbility::PriorityCase3(int code) for (auto index : outerTaskIndex) { result = result && (index != std::string::npos); } - result = result && (outerTaskIndex[0] > outerTaskIndex[1]) && (outerTaskIndex[1] > outerTaskIndex[2]); + result = result && (outerTaskIndex[numZero] > outerTaskIndex[numOne]) && (outerTaskIndex[numOne] > outerTaskIndex[numTwo]); TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); } void MainAbility::PriorityCase4(int code) @@ -10673,9 +10688,9 @@ void MainAbility::PriorityCase4(int code) FillInDispathcer(); Reset(); auto context = GetContext(); - TaskList parallelDispatcherLow = TaskList{TestDispatcher::PARALLEL, context, "parallelLow"}; - TaskList parallelDispatcherDefault = TaskList{TestDispatcher::PARALLEL, context, "parallelDefault"}; - TaskList mainDispatcherHigh = TaskList{TestDispatcher::MAIN, context, "mainHigh"}; + TaskList parallelDispatcherLow = TaskList {TestDispatcher::PARALLEL, context, "parallelLow"}; + TaskList parallelDispatcherDefault = TaskList {TestDispatcher::PARALLEL, context, "parallelDefault"}; + TaskList mainDispatcherHigh = TaskList {TestDispatcher::MAIN, context, "mainHigh"}; int taskId = 0; parallelDispatcherLow.setTaskPriority(AppExecFwk::TaskPriority::LOW) .addOperation(TestOperation::ASYNC) @@ -10699,7 +10714,7 @@ void MainAbility::PriorityCase4(int code) for (auto index : outerTaskIndex) { result = result && (index != std::string::npos); } - result = result && (outerTaskIndex[0] > outerTaskIndex[1]) && (outerTaskIndex[1] > outerTaskIndex[2]); + result = result && (outerTaskIndex[numZero] > outerTaskIndex[numOne]) && (outerTaskIndex[numOne] > outerTaskIndex[numTwo]); TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); } void MainAbility::PriorityCase5(int code) @@ -10708,9 +10723,9 @@ void MainAbility::PriorityCase5(int code) FillInDispathcer(); Reset(); auto context = GetContext(); - TaskList globalDispatcherLow = TaskList{TestDispatcher::GLOBAL, context, "globallLow"}; - TaskList parallelDispatcherDefault = TaskList{TestDispatcher::PARALLEL, context, "parallelDefault"}; - TaskList globalDispatcherHigh = TaskList{TestDispatcher::GLOBAL, context, "globalHigh"}; + TaskList globalDispatcherLow = TaskList {TestDispatcher::GLOBAL, context, "globallLow"}; + TaskList parallelDispatcherDefault = TaskList {TestDispatcher::PARALLEL, context, "parallelDefault"}; + TaskList globalDispatcherHigh = TaskList {TestDispatcher::GLOBAL, context, "globalHigh"}; int taskId = 0; globalDispatcherLow.setTaskPriority(AppExecFwk::TaskPriority::LOW) .addOperation(TestOperation::ASYNC) @@ -10735,7 +10750,7 @@ void MainAbility::PriorityCase5(int code) for (auto index : outerTaskIndex) { result = result && (index != std::string::npos); } - result = result && (outerTaskIndex[0] > outerTaskIndex[1]) && (outerTaskIndex[1] > outerTaskIndex[2]); + result = result && (outerTaskIndex[numZero] > outerTaskIndex[numOne]) && (outerTaskIndex[numOne] > outerTaskIndex[numTwo]); TestUtils::PublishEvent(g_EVENT_RESP_FIRST, code, std::to_string(result)); } void MainAbility::RevokeCase1(int code) @@ -10744,13 +10759,13 @@ void MainAbility::RevokeCase1(int code) FillInDispathcer(); Reset(); auto context = GetContext(); - TaskList parallelDispatcher = TaskList{TestDispatcher::GLOBAL, context, "parallel"}; + TaskList parallelDispatcher = TaskList {TestDispatcher::GLOBAL, context, "parallel"}; int taskId = 0; bool result = parallelDispatcher.addOperation(TestOperation::ASYNC) - .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) - .addOperation(TestOperation::REVOCABLE) - .addRevokeTask(1) - .executedTask(); + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addOperation(TestOperation::REVOCABLE) + .addRevokeTask(1) + .executedTask(); taskId++; result = !result || Wait(taskId); result = result || task_execution_sequence.size() > 1; @@ -10762,11 +10777,11 @@ void MainAbility::RevokeCase2(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList parallelDispatcher = TaskList{TestDispatcher::GLOBAL, context, "parallel"}; + TaskList parallelDispatcher = TaskList {TestDispatcher::GLOBAL, context, "parallel"}; int taskId = 0; bool result = parallelDispatcher.addOperation(TestOperation::ASYNC) - .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) - .executedTask(); + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); taskId++; result = result && Wait(taskId); result = result && !parallelDispatcher.addOperation(TestOperation::REVOCABLE).addRevokeTask(1).executedTask(); @@ -10779,14 +10794,14 @@ void MainAbility::RevokeCase3(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList parallelDispatcher = TaskList{TestDispatcher::GLOBAL, context, "parallel"}; + TaskList parallelDispatcher = TaskList {TestDispatcher::GLOBAL, context, "parallel"}; int taskId = 0; bool result = parallelDispatcher.addOperation(TestOperation::DELAY) - .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) - .addDelay(delayMs) - .addOperation(TestOperation::REVOCABLE) - .addRevokeTask(1) - .executedTask(); + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addDelay(delayMs) + .addOperation(TestOperation::REVOCABLE) + .addRevokeTask(1) + .executedTask(); taskId++; result = !result || Wait(taskId); result = result || task_execution_sequence.size() > 1; @@ -10798,12 +10813,12 @@ void MainAbility::RevokeCase4(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList parallelDispatcher = TaskList{TestDispatcher::GLOBAL, context, "parallel"}; + TaskList parallelDispatcher = TaskList {TestDispatcher::GLOBAL, context, "parallel"}; int taskId = 0; bool result = parallelDispatcher.addOperation(TestOperation::DELAY) - .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) - .addDelay(delayMs) - .executedTask(); + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addDelay(delayMs) + .executedTask(); taskId++; result = result && Wait(taskId); result = result && !parallelDispatcher.addOperation(TestOperation::REVOCABLE).addRevokeTask(1).executedTask(); @@ -10817,14 +10832,14 @@ void MainAbility::RevokeCase5(int code) FillInDispathcer(); Reset(); auto context = GetContext(); - TaskList parallelDispatcher = TaskList{TestDispatcher::GLOBAL, context, "parallel"}; + TaskList parallelDispatcher = TaskList {TestDispatcher::GLOBAL, context, "parallel"}; int taskId = 0; bool result = parallelDispatcher.addOperation(TestOperation::CREATE_GROUP) - .addOperation(TestOperation::ASYNC_GROUP) - .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) - .addOperation(TestOperation::REVOCABLE) - .addRevokeTask(1) - .executedTask(); + .addOperation(TestOperation::ASYNC_GROUP) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .addOperation(TestOperation::REVOCABLE) + .addRevokeTask(1) + .executedTask(); taskId++; result = !result || Wait(taskId); result = result || task_execution_sequence.size() > 1; @@ -10836,12 +10851,12 @@ void MainAbility::RevokeCase6(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList parallelDispatcher = TaskList{TestDispatcher::GLOBAL, context, "parallel"}; + TaskList parallelDispatcher = TaskList {TestDispatcher::GLOBAL, context, "parallel"}; int taskId = 0; bool result = parallelDispatcher.addOperation(TestOperation::CREATE_GROUP) - .addOperation(TestOperation::ASYNC_GROUP) - .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) - .executedTask(); + .addOperation(TestOperation::ASYNC_GROUP) + .addFunc(std::make_shared([=]() { TestTask(std::to_string(taskId)); })) + .executedTask(); taskId++; result = result && Wait(taskId); result = result && !parallelDispatcher.addOperation(TestOperation::REVOCABLE).addRevokeTask(1).executedTask(); diff --git a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/second_ability.cpp b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/second_ability.cpp index 74b750fe7fa5a49e9051fd2107ca246fe119859a..57b1eff8c0d1ff2185e6f19582328e6236511c28 100644 --- a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/second_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/second_ability.cpp @@ -20,6 +20,14 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; +namespace +{ +constexpr int numZero = 0; +constexpr int numOne = 1; +constexpr int numTwo = 2; +constexpr int numThree = 3; +} // namespace + void SecondAbility::Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, @@ -109,11 +117,11 @@ void SecondEventSubscriber::OnReceiveEvent(const CommonEventData &data) if (std::strcmp(eventName.c_str(), g_EVENT_REQU_SECOND.c_str()) == 0) { auto target = data.GetData(); auto caseInfo = TestUtils::split(target, "_"); - if (caseInfo.size() < 3) { + if (caseInfo.size() < numThree) { return; } - if (mapTestFunc_.find(caseInfo[0]) != mapTestFunc_.end()) { - mapTestFunc_[caseInfo[0]](std::stoi(caseInfo[1]), std::stoi(caseInfo[2]), data.GetCode()); + if (mapTestFunc_.find(caseInfo[numZero]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[numZero]](std::stoi(caseInfo[numOne]), std::stoi(caseInfo[numTwo]), data.GetCode()); } else { APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); } diff --git a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/test_utils.cpp b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/test_utils.cpp index 07ebf00c47128276f0e83d0aa5783fec0a417147..3e75bdf815379f71af430ad9d5c979da62400675 100644 --- a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/test_utils.cpp +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestA/src/test_utils.cpp @@ -47,9 +47,10 @@ Want TestUtils::MakeWant( std::vector TestUtils::split(const std::string &in, const std::string &delim) { - std::regex reg{delim}; - return std::vector{ - std::sregex_token_iterator(in.begin(), in.end(), reg, -1), std::sregex_token_iterator()}; + std::regex reg {delim}; + return std::vector { + std::sregex_token_iterator(in.begin(), in.end(), reg, -1), std::sregex_token_iterator() + }; } } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/include/test_utils.h b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/include/test_utils.h index e32f3c5521a3b852d7224e2e63db851c71226d23..f0ffaa195385b9f13d7fb5035a070d365485fe00 100644 --- a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/include/test_utils.h +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/include/test_utils.h @@ -19,7 +19,6 @@ namespace OHOS { namespace AppExecFwk { - class TestUtils { public: TestUtils() = default; diff --git a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/main_ability.cpp b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/main_ability.cpp index e80ab723aa4c01b840b256cef11908d2e0fa9606..5d6ca2081673da539f3284424e640e990472d4f8 100644 --- a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/main_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/main_ability.cpp @@ -25,7 +25,7 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; using namespace OHOS::STtools; - +namespace { int terminated_task_num = 0; std::condition_variable cv; std::mutex cv_mutex; @@ -38,17 +38,28 @@ std::string outerSyncBarrierId = "outerSyncBarrierId"; std::string outerAsyncBarrierId = "outerAsyncBarrierId"; std::string outerGroupWaitId = "outerGroupWaitId"; std::string outerGroupNotifyId = "outerGroupNotifyId"; - std::string delimiter = "_"; std::string innerDelimiter = "-"; std::string task_execution_sequence = delimiter; +std::vector> allDispatchers; +std::mutex dispatcher_mutex; +constexpr int numZero = 0; +constexpr int numOne = 1; +constexpr int numTwo = 2; +constexpr int numThree = 3; +} bool Wait(const int task_num) { APP_LOGI("-- -- -- -- -- --MainAbility::Wait"); std::unique_lock ulock(cv_mutex); using namespace std::chrono_literals; - return cv.wait_for(ulock, 5000ms, [task_num] { return terminated_task_num == task_num; }); + bool result = cv.wait_for(ulock, 5000ms, [task_num] { return terminated_task_num == task_num; }); + if (result) { + allDispatchers.clear(); + } + APP_LOGI("-- -- -- -- -- --MainAbility::Wait result:%{public}d", result); + return result; } void TestTask(const std::string &task_id) @@ -68,6 +79,7 @@ void Reset() APP_LOGI("-- -- -- -- -- --MainAbility::Reset"); terminated_task_num = 0; task_execution_sequence = delimiter; + allDispatchers.clear(); } bool IsAscend(const std::vector &vec) @@ -268,14 +280,11 @@ void FirstEventSubscriber::OnReceiveEvent(const CommonEventData &data) auto target = data.GetData(); auto caseInfo = TestUtils::split(target, "_"); APP_LOGI("FirstEventSubscriber::OnReceiveEvent:caseInfo.size()=%{public}zu", caseInfo.size()); - if (caseInfo.size() < 3) { + if (caseInfo.size() < numThree) { return; } - APP_LOGI("FirstEventSubscriber::OnReceiveEvent:caseInfo[0]=%{public}s", caseInfo[0].c_str()); - APP_LOGI("FirstEventSubscriber::OnReceiveEvent:caseInfo[1]=%{public}s", caseInfo[1].c_str()); - APP_LOGI("FirstEventSubscriber::OnReceiveEvent:caseInfo[2]=%{public}s", caseInfo[2].c_str()); - if (mapTestFunc_.find(caseInfo[0]) != mapTestFunc_.end()) { - mapTestFunc_[caseInfo[0]](std::stoi(caseInfo[1]), std::stoi(caseInfo[2]), data.GetCode()); + if (mapTestFunc_.find(caseInfo[numZero]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[numZero]](std::stoi(caseInfo[numOne]), std::stoi(caseInfo[numTwo]), data.GetCode()); } else { APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); } @@ -291,15 +300,92 @@ void MainAbility::TestDispatcher(int apiIndex, int caseIndex, int code) } } +void SetInnerTask(TaskList innerDispatcher, TestSetting innerSetting, std::string outerTaskId, int innerTaskSeq) { + std::string innerTaskId = outerTaskId + innerDelimiter + std::to_string(innerTaskSeq); + auto innerTask = std::make_shared([=]() { TestTask(innerTaskId); }); + innerDispatcher.addOperation(innerSetting.op); + if (innerSetting.op == TestOperation::APPLY && innerSetting.apply > 0) { + innerDispatcher.addApply(innerSetting.apply); + } + if (innerSetting.op == TestOperation::DELAY && innerSetting.delay > 0) { + innerDispatcher.addDelay(innerSetting.delay); + } + innerDispatcher.addFunc(innerTask); +} + +void SetInnerTaskOther(TaskList innerDispatcher, TestSetting innerSetting, int outerTaskSeq) { + if (innerSetting.sync_barrier) { + std::string taskId = innerSyncBarrierId + std::to_string(outerTaskSeq); + auto task = std::make_shared([=]() { TestTask(taskId); }); + innerDispatcher.addOperation(TestOperation::SYNC_BARRIER).addFunc(task); + } + if (innerSetting.async_barrier) { + std::string taskId = innerAsyncBarrierId + std::to_string(outerTaskSeq); + auto task = std::make_shared([=]() { TestTask(taskId); }); + innerDispatcher.addOperation(TestOperation::ASYNC_BARRIER).addFunc(task); + } + if (innerSetting.group_wait) { + innerDispatcher.addOperation(TestOperation::GROUP_WAIT).addWaitTime(innerSetting.group_timeout); + } + if (innerSetting.group_notify) { + std::string taskId = innerGroupNotifyId + std::to_string(outerTaskSeq); + auto task = std::make_shared([=]() { TestTask(taskId); }); + innerDispatcher.addOperation(TestOperation::GROUP_NOTIFY).addFunc(task); + } +} + +void SetOuterTaskOther(TaskList outerDispatcher, TestSetting outerSetting) { + if (outerSetting.sync_barrier) { + auto task = std::make_shared([=]() { TestTask(outerSyncBarrierId); }); + outerDispatcher.addOperation(TestOperation::SYNC_BARRIER).addFunc(task); + } + if (outerSetting.async_barrier) { + auto task = std::make_shared([=]() { TestTask(outerAsyncBarrierId); }); + outerDispatcher.addOperation(TestOperation::ASYNC_BARRIER).addFunc(task); + } + if (outerSetting.group_wait) { + outerDispatcher.addOperation(TestOperation::GROUP_WAIT).addWaitTime(outerSetting.group_timeout); + } + if (outerSetting.group_notify) { + auto task = std::make_shared([=]() { TestTask(outerGroupNotifyId); }); + outerDispatcher.addOperation(TestOperation::GROUP_NOTIFY).addFunc(task); + } +} + +int CountTask(TestSetting outerSetting, TestSetting innerSetting) { + int taskCount = 0; + taskCount = (innerSetting.op == TestOperation::APPLY) ? (innerSetting.apply * testTaskCount) : testTaskCount; + if (innerSetting.sync_barrier) { + taskCount++; + } + if (innerSetting.async_barrier) { + taskCount++; + } + if (innerSetting.group_notify) { + taskCount++; + } + taskCount = (outerSetting.op == TestOperation::APPLY) + ? (outerSetting.apply * testTaskCount + outerSetting.apply * testTaskCount * taskCount) + : (testTaskCount + testTaskCount * taskCount); + if (outerSetting.sync_barrier) { + taskCount++; + } + if (outerSetting.async_barrier) { + taskCount++; + } + if (outerSetting.group_notify) { + taskCount++; + } + return taskCount; +} + int MainAbility::Dispatch(TestSetting outerSetting, TestSetting innerSetting) { - APP_LOGI("-- -- -- -- -- --MainAbility::Dispatch begin"); std::string outerName = "outerDispatcher"; std::string innerName = "innerDispatcher"; - std::string outerTaskId; auto context = GetContext(); - TaskList outerDispatcher{outerSetting.dispatcher, context, outerName}; + TaskList outerDispatcher {outerSetting.dispatcher, context, outerName}; if (outerSetting.create_group) { outerDispatcher.addOperation(TestOperation::CREATE_GROUP); } @@ -307,41 +393,19 @@ int MainAbility::Dispatch(TestSetting outerSetting, TestSetting innerSetting) outerTaskId = std::to_string(i); auto outerTask = std::make_shared([=]() { auto context = this->GetContext(); - TaskList innerDispatcher{innerSetting.dispatcher, context, innerName + std::to_string(i)}; + TaskList innerDispatcher {innerSetting.dispatcher, context, innerName + std::to_string(i)}; if (innerSetting.create_group) { innerDispatcher.addOperation(TestOperation::CREATE_GROUP); } for (int j = 0; j < testTaskCount; j++) { - std::string innerTaskId = outerTaskId + innerDelimiter + std::to_string(j); - auto innerTask = std::make_shared([=]() { TestTask(innerTaskId); }); - innerDispatcher.addOperation(innerSetting.op); - if (innerSetting.op == TestOperation::APPLY && innerSetting.apply > 0) { - innerDispatcher.addApply(innerSetting.apply); - } - if (innerSetting.op == TestOperation::DELAY && innerSetting.delay > 0) { - innerDispatcher.addDelay(innerSetting.delay); - } - innerDispatcher.addFunc(innerTask); - } - if (innerSetting.sync_barrier) { - std::string taskId = innerSyncBarrierId + std::to_string(i); - auto task = std::make_shared([=]() { TestTask(taskId); }); - innerDispatcher.addOperation(TestOperation::SYNC_BARRIER).addFunc(task); - } - if (innerSetting.async_barrier) { - std::string taskId = innerAsyncBarrierId + std::to_string(i); - auto task = std::make_shared([=]() { TestTask(taskId); }); - innerDispatcher.addOperation(TestOperation::ASYNC_BARRIER).addFunc(task); - } - if (innerSetting.group_wait) { - innerDispatcher.addOperation(TestOperation::GROUP_WAIT).addWaitTime(innerSetting.group_timeout); - } - if (innerSetting.group_notify) { - std::string taskId = innerGroupNotifyId + std::to_string(i); - auto task = std::make_shared([=]() { TestTask(taskId); }); - innerDispatcher.addOperation(TestOperation::GROUP_NOTIFY).addFunc(task); + SetInnerTask(innerDispatcher, innerSetting, outerTaskId, j); } + SetInnerTaskOther(innerDispatcher, innerSetting, i); innerDispatcher.executedTask(); + { + std::lock_guard lock(dispatcher_mutex); + allDispatchers.push_back(innerDispatcher.getDispatcher()); + } TestTask(outerTaskId); }); outerDispatcher.addOperation(outerSetting.op); @@ -353,29 +417,13 @@ int MainAbility::Dispatch(TestSetting outerSetting, TestSetting innerSetting) } outerDispatcher.addFunc(outerTask); } - if (outerSetting.sync_barrier) { - auto task = std::make_shared([=]() { TestTask(outerSyncBarrierId); }); - outerDispatcher.addOperation(TestOperation::SYNC_BARRIER).addFunc(task); - } - if (outerSetting.async_barrier) { - auto task = std::make_shared([=]() { TestTask(outerAsyncBarrierId); }); - outerDispatcher.addOperation(TestOperation::ASYNC_BARRIER).addFunc(task); - } - if (outerSetting.group_wait) { - outerDispatcher.addOperation(TestOperation::GROUP_WAIT).addWaitTime(outerSetting.group_timeout); - } - if (outerSetting.group_notify) { - auto task = std::make_shared([=]() { TestTask(outerGroupNotifyId); }); - outerDispatcher.addOperation(TestOperation::GROUP_NOTIFY).addFunc(task); - } + SetOuterTaskOther(outerDispatcher, outerSetting); outerDispatcher.executedTask(); - int taskCount = 0; - taskCount = (innerSetting.op == TestOperation::APPLY) ? (innerSetting.apply * testTaskCount) : testTaskCount; - taskCount = (outerSetting.op == TestOperation::APPLY) - ? (innerSetting.apply * testTaskCount + innerSetting.apply * testTaskCount * taskCount) - : (testTaskCount + testTaskCount * taskCount); - - APP_LOGI("-- -- -- -- -- --MainAbility::Dispatch end"); + { + std::lock_guard lock(dispatcher_mutex); + allDispatchers.push_back(outerDispatcher.getDispatcher()); + } + int taskCount = CountTask(outerSetting, innerSetting); return taskCount; } @@ -403,7 +451,7 @@ void MainAbility::MultiAppCase1(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::GLOBAL, context, "global"}; + TaskList globalDispatcher = TaskList {TestDispatcher::GLOBAL, context, "global"}; std::vector operationList = { TestOperation::ASYNC, TestOperation::ASYNC, @@ -435,7 +483,7 @@ void MainAbility::MultiAppCase2(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::PARALLEL, context, "parallel"}; + TaskList globalDispatcher = TaskList {TestDispatcher::PARALLEL, context, "parallel"}; std::vector operationList = { TestOperation::ASYNC, TestOperation::ASYNC, @@ -467,7 +515,7 @@ void MainAbility::MultiAppCase3(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::SERIAL, context, "serial"}; + TaskList globalDispatcher = TaskList {TestDispatcher::SERIAL, context, "serial"}; std::vector operationList = { TestOperation::ASYNC, TestOperation::ASYNC, @@ -499,7 +547,7 @@ void MainAbility::MultiAppCase4(int code) APP_LOGI("-- -- -- -- -- --MainAbility::%{public}s", __FUNCTION__); Reset(); auto context = GetContext(); - TaskList globalDispatcher = TaskList{TestDispatcher::MAIN, context, "main"}; + TaskList globalDispatcher = TaskList {TestDispatcher::MAIN, context, "main"}; std::vector operationList = { TestOperation::ASYNC, TestOperation::ASYNC, diff --git a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/second_ability.cpp b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/second_ability.cpp index 67a8ed8c7c7381c3e7297f5ad419e9dc0f3f95f3..9c770b1249159f651d0c48fcc98ac92003660c94 100644 --- a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/second_ability.cpp +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/second_ability.cpp @@ -20,6 +20,12 @@ namespace OHOS { namespace AppExecFwk { using namespace OHOS::EventFwk; +namespace { +constexpr int numZero = 0; +constexpr int numOne = 1; +constexpr int numTwo = 2; +constexpr int numThree = 3; +} void SecondAbility::Init(const std::shared_ptr &abilityInfo, const std::shared_ptr &application, std::shared_ptr &handler, @@ -103,11 +109,11 @@ void SecondEventSubscriber::OnReceiveEvent(const CommonEventData &data) if (std::strcmp(eventName.c_str(), g_EVENT_REQU_SECOND_B.c_str()) == 0) { auto target = data.GetData(); auto caseInfo = TestUtils::split(target, "_"); - if (caseInfo.size() < 3) { + if (caseInfo.size() < numThree) { return; } - if (mapTestFunc_.find(caseInfo[0]) != mapTestFunc_.end()) { - mapTestFunc_[caseInfo[0]](std::stoi(caseInfo[1]), std::stoi(caseInfo[2]), data.GetCode()); + if (mapTestFunc_.find(caseInfo[numZero]) != mapTestFunc_.end()) { + mapTestFunc_[caseInfo[numZero]](std::stoi(caseInfo[numOne]), std::stoi(caseInfo[numTwo]), data.GetCode()); } else { APP_LOGI("OnReceiveEvent: CommonEventData error(%{public}s)", target.c_str()); } diff --git a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/test_utils.cpp b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/test_utils.cpp index 07ebf00c47128276f0e83d0aa5783fec0a417147..3e75bdf815379f71af430ad9d5c979da62400675 100644 --- a/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/test_utils.cpp +++ b/test/resource/amssystemtestability/abilitySrc/taskDispatcherTestB/src/test_utils.cpp @@ -47,9 +47,10 @@ Want TestUtils::MakeWant( std::vector TestUtils::split(const std::string &in, const std::string &delim) { - std::regex reg{delim}; - return std::vector{ - std::sregex_token_iterator(in.begin(), in.end(), reg, -1), std::sregex_token_iterator()}; + std::regex reg {delim}; + return std::vector { + std::sregex_token_iterator(in.begin(), in.end(), reg, -1), std::sregex_token_iterator() + }; } } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/tools/include/event.h b/test/resource/amssystemtestability/abilitySrc/tools/include/event.h index 00ced741999b3e91b6f639acf99a7753263b6e04..4e659a7bd700b404d249954636828c6c3b3100d5 100644 --- a/test/resource/amssystemtestability/abilitySrc/tools/include/event.h +++ b/test/resource/amssystemtestability/abilitySrc/tools/include/event.h @@ -18,7 +18,6 @@ #include namespace STtools { - class Event { public: Event(); @@ -38,5 +37,4 @@ private: int WaitCompleted(Event &event, const std::string &eventName, const int code, const int timeout = 60); void Completed(Event &event, const std::string &eventName, const int code); void CleanMsg(Event &event); - } // namespace STtools \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/tools/include/stoperator.h b/test/resource/amssystemtestability/abilitySrc/tools/include/stoperator.h index c0683c1ae47c2b17ca607c8ff6a5448b7271722b..f7a8f367f01b3302b96144dfc2050e7bc2b07c21 100644 --- a/test/resource/amssystemtestability/abilitySrc/tools/include/stoperator.h +++ b/test/resource/amssystemtestability/abilitySrc/tools/include/stoperator.h @@ -20,11 +20,8 @@ namespace STtools { using std::string; class StOperator; - std::vector SerializationStOperatorToVector(StOperator &ParentOperator); - void DeserializationStOperatorFromVector(StOperator &ParentOperator, std::vector &vectorOperator); - class StOperator { private: std::vector> g_childOperator; @@ -57,5 +54,4 @@ public: std::vector> GetChildOperator(); std::vector> PopChildOperator(); }; - } // namespace STtools diff --git a/test/resource/amssystemtestability/abilitySrc/tools/include/stpageabilityevent.h b/test/resource/amssystemtestability/abilitySrc/tools/include/stpageabilityevent.h index 0ac76a4b9f5284961ae275fdef5935d2f101d38e..7c441e4f4dcf660e0f1f64ce5e8043175e17c3f7 100644 --- a/test/resource/amssystemtestability/abilitySrc/tools/include/stpageabilityevent.h +++ b/test/resource/amssystemtestability/abilitySrc/tools/include/stpageabilityevent.h @@ -27,7 +27,6 @@ namespace OHOS { namespace AppExecFwk { - namespace STEventName { const std::string g_eventName = "resp_st_page_ability_callback"; const std::string g_eventNameProcessMemory = "resp_st_process_memory_info"; @@ -129,8 +128,6 @@ private: std::string callBackPath_; std::string abilityStatus_; }; - } // namespace AppExecFwk } // namespace OHOS - -#endif //_AMS_ST_PAGE_ABILITY_EVENT_H_ \ No newline at end of file +#endif // _AMS_ST_PAGE_ABILITY_EVENT_H_ \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/tools/src/event.cpp b/test/resource/amssystemtestability/abilitySrc/tools/src/event.cpp index a51291b4b24bf14bfd45d1c6b27f4e390d2443e9..933a13149cedd0306a45973a8d488359257eb0c8 100644 --- a/test/resource/amssystemtestability/abilitySrc/tools/src/event.cpp +++ b/test/resource/amssystemtestability/abilitySrc/tools/src/event.cpp @@ -17,7 +17,6 @@ #include namespace STtools { - int WaitCompleted(Event &event, const std::string &eventName, const int code, const int timeout) { return event.WaitingMessage(std::to_string(code) + eventName, timeout, false); @@ -98,5 +97,4 @@ void Event::Clean() waiting_message_ = ""; complete_message_.clear(); } - } // namespace STtools \ No newline at end of file diff --git a/test/resource/amssystemtestability/abilitySrc/tools/src/stoperator.cpp b/test/resource/amssystemtestability/abilitySrc/tools/src/stoperator.cpp index 2c7ea20bc5fc7992fa9217e857611dfc0c303532..c441c6cedf8da2677a28bd6d63054022b3f9b581 100644 --- a/test/resource/amssystemtestability/abilitySrc/tools/src/stoperator.cpp +++ b/test/resource/amssystemtestability/abilitySrc/tools/src/stoperator.cpp @@ -75,7 +75,8 @@ void DeserializationStOperatorFromVector(StOperator &ParentOperator, std::vector int StOperator::countChild = 0; StOperator::StOperator() - : g_parentOperator(nullptr), g_abilityType("0"), g_bundleName(""), g_abilityName(""), g_operatorName(""), g_message("") + : g_parentOperator(nullptr), g_abilityType("0"), + g_bundleName(""), g_abilityName(""), g_operatorName(""), g_message("") { g_childOperator.clear(); StOperator::countChild++; diff --git a/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo3/src/pageAbilityDemo.cpp b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo3/src/pageAbilityDemo.cpp index bce1ad6f00bfe8f77b723eebca2a8bdfd4ee7314..2ed39e4dc00aba02cd7e2f7b0b18483f6aecc0de 100644 --- a/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo3/src/pageAbilityDemo.cpp +++ b/test/resource/bmssystemtestability/abilitySrc/thirdPageDemo3/src/pageAbilityDemo.cpp @@ -19,7 +19,6 @@ namespace OHOS { namespace AppExecFwk { const std::string BUNDLE_DATA_ROOT_PATH = "/data/accounts/account_0/appdata/"; -const int DIR_DEPTH = 7; void PageAbilityDemo::OnStart(const Want &want) { APP_LOGI("PageAbilityDemo::onStart"); @@ -27,7 +26,7 @@ void PageAbilityDemo::OnStart(const Want &want) const std::string appName = "com.third.hiworld.example1"; std::string path = BUNDLE_DATA_ROOT_PATH + appName + "/cache/"; APP_LOGI("PageAbilityDemo::CreateDir"); - for (int i = 1; i < DIR_DEPTH; i++) { + for (int i = 1; i < 7; i++) { path += "dir" + std::to_string(i) + "/"; APP_LOGI("PageAbilityDemo::CreateDir %{public}s", path.c_str()); CreateDir(path); diff --git a/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle41.hap b/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle41.hap old mode 100644 new mode 100755 index 6939058dc68e2c0bd987a944d293c410e6acae60..05035ff2a8d5b96887346b15f6473e2f8e197b3f Binary files a/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle41.hap and b/test/resource/bundlemgrsst/stThirdBundle/bmsThirdBundle41.hap differ diff --git a/test/resource/formsystemtestability/formSystemTestServiceA/BUILD.gn b/test/resource/formsystemtestability/formSystemTestServiceA/BUILD.gn index eb3960bf94b35bb13afda611eb4587d6383ff8f3..a3b48e26782593bb028c22c004a8d63f3e1ca781 100644 --- a/test/resource/formsystemtestability/formSystemTestServiceA/BUILD.gn +++ b/test/resource/formsystemtestability/formSystemTestServiceA/BUILD.gn @@ -35,7 +35,7 @@ config("formSystemTestAConfig") { ] } ohos_shared_library("formSystemTestServiceA") { - sources = [ "${subdemosystem_path}/src/form_st_service_ability_A.cpp" ] + sources = [ "${subdemosystem_path}/src/form_st_service_ability_a1.cpp" ] configs = [ ":formSystemTestAConfig" ] deps = [ "${aafwk_path}/frameworks/kits/ability/native:abilitykit_native", diff --git a/test/resource/formsystemtestability/formSystemTestServiceA/config.json b/test/resource/formsystemtestability/formSystemTestServiceA/config.json index c7baafed52bb0c88b550f74f77a16c0b154ad98f..f88dbdcf504e1285e7835194c30ca94bb0391b35 100644 --- a/test/resource/formsystemtestability/formSystemTestServiceA/config.json +++ b/test/resource/formsystemtestability/formSystemTestServiceA/config.json @@ -1,112 +1,87 @@ -{ - "app": { - "bundleName": "com.provider.bundleName1", - "vendor": "ohos", - "version": { - "code": 1, - "name": "1.0" - }, - "apiVersion": { - "compatible": 3, - "target": 3 - } - }, - "deviceConfig": { - "default": { - } - }, - "module": { - "package": "com.provider.FormSystemTestServiceA.src", - "name": "moduleName11", - "deviceType": [ - "phone" - ], - "distro": { - "deliveryWithInstall": true, - "moduleName": "moduleName11", - "moduleType": "entry" - }, - "abilities": [ - { - "name": "FormStServiceAbilityA", - "icon": "$media:snowball", - "label": "FormStServiceAbilityA Ability", - "launchType": "standard", - "orientation": "unspecified", - "type": "service", - "visible": true, - "formsEnabled": true, - "forms": [ - { - "name": "formName111", - "description": "form_description", - "isDefault": true, - "type": "JS", - "colorMode": "auto", - "supportDimensions":[ "1*2", "2*2" ], - "defaultDimension": "1*2", - "landscapeLayouts": [""], - "portraitLayouts": [""], - "updateEnabled": true, - "scheduledUpateTime": "0:0", - "updateDuration": 1, - "deepLink": "", - "jsComponentName": "card", - "formVisibleNotify" : true, - "metaData": { - "customizeData": [ - { - "name": "originWidgetName", - "value": "myTest" - } - ] - } - }, - { - "name": "formName112", - "description": "form_description", - "isDefault": true, - "type": "JS", - "colorMode": "auto", - "supportDimensions":[ "1*2", "2*2" ], - "defaultDimension": "1*2", - "landscapeLayouts": [""], - "portraitLayouts": [""], - "updateEnabled": true, - "scheduledUpateTime": "10:30", - "updateDuration": 0, - "deepLink": "", - "jsComponentName": "card", - "formVisibleNotify" : true, - "metaData": { - "customizeData": [ - { - "name": "originWidgetName", - "value": "myTest" - } - ] - } - } - ] - } - ], - "defPermissions": [ - { - "name": "com.permission.CAMERA", - "grantMode": "system_grant", - "availableScope": ["signature"], - "label": "CAMERA permission", - "description": "CAMERA permission in detail" - } - ], - "js": [ - { - "name": "card", - "pages": [ - "pages/index/index" - ], - "type": "form" - } - ] - } -} +{ + "app": { + "bundleName": "com.provider.bundleName1", + "vendor": "ohos", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 3, + "target": 3 + } + }, + "deviceConfig": { + "default": { + } + }, + "module": { + "package": "com.provider.FormSystemTestServiceA.src", + "name": "moduleName11", + "deviceType": [ + "phone" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "testability", + "moduleType": "entry" + }, + "abilities": [ + { + "name": "FormStServiceAbilityA1", + "icon": "$media:snowball", + "label": "FormStServiceAbilityA1 Ability", + "launchType": "standard", + "orientation": "unspecified", + "type": "service", + "visible": true, + "formsEnabled": true, + "forms": [ + { + "name": "formName111", + "description": "form_description", + "isDefault": true, + "type": "JS", + "colorMode": "auto", + "supportDimensions":[ "1*2", "2*2" ], + "defaultDimension": "1*2", + "landscapeLayouts": [""], + "portraitLayouts": [""], + "updateEnabled": true, + "scheduledUpateTime": "10:30", + "updateDuration": 1, + "deepLink": "", + "jsComponentName": "card", + "formVisibleNotify" : true, + "metaData": { + "customizeData": [ + { + "name": "originWidgetName", + "value": "myTest" + } + ] + } + } + ] + } + ], + "defPermissions": [ + { + "name": "com.permission.CAMERA", + "grantMode": "system_grant", + "availableScope": ["signature"], + "label": "CAMERA permission", + "description": "CAMERA permission in detail" + } + ], + "js": [ + { + "name": "card", + "pages": [ + "pages/index/index" + ], + "type": "form" + } + ] + } +} diff --git a/test/resource/formsystemtestability/formSystemTestServiceA/include/form_st_service_ability_A.h b/test/resource/formsystemtestability/formSystemTestServiceA/include/form_st_service_ability_A.h deleted file mode 100755 index 610caccc59c7c13bdcf5f2be0a3eabe5ea456860..0000000000000000000000000000000000000000 --- a/test/resource/formsystemtestability/formSystemTestServiceA/include/form_st_service_ability_A.h +++ /dev/null @@ -1,142 +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 FORM_ST_SERVICE_ABILITY_A_ -#define FORM_ST_SERVICE_ABILITY_A_ -#include -#include -#include "ability_connect_callback_stub.h" -#include "ability_connect_callback_proxy.h" -#include "ability_loader.h" -#include "common_event.h" -#include "common_event_manager.h" -#include "form_provider_info.h" - -namespace OHOS { -namespace AppExecFwk { -using AbilityConnectionStub = OHOS::AAFwk::AbilityConnectionStub; -using AbilityConnectionProxy = OHOS::AAFwk::AbilityConnectionProxy; -const std::string APP_A_RESP_EVENT_NAME = "resp_com_ohos_formst_service_app_a"; -const std::string APP_A_REQ_EVENT_NAME = "req_com_ohos_formst_service_app_a"; -const std::string COMMON_EVENT_TEST_ACTION1 = "usual.event.test1"; -/** - * Form event trigger result - */ -typedef enum { - FORM_EVENT_TRIGGER_RESULT_NG = 0, - FORM_EVENT_TRIGGER_RESULT_OK = 1, -} FORM_EVENT_TRIGGER_RESULT; - -class FormStServiceAbilityA : public Ability { -public: - ~FormStServiceAbilityA(); - -protected: - virtual void OnStart(const Want &want) override; - virtual void OnStop() override; - virtual void OnActive() override; - virtual void OnInactive() override; - virtual void OnBackground() override; - virtual void OnNewWant(const Want &want) override; - virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; - virtual sptr OnConnect(const Want &want) override; - virtual void OnDisconnect(const Want &want) override; - virtual FormProviderInfo OnCreate(const Want &want) override; - virtual void OnUpdate(const int64_t formId) override; - virtual void OnTriggerEvent(const int64_t formId, const std::string &message) override; - virtual void OnDelete(const int64_t formId) override; - virtual void OnCastTemptoNormal(const int64_t formId) override; - virtual void OnVisibilityChanged(const std::map &formEventsMap) override; - -private: - void Clear(); - void GetWantInfo(const Want &want); - std::vector Split(std::string str, const std::string &token); - bool SubscribeEvent(); - static bool PublishEvent(const std::string &eventName, const int &code, const std::string &data); - void StartOtherAbility(); - void ConnectOtherAbility(); - void DisConnectOtherAbility(); - void StopSelfAbility(); - - std::string shouldReturn_ = {}; - std::string targetBundle_ = {}; - std::string targetAbility_ = {}; - std::string nextTargetBundle_ = {}; - std::string nextTargetAbility_ = {}; - std::string targetBundleConn_ = {}; - std::string targetAbilityConn_ = {}; - std::string nextTargetBundleConn_ = {}; - std::string nextTargetAbilityConn_ = {}; - std::string zombie_ = {}; - - typedef void (FormStServiceAbilityA::*func)(); - static std::map funcMap_; - class AbilityConnectCallback; - sptr stub_ = {}; - sptr connCallback_ = {}; - class AppEventSubscriber; - std::shared_ptr subscriber_ = {}; - - class AbilityConnectCallback : public AbilityConnectionStub { - public: - sptr AsObject() override - { - return nullptr; - } - /** - * OnAbilityConnectDone, AbilityMs notify caller ability the result of connect. - * - * @param element,.service ability's ElementName. - * @param remoteObject,.the session proxy of service ability. - * @param resultCode, ERR_OK on success, others on failure. - */ - void OnAbilityConnectDone( - const AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override - { - if (resultCode == 0) { - onAbilityConnectDoneCount++; - PublishEvent(APP_A_RESP_EVENT_NAME, onAbilityConnectDoneCount, "OnAbilityConnectDone"); - } - } - - /** - * OnAbilityDisconnectDone, AbilityMs notify caller ability the result of disconnect. - * - * @param element,.service ability's ElementName. - * @param resultCode, ERR_OK on success, others on failure. - */ - void OnAbilityDisconnectDone(const AppExecFwk::ElementName &element, int resultCode) override - { - if (resultCode == 0) { - onAbilityConnectDoneCount--; - PublishEvent(APP_A_RESP_EVENT_NAME, onAbilityConnectDoneCount, "OnAbilityDisconnectDone"); - } - } - - static int onAbilityConnectDoneCount; - }; - class AppEventSubscriber : public EventFwk::CommonEventSubscriber { - public: - AppEventSubscriber(const EventFwk::CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp){}; - ~AppEventSubscriber() = default; - virtual void OnReceiveEvent(const EventFwk::CommonEventData &data) override; - - FormStServiceAbilityA *mainAbility_ = nullptr; - }; -}; -} // namespace AppExecFwk -} // namespace OHOS -#endif // FORM_ST_SERVICE_ABILITY_A_ diff --git a/test/resource/formsystemtestability/formSystemTestServiceA/include/form_st_service_ability_a1.h b/test/resource/formsystemtestability/formSystemTestServiceA/include/form_st_service_ability_a1.h old mode 100755 new mode 100644 index e5e30429343af0cdfe4aca95ac07ec9d7d07fd75..d50f4f3bc4da5b6309ef572c1c4b1be04333a10b --- a/test/resource/formsystemtestability/formSystemTestServiceA/include/form_st_service_ability_a1.h +++ b/test/resource/formsystemtestability/formSystemTestServiceA/include/form_st_service_ability_a1.h @@ -46,7 +46,7 @@ protected: virtual void OnCommand(const AAFwk::Want &want, bool restart, int startId) override; virtual sptr OnConnect(const Want &want) override; virtual void OnDisconnect(const Want &want) override; - virtual FormProviderInfo OnCreate(const Want &want) override; + virtual FormProviderInfo OnCreateForm(const Want &want) override; private: void Clear(); diff --git a/test/resource/formsystemtestability/formSystemTestServiceA/src/form_st_service_ability_A.cpp b/test/resource/formsystemtestability/formSystemTestServiceA/src/form_st_service_ability_A.cpp deleted file mode 100755 index e229ca09f08fa93e2f8f9cd9d08d5ca851d76f52..0000000000000000000000000000000000000000 --- a/test/resource/formsystemtestability/formSystemTestServiceA/src/form_st_service_ability_A.cpp +++ /dev/null @@ -1,370 +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 "form_st_service_ability_A.h" -#include "app_log_wrapper.h" -#include "common_event.h" -#include "common_event_manager.h" -#include "form_provider_client.h" - -using namespace OHOS::EventFwk; - -constexpr int64_t SEC_TO_MILLISEC = 1000; -constexpr int64_t MILLISEC_TO_NANOSEC = 1000000; - -namespace OHOS { -namespace AppExecFwk { -using AbilityConnectionProxy = OHOS::AAFwk::AbilityConnectionProxy; - -int FormStServiceAbilityA::AbilityConnectCallback::onAbilityConnectDoneCount = 0; -std::map FormStServiceAbilityA::funcMap_ = { - {"StartOtherAbility", &FormStServiceAbilityA::StartOtherAbility}, - {"ConnectOtherAbility", &FormStServiceAbilityA::ConnectOtherAbility}, - {"DisConnectOtherAbility", &FormStServiceAbilityA::DisConnectOtherAbility}, - {"StopSelfAbility", &FormStServiceAbilityA::StopSelfAbility}, -}; - -FormStServiceAbilityA::~FormStServiceAbilityA() -{ - CommonEventManager::UnSubscribeCommonEvent(subscriber_); -} - -std::vector FormStServiceAbilityA::Split(std::string str, const std::string &token) -{ - APP_LOGI("FormStServiceAbilityA::Split"); - - std::vector splitString; - while (str.size()) { - size_t index = str.find(token); - if (index != std::string::npos) { - splitString.push_back(str.substr(0, index)); - str = str.substr(index + token.size()); - if (str.size() == 0) { - splitString.push_back(str); - } - } else { - splitString.push_back(str); - str = ""; - } - } - return splitString; -} -void FormStServiceAbilityA::StartOtherAbility() -{ - APP_LOGI("FormStServiceAbilityA::StartOtherAbility begin targetBundle=%{public}s, targetAbility=%{public}s", - targetBundle_.c_str(), - targetAbility_.c_str()); - APP_LOGI("FormStServiceAbilityA::StartOtherAbility begin nextTargetBundleConn=%{public}s, " - "nextTargetAbilityConn=%{public}s", - nextTargetBundleConn_.c_str(), - nextTargetAbilityConn_.c_str()); - - if (!targetBundle_.empty() && !targetAbility_.empty()) { - std::vector strtargetBundles = Split(targetBundle_, ","); - std::vector strTargetAbilitys = Split(targetAbility_, ","); - for (size_t i = 0; i < strtargetBundles.size() && i < strTargetAbilitys.size(); i++) { - Want want; - want.SetElementName(strtargetBundles[i], strTargetAbilitys[i]); - want.SetParam("shouldReturn", shouldReturn_); - want.SetParam("targetBundle", nextTargetBundle_); - want.SetParam("targetAbility", nextTargetAbility_); - want.SetParam("targetBundleConn", nextTargetBundleConn_); - want.SetParam("targetAbilityConn", nextTargetAbilityConn_); - StartAbility(want); - sleep(1); - } - } -} -void FormStServiceAbilityA::ConnectOtherAbility() -{ - APP_LOGI( - "FormStServiceAbilityA::ConnectOtherAbility begin targetBundleConn=%{public}s, targetAbilityConn=%{public}s", - targetBundleConn_.c_str(), - targetAbilityConn_.c_str()); - APP_LOGI("FormStServiceAbilityA::ConnectOtherAbility begin nextTargetBundleConn=%{public}s, " - "nextTargetAbilityConn=%{public}s", - nextTargetBundleConn_.c_str(), - nextTargetAbilityConn_.c_str()); - - // connect service ability - if (!targetBundleConn_.empty() && !targetAbilityConn_.empty()) { - std::vector strtargetBundles = Split(targetBundleConn_, ","); - std::vector strTargetAbilitys = Split(targetAbilityConn_, ","); - for (size_t i = 0; i < strtargetBundles.size() && i < strTargetAbilitys.size(); i++) { - Want want; - want.SetElementName(strtargetBundles[i], strTargetAbilitys[i]); - want.SetParam("shouldReturn", shouldReturn_); - want.SetParam("targetBundle", nextTargetBundle_); - want.SetParam("targetAbility", nextTargetAbility_); - want.SetParam("targetBundleConn", nextTargetBundleConn_); - want.SetParam("targetAbilityConn", nextTargetAbilityConn_); - stub_ = new (std::nothrow) AbilityConnectCallback(); - connCallback_ = new (std::nothrow) AbilityConnectionProxy(stub_); - APP_LOGI("FormStServiceAbilityA::ConnectOtherAbility->ConnectAbility"); - bool ret = ConnectAbility(want, connCallback_); - sleep(1); - if (!ret) { - APP_LOGE("FormStServiceAbilityA::ConnectAbility failed!"); - } - } - } -} -void FormStServiceAbilityA::DisConnectOtherAbility() -{ - APP_LOGI("FormStServiceAbilityA::DisConnectOtherAbility begin"); - if (connCallback_ != nullptr) { - DisconnectAbility(connCallback_); - sleep(1); - } - APP_LOGI("FormStServiceAbilityA::DisConnectOtherAbility end"); -} - -void FormStServiceAbilityA::StopSelfAbility() -{ - APP_LOGI("FormStServiceAbilityA::StopSelfAbility"); - - TerminateAbility(); -} - -void FormStServiceAbilityA::OnStart(const Want &want) -{ - APP_LOGI("FormStServiceAbilityA::OnStart"); - - GetWantInfo(want); - Ability::OnStart(want); - PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnStart"); - SubscribeEvent(); - - // make exception for test - if (!zombie_.empty()) { - std::unique_ptr pWant = nullptr; - pWant->GetScheme(); - } -} -void FormStServiceAbilityA::OnCommand(const AAFwk::Want &want, bool restart, int startId) -{ - APP_LOGI("FormStServiceAbilityA::OnCommand"); - - GetWantInfo(want); - Ability::OnCommand(want, restart, startId); - PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnCommand"); -} -void FormStServiceAbilityA::OnNewWant(const Want &want) -{ - APP_LOGI("FormStServiceAbilityA::OnNewWant"); - - GetWantInfo(want); - Ability::OnNewWant(want); -} -void FormStServiceAbilityA::OnStop() -{ - APP_LOGI("FormStServiceAbilityA::OnStop"); - - Ability::OnStop(); - PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INITIAL, "OnStop"); -} -void FormStServiceAbilityA::OnActive() -{ - APP_LOGI("FormStServiceAbilityA::OnActive"); - - Ability::OnActive(); - PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::ACTIVE, "OnActive"); -} -void FormStServiceAbilityA::OnInactive() -{ - APP_LOGI("FormStServiceAbilityA::OnInactive"); - - Ability::OnInactive(); - PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::INACTIVE, "OnInactive"); -} -void FormStServiceAbilityA::OnBackground() -{ - APP_LOGI("FormStServiceAbilityA::OnBackground"); - - Ability::OnBackground(); - PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnBackground"); -} - -void FormStServiceAbilityA::Clear() -{ - shouldReturn_ = ""; - targetBundle_ = ""; - targetAbility_ = ""; - targetBundleConn_ = ""; - targetAbilityConn_ = ""; - nextTargetBundle_ = ""; - nextTargetAbility_ = ""; - nextTargetBundleConn_ = ""; - nextTargetAbilityConn_ = ""; -} -void FormStServiceAbilityA::GetWantInfo(const Want &want) -{ - Want mWant(want); - shouldReturn_ = mWant.GetStringParam("shouldReturn"); - targetBundle_ = mWant.GetStringParam("targetBundle"); - targetAbility_ = mWant.GetStringParam("targetAbility"); - targetBundleConn_ = mWant.GetStringParam("targetBundleConn"); - targetAbilityConn_ = mWant.GetStringParam("targetAbilityConn"); - nextTargetBundle_ = mWant.GetStringParam("nextTargetBundle"); - nextTargetAbility_ = mWant.GetStringParam("nextTargetAbility"); - nextTargetBundleConn_ = mWant.GetStringParam("nextTargetBundleConn"); - nextTargetAbilityConn_ = mWant.GetStringParam("nextTargetAbilityConn"); - zombie_ = mWant.GetStringParam("zombie"); - FormStServiceAbilityA::AbilityConnectCallback::onAbilityConnectDoneCount = 0; -} -bool FormStServiceAbilityA::PublishEvent(const std::string &eventName, const int &code, const std::string &data) -{ - APP_LOGI("FormStServiceAbilityA::PublishEvent eventName = %{public}s, code = %{public}d, data = %{public}s", - eventName.c_str(), - code, - data.c_str()); - - Want want; - want.SetAction(eventName); - CommonEventData commonData; - commonData.SetWant(want); - commonData.SetCode(code); - commonData.SetData(data); - return CommonEventManager::PublishCommonEvent(commonData); -} -sptr FormStServiceAbilityA::OnConnect(const Want &want) -{ - APP_LOGI("FormStServiceAbilityA::OnConnect"); - - sptr formProviderClient = new (std::nothrow) FormProviderClient(); - std::shared_ptr thisAbility = this->shared_from_this(); - formProviderClient->SetOwner(thisAbility); - - return formProviderClient; -} -void FormStServiceAbilityA::OnDisconnect(const Want &want) -{ - APP_LOGI("FormStServiceAbilityA::OnDisconnect"); - - Ability::OnDisconnect(want); - PublishEvent(APP_A_RESP_EVENT_NAME, AbilityLifecycleExecutor::LifecycleState::BACKGROUND, "OnDisconnect"); -} -bool FormStServiceAbilityA::SubscribeEvent() -{ - MatchingSkills matchingSkills; - matchingSkills.AddEvent(APP_A_REQ_EVENT_NAME); - CommonEventSubscribeInfo subscribeInfo(matchingSkills); - subscribeInfo.SetPriority(1); - subscriber_ = std::make_shared(subscribeInfo); - subscriber_->mainAbility_ = this; - return CommonEventManager::SubscribeCommonEvent(subscriber_); -} -void FormStServiceAbilityA::AppEventSubscriber::OnReceiveEvent(const CommonEventData &data) -{ - auto eventName = data.GetWant().GetAction(); - auto dataContent = data.GetData(); - APP_LOGI("FormStServiceAbilityA::OnReceiveEvent eventName = %{public}s, code = %{public}d, data = %{public}s", - eventName.c_str(), - data.GetCode(), - dataContent.c_str()); - if (APP_A_REQ_EVENT_NAME.compare(eventName) == 0) { - if (funcMap_.find(dataContent) == funcMap_.end()) { - APP_LOGI( - "FormStServiceAbilityA::OnReceiveEvent eventName = %{public}s, code = %{public}d, data = %{public}s", - eventName.c_str(), - data.GetCode(), - dataContent.c_str()); - } else { - if (mainAbility_ != nullptr) { - (mainAbility_->*funcMap_[dataContent])(); - } - } - } -} - -FormProviderInfo FormStServiceAbilityA::OnCreate(const Want &want) -{ - APP_LOGI("%{public}s start", __func__); - FormProviderInfo formProviderInfo; - if(!want.HasParameter(Constants::PARAM_FORM_IDENTITY_KEY)) { - APP_LOGE("%{public}s, formId not exist", __func__); - return formProviderInfo; - } - std::string formId = want.GetStringParam(Constants::PARAM_FORM_IDENTITY_KEY); - std::string jsonData = std::string("{\"city\":\"beijingA\"}"); - FormProviderData formProviderData = FormProviderData(jsonData); - formProviderInfo.SetFormData(formProviderData); - PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, "OnCreate"); - APP_LOGI("%{public}s end, formId: %{public}s", __func__, formId.c_str()); - return formProviderInfo; -} - -void FormStServiceAbilityA::OnUpdate(const int64_t formId) -{ - APP_LOGI("%{public}s start", __func__); - struct timespec ts; - clock_gettime(CLOCK_REALTIME, &ts); - long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; - - PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, "OnUpdate"); - APP_LOGI("%{public}s end, formId: %{public}lld, current time: %{public}ld", __func__, formId, currentTime); -} - -void FormStServiceAbilityA::OnTriggerEvent(const int64_t formId, const std::string &message) -{ - APP_LOGI("%{public}s start", __func__); - - struct timespec ts; - clock_gettime(CLOCK_REALTIME, &ts); - long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; - - PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, "OnTriggerEvent"); - APP_LOGI("%{public}s end, formId: %{public}lld, message: %{public}s, current time: %{public}ld", __func__, formId, message.c_str(), currentTime); -} - -void FormStServiceAbilityA::OnDelete(const int64_t formId) -{ - APP_LOGI("%{public}s start", __func__); - - struct timespec ts; - clock_gettime(CLOCK_REALTIME, &ts); - long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; - - PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, "OnDelete"); - APP_LOGI("%{public}s end, formId: %{public}lld, current time: %{public}ld", __func__, formId, currentTime); -} - -void FormStServiceAbilityA::OnCastTemptoNormal(const int64_t formId) -{ - APP_LOGI("%{public}s start", __func__); - - struct timespec ts; - clock_gettime(CLOCK_REALTIME, &ts); - long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; - - PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, "OnCastTemptoNormal"); - APP_LOGI("%{public}s end, formId: %{public}lld, current time: %{public}ld", __func__, formId, currentTime); -} - -void FormStServiceAbilityA::OnVisibilityChanged(const std::map &formEventsMap) -{ - APP_LOGI("%{public}s start", __func__); - - struct timespec ts; - clock_gettime(CLOCK_REALTIME, &ts); - long currentTime = ts.tv_sec * SEC_TO_MILLISEC + ts.tv_nsec / MILLISEC_TO_NANOSEC; - - PublishEvent(COMMON_EVENT_TEST_ACTION1, FORM_EVENT_TRIGGER_RESULT::FORM_EVENT_TRIGGER_RESULT_OK, "OnVisibilityChanged"); - APP_LOGI("%{public}s end, current time: %{public}ld", __func__, currentTime); -} - -REGISTER_AA(FormStServiceAbilityA); -} // namespace AppExecFwk -} // namespace OHOS diff --git a/test/resource/formsystemtestability/formSystemTestServiceA/src/form_st_service_ability_a1.cpp b/test/resource/formsystemtestability/formSystemTestServiceA/src/form_st_service_ability_a1.cpp old mode 100755 new mode 100644 index 8a3d6e97ff72f23d2984f4ebc23169c90fef389e..dfe34180b5989830052433c54d296728e457686a --- a/test/resource/formsystemtestability/formSystemTestServiceA/src/form_st_service_ability_a1.cpp +++ b/test/resource/formsystemtestability/formSystemTestServiceA/src/form_st_service_ability_a1.cpp @@ -287,7 +287,7 @@ void FormStServiceAbilityA1::AppEventSubscriber::OnReceiveEvent(const CommonEven } } -FormProviderInfo FormStServiceAbilityA1::OnCreate(const Want &want) +FormProviderInfo FormStServiceAbilityA1::OnCreateForm(const Want &want) { APP_LOGI("%{public}s start", __func__); FormProviderInfo formProviderInfo; diff --git a/test/systemtest/common/ams/ams_ability_visible_test/ams_ability_visible_test.cpp b/test/systemtest/common/ams/ams_ability_visible_test/ams_ability_visible_test.cpp index a5e0b79835adb858f54dfff248b545a0821e30eb..22a703ffbda6faf040c4f745626acba83dd18eee 100644 --- a/test/systemtest/common/ams/ams_ability_visible_test/ams_ability_visible_test.cpp +++ b/test/systemtest/common/ams/ams_ability_visible_test/ams_ability_visible_test.cpp @@ -174,11 +174,13 @@ public: static sptr abilityMs_; static STtools::Event event_; static std::shared_ptr subscriber_; + static int *memTestValue_; }; sptr AmsAbilityVisibleTest::appMs_ = nullptr; sptr AmsAbilityVisibleTest::abilityMs_ = nullptr; STtools::Event AmsAbilityVisibleTest::event_ = STtools::Event(); +int *AmsAbilityVisibleTest::memTestValue_ = nullptr; std::shared_ptr AmsAbilityVisibleTest::subscriber_ = nullptr; size_t AmsAbilityVisibleTest::AbilityConnectCallback::onAbilityConnectDoneCount = 0; int AmsAbilityVisibleTest::AbilityConnectCallback::resultConnectCode = 0; @@ -215,6 +217,10 @@ void AmsAbilityVisibleTest::SetUp(void) void AmsAbilityVisibleTest::TearDown(void) { GTEST_LOG_(INFO) << "void AmsAbilityVisibleTest::TearDown(void)"; + if (memTestValue_) { + delete[] memTestValue_; + } + std::vector bundleNames = GetBundleNames(bundleNameBase, bundleNameSuffix); STAbilityUtil::UninstallBundle(bundleNames); diff --git a/test/systemtest/common/bms/acts_bms_kit_system_test/acts_bms_kit_system_test.cpp b/test/systemtest/common/bms/acts_bms_kit_system_test/acts_bms_kit_system_test.cpp index 11805537bf3a3108a7d446a02de2551a39e7b10e..f1136e725d6e7371f3fdbe110b473200101ed6ed 100644 --- a/test/systemtest/common/bms/acts_bms_kit_system_test/acts_bms_kit_system_test.cpp +++ b/test/systemtest/common/bms/acts_bms_kit_system_test/acts_bms_kit_system_test.cpp @@ -53,6 +53,7 @@ const int TARGETVERSION = 3; namespace OHOS { namespace AppExecFwk { + class BundleStatusCallbackImpl : public BundleStatusCallbackHost { public: BundleStatusCallbackImpl(); @@ -193,6 +194,7 @@ public: void CheckFileNonExist(const std::string &bundleName, const std::string &modulePackage) const; static StressTestLevel stLevel_; }; + StressTestLevel ActsBmsKitSystemTest::stLevel_{}; void ActsBmsKitSystemTest::SetUpTestCase() @@ -226,7 +228,7 @@ void ActsBmsKitSystemTest::Install( InstallParam installParam; installParam.installFlag = installFlag; installParam.userId = Constants::DEFAULT_USERID; - sptr statusReceiver = new (std::nothrow) StatusReceiverImpl(); + sptr statusReceiver = (new (std::nothrow) StatusReceiverImpl()); EXPECT_NE(statusReceiver, nullptr); installerProxy->Install(bundleFilePath, installParam, statusReceiver); resvec.push_back(statusReceiver->GetResultMsg()); @@ -247,7 +249,7 @@ void ActsBmsKitSystemTest::Uninstall(const std::string &bundleName, std::vector< } else { InstallParam installParam; installParam.userId = Constants::DEFAULT_USERID; - sptr statusReceiver = new (std::nothrow) StatusReceiverImpl(); + sptr statusReceiver = (new (std::nothrow) StatusReceiverImpl()); EXPECT_NE(statusReceiver, nullptr); installerProxy->Uninstall(bundleName, installParam, statusReceiver); resvec.push_back(statusReceiver->GetResultMsg()); @@ -270,7 +272,7 @@ void ActsBmsKitSystemTest::HapUninstall( } else { InstallParam installParam; installParam.userId = Constants::DEFAULT_USERID; - sptr statusReceiver = new (std::nothrow) StatusReceiverImpl(); + sptr statusReceiver = (new (std::nothrow) StatusReceiverImpl()); EXPECT_NE(statusReceiver, nullptr); installerProxy->Uninstall(bundleName, modulePackage, installParam, statusReceiver); resvec.push_back(statusReceiver->GetResultMsg()); @@ -2427,8 +2429,11 @@ HWTEST_F(ActsBmsKitSystemTest, GetHapModuleInfo_0200, Function | MediumTest | Le std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle2.hap"; std::string appName = BASE_BUNDLE_NAME + "1"; Install(bundleFilePath, InstallFlag::NORMAL, resvec); + CommonTool commonTool; - EXPECT_EQ(commonTool.VectorToStr(resvec), "Success") << "install fail!"; + std::string installResult = commonTool.VectorToStr(resvec); + EXPECT_EQ(installResult, "Success") << "install fail!"; + AbilityInfo abilityInfo; abilityInfo.bundleName = appName; abilityInfo.package = BASE_BUNDLE_NAME + ".h1"; @@ -2457,7 +2462,8 @@ HWTEST_F(ActsBmsKitSystemTest, GetHapModuleInfo_0200, Function | MediumTest | Le } resvec.clear(); Uninstall(appName, resvec); - EXPECT_EQ(commonTool.VectorToStr(resvec), "Success") << "uninstall fail!"; + std::string uninstallResult = commonTool.VectorToStr(resvec); + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; if (!queryResult) { APP_LOGI("GetHapModuleInfo_0200 failed - cycle count: %{public}d", i); @@ -2465,6 +2471,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetHapModuleInfo_0200, Function | MediumTest | Le } result = true; } + if (result && stLevel_.BMSLevel > 1) { APP_LOGI("GetHapModuleInfo_0200 success - cycle count: %{public}d", stLevel_.BMSLevel); } @@ -3074,6 +3081,7 @@ HWTEST_F(ActsBmsKitSystemTest, Callback_0700, Function | MediumTest | Level1) std::string firstAppName = BASE_BUNDLE_NAME + "1"; std::string secondFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle7.hap"; std::string secondAppName = BASE_BUNDLE_NAME + "2"; + CommonTool commonTool; sptr firstBundleStatusCallback = (new (std::nothrow) BundleStatusCallbackImpl()); EXPECT_NE(firstBundleStatusCallback, nullptr); @@ -3085,28 +3093,37 @@ HWTEST_F(ActsBmsKitSystemTest, Callback_0700, Function | MediumTest | Level1) } bundleMgrProxy->RegisterBundleStatusCallback(firstBundleStatusCallback); Install(firstFilePath, InstallFlag::NORMAL, resvec); - EXPECT_EQ(commonTool.VectorToStr(resvec), "Success") << "install fail!"; + std::string firstinstallResult = commonTool.VectorToStr(resvec); + EXPECT_EQ(firstinstallResult, "Success") << "install fail!"; + resvec.clear(); sptr secondBundleStatusCallback = (new (std::nothrow) BundleStatusCallbackImpl()); EXPECT_NE(secondBundleStatusCallback, nullptr); secondBundleStatusCallback->SetBundleName(secondAppName); bundleMgrProxy->RegisterBundleStatusCallback(secondBundleStatusCallback); Install(secondFilePath, InstallFlag::NORMAL, resvec); - EXPECT_EQ(commonTool.VectorToStr(resvec), "Success") << "install fail!"; + std::string secondinstallResult = commonTool.VectorToStr(resvec); + EXPECT_EQ(secondinstallResult, "Success") << "install fail!"; + bool clearResult = bundleMgrProxy->ClearBundleStatusCallback(firstBundleStatusCallback); EXPECT_TRUE(clearResult); + std::vector resvec2; Uninstall(firstAppName, resvec2); - EXPECT_EQ(commonTool.VectorToStr(resvec2), "Success") << "uninstall fail!"; + std::string uninstallResult = commonTool.VectorToStr(resvec2); + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; resvec2.clear(); Uninstall(secondAppName, resvec2); - EXPECT_EQ(commonTool.VectorToStr(resvec2), "Success") << "uninstall fail!"; + uninstallResult = commonTool.VectorToStr(resvec2); + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; + if (!clearResult) { APP_LOGI("Callback_0700 failed - cycle count: %{public}d", i); break; } result = true; } + if (result && stLevel_.BMSLevel > 1) { APP_LOGI("Callback_0700 success - cycle count: %{public}d", stLevel_.BMSLevel); } @@ -3135,6 +3152,7 @@ HWTEST_F(ActsBmsKitSystemTest, Callback_0800, Function | MediumTest | Level1) std::string firstAppName = BASE_BUNDLE_NAME + "1"; std::string secondFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle7.hap"; std::string secondAppName = BASE_BUNDLE_NAME + "2"; + CommonTool commonTool; sptr firstBundleStatusCallback = (new (std::nothrow) BundleStatusCallbackImpl()); EXPECT_NE(firstBundleStatusCallback, nullptr); @@ -3148,6 +3166,7 @@ HWTEST_F(ActsBmsKitSystemTest, Callback_0800, Function | MediumTest | Level1) Install(firstFilePath, InstallFlag::NORMAL, resvec); std::string firstinstallResult = commonTool.VectorToStr(resvec); EXPECT_EQ(firstinstallResult, "Success") << "install fail!"; + resvec.clear(); sptr secondBundleStatusCallback = (new (std::nothrow) BundleStatusCallbackImpl()); EXPECT_NE(secondBundleStatusCallback, nullptr); @@ -3156,20 +3175,26 @@ HWTEST_F(ActsBmsKitSystemTest, Callback_0800, Function | MediumTest | Level1) Install(secondFilePath, InstallFlag::NORMAL, resvec); std::string secondinstallResult = commonTool.VectorToStr(resvec); EXPECT_EQ(secondinstallResult, "Success") << "install fail!"; + bool clearResult = bundleMgrProxy->ClearBundleStatusCallback(secondBundleStatusCallback); EXPECT_TRUE(clearResult); + std::vector resvec2; Uninstall(firstAppName, resvec2); - EXPECT_EQ(commonTool.VectorToStr(resvec2), "Success") << "uninstall fail!"; + std::string uninstallResult = commonTool.VectorToStr(resvec2); + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; resvec2.clear(); Uninstall(secondAppName, resvec2); - EXPECT_EQ(commonTool.VectorToStr(resvec2), "Success") << "uninstall fail!"; + uninstallResult = commonTool.VectorToStr(resvec2); + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; + if (!clearResult) { APP_LOGI("Callback_0800 failed - cycle count: %{public}d", i); break; } result = true; } + if (result && stLevel_.BMSLevel > 1) { APP_LOGI("Callback_0800 success - cycle count: %{public}d", stLevel_.BMSLevel); } @@ -3199,6 +3224,7 @@ HWTEST_F(ActsBmsKitSystemTest, Callback_0900, Function | MediumTest | Level1) std::string firstAppName = BASE_BUNDLE_NAME + "1"; std::string secondFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle7.hap"; std::string secondAppName = BASE_BUNDLE_NAME + "2"; + CommonTool commonTool; sptr firstBundleStatusCallback = (new (std::nothrow) BundleStatusCallbackImpl()); EXPECT_NE(firstBundleStatusCallback, nullptr); @@ -3210,30 +3236,39 @@ HWTEST_F(ActsBmsKitSystemTest, Callback_0900, Function | MediumTest | Level1) } bundleMgrProxy->RegisterBundleStatusCallback(firstBundleStatusCallback); Install(firstFilePath, InstallFlag::NORMAL, resvec); - EXPECT_EQ(commonTool.VectorToStr(resvec), "Success") << "install fail!"; + std::string firstinstallResult = commonTool.VectorToStr(resvec); + EXPECT_EQ(firstinstallResult, "Success") << "install fail!"; + resvec.clear(); sptr secondBundleStatusCallback = (new (std::nothrow) BundleStatusCallbackImpl()); EXPECT_NE(secondBundleStatusCallback, nullptr); secondBundleStatusCallback->SetBundleName(secondAppName); bundleMgrProxy->RegisterBundleStatusCallback(secondBundleStatusCallback); Install(secondFilePath, InstallFlag::NORMAL, resvec); - EXPECT_EQ(commonTool.VectorToStr(resvec), "Success") << "install fail!"; + std::string secondinstallResult = commonTool.VectorToStr(resvec); + EXPECT_EQ(secondinstallResult, "Success") << "install fail!"; + bool clearResult1 = bundleMgrProxy->ClearBundleStatusCallback(firstBundleStatusCallback); EXPECT_TRUE(clearResult1); bool clearResult2 = bundleMgrProxy->ClearBundleStatusCallback(secondBundleStatusCallback); EXPECT_TRUE(clearResult2); + std::vector resvec2; Uninstall(firstAppName, resvec2); - EXPECT_EQ(commonTool.VectorToStr(resvec2), "Success") << "uninstall fail!"; + std::string uninstallResult = commonTool.VectorToStr(resvec2); + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; resvec2.clear(); Uninstall(secondAppName, resvec2); - EXPECT_EQ(commonTool.VectorToStr(resvec2), "Success") << "uninstall fail!"; + uninstallResult = commonTool.VectorToStr(resvec2); + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; + if (!clearResult1 && !clearResult2) { APP_LOGI("Callback_0900 failed - cycle count: %{public}d", i); break; } result = true; } + if (result && stLevel_.BMSLevel > 1) { APP_LOGI("Callback_0900 success - cycle count: %{public}d", stLevel_.BMSLevel); } @@ -3446,6 +3481,7 @@ HWTEST_F(ActsBmsKitSystemTest, CleanBundleCacheFiles_0400, Function | MediumTest std::vector resvec; std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle45.hap"; std::string appName = BASE_BUNDLE_NAME + "1"; + CommonTool commonTool; Install(bundleFilePath, InstallFlag::NORMAL, resvec); std::string installResult = commonTool.VectorToStr(resvec); @@ -3475,15 +3511,19 @@ HWTEST_F(ActsBmsKitSystemTest, CleanBundleCacheFiles_0400, Function | MediumTest EXPECT_NE(name1Exist, 0) << "the cache test dir1 exists."; name2Exist = access(testCacheDir2.c_str(), F_OK); EXPECT_NE(name2Exist, 0) << "the cache test dir2 exists."; + resvec.clear(); Uninstall(appName, resvec); - EXPECT_EQ(commonTool.VectorToStr(resvec), "Success") << "uninstall fail!"; + std::string uninstallResult = commonTool.VectorToStr(resvec); + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; + if (!cleanCacheResult) { APP_LOGI("CleanBundleCacheFiles_0400 failed - cycle count: %{public}d", i); break; } result = true; } + if (result && stLevel_.BMSLevel > 1) { APP_LOGI("CleanBundleCacheFiles_0400 success - cycle count: %{public}d", stLevel_.BMSLevel); } @@ -3943,8 +3983,11 @@ HWTEST_F(ActsBmsKitSystemTest, AbilityDump_0100, Function | MediumTest | Level0) std::string appName = BASE_BUNDLE_NAME + "1"; std::string abilityName = "bmsThirdBundle_A1"; Install(bundleFilePath, InstallFlag::NORMAL, resvec); + CommonTool commonTool; - EXPECT_EQ(commonTool.VectorToStr(resvec), "Success") << "install fail!"; + std::string installResult = commonTool.VectorToStr(resvec); + EXPECT_EQ(installResult, "Success") << "install fail!"; + Want want; ElementName name; name.SetAbilityName(abilityName); @@ -3960,6 +4003,7 @@ HWTEST_F(ActsBmsKitSystemTest, AbilityDump_0100, Function | MediumTest | Level0) bool queryResult = bundleMgrProxy->QueryAbilityInfo(want, abilityInfo); EXPECT_EQ(abilityInfo.name, abilityName); EXPECT_TRUE(queryResult); + std::string path = "/data/test/abilityInfo.txt"; std::ofstream file(path); file.close(); @@ -3970,15 +4014,19 @@ HWTEST_F(ActsBmsKitSystemTest, AbilityDump_0100, Function | MediumTest | Level0) long length = lseek(fd, 0, SEEK_END); EXPECT_GT(length, 0); close(fd); + resvec.clear(); Uninstall(appName, resvec); - EXPECT_EQ(commonTool.VectorToStr(resvec), "Success") << "uninstall fail!"; + std::string uninstallResult = commonTool.VectorToStr(resvec); + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; + if (!queryResult) { APP_LOGI("AbilityDump_0100 failed - cycle count: %{public}d", i); break; } result = true; } + if (result && stLevel_.BMSLevel > 1) { APP_LOGI("AbilityDump_0100 success - cycle count: %{public}d", stLevel_.BMSLevel); } @@ -4432,10 +4480,14 @@ HWTEST_F(ActsBmsKitSystemTest, ApplicationInfo_0100, Function | MediumTest | Lev bool result = false; for (int i = 1; i <= stLevel_.BMSLevel; i++) { std::vector resvec; + std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle1.hap"; std::string appName = BASE_BUNDLE_NAME + "1"; - Install(THIRD_BUNDLE_PATH + "bmsThirdBundle1.hap", InstallFlag::NORMAL, resvec); + Install(bundleFilePath, InstallFlag::NORMAL, resvec); + CommonTool commonTool; - EXPECT_EQ(commonTool.VectorToStr(resvec), "Success") << "install fail!"; + std::string installResult = commonTool.VectorToStr(resvec); + EXPECT_EQ(installResult, "Success") << "install fail!"; + ApplicationInfo appInfo; int userId = Constants::DEFAULT_USERID; sptr bundleMgrProxy = GetBundleMgrProxy(); @@ -4453,7 +4505,8 @@ HWTEST_F(ActsBmsKitSystemTest, ApplicationInfo_0100, Function | MediumTest | Lev file.close(); int fd = open(path.c_str(), O_RDWR); EXPECT_NE(fd, -1) << "open file error"; - pAppInfo->Dump("[pAppInfo]", fd); + std::string prefix = "[pAppInfo]"; + pAppInfo->Dump(prefix, fd); long length = lseek(fd, 0, SEEK_END); lseek(fd, 0, SEEK_SET); std::string strAppInfo; @@ -4464,15 +4517,19 @@ HWTEST_F(ActsBmsKitSystemTest, ApplicationInfo_0100, Function | MediumTest | Lev std::string cacheDir = BUNDLE_DATA_ROOT_PATH + appName + "/cache"; EXPECT_TRUE(IsSubStr(strAppInfo, cacheDir)); close(fd); + resvec.clear(); Uninstall(appName, resvec); - EXPECT_EQ(commonTool.VectorToStr(resvec), "Success") << "uninstall fail!"; + std::string uninstallResult = commonTool.VectorToStr(resvec); + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; + if (retVal <= 0) { APP_LOGI("ApplicationInfo_0100 failed - cycle count: %{public}d", i); break; } result = true; } + if (result && stLevel_.BMSLevel > 1) { APP_LOGI("ApplicationInfo_0100 success - cycle count: %{public}d", stLevel_.BMSLevel); } @@ -4624,7 +4681,7 @@ HWTEST_F(ActsBmsKitSystemTest, Uninstall_KeepData_0100, Function | MediumTest | installParam.installFlag = InstallFlag::NORMAL; installParam.userId = Constants::DEFAULT_USERID; installParam.isKeepData = false; - sptr statusReceiver = new (std::nothrow) StatusReceiverImpl(); + sptr statusReceiver = (new (std::nothrow) StatusReceiverImpl()); EXPECT_NE(statusReceiver, nullptr); installerProxy->Install(bundleFilePath, installParam, statusReceiver); std::string installMsg = statusReceiver->GetResultMsg(); @@ -4661,7 +4718,7 @@ HWTEST_F(ActsBmsKitSystemTest, Uninstall_KeepData_0200, Function | MediumTest | installParam.installFlag = InstallFlag::NORMAL; installParam.userId = Constants::DEFAULT_USERID; installParam.isKeepData = true; - sptr statusReceiver = new (std::nothrow) StatusReceiverImpl(); + sptr statusReceiver = (new (std::nothrow) StatusReceiverImpl()); EXPECT_NE(statusReceiver, nullptr); installerProxy->Install(bundleFilePath, installParam, statusReceiver); std::string installMsg = statusReceiver->GetResultMsg(); @@ -4698,14 +4755,14 @@ HWTEST_F(ActsBmsKitSystemTest, Uninstall_KeepData_0300, Function | MediumTest | installParam.installFlag = InstallFlag::NORMAL; installParam.userId = Constants::DEFAULT_USERID; installParam.isKeepData = false; - sptr statusReceiver = new (std::nothrow) StatusReceiverImpl(); + sptr statusReceiver = (new (std::nothrow) StatusReceiverImpl()); EXPECT_NE(statusReceiver, nullptr); installerProxy->Install(bundleFilePath, installParam, statusReceiver); std::string installMsg = statusReceiver->GetResultMsg(); EXPECT_EQ(installMsg, "Success") << "install fail!"; bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle4.hap"; - sptr statusReceiver2 = new (std::nothrow) StatusReceiverImpl(); + sptr statusReceiver2 = (new (std::nothrow) StatusReceiverImpl()); EXPECT_NE(statusReceiver2, nullptr); installerProxy->Install(bundleFilePath, installParam, statusReceiver2); installMsg = statusReceiver2->GetResultMsg(); @@ -4749,14 +4806,14 @@ HWTEST_F(ActsBmsKitSystemTest, Uninstall_KeepData_0400, Function | MediumTest | installParam.installFlag = InstallFlag::NORMAL; installParam.userId = Constants::DEFAULT_USERID; installParam.isKeepData = true; - sptr statusReceiver = new (std::nothrow) StatusReceiverImpl(); + sptr statusReceiver = (new (std::nothrow) StatusReceiverImpl()); EXPECT_NE(statusReceiver, nullptr); installerProxy->Install(bundleFilePath, installParam, statusReceiver); std::string installMsg = statusReceiver->GetResultMsg(); EXPECT_EQ(installMsg, "Success") << "install fail!"; bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle4.hap"; - sptr statusReceiver2 = new (std::nothrow) StatusReceiverImpl(); + sptr statusReceiver2 = (new (std::nothrow) StatusReceiverImpl()); EXPECT_NE(statusReceiver2, nullptr); installerProxy->Install(bundleFilePath, installParam, statusReceiver2); installMsg = statusReceiver2->GetResultMsg(); @@ -4795,20 +4852,24 @@ HWTEST_F(ActsBmsKitSystemTest, GetBundlesForUid_0100, Function | MediumTest | Le APP_LOGE("bundle mgr proxy is nullptr."); EXPECT_EQ(bundleMgrProxy, nullptr); } + std::string installResult; CommonTool commonTool; for (int i = 6; i <= 8; i++) { std::vector resvec; std::string hapFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle" + std::to_string(i) + ".hap"; + std::cout << "begin install" << hapFilePath << std::endl; Install(hapFilePath, InstallFlag::NORMAL, resvec); - EXPECT_EQ(commonTool.VectorToStr(resvec), "Success") << "install fail!"; + installResult = commonTool.VectorToStr(resvec); + EXPECT_EQ(installResult, "Success") << "install fail!"; } bool ret; for (int i = 1; i <= 3; i++) { std::string appName = BASE_BUNDLE_NAME + std::to_string(i); BundleInfo bundleInfo; bundleMgrProxy->GetBundleInfo(appName, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo); + int uid = bundleInfo.uid; std::vector bundleNames; - ret = bundleMgrProxy->GetBundlesForUid(bundleInfo.uid, bundleNames); + ret = bundleMgrProxy->GetBundlesForUid(uid, bundleNames); EXPECT_TRUE(ret); for (auto bundleName : bundleNames) { EXPECT_EQ(bundleName, appName); @@ -4818,7 +4879,8 @@ HWTEST_F(ActsBmsKitSystemTest, GetBundlesForUid_0100, Function | MediumTest | Le std::vector resvec; std::string appName = BASE_BUNDLE_NAME + std::to_string(i); Uninstall(appName, resvec); - EXPECT_EQ(commonTool.VectorToStr(resvec), "Success") << "uninstall fail!"; + std::string uninstallResult = commonTool.VectorToStr(resvec); + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; } if (!ret) { APP_LOGI("GetBundlesForUid_0100 failed - cycle count: %{public}d", i); @@ -4923,39 +4985,55 @@ HWTEST_F(ActsBmsKitSystemTest, GetNameForUid_0100, Function | MediumTest | Level bool result = false; for (int i = 1; i <= stLevel_.BMSLevel; i++) { CommonTool commonTool; + std::string installResult; std::vector resvec; - std::string name1, name2; - Install(THIRD_BUNDLE_PATH + "bmsThirdBundle6.hap", InstallFlag::NORMAL, resvec); - EXPECT_EQ(commonTool.VectorToStr(resvec), "Success") << "install fail!"; + std::string bundleFilePath1 = THIRD_BUNDLE_PATH + "bmsThirdBundle6.hap"; + std::string bundleFilePath2 = THIRD_BUNDLE_PATH + "bmsThirdBundle7.hap"; + std::string appName1 = BASE_BUNDLE_NAME + '1'; + std::string appName2 = BASE_BUNDLE_NAME + '2'; + std::string name1; + std::string name2; + Install(bundleFilePath1, InstallFlag::NORMAL, resvec); + installResult = commonTool.VectorToStr(resvec); + EXPECT_EQ(installResult, "Success") << "install fail!"; resvec.clear(); sptr bundleMgrProxy = GetBundleMgrProxy(); if (!bundleMgrProxy) { APP_LOGE("bundle mgr proxy is nullptr."); EXPECT_EQ(bundleMgrProxy, nullptr); } + BundleInfo bundleInfo1; - bundleMgrProxy->GetBundleInfo(BASE_BUNDLE_NAME + '1', BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo1); - bool ret = bundleMgrProxy->GetNameForUid(bundleInfo1.uid, name1); + bundleMgrProxy->GetBundleInfo(appName1, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo1); + int uid1 = bundleInfo1.uid; + bool ret = bundleMgrProxy->GetNameForUid(uid1, name1); EXPECT_TRUE(ret); - Uninstall(BASE_BUNDLE_NAME + '1', resvec); + + Uninstall(appName1, resvec); EXPECT_EQ(commonTool.VectorToStr(resvec), "Success") << "uninstall fail!"; resvec.clear(); - Install(THIRD_BUNDLE_PATH + "bmsThirdBundle7.hap", InstallFlag::NORMAL, resvec); - EXPECT_EQ(commonTool.VectorToStr(resvec), "Success") << "install fail!"; + Install(bundleFilePath2, InstallFlag::NORMAL, resvec); + installResult = commonTool.VectorToStr(resvec); + EXPECT_EQ(installResult, "Success") << "install fail!"; resvec.clear(); - Install(THIRD_BUNDLE_PATH + "bmsThirdBundle6.hap", InstallFlag::NORMAL, resvec); - EXPECT_EQ(commonTool.VectorToStr(resvec), "Success") << "install fail!"; + + Install(bundleFilePath1, InstallFlag::NORMAL, resvec); + installResult = commonTool.VectorToStr(resvec); + EXPECT_EQ(installResult, "Success") << "install fail!"; + BundleInfo bundleInfo2; - bundleMgrProxy->GetBundleInfo(BASE_BUNDLE_NAME + '1', BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo2); - ret = bundleMgrProxy->GetNameForUid(bundleInfo2.uid, name2); + bundleMgrProxy->GetBundleInfo(appName1, BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo2); + int uid2 = bundleInfo2.uid; + ret = bundleMgrProxy->GetNameForUid(uid2, name2); EXPECT_TRUE(ret); - EXPECT_NE(bundleInfo1.uid, bundleInfo2.uid); + EXPECT_NE(uid1, uid2); EXPECT_EQ(name1, name2); for (int i = 1; i <= 2; i++) { std::string appName = BASE_BUNDLE_NAME + std::to_string(i); std::vector resvec2; Uninstall(appName, resvec2); - EXPECT_EQ(commonTool.VectorToStr(resvec2), "Success") << "uninstall fail!"; + std::string uninstallResult = commonTool.VectorToStr(resvec2); + EXPECT_EQ(uninstallResult, "Success") << "uninstall fail!"; } if (!ret) { APP_LOGI("GetNameForUid_0100 failed - cycle count: %{public}d", i); @@ -4963,6 +5041,7 @@ HWTEST_F(ActsBmsKitSystemTest, GetNameForUid_0100, Function | MediumTest | Level } result = true; } + if (result && stLevel_.BMSLevel > 1) { APP_LOGI("GetNameForUid_0100 success - cycle count: %{public}d", stLevel_.BMSLevel); } @@ -5753,4 +5832,4 @@ HWTEST_F(ActsBmsKitSystemTest, IsApplicationEnabled_0300, Function | MediumTest std::cout << "END IsApplicationEnabled_0300" << std::endl; } } // namespace AppExecFwk -} // namespace OHOS +} // namespace OHOS \ No newline at end of file diff --git a/test/systemtest/common/bms/bms_compatible_system_test/bms_compatible_system_test.cpp b/test/systemtest/common/bms/bms_compatible_system_test/bms_compatible_system_test.cpp index eeb0dcf8762895e8cf0c0bd958245b0daca0fa6b..b0287ef45e2f681f8d09a6dfe90a3cb2307b2e16 100644 --- a/test/systemtest/common/bms/bms_compatible_system_test/bms_compatible_system_test.cpp +++ b/test/systemtest/common/bms/bms_compatible_system_test/bms_compatible_system_test.cpp @@ -49,6 +49,7 @@ const int MIN_WIDTH = 100; const int DEFAULT_HEIGHT = 100; const int DEFAULT_WIDTH = 200; const int FORM_NUM = 3; + } // namespace using OHOS::AAFwk::Want; using namespace testing::ext; @@ -151,7 +152,7 @@ void BmsCompatibleSystemTest::Uninstall(const std::string &bundleName, std::stri } else { InstallParam installParam; installParam.userId = Constants::DEFAULT_USERID; - sptr statusReceiver = new (std::nothrow) StatusReceiverImpl(); + sptr statusReceiver = (new (std::nothrow) StatusReceiverImpl()); EXPECT_NE(statusReceiver, nullptr); installerProxy->Uninstall(bundleName, installParam, statusReceiver); uninstallMessage = statusReceiver->GetResultMsg(); @@ -724,5 +725,6 @@ HWTEST_F(BmsCompatibleSystemTest, BMS_QueryAbilityInfoByUri_0300, Function | Med EXPECT_EQ(abilityInfo.uri, ""); GTEST_LOG_(INFO) << "END BMS_QueryAbilityInfoByUri_0300"; } + } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/test/systemtest/common/bms/bms_install_system_test/bms_install_system_test.cpp b/test/systemtest/common/bms/bms_install_system_test/bms_install_system_test.cpp index 3c2cf82c4e07efb70749da69a328ec0410feb9ec..b018a324f714d7dc0d19c17b3f7680aa08257bc7 100755 --- a/test/systemtest/common/bms/bms_install_system_test/bms_install_system_test.cpp +++ b/test/systemtest/common/bms/bms_install_system_test/bms_install_system_test.cpp @@ -31,6 +31,7 @@ using namespace testing::ext; using namespace std::chrono_literals; namespace { + const std::string THIRD_BUNDLE_PATH = "/data/test/bms_bundle/"; const std::string CODE_ROOT_PATH = "/data/accounts/account_0/applications/"; const std::string DATA_ROOT_PATH = "/data/accounts/account_0/appdata/"; @@ -40,7 +41,6 @@ const std::string SYSTEM_BASE_BUNDLE_NAME = "com.system.hiworld.example"; const std::string MSG_SUCCESS = "[SUCCESS]"; const std::string OPERATION_FAILURE = "Failure"; const std::string OPERATION_SUCCESS = "Success"; -const int TIMEOUT = 10; } // namespace namespace OHOS { @@ -87,7 +87,7 @@ void StatusReceiverImpl::OnFinished(const int32_t resultCode, const std::string std::string StatusReceiverImpl::GetResultMsg() const { auto future = resultMsgSignal_.get_future(); - std::chrono::seconds timeout(TIMEOUT); + std::chrono::seconds timeout(10); if (future.wait_for(timeout) == std::future_status::timeout) { return OPERATION_FAILURE + " timeout"; } @@ -103,7 +103,6 @@ public: explicit SubscriberTest(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp){}; virtual void OnReceiveEvent(const CommonEventData &data) override; std::string GetSubscriberResultMsg() const; - virtual ~SubscriberTest() = default; private: mutable std::promise subscriberMsgSignal_; @@ -2446,5 +2445,6 @@ HWTEST_F(BmsInstallSystemTest, BMS_DFX_0400, Function | MediumTest | Level2) EXPECT_FALSE(getInfoResult); std::cout << "END BMS_DFX_0400" << std::endl; } + } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/test/systemtest/common/bms/bms_launcher_service_system_test/bms_launcher_service_system_test.cpp b/test/systemtest/common/bms/bms_launcher_service_system_test/bms_launcher_service_system_test.cpp index 30137f71ee9761cc5de883d40a822cd907ba3ade..3fa58800fc32e6c7b93f7d0d68cc485c523d4861 100644 --- a/test/systemtest/common/bms/bms_launcher_service_system_test/bms_launcher_service_system_test.cpp +++ b/test/systemtest/common/bms/bms_launcher_service_system_test/bms_launcher_service_system_test.cpp @@ -44,7 +44,7 @@ const std::string BUNDLE_ADD = "Bundle Add Success"; const std::string BUNDLE_UPDATE = "Bundle Update Success"; const std::string BUNDLE_REMOVE = "Bundle Remove Success"; constexpr uint32_t WAIT_SECONDS = 5; -const unsigned int LIST_SIZE = 2; + } // namespace using OHOS::AAFwk::Want; using namespace testing::ext; @@ -173,7 +173,7 @@ void BmsLauncherServiceSystemTest::Install( InstallParam installParam; installParam.installFlag = installFlag; installParam.userId = Constants::DEFAULT_USERID; - sptr statusReceiver = new (std::nothrow) StatusReceiverImpl(); + sptr statusReceiver = (new (std::nothrow) StatusReceiverImpl()); EXPECT_NE(statusReceiver, nullptr); installerProxy->Install(bundleFilePath, installParam, statusReceiver); installMessage = statusReceiver->GetResultMsg(); @@ -194,7 +194,7 @@ void BmsLauncherServiceSystemTest::Uninstall(const std::string &bundleName, std: } else { InstallParam installParam; installParam.userId = Constants::DEFAULT_USERID; - sptr statusReceiver = new (std::nothrow) StatusReceiverImpl(); + sptr statusReceiver = (new (std::nothrow) StatusReceiverImpl()); EXPECT_NE(statusReceiver, nullptr); installerProxy->Uninstall(bundleName, installParam, statusReceiver); uninstallMessage = statusReceiver->GetResultMsg(); @@ -294,13 +294,13 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_Register_0100, Function | MediumTest std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle1.hap"; std::string bundleName = "com.example.third1"; std::string message; - LauncherService launcherservice; + std::shared_ptr launcherservice = std::make_shared(); sptr callback = new TestBundleStatusCallback(); - launcherservice.RegisterCallback(callback); + launcherservice->RegisterCallback(callback); Install(bundleFilePath, InstallFlag::NORMAL, message); EXPECT_EQ(message, "Success") << "install fail!"; EXPECT_TRUE(Wait(BUNDLE_ADD)); - launcherservice.UnRegisterCallback(); + launcherservice->UnRegisterCallback(); Uninstall(bundleName, message); EXPECT_EQ(message, "Success") << "uninstall fail!"; GTEST_LOG_(INFO) << "END BMS_Register_0100"; @@ -316,15 +316,15 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_Register_0200, Function | MediumTest std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle1.hap"; std::string bundleName = "com.example.third1"; std::string message; - LauncherService launcherservice; + std::shared_ptr launcherservice = std::make_shared(); sptr callback = new TestBundleStatusCallback(); - launcherservice.RegisterCallback(callback); + launcherservice->RegisterCallback(callback); Install(bundleFilePath, InstallFlag::NORMAL, message); EXPECT_EQ(message, "Success") << "install fail!"; Uninstall(bundleName, message); EXPECT_TRUE(Wait(BUNDLE_REMOVE)); EXPECT_EQ(message, "Success") << "uninstall fail!"; - launcherservice.UnRegisterCallback(); + launcherservice->UnRegisterCallback(); GTEST_LOG_(INFO) << "END BMS_Register_0200"; } /** @@ -339,16 +339,16 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_Register_0300, Function | MediumTest std::string bundleFilePath1 = THIRD_BUNDLE_PATH + "bmsThirdBundle1.hap"; std::string bundleFilePath2 = THIRD_BUNDLE_PATH + "bmsThirdBundle4.hap"; std::string message; - LauncherService launcherservice; + std::shared_ptr launcherservice = std::make_shared(); sptr callback = new TestBundleStatusCallback(); - launcherservice.RegisterCallback(callback); + launcherservice->RegisterCallback(callback); Install(bundleFilePath1, InstallFlag::NORMAL, message); EXPECT_EQ(message, "Success") << "install fail!"; EXPECT_TRUE(Wait(BUNDLE_ADD)); Install(bundleFilePath2, InstallFlag::REPLACE_EXISTING, message); EXPECT_EQ(message, "Success") << "install fail!"; EXPECT_TRUE(Wait(BUNDLE_UPDATE)); - launcherservice.UnRegisterCallback(); + launcherservice->UnRegisterCallback(); Uninstall(bundleName, message); EXPECT_EQ(message, "Success") << "uninstall fail!"; GTEST_LOG_(INFO) << "END BMS_Register_0300"; @@ -364,10 +364,10 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_Register_0400, Function | MediumTest std::string bundleName = THIRD_BASE_BUNDLE_NAME + "2"; std::string bundleFilePath = THIRD_BUNDLE_PATH + "bmsThirdBundle2.hap"; std::string message; - LauncherService launcherservice; + std::shared_ptr launcherservice = std::make_shared(); sptr callback = new TestBundleStatusCallback(); - launcherservice.RegisterCallback(callback); - launcherservice.UnRegisterCallback(); + launcherservice->RegisterCallback(callback); + launcherservice->UnRegisterCallback(); Install(bundleFilePath, InstallFlag::NORMAL, message); EXPECT_EQ(message, "Success") << "install fail!"; EXPECT_FALSE(Wait(BUNDLE_ADD)); @@ -392,9 +392,13 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetAbilityList_0100, Function | Mediu Install(bundleFilePath, InstallFlag::NORMAL, message); EXPECT_EQ(message, "Success") << "install fail!"; - LauncherService launcherservice; + std::shared_ptr launcherservice = std::make_shared(); std::vector launcherAbilityInfos; - bool result = launcherservice.GetAbilityList(bundleName, userId, launcherAbilityInfos); + if (!launcherservice) { + APP_LOGE("launcher service is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->GetAbilityList(bundleName, userId, launcherAbilityInfos); EXPECT_TRUE(result) << "Get ability list failed"; EXPECT_FALSE(launcherAbilityInfos.empty()) << "Launcher ability infos is empty"; EXPECT_EQ(launcherAbilityInfos[0].name, abilityName); @@ -425,9 +429,13 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetAbilityList_0200, Function | Mediu Install(bundleFilePath2, InstallFlag::REPLACE_EXISTING, message); EXPECT_EQ(message, "Success") << "install fail!"; - LauncherService launcherservice; + std::shared_ptr launcherservice = std::make_shared(); std::vector launcherAbilityInfos; - bool result = launcherservice.GetAbilityList(bundleName, userId, launcherAbilityInfos); + if (!launcherservice) { + APP_LOGE("launcher service is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->GetAbilityList(bundleName, userId, launcherAbilityInfos); EXPECT_TRUE(result) << "Get ability list failed"; EXPECT_FALSE(launcherAbilityInfos.empty()) << "Launcher ability infos is empty"; EXPECT_EQ(launcherAbilityInfos[0].name, abilityName); @@ -454,12 +462,15 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetAbilityList_0300, Function | Mediu Install(bundleFilePath, InstallFlag::NORMAL, message); EXPECT_EQ(message, "Success") << "install fail!"; std::vector launcherAbilityInfos; - LauncherService launcherservice; - - bool result = launcherservice.GetAbilityList(bundleName, userId, launcherAbilityInfos); + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcher service is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->GetAbilityList(bundleName, userId, launcherAbilityInfos); EXPECT_TRUE(result) << "Get ability list failed"; EXPECT_FALSE(launcherAbilityInfos.empty()) << "Launcher ability infos is empty"; - EXPECT_EQ(launcherAbilityInfos.size(), LIST_SIZE); + EXPECT_GE(launcherAbilityInfos.size(), 1); EXPECT_EQ(launcherAbilityInfos[0].name, abilityName1); EXPECT_EQ(launcherAbilityInfos[1].name, abilityName2); Uninstall(bundleName, message); @@ -489,12 +500,15 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetAbilityList_0400, Function | Mediu Install(bundleFilePath2, InstallFlag::NORMAL, message); EXPECT_EQ(message, "Success") << "install fail!"; std::vector launcherAbilityInfos; - LauncherService launcherservice; - - bool result = launcherservice.GetAbilityList(bundleName, userId, launcherAbilityInfos); + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcher service is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->GetAbilityList(bundleName, userId, launcherAbilityInfos); EXPECT_TRUE(result) << "Get ability list failed"; EXPECT_FALSE(launcherAbilityInfos.empty()) << "Launcher ability infos is empty"; - EXPECT_EQ(launcherAbilityInfos.size(), LIST_SIZE); + EXPECT_GE(launcherAbilityInfos.size(), 1); EXPECT_EQ(launcherAbilityInfos[0].name, abilityName1); EXPECT_EQ(launcherAbilityInfos[1].name, abilityName2); Uninstall(bundleName, message); @@ -513,9 +527,12 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetAbilityList_0500, Function | Mediu int userId = Constants::DEFAULT_USERID; std::vector launcherAbilityInfos; - LauncherService launcherservice; - - bool result = launcherservice.GetAbilityList(bundleName, userId, launcherAbilityInfos); + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcher service is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->GetAbilityList(bundleName, userId, launcherAbilityInfos); EXPECT_FALSE(result); GTEST_LOG_(INFO) << "END BMS_GetAbilityList_0500"; } @@ -537,10 +554,13 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetAbilityList_0600, Function | Mediu Install(bundleFilePath, InstallFlag::NORMAL, message); EXPECT_EQ(message, "Success") << "install fail!"; - LauncherService launcherservice; + std::shared_ptr launcherservice = std::make_shared(); std::vector launcherAbilityInfos; - - bool result1 = launcherservice.GetAbilityList(bundleName, userId, launcherAbilityInfos); + if (!launcherservice) { + APP_LOGE("launcher service is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result1 = launcherservice->GetAbilityList(bundleName, userId, launcherAbilityInfos); EXPECT_TRUE(result1) << "Get ability list failed"; EXPECT_FALSE(launcherAbilityInfos.empty()) << "Launcher ability infos is empty"; EXPECT_EQ(launcherAbilityInfos[0].name, abilityName); @@ -548,7 +568,7 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetAbilityList_0600, Function | Mediu Uninstall(bundleName, message); EXPECT_EQ(message, "Success") << "uninstall fail!"; - bool result2 = launcherservice.GetAbilityList(bundleName, userId, launcherAbilityInfos); + bool result2 = launcherservice->GetAbilityList(bundleName, userId, launcherAbilityInfos); EXPECT_FALSE(result2); GTEST_LOG_(INFO) << "END BMS_GetAbilityList_0600"; } @@ -565,9 +585,12 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetAbilityList_0700, Function | Mediu int userId = Constants::DEFAULT_USERID; std::vector launcherAbilityInfos; - LauncherService launcherservice; - - bool result = launcherservice.GetAbilityList(bundleName, userId, launcherAbilityInfos); + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcher service is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->GetAbilityList(bundleName, userId, launcherAbilityInfos); EXPECT_TRUE(result); EXPECT_FALSE(launcherAbilityInfos.empty()) << "Launcher ability infos is empty"; EXPECT_EQ(launcherAbilityInfos[0].name, abilityName); @@ -599,9 +622,12 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetAbilityInfo_0100, Function | Mediu want.SetElement(name); LauncherAbilityInfo launcherAbilityInfo; - LauncherService launcherservice; - - bool Result = launcherservice.GetAbilityInfo(want, userId, launcherAbilityInfo); + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcherservice is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool Result = launcherservice->GetAbilityInfo(want, userId, launcherAbilityInfo); EXPECT_TRUE(Result); EXPECT_EQ(launcherAbilityInfo.name, abilityName); @@ -632,9 +658,12 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetAbilityInfo_0200, Function | Mediu want.SetElement(name); LauncherAbilityInfo launcherAbilityInfos; - LauncherService launcherservice; - - bool result = launcherservice.GetAbilityInfo(want, userId, launcherAbilityInfos); + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcher service is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->GetAbilityInfo(want, userId, launcherAbilityInfos); EXPECT_TRUE(result) << "Get ability list failed"; EXPECT_EQ(launcherAbilityInfos.name, abilityName); Uninstall(bundleName, message); @@ -668,9 +697,12 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetAbilityInfo_0300, Function | Mediu name.SetBundleName(bundleName); want.SetElement(name); LauncherAbilityInfo launcherAbilityInfo; - LauncherService launcherservice; - - bool result = launcherservice.GetAbilityInfo(want, userId, launcherAbilityInfo); + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcherservice is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->GetAbilityInfo(want, userId, launcherAbilityInfo); EXPECT_FALSE(result); GTEST_LOG_(INFO) << "END GetAbilityInfo_0300"; } @@ -692,9 +724,12 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetAbilityInfo_0400, Function | Mediu want.SetElement(name); LauncherAbilityInfo launcherAbilityInfo; - LauncherService launcherservice; - - bool Result = launcherservice.GetAbilityInfo(want, userId, launcherAbilityInfo); + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcherservice is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool Result = launcherservice->GetAbilityInfo(want, userId, launcherAbilityInfo); EXPECT_TRUE(Result); EXPECT_EQ(launcherAbilityInfo.name, abilityName); @@ -729,9 +764,12 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetAbilityInfo_0500, Function | Mediu want.SetElement(name); LauncherAbilityInfo launcherAbilityInfos; - LauncherService launcherservice; - - bool result = launcherservice.GetAbilityInfo(want, userId, launcherAbilityInfos); + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcher service is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->GetAbilityInfo(want, userId, launcherAbilityInfos); EXPECT_TRUE(result); EXPECT_EQ(launcherAbilityInfos.name, abilityName); Uninstall(bundleName, message); @@ -752,11 +790,14 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetApplicationInfo_0100, Function | M int userId = Constants::DEFAULT_USERID; Install(bundleFilePath, InstallFlag::NORMAL, message); EXPECT_EQ(message, "Success") << "install fail!"; - LauncherService launcherservice; - + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcher service is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } ApplicationInfo appInfo; ApplicationFlag flag = ApplicationFlag::GET_BASIC_APPLICATION_INFO; - bool result = launcherservice.GetApplicationInfo(bundleName, flag, userId, appInfo); + bool result = launcherservice->GetApplicationInfo(bundleName, flag, userId, appInfo); EXPECT_TRUE(result); EXPECT_EQ(appInfo.name, bundleName); Uninstall(bundleName, message); @@ -779,10 +820,13 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetApplicationInfo_0200, Function | M Install(bundleFilePath, InstallFlag::NORMAL, message); EXPECT_EQ(message, "Success") << "install fail!"; - LauncherService launcherservice; - + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcherservice is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } ApplicationInfo applicationInfo; - bool Result = launcherservice.GetApplicationInfo( + bool Result = launcherservice->GetApplicationInfo( bundleName, ApplicationFlag::GET_APPLICATION_INFO_WITH_PERMS, userId, applicationInfo); EXPECT_TRUE(Result); @@ -805,10 +849,13 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetApplicationInfo_0300, Function | M std::string bundleName = SYSTEM_BASE_BUNDLE_NAME + "1"; int userId = Constants::DEFAULT_USERID; - LauncherService launcherservice; - + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcherservice is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } ApplicationInfo applicationInfo; - bool Result = launcherservice.GetApplicationInfo( + bool Result = launcherservice->GetApplicationInfo( bundleName, ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, applicationInfo); EXPECT_TRUE(Result); EXPECT_EQ(applicationInfo.name, bundleName); @@ -835,10 +882,13 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetApplicationInfo_0400, Function | M Install(bundleFilePath2, InstallFlag::REPLACE_EXISTING, message); EXPECT_EQ(message, "Success") << "install fail!"; - LauncherService launcherservice; - + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcher service is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } ApplicationInfo applicationInfo; - bool Result = launcherservice.GetApplicationInfo( + bool Result = launcherservice->GetApplicationInfo( bundleName, ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, applicationInfo); EXPECT_TRUE(Result); EXPECT_EQ(applicationInfo.name, bundleName); @@ -863,11 +913,14 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetApplicationInfo_0500, Function | M Uninstall(bundleName, message); EXPECT_EQ(message, "Success") << "uninstall fail!"; - LauncherService launcherservice; - + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcher service is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } ApplicationInfo appInfo; bool result = - launcherservice.GetApplicationInfo(bundleName, ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, appInfo); + launcherservice->GetApplicationInfo(bundleName, ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, appInfo); EXPECT_FALSE(result); GTEST_LOG_(INFO) << "END BMS_GetApplicationInfo_0500"; } @@ -883,11 +936,14 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetApplicationInfo_0600, Function | M std::string bundleName = ""; int userId = Constants::DEFAULT_USERID; - LauncherService launcherservice; - + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcher service is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } ApplicationInfo appInfo; bool result = - launcherservice.GetApplicationInfo(bundleName, ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, appInfo); + launcherservice->GetApplicationInfo(bundleName, ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, appInfo); EXPECT_FALSE(result); GTEST_LOG_(INFO) << "END BMS_GetApplicationInfo_0600"; } @@ -908,9 +964,12 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_IsAbilityEnabled_0100, Function | Med AbilityInfo abilityInfo; abilityInfo.bundleName = bundleName; abilityInfo.name = abilityName; - LauncherService launcherservice; - - bool result = launcherservice.IsAbilityEnabled(abilityInfo); + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcherservice is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->IsAbilityEnabled(abilityInfo); EXPECT_TRUE(result); Uninstall(bundleName, message); EXPECT_EQ(message, "Success") << "uninstall fail!"; @@ -934,9 +993,12 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_IsAbilityEnabled_0200, Function | Med APP_LOGE("bundle mgr proxy is nullptr."); EXPECT_EQ(bundleMgrProxy, nullptr); } - LauncherService launcherservice; - - bool result = launcherservice.IsAbilityEnabled(abilityInfo); + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcherservice is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->IsAbilityEnabled(abilityInfo); EXPECT_TRUE(result); GTEST_LOG_(INFO) << "END BMS_IsAbilityEnabled_0200"; } @@ -953,9 +1015,12 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_IsAbilityEnabled_0300, Function | Med AbilityInfo abilityInfo; abilityInfo.bundleName = bundleName; abilityInfo.name = abilityName; - LauncherService launcherservice; - - bool result = launcherservice.IsAbilityEnabled(abilityInfo); + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcherservice is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->IsAbilityEnabled(abilityInfo); EXPECT_FALSE(result); GTEST_LOG_(INFO) << "END BMS_IsAbilityEnabled_0300"; } @@ -984,9 +1049,12 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_IsAbilityEnabled_0400, Function | Med } bool ret = bundleMgrProxy->SetAbilityEnabled(abilityInfo, true); EXPECT_TRUE(ret); - LauncherService launcherservice; - - bool result = launcherservice.IsAbilityEnabled(abilityInfo); + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcherservice is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->IsAbilityEnabled(abilityInfo); EXPECT_TRUE(result); Uninstall(bundleName, message); EXPECT_EQ(message, "Success") << "uninstall fail!"; @@ -1005,9 +1073,12 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_IsBundleEnabled_0100, Function | Medi std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; Install(bundleFilePath, InstallFlag::NORMAL, message); EXPECT_EQ(message, "Success") << "install fail!"; - LauncherService launcherservice; - - bool result = launcherservice.IsBundleEnabled(bundleName); + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcherservice is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->IsBundleEnabled(bundleName); EXPECT_TRUE(result); Uninstall(bundleName, message); EXPECT_EQ(message, "Success") << "uninstall fail!"; @@ -1027,12 +1098,15 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_IsBundleEnabled_0200, Function | Medi std::string bundleName = THIRD_BASE_BUNDLE_NAME + "1"; Install(bundleFilePath, InstallFlag::NORMAL, message); EXPECT_EQ(message, "Success") << "install fail!"; - LauncherService launcherservice; + std::shared_ptr launcherservice = std::make_shared(); sptr bundleMgrProxy = GetBundleMgrProxy(); - + if (!launcherservice) { + APP_LOGE("launcherservice is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } bool ret = bundleMgrProxy->SetApplicationEnabled(bundleName, false); EXPECT_TRUE(ret); - bool result = launcherservice.IsBundleEnabled(bundleName); + bool result = launcherservice->IsBundleEnabled(bundleName); EXPECT_FALSE(result); Uninstall(bundleName, message); EXPECT_EQ(message, "Success") << "uninstall fail!"; @@ -1047,9 +1121,12 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_IsBundleEnabled_0300, Function | Medi { GTEST_LOG_(INFO) << "START BMS_IsBundleEnabled_0300"; std::string bundleName = SYSTEM_BASE_BUNDLE_NAME + "1"; - LauncherService launcherservice; - - bool result = launcherservice.IsBundleEnabled(bundleName); + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcherservice is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->IsBundleEnabled(bundleName); EXPECT_TRUE(result); GTEST_LOG_(INFO) << "END BMS_IsBundleEnabled_0300"; } @@ -1062,9 +1139,12 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_IsBundleEnabled_0400, Function | Medi { GTEST_LOG_(INFO) << "START BMS_IsBundleEnabled_0400"; std::string bundleName = ""; - LauncherService launcherservice; - - bool result = launcherservice.IsBundleEnabled(bundleName); + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcherservice is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->IsBundleEnabled(bundleName); EXPECT_FALSE(result); GTEST_LOG_(INFO) << "END BMS_IsBundleEnabled_0400"; } @@ -1084,9 +1164,12 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetShortcutInfos_0100, Function | Med Install(bundleFilePath, InstallFlag::NORMAL, message); EXPECT_EQ(message, "Success") << "install fail!"; std::vector launcherShortcutInfo; - LauncherService launcherservice; - - bool result = launcherservice.GetShortcutInfos(bundleName, launcherShortcutInfo); + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcher service is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->GetShortcutInfos(bundleName, launcherShortcutInfo); EXPECT_TRUE(result) << "Get shortcut info failed"; EXPECT_FALSE(launcherShortcutInfo.empty()) << "Launcher shortcut infos is empty"; EXPECT_EQ(launcherShortcutInfo[0].bundleName, bundleName); @@ -1117,12 +1200,15 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetShortcutInfos_0200, Function | Med Install(bundleFilePath2, InstallFlag::NORMAL, message); EXPECT_EQ(message, "Success") << "install fail!"; std::vector launcherShortcutInfo; - LauncherService launcherservice; - - bool result = launcherservice.GetShortcutInfos(bundleName, launcherShortcutInfo); + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcher service is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->GetShortcutInfos(bundleName, launcherShortcutInfo); EXPECT_TRUE(result) << "Get shortcut info failed"; EXPECT_FALSE(launcherShortcutInfo.empty()) << "Launcher shortcut infos is empty"; - EXPECT_EQ(launcherShortcutInfo.size(), LIST_SIZE); + EXPECT_GE(launcherShortcutInfo.size(), 1); EXPECT_EQ(launcherShortcutInfo[0].shortcutid, shortcutId1); EXPECT_EQ(launcherShortcutInfo[1].shortcutid, shortcutId2); Uninstall(bundleName, message); @@ -1144,9 +1230,12 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetShortcutInfos_0300, Function | Med Install(bundleFilePath, InstallFlag::NORMAL, message); EXPECT_EQ(message, "Success") << "install fail!"; std::vector launcherShortcutInfo; - LauncherService launcherservice; - - bool result = launcherservice.GetShortcutInfos(bundleName, launcherShortcutInfo); + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcher service is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->GetShortcutInfos(bundleName, launcherShortcutInfo); EXPECT_FALSE(result); EXPECT_TRUE(launcherShortcutInfo.empty()); Uninstall(bundleName, message); @@ -1163,9 +1252,12 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetShortcutInfos_0400, Function | Med GTEST_LOG_(INFO) << "START BMS_GetShortcutInfos_0400"; std::string bundleName = ""; std::vector launcherShortcutInfo; - LauncherService launcherservice; - - bool result = launcherservice.GetShortcutInfos(bundleName, launcherShortcutInfo); + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcher service is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->GetShortcutInfos(bundleName, launcherShortcutInfo); EXPECT_FALSE(result); GTEST_LOG_(INFO) << "END BMS_GetShortcutInfos_0400"; } @@ -1191,9 +1283,12 @@ HWTEST_F(BmsLauncherServiceSystemTest, BMS_GetShortcutInfos_0500, Function | Med EXPECT_EQ(message, "Success") << "install fail!"; std::vector launcherShortcutInfo; - LauncherService launcherservice; - - bool result = launcherservice.GetShortcutInfos(bundleName, launcherShortcutInfo); + std::shared_ptr launcherservice = std::make_shared(); + if (!launcherservice) { + APP_LOGE("launcher service is nullptr."); + EXPECT_EQ(launcherservice, nullptr); + } + bool result = launcherservice->GetShortcutInfos(bundleName, launcherShortcutInfo); EXPECT_TRUE(result); EXPECT_FALSE(launcherShortcutInfo.empty()) << "Launcher shortcut info is empty"; EXPECT_EQ(launcherShortcutInfo[0].bundleName, bundleName); diff --git a/test/systemtest/common/bms/bms_search_system_test/bms_search_system_test.cpp b/test/systemtest/common/bms/bms_search_system_test/bms_search_system_test.cpp index 27164f0e94280cb8c43eeed9844fe804b8c508a9..3ed774b21716b8412dfd1f73cf86bcd2ccd00fc9 100644 --- a/test/systemtest/common/bms/bms_search_system_test/bms_search_system_test.cpp +++ b/test/systemtest/common/bms/bms_search_system_test/bms_search_system_test.cpp @@ -45,6 +45,7 @@ const std::string OPERATION_SUCCESS = "Success"; namespace OHOS { namespace AppExecFwk { + class BundleStatusCallbackImpl : public BundleStatusCallbackHost { public: BundleStatusCallbackImpl(); @@ -1426,5 +1427,6 @@ HWTEST_F(BmsSearchSystemTest, BMS_Search_3900, Function | MediumTest | Level1) EXPECT_NE(name2Exist, 0) << "the test file2 exists."; std::cout << "END BMS_SEARCH_3900" << std::endl; } + } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/test/systemtest/common/bms/bms_uninstall_system_test/bms_uninstall_system_test.cpp b/test/systemtest/common/bms/bms_uninstall_system_test/bms_uninstall_system_test.cpp index e74303550a0acab6a4e9293422f92ed4f4d2bdca..aff2267f599c8beb95e1dfe7c1939405a717bbc3 100755 --- a/test/systemtest/common/bms/bms_uninstall_system_test/bms_uninstall_system_test.cpp +++ b/test/systemtest/common/bms/bms_uninstall_system_test/bms_uninstall_system_test.cpp @@ -47,6 +47,7 @@ const int32_t MAX_BUNDLE_NAME = 6; namespace OHOS { namespace AppExecFwk { + class StatusReceiverImpl : public StatusReceiverHost { public: StatusReceiverImpl(); @@ -1368,5 +1369,6 @@ HWTEST_F(BmsUninstallSystemTest, BMS_DFX_0500, Function | MediumTest | Level2) EXPECT_EQ(uninstallMsg, "Success") << "uninstall fail!"; std::cout << "END BMS_DFX_0500" << std::endl; } + } // namespace AppExecFwk } // namespace OHOS \ No newline at end of file diff --git a/tools/BUILD.gn b/tools/BUILD.gn index b47fd7e86ec0bc3b9df3db730f710bf587879347..399d30752ca3db683bc2aa6bd62cadf946c4cf5e 100644 --- a/tools/BUILD.gn +++ b/tools/BUILD.gn @@ -12,8 +12,5 @@ # limitations under the License. group("tools_target") { - deps = [ - "bm:tools_bm", - "fm:tools_fm", - ] + deps = [ "bm:tools_bm" ] } diff --git a/tools/fm/BUILD.gn b/tools/fm/BUILD.gn deleted file mode 100755 index 088c82dd6bcf7707064b929f90cf4ec75bb49d55..0000000000000000000000000000000000000000 --- a/tools/fm/BUILD.gn +++ /dev/null @@ -1,77 +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") -import("//foundation/appexecfwk/standard/appexecfwk.gni") - -config("tools_fm_config") { - include_dirs = [ - "${aafwk_path}/interfaces/innerkits/want/include", - "${aafwk_path}/interfaces/innerkits/base/include", - "${aafwk_path}/services/common/include", - "${aafwk_path}/tools/aa/include", - "${appexecfwk_path}/common/log/include", - "${appexecfwk_path}/interfaces/innerkits/libeventhandler/include", - "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", - "//utils/native/base/include", - "//utils/system/safwk/native/include", - "include", - ] -} - -ohos_source_set("tools_fm_source_set") { - sources = [ - "${aafwk_path}/tools/aa/src/shell_command.cpp", - "src/fms_command.cpp", - "src/main.cpp", - ] - - defines = [ - "APP_LOG_TAG = \"FmsTool\"", - "LOG_DOMAIN = 0xD001152", - ] - - public_configs = [ ":tools_fm_config" ] - - cflags = [] - if (target_cpu == "arm") { - cflags += [ "-DBINDER_IPC_32BIT" ] - } - - deps = [ - "${aafwk_path}/interfaces/innerkits/want:want", - "${appexecfwk_path}/common:libappexecfwk_common", - "${appexecfwk_path}/interfaces/innerkits/appexecfwk_base:appexecfwk_base", - "${appexecfwk_path}/interfaces/innerkits/appexecfwk_core:appexecfwk_core", - "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", - "//utils/native/base:utils", - ] - - external_deps = [ - "hiviewdfx_hilog_native:libhilog", - "ipc:ipc_core", - ] -} - -ohos_executable("fm") { - deps = [ ":tools_fm_source_set" ] - - install_enable = true - - subsystem_name = "appexecfwk" - part_name = "appexecfwk_standard" -} - -group("tools_fm") { - deps = [ ":fm" ] -} diff --git a/tools/fm/include/fms_command.h b/tools/fm/include/fms_command.h deleted file mode 100755 index 86414c03d098a98779ab30517ea1dd070071caff..0000000000000000000000000000000000000000 --- a/tools/fm/include/fms_command.h +++ /dev/null @@ -1,139 +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 FOUNDATION_APPEXECFWK_STANDARD_TOOLS_FM_INCLUDE_FMS_COMMAND_H -#define FOUNDATION_APPEXECFWK_STANDARD_TOOLS_FM_INCLUDE_FMS_COMMAND_H - -#include "shell_command.h" -#include "form_mgr_interface.h" -#include "iremote_proxy.h" - -namespace OHOS { -namespace AppExecFwk { -namespace { -const std::string FM_TOOL_NAME = "fm"; - -const std::string FM_HELP_MSG = "usage: fm \n" - "These are common fm commands list:\n" - " help list available commands\n" - " query query form info with options\n"; - -const std::string HELP_MSG_QUERY = - "usage: fm query \n" - "options list:\n" - " -h, --help list available commands\n" - " -s, --storage query form storage info\n" - " -n query form info by a bundle name\n" - " -i query form info by a form id\n"; - - -const std::string HELP_MSG_NO_BUNDLE_PATH_OPTION = - "error: you must specify a form id with '-1' or '--formid'."; - -const std::string HELP_MSG_NO_BUNDLE_NAME_OPTION = - "error: you must specify a bundle name with '-n' or '--name'."; - -const std::string STRING_QUERY_FORM_INFO_OK = "query form info successfully."; -const std::string STRING_QUERY_FORM_INFO_NG = "error: failed to query form info."; -} // namespace - -class FormMgrShellCommand : public OHOS::AAFwk::ShellCommand { -public: - FormMgrShellCommand(int argc, char *argv[]); - ~FormMgrShellCommand() override - {} - -private: - /** - * @brief Create command map. - */ - ErrCode CreateCommandMap() override; - /** - * @brief Create message map. - */ - ErrCode CreateMessageMap() override; - /** - * @brief init. - */ - ErrCode init() override; - /** - * @brief Run help command. - */ - ErrCode RunAsHelpCommand(); - /** - * @brief Run query form info command. - */ - ErrCode RunAsQueryCommand(); - // ErrCode RunAsDumpCommand(); - - /** - * @brief Query all of form storage infos. - * @return Returns ERR_OK on success, others on failure. - */ - int32_t QueryStorageFormInfos(); - /** - * @brief Query form infos by bundleName. - * @param bundleName BundleName. - * @return Returns ERR_OK on success, others on failure. - */ - int32_t QueryFormInfoByBundleName(const std::string& bundleName); - /** - * @brief Query form infos by form id. - * @param formId The id of the form. - * @return Returns ERR_OK on success, others on failure. - */ - int32_t QueryFormInfoByFormId(const std::int64_t formId); - /** - * @brief Handle command args. - * @param optopt Command optopt. - * @return Returns ERR_OK on success, others on failure. - */ - int32_t HandleUnknownOption(const char optopt); - /** - * @brief Handle command args. - * @param option Command option. - * @param bundleName BundleName. - * @param formId The id of the form. - * @param cmdFlag Command Flag. - * @return Returns ERR_OK on success, others on failure. - */ - int32_t HandleNormalOption(const int option, std::string &bundleName, int64_t &formId, int32_t &cmdFlag); - - /** - * @brief Execute query form info command. - * @param bundleName BundleName. - * @param formId The id of the form. - * @param cmdFlag Command Flag. - * @return Returns ERR_OK on success, others on failure. - */ - int32_t ExecuteQuery(const std::string &bundleName, const int64_t formId, const int32_t cmdFlag); - - /** - * @brief Connect form manager service. - * @return Returns ERR_OK on success, others on failure. - */ - int32_t ConnectFms(); - - bool WriteInterfaceToken(MessageParcel &data); - int GetStringInfo(IFormMgr::Message code, MessageParcel &data, std::string &stringInfo); - int SendTransactCmd(IFormMgr::Message code, MessageParcel &data, MessageParcel &reply); -private: - sptr remoteObject_; -}; - -} // namespace AppExecFwk -} // namespace OHOS - -#endif // FOUNDATION_APPEXECFWK_STANDARD_TOOLS_FM_INCLUDE_FMS_COMMAND_H \ No newline at end of file diff --git a/tools/fm/src/fms_command.cpp b/tools/fm/src/fms_command.cpp deleted file mode 100755 index 462165df9a8f3367e9b8f15e57fb03010cec9ca0..0000000000000000000000000000000000000000 --- a/tools/fm/src/fms_command.cpp +++ /dev/null @@ -1,499 +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 - -#include "appexecfwk_errors.h" -#include "app_log_wrapper.h" -#include "fms_command.h" -#include "if_system_ability_manager.h" -#include "ipc_skeleton.h" -#include "iservice_registry.h" -#include "string_ex.h" -#include "system_ability_definition.h" - -using namespace OHOS::AAFwk; - -namespace OHOS { -namespace AppExecFwk { -namespace { -const int COMMAND_QUERY_INVALID = -1; -const int COMMAND_QUERY_STORAGE = 0; -const int COMMAND_QUERY_NAME = 1; -const int COMMAND_QUERY_ID = 2; - -// const std::string BUNDLE_NAME_EMPTY = ""; - -const std::string SHORT_OPTIONS = "hsn:i:"; -const struct option LONG_OPTIONS[] = { - {"help", no_argument, nullptr, 'h'}, - {"storage", no_argument, nullptr, 's'}, - {"bundle-name", required_argument, nullptr, 'n'}, - {"form-id", required_argument, nullptr, 'i'}, - {0, 0, 0, 0}, -}; -} // namespace - -FormMgrShellCommand::FormMgrShellCommand(int argc, char *argv[]) : ShellCommand(argc, argv, FM_TOOL_NAME) -{ -} -ErrCode FormMgrShellCommand::init() -{ - return ERR_OK; -} -/** - * @brief Create command map. - */ -ErrCode FormMgrShellCommand::CreateCommandMap() -{ - commandMap_ = { - {"help", std::bind(&FormMgrShellCommand::RunAsHelpCommand, this)}, - {"query", std::bind(&FormMgrShellCommand::RunAsQueryCommand, this)}, - // {"dump", std::bind(&FormMgrShellCommand::RunAsDumpCommand, this)}, - }; - - return OHOS::ERR_OK; -} -/** - * @brief Create message map. - */ -ErrCode FormMgrShellCommand::CreateMessageMap() -{ - messageMap_ = { - // error + message - { - ERR_APPEXECFWK_INSTALL_INTERNAL_ERROR, - "error: fm query internal error.", - }, - { - ERR_APPEXECFWK_FORM_INVALID_PARAM, - "error: fm query param error.", - }, - { - ERR_APPEXECFWK_FORM_PERMISSION_DENY, - "error: fm query permission denied.", - }, - { - ERR_APPEXECFWK_FORM_NOT_EXIST_ID, - "warning: fm query no form info.", - }, - { - ERR_APPEXECFWK_FORM_COMMON_CODE, - "error: unknown.", - }, - }; - - return OHOS::ERR_OK; -} -/** - * @brief Run help command. - */ -ErrCode FormMgrShellCommand::RunAsHelpCommand() -{ - resultReceiver_.append(FM_HELP_MSG); - - return OHOS::ERR_OK; -} -/** - * @brief Run query form info command. - */ -ErrCode FormMgrShellCommand::RunAsQueryCommand() -{ - int32_t result = OHOS::ERR_OK; - int32_t cmdFlag = COMMAND_QUERY_INVALID; - int option = -1; - int counter = 0; - std::string bundleName = ""; - int64_t formId = 0; - - while (true) { - counter++; - option = getopt_long(argc_, argv_, SHORT_OPTIONS.c_str(), LONG_OPTIONS, nullptr); - APP_LOGI("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind); - if (optind < 0 || optind > argc_) { - return OHOS::ERR_INVALID_VALUE; - } - - for (int i = 0; i < argc_; i++) { - APP_LOGI("argv_[%{public}d]: %{public}s", i, argv_[i]); - } - - if (option == -1) { - if (counter == 1) { - // When scanning the first argument - if (strcmp(argv_[optind], cmd_.c_str()) == 0) { - // 'fm query' with no option: fm query - // 'fm query' with a wrong argument: fm query xxx - APP_LOGE("'fm query' with no option."); - resultReceiver_.append(HELP_MSG_NO_OPTION + "\n"); - result = OHOS::ERR_INVALID_VALUE; - } - } - break; - } - - if (option == '?') { - result = HandleUnknownOption(optopt); - break; - } - - result = HandleNormalOption(option, bundleName, formId, cmdFlag); - // if(result == OHOS::ERR_OK) { - // break; - // } - } - - if (result == OHOS::ERR_OK) { - result = ExecuteQuery(bundleName, formId, cmdFlag); - } else { - resultReceiver_.append(HELP_MSG_QUERY); - } - - return result; -} -/** - * @brief Handle command args. - * @param optopt Command optopt. - * @return Returns ERR_OK on success, others on failure. - */ -int32_t FormMgrShellCommand::HandleUnknownOption(const char optopt) -{ - int32_t result = OHOS::ERR_OK; - switch (optopt) { - case 'n': - case 'i': { - // 'fm query -n' with no argument: fm query -n - // 'fm query --bundle-name' with no argument: fm query --bundle-name - // 'fm query -i' with no argument: fm query -i - // 'fm query --form-id' with no argument: fm query --form-id - APP_LOGE("'fm query' %{public}s with no argument.", argv_[optind - 1]); - resultReceiver_.append("error: option '"); - resultReceiver_.append(argv_[optind - 1]); - resultReceiver_.append("' requires a value.\n"); - result = OHOS::ERR_INVALID_VALUE; - break; - } - case 0: { - // 'fm query' with a unknown option: fm query --x - // 'fm query' with a unknown option: fm query --xxx - std::string unknownOption = ""; - std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption); - APP_LOGE("'fm query' with a unknown option: %{public}s", unknownOption.c_str()); - resultReceiver_.append(unknownOptionMsg); - result = OHOS::ERR_INVALID_VALUE; - break; - } - default: { - // 'fm query' with a unknown option: fm query -x - // 'fm query' with a unknown option: fm query -xxx - std::string unknownOption = ""; - std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption); - APP_LOGE("'fm query' with a unknown option: %{public}s", unknownOption.c_str()); - resultReceiver_.append(unknownOptionMsg); - result = OHOS::ERR_INVALID_VALUE; - break; - } - } - - return result; -} -/** - * @brief Handle command args. - * @param option Command option. - * @param bundleName BundleName. - * @param formId The id of the form. - * @param cmdFlag Command Flag. - * @return Returns ERR_OK on success, others on failure. - */ -int32_t FormMgrShellCommand::HandleNormalOption(const int option, std::string &bundleName, int64_t &formId, int32_t &cmdFlag) -{ - APP_LOGI("%{public}s start, option: %{public}d", __func__, option); - int32_t result = OHOS::ERR_OK; - switch (option) { - case 'h': { - // 'fm query -h' - // 'fm query --help' - APP_LOGI("'fm query' %{public}s", argv_[optind - 1]); - result = OHOS::ERR_INVALID_VALUE; - break; - } - case 's': { - // 'fm query -s' - // 'fm query --storage' - cmdFlag = COMMAND_QUERY_STORAGE; - break; - } - case 'n': { - // 'fm query -n ' - // 'fm query --bundle-name ' - if(optarg == nullptr) { - resultReceiver_.append("error: option "); - resultReceiver_.append("'-n'"); - resultReceiver_.append(" requires a value.\n"); - result = OHOS::ERR_INVALID_VALUE; - break; - } - cmdFlag = COMMAND_QUERY_NAME; - bundleName = optarg; - break; - } - case 'i': { - // 'fm query -i ' - // 'fm query --form-id ' - if(optarg == nullptr) { - resultReceiver_.append("error: option "); - resultReceiver_.append("'-i'"); - resultReceiver_.append(" requires a value.\n"); - result = OHOS::ERR_INVALID_VALUE; - break; - } - cmdFlag = COMMAND_QUERY_ID; - formId = std::stoll(optarg); - break; - } - default: { - result = OHOS::ERR_INVALID_VALUE; - APP_LOGI("'fm query' invalid option."); - break; - } - } - APP_LOGI("%{public}s end, result: %{public}d", __func__, result); - return result; -} -/** - * @brief Execute query form info command. - * @param bundleName BundleName. - * @param formId The id of the form. - * @param cmdFlag Command Flag. - * @return Returns ERR_OK on success, others on failure. - */ -int32_t FormMgrShellCommand::ExecuteQuery(const std::string &bundleName, const int64_t formId, const int32_t cmdFlag) -{ - APP_LOGI("%{public}s start, bundleName: %{public}s, formId:%{public}" PRId64 "", __func__, bundleName.c_str(), formId); - int32_t result = OHOS::ERR_OK; - switch (cmdFlag) { - case COMMAND_QUERY_STORAGE: { - result = QueryStorageFormInfos(); - break; - } - case COMMAND_QUERY_NAME: { - result = QueryFormInfoByBundleName(bundleName); - break; - } - case COMMAND_QUERY_ID: { - result = QueryFormInfoByFormId(formId); - break; - } - default: { - APP_LOGI("'fm query' invalid command."); - break; - } - APP_LOGI("%{public}s end, cmdFlag: %{public}d", __func__, cmdFlag); - } - - if (result == OHOS::ERR_OK) { - resultReceiver_ = STRING_QUERY_FORM_INFO_OK + "\n" + resultReceiver_; - } else if(result == OHOS::ERR_APPEXECFWK_FORM_NOT_EXIST_ID){ - resultReceiver_ = STRING_QUERY_FORM_INFO_OK + "\n"; - resultReceiver_.append(GetMessageFromCode(result)); - } else { - resultReceiver_ = STRING_QUERY_FORM_INFO_NG + "\n"; - resultReceiver_.append(GetMessageFromCode(result)); - } - - return result; -} -/** - * @brief Query all of form storage infos. - * @return Returns ERR_OK on success, others on failure. - */ -int32_t FormMgrShellCommand::QueryStorageFormInfos() -{ - APP_LOGI("%{public}s start", __func__); - - int errCode = ConnectFms(); - if(errCode != OHOS::ERR_OK) { - return errCode; - } - - std::string formInfos; - MessageParcel data; - if (!WriteInterfaceToken(data)) { - APP_LOGE("%{public}s, failed to write interface token", __func__); - return ERR_APPEXECFWK_PARCEL_ERROR; - } - - int result = GetStringInfo(IFormMgr::Message::FORM_MGR_STORAGE_FORM_INFOS, data, formInfos); - if (result == ERR_OK) { - resultReceiver_= formInfos; - } else { - APP_LOGE("'fm query' failed to query form info."); - } - APP_LOGI("%{public}s end, formInfo: %{public}s", __func__, resultReceiver_.c_str()); - - return result; -} -/** - * @brief Query form infos by bundleName. - * @param bundleName BundleName. - * @return Returns ERR_OK on success, others on failure. - */ -int32_t FormMgrShellCommand::QueryFormInfoByBundleName(const std::string& bundleName) -{ - APP_LOGI("%{public}s start, bundleName: %{public}s", __func__, bundleName.c_str()); - - int errCode = ConnectFms(); - if(errCode != OHOS::ERR_OK) { - return errCode; - } - - std::string formInfos; - MessageParcel data; - if (!WriteInterfaceToken(data)) { - APP_LOGE("%{public}s, failed to write interface token", __func__); - return ERR_APPEXECFWK_PARCEL_ERROR; - } - - if (!data.WriteString(bundleName)) { - APP_LOGE("%{public}s, failed to write bundleName", __func__); - return ERR_APPEXECFWK_PARCEL_ERROR; - } - - int result = GetStringInfo(IFormMgr::Message::FORM_MGR_FORM_INFOS_BY_NAME, data, formInfos); - if (result == ERR_OK) { - APP_LOGI("%{public}s, DumpFormInfoByBundleName success", __func__); - resultReceiver_ = formInfos; - } else { - APP_LOGE("'fm query' failed to query form info."); - } - APP_LOGI("%{public}s end, formInfo: %{public}s", __func__, resultReceiver_.c_str()); - - return result; -} -/** - * @brief Query form infos by form id. - * @param formId The id of the form. - * @return Returns ERR_OK on success, others on failure. - */ -int32_t FormMgrShellCommand::QueryFormInfoByFormId(const std::int64_t formId) -{ - APP_LOGI("%{public}s start, formId: %{public}" PRId64 "", __func__, formId); - - int errCode = ConnectFms(); - if(errCode != OHOS::ERR_OK) { - return errCode; - } - - std::string formInfo; - MessageParcel data; - if (!WriteInterfaceToken(data)) { - APP_LOGE("%{public}s, failed to write interface token", __func__); - return ERR_APPEXECFWK_PARCEL_ERROR; - } - if (!data.WriteInt64(formId)) { - APP_LOGE("%{public}s, failed to write formId", __func__); - return ERR_APPEXECFWK_PARCEL_ERROR; - } - - int result = GetStringInfo(IFormMgr::Message::FORM_MGR_FORM_INFOS_BY_ID, data, formInfo); - if (result == ERR_OK) { - resultReceiver_ = formInfo; - } else if(result == OHOS::ERR_APPEXECFWK_FORM_NOT_EXIST_ID) { - APP_LOGW("'fm query' no form info."); - } else { - APP_LOGE("'fm query' failed to query form info."); - } - APP_LOGI("%{public}s end, formInfo: %{public}s", __func__, resultReceiver_.c_str()); - - return result; -} -bool FormMgrShellCommand::WriteInterfaceToken(MessageParcel &data) -{ - if (!data.WriteInterfaceToken(IFormMgr::GetDescriptor())) { - APP_LOGE("%{public}s, failed to write interface token", __func__); - return false; - } - return true; -} -int FormMgrShellCommand::GetStringInfo(IFormMgr::Message code, MessageParcel &data, std::string &stringInfo) -{ - int error; - MessageParcel reply; - error = SendTransactCmd(code, data, reply); - if (error != ERR_OK) { - return error; - } - - error = reply.ReadInt32(); - if (error != ERR_OK) { - APP_LOGE("%{public}s, failed to read reply result: %{public}d", __func__, error); - return error; - } - std::vector stringInfoList; - if (!reply.ReadStringVector(&stringInfoList)) { - APP_LOGE("%{public}s, failed to read string vector from reply", __func__); - return false; - } - if (stringInfoList.empty()) { - APP_LOGI("%{public}s, No string info", __func__); - return ERR_APPEXECFWK_FORM_NOT_EXIST_ID; - } - for (auto &info : stringInfoList) { - stringInfo += info; - } - APP_LOGD("%{public}s, get string info success", __func__); - return ERR_OK; -} -int FormMgrShellCommand::SendTransactCmd(IFormMgr::Message code, MessageParcel &data, MessageParcel &reply) -{ - MessageOption option(MessageOption::TF_SYNC); - - if (!remoteObject_) { - APP_LOGE("%{public}s, failed to get remote object, cmd: %{public}d", __func__, code); - return ERR_APPEXECFWK_SERVICE_NOT_CONNECTED; - } - int32_t result = remoteObject_->SendRequest(static_cast(code), data, reply, option); - if (result != ERR_OK) { - APP_LOGE("%{public}s, failed to SendRequest: %{public}d, cmd: %{public}d", __func__, result, code); - return result; - } - return ERR_OK; -} -/** - * @brief Connect form manager service. - * @return Returns ERR_OK on success, others on failure. - */ -int32_t FormMgrShellCommand::ConnectFms() -{ - if(remoteObject_ != nullptr) { - return OHOS::ERR_OK; - } - sptr systemManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (systemManager == nullptr) { - APP_LOGE("%{private}s:fail to get system ability manager", __func__); - return ERR_APPEXECFWK_FORM_GET_FMS_FAILED; - } - remoteObject_ = systemManager->GetSystemAbility(FORM_MGR_SERVICE_ID); - if (remoteObject_ == nullptr) { - APP_LOGE("%{private}s:fail to connect FormMgrService", __func__); - return ERR_APPEXECFWK_FORM_GET_FMS_FAILED; - } - - APP_LOGI("%{public}s end, get fms proxy success", __func__); - return OHOS::ERR_OK; -} -} // namespace AppExecFwk -} // namespace OHOS \ No newline at end of file diff --git a/tools/fm/src/main.cpp b/tools/fm/src/main.cpp deleted file mode 100755 index 7b2115dbeb15dcef0e3e4d24350e40a4c1086b44..0000000000000000000000000000000000000000 --- a/tools/fm/src/main.cpp +++ /dev/null @@ -1,23 +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 "fms_command.h" - -int main(int argc, char *argv[]) -{ - OHOS::AppExecFwk::FormMgrShellCommand cmd(argc, argv); - std::cout << cmd.ExecCommand(); - return 0; -}