update OpenHarmony 2.0 Canary

This commit is contained in:
mamingshuai
2021-06-02 00:03:43 +08:00
parent cdc88bdc08
commit 1a2f924c77
154 changed files with 39681 additions and 73 deletions
View File
+14
View File
@@ -0,0 +1,14 @@
# 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")
+177
View File
@@ -0,0 +1,177 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
+70
View File
@@ -0,0 +1,70 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- 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.
Notes:
This is project config file for OpenHarmony OSS Audit Tool, if you have any questions or concerns, please email chenyaxun@huawei.com.
-->
<!-- OAT(OSS Audit Tool) configuration guide:
basedir: Root dir, the basedir + project path is the real source file location.
licensefile:
1.If the project don't have "LICENSE" in root dir, please define all the license files in this project in , OAT will check license files according to this rule.
tasklist(only for batch mode):
1. task: Define oat check thread, each task will start a new thread.
2. task name: Only an name, no practical effect.
3. task policy: Default policy for projects under this task, this field is required and the specified policy must defined in policylist.
4. task filter: Default filefilter for projects under this task, this field is required and the specified filefilter must defined in filefilterlist.
5. task project: Projects to be checked, the path field define the source root dir of the project.
policyList:
1. policy: All policyitems will be merged to default OAT.xml rules, the name of policy doesn't affect OAT check process.
2. policyitem: The fields type, name, path, desc is required, and the fields rule, group, filefilter is optional,the default value is:
<policyitem type="" name="" path="" desc="" rule="may" group="defaultGroup" filefilter="defaultPolicyFilter"/>
3. policyitem type:
"compatibility" is used to check license compatibility in the specified path;
"license" is used to check source license header in the specified path;
"copyright" is used to check source copyright header in the specified path;
"import" is used to check source dependency in the specified path, such as import ... ,include ...
"filetype" is used to check file type in the specified path, supported file types: archive, binary
"filename" is used to check whether the specified file exists in the specified path(support projectroot in default OAT.xml), supported file names: LICENSE, README, README.OpenSource
4. policyitem name: This field is used for define the license, copyright, "*" means match all, the "!" prefix means could not match this value. For example, "!GPL" means can not use GPL license.
5. policyitem path: This field is used for define the source file scope to apply this policyitem, the "!" prefix means exclude the files. For example, "!.*/lib/.*" means files in lib dir will be exclude while process this policyitem.
6. policyitem rule and group: These two fields are used together to merge policy results. "may" policyitems in the same group means any one in this group passed, the result will be passed.
7. policyitem filefilter: Used to bind filefilter which define filter rules.
8. filefilter: Filter rules, the type filename is used to filter file name, the type filepath is used to filter file path.
Note:If the text contains special characters, please escape them according to the following rules:
" == &gt;
& == &gt;
' == &gt;
< == &gt;
> == &gt;
-->
<configuration>
<oatconfig>
<licensefile></licensefile>
<policylist>
<policy name="projectPolicy" desc="">
</policy>
</policylist>
<filefilterlist>
<filefilter name="defaultFilter" desc="Files not to check">
<filteritem type="filename" name="*.hap|*.rpk" desc="valid and invalid bundle files for tests"/>
</filefilter>
</filefilterlist>
</oatconfig>
</configuration>
-36
View File
@@ -1,36 +0,0 @@
# notification_ces_standard
#### Description
Common event and notification management framework | 通知和公共事件管理框架
#### Software Architecture
Software architecture description
#### Installation
1. xxxx
2. xxxx
3. xxxx
#### Instructions
1. xxxx
2. xxxx
3. xxxx
#### Contribution
1. Fork the repository
2. Create Feat_xxx branch
3. Commit your code
4. Create Pull Request
#### Gitee Feature
1. You can use Readme\_XXX.md to support different languages, such as Readme\_en.md, Readme\_zh.md
2. Gitee blog [blog.gitee.com](https://blog.gitee.com)
3. Explore open source project [https://gitee.com/explore](https://gitee.com/explore)
4. The most valuable open source project [GVP](https://gitee.com/gvp)
5. The manual of Gitee [https://gitee.com/help](https://gitee.com/help)
6. The most popular members [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)
-37
View File
@@ -1,37 +0,0 @@
# notification_ces_standard
#### 介绍
Common event and notification management framework | 通知和公共事件管理框架
#### 软件架构
软件架构说明
#### 安装教程
1. xxxx
2. xxxx
3. xxxx
#### 使用说明
1. xxxx
2. xxxx
3. xxxx
#### 参与贡献
1. Fork 本仓库
2. 新建 Feat_xxx 分支
3. 提交代码
4. 新建 Pull Request
#### 特技
1. 使用 Readme\_XXX.md 来支持不同的语言,例如 Readme\_en.md, Readme\_zh.md
2. Gitee 官方博客 [blog.gitee.com](https://blog.gitee.com)
3. 你可以 [https://gitee.com/explore](https://gitee.com/explore) 这个地址来了解 Gitee 上的优秀开源项目
4. [GVP](https://gitee.com/gvp) 全称是 Gitee 最有价值开源项目,是综合评定出的优秀开源项目
5. Gitee 官方提供的使用手册 [https://gitee.com/help](https://gitee.com/help)
6. Gitee 封面人物是一档用来展示 Gitee 会员风采的栏目 [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)
Executable
+56
View File
@@ -0,0 +1,56 @@
# 事件通知子系统
## 简介
OpenHarmony通过CESCommon Event Service,公共事件服务)为应用程序提供订阅、发布、退订公共事件的能力。
公共事件可分为系统公共事件和自定义公共事件。
- 系统公共事件:系统将收集到的事件信息,根据系统策略发送给订阅该事件的用户程序。 例如:系统关键服务发布的系统事件(例如:hap安装,更新,卸载等)。
- 自定义公共事件:应用自定义一些公共事件用来实现跨应用的事件通信能力。
每个应用都可以按需订阅公共事件,订阅成功且公共事件发布,系统会把其发送给应用。这些公共事件可能来自系统、其他应用和应用自身。
### 架构图
![](figures/cesfwk_architecture_diagram.png "公共事件服务架构图")
## 目录
```
/base/notification/ces_standard/
│── cesfwk # 组件目录
│ ├── innerkits # 对内接口目录
│ ├── kits # 对外接口目录
│ ├── sa_profile # 组件服务配置
│ ├── services # 组件服务实现
│ ├── tools # 组件工具实现
|── common
| |──log # 日志组件目录
|── interfaces
| |── kits # typescript描述文件
│── ohos.build # 组件编译脚本
```
## 使用说明
以下模块的JS接口为非正式API,仅供Launcher、Settings、SystemUI等系统应用使用,不排除对这些接口进行变更的可能性,后续版本将提供正式API。
- commoneventdata.d.ts
- commoneventpublishdata.d.ts
- commoneventsubscribeinfo.d.ts
- commoneventsubscriber.d.ts
- @ohos.commonevent.d.ts
## 相关仓
事件通知子系统
**notification_ces_standard**
+91
View File
@@ -0,0 +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.
import("//base/notification/ces_standard/event.gni")
import("//build/ohos.gni")
CESFWK_INNERKITS_DIR = "//base/notification/ces_standard/cesfwk/innerkits"
CESFWK_KITS_DIR = "//base/notification/ces_standard/cesfwk/kits/native"
cflags = []
config("cesfwk_innerkits_config") {
visibility = [ ":*" ]
include_dirs = []
if (target_cpu == "arm") {
cflags += [ "-DBINDER_IPC_32BIT" ]
}
defines = [
"APP_LOG_TAG = \"CesFwk\"",
"LOG_DOMAIN = 0xD002200",
]
}
config("cesfwk_innerkits_public_config") {
visibility = [ ":*" ]
include_dirs = [
"${CESFWK_INNERKITS_DIR}/include",
"${CESFWK_KITS_DIR}/include",
"//foundation/aafwk/standard/interfaces/innerkits/base/include/",
"//foundation/aafwk/standard/interfaces/innerkits/base/include/ohos/aafwk/base/",
"//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content/",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include",
"//foundation/appexecfwk/standard/services/bundlemgr/include/",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include",
"//base/notification/ces_standard/common/log/include",
"//utils/native/base/include",
"//utils/system/safwk/native/include",
]
}
ohos_shared_library("cesfwk_innerkits") {
sources = [
"${CESFWK_INNERKITS_DIR}/src/common_event.cpp",
"${CESFWK_INNERKITS_DIR}/src/common_event_death_recipient.cpp",
"${CESFWK_INNERKITS_DIR}/src/common_event_listener.cpp",
"${CESFWK_INNERKITS_DIR}/src/common_event_proxy.cpp",
"${CESFWK_INNERKITS_DIR}/src/common_event_stub.cpp",
"${CESFWK_INNERKITS_DIR}/src/event_receive_proxy.cpp",
"${CESFWK_INNERKITS_DIR}/src/event_receive_stub.cpp",
"${CESFWK_KITS_DIR}/src/async_common_event_result.cpp",
"${CESFWK_KITS_DIR}/src/common_event_data.cpp",
"${CESFWK_KITS_DIR}/src/common_event_publish_info.cpp",
"${CESFWK_KITS_DIR}/src/common_event_subscribe_info.cpp",
"${CESFWK_KITS_DIR}/src/common_event_subscriber.cpp",
"${CESFWK_KITS_DIR}/src/matching_skills.cpp",
]
configs = [ ":cesfwk_innerkits_config" ]
public_configs = [ ":cesfwk_innerkits_public_config" ]
deps = [
"${event_common_path}:libevent_common",
"//foundation/aafwk/standard/interfaces/innerkits/want:want",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//utils/native/base:utils",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
]
subsystem_name = "notification"
part_name = "ces_standard"
}
+130
View File
@@ -0,0 +1,130 @@
/*
* 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_EVENT_CESFWK_INNERKITS_INCLUDE_COMMON_EVENT_H
#define FOUNDATION_EVENT_CESFWK_INNERKITS_INCLUDE_COMMON_EVENT_H
#include <map>
#include <mutex>
#include "common_event_listener.h"
#include "icommon_event.h"
namespace OHOS {
namespace EventFwk {
class CommonEvent {
public:
enum SubscribeState { ALREADY_SUBSCRIBED = 0, INITIAL_SUBSCRIPTION, SUBSCRIBE_FAILD };
/**
* Publish an ordered, sticky, or standard common event.
*
* @param data the common event data
* @param publishInfo the publish info
* @param subscriber the common event subscriber
*/
bool PublishCommonEvent(const CommonEventData &data, const CommonEventPublishInfo &publishInfo,
const std::shared_ptr<CommonEventSubscriber> &subscriber);
/**
* Subscribe to common events.
*
* @param subscriber the common event subscriber
*/
bool SubscribeCommonEvent(const std::shared_ptr<CommonEventSubscriber> &subscriber);
/**
* Unsubscribe from common events.
*
* @param subscriber the common event subscriber
*/
bool UnSubscribeCommonEvent(const std::shared_ptr<CommonEventSubscriber> &subscriber);
/**
* Gets the current sticky common event
*
* @param event the common event
* @param eventData the common event data
*/
bool GetStickyCommonEvent(const std::string &event, CommonEventData &eventData);
/**
* Finish Receiver.
*
* @param proxy Receiver proxy.
* @param code the code of a common event.
* @param data the data of a common event.
* @param abortEvent Cancel the current common event.
* @return Finish Receiver success or not.
*/
bool FinishReceiver(
const sptr<IRemoteObject> &proxy, const int &code, const std::string &data, const bool &abortEvent);
/**
* Dump state of common event service.
*
* @param event Specifies the information for the common event. Set null string ("") if you want to dump all.
* @param state the state of common event service
*/
bool DumpState(const std::string &event, std::vector<std::string> &state);
/**
* Reset Common Event Proxy.
*/
void ResetCommonEventProxy();
/**
* Freeze application.
*
* @param uid Uid of application.
*/
bool Freeze(const uid_t &uid);
/**
* Unfreeze application.
*
* @param uid Uid of application.
*/
bool Unfreeze(const uid_t &uid);
private:
/**
* Get common evnet proxy.
*
* @return Get common evnet proxy success or not
*/
bool GetCommonEventProxy();
/**
* Get common evenet listener.
*
* @param subscriber the subscriber
* @param commonEventListener the common event listener
* @return Get common evnet listener success or not
*/
int CreateCommonEventListener(
const std::shared_ptr<CommonEventSubscriber> &subscriber, sptr<IRemoteObject> &commonEventListener);
private:
std::mutex mutex_;
std::mutex eventListenersMutex_;
sptr<ICommonEvent> commonEventProxy_;
std::map<std::shared_ptr<CommonEventSubscriber>, sptr<IRemoteObject>> eventListeners_;
sptr<IRemoteObject::DeathRecipient> recipient_;
};
} // namespace EventFwk
} // namespace OHOS
#endif // FOUNDATION_EVENT_CESFWK_INNERKITS_INCLUDE_COMMON_EVENT_H
@@ -0,0 +1,34 @@
/*
* 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_EVENT_CESFWK_INNERKITS_INCLUDE_COMMON_EVENT_DEATH_RECIPIENT_H
#define FOUNDATION_EVENT_CESFWK_INNERKITS_INCLUDE_COMMON_EVENT_DEATH_RECIPIENT_H
#include "iremote_object.h"
namespace OHOS {
namespace EventFwk {
class CommonEventDeathRecipient : public IRemoteObject::DeathRecipient {
public:
CommonEventDeathRecipient() = default;
virtual ~CommonEventDeathRecipient() = default;
virtual void OnRemoteDied(const wptr<IRemoteObject> &remote);
};
} // namespace EventFwk
} // namespace OHOS
#endif // FOUNDATION_EVENT_CESFWK_INNERKITS_INCLUDE_COMMON_EVENT_DEATH_RECIPIENT_H
@@ -0,0 +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_EVENT_CESFWK_INNERKITS_INCLUDE_COMMON_EVENT_LISTENER_H
#define FOUNDATION_EVENT_CESFWK_INNERKITS_INCLUDE_COMMON_EVENT_LISTENER_H
#include "event_handler.h"
#include "common_event_subscriber.h"
#include "event_receive_stub.h"
namespace OHOS {
namespace EventFwk {
class CommonEventListener : public EventReceiveStub {
public:
using EventHandler = OHOS::AppExecFwk::EventHandler;
using EventRunner = OHOS::AppExecFwk::EventRunner;
explicit CommonEventListener(const std::shared_ptr<CommonEventSubscriber> &commonEventSubscriber);
virtual ~CommonEventListener() override;
virtual void NotifyEvent(const CommonEventData &CommonEventData, const bool &ordered, const bool &sticky) override;
private:
ErrCode Init();
bool IsReady();
void OnReceiveEvent(const CommonEventData &commonEventData, const bool &ordered, const bool &sticky);
private:
std::shared_ptr<CommonEventSubscriber> commonEventSubscriber_;
std::shared_ptr<EventRunner> runner_;
std::shared_ptr<EventHandler> handler_;
};
} // namespace EventFwk
} // namespace OHOS
#endif // FOUNDATION_EVENT_CESFWK_INNERKITS_INCLUDE_COMMON_EVENT_LISTENER_H
@@ -0,0 +1,35 @@
/*
* 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_EVENT_CESFWK_INNERKITS_INCLUDE_COMMON_EVENT_LISTENER_HANDLER_H
#define FOUNDATION_EVENT_CESFWK_INNERKITS_INCLUDE_COMMON_EVENT_LISTENER_HANDLER_H
#include "event_handler.h"
namespace OHOS {
namespace EventFwk {
using EventHandler = OHOS::AppExecFwk::EventHandler;
using EventRunner = OHOS::AppExecFwk::EventRunner;
class CommonEventListenerHandler : public EventHandler {
public:
explicit CommonEventListenerHandler(const std::shared_ptr<EventRunner> &runner);
virtual ~CommonEventListenerHandler() override;
};
} // namespace EventFwk
} // namespace OHOS
#endif // FOUNDATION_EVENT_CESFWK_INNERKITS_INCLUDE_COMMON_EVENT_LISTENER_HANDLER_H
@@ -0,0 +1,50 @@
/*
* 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_EVENT_CESFWK_INNERKITS_INCLUDE_COMMON_EVENT_PROXY_H
#define FOUNDATION_EVENT_CESFWK_INNERKITS_INCLUDE_COMMON_EVENT_PROXY_H
#include "icommon_event.h"
#include "iremote_proxy.h"
namespace OHOS {
namespace EventFwk {
class CommonEventProxy : public IRemoteProxy<ICommonEvent> {
public:
explicit CommonEventProxy(const sptr<IRemoteObject> &object);
virtual ~CommonEventProxy() override;
virtual bool PublishCommonEvent(const CommonEventData &event, const CommonEventPublishInfo &publishInfo,
const sptr<IRemoteObject> &commonEventListener) override;
virtual bool SubscribeCommonEvent(
const CommonEventSubscribeInfo &subscriberInfo, const sptr<IRemoteObject> &commonEventListener) override;
virtual bool UnsubscribeCommonEvent(const sptr<IRemoteObject> &commonEventListener) override;
virtual bool GetStickyCommonEvent(const std::string &event, CommonEventData &eventData) override;
virtual bool DumpState(const std::string &event, std::vector<std::string> &state) override;
virtual bool FinishReceiver(const sptr<IRemoteObject> &proxy, const int &code, const std::string &receiverData,
const bool &abortEvent) override;
virtual bool Freeze(const uid_t &uid) override;
virtual bool Unfreeze(const uid_t &uid) override;
private:
bool SendRequest(ICommonEvent::Message code, MessageParcel &data, MessageParcel &reply);
private:
static inline BrokerDelegator<CommonEventProxy> delegator_;
};
} // namespace EventFwk
} // namespace OHOS
#endif // FOUNDATION_EVENT_CESFWK_INNERKITS_INCLUDE_COMMON_EVENT_PROXY_H
@@ -0,0 +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_EVENT_CESFWK_INNERKITS_INCLUDE_COMMON_EVENT_STUB_H
#define FOUNDATION_EVENT_CESFWK_INNERKITS_INCLUDE_COMMON_EVENT_STUB_H
#include "icommon_event.h"
#include "iremote_stub.h"
#include "nocopyable.h"
namespace OHOS {
namespace EventFwk {
class CommonEventStub : public IRemoteStub<ICommonEvent> {
public:
CommonEventStub();
virtual ~CommonEventStub() override;
DECLARE_INTERFACE_DESCRIPTOR(u"ICommonEvent");
virtual int OnRemoteRequest(
uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override;
virtual bool PublishCommonEvent(const CommonEventData &event, const CommonEventPublishInfo &publishinfo,
const sptr<IRemoteObject> &commonEventListener) override;
virtual bool SubscribeCommonEvent(
const CommonEventSubscribeInfo &subscriberInfo, const sptr<IRemoteObject> &commonEventListener) override;
virtual bool UnsubscribeCommonEvent(const sptr<IRemoteObject> &commonEventListener) override;
virtual bool GetStickyCommonEvent(const std::string &event, CommonEventData &eventData) override;
virtual bool DumpState(const std::string &event, std::vector<std::string> &state) override;
virtual bool Freeze(const uid_t &uid) override;
virtual bool Unfreeze(const uid_t &uid) override;
private:
DISALLOW_COPY_AND_MOVE(CommonEventStub);
};
} // namespace EventFwk
} // namespace OHOS
#endif // FOUNDATION_EVENT_CESFWK_INNERKITS_INCLUDE_COMMON_EVENT_STUB_H
@@ -0,0 +1,37 @@
/*
* 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_EVENT_CESFWK_INNERKITS_INCLUDE_EVENT_RECEIVE_PROXY_H
#define FOUNDATION_EVENT_CESFWK_INNERKITS_INCLUDE_EVENT_RECEIVE_PROXY_H
#include "common_event_data.h"
#include "ievent_receive.h"
#include "iremote_proxy.h"
namespace OHOS {
namespace EventFwk {
class EventReceiveProxy : public IRemoteProxy<IEventReceive> {
public:
explicit EventReceiveProxy(const sptr<IRemoteObject> &object);
virtual ~EventReceiveProxy() override;
virtual void NotifyEvent(const CommonEventData &commonEventData, const bool &ordered, const bool &sticky) override;
private:
static inline BrokerDelegator<EventReceiveProxy> delegator_;
};
} // namespace EventFwk
} // namespace OHOS
#endif // FOUNDATION_EVENT_CESFWK_INNERKITS_INCLUDE_EVENT_RECEIVE_PROXY_H
@@ -0,0 +1,34 @@
/*
* 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_EVENT_CESFWK_INNERKITS_INCLUDE_EVENT_RECEIVE_STUB_H
#define FOUNDATION_EVENT_CESFWK_INNERKITS_INCLUDE_EVENT_RECEIVE_STUB_H
#include "ievent_receive.h"
#include "iremote_stub.h"
namespace OHOS {
namespace EventFwk {
class EventReceiveStub : public IRemoteStub<IEventReceive> {
public:
EventReceiveStub();
virtual ~EventReceiveStub() override;
virtual int OnRemoteRequest(
uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override;
};
} // namespace EventFwk
} // namespace OHOS
#endif // FOUNDATION_EVENT_CESFWK_INNERKITS_INCLUDE_EVENT_RECEIVE_STUB_H
+59
View File
@@ -0,0 +1,59 @@
/*
* 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_EVENT_CESFWK_INNERKITS_INCLUDE_ICOMMON_EVENT_H
#define FOUNDATION_EVENT_CESFWK_INNERKITS_INCLUDE_ICOMMON_EVENT_H
#include "common_event_data.h"
#include "common_event_publish_info.h"
#include "common_event_subscribe_info.h"
#include "iremote_broker.h"
#include "iremote_object.h"
namespace OHOS {
namespace EventFwk {
class ICommonEvent : public IRemoteBroker {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"ohos.eventfwk.ICommonEvent");
virtual bool PublishCommonEvent(const CommonEventData &event, const CommonEventPublishInfo &publishinfo,
const sptr<IRemoteObject> &commonEventListener) = 0;
virtual bool SubscribeCommonEvent(
const CommonEventSubscribeInfo &subscriberInfo, const sptr<IRemoteObject> &commonEventListener) = 0;
virtual bool UnsubscribeCommonEvent(const sptr<IRemoteObject> &commonEventListener) = 0;
virtual bool GetStickyCommonEvent(const std::string &event, CommonEventData &eventData) = 0;
virtual bool DumpState(const std::string &event, std::vector<std::string> &state) = 0;
virtual bool FinishReceiver(
const sptr<IRemoteObject> &proxy, const int &code, const std::string &receiverData, const bool &abortEvent) = 0;
virtual bool Freeze(const uid_t &uid) = 0;
virtual bool Unfreeze(const uid_t &uid) = 0;
enum class Message {
CES_PUBLISH_COMMON_EVENT = 0,
CES_SUBSCRIBE_COMMON_EVENT,
CES_UNSUBSCRIBE_COMMON_EVENT,
CES_GET_STICKY_COMMON_EVENT,
CES_FINISH_RECEIVER,
CES_FREEZE,
CES_UNFREEZE,
// ipc id 2001-3000 for tools
// ipc id for dumping Subscribe State (2001)
CES_DUMP_STATE = 2001,
};
};
} // namespace EventFwk
} // namespace OHOS
#endif // FOUNDATION_EVENT_CESFWK_INNERKITS_INCLUDE_ICOMMON_EVENT_H
+45
View File
@@ -0,0 +1,45 @@
/*
* 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_EVENT_CESFWK_INNERKITS_INCLUDE_IEVENT_RECEIVE_H
#define FOUNDATION_EVENT_CESFWK_INNERKITS_INCLUDE_IEVENT_RECEIVE_H
#include "common_event_data.h"
#include "iremote_broker.h"
namespace OHOS {
namespace EventFwk {
class IEventReceive : public IRemoteBroker {
public:
DECLARE_INTERFACE_DESCRIPTOR(u"ohos.eventfwk.IEventReceive");
/**
* Notify event.
*
* @param commonEventData the common event data
* @param ordered whether it is an ordered common event
* @param sticky whether it is a sticky common event
*
*/
virtual void NotifyEvent(const CommonEventData &commonEventData, const bool &ordered, const bool &sticky) = 0;
enum class Message {
CES_NOTIFY_COMMON_EVENT = 1,
};
};
} // namespace EventFwk
} // namespace OHOS
#endif // FOUNDATION_EVENT_CESFWK_INNERKITS_INCLUDE_IEVENT_RECEIVE_H
+260
View File
@@ -0,0 +1,260 @@
/*
* 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 "common_event.h"
#include "common_event_death_recipient.h"
#include "event_log_wrapper.h"
#include "iservice_registry.h"
#include "system_ability_definition.h"
namespace OHOS {
namespace EventFwk {
bool CommonEvent::PublishCommonEvent(const CommonEventData &data, const CommonEventPublishInfo &publishInfo,
const std::shared_ptr<CommonEventSubscriber> &subscriber)
{
EVENT_LOGI("enter");
if (data.GetWant().GetAction() == std::string()) {
EVENT_LOGE("the commonEventdata action is null");
return false;
}
if ((publishInfo.IsOrdered() == false) && (subscriber != nullptr)) {
EVENT_LOGE("When publishing unordered events, the subscriber object is not required.");
return false;
}
if (!GetCommonEventProxy()) {
EVENT_LOGE("the commonEventProxy_ is null");
return false;
}
sptr<IRemoteObject> commonEventListener = nullptr;
if (subscriber) {
if (CreateCommonEventListener(subscriber, commonEventListener) == SUBSCRIBE_FAILD) {
return false;
}
}
return commonEventProxy_->PublishCommonEvent(data, publishInfo, commonEventListener);
}
bool CommonEvent::SubscribeCommonEvent(const std::shared_ptr<CommonEventSubscriber> &subscriber)
{
EVENT_LOGI("enter");
if (subscriber == nullptr) {
EVENT_LOGE("the subscriber is null");
return false;
}
if (subscriber->GetSubscribeInfo().GetMatchingSkills().CountEvent() == 0) {
EVENT_LOGE("the subscriber has no event");
return false;
}
if (!GetCommonEventProxy()) {
EVENT_LOGE("the commonEventProxy_ is null");
return false;
}
sptr<IRemoteObject> commonEventListener = nullptr;
int subscribeState_ = CreateCommonEventListener(subscriber, commonEventListener);
if (subscribeState_ == INITIAL_SUBSCRIPTION) {
return commonEventProxy_->SubscribeCommonEvent(subscriber->GetSubscribeInfo(), commonEventListener);
} else if (subscribeState_ == ALREADY_SUBSCRIBED) {
return true;
} else {
return false;
}
}
bool CommonEvent::UnSubscribeCommonEvent(const std::shared_ptr<CommonEventSubscriber> &subscriber)
{
EVENT_LOGI("enter");
if (subscriber == nullptr) {
EVENT_LOGE("the subscriber is null");
return false;
}
if (!GetCommonEventProxy()) {
EVENT_LOGE("the commonEventProxy is null");
return false;
}
std::lock_guard<std::mutex> lock(eventListenersMutex_);
auto eventListener = eventListeners_.find(subscriber);
if (eventListener != eventListeners_.end()) {
if (commonEventProxy_->UnsubscribeCommonEvent(eventListener->second)) {
eventListeners_.erase(eventListener);
return true;
}
return false;
} else {
EVENT_LOGW("No specified subscriber has been registered");
}
return true;
}
bool CommonEvent::GetStickyCommonEvent(const std::string &event, CommonEventData &eventData)
{
EVENT_LOGI("enter");
if (!GetCommonEventProxy()) {
EVENT_LOGE("the commonEventProxy is null");
return false;
}
if (event.empty()) {
EVENT_LOGE("event is empty");
return false;
}
return commonEventProxy_->GetStickyCommonEvent(event, eventData);
}
bool CommonEvent::FinishReceiver(
const sptr<IRemoteObject> &proxy, const int &code, const std::string &data, const bool &abortEvent)
{
EVENT_LOGI("enter");
if (proxy == nullptr) {
EVENT_LOGE("the proxy is null");
return false;
}
if (!GetCommonEventProxy()) {
EVENT_LOGE("the commonEventProxy is null");
return false;
}
return commonEventProxy_->FinishReceiver(proxy, code, data, abortEvent);
}
bool CommonEvent::DumpState(const std::string &event, std::vector<std::string> &state)
{
EVENT_LOGI("enter");
if (!GetCommonEventProxy()) {
EVENT_LOGE("the commonEventProxy is null");
return false;
}
return commonEventProxy_->DumpState(event, state);
}
void CommonEvent::ResetCommonEventProxy()
{
EVENT_LOGI("enter");
std::lock_guard<std::mutex> lock(mutex_);
if ((commonEventProxy_ != nullptr) && (commonEventProxy_->AsObject() != nullptr)) {
commonEventProxy_->AsObject()->RemoveDeathRecipient(recipient_);
}
commonEventProxy_ = nullptr;
}
bool CommonEvent::Freeze(const uid_t &uid)
{
EVENT_LOGI("enter");
if (!GetCommonEventProxy()) {
EVENT_LOGE("the commonEventProxy is null");
return false;
}
return commonEventProxy_->Freeze(uid);
}
bool CommonEvent::Unfreeze(const uid_t &uid)
{
EVENT_LOGI("enter");
if (!GetCommonEventProxy()) {
EVENT_LOGE("the commonEventProxy is null");
return false;
}
return commonEventProxy_->Unfreeze(uid);
}
bool CommonEvent::GetCommonEventProxy()
{
EVENT_LOGI("enter");
if (!commonEventProxy_) {
std::lock_guard<std::mutex> lock(mutex_);
if (!commonEventProxy_) {
sptr<ISystemAbilityManager> systemAbilityManager =
SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (!systemAbilityManager) {
EVENT_LOGE("Failed to get system ability mgr.");
return false;
}
sptr<IRemoteObject> remoteObject = systemAbilityManager->GetSystemAbility(COMMON_EVENT_SERVICE_ID);
if (!remoteObject) {
EVENT_LOGE("Failed to get COMMON Event Manager.");
return false;
}
commonEventProxy_ = iface_cast<ICommonEvent>(remoteObject);
if ((!commonEventProxy_) || (!commonEventProxy_->AsObject())) {
EVENT_LOGE("Failed to get COMMON Event Manager's proxy");
return false;
}
recipient_ = new CommonEventDeathRecipient();
if (!recipient_) {
EVENT_LOGE("Failed to create death Recipient ptr CommonEventDeathRecipient!");
return false;
}
commonEventProxy_->AsObject()->AddDeathRecipient(recipient_);
}
}
return true;
}
int CommonEvent::CreateCommonEventListener(
const std::shared_ptr<CommonEventSubscriber> &subscriber, sptr<IRemoteObject> &commonEventListener)
{
if (subscriber == nullptr) {
EVENT_LOGE("subscriber is null");
return SUBSCRIBE_FAILD;
}
std::lock_guard<std::mutex> lock(eventListenersMutex_);
auto eventListener = eventListeners_.find(subscriber);
if (eventListener != eventListeners_.end()) {
commonEventListener = eventListener->second;
EVENT_LOGW("subscriber has common event listener");
return ALREADY_SUBSCRIBED;
} else {
sptr<IEventReceive> listener = new CommonEventListener(subscriber);
if (!listener) {
EVENT_LOGE("the common event listener is null");
return SUBSCRIBE_FAILD;
}
commonEventListener = listener->AsObject();
eventListeners_[subscriber] = commonEventListener;
}
return INITIAL_SUBSCRIPTION;
}
} // namespace EventFwk
} // namespace OHOS
@@ -0,0 +1,30 @@
/*
* 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 "common_event_death_recipient.h"
#include "common_event.h"
#include "event_log_wrapper.h"
#include "singleton.h"
namespace OHOS {
namespace EventFwk {
void CommonEventDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &remote)
{
EVENT_LOGI("common event service died, remove the proxy object");
DelayedSingleton<CommonEvent>::GetInstance()->ResetCommonEventProxy();
}
} // namespace EventFwk
} // namespace OHOS
@@ -0,0 +1,118 @@
/*
* 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 "common_event_listener.h"
#include "event_log_wrapper.h"
namespace OHOS {
namespace EventFwk {
CommonEventListener::CommonEventListener(const std::shared_ptr<CommonEventSubscriber> &commonEventSubscriber)
: commonEventSubscriber_(commonEventSubscriber)
{
Init();
}
CommonEventListener::~CommonEventListener()
{}
void CommonEventListener::NotifyEvent(const CommonEventData &commonEventData, const bool &ordered, const bool &sticky)
{
EVENT_LOGI("enter");
if (!IsReady()) {
EVENT_LOGE("not ready");
return;
}
std::function<void()> onReceiveEventFunc =
std::bind(&CommonEventListener::OnReceiveEvent, this, commonEventData, ordered, sticky);
handler_->PostTask(onReceiveEventFunc);
}
ErrCode CommonEventListener::Init()
{
EVENT_LOGD("ready to init");
if (runner_ == nullptr) {
if (!commonEventSubscriber_) {
EVENT_LOGE("Failed to init with CommonEventSubscriber nullptr");
return ERR_INVALID_OPERATION;
}
if (CommonEventSubscribeInfo::HANDLER == commonEventSubscriber_->GetSubscribeInfo().GetThreadMode()) {
runner_ = EventRunner::GetMainEventRunner();
} else {
runner_ = EventRunner::Create(true);
}
if (!runner_) {
EVENT_LOGE("Failed to init due to create runner error");
return ERR_INVALID_OPERATION;
}
}
if (handler_ == nullptr) {
handler_ = std::make_shared<EventHandler>(runner_);
if (!handler_) {
EVENT_LOGE("Failed to init due to create handler error");
return ERR_INVALID_OPERATION;
}
}
return ERR_OK;
}
bool CommonEventListener::IsReady()
{
if (runner_ == nullptr) {
EVENT_LOGE("runner is not ready");
return false;
}
if (handler_ == nullptr) {
EVENT_LOGE("handler is not ready");
return false;
}
return true;
}
void CommonEventListener::OnReceiveEvent(
const CommonEventData &commonEventData, const bool &ordered, const bool &sticky)
{
EVENT_LOGI("enter");
int code = commonEventData.GetCode();
std::string data = commonEventData.GetData();
std::shared_ptr<AsyncCommonEventResult> result =
std::make_shared<AsyncCommonEventResult>(code, data, ordered, sticky, this);
if (result == nullptr) {
EVENT_LOGE("Failed to create AsyncCommonEventResult");
return;
}
if (!commonEventSubscriber_) {
EVENT_LOGE("CommonEventSubscriber ptr is nullptr");
return;
}
commonEventSubscriber_->SetAsyncCommonEventResult(result);
commonEventSubscriber_->OnReceiveEvent(commonEventData);
if ((commonEventSubscriber_->GetAsyncCommonEventResult() != nullptr) && ordered) {
commonEventSubscriber_->GetAsyncCommonEventResult()->FinishCommonEvent();
}
}
} // namespace EventFwk
} // namespace OHOS
@@ -0,0 +1,32 @@
/*
* 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 "common_event_listener_handler.h"
#include "event_log_wrapper.h"
namespace OHOS {
namespace EventFwk {
CommonEventListenerHandler::CommonEventListenerHandler(const std::shared_ptr<EventRunner> &runner)
: EventHandler(runner)
{
EVENT_LOGD("instance created");
}
CommonEventListenerHandler::~CommonEventListenerHandler()
{
EVENT_LOGD("instance destroyed");
}
} // namespace EventFwk
} // namespace OHOS
+260
View File
@@ -0,0 +1,260 @@
/*
* 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 "common_event_proxy.h"
#include "event_log_wrapper.h"
#include "string_ex.h"
namespace OHOS {
namespace EventFwk {
using namespace OHOS::AppExecFwk;
CommonEventProxy::CommonEventProxy(const sptr<IRemoteObject> &object) : IRemoteProxy<ICommonEvent>(object)
{
EVENT_LOGD("CommonEventProxy instance created");
}
CommonEventProxy::~CommonEventProxy()
{
EVENT_LOGD("CommonEventProxy instance destoryed");
}
bool CommonEventProxy::PublishCommonEvent(const CommonEventData &event, const CommonEventPublishInfo &publishInfo,
const sptr<IRemoteObject> &commonEventListener)
{
EVENT_LOGD("start");
MessageParcel data;
MessageParcel reply;
if (!data.WriteParcelable(&event)) {
EVENT_LOGE("Failed to write parcelable event");
return false;
}
if (!data.WriteParcelable(&publishInfo)) {
EVENT_LOGE("Failed to write parcelable publishInfo");
return false;
}
if (!data.WriteParcelable(commonEventListener)) {
EVENT_LOGE("Failed to write parcelable commonEventListener");
return false;
}
bool ret = SendRequest(ICommonEvent::Message::CES_PUBLISH_COMMON_EVENT, data, reply);
if (ret) {
ret = reply.ReadBool();
}
EVENT_LOGD("end");
return ret;
}
bool CommonEventProxy::SubscribeCommonEvent(
const CommonEventSubscribeInfo &subscriberInfo, const sptr<IRemoteObject> &commonEventListener)
{
EVENT_LOGD("start");
MessageParcel data;
MessageParcel reply;
if (!data.WriteParcelable(&subscriberInfo)) {
EVENT_LOGE("Failed to write parcelable subscriberInfo");
return false;
}
if (!data.WriteParcelable(commonEventListener)) {
EVENT_LOGE("Failed to write parcelable commonEventListener");
return false;
}
bool ret = SendRequest(ICommonEvent::Message::CES_SUBSCRIBE_COMMON_EVENT, data, reply);
if (ret) {
ret = reply.ReadBool();
}
EVENT_LOGD("end");
return ret;
}
bool CommonEventProxy::UnsubscribeCommonEvent(const sptr<IRemoteObject> &commonEventListener)
{
EVENT_LOGD("start");
MessageParcel data;
MessageParcel reply;
if (!data.WriteParcelable(commonEventListener)) {
EVENT_LOGE("Failed to write parcelable commonEventListener");
return false;
}
bool ret = SendRequest(ICommonEvent::Message::CES_UNSUBSCRIBE_COMMON_EVENT, data, reply);
if (ret) {
ret = reply.ReadBool();
}
EVENT_LOGD("end");
return ret;
}
bool CommonEventProxy::GetStickyCommonEvent(const std::string &event, CommonEventData &eventData)
{
EVENT_LOGD("start");
MessageParcel data;
MessageParcel reply;
if (!data.WriteString16(Str8ToStr16(event))) {
EVENT_LOGE("Failed to write string event");
return false;
}
bool ret = SendRequest(ICommonEvent::Message::CES_GET_STICKY_COMMON_EVENT, data, reply);
if (ret) {
ret = reply.ReadBool();
if (ret) {
std::unique_ptr<CommonEventData> eventDataPtr(reply.ReadParcelable<CommonEventData>());
eventData = *eventDataPtr;
}
}
EVENT_LOGD("end");
return ret;
}
bool CommonEventProxy::DumpState(const std::string &event, std::vector<std::string> &state)
{
EVENT_LOGD("start");
MessageParcel data;
MessageParcel reply;
if (!data.WriteString16(Str8ToStr16(event))) {
EVENT_LOGE("Failed to write string event");
return false;
}
bool ret = SendRequest(ICommonEvent::Message::CES_DUMP_STATE, data, reply);
if (ret) {
int32_t stackNum = reply.ReadInt32();
for (int i = 0; i < stackNum; i++) {
std::string stack = Str16ToStr8(reply.ReadString16());
state.emplace_back(stack);
}
}
EVENT_LOGD("end");
return ret;
}
bool CommonEventProxy::FinishReceiver(
const sptr<IRemoteObject> &proxy, const int &code, const std::string &receiverData, const bool &abortEvent)
{
EVENT_LOGD("start");
MessageParcel data;
MessageParcel reply;
if (!data.WriteParcelable(proxy)) {
EVENT_LOGE("Failed to write parcelable proxy");
return false;
}
if (!data.WriteInt32(code)) {
EVENT_LOGE("Failed to write int code");
return false;
}
if (!data.WriteString16(Str8ToStr16(receiverData))) {
EVENT_LOGE("Failed to write string receiverData");
return false;
}
if (!data.WriteBool(abortEvent)) {
EVENT_LOGE("Failed to write bool abortEvent");
return false;
}
bool ret = SendRequest(ICommonEvent::Message::CES_FINISH_RECEIVER, data, reply);
if (ret) {
ret = reply.ReadBool();
}
EVENT_LOGD("end");
return ret;
}
bool CommonEventProxy::Freeze(const uid_t &uid)
{
EVENT_LOGD("start");
MessageParcel data;
MessageParcel reply;
if (!data.WriteInt32(uid)) {
EVENT_LOGE("Failed to write int uid");
return false;
}
bool ret = SendRequest(ICommonEvent::Message::CES_FREEZE, data, reply);
if (ret) {
ret = reply.ReadBool();
}
EVENT_LOGD("end");
return ret;
}
bool CommonEventProxy::Unfreeze(const uid_t &uid)
{
EVENT_LOGD("start");
MessageParcel data;
MessageParcel reply;
if (!data.WriteInt32(uid)) {
EVENT_LOGE("Failed to write int uid");
return false;
}
bool ret = SendRequest(ICommonEvent::Message::CES_UNFREEZE, data, reply);
if (ret) {
ret = reply.ReadBool();
}
EVENT_LOGD("end");
return ret;
}
bool CommonEventProxy::SendRequest(ICommonEvent::Message code, MessageParcel &data, MessageParcel &reply)
{
EVENT_LOGD("start");
sptr<IRemoteObject> remote = Remote();
if (remote == nullptr) {
EVENT_LOGE("Remote is NULL, %{public}d", code);
return false;
}
MessageOption option(MessageOption::TF_SYNC);
int32_t result = remote->SendRequest(static_cast<uint32_t>(code), data, reply, option);
if (result != OHOS::NO_ERROR) {
EVENT_LOGE("Failed to SendRequest %{public}d, error code: %{public}d", code, result);
return false;
}
EVENT_LOGD("end");
return true;
}
} // namespace EventFwk
} // namespace OHOS
+207
View File
@@ -0,0 +1,207 @@
/*
* 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 "common_event_stub.h"
#include "common_event_publish_info.h"
#include "event_log_wrapper.h"
#include "string_ex.h"
namespace OHOS {
namespace EventFwk {
CommonEventStub::CommonEventStub()
{}
CommonEventStub::~CommonEventStub()
{}
int CommonEventStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)
{
switch (code) {
case static_cast<uint32_t>(ICommonEvent::Message::CES_PUBLISH_COMMON_EVENT): {
std::unique_ptr<CommonEventData> event(data.ReadParcelable<CommonEventData>());
std::unique_ptr<CommonEventPublishInfo> publishinfo(data.ReadParcelable<CommonEventPublishInfo>());
sptr<IRemoteObject> commonEventListener = data.ReadParcelable<IRemoteObject>();
if (!event) {
EVENT_LOGE("Failed to ReadParcelable<CommonEventData>");
return ERR_INVALID_VALUE;
}
if (!publishinfo) {
EVENT_LOGE("Failed to ReadParcelable<CommonEventPublishInfo>");
return ERR_INVALID_VALUE;
}
bool ret = PublishCommonEvent(*event, *publishinfo, commonEventListener);
if (!reply.WriteBool(ret)) {
EVENT_LOGE("Failed to write reply ");
return ERR_INVALID_VALUE;
}
break;
}
case static_cast<uint32_t>(ICommonEvent::Message::CES_SUBSCRIBE_COMMON_EVENT): {
std::unique_ptr<CommonEventSubscribeInfo> subscriberInfo(data.ReadParcelable<CommonEventSubscribeInfo>());
sptr<IRemoteObject> commonEventListener = data.ReadParcelable<IRemoteObject>();
if (!subscriberInfo) {
EVENT_LOGE("Failed to ReadParcelable<CommonEventSubscribeInfo>");
return ERR_INVALID_VALUE;
}
if (commonEventListener == nullptr) {
EVENT_LOGE("Failed to ReadParcelable<IRemoteObject>");
return ERR_INVALID_VALUE;
}
bool ret = SubscribeCommonEvent(*subscriberInfo, commonEventListener);
if (!reply.WriteBool(ret)) {
EVENT_LOGE("Failed to write reply");
return ERR_INVALID_VALUE;
}
break;
}
case static_cast<uint32_t>(ICommonEvent::Message::CES_UNSUBSCRIBE_COMMON_EVENT): {
sptr<IRemoteObject> commonEventListener = data.ReadParcelable<IRemoteObject>();
if (commonEventListener == nullptr) {
EVENT_LOGE("Failed to ReadParcelable<IRemoteObject>");
return ERR_INVALID_VALUE;
}
bool ret = UnsubscribeCommonEvent(commonEventListener);
if (!reply.WriteBool(ret)) {
EVENT_LOGE("Failed to write reply");
return ERR_INVALID_VALUE;
}
break;
}
case static_cast<uint32_t>(ICommonEvent::Message::CES_GET_STICKY_COMMON_EVENT): {
std::string event = Str16ToStr8(data.ReadString16());
CommonEventData eventData;
bool ret = GetStickyCommonEvent(event, eventData);
if (!reply.WriteBool(ret)) {
EVENT_LOGE("Failed to write reply ret!");
return ERR_INVALID_VALUE;
}
if (!reply.WriteParcelable(&eventData)) {
EVENT_LOGE("Failed to write reply eventData!");
return ERR_INVALID_VALUE;
}
break;
}
case static_cast<uint32_t>(ICommonEvent::Message::CES_DUMP_STATE): {
std::vector<std::string> result;
std::string event = Str16ToStr8(data.ReadString16());
DumpState(event, result);
reply.WriteInt32(result.size());
for (auto stack : result) {
reply.WriteString16(Str8ToStr16(stack));
}
break;
}
case static_cast<uint32_t>(ICommonEvent::Message::CES_FINISH_RECEIVER): {
sptr<IRemoteObject> proxy = data.ReadParcelable<IRemoteObject>();
if (proxy == nullptr) {
EVENT_LOGE("Failed to ReadParcelable<IRemoteObject>");
return ERR_INVALID_VALUE;
}
int receiverCode = data.ReadInt32();
std::string receiverData = Str16ToStr8(data.ReadString16());
bool abortEvent = data.ReadBool();
bool ret = FinishReceiver(proxy, receiverCode, receiverData, abortEvent);
if (!reply.WriteBool(ret)) {
EVENT_LOGE("Failed to write reply");
return ERR_INVALID_VALUE;
}
break;
}
case static_cast<uint32_t>(ICommonEvent::Message::CES_FREEZE): {
int uid = data.ReadInt32();
bool ret = Freeze(uid);
if (!reply.WriteBool(ret)) {
EVENT_LOGE("Failed to write reply");
return ERR_INVALID_VALUE;
}
break;
}
case static_cast<uint32_t>(ICommonEvent::Message::CES_UNFREEZE): {
int uid = data.ReadInt32();
bool ret = Unfreeze(uid);
if (!reply.WriteBool(ret)) {
EVENT_LOGE("Failed to write reply");
return ERR_INVALID_VALUE;
}
break;
}
default:
EVENT_LOGW("unknown, code = %{public}u, flags= %{public}u", code, option.GetFlags());
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}
return NO_ERROR;
}
bool CommonEventStub::PublishCommonEvent(const CommonEventData &event, const CommonEventPublishInfo &publishinfo,
const sptr<IRemoteObject> &commonEventListener)
{
EVENT_LOGD("called");
return true;
}
bool CommonEventStub::SubscribeCommonEvent(
const CommonEventSubscribeInfo &subscriberInfo, const sptr<IRemoteObject> &commonEventListener)
{
EVENT_LOGD("called");
return true;
}
bool CommonEventStub::UnsubscribeCommonEvent(const sptr<IRemoteObject> &commonEventListener)
{
EVENT_LOGD("called");
return true;
}
bool CommonEventStub::GetStickyCommonEvent(const std::string &event, CommonEventData &eventData)
{
EVENT_LOGD("called");
return true;
}
bool CommonEventStub::DumpState(const std::string &event, std::vector<std::string> &state)
{
EVENT_LOGD("called");
return true;
}
bool CommonEventStub::Freeze(const uid_t &uid)
{
EVENT_LOGD("called");
return true;
}
bool CommonEventStub::Unfreeze(const uid_t &uid)
{
EVENT_LOGD("called");
return true;
}
} // namespace EventFwk
} // namespace OHOS
@@ -0,0 +1,70 @@
/*
* 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 "event_receive_proxy.h"
#include "event_log_wrapper.h"
namespace OHOS {
namespace EventFwk {
EventReceiveProxy::EventReceiveProxy(const sptr<IRemoteObject> &object) : IRemoteProxy<IEventReceive>(object)
{
EVENT_LOGD("event receive proxy instance is created");
}
EventReceiveProxy::~EventReceiveProxy()
{
EVENT_LOGD("event receive proxy is destoryed");
}
void EventReceiveProxy::NotifyEvent(const CommonEventData &commonEventData, const bool &ordered, const bool &sticky)
{
EVENT_LOGD("start");
MessageParcel data;
MessageParcel reply;
MessageOption option(MessageOption::TF_ASYNC);
sptr<IRemoteObject> remote = Remote();
if (remote == nullptr) {
EVENT_LOGE("Failed to send cmd to service due to remote objetc is null");
return;
}
if (!data.WriteParcelable(&commonEventData)) {
EVENT_LOGE("Failed to write parcelable");
return;
}
if (!data.WriteBool(ordered)) {
EVENT_LOGE("Failed to write Bool");
return;
}
if (!data.WriteBool(sticky)) {
EVENT_LOGE("Failed to write Bool");
return;
}
int32_t result = remote->SendRequest(
static_cast<uint32_t>(IEventReceive::Message::CES_NOTIFY_COMMON_EVENT), data, reply, option);
if (result != OHOS::NO_ERROR) {
EVENT_LOGE("Failed to SendRequest, error code: %{public}d", result);
return;
}
EVENT_LOGD("end");
}
} // namespace EventFwk
} // namespace OHOS
@@ -0,0 +1,54 @@
/*
* 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 "event_receive_stub.h"
#include "event_log_wrapper.h"
namespace OHOS {
namespace EventFwk {
EventReceiveStub::EventReceiveStub()
{
EVENT_LOGD("event receive stub instance is created");
}
EventReceiveStub::~EventReceiveStub()
{
EVENT_LOGD("event receive stub instance is destroyed");
}
int EventReceiveStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)
{
switch (code) {
case static_cast<uint32_t>(IEventReceive::Message::CES_NOTIFY_COMMON_EVENT): {
std::unique_ptr<CommonEventData> eventData(data.ReadParcelable<CommonEventData>());
bool ordered = data.ReadBool();
bool sticky = data.ReadBool();
if (eventData == nullptr) {
EVENT_LOGE("callback stub receive common event data is nullptr");
return ERR_INVALID_VALUE;
}
NotifyEvent(*eventData, ordered, sticky);
break;
}
default:
EVENT_LOGW("event receive stub receives unknown code, code = %{public}u", code);
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}
return NO_ERROR;
}
} // namespace EventFwk
} // namespace OHOS
+39
View File
@@ -0,0 +1,39 @@
# 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/test.gni")
module_output_path = "ces_standard/cesfwk/innerkits"
config("temp_config") {
visibility = [ ":*" ]
include_dirs = [ "//utils/native/base/include" ]
}
ohos_unittest("temp_test") {
module_out_path = module_output_path
sources = [
#"temp_test.cpp"
]
configs = [ ":temp_config" ]
deps = [ "//third_party/googletest:gtest_main" ]
}
group("unittest") {
testonly = true
deps = []
deps += [ ":temp_test" ]
}
+18
View File
@@ -0,0 +1,18 @@
# 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")
group("napi_packages") {
deps = [ "//base/notification/ces_standard/cesfwk/kits/napi/native_module:commonevent" ]
}
+42
View File
@@ -0,0 +1,42 @@
# Copyright (c) 2021 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import("//build/ohos.gni")
ohos_shared_library("commonevent") {
include_dirs = [
"//foundation/aafwk/standard/services/common/include/",
"//foundation/ace/napi/interfaces/kits/napi",
"//third_party/node/src",
"//third_party/libuv/include",
]
sources = [ "native_module.cpp" ]
deps = [
"//base/notification/ces_standard/cesfwk/kits/native:cesfwk_kits",
"//foundation/aafwk/standard/interfaces/innerkits/want:want",
"//foundation/ace/napi:ace_napi",
"//third_party/libuv:uv_static",
]
external_deps = [
"appexecfwk_standard:appexecfwk_base",
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
]
relative_install_dir = "module"
subsystem_name = "notification"
part_name = "ces_standard"
}
File diff suppressed because it is too large Load Diff
+81
View File
@@ -0,0 +1,81 @@
# 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("//base/notification/ces_standard/event.gni")
import("//build/ohos.gni")
CESFWK_INNERKITS_DIR = "//base/notification/ces_standard/cesfwk/innerkits"
CESFWK_KITS_DIR = "//base/notification/ces_standard/cesfwk/kits/native"
cflags = []
config("cesfwk_kit_config") {
visibility = [ ":*" ]
include_dirs = []
if (target_cpu == "arm") {
cflags += [ "-DBINDER_IPC_32BIT" ]
}
defines = [
"APP_LOG_TAG = \"CesFwkKits\"",
"LOG_DOMAIN = 0xD002200",
]
}
config("cesfwk_kit_public_config") {
visibility = [ ":*" ]
include_dirs = [
"${CESFWK_INNERKITS_DIR}/include",
"${CESFWK_KITS_DIR}/include",
"//foundation/aafwk/standard/interfaces/innerkits/base/include/",
"//foundation/aafwk/standard/interfaces/innerkits/base/include/ohos/aafwk/base/",
"//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content/",
"//base/notification/ces_standard/common/log/include",
"//utils/native/base/include",
]
}
ohos_shared_library("cesfwk_kits") {
sources = [
"${CESFWK_KITS_DIR}/src/async_common_event_result.cpp",
"${CESFWK_KITS_DIR}/src/common_event_data.cpp",
"${CESFWK_KITS_DIR}/src/common_event_manager.cpp",
"${CESFWK_KITS_DIR}/src/common_event_publish_info.cpp",
"${CESFWK_KITS_DIR}/src/common_event_subscribe_info.cpp",
"${CESFWK_KITS_DIR}/src/common_event_subscriber.cpp",
"${CESFWK_KITS_DIR}/src/common_event_support.cpp",
"${CESFWK_KITS_DIR}/src/matching_skills.cpp",
]
configs = [ ":cesfwk_kit_config" ]
public_configs = [ ":cesfwk_kit_public_config" ]
deps = [
"${CESFWK_INNERKITS_DIR}:cesfwk_innerkits",
"${event_common_path}:libevent_common",
"//foundation/aafwk/standard/interfaces/innerkits/want:want",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler",
"//utils/native/base:utils",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
]
subsystem_name = "notification"
part_name = "ces_standard"
}
@@ -0,0 +1,128 @@
/*
* 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_EVENT_CESFWK_KITS_NATIVE_INCLUDE_ASYNC_COMMON_EVENT_RESULT_H
#define FOUNDATION_EVENT_CESFWK_KITS_NATIVE_INCLUDE_ASYNC_COMMON_EVENT_RESULT_H
#include <string>
#include "iremote_object.h"
namespace OHOS {
namespace EventFwk {
class AsyncCommonEventResult {
public:
/**
* Create a AsyncCommonEventResult instance based on the parameters.
*
* @param resultCode the result code of the current ordered common event
* @param resultData the result data of the current ordered common event
* @param ordered the type of the current ordered common event is ordered or not
* @param sticky the type of the current sticky common event is sticky or not
* @param token the remote object of the current ordered common event
*/
AsyncCommonEventResult(const int &resultCode, const std::string &resultData, const bool &ordered,
const bool &sticky, const sptr<IRemoteObject> &token);
/**
* Default deconstructor used to deconstruct.
*
*/
~AsyncCommonEventResult();
/**
* Set the result code of the current ordered common event.
*
* @param code the result code of the current ordered common event
*/
bool SetCode(const int &code);
/**
* Obtain the result code of the current ordered common event.
*
* @return the result code of the current ordered common event
*/
int GetCode() const;
/**
* Set the result data of the current ordered common event.
*
* @param data the result data of the current ordered common event.
*/
bool SetData(const std::string &data);
/**
* Obtain the result data of the current ordered common event.
*
* @return the result data of the current ordered common event
*/
std::string GetData() const;
/**
* Set the result of the current ordered common event.
*
* @param code the result code of the current ordered common event.
* @param data the result data of the current ordered common event.
*/
bool SetCodeAndData(const int &code, const std::string &data);
/**
* Cancel the current ordered common event.
*/
bool AbortCommonEvent();
/**
* Clear the abort state of the current ordered common event.
*/
bool ClearAbortCommonEvent();
/**
* Check whether the current ordered common event should be aborted.
*/
bool GetAbortCommonEvent() const;
/**
* Finishe processing the current ordered common event.
*/
bool FinishCommonEvent();
/**
* Check whether the current common event is an ordered common event.
*/
bool IsOrderedCommonEvent() const;
/**
* Check whether the current common event is a sticky common event.
*/
bool IsStickyCommonEvent() const;
/**
* Check whether the current common event is ordered.
*/
bool CheckSynchronous() const;
private:
int resultCode_;
std::string resultData_;
bool ordered_;
bool sticky_;
sptr<IRemoteObject> token_;
bool abortEvent_;
bool finished_;
};
} // namespace EventFwk
} // namespace OHOS
#endif // FOUNDATION_EVENT_CESFWK_KITS_NATIVE_INCLUDE_ASYNC_COMMON_EVENT_RESULT_H
@@ -0,0 +1,130 @@
/*
* 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_EVENT_CESFWK_KITS_NATIVE_INCLUDE_COMMON_EVENT_DATA_H
#define FOUNDATION_EVENT_CESFWK_KITS_NATIVE_INCLUDE_COMMON_EVENT_DATA_H
#include <string>
#include "parcel.h"
#include "want.h"
namespace OHOS {
namespace EventFwk {
using Want = OHOS::AAFwk::Want;
class CommonEventData : public Parcelable {
public:
/**
* Default constructor used to create an empty CommonEventData instance.
*/
CommonEventData();
/**
* Create a CommonEventData instance based on the want parameter to set
* the content of a common want.
*
* @param want the want of a common event
*/
explicit CommonEventData(const Want &want);
/**
* Create a CommonEventData instance based on the parameters want, code,
* and data to set the content of the common event.
*
* @param want the want of a common event
* @param code the code of a common event
* @param data the data of a common event
*/
CommonEventData(const Want &want, const int &code, const std::string &data);
/**
* Default deconstructor used to deconstruct.
*
*/
~CommonEventData();
/**
* Set the want attribute of a common event.
*
* @param want the want of a common event
*/
void SetWant(const Want &want);
/**
* Obtain the Want attribute of a common event.
*
* @return the want of a common event
*/
const Want &GetWant() const;
/**
* Set the result code of the common event.
*
* @param code the code of a common event
*/
void SetCode(const int &code);
/**
* Obtain the result code of a common event.
*
* @return the code of a common event
*/
int GetCode() const;
/**
* Set the result data of a common event.
*
* @param data the data of a common event
*/
void SetData(const std::string &data);
/**
* Obtain the result data of a common event, which is set by
* setData(java.lang.String).
*
* @return the data of a common event
*/
std::string GetData() const;
/**
* Marshal a common event data object into a Parcel.
*
* @param parcel the common event data into the parcel
*/
virtual bool Marshalling(Parcel &parcel) const override;
/**
* Unmarshal this common event data object from a Parcel.
* @return the common event data
*/
static CommonEventData *Unmarshalling(Parcel &parcel);
private:
/**
* Read a CommonEventData object from a Parcel.
*
* @param parcel the parcel
*/
bool ReadFromParcel(Parcel &parcel);
private:
Want want_;
int code_;
std::string data_;
};
} // namespace EventFwk
} // namespace OHOS
#endif // FOUNDATION_EVENT_CESFWK_KITS_NATIVE_INCLUDE_COMMON_EVENT_DATA_H
@@ -0,0 +1,77 @@
/*
* 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_EVENT_CESFWK_KITS_NATIVE_INCLUDE_COMMON_EVENT_MANAGER_H
#define FOUNDATION_EVENT_CESFWK_KITS_NATIVE_INCLUDE_COMMON_EVENT_MANAGER_H
#include "common_event_data.h"
#include "common_event_publish_info.h"
#include "common_event_subscriber.h"
namespace OHOS {
namespace EventFwk {
class CommonEventManager {
public:
/**
* Publish a standard common event.
*
* @param data the common event data
*/
static bool PublishCommonEvent(const CommonEventData &data);
/**
* Publish an ordered, sticky, or standard common event.
*
* @param data the common event data
* @param publishInfo the publish info
*/
static bool PublishCommonEvent(const CommonEventData &data, const CommonEventPublishInfo &publishInfo);
/**
* Publish an ordered, sticky, or standard common event.
*
* @param data the common event data
* @param publishInfo the publish info
* @param subscriber the common event subscriber
*/
static bool PublishCommonEvent(const CommonEventData &data, const CommonEventPublishInfo &publishInfo,
const std::shared_ptr<CommonEventSubscriber> &subscriber);
/**
* Subscribe to common events.
*
* @param subscriber the common event subscriber
*/
static bool SubscribeCommonEvent(const std::shared_ptr<CommonEventSubscriber> &subscriber);
/**
* Unsubscribe from common events.
*
* @param subscriber the common event subscriber
*/
static bool UnSubscribeCommonEvent(const std::shared_ptr<CommonEventSubscriber> &subscriber);
/**
* Gets the current sticky common event
*
* @param event the common event
* @param commonEventData the common event data
*/
static bool GetStickyCommonEvent(const std::string &event, CommonEventData &commonEventData);
};
} // namespace EventFwk
} // namespace OHOS
#endif // FOUNDATION_EVENT_CESFWK_KITS_NATIVE_INCLUDE_COMMON_EVENT_MANAGER_H
@@ -0,0 +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.
*/
#ifndef FOUNDATION_EVENT_CESFWK_KITS_NATIVE_INCLUDE_PUBLISH_INFO_H
#define FOUNDATION_EVENT_CESFWK_KITS_NATIVE_INCLUDE_PUBLISH_INFO_H
#include <string>
#include "parcel.h"
namespace OHOS {
namespace EventFwk {
class CommonEventPublishInfo : public Parcelable {
public:
/**
* Default constructor used to create an empty CommonEventPublishInfo instance.
*/
CommonEventPublishInfo();
/**
* A constructor used to create a CommonEventPublishInfo instance by copying
* parameters from an existing one.
*
*/
explicit CommonEventPublishInfo(const CommonEventPublishInfo &commonEventPublishInfo);
/**
* Default deconstructor used to deconstruct.
*/
~CommonEventPublishInfo();
/**
* Set whether the type of a common event is sticky or not.
*
* @param sticky the type of a common event is sticky or not
*/
void SetSticky(bool sticky);
/**
* Obtain whether it is a sticky common event, which can be set
* by SetSticky(bool).
*
* @return the common event is sticky or not.
*/
bool IsSticky() const;
/**
* Set permissions for subscribers.
*
* @param subscriberPermissions the permissions for subscribers
*/
void SetSubscriberPermissions(const std::vector<std::string> &subscriberPermissions);
/**
*
* Obtain subscriber permissions to a common event, which can be set by
* setSubscriberPermissions(const std::vector<std::string>&).
*
* @return the permissions for subscribers
*/
const std::vector<std::string> &GetSubscriberPermissions() const;
/**
* Set whether the type of a common event is ordered or not.
*
* @param ordered the type of a common event is ordered or not
*/
void SetOrdered(bool ordered);
/**
*
* Obtain whether it is an ordered common event, which can be set by setOrdered(boolean).
* set by SetOrdered(bool).
*
* @return the type of a common event is ordered or not
*/
bool IsOrdered() const;
/**
* Marshal a CommonEventData object into a Parcel.
*
* @param parcel the common event data into the parcel
*/
virtual bool Marshalling(Parcel &parcel) const override;
/**
* UnMarshal a Parcel object into a CommonEventData.
*
* @return the common event data
*/
static CommonEventPublishInfo *Unmarshalling(Parcel &parcel);
private:
/**
* Read a CommonEventData object from a Parcel.
*
* @param parcel the parcel
*/
bool ReadFromParcel(Parcel &parcel);
private:
bool sticky_;
bool ordered_;
std::vector<std::string> subscriberPermissions_;
};
} // namespace EventFwk
} // namespace OHOS
#endif // FOUNDATION_EVENT_CESFWK_KITS_NATIVE_INCLUDE_PUBLISH_INFO_H
@@ -0,0 +1,159 @@
/*
* 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_EVENT_CESFWK_KITS_NATIVE_INCLUDE_COMMON_EVENT_SUBSCRIBE_INFO_H
#define FOUNDATION_EVENT_CESFWK_KITS_NATIVE_INCLUDE_COMMON_EVENT_SUBSCRIBE_INFO_H
#include "matching_skills.h"
namespace OHOS {
namespace EventFwk {
class CommonEventSubscribeInfo : public Parcelable {
public:
enum ThreadMode {
HANDLER, // the main thread of this ability.
POST, // the event dispatch thread.
ASYNC, // an asynchronous thread.
BACKGROUND, // the background thread.
};
/**
* A constructor used to create a CommonEventSubscribeInfo instance
* with the matchingSkills parameters passed.
*
* @param matchingSkills the matching skills
*/
explicit CommonEventSubscribeInfo(const MatchingSkills &matchingSkills);
/**
* A constructor used to create a CommonEventSubscribeInfo instance
*
*/
CommonEventSubscribeInfo();
/**
* A constructor used to create a CommonEventSubscribeInfo instance by
* copying parameters from an existing one.
*
* @param commonEventSubscribeInfo the commonEventSubscribeInfo
*/
explicit CommonEventSubscribeInfo(const CommonEventSubscribeInfo &commonEventSubscribeInfo);
/**
* A deconstructor used to deconstruct
*
*/
~CommonEventSubscribeInfo();
/**
* Set the subscriber priority for this CommonEventSubscribeInfo object.
*
* @param priority the subscriber priority
*/
void SetPriority(const int32_t &priority);
/**
* Obtain the subscriber priority of this CommonEventSubscribeInfo object.
*
* @return the subscriber priority
*/
int32_t GetPriority() const;
/**
* Set the permission that the publisher must have in order to send
* a common event to this subscriber.
*
* @param permission the subscriber permission
*/
void SetPermission(const std::string &permission);
/**
* Obtain the publisher permission of this CommonEventSubscribeInfo object.
*
* @return the subscriber permission
*/
std::string GetPermission() const;
/**
* Obtain the thread mode of this CommonEventSubscribeInfo object.
*
* @return the thread mode
*/
CommonEventSubscribeInfo::ThreadMode GetThreadMode() const;
/**
* Set the thread mode of this CommonEventSubscribeInfo object.
*
* @param threadMode the thread mode to be set, which is specified in ThreadMode. Currently, only the HANDLER mode
* is supported.
*/
void SetThreadMode(CommonEventSubscribeInfo::ThreadMode threadMode);
/**
* Set the device ID for this CommonEventSubscribeInfo object.
* Your application will only receive common events sent from the specified device.
*
* @param deviceId Indicates the device ID. The value must be an existing device ID on the same ohos network.
* Otherwise, it is invalid.
*/
void SetDeviceId(const std::string &deviceId);
/**
* Obtain the device ID in this CommonEventSubscribeInfo object.
*
* @return the device ID.
*/
std::string GetDeviceId() const;
/**
* Obtain the MatchingSkills object carried in this CommonEventSubscribeInfo object.
*
* @return the matchingSkills
*/
const MatchingSkills &GetMatchingSkills() const;
/**
* Marshal a subscriber info object into a Parcel.
*
* @param parcel the common event data into the parcel
*/
virtual bool Marshalling(Parcel &parcel) const override;
/**
* Unmarshal a Parcel object into a subscriber info.
*
* @return subscriber info.
*/
static CommonEventSubscribeInfo *Unmarshalling(Parcel &parcel);
private:
/**
* Read a subscriber object from a Parcel.
*
* @param parcel the parcel
*/
bool ReadFromParcel(Parcel &parcel);
private:
MatchingSkills matchingSkills_;
int32_t priority_;
std::string permission_;
std::string deviceId_;
CommonEventSubscribeInfo::ThreadMode threadMode_;
};
} // namespace EventFwk
} // namespace OHOS
#endif // FOUNDATION_EVENT_CESFWK_KITS_NATIVE_INCLUDE_COMMON_EVENT_SUBSCRIBE_INFO_H
@@ -0,0 +1,152 @@
/*
* 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_EVENT_CESFWK_KITS_NATIVE_INCLUDE_COMMON_EVENT_SUBSCRIBER_H
#define FOUNDATION_EVENT_CESFWK_KITS_NATIVE_INCLUDE_COMMON_EVENT_SUBSCRIBER_H
#include "async_common_event_result.h"
#include "common_event_data.h"
#include "common_event_subscribe_info.h"
namespace OHOS {
namespace EventFwk {
class CommonEventSubscriber {
public:
/**
* A constructor used to create a CommonEventSubscriber instance
*
*/
CommonEventSubscriber();
/**
* A constructor used to create a CommonEventSubscriber instance with the
* subscribeInfo parameter passed.
*
* @param subscriberInfo the subscriberInfo
*/
explicit CommonEventSubscriber(const CommonEventSubscribeInfo &subscribeInfo);
/**
* A deconstructor used to deconstruct
*
*/
virtual ~CommonEventSubscriber();
/**
* Call back when the application receives a new common event.
*
* @param data the common event data
*/
virtual void OnReceiveEvent(const CommonEventData &data) = 0;
/**
* Get common event subscriber info
*
* @return common event subscriber info
*/
const CommonEventSubscribeInfo &GetSubscribeInfo() const;
/**
* Set the result code of the current ordered common event.
*
* @param code the result code of the current ordered common event
*/
bool SetCode(const int &code);
/**
* Obtain the result code of the current ordered common event.
*
* @return the result code of the current ordered common event
*/
int GetCode() const;
/**
* Set the result data of the current ordered common event.
*
* @param data the result data of the current ordered common event.
*/
bool SetData(const std::string &data);
/**
* Obtain the result data of the current ordered common event.
*
* @return the result data of the current ordered common event
*/
std::string GetData() const;
/**
* Set the result of the current ordered common event.
*
* @param code the result code of the current ordered common event.
* @param data the result data of the current ordered common event.
*/
bool SetCodeAndData(const int &code, const std::string &data);
/**
* Cancel the current ordered common event.
*/
bool AbortCommonEvent();
/**
* Clear the abort state of the current ordered common event.
*/
bool ClearAbortCommonEvent();
/**
* Check whether the current ordered common event should be aborted.
*/
bool GetAbortCommonEvent() const;
/**
* Enable asynchronous processing for the current ordered common event.
*/
std::shared_ptr<AsyncCommonEventResult> GoAsyncCommonEvent();
/**
* Check whether the current common event is an ordered common event.
*/
bool IsOrderedCommonEvent() const;
/**
* Check whether the current common event is a sticky common event.
*/
bool IsStickyCommonEvent() const;
private:
/**
* Set AsyncCommonEventResult for init before perform onReceiveEvent.
*/
bool SetAsyncCommonEventResult(const std::shared_ptr<AsyncCommonEventResult> &result);
/**
* Get AsyncCommonEventResult for check after perform onReceiveEvent.
*/
std::shared_ptr<AsyncCommonEventResult> GetAsyncCommonEventResult();
/**
* Check whether the current common event is ordered.
*/
bool CheckSynchronous() const;
private:
friend class CommonEventListener;
CommonEventSubscribeInfo subscribeInfo_;
std::shared_ptr<AsyncCommonEventResult> result_;
};
} // namespace EventFwk
} // namespace OHOS
#endif // FOUNDATION_EVENT_CESFWK_KITS_NATIVE_INCLUDE_COMMON_EVENT_SUBSCRIBER_H
@@ -0,0 +1,954 @@
/*
* 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_EVENT_CESFWK_KITS_NATIVE_INCLUDE_COMMON_EVENT_SUPPORT_H
#define FOUNDATION_EVENT_CESFWK_KITS_NATIVE_INCLUDE_COMMON_EVENT_SUPPORT_H
#include <string>
#include <vector>
namespace OHOS {
namespace EventFwk {
class CommonEventSupport {
public:
/**
* Indicate the action of a common event that the user has finished booting and the system has been loaded.
* To subscribe to this common event, your application must have the ohos.permission.RECEIVER_STARTUP_COMPLETED
* permission.
* This common event can only be published by the system.
*/
static const std::string COMMON_EVENT_BOOT_COMPLETED;
/**
* Indicate the action of a common event that the user has finished booting and the system has been loaded but the
* screen is still locked.
* To subscribe to this common event, your application must have the ohos.permission.RECEIVER_STARTUP_COMPLETED
* permission.
* This common event can only be published by the system.
*/
static const std::string COMMON_EVENT_LOCKED_BOOT_COMPLETED;
/**
* Indicate the action of a common event that the device is being shut down and the final shutdown will proceed.
* This is different from sleeping. All unsaved data will be lost after shut down.
* This common event can only be published by the system.
*/
static const std::string COMMON_EVENT_SHUTDOWN;
/**
* Indicate the action of a common event that the charging state, level, and other information about the battery
* have changed.
* This common event can only be published by the system.
*/
static const std::string COMMON_EVENT_BATTERY_CHANGED;
/**
* Indicate the action of a common event that the battery level is low.
* This common event can only be published by the system.
*/
static const std::string COMMON_EVENT_BATTERY_LOW;
/**
* Indicate the action of a common event that the battery exit the low state.
* This common event can only be published by the system.
*/
static const std::string COMMON_EVENT_BATTERY_OKAY;
/**
* Indicate the action of a common event that the device is connected to the external power.
* This common event can only be published by the system.
*/
static const std::string COMMON_EVENT_POWER_CONNECTED;
/**
* Indicate the action of a common event that the device is disconnected from the external power.
* This common event can only be published by the system.
*/
static const std::string COMMON_EVENT_POWER_DISCONNECTED;
/**
* Indicate the action of a common event that the device screen is off and the device is sleeping.
* This common event can only be published by the system.
*/
static const std::string COMMON_EVENT_SCREEN_OFF;
/**
* Indicate the action of a common event that the device screen is on and the device is interactive.
* This common event can only be published by the system.
*/
static const std::string COMMON_EVENT_SCREEN_ON;
/**
* Indicate the action of a common event that the user unlocks the device.
* This common event can only be published by the system.
*/
static const std::string COMMON_EVENT_USER_PRESENT;
/**
* Indicate the action of a common event that the system time has changed.
* This common event can only be published by the system.
*/
static const std::string COMMON_EVENT_TIME_TICK;
/**
* Indicate the action of a common event that the system time is set.
* This common event can only be published by the system.
*/
static const std::string COMMON_EVENT_TIME_CHANGED;
/**
* Indicate the action of a common event that the system date has changed.
* This common event can only be published by the system.
*/
static const std::string COMMON_EVENT_DATE_CHANGED;
/**
* Indicate the action of a common event that the system time zone has changed.
* This common event can only be published by the system.
*/
static const std::string COMMON_EVENT_TIMEZONE_CHANGED;
/**
* Indicate the action of a common event that a user closes a temporary system dialog box.
* This common event can only be published by the system.
*/
static const std::string COMMON_EVENT_CLOSE_SYSTEM_DIALOGS;
/**
* Indicate the action of a common event that a new application package has been installed on the device.
* This common event can only be published by the system.
*/
static const std::string COMMON_EVENT_PACKAGE_ADDED;
/**
* Indicate the action of a common event that a new version of an installed application package has replaced
* the previous one on the device.
* This common event can only be published by the system.
*/
static const std::string COMMON_EVENT_PACKAGE_REPLACED;
/**
* Indicate the action of a common event that a new version of your application package has replaced
* the previous one. This common event is sent only to the application that was replaced.
* This common event can only be published by the system.
*/
static const std::string COMMON_EVENT_MY_PACKAGE_REPLACED;
/**
* Indicate the action of a common event that an installed application has been uninstalled from the device
* with the application data remained.
* This common event can only be published by the system.
*/
static const std::string COMMON_EVENT_PACKAGE_REMOVED;
/**
* Indicate the action of a common event that an installed application, including both the application data and
* code, have been completely uninstalled from the device.
* This common event can only be published by the system.
*/
static const std::string COMMON_EVENT_PACKAGE_FULLY_REMOVED;
/**
* Indicate the action of a common event that an application package has been changed
* (for example, a component in the package has been enabled or disabled).
* This common event can only be published by the system.
*/
static const std::string COMMON_EVENT_PACKAGE_CHANGED;
/**
* Indicate the action of a common event that the user has restarted the application package and killed all its
* processes.
* This common event can only be published by the system.
*/
static const std::string COMMON_EVENT_PACKAGE_RESTARTED;
/**
* Indicate the action of a common event that the user has cleared the application package data.
* This common event is published after COMMON_EVENT_PACKAGE_RESTARTED is triggered and the data has been cleared.
* This common event can only be published by the system.
*/
static const std::string COMMON_EVENT_PACKAGE_DATA_CLEARED;
/**
* Indicate the action of a common event that application packages have been suspended.
* This common event can only be published by the system.
*/
static const std::string COMMON_EVENT_PACKAGES_SUSPENDED;
/**
* Indicate the action of a common event that application packages have not been suspended.
* This common event can only be published by the system.
*/
static const std::string COMMON_EVENT_PACKAGES_UNSUSPENDED;
/**
* Indicate the action of a common event that an application package has been suspended.
* This common event can only be published by the system.
*/
static const std::string COMMON_EVENT_MY_PACKAGE_SUSPENDED;
/**
* Indicate the action of a common event that an application package has not been suspended.
* This common event can only be published by the system.
*/
static const std::string COMMON_EVENT_MY_PACKAGE_UNSUSPENDED;
/**
* Indicate the action of a common event that a user ID has been removed from the system.
* This common event can only be published by the system.
*/
static const std::string COMMON_EVENT_UID_REMOVED;
/**
* Indicate the action of a common event that an installed application is started for the first time.
* This common event can only be published by the system.
*/
static const std::string COMMON_EVENT_PACKAGE_FIRST_LAUNCH;
/**
* Indicate the action of a common event that an application requires system verification.
* This common event can only be published by the system.
*/
static const std::string COMMON_EVENT_PACKAGE_NEEDS_VERIFICATION;
/**
* Indicate the action of a common event that an application has been verified by the system.
* This common event can only be published by the system.
*/
static const std::string COMMON_EVENT_PACKAGE_VERIFIED;
/**
* Indicate the action of a common event that applications installed on the external storage become
* available for the system.
* This common event can only be published by the system.
*/
static const std::string COMMON_EVENT_EXTERNAL_APPLICATIONS_AVAILABLE;
/**
* Indicate the action of a common event that applications installed on the external storage become unavailable for
* the system.
* This common event can only be published by the system.
*/
static const std::string COMMON_EVENT_EXTERNAL_APPLICATIONS_UNAVAILABLE;
/**
* Indicates the action of a common event that the device state (for example, orientation and locale) has changed.
* This common event can only be published by the system.
*/
static const std::string COMMON_EVENT_CONFIGURATION_CHANGED;
/**
* Indicate the action of a common event that the device locale has changed.
* This common event can only be published by the system.
*/
static const std::string COMMON_EVENT_LOCALE_CHANGED;
/**
* Indicate the action of a common event that the device storage is insufficient.
*/
static const std::string COMMON_EVENT_MANAGE_PACKAGE_STORAGE;
/**
* Indicate the action of a common event that the system is in driving mode.
* This is a protected common event, which can be sent only by the system.
*/
static const std::string COMMON_EVENT_DRIVE_MODE;
/**
* Indicate the action of a common event that the system is in home mode.
* This is a protected common event, which can be sent only by the system.
*/
static const std::string COMMON_EVENT_HOME_MODE;
/**
* Indicate the action of a common event that the system is in office mode.
* This is a protected common event, which can be sent only by the system.
*/
static const std::string COMMON_EVENT_OFFICE_MODE;
/**
* Indicate the action of a common event that the user has been started.
*/
static const std::string COMMON_EVENT_USER_STARTED;
/**
* Indicate the action of a common event that the user has been brought to the background.
*/
static const std::string COMMON_EVENT_USER_BACKGROUND;
/**
* Indicate the action of a common event that the user has been brought to the foreground.
*/
static const std::string COMMON_EVENT_USER_FOREGROUND;
/**
* Indicate the action of a common event that a user switch is happening.
* To subscribe to this common event, your application must have the ohos.permission.MANAGE_USERS permission.
*/
static const std::string COMMON_EVENT_USER_SWITCHED;
/**
* Indicate the action of a common event that the user is going to be started.
* To subscribe to this common event, your application must have the ohos.permission.INTERACT_ACROSS_USERS
* permission.
*/
static const std::string COMMON_EVENT_USER_STARTING;
/**
* Indicate the action of a common event that the credential-encrypted storage has become unlocked
* for the current user when the device is unlocked after being restarted.
*/
static const std::string COMMON_EVENT_USER_UNLOCKED;
/**
* Indicate the action of a common event that the user is going to be stopped.
* To subscribe to this common event, your application must have the ohos.permission.INTERACT_ACROSS_USERS
* permission.
*/
static const std::string COMMON_EVENT_USER_STOPPING;
/**
* Indicate the action of a common event that the user has been stopped.
*/
static const std::string COMMON_EVENT_USER_STOPPED;
/**
* Indicate the action of a common event about a login of a user with account ID.
* This is a protected common event, which can be sent only by the system.
*/
static const std::string COMMON_EVENT_HWID_LOGIN;
/**
* Indicate the action of a common event about a logout of a user with account ID.
* This is a protected common event, which can be sent only by the system.
*/
static const std::string COMMON_EVENT_HWID_LOGOUT;
/**
* Indicate the action of a common event that the account ID is invalid.
* This is a protected common event, which can be sent only by the system.
*/
static const std::string COMMON_EVENT_HWID_TOKEN_INVALID;
/**
* Indicate the action of a common event about a logoff of a account ID.
* This is a protected common event, which can be sent only by the system.
*/
static const std::string COMMON_EVENT_HWID_LOGOFF;
/**
* Indicate the action of a common event about the Wi-Fi state, such as enabled and disabled.
*/
static const std::string COMMON_EVENT_WIFI_POWER_STATE;
/**
* Indicate the action of a common event that the Wi-Fi access point has been scanned and proven to be available.
* To subscribe to this common event, your application must have the ohos.permission.LOCATION permission.
*/
static const std::string COMMON_EVENT_WIFI_SCAN_FINISHED;
/**
* Indicate the action of a common event that the Wi-Fi signal strength (RSSI) has changed.
* To subscribe to this common event, your application must have the ohos.permission.GET_WIFI_INFO permission.
*/
static const std::string COMMON_EVENT_WIFI_RSSI_VALUE;
/**
* Indicate the action of a common event that the Wi-Fi connection state has changed.
*/
static const std::string COMMON_EVENT_WIFI_CONN_STATE;
/**
* Indicate the action of a common event about the Wi-Fi hotspot state, such as enabled or disabled.
*/
static const std::string COMMON_EVENT_WIFI_HOTSPOT_STATE;
/**
* Indicates the action of a common event that a client has joined the Wi-Fi hotspot of the current device. You can
* register this common event to listen for information about the clients joining your hotspot.
* To subscribe to this common event, your application must have the ohos.permission.GET_WIFI_INFO permission.
*/
static const std::string COMMON_EVENT_WIFI_AP_STA_JOIN;
/**
* Indicates the action of a common event that a client has dropped connection to the Wi-Fi hotspot of the current
* device. You can register this common event to listen for information about the clients leaving your hotspot.
* To subscribe to this common event, your application must have the ohos.permission.GET_WIFI_INFO permission.
*/
static const std::string COMMON_EVENT_WIFI_AP_STA_LEAVE;
/**
* Indicate the action of a common event that the state of MPLink (an enhanced Wi-Fi feature) has changed.
* To subscribe to this common event, your application must have the ohos.permission.MPLINK_CHANGE_STATE permission.
*/
static const std::string COMMON_EVENT_WIFI_MPLINK_STATE_CHANGE;
/**
* Indicate the action of a common event that the Wi-Fi P2P connection state has changed.
* To subscribe to this common event, your application must have the ohos.permission.GET_WIFI_INFO and
* ohos.permission.LOCATION permissions.
*/
static const std::string COMMON_EVENT_WIFI_P2P_CONN_STATE;
/**
* Indicate the action of a common event about the Wi-Fi P2P state, such as enabled and disabled.
* To subscribe to this common event, your application must have the ohos.permission.GET_WIFI_INFO permission.
*/
static const std::string COMMON_EVENT_WIFI_P2P_STATE_CHANGED;
/**
* Indicate that the Wi-Fi P2P peers state change.
* To subscribe to this common event, your application must have the ohos.permission.GET_WIFI_INFO permission.
*/
static const std::string COMMON_EVENT_WIFI_P2P_PEERS_STATE_CHANGED;
/**
* Indicate that the Wi-Fi P2P discovery state change.
* To subscribe to this common event, your application must have the ohos.permission.GET_WIFI_INFO permission.
*/
static const std::string COMMON_EVENT_WIFI_P2P_PEERS_DISCOVERY_STATE_CHANGED;
/**
* Indicate that the Wi-Fi P2P current device state change.
* To subscribe to this common event, your application must have the ohos.permission.GET_WIFI_INFO permission.
*/
static const std::string COMMON_EVENT_WIFI_P2P_CURRENT_DEVICE_STATE_CHANGED;
/**
* Indicate that the Wi-Fi P2P group info is changed.
* To subscribe to this common event, your application must have the ohos.permission.GET_WIFI_INFO permission.
*/
static const std::string COMMON_EVENT_WIFI_P2P_GROUP_STATE_CHANGED;
/**
* Indicate the action of a common event about the connection state of Bluetooth handsfree communication.
* To subscribe to this common event, your application must have the ohos.permission.USE_BLUETOOTH permission.
*/
static const std::string COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_CONNECT_STATE_UPDATE;
/**
* Indicate the action of a common event that the device connected to the Bluetooth handsfree is active.
* To subscribe to this common event, your application must have the ohos.permission.USE_BLUETOOTH permission.
*/
static const std::string COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_CURRENT_DEVICE_UPDATE;
/**
* Indicate the action of a common event that the connection state of Bluetooth A2DP has changed.
* To subscribe to this common event, your application must have the ohos.permission.USE_BLUETOOTH permission.
*/
static const std::string COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_AUDIO_STATE_UPDATE;
/**
* Indicate the action of a common event about the connection state of Bluetooth A2DP.
* To subscribe to this common event, your application must have the ohos.permission.USE_BLUETOOTH permission.
*/
static const std::string COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CONNECT_STATE_UPDATE;
/**
* Indicate the action of a common event that the device connected using Bluetooth A2DP is active.
* To subscribe to this common event, your application must have the ohos.permission.USE_BLUETOOTH permission.
*/
static const std::string COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CURRENT_DEVICE_UPDATE;
/**
* Indicate the action of a common event that the playing state of Bluetooth A2DP has changed.
* To subscribe to this common event, your application must have the ohos.permission.USE_BLUETOOTH permission.
*/
static const std::string COMMON_EVENT_BLUETOOTH_A2DPSOURCE_PLAYING_STATE_UPDATE;
/**
* Indicate the action of a common event that the AVRCP connection state of Bluetooth A2DP has changed.
*/
static const std::string COMMON_EVENT_BLUETOOTH_A2DPSOURCE_AVRCP_CONNECT_STATE_UPDATE;
/**
* Indicate the action of a common event that the audio codec state of Bluetooth A2DP has changed.
* To subscribe to this common event, your application must have the ohos.permission.USE_BLUETOOTH permission.
*/
static const std::string COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CODEC_VALUE_UPDATE;
/**
* Indicate the action of a common event that a remote Bluetooth device has been discovered.
* To subscribe to this common event, your application must have the ohos.permission.USE_BLUETOOTH and
* ohos.permission.LOCATION permissions.
*/
static const std::string COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_DISCOVERED;
/**
* Indicate the action of a common event that the Bluetooth class of a remote Bluetooth device has changed.
* To subscribe to this common event, your application must have the ohos.permission.USE_BLUETOOTH permission.
*/
static const std::string COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CLASS_VALUE_UPDATE;
/**
* Indicate the action of a common event that a low level (ACL) connection has been established with a remote
* Bluetooth device.
* To subscribe to this common event, your application must have the ohos.permission.USE_BLUETOOTH permission.
*/
static const std::string COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_ACL_CONNECTED;
/**
* Indicate the action of a common event that a low level (ACL) connection has been disconnected from a remote
* Bluetooth device.
* To subscribe to this common event, your application must have the ohos.permission.USE_BLUETOOTH permission.
*/
static const std::string COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_ACL_DISCONNECTED;
/**
* Indicate the action of a common event that the friendly name of a remote Bluetooth device has been retrieved for
* the first time or has been changed since the last retrieval.
* To subscribe to this common event, your application must have the ohos.permission.USE_BLUETOOTH permission.
*/
static const std::string COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_NAME_UPDATE;
/**
* Indicate the action of a common event that the connection state of a remote Bluetooth device has changed.
* To subscribe to this common event, your application must have the ohos.permission.USE_BLUETOOTH permission.
*/
static const std::string COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIR_STATE;
/**
* Indicate the action of a common event that the battery level of a remote Bluetooth device has been retrieved
* for the first time or has been changed since the last retrieval.
* To subscribe to this common event, your application must have the ohos.permission.USE_BLUETOOTH permission.
*/
static const std::string COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_BATTERY_VALUE_UPDATE;
/**
* Indicate the action of a common event about the SDP state of a remote Bluetooth device.
*/
static const std::string COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_SDP_RESULT;
/**
* Indicate the action of a common event about the UUID connection state of a remote Bluetooth device.
* To subscribe to this common event, your application must have the ohos.permission.DISCOVER_BLUETOOTH permission.
*/
static const std::string COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_UUID_VALUE;
/**
* Indicate the action of a common event about the pairing request from a remote Bluetooth device.
* To subscribe to this common event, your application must have the ohos.permission.DISCOVER_BLUETOOTH permission.
*/
static const std::string COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIRING_REQ;
/**
* Indicate the action of a common event that Bluetooth pairing is canceled.
*/
static const std::string COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIRING_CANCEL;
/**
* Indicate the action of a common event about the connection request from a remote Bluetooth device.
*/
static const std::string COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_REQ;
/**
* Indicate the action of a common event about the response to the connection request from a remote Bluetooth
* device.
*/
static const std::string COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_REPLY;
/**
* Indicate the action of a common event that the connection to a remote Bluetooth device has been canceled.
*/
static const std::string COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_CANCEL;
/**
* Indicate the action of a common event that the connection state of a Bluetooth handsfree has changed.
*/
static const std::string COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_CONNECT_STATE_UPDATE;
/**
* Indicate the action of a common event that the audio state of a Bluetooth handsfree has changed.
*/
static const std::string COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AUDIO_STATE_UPDATE;
/**
* Indicate the action of a common event that the audio gateway state of a Bluetooth handsfree has changed.
*/
static const std::string COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AG_COMMON_EVENT;
/**
* Indicate the action of a common event that the calling state of a Bluetooth handsfree has changed.
*/
static const std::string COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AG_CALL_STATE_UPDATE;
/**
* Indicate the action of a common event that the state of a Bluetooth adapter has been changed, for example,
* Bluetooth has been turned on or off.
* To subscribe to this common event, your application must have the ohos.permission.USE_BLUETOOTH permission.
*/
static const std::string COMMON_EVENT_BLUETOOTH_HOST_STATE_UPDATE;
/**
* Indicate the action of a common event about the requests for the user to allow Bluetooth to be scanned.
*/
static const std::string COMMON_EVENT_BLUETOOTH_HOST_REQ_DISCOVERABLE;
/**
* Indicate the action of a common event about the requests for the user to turn on Bluetooth.
* To subscribe to this common event, your application must have the ohos.permission.USE_BLUETOOTH permission.
*/
static const std::string COMMON_EVENT_BLUETOOTH_HOST_REQ_ENABLE;
/**
* Indicate the action of a common event about the requests for the user to turn off Bluetooth.
* To subscribe to this common event, your application must have the ohos.permission.USE_BLUETOOTH permission.
*/
static const std::string COMMON_EVENT_BLUETOOTH_HOST_REQ_DISABLE;
/**
* Indicate the action of a common event that the Bluetooth scanning mode of a device has changed.
* To subscribe to this common event, your application must have the ohos.permission.USE_BLUETOOTH permission.
*/
static const std::string COMMON_EVENT_BLUETOOTH_HOST_SCAN_MODE_UPDATE;
/**
* Indicate the action of a common event that the Bluetooth scanning has been started on the device.
* To subscribe to this common event, your application must have the ohos.permission.USE_BLUETOOTH permission.
*/
static const std::string COMMON_EVENT_BLUETOOTH_HOST_DISCOVERY_STARTED;
/**
* Indicate the action of a common event that the Bluetooth scanning is finished on the device.
* To subscribe to this common event, your application must have the ohos.permission.USE_BLUETOOTH permission.
*/
static const std::string COMMON_EVENT_BLUETOOTH_HOST_DISCOVERY_FINISHED;
/**
* Indicate the action of a common event that the Bluetooth adapter name of the device has changed.
* To subscribe to this common event, your application must have the ohos.permission.USE_BLUETOOTH permission.
*/
static const std::string COMMON_EVENT_BLUETOOTH_HOST_NAME_UPDATE;
/**
* Indicate the action of a common event that the connection state of Bluetooth A2DP Sink has changed.
* To subscribe to this common event, your application must have the ohos.permission.USE_BLUETOOTH permission.
*/
static const std::string COMMON_EVENT_BLUETOOTH_A2DPSINK_CONNECT_STATE_UPDATE;
/**
* Indicate the action of a common event that the playing state of Bluetooth A2DP Sink has changed.
* To subscribe to this common event, your application must have the ohos.permission.USE_BLUETOOTH permission.
*/
static const std::string COMMON_EVENT_BLUETOOTH_A2DPSINK_PLAYING_STATE_UPDATE;
/**
* Indicate the action of a common event that the audio state of Bluetooth A2DP Sink has changed.
* To subscribe to this common event, your application must have the ohos.permission.USE_BLUETOOTH permission.
*/
static const std::string COMMON_EVENT_BLUETOOTH_A2DPSINK_AUDIO_STATE_UPDATE;
/**
* Indicate the action of a common event that the state of the device NFC adapter has changed.
* This is a protected common event, which can be sent only by the system.
*/
static const std::string COMMON_EVENT_NFC_ACTION_ADAPTER_STATE_CHANGED;
/**
* Indicate the action of a common event that the NFC RF field is detected to be in the enabled state.
* To subscribe to this common event, your application must have the ohos.permission.MANAGE_SECURE_SETTINGS
* permission.
* This is a protected common event, which can be sent only by the system.
*/
static const std::string COMMON_EVENT_NFC_ACTION_RF_FIELD_ON_DETECTED;
/**
* Indicate the action of a common event that the NFC RF field is detected to be in the disabled state.
* To subscribe to this common event, your application must have the ohos.permission.MANAGE_SECURE_SETTINGS
* permission.
* This is a protected common event, which can be sent only by the system.
*/
static const std::string COMMON_EVENT_NFC_ACTION_RF_FIELD_OFF_DETECTED;
/**
* Indicate the action of a common event that the system stops charging the battery.
* This is a protected common event, which can be sent only by the system.
*/
static const std::string COMMON_EVENT_DISCHARGING;
/**
* Indicate the action of a common event that the system starts charging the battery.
* This is a protected common event, which can be sent only by the system.
*/
static const std::string COMMON_EVENT_CHARGING;
/**
* Indicate the action of a common event that the system idle mode has changed.
* This is a protected common event, which can be sent only by the system.
*/
static const std::string COMMON_EVENT_DEVICE_IDLE_MODE_CHANGED;
/**
* Indicate the action of a common event that the power save mode of the system has changed.
* This is a protected common event, which can be sent only by the system.
*/
static const std::string COMMON_EVENT_POWER_SAVE_MODE_CHANGED;
/**
* Indicate the action of a common event that a user has been added to the system.
* To subscribe to this common event, your application must have the ohos.permission.MANAGE_USERS permission.
*/
static const std::string COMMON_EVENT_USER_ADDED;
/**
* Indicate the action of a common event that a user has been removed from the system.
* To subscribe to this common event, your application must have the ohos.permission.MANAGE_USERS permission.
*/
static const std::string COMMON_EVENT_USER_REMOVED;
/**
* Indicate the action of a common event that an ability has been added.
* To subscribe to this common event, your application must have the ohos.permission.LISTEN_BUNDLE_CHANGE
* permission.
* This is a protected common event, which can be sent only by the system.
*/
static const std::string COMMON_EVENT_ABILITY_ADDED;
/**
* Indicate the action of a common event that an ability has been removed.
* To subscribe to this common event, your application must have the ohos.permission.LISTEN_BUNDLE_CHANGE
* permission.
* This is a protected common event, which can be sent only by the system.
*/
static const std::string COMMON_EVENT_ABILITY_REMOVED;
/**
* Indicate the action of a common event that an ability has been updated.
* To subscribe to this common event, your application must have the ohos.permission.LISTEN_BUNDLE_CHANGE
* permission.
* This is a protected common event, which can be sent only by the system.
*/
static const std::string COMMON_EVENT_ABILITY_UPDATED;
/**
* Indicate the action of a common event that the location mode of the system has changed.
* This is a protected common event, which can be sent only by the system.
*/
static const std::string COMMON_EVENT_LOCATION_MODE_STATE_CHANGED;
/**
* Indicate the action of a common event that the in-vehicle infotainment (IVI) system of a vehicle is sleeping.
* This is a protected common event, which can be sent only by the system.
*/
static const std::string COMMON_EVENT_IVI_SLEEP;
/**
* The ivi is slept and notify the app stop playing.
* This is a protected common event that can only be sent by system.
*/
static const std::string COMMON_EVENT_IVI_PAUSE;
/**
* Indicate the action of a common event that a third-party application is instructed to pause the current work.
* This is a protected common event, which can be sent only by the system.
*/
static const std::string COMMON_EVENT_IVI_STANDBY;
/**
* Indicate the action of a common event that a third-party application is instructed to save its last mode.
* This is a protected common event, which can be sent only by the system.
*/
static const std::string COMMON_EVENT_IVI_LASTMODE_SAVE;
/**
* Indicate the action of a common event that the voltage of the vehicle power system is abnormal.
* This is a protected common event, which can be sent only by the system.
*/
static const std::string COMMON_EVENT_IVI_VOLTAGE_ABNORMAL;
/**
* The ivi temperature is too high.
* This is a protected common event that can only be sent by system.
* This common event will be delete later, please use COMMON_EVENT_IVI_TEMPERATURE_ABNORMAL.
*/
static const std::string COMMON_EVENT_IVI_HIGH_TEMPERATURE;
/**
* The ivi temperature is extreme high.
* This is a protected common event that can only be sent by system.
* This common event will be delete later, please use COMMON_EVENT_IVI_TEMPERATURE_ABNORMAL.
*/
static const std::string COMMON_EVENT_IVI_EXTREME_TEMPERATURE;
/**
* Indicate the action of a common event that the in-vehicle system has an extreme temperature.
* This is a protected common event, which can be sent only by the system.
*/
static const std::string COMMON_EVENT_IVI_TEMPERATURE_ABNORMAL;
/**
* Indicate the action of a common event that the voltage of the vehicle power system is restored to normal.
* This is a protected common event, which can be sent only by the system.
*/
static const std::string COMMON_EVENT_IVI_VOLTAGE_RECOVERY;
/**
* Indicate the action of a common event that the temperature of the in-vehicle system is restored to normal.
* This is a protected common event, which can be sent only by the system.
*/
static const std::string COMMON_EVENT_IVI_TEMPERATURE_RECOVERY;
/**
* Indicate the action of a common event that the battery service is active.
* This is a protected common event, which can be sent only by the system.
*/
static const std::string COMMON_EVENT_IVI_ACTIVE;
/**
* The usb state changed.
* This is a protected common event that can only be sent by system.
*/
static const std::string COMMON_EVENT_USB_STATE;
/**
* The usb port changed.
* This is a protected common event that can only be sent by system.
*/
static const std::string COMMON_EVENT_USB_PORT_CHANGED;
/**
* Indicate the action of a common event that a USB device has been attached when the user device functions as a USB
* host.
* This is a protected common event, which can be sent only by the system.
*/
static const std::string COMMON_EVENT_USB_DEVICE_ATTACHED;
/**
* Indicate the action of a common event that a USB device has been detached when the user device functions as a USB
* host.
* This is a protected common event, which can be sent only by the system.
*/
static const std::string COMMON_EVENT_USB_DEVICE_DETACHED;
/**
* Indicate the action of a common event that a USB accessory has been attached.
* This is a protected common event, which can be sent only by the system.
*/
static const std::string COMMON_EVENT_USB_ACCESSORY_ATTACHED;
/**
* Indicate the action of a common event that a USB accessory has been detached.
* This is a protected common event, which can be sent only by the system.
*/
static const std::string COMMON_EVENT_USB_ACCESSORY_DETACHED;
/**
* The storage space is low.
* This is a protected common event that can only be sent by system.
*/
static const std::string COMMON_EVENT_DEVICE_STORAGE_LOW;
/**
* The storage space is normal.
* This is a protected common event that can only be sent by system.
*/
static const std::string COMMON_EVENT_DEVICE_STORAGE_OK;
/**
* The storage space is full.
* This is a protected common event that can only be sent by system.
*/
static const std::string COMMON_EVENT_DEVICE_STORAGE_FULL;
/**
* The network connection was changed.
* This is a protected common event that can only be sent by system.
*/
static const std::string COMMON_EVENT_CONNECTIVITY_CHANGE;
/**
* Indicate the action of a common event that an external storage device was removed.
* To subscribe to this common event, your application must have the ohos.permission.WRITE_USER_STORAGE or
* ohos.permission.READ_USER_STORAGE permission.
* This common event can be published only by system applications.
*/
static const std::string COMMON_EVENT_DISK_REMOVED;
/**
* Indicate the action of a common event that an external storage device was unmounted.
* To subscribe to this common event, your application must have the ohos.permission.WRITE_USER_STORAGE or
* ohos.permission.READ_USER_STORAGE permission.
* This common event can be published only by system applications.
*/
static const std::string COMMON_EVENT_DISK_UNMOUNTED;
/**
* Indicate the action of a common event that an external storage device was mounted.
* To subscribe to this common event, your application must have the ohos.permission.WRITE_USER_STORAGE or
* ohos.permission.READ_USER_STORAGE permission.
* This common event can be published only by system applications.
*/
static const std::string COMMON_EVENT_DISK_MOUNTED;
/**
* Indicate the action of a common event that an external storage device was removed without being unmounted.
* To subscribe to this common event, your application must have the ohos.permission.WRITE_USER_STORAGE or
* ohos.permission.READ_USER_STORAGE permission.
* This common event can be published only by system applications.
*/
static const std::string COMMON_EVENT_DISK_BAD_REMOVAL;
/**
* Indicate the action of a common event that an external storage device becomes unmountable.
* To subscribe to this common event, your application must have the ohos.permission.WRITE_USER_STORAGE or
* ohos.permission.READ_USER_STORAGE permission.
* This common event can be published only by system applications.
*/
static const std::string COMMON_EVENT_DISK_UNMOUNTABLE;
/**
* Indicate the action of a common event that an external storage device was ejected.
* To subscribe to this common event, your application must have the ohos.permission.WRITE_USER_STORAGE or
* ohos.permission.READ_USER_STORAGE permission.
* This common event can be published only by system applications.
*/
static const std::string COMMON_EVENT_DISK_EJECT;
/**
* Indicate the action of a common event that the account visible changed.
* To subscribe to this common event, your application must have the ohos.permission.GET_APP_ACCOUNTS permission.
* This is a protected common event, which can be sent only by the system.
*/
static const std::string COMMON_EVENT_VISIBLE_ACCOUNTS_UPDATED;
/**
* Indicate the action of a common event that the account is deleted.
* To subscribe to this common event, your application must have the ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
* permission.
* This is a protected common event, which can be sent only by the system.
*/
static const std::string COMMON_EVENT_ACCOUNT_DELETED;
/**
* Indicate the action of a common event that the foundation is ready.
* To subscribe to this common event, your application must have the ohos.permission.RECEIVER_STARTUP_COMPLETED
* permission.
* This is a protected common event, which can be sent only by the system.
*/
static const std::string COMMON_EVENT_FOUNDATION_READY;
/**
* Indicates the action of a common event that the phone SIM card state has changed.
* This is a protected common event that can only be sent by system.
*/
static const std::string COMMON_EVENT_SIM_CARD_DEFAULT_VOICE_SUBSCRIPTION_CHANGED;
/**
* Indicates the action of a common event that the phone SIM card state has changed.
* This is a protected common event that can only be sent by system.
*/
static const std::string COMMON_EVENT_SIM_STATE_CHANGED;
/**
* Indicate the action of a common event that the airplane mode of the device has changed.
* This common event can be triggered only by system applications.
*/
static const std::string COMMON_EVENT_AIRPLANE_MODE_CHANGED;
/**
* Only for test case.
*/
static const std::string COMMON_EVENT_TEST_ACTION1;
/**
* Only for test case.
*/
static const std::string COMMON_EVENT_TEST_ACTION2;
public:
/**
* Default constructor used to create an empty CommonEventSupport instance.
*/
CommonEventSupport();
/**
* Default deconstructor used to deconstruct.
*/
virtual ~CommonEventSupport();
/**
* Check whether the current common event is a system common event.
* @param str the action of a common event.
* @return whether the current common event is a system common event or not.
*/
bool IsSystemEvent(std::string &str);
private:
void Init();
private:
std::vector<std::string> commonEventSupport_;
};
} // namespace EventFwk
} // namespace OHOS
#endif // FOUNDATION_EVENT_CESFWK_KITS_NATIVE_INCLUDE_COMMON_EVENT_SUPPORT_H
@@ -0,0 +1,229 @@
/*
* 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_EVENT_CESFWK_KITS_NATIVE_INCLUDE_MATCHING_SKILLS_H
#define FOUNDATION_EVENT_CESFWK_KITS_NATIVE_INCLUDE_MATCHING_SKILLS_H
#include <string>
#include <vector>
#include "parcel.h"
#include "want.h"
namespace OHOS {
namespace EventFwk {
using Want = OHOS::AAFwk::Want;
class MatchingSkills : public Parcelable {
public:
/**
* A constructor used to create an empty MatchingSkills instance.
*/
MatchingSkills();
/**
* A constructor used to create a MatchingSkills instance by using the parameters of an existing MatchingSkills
* object.
*/
MatchingSkills(const MatchingSkills &matchingSkills);
/**
* A deconstructor used to deconstruct
*/
~MatchingSkills();
/**
* Obtain an entity.
*
* @return entity
*/
std::string GetEntity(int index) const;
/**
* Add an event to this MatchingSkills object.
*
* @param entity the entity
*/
void AddEntity(const std::string &entity);
/**
* Has entity.
*
* @param event the entity in MatchingSkills
* @return whether the entity in MatchingSkills or not
*/
bool HasEntity(const std::string &entity) const;
/**
* Remove entity.
*
* @param event the entity in MatchingSkills
* @return remove entity success or not
*/
void RemoveEntity(const std::string &entity);
/**
* Gets entity count.
*
* @return entity count
*/
int CountEntities() const;
/**
* Adds an event to this MatchingSkills object.
*
* @param event the event
*/
void AddEvent(const std::string &event);
/**
* Get event count.
*
* @return the event count in MatchingSkills
*/
int CountEvent() const;
/**
* Get event.
*
* @return the event in MatchingSkills
*/
std::string GetEvent(int index) const;
/**
* Get events.
*
* @return the events in MatchingSkills
*/
std::vector<std::string> GetEvents() const;
/**
* Remove events.
*
* @return event the event in MatchingSkills
*/
void RemoveEvent(const std::string &event);
/**
* Has event.
*
* @param event the event in MatchingSkills
* @return whether the event in MatchingSkills or not
*/
bool HasEvent(const std::string &event) const;
/**
* obtain an Scheme.
*
* @return Scheme
*/
std::string GetScheme(int index) const;
/**
* Add scheme to this MatchingSkills object.
*
* @param scheme the scheme
*/
void AddScheme(const std::string &scheme);
/**
* Has scheme.
*
* @param event the scheme in MatchingSkills
* @return whether the scheme in MatchingSkills or not
*/
bool HasScheme(const std::string &scheme) const;
/**
* Remove entity.
*
* @param event the entity in MatchingSkills
* @return remove entity success or not
*/
void RemoveScheme(const std::string &scheme);
/**
* Get scheme count.
*
* @return scheme count
*/
int CountSchemes() const;
/**
* Match want.
*
* @param want the want in MatchingSkills
* @return match the want result
*/
bool Match(const Want &want) const;
/**
* Marshal this MatchingSkills object into a Parcel.
*
* @param parcel parcel
* @return marshalling result
*/
virtual bool Marshalling(Parcel &parcel) const override;
/**
* Unmarshal this MatchingSkills object from a Parcel.
*
* @param parcel parcel
* @return MatchingSkills
*/
static MatchingSkills *Unmarshalling(Parcel &parcel);
private:
/**
* Read MatchingSkills object from a Parcel.
*
* @param parcel the parcel
* @return read from parcel success or fail
*/
bool ReadFromParcel(Parcel &parcel);
/**
* Match event.
*
* @param parcel the event in want
* @return match event success or fail
*/
bool MatchEvent(const std::string &event) const;
/**
* Match entity.
*
* @param parcel the entity in want
* @return match entity success or fail
*/
bool MatchEntity(const std::vector<std::string> &entities) const;
/**
* Match scheme.
*
* @param parcel the scheme in want
* @return match scheme success or fail
*/
bool MatchScheme(const std::string &scheme) const;
private:
std::vector<std::string> entities_;
std::vector<std::string> events_;
std::vector<std::string> schemes_;
};
} // namespace EventFwk
} // namespace OHOS
#endif // FOUNDATION_EVENT_CESFWK_KITS_NATIVE_INCLUDE_MATCHING_SKILLS_H
@@ -0,0 +1,149 @@
/*
* 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 "async_common_event_result.h"
#include "common_event.h"
#include "event_log_wrapper.h"
#include "singleton.h"
namespace OHOS {
namespace EventFwk {
AsyncCommonEventResult::AsyncCommonEventResult(const int &resultCode, const std::string &resultData,
const bool &ordered, const bool &sticky, const sptr<IRemoteObject> &token)
: abortEvent_(false), finished_(false)
{
resultCode_ = resultCode;
resultData_ = resultData;
ordered_ = ordered;
sticky_ = sticky;
token_ = token;
}
AsyncCommonEventResult::~AsyncCommonEventResult()
{}
bool AsyncCommonEventResult::SetCode(const int &code)
{
if (!CheckSynchronous()) {
return false;
}
resultCode_ = code;
return true;
}
int AsyncCommonEventResult::GetCode() const
{
return resultCode_;
}
bool AsyncCommonEventResult::SetData(const std::string &data)
{
if (!CheckSynchronous()) {
return false;
}
resultData_ = data;
return true;
}
std::string AsyncCommonEventResult::GetData() const
{
return resultData_;
}
bool AsyncCommonEventResult::SetCodeAndData(const int &code, const std::string &data)
{
if (!CheckSynchronous()) {
return false;
}
resultCode_ = code;
resultData_ = data;
return true;
}
bool AsyncCommonEventResult::AbortCommonEvent()
{
if (!CheckSynchronous()) {
return false;
}
abortEvent_ = true;
return true;
}
bool AsyncCommonEventResult::ClearAbortCommonEvent()
{
if (!CheckSynchronous()) {
return false;
}
abortEvent_ = false;
return true;
}
bool AsyncCommonEventResult::GetAbortCommonEvent() const
{
return abortEvent_;
}
bool AsyncCommonEventResult::FinishCommonEvent()
{
EVENT_LOGI("enter");
if (!CheckSynchronous()) {
return false;
}
if (finished_) {
EVENT_LOGE("Common event already finished.");
return false;
}
finished_ = true;
return DelayedSingleton<CommonEvent>::GetInstance()->FinishReceiver(token_, resultCode_, resultData_, abortEvent_);
}
bool AsyncCommonEventResult::IsOrderedCommonEvent() const
{
return ordered_;
}
bool AsyncCommonEventResult::IsStickyCommonEvent() const
{
return sticky_;
}
bool AsyncCommonEventResult::CheckSynchronous() const
{
bool ret = false;
if (ordered_) {
ret = true;
} else {
EVENT_LOGE("Subscriber want to set result for an unordered common event.");
return false;
}
return ret;
}
} // namespace EventFwk
} // namespace OHOS
@@ -0,0 +1,125 @@
/*
* 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 "common_event_data.h"
#include "event_log_wrapper.h"
#include "string_ex.h"
namespace OHOS {
namespace EventFwk {
CommonEventData::CommonEventData() : code_(0)
{
EVENT_LOGD("constructor used to create a common event data instance");
}
CommonEventData::CommonEventData(const Want &want) : want_(want), code_(0)
{
EVENT_LOGD("constructor used to create a common event data instance by want");
}
CommonEventData::CommonEventData(const Want &want, const int &code, const std::string &data)
: want_(want), code_(code), data_(data)
{
EVENT_LOGD("constructor used to create a common event data instance by want code data.");
}
CommonEventData::~CommonEventData()
{
EVENT_LOGD("deconstructor used to destory a common event data instance");
}
void CommonEventData::SetCode(const int &code)
{
code_ = code;
}
int CommonEventData::GetCode() const
{
return code_;
}
void CommonEventData::SetData(const std::string &data)
{
data_ = data;
}
std::string CommonEventData::GetData() const
{
return data_;
}
void CommonEventData::SetWant(const Want &want)
{
want_ = want;
}
const Want &CommonEventData::GetWant() const
{
return want_;
}
bool CommonEventData::Marshalling(Parcel &parcel) const
{
if (!parcel.WriteString16(Str8ToStr16(data_))) {
EVENT_LOGE("Failed to write data");
return false;
}
if (!parcel.WriteInt32(code_)) {
EVENT_LOGE("Failed to write code");
return false;
}
if (!parcel.WriteParcelable(&want_)) {
EVENT_LOGE("Failed to write want");
return false;
}
return true;
}
bool CommonEventData::ReadFromParcel(Parcel &parcel)
{
// read data
data_ = Str16ToStr8(parcel.ReadString16());
// read code
code_ = parcel.ReadUint32();
// read want
std::unique_ptr<Want> want(parcel.ReadParcelable<Want>());
if (!want) {
EVENT_LOGE("Failed to ReadParcelable<Want>");
return false;
}
want_ = *want;
return true;
}
CommonEventData *CommonEventData::Unmarshalling(Parcel &parcel)
{
CommonEventData *commonEventData = new CommonEventData();
if (commonEventData && !commonEventData->ReadFromParcel(parcel)) {
delete commonEventData;
commonEventData = nullptr;
}
return commonEventData;
}
} // namespace EventFwk
} // namespace OHOS
@@ -0,0 +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 "common_event_manager.h"
#include "common_event.h"
#include "event_log_wrapper.h"
#include "singleton.h"
namespace OHOS {
namespace EventFwk {
bool CommonEventManager::PublishCommonEvent(const CommonEventData &data)
{
CommonEventPublishInfo publishInfo;
std::shared_ptr<CommonEventSubscriber> subscriber = nullptr;
return DelayedSingleton<CommonEvent>::GetInstance()->PublishCommonEvent(data, publishInfo, subscriber);
}
bool CommonEventManager::PublishCommonEvent(const CommonEventData &data, const CommonEventPublishInfo &publishInfo)
{
std::shared_ptr<CommonEventSubscriber> subscriber = nullptr;
return DelayedSingleton<CommonEvent>::GetInstance()->PublishCommonEvent(data, publishInfo, subscriber);
}
bool CommonEventManager::PublishCommonEvent(const CommonEventData &data, const CommonEventPublishInfo &publishInfo,
const std::shared_ptr<CommonEventSubscriber> &subscriber)
{
EVENT_LOGI("enter");
return DelayedSingleton<CommonEvent>::GetInstance()->PublishCommonEvent(data, publishInfo, subscriber);
}
bool CommonEventManager::SubscribeCommonEvent(const std::shared_ptr<CommonEventSubscriber> &subscriber)
{
return DelayedSingleton<CommonEvent>::GetInstance()->SubscribeCommonEvent(subscriber);
}
bool CommonEventManager::UnSubscribeCommonEvent(const std::shared_ptr<CommonEventSubscriber> &subscriber)
{
return DelayedSingleton<CommonEvent>::GetInstance()->UnSubscribeCommonEvent(subscriber);
}
bool CommonEventManager::GetStickyCommonEvent(const std::string &event, CommonEventData &commonEventData)
{
return DelayedSingleton<CommonEvent>::GetInstance()->GetStickyCommonEvent(event, commonEventData);
}
} // namespace EventFwk
} // namespace OHOS
@@ -0,0 +1,137 @@
/*
* 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 "common_event_publish_info.h"
#include "event_log_wrapper.h"
#include "string_ex.h"
namespace OHOS {
namespace EventFwk {
CommonEventPublishInfo::CommonEventPublishInfo() : sticky_(false), ordered_(false)
{
EVENT_LOGD("constructor used to create a common event publish info instance");
}
CommonEventPublishInfo::CommonEventPublishInfo(const CommonEventPublishInfo &commonEventPublishInfo)
{
EVENT_LOGD(
"constructor used to create a common event publish info instance by copying parameters from an existing one.");
sticky_ = commonEventPublishInfo.sticky_;
ordered_ = commonEventPublishInfo.ordered_;
subscriberPermissions_ = commonEventPublishInfo.subscriberPermissions_;
}
CommonEventPublishInfo::~CommonEventPublishInfo()
{
EVENT_LOGD("deconstructor used to destory a publish info instance");
}
void CommonEventPublishInfo::SetSticky(bool sticky)
{
sticky_ = sticky;
}
bool CommonEventPublishInfo::IsSticky() const
{
return sticky_;
}
void CommonEventPublishInfo::SetSubscriberPermissions(const std::vector<std::string> &subscriberPermissions)
{
subscriberPermissions_ = subscriberPermissions;
}
const std::vector<std::string> &CommonEventPublishInfo::GetSubscriberPermissions() const
{
return subscriberPermissions_;
}
void CommonEventPublishInfo::SetOrdered(bool ordered)
{
ordered_ = ordered;
}
bool CommonEventPublishInfo::IsOrdered() const
{
return ordered_;
}
bool CommonEventPublishInfo::Marshalling(Parcel &parcel) const
{
EVENT_LOGD("enter");
// write subscriberpermissions
std::vector<std::u16string> permissionVec_;
for (std::vector<std::string>::size_type i = 0; i < subscriberPermissions_.size(); ++i) {
permissionVec_.emplace_back(Str8ToStr16(subscriberPermissions_[i]));
}
if (!parcel.WriteString16Vector(permissionVec_)) {
EVENT_LOGE("common event Publish Info write permission failed");
return false;
}
// write ordered
if (!parcel.WriteBool(ordered_)) {
EVENT_LOGE("common event Publish Info write ordered failed");
return false;
}
// write sticky
if (!parcel.WriteBool(sticky_)) {
EVENT_LOGE("common event Publish Info write sticky failed");
return false;
}
return true;
}
bool CommonEventPublishInfo::ReadFromParcel(Parcel &parcel)
{
EVENT_LOGD("enter");
// read subscriberpermissions
std::vector<std::u16string> permissionVec_;
if (!parcel.ReadString16Vector(&permissionVec_)) {
EVENT_LOGE("ReadFromParcel read permission error");
return false;
}
subscriberPermissions_.clear();
for (std::vector<std::u16string>::size_type i = 0; i < permissionVec_.size(); i++) {
subscriberPermissions_.emplace_back(Str16ToStr8(permissionVec_[i]));
}
// read ordered
ordered_ = parcel.ReadBool();
// read sticky
sticky_ = parcel.ReadBool();
return true;
}
CommonEventPublishInfo *CommonEventPublishInfo::Unmarshalling(Parcel &parcel)
{
CommonEventPublishInfo *commonEventPublishInfo = new CommonEventPublishInfo();
if (commonEventPublishInfo && !commonEventPublishInfo->ReadFromParcel(parcel)) {
delete commonEventPublishInfo;
commonEventPublishInfo = nullptr;
}
return commonEventPublishInfo;
}
} // namespace EventFwk
} // namespace OHOS
@@ -0,0 +1,166 @@
/*
* 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 "common_event_subscribe_info.h"
#include "event_log_wrapper.h"
#include "string_ex.h"
namespace OHOS {
namespace EventFwk {
CommonEventSubscribeInfo::CommonEventSubscribeInfo(const MatchingSkills &matchingSkills)
: matchingSkills_(matchingSkills), priority_(0), threadMode_(CommonEventSubscribeInfo::ASYNC)
{
EVENT_LOGD("constructor used to create a common event subscriber info instance by matcingSkills");
}
CommonEventSubscribeInfo::CommonEventSubscribeInfo() : priority_(0), threadMode_(CommonEventSubscribeInfo::ASYNC)
{
EVENT_LOGD("constructor used to create a common event subscriber info instance");
}
CommonEventSubscribeInfo::CommonEventSubscribeInfo(const CommonEventSubscribeInfo &commonEventSubscribeInfo)
{
matchingSkills_ = commonEventSubscribeInfo.matchingSkills_;
priority_ = commonEventSubscribeInfo.priority_;
permission_ = commonEventSubscribeInfo.permission_;
deviceId_ = commonEventSubscribeInfo.deviceId_;
threadMode_ = commonEventSubscribeInfo.threadMode_;
}
CommonEventSubscribeInfo::~CommonEventSubscribeInfo()
{
EVENT_LOGD("deconstructor used to destroy a common event subscriber info instance");
}
void CommonEventSubscribeInfo::SetPriority(const int32_t &priority)
{
priority_ = priority;
}
int32_t CommonEventSubscribeInfo::GetPriority() const
{
return priority_;
}
void CommonEventSubscribeInfo::SetPermission(const std::string &permission)
{
permission_ = permission;
}
std::string CommonEventSubscribeInfo::GetPermission() const
{
return permission_;
}
CommonEventSubscribeInfo::ThreadMode CommonEventSubscribeInfo::GetThreadMode() const
{
return threadMode_;
}
void CommonEventSubscribeInfo::SetThreadMode(CommonEventSubscribeInfo::ThreadMode threadMode)
{
threadMode_ = threadMode;
}
void CommonEventSubscribeInfo::SetDeviceId(const std::string &deviceId)
{
deviceId_ = deviceId;
}
std::string CommonEventSubscribeInfo::GetDeviceId() const
{
return deviceId_;
}
const MatchingSkills &CommonEventSubscribeInfo::GetMatchingSkills() const
{
return matchingSkills_;
}
bool CommonEventSubscribeInfo::Marshalling(Parcel &parcel) const
{
// write permission
if (!parcel.WriteString16(Str8ToStr16(permission_))) {
EVENT_LOGE("Failed to write permission");
return false;
}
// write priority
if (!parcel.WriteUint32(priority_)) {
EVENT_LOGE("Failed to write priority");
return false;
}
// write threadMode
if (!parcel.WriteUint32(threadMode_)) {
EVENT_LOGE("Failed to write threadMode");
return false;
}
// write deviceId
if (!parcel.WriteString16(Str8ToStr16(deviceId_))) {
EVENT_LOGE("Failed to write deviceId");
return false;
}
// write matchingSkills
if (!parcel.WriteParcelable(&matchingSkills_)) {
EVENT_LOGE("Failed to write matchingSkills");
return false;
}
return true;
}
bool CommonEventSubscribeInfo::ReadFromParcel(Parcel &parcel)
{
// read permission
permission_ = Str16ToStr8(parcel.ReadString16());
// read priority
priority_ = parcel.ReadUint32();
// read threadMode
threadMode_ = (CommonEventSubscribeInfo::ThreadMode)parcel.ReadUint32();
// read deviceId
deviceId_ = Str16ToStr8(parcel.ReadString16());
// read MatchingSkills
auto skills = parcel.ReadParcelable<MatchingSkills>();
if (skills != nullptr) {
matchingSkills_ = *skills;
delete skills;
} else {
EVENT_LOGE("Failed to read matchingSkills");
return false;
}
return true;
}
CommonEventSubscribeInfo *CommonEventSubscribeInfo::Unmarshalling(Parcel &parcel)
{
CommonEventSubscribeInfo *commonEventSubscribeInfo = new CommonEventSubscribeInfo();
if (commonEventSubscribeInfo && !commonEventSubscribeInfo->ReadFromParcel(parcel)) {
delete commonEventSubscribeInfo;
commonEventSubscribeInfo = nullptr;
}
return commonEventSubscribeInfo;
}
} // namespace EventFwk
} // namespace OHOS
+150
View File
@@ -0,0 +1,150 @@
/*
* 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 "common_event_subscriber.h"
#include "event_log_wrapper.h"
namespace OHOS {
namespace EventFwk {
CommonEventSubscriber::CommonEventSubscriber() : result_(nullptr)
{}
CommonEventSubscriber::CommonEventSubscriber(const CommonEventSubscribeInfo &subscribeInfo)
: subscribeInfo_(subscribeInfo), result_(nullptr)
{}
CommonEventSubscriber::~CommonEventSubscriber()
{}
const CommonEventSubscribeInfo &CommonEventSubscriber::GetSubscribeInfo() const
{
return subscribeInfo_;
}
bool CommonEventSubscriber::SetCode(const int &code)
{
if (!CheckSynchronous()) {
return false;
}
return result_->SetCode(code);
}
int CommonEventSubscriber::GetCode() const
{
if (!CheckSynchronous()) {
return 0;
}
return result_->GetCode();
}
bool CommonEventSubscriber::SetData(const std::string &data)
{
if (!CheckSynchronous()) {
return false;
}
return result_->SetData(data);
}
std::string CommonEventSubscriber::GetData() const
{
if (!CheckSynchronous()) {
return std::string();
}
return result_->GetData();
}
bool CommonEventSubscriber::SetCodeAndData(const int &code, const std::string &data)
{
if (!CheckSynchronous()) {
return false;
}
return result_->SetCodeAndData(code, data);
}
bool CommonEventSubscriber::AbortCommonEvent()
{
if (!CheckSynchronous()) {
return false;
}
return result_->AbortCommonEvent();
}
bool CommonEventSubscriber::ClearAbortCommonEvent()
{
if (!CheckSynchronous()) {
return false;
}
return result_->ClearAbortCommonEvent();
}
bool CommonEventSubscriber::GetAbortCommonEvent() const
{
if (!CheckSynchronous()) {
return false;
}
return result_->GetAbortCommonEvent();
}
std::shared_ptr<AsyncCommonEventResult> CommonEventSubscriber::GoAsyncCommonEvent()
{
std::shared_ptr<AsyncCommonEventResult> res = result_;
result_ = nullptr;
return res;
}
bool CommonEventSubscriber::IsOrderedCommonEvent() const
{
return (result_ != nullptr) ? result_->IsOrderedCommonEvent() : false;
}
bool CommonEventSubscriber::IsStickyCommonEvent() const
{
return (result_ != nullptr) ? result_->IsStickyCommonEvent() : false;
}
bool CommonEventSubscriber::SetAsyncCommonEventResult(const std::shared_ptr<AsyncCommonEventResult> &result)
{
result_ = result;
return true;
}
std::shared_ptr<AsyncCommonEventResult> CommonEventSubscriber::GetAsyncCommonEventResult()
{
return result_;
}
bool CommonEventSubscriber::CheckSynchronous() const
{
if (!result_) {
EVENT_LOGE("Call when result is not set.");
return false;
}
if (!result_->CheckSynchronous()) {
return false;
}
return true;
}
} // namespace EventFwk
} // namespace OHOS
File diff suppressed because it is too large Load Diff
+274
View File
@@ -0,0 +1,274 @@
/*
* 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 "matching_skills.h"
#include "event_log_wrapper.h"
#include "string_ex.h"
namespace OHOS {
namespace EventFwk {
MatchingSkills::MatchingSkills()
{}
MatchingSkills::MatchingSkills(const MatchingSkills &matchingSkills)
{
entities_ = matchingSkills.entities_;
events_ = matchingSkills.events_;
schemes_ = matchingSkills.schemes_;
}
MatchingSkills::~MatchingSkills()
{}
std::string MatchingSkills::GetEntity(int index) const
{
std::string entity;
if (0 <= index && index < static_cast<int>(entities_.size())) {
entity = entities_[index];
}
return entity;
}
void MatchingSkills::AddEntity(const std::string &entity)
{
auto it = std::find(entities_.begin(), entities_.end(), entity);
if (it == entities_.end()) {
entities_.emplace_back(entity);
}
}
bool MatchingSkills::HasEntity(const std::string &entity) const
{
return std::find(entities_.cbegin(), entities_.cend(), entity) != entities_.cend();
}
void MatchingSkills::RemoveEntity(const std::string &entity)
{
auto it = std::find(entities_.cbegin(), entities_.cend(), entity);
if (it != entities_.cend()) {
entities_.erase(it);
}
}
int MatchingSkills::CountEntities() const
{
return entities_.size();
}
void MatchingSkills::AddEvent(const std::string &event)
{
auto it = std::find(events_.cbegin(), events_.cend(), event);
if (it == events_.cend()) {
events_.emplace_back(event);
}
}
int MatchingSkills::CountEvent() const
{
return events_.size();
}
std::string MatchingSkills::GetEvent(int index) const
{
std::string event;
if (0 <= index && index < static_cast<int>(events_.size())) {
event = events_[index];
}
return event;
}
std::vector<std::string> MatchingSkills::GetEvents() const
{
return events_;
}
void MatchingSkills::RemoveEvent(const std::string &event)
{
auto it = std::find(events_.cbegin(), events_.cend(), event);
if (it != events_.cend()) {
events_.erase(it);
}
}
bool MatchingSkills::HasEvent(const std::string &event) const
{
return std::find(events_.cbegin(), events_.cend(), event) != events_.cend();
}
std::string MatchingSkills::GetScheme(int index) const
{
std::string schemes;
if (0 <= index && index < static_cast<int>(schemes_.size())) {
schemes = schemes_[index];
}
return schemes;
}
void MatchingSkills::AddScheme(const std::string &scheme)
{
auto it = std::find(schemes_.begin(), schemes_.end(), scheme);
if (it == schemes_.end()) {
schemes_.emplace_back(scheme);
}
}
bool MatchingSkills::HasScheme(const std::string &scheme) const
{
return std::find(schemes_.begin(), schemes_.end(), scheme) != schemes_.end();
}
void MatchingSkills::RemoveScheme(const std::string &scheme)
{
auto it = std::find(schemes_.cbegin(), schemes_.cend(), scheme);
if (it != schemes_.cend()) {
schemes_.erase(it);
}
}
int MatchingSkills::CountSchemes() const
{
return schemes_.size();
}
bool MatchingSkills::Marshalling(Parcel &parcel) const
{
// write entity
std::vector<std::u16string> actionU16Entity;
for (std::vector<std::string>::size_type i = 0; i < entities_.size(); i++) {
actionU16Entity.emplace_back(Str8ToStr16(entities_[i]));
}
if (!parcel.WriteString16Vector(actionU16Entity)) {
EVENT_LOGE("matching skills write entity error");
return false;
}
// write event
std::vector<std::u16string> actionU16Event;
for (std::vector<std::string>::size_type i = 0; i < events_.size(); i++) {
actionU16Event.emplace_back(Str8ToStr16(events_[i]));
}
if (!parcel.WriteString16Vector(actionU16Event)) {
EVENT_LOGE("matching skills write event error");
return false;
}
// write scheme
std::vector<std::u16string> actionU16Scheme;
for (std::vector<std::string>::size_type i = 0; i < schemes_.size(); i++) {
actionU16Scheme.emplace_back(Str8ToStr16(schemes_[i]));
}
if (!parcel.WriteString16Vector(actionU16Scheme)) {
EVENT_LOGE("matching skills write scheme error");
return false;
}
return true;
}
bool MatchingSkills::ReadFromParcel(Parcel &parcel)
{
// read entity
std::vector<std::u16string> actionU16Entity;
if (!parcel.ReadString16Vector(&actionU16Entity)) {
EVENT_LOGE("matching skills read entity error");
return false;
}
entities_.clear();
for (std::vector<std::u16string>::size_type i = 0; i < actionU16Entity.size(); i++) {
entities_.emplace_back(Str16ToStr8(actionU16Entity[i]));
}
// read event
std::vector<std::u16string> actionU16Event;
if (!parcel.ReadString16Vector(&actionU16Event)) {
EVENT_LOGE("matching skills read event error");
return false;
}
events_.clear();
for (std::vector<std::u16string>::size_type i = 0; i < actionU16Event.size(); i++) {
events_.emplace_back(Str16ToStr8(actionU16Event[i]));
}
// read scheme
std::vector<std::u16string> actionU16Scheme;
if (!parcel.ReadString16Vector(&actionU16Scheme)) {
EVENT_LOGE("matching skills read scheme error");
return false;
}
schemes_.clear();
for (std::vector<std::u16string>::size_type i = 0; i < actionU16Scheme.size(); i++) {
schemes_.emplace_back(Str16ToStr8(actionU16Scheme[i]));
}
return true;
}
MatchingSkills *MatchingSkills::Unmarshalling(Parcel &parcel)
{
MatchingSkills *matchingSkills = new MatchingSkills();
if (matchingSkills && !matchingSkills->ReadFromParcel(parcel)) {
delete matchingSkills;
matchingSkills = nullptr;
}
return matchingSkills;
}
bool MatchingSkills::MatchEvent(const std::string &event) const
{
if (event == std::string()) {
EVENT_LOGD("event is null");
return false;
}
return HasEvent(event);
}
bool MatchingSkills::MatchEntity(const std::vector<std::string> &entities) const
{
if (entities.size() == 0) {
return true;
}
for (auto vec : entities) {
auto it = std::find(entities_.cbegin(), entities_.cend(), vec);
if (it == entities_.cend()) {
return false;
}
}
return true;
}
bool MatchingSkills::MatchScheme(const std::string &scheme) const
{
if (schemes_.size()) {
return HasScheme(scheme);
}
if (scheme == std::string()) {
EVENT_LOGD("scheme is null");
return true;
}
return false;
}
bool MatchingSkills::Match(const Want &want) const
{
return MatchEvent(want.GetAction()) && MatchEntity(want.GetEntities()) && MatchScheme(want.GetScheme());
}
} // namespace EventFwk
} // namespace OHOS
+121
View File
@@ -0,0 +1,121 @@
# 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/test.gni")
module_output_path = "ces_standard/cesfwk/kits/native"
config("kits_natvie_config") {
visibility = [ ":*" ]
include_dirs = [
"//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include",
"//foundation/aafwk/standard/interfaces/innerkits/base/include/",
"//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content",
"//foundation/aafwk/standard/services/abilitymgr/include/",
"//foundation/appexecfwk/standard/services/bundlemgr/include",
"//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include",
"//foundation/distributedschedule/safwk/services/safwk/include",
"//base/notification/ces_standard/cesfwk/innerkits/include",
"//base/notification/ces_standard/cesfwk/kits/native/include",
"//base/notification/ces_standard/cesfwk/services/include",
"//base/notification/ces_standard/common/log/include",
"//utils/native/base/include",
"//utils/system/safwk/native/include",
]
cflags = []
if (target_cpu == "arm") {
cflags += [ "-DBINDER_IPC_32BIT" ]
}
}
ohos_unittest("matching_skills_test") {
module_out_path = module_output_path
sources = [ "matching_skills_test.cpp" ]
configs = [ ":kits_natvie_config" ]
deps = [
"//base/notification/ces_standard/cesfwk/innerkits:cesfwk_innerkits",
"//base/notification/ces_standard/cesfwk/kits/native:cesfwk_kits",
"//base/notification/ces_standard/common:libevent_common",
"//foundation/aafwk/standard/interfaces/innerkits/want:want",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base",
"//third_party/googletest:gtest_main",
"//utils/native/base:utils",
]
external_deps = [ "ipc:ipc_core" ]
}
ohos_unittest("common_event_subscribe_test") {
module_out_path = module_output_path
sources = [ "common_event_subscribe_test.cpp" ]
configs = [ ":kits_natvie_config" ]
deps = [
"//base/notification/ces_standard/cesfwk/innerkits:cesfwk_innerkits",
"//base/notification/ces_standard/cesfwk/kits/native:cesfwk_kits",
"//base/notification/ces_standard/cesfwk/services:cesfwk_services",
"//base/notification/ces_standard/common:libevent_common",
"//foundation/aafwk/standard/interfaces/innerkits/want:want",
"//foundation/aafwk/standard/services/abilitymgr:abilityms",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler",
"//third_party/googletest:gtest_main",
"//utils/native/base:utils",
]
external_deps = [ "ipc:ipc_core" ]
}
ohos_unittest("common_event_unsubscribe_test") {
module_out_path = module_output_path
sources = [ "common_event_unsubscribe_test.cpp" ]
configs = [ ":kits_natvie_config" ]
deps = [
"//base/notification/ces_standard/cesfwk/innerkits:cesfwk_innerkits",
"//base/notification/ces_standard/cesfwk/kits/native:cesfwk_kits",
"//base/notification/ces_standard/cesfwk/services:cesfwk_services",
"//foundation/aafwk/standard/interfaces/innerkits/want:want",
"//foundation/aafwk/standard/services/abilitymgr:abilityms",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler",
"//third_party/googletest:gtest_main",
"//utils/native/base:utils",
]
external_deps = [ "ipc:ipc_core" ]
}
group("unittest") {
testonly = true
deps = []
deps += [
":common_event_subscribe_test",
":common_event_unsubscribe_test",
":matching_skills_test",
]
}
@@ -0,0 +1,531 @@
/*
* 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 <thread>
#include <chrono>
#include <sys/time.h>
// redefine private and protected since testcase need to invoke and test private function
#define private public
#define protected public
#include "common_event.h"
#include "common_event_manager.h"
#include "common_event_manager_service.h"
#undef private
#undef protected
#include "datetime_ex.h"
#include "iremote_object.h"
#include "message_parcel.h"
#include "sa_mgr_client.h"
#include "singleton.h"
#include "system_ability.h"
#include "system_ability_definition.h"
#include "want.h"
#include <gtest/gtest.h>
using namespace testing::ext;
using namespace OHOS::EventFwk;
using OHOS::Parcel;
namespace {
const std::string EVENT = "com.ces.test.event";
std::mutex mtx;
const time_t TIME_OUT_SECONDS_LIMIT = 5;
} // namespace
class SubscriberTest;
class CommonEventSubscribeTest : public testing::Test {
public:
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
public:
static constexpr int TEST_WAIT_TIME = 100000;
std::shared_ptr<CommonEventManagerService> commonEventMs_;
CommonEventManager commonEventManager;
MatchingSkills matchingSkills;
};
class SubscriberTest : public CommonEventSubscriber {
public:
SubscriberTest(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp)
{}
~SubscriberTest()
{}
virtual void OnReceiveEvent(const CommonEventData &data)
{
mtx.unlock();
}
};
class EventReceiveStubTest : public EventReceiveStub {
public:
EventReceiveStubTest()
{}
~EventReceiveStubTest()
{}
virtual void NotifyEvent(const CommonEventData &commonEventData, const bool &ordered, const bool &sticky)
{}
};
class CommonEventStubTest : public CommonEventStub {
public:
CommonEventStubTest()
{}
virtual bool PublishCommonEvent(const CommonEventData &event, const CommonEventPublishInfo &publishinfo,
const OHOS::sptr<IRemoteObject> &commonEventListener)
{
return false;
}
virtual bool SubscribeCommonEvent(
const CommonEventSubscribeInfo &subscriberInfo, const OHOS::sptr<IRemoteObject> &commonEventListener)
{
return false;
}
virtual bool UnsubscribeCommonEvent(const OHOS::sptr<IRemoteObject> &commonEventListener)
{
return false;
}
virtual bool DumpState(const std::string &event, std::vector<std::string> &state)
{
return false;
}
virtual ~CommonEventStubTest()
{}
virtual bool FinishReceiver(const OHOS::sptr<IRemoteObject> &proxy, const int &code,
const std::string &receiverData, const bool &abortEvent)
{
return false;
}
};
void CommonEventSubscribeTest::SetUpTestCase(void)
{}
void CommonEventSubscribeTest::TearDownTestCase(void)
{}
void CommonEventSubscribeTest::SetUp(void)
{}
void CommonEventSubscribeTest::TearDown(void)
{}
/*
* Feature: CommonEventSubscribeTest
* Function:CommonEvent SubscribeCommonEvent
* SubFunction: Subscribe common event
* FunctionPoints: test subscribe event
* EnvConditions: system run normally
* CaseDescription: 1. subscribe common event
* 2. success subscribe common event with right parameters
*/
HWTEST_F(CommonEventSubscribeTest, CommonEventSubscribe_001, TestSize.Level1)
{
/* Subscribe */
MatchingSkills matchingSkills;
matchingSkills.AddEvent(EVENT);
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
bool subscribeResult = CommonEventManager::SubscribeCommonEvent(subscriber);
EXPECT_EQ(true, subscribeResult);
/* Publish */
// make a want
Want want;
want.SetAction(EVENT);
// make common event data
CommonEventData data;
data.SetWant(want);
// lock the mutex
mtx.lock();
// publish a common event
bool publishResult = CommonEventManager::PublishCommonEvent(data);
EXPECT_EQ(true, publishResult);
// record start time of publishing
struct tm startTime = {0};
EXPECT_EQ(OHOS::GetSystemCurrentTime(&startTime), true);
// record current time
struct tm doingTime = {0};
int64_t seconds = 0;
while (!mtx.try_lock()) {
// get current time and compare it with the start time
EXPECT_EQ(OHOS::GetSystemCurrentTime(&doingTime), true);
seconds = OHOS::GetSecondsBetween(startTime, doingTime);
if (seconds >= TIME_OUT_SECONDS_LIMIT) {
break;
}
}
// expect the subscriber could receive the event within 5 seconds.
EXPECT_LT(seconds, TIME_OUT_SECONDS_LIMIT);
mtx.unlock();
}
/*
* Feature: CommonEventSubscribeTest
* Function:CommonEventSubscriberManager InsertSubscriber
* SubFunction: Subscribe common event
* FunctionPoints: test subscribe event
* EnvConditions: system run normally
* CaseDescription: 1. subscribe common event
* 2. different subscriber subscribe event
* 3. success subscribe common event with right parameters
*/
HWTEST_F(CommonEventSubscribeTest, CommonEventSubscribe_002, TestSize.Level1)
{
MatchingSkills matchingSkills;
matchingSkills.AddEvent(EVENT);
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
std::shared_ptr<SubscriberTest> subscribera = std::make_shared<SubscriberTest>(subscriberInfo);
std::shared_ptr<SubscriberTest> subscriberb = std::make_shared<SubscriberTest>(subscriberInfo);
bool subscribeResulta = CommonEventManager::SubscribeCommonEvent(subscribera);
EXPECT_EQ(true, subscribeResulta);
bool subscribeResultb = CommonEventManager::SubscribeCommonEvent(subscriberb);
EXPECT_EQ(true, subscribeResultb);
}
/*
* Feature: CommonEventSubscribeTest
* Function:CommonEvent SubscribeCommonEvent
* SubFunction: Subscribe common event
* FunctionPoints: test subscribe event
* EnvConditions: system run normally
* CaseDescription: 1. subscribe common event
* 2. fail subscribe common event kit with null subscriber
*/
HWTEST_F(CommonEventSubscribeTest, CommonEventSubscribe_003, TestSize.Level1)
{
bool subscribeResult = CommonEventManager::SubscribeCommonEvent(nullptr);
EXPECT_EQ(false, subscribeResult);
}
/*
* Feature: CommonEventSubscribeTest
* Function:CommonEvent SubscribeCommonEvent
* SubFunction: Subscribe common event
* FunctionPoints: test subscribe event
* EnvConditions: system run normally
* CaseDescription: 1. subscribe common event
* 2. fail subscribe common event with no event
*/
HWTEST_F(CommonEventSubscribeTest, CommonEventSubscribe_004, TestSize.Level1)
{
MatchingSkills matchingSkills;
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
bool subscribeResult = CommonEventManager::SubscribeCommonEvent(subscriber);
EXPECT_EQ(false, subscribeResult);
}
/*
* Feature: CommonEventSubscribeTest
* Function:CommonEvent SubscribeCommonEvent
* SubFunction: Subscribe common event
* FunctionPoints: test subscribe event
* EnvConditions: system run normally
* CaseDescription: 1. subscribe common event
* 2. fail subscribe common event because common event listener has subsrciber
*/
HWTEST_F(CommonEventSubscribeTest, CommonEventSubscribe_005, TestSize.Level1)
{
MatchingSkills matchingSkills;
matchingSkills.AddEvent(EVENT);
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
CommonEventManager::SubscribeCommonEvent(subscriber);
bool subscribeResult = CommonEventManager::SubscribeCommonEvent(subscriber);
EXPECT_EQ(true, subscribeResult);
}
/*
* Feature: CommonEventSubscribeTest
* Function: CommonEventProxy SubscribeCommonEvent CommonEventStub OnRemoteRequest
* SubFunction: Subscribe common event
* FunctionPoints: test subscribe event
* EnvConditions: system run normally
* CaseDescription: 1. subscribe common event
* 2. fail subscribe common event kit proxy subscriber info is null to do
*/
HWTEST_F(CommonEventSubscribeTest, CommonEventSubscribe_006, TestSize.Level1)
{
CommonEventStubTest CommonEventStubTest;
OHOS::MessageParcel data, reply;
OHOS::MessageOption option;
int subscribeResult = CommonEventStubTest.OnRemoteRequest(
static_cast<uint32_t>(ICommonEvent::Message::CES_SUBSCRIBE_COMMON_EVENT), data, reply, option);
EXPECT_EQ(OHOS::ERR_INVALID_VALUE, subscribeResult);
}
/*
* Feature: CommonEventSubscribeTest
* Function: CommonEventProxy SubscribeCommonEvent CommonEventStub OnRemoteRequest
* SubFunction: Subscribe common event
* FunctionPoints: test subscribe event
* EnvConditions: system run normally
* CaseDescription: 1. subscribe common event
* 2. fail subscribe common event kit proxy common event listener is null
*/
HWTEST_F(CommonEventSubscribeTest, CommonEventSubscribe_007, TestSize.Level1)
{
CommonEventStubTest CommonEventStubTest;
MatchingSkills matchingSkills;
matchingSkills.AddEvent(EVENT);
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
OHOS::MessageParcel data, reply;
OHOS::MessageOption option;
data.WriteParcelable(&subscriberInfo);
int subscribeResult = CommonEventStubTest.OnRemoteRequest(
static_cast<uint32_t>(ICommonEvent::Message::CES_SUBSCRIBE_COMMON_EVENT), data, reply, option);
EXPECT_EQ(OHOS::ERR_INVALID_VALUE, subscribeResult);
}
/*
* Feature: CommonEventSubscribeTest
* Function: CommonEventProxy SubscribeCommonEvent CommonEventStub OnRemoteRequest
* SubFunction: Subscribe common event
* FunctionPoints: test subscribe event
* EnvConditions: system run normally
* CaseDescription: 1. subscribe common event
* 2. fail subscribe common event code is error
*/
HWTEST_F(CommonEventSubscribeTest, CommonEventSubscribe_008, TestSize.Level1)
{
CommonEventStubTest CommonEventStubTest;
MatchingSkills matchingSkills;
matchingSkills.AddEvent(EVENT);
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
OHOS::MessageParcel data, reply;
OHOS::MessageOption option;
data.WriteParcelable(&subscriberInfo);
int subscribeResult = CommonEventStubTest.OnRemoteRequest(static_cast<uint32_t>(-1), data, reply, option);
EXPECT_EQ(OHOS::IPC_STUB_UNKNOW_TRANS_ERR, subscribeResult);
}
/*
* Feature: CommonEventSubscribeTest
* Function: InnerCommonEventManager SubscribeCommonEvent
* SubFunction: Subscribe common event
* FunctionPoints: test subscribe event
* EnvConditions: system run normally
* CaseDescription: 1. subscribe common event
* 2. fail subscribe common event, inner common event manager
* common event listener is null
*/
HWTEST_F(CommonEventSubscribeTest, CommonEventSubscribe_009, TestSize.Level1)
{
MatchingSkills matchingSkills;
matchingSkills.AddEvent(EVENT);
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
std::shared_ptr<InnerCommonEventManager> innerCommonEventManager = std::make_shared<InnerCommonEventManager>();
OHOS::sptr<OHOS::IRemoteObject> sp(nullptr);
struct tm curTime;
EXPECT_EQ(false, innerCommonEventManager->SubscribeCommonEvent(subscriberInfo, sp, curTime, 0, 0, ""));
}
/*
* Feature: CommonEventSubscribeTest
* Function: CommonEventSubscriberManager InsertSubscriber
* SubFunction: Subscribe common event
* FunctionPoints: test subscribe event
* EnvConditions: system run normally
* CaseDescription: 1. subscribe common event
* 2. fail subscribe common event , common event subscriber manager
* event subscriber info is null
*/
HWTEST_F(CommonEventSubscribeTest, CommonEventSubscribe_010, TestSize.Level1)
{
MatchingSkills matchingSkills;
matchingSkills.AddEvent(EVENT);
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
OHOS::sptr<CommonEventListener> commonEventListener = new CommonEventListener(subscriber);
std::shared_ptr<InnerCommonEventManager> innerCommonEventManager = std::make_shared<InnerCommonEventManager>();
OHOS::sptr<OHOS::IRemoteObject> commonEventListenerPtr(commonEventListener);
struct tm curTime{0};
int result = OHOS::DelayedSingleton<CommonEventSubscriberManager>::GetInstance()->InsertSubscriber(
nullptr, commonEventListenerPtr, curTime, 0, 0, "");
EXPECT_EQ(OHOS::ERR_INVALID_VALUE, result);
}
/*
* Feature: CommonEventSubscribeTest
* Function: CommonEventSubscriberManager InsertSubscriber
* SubFunction: Subscribe common event
* FunctionPoints: test subscribe event
* EnvConditions: system run normally
* CaseDescription: 1. subscribe common event
* 2. fail subscribe common event , common event subscriber manager
* event common event listener is null
*/
HWTEST_F(CommonEventSubscribeTest, CommonEventSubscribe_011, TestSize.Level1)
{
MatchingSkills matchingSkills;
matchingSkills.AddEvent(EVENT);
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
std::shared_ptr<CommonEventSubscribeInfo> commonEventSubscribeInfo =
std::make_shared<CommonEventSubscribeInfo>(subscriberInfo);
struct tm curTime{0};
int result = OHOS::DelayedSingleton<CommonEventSubscriberManager>::GetInstance()->InsertSubscriber(
commonEventSubscribeInfo, nullptr, curTime, 0, 0, "");
EXPECT_EQ(OHOS::ERR_INVALID_VALUE, result);
}
/*
* Feature: CommonEventSubscribeTest
* Function: CommonEventSubscriberManager InsertSubscriber
* SubFunction: Subscribe common event
* FunctionPoints: test subscribe event
* EnvConditions: system run normally
* CaseDescription: 1. subscribe common event
* 2. fail subscribe common event , common event subscriber manager
* event size is null
*/
HWTEST_F(CommonEventSubscribeTest, CommonEventSubscribe_012, TestSize.Level1)
{
MatchingSkills matchingSkills;
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
std::shared_ptr<CommonEventSubscribeInfo> commonEventSubscribeInfo =
std::make_shared<CommonEventSubscribeInfo>(subscriberInfo);
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
OHOS::sptr<CommonEventListener> commonEventListener = new CommonEventListener(subscriber);
std::shared_ptr<InnerCommonEventManager> innerCommonEventManager = std::make_shared<InnerCommonEventManager>();
OHOS::sptr<OHOS::IRemoteObject> commonEventListenerSp(commonEventListener);
struct tm curTime{0};
int result = OHOS::DelayedSingleton<CommonEventSubscriberManager>::GetInstance()->InsertSubscriber(
commonEventSubscribeInfo, commonEventListenerSp, curTime, 0, 0, "");
EXPECT_EQ(OHOS::ERR_INVALID_VALUE, result);
}
/*
* Feature: CommonEventSubscribeTest
* Function: EventReceiveStub OnRemoteRequest
* SubFunction: EventReceiveStub OnRemoteRequest
* FunctionPoints: test on Remote request
* EnvConditions: system run normally
* CaseDescription: 1. event receive fail
*/
HWTEST_F(CommonEventSubscribeTest, CommonEventSubscribe_013, TestSize.Level1)
{
EventReceiveStubTest eventReceiveStub;
OHOS::MessageParcel data, reply;
OHOS::MessageOption option;
int result = eventReceiveStub.OnRemoteRequest(0, data, reply, option);
EXPECT_EQ(OHOS::IPC_STUB_UNKNOW_TRANS_ERR, result);
}
/*
* Feature: CommonEventSubscribeTest
* Function: CommonEventListener IsReady
* SubFunction: Subscribe common event
* FunctionPoints: test is ready
* EnvConditions: system run normally
* CaseDescription: 1. ready fail because runner is null
*/
HWTEST_F(CommonEventSubscribeTest, CommonEventSubscribe_014, TestSize.Level1)
{
MatchingSkills matchingSkills;
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
std::shared_ptr<CommonEventSubscribeInfo> commonEventSubscribeInfo =
std::make_shared<CommonEventSubscribeInfo>(subscriberInfo);
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
CommonEventListener commonEventListener(subscriber);
commonEventListener.runner_ = nullptr;
int result = commonEventListener.IsReady();
EXPECT_EQ(false, result);
}
/*
* Feature: CommonEventSubscribeTest
* Function: CommonEventListener IsReady
* SubFunction: Subscribe common event
* FunctionPoints: test is ready
* EnvConditions: system run normally
* CaseDescription: 1. ready fail because handler is null
*/
HWTEST_F(CommonEventSubscribeTest, CommonEventSubscribe_015, TestSize.Level1)
{
MatchingSkills matchingSkills;
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
std::shared_ptr<CommonEventSubscribeInfo> commonEventSubscribeInfo =
std::make_shared<CommonEventSubscribeInfo>(subscriberInfo);
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
CommonEventListener commonEventListener(subscriber);
commonEventListener.handler_ = nullptr;
int result = commonEventListener.IsReady();
EXPECT_EQ(false, result);
}
@@ -0,0 +1,331 @@
/*
* 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.
*/
// redefine private and protected since testcase need to invoke and test private function
#define private public
#define protected public
#include "common_event.h"
#include "common_event_manager.h"
#include "common_event_manager_service.h"
#undef private
#undef protected
#include "errors.h"
#include "sa_mgr_client.h"
#include "system_ability.h"
#include "system_ability_definition.h"
#include <gtest/gtest.h>
using namespace testing::ext;
using namespace OHOS;
using namespace OHOS::EventFwk;
using OHOS::Parcel;
class CommonEventUnSubscribeTest : public testing::Test {
public:
CommonEventUnSubscribeTest()
{}
~CommonEventUnSubscribeTest()
{}
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
public:
MatchingSkills matchingSkills_;
void SetMatchingSkillsWithEvent(const std::string &event);
void SetMatchingSkillsWithEntity(const std::string &entity);
void SetMatchingSkillsWithScheme(const std::string &scheme);
};
class DreivedSubscriber : public CommonEventSubscriber {
public:
DreivedSubscriber(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp)
{}
~DreivedSubscriber()
{}
virtual void OnReceiveEvent(const CommonEventData &data)
{}
};
class CommonEventStubTest : public CommonEventStub {
public:
CommonEventStubTest()
{}
virtual bool PublishCommonEvent(const CommonEventData &event, const CommonEventPublishInfo &publishinfo,
const OHOS::sptr<IRemoteObject> &commonEventListener)
{
return false;
}
virtual bool SubscribeCommonEvent(
const CommonEventSubscribeInfo &subscriberInfo, const OHOS::sptr<IRemoteObject> &commonEventListener)
{
return false;
}
virtual bool UnsubscribeCommonEvent(const OHOS::sptr<IRemoteObject> &commonEventListener)
{
return false;
}
virtual bool DumpState(const std::string &event, std::vector<std::string> &state)
{
return false;
}
virtual ~CommonEventStubTest()
{}
virtual bool FinishReceiver(const OHOS::sptr<IRemoteObject> &proxy, const int &code,
const std::string &receiverData, const bool &abortEvent)
{
return false;
}
};
class SubscriberTest : public CommonEventSubscriber {
public:
SubscriberTest(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp)
{}
~SubscriberTest()
{}
virtual void OnReceiveEvent(const CommonEventData &data)
{}
};
void CommonEventUnSubscribeTest::SetUpTestCase(void)
{}
void CommonEventUnSubscribeTest::TearDownTestCase(void)
{}
void CommonEventUnSubscribeTest::SetUp(void)
{}
void CommonEventUnSubscribeTest::TearDown(void)
{}
void CommonEventUnSubscribeTest::SetMatchingSkillsWithEvent(const std::string &event)
{
matchingSkills_.AddEvent(event);
}
void CommonEventUnSubscribeTest::SetMatchingSkillsWithEntity(const std::string &entity)
{
matchingSkills_.AddEntity(entity);
}
void CommonEventUnSubscribeTest::SetMatchingSkillsWithScheme(const std::string &scheme)
{
matchingSkills_.AddScheme(scheme);
}
/*
* Feature: CommonEventManager
* Function: UnSubscribeCommonEvent
* SubFunction: NA
* FunctionPoints: normal
* EnvConditions: system running normally
* CaseDescription: Unsubscribe normally and verify UnSubscribeCommonEvent function return value.
*/
HWTEST_F(CommonEventUnSubscribeTest, UnSubscribe_001, TestSize.Level1)
{
CommonEventUnSubscribeTest::SetMatchingSkillsWithEvent("event");
CommonEventSubscribeInfo subscriberInfo(matchingSkills_);
std::shared_ptr<DreivedSubscriber> subscriber = std::make_shared<DreivedSubscriber>(subscriberInfo);
std::shared_ptr<CommonEventManager> helper;
EXPECT_EQ(true, helper->UnSubscribeCommonEvent(subscriber));
}
/*
* Feature: CommonEvent
* Function: UnSubscribeCommonEvent
* SubFunction: NA
* FunctionPoints: normal
* EnvConditions: system running normally
* CaseDescription: Verify UnSubscribeCommonEvent function return value with eventListener not exist.
*/
HWTEST_F(CommonEventUnSubscribeTest, UnSubscribe_002, TestSize.Level1)
{
CommonEventUnSubscribeTest::SetMatchingSkillsWithEvent("event");
CommonEventSubscribeInfo subscriberInfo(matchingSkills_);
std::shared_ptr<DreivedSubscriber> subscriber = std::make_shared<DreivedSubscriber>(subscriberInfo);
EXPECT_EQ(true, DelayedSingleton<CommonEvent>::GetInstance()->UnSubscribeCommonEvent(subscriber));
}
/*
* Feature: CommonEvent
* Function: UnSubscribeCommonEvent
* SubFunction: NA
* FunctionPoints: normal
* EnvConditions: system running normally
* CaseDescription: Verify UnSubscribeCommonEvent function return value with eventListener existed.
*/
HWTEST_F(CommonEventUnSubscribeTest, UnSubscribe_003, TestSize.Level1)
{
CommonEventUnSubscribeTest::SetMatchingSkillsWithEvent("event");
CommonEventSubscribeInfo subscriberInfo(matchingSkills_);
std::shared_ptr<DreivedSubscriber> subscriber = std::make_shared<DreivedSubscriber>(subscriberInfo);
DelayedSingleton<CommonEvent>::GetInstance()->SubscribeCommonEvent(subscriber);
EXPECT_EQ(true, DelayedSingleton<CommonEvent>::GetInstance()->UnSubscribeCommonEvent(subscriber));
}
/*
* Feature: InnerCommonEventManager
* Function: UnsubscribeCommonEvent
* SubFunction: NA
* FunctionPoints: normal
* EnvConditions: system running normally
* CaseDescription: Verify UnSubscribeCommonEvent function return value.
*/
HWTEST_F(CommonEventUnSubscribeTest, UnSubscribe_004, TestSize.Level1)
{
CommonEventUnSubscribeTest::SetMatchingSkillsWithEvent("event");
CommonEventSubscribeInfo subscriberInfo(matchingSkills_);
std::shared_ptr<DreivedSubscriber> subscriber = std::make_shared<DreivedSubscriber>(subscriberInfo);
sptr<IRemoteObject> commonEventListener = new CommonEventListener(subscriber);
std::shared_ptr<InnerCommonEventManager> innerCommonEventManager = std::make_shared<InnerCommonEventManager>();
EXPECT_EQ(true, innerCommonEventManager->UnsubscribeCommonEvent(commonEventListener));
}
/*
* Feature: CommonEventSubscriberManager
* Function: RemoveSubscriber
* SubFunction: NA
* FunctionPoints: normal
* EnvConditions: system running normally
* CaseDescription: Verify RemoveSubscriber function return value.
*/
HWTEST_F(CommonEventUnSubscribeTest, UnSubscribe_005, TestSize.Level1)
{
CommonEventUnSubscribeTest::SetMatchingSkillsWithEvent("event");
CommonEventSubscribeInfo subscriberInfo(matchingSkills_);
std::shared_ptr<DreivedSubscriber> subscriber = std::make_shared<DreivedSubscriber>(subscriberInfo);
sptr<IRemoteObject> commonEventListener = new CommonEventListener(subscriber);
EXPECT_EQ(
ERR_OK, DelayedSingleton<CommonEventSubscriberManager>::GetInstance()->RemoveSubscriber(commonEventListener));
}
/*
* Feature: CommonEvent
* Function: UnSubscribeCommonEvent
* SubFunction: NA
* FunctionPoints: exception
* EnvConditions: system running normally
* CaseDescription: When the subscriber does not exist, verify UnSubscribeCommonEvent function return value.
*/
HWTEST_F(CommonEventUnSubscribeTest, UnSubscribe_006, TestSize.Level1)
{
std::shared_ptr<DreivedSubscriber> subscriber = nullptr;
EXPECT_EQ(false, DelayedSingleton<CommonEvent>::GetInstance()->UnSubscribeCommonEvent(subscriber));
}
/*
* Feature: CommonEventStub
* Function: OnRemoteRequest
* SubFunction: NA
* FunctionPoints: exception
* EnvConditions: system running normally
* CaseDescription: When the CommonEventListener does not exist, verify IPC return value.
*/
HWTEST_F(CommonEventUnSubscribeTest, UnSubscribe_007, TestSize.Level1)
{
CommonEventStubTest CommonEventStubTest;
MessageParcel data;
MessageParcel reply;
MessageOption option(MessageOption::TF_SYNC);
sptr<CommonEventListener> commonEventListener = nullptr;
data.WriteParcelable(commonEventListener);
int32_t ret = CommonEventStubTest.OnRemoteRequest(
static_cast<int32_t>(ICommonEvent::Message::CES_UNSUBSCRIBE_COMMON_EVENT), data, reply, option);
EXPECT_EQ(ERR_INVALID_VALUE, ret);
}
/*
* Feature: CommonEventManagerService
* Function: UnsubscribeCommonEvent
* SubFunction: IsReady
* FunctionPoints: exception
* EnvConditions: system running normally
* CaseDescription: When the CommonEventManagerService is not ready,
* verify UnsubscribeCommonEvent function return value.
*/
HWTEST_F(CommonEventUnSubscribeTest, UnSubscribe_008, TestSize.Level1)
{
DelayedSingleton<CommonEventManagerService>::GetInstance()->innerCommonEventManager_ = nullptr;
sptr<IRemoteObject> sp;
EXPECT_EQ(false, DelayedSingleton<CommonEventManagerService>::GetInstance()->UnsubscribeCommonEvent(sp));
}
/*
* Feature: InnerCommonEventManager
* Function: UnsubscribeCommonEvent
* SubFunction: NA
* FunctionPoints: exception
* EnvConditions: system running normally
* CaseDescription: When the CommonEventListener does not exist,
* verify UnsubscribeCommonEvent function return value.
*/
HWTEST_F(CommonEventUnSubscribeTest, UnSubscribe_009, TestSize.Level1)
{
std::shared_ptr<InnerCommonEventManager> innerCommonEventManager = std::make_shared<InnerCommonEventManager>();
sptr<IRemoteObject> sp(nullptr);
EXPECT_EQ(false, innerCommonEventManager->UnsubscribeCommonEvent(sp));
}
/*
* Feature: CommonEventSubscriberManager
* Function: RemoveSubscriber
* SubFunction: NA
* FunctionPoints: exception
* EnvConditions: system running normally
* CaseDescription: When the CommonEventListener does not exist,
* verify RemoveSubscriber function return value.
*/
HWTEST_F(CommonEventUnSubscribeTest, UnSubscribe_010, TestSize.Level1)
{
EXPECT_EQ(
ERR_INVALID_VALUE, DelayedSingleton<CommonEventSubscriberManager>::GetInstance()->RemoveSubscriber(nullptr));
}
/*
* Feature: CommonEventSubscriberManager
* Function: RemoveSubscriber
* SubFunction: NA
* FunctionPoints: exception
* EnvConditions: system running normally
* CaseDescription: When the death_ is not null,
* verify RemoveSubscriber function return value.
*/
HWTEST_F(CommonEventUnSubscribeTest, UnSubscribe_011, TestSize.Level1)
{
CommonEventUnSubscribeTest::SetMatchingSkillsWithEvent("event");
CommonEventSubscribeInfo subscriberInfo(matchingSkills_);
// make a subcriber object
std::shared_ptr<SubscriberTest> subscriberTest = std::make_shared<SubscriberTest>(subscriberInfo);
OHOS::sptr<CommonEventListener> commonEventListener = new CommonEventListener(subscriberTest);
DelayedSingleton<CommonEventSubscriberManager>::GetInstance()->death_ = nullptr;
EXPECT_EQ(
ERR_OK, DelayedSingleton<CommonEventSubscriberManager>::GetInstance()->RemoveSubscriber(commonEventListener));
}
@@ -0,0 +1,221 @@
/*
* 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.
*/
#define private public
#define protected public
#include "matching_skills.h"
#undef private
#undef protected
#include <gtest/gtest.h>
using namespace testing::ext;
using namespace OHOS::EventFwk;
using OHOS::Parcel;
static const int SET_COUNT = 1;
static const int MAX_COUNT = 100;
class MatchingSkillsTest : public testing::Test {
public:
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
void MatchingSkillsTest::SetUpTestCase(void)
{}
void MatchingSkillsTest::TearDownTestCase(void)
{}
void MatchingSkillsTest::SetUp(void)
{}
void MatchingSkillsTest::TearDown(void)
{}
/*
* Feature: MatchingSkills
* Function: AddEntity/GetEntity/CountEntities/HasEntity/RemoveEntity
* SubFunction: NA
* FunctionPoints: AddEntity/GetEntity
* EnvConditions: NA
* CaseDescription: Verify the function when after add entity can get entity
* and count entity is right,has entity and can success remove entity
*/
HWTEST_F(MatchingSkillsTest, MatchingSkills_Entity_001, TestSize.Level1)
{
MatchingSkills matchSkills;
std::string empty;
std::string entity = "event.unit.test";
matchSkills.AddEntity(entity);
matchSkills.AddEntity(entity);
EXPECT_EQ(SET_COUNT, matchSkills.CountEntities());
EXPECT_EQ(true, matchSkills.HasEntity(entity));
EXPECT_EQ(entity, matchSkills.GetEntity(0));
EXPECT_EQ(false, entity == matchSkills.GetEntity(MAX_COUNT));
matchSkills.RemoveEntity(entity);
matchSkills.RemoveEntity(entity);
EXPECT_EQ(0, matchSkills.CountEntities());
}
/*
* Feature: MatchingSkills
* Function: event
* SubFunction: NA
* FunctionPoints: AddEvent/GetEvent/CountEvent/HasEvent/RemoveEvent
* EnvConditions: NA
* CaseDescription: Verify the function when after add evnet can get event
* and count event is right,has event and can success remove event
*/
HWTEST_F(MatchingSkillsTest, MatchingSkills_Event_001, TestSize.Level1)
{
MatchingSkills matchSkills;
std::string empty;
std::string event = "event.unit.test";
matchSkills.AddEvent(event);
matchSkills.AddEvent(event);
EXPECT_EQ(true, matchSkills.HasEvent(event));
EXPECT_EQ(event, matchSkills.GetEvent(0));
EXPECT_EQ(false, event == matchSkills.GetEvent(SET_COUNT));
matchSkills.RemoveEvent(event);
matchSkills.RemoveEvent(event);
EXPECT_EQ(0, matchSkills.CountEvent());
}
/*
* Feature: MatchingSkills
* Function: scheme
* SubFunction: NA
* FunctionPoints: AddScheme/GetScheme/CountScheme/HasScheme/RemoveScheme
* EnvConditions: NA
* CaseDescription: Verify the function when after add scheme can get scheme
* and count scheme is right,has scheme and can success remove scheme
*/
HWTEST_F(MatchingSkillsTest, MatchingSkills_Scheme_001, TestSize.Level1)
{
MatchingSkills matchSkills;
std::string empty;
std::string shceme = "event.unit.test";
matchSkills.AddScheme(shceme);
matchSkills.AddScheme(shceme);
EXPECT_EQ(true, matchSkills.HasScheme(shceme));
EXPECT_EQ(shceme, matchSkills.GetScheme(0));
EXPECT_EQ(false, shceme == matchSkills.GetScheme(SET_COUNT));
matchSkills.RemoveScheme(shceme);
matchSkills.RemoveScheme(shceme);
EXPECT_EQ(0, matchSkills.CountSchemes());
}
/*
* Feature: MatchingSkills
* Function: Match Event
* SubFunction: NA
* FunctionPoints: Match Event
* EnvConditions: NA
* CaseDescription: Verify match event
*/
HWTEST_F(MatchingSkillsTest, MatchingSkills_MatchEvent_001, TestSize.Level1)
{
MatchingSkills matchSkills;
EXPECT_EQ(false, matchSkills.MatchEvent(""));
std::string event = "event.unit.test";
matchSkills.AddEvent(event);
EXPECT_EQ(true, matchSkills.MatchEvent(event));
}
/*
* Feature: MatchingSkills
* Function: Match entity
* SubFunction: NA
* FunctionPoints: Match entity
* EnvConditions: NA
* CaseDescription: Verify match entity
*/
HWTEST_F(MatchingSkillsTest, MatchingSkills_MatchEntity_001, TestSize.Level1)
{
MatchingSkills matchSkills;
std::vector<std::string> entities;
EXPECT_EQ(true, matchSkills.MatchEntity(entities));
std::string entity = "event.unit.test";
matchSkills.AddEntity(entity);
entities.emplace_back(entity);
EXPECT_EQ(true, matchSkills.MatchEntity(entities));
entities.emplace_back("entitydiffer");
EXPECT_EQ(false, matchSkills.MatchEntity(entities));
}
/*
* Feature: MatchingSkills
* Function: Match scheme
* SubFunction: NA
* FunctionPoints: Match scheme
* EnvConditions: NA
* CaseDescription: Verify match scheme
*/
HWTEST_F(MatchingSkillsTest, MatchingSkills_MatchScheme_001, TestSize.Level1)
{
MatchingSkills matchSkills;
EXPECT_EQ(true, matchSkills.MatchScheme(""));
std::string scheme = "action.system.event";
matchSkills.AddScheme(scheme);
EXPECT_EQ(true, matchSkills.MatchScheme(scheme));
EXPECT_EQ(false, matchSkills.MatchScheme("schemediffer"));
}
/*
* Feature: Match
* Function: Match
* SubFunction: NA
* FunctionPoints: Match
* EnvConditions: NA
* CaseDescription: Verify match
*/
HWTEST_F(MatchingSkillsTest, MatchingSkills_Match_001, TestSize.Level1)
{
MatchingSkills matchSkills;
std::string event = "event.unit.test";
matchSkills.AddEvent(event);
std::string entity;
matchSkills.AddEntity(entity);
Want want;
want.AddEntity(entity);
want.SetAction(event);
EXPECT_EQ(true, matchSkills.Match(want));
}
+27
View File
@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- 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.
-->
<info>
<process>foundation</process>
<systemability>
<name>3299</name>
<libpath>/system/lib64/libcesfwk_services.z.so</libpath>
<!--<depend></depend> --> <!-- Declare the name of system abilities which the system ability depends on, Note that one dependency uses 1 line. If there are dependencies, it needs to check if all those dependencies are available in service manager before starting the system ability. -->
<!--<depend-time-out></depend-time-out> --> <!-- Check all dependencies are available before the timeout period ended. The MAX_DEPENDENCY_TIMEOUT is 60s. -->
<run-on-create>true</run-on-create>
<distributed>false</distributed>
<dump-level>1</dump-level>
</systemability>
</info>
+20
View File
@@ -0,0 +1,20 @@
# 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/sa_profile/sa_profile.gni")
ohos_sa_profile("event_sa_profile") {
sources = [ "3299.xml" ]
part_name = "ces_standard"
}
+95
View File
@@ -0,0 +1,95 @@
# 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("//base/notification/ces_standard/event.gni")
import("//build/ohos.gni")
CESFWK_INNERKITS_DIR = "//base/notification/ces_standard/cesfwk/innerkits"
CESFWK_KITS_DIR = "//base/notification/ces_standard/cesfwk/kits/native"
CESFWK_SERVICES_DIR = "//base/notification/ces_standard/cesfwk/services"
cflags = []
config("cesfwk_services_config") {
visibility = [ ":*" ]
include_dirs = []
if (target_cpu == "arm") {
cflags += [ "-DBINDER_IPC_32BIT" ]
}
defines = [
"APP_LOG_TAG = \"CesFwk\"",
"LOG_DOMAIN = 0xD002200",
]
}
config("cesfwk_services_public_config") {
visibility = [ ":*" ]
include_dirs = [
"${CESFWK_INNERKITS_DIR}/include",
"${CESFWK_KITS_DIR}/include",
"${CESFWK_SERVICES_DIR}/include",
"//foundation/aafwk/standard/interfaces/innerkits/base/include/",
"//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include/",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include",
"//base/notification/ces_standard/common/log/include",
"//utils/native/base/include",
"//utils/system/safwk/native/include",
]
}
ohos_shared_library("cesfwk_services") {
sources = [
"${CESFWK_SERVICES_DIR}/src/bms_death_recipient.cpp",
"${CESFWK_SERVICES_DIR}/src/bundle_manager_helper.cpp",
"${CESFWK_SERVICES_DIR}/src/common_event_control_manager.cpp",
"${CESFWK_SERVICES_DIR}/src/common_event_manager_service.cpp",
"${CESFWK_SERVICES_DIR}/src/common_event_permission_manager.cpp",
"${CESFWK_SERVICES_DIR}/src/common_event_sticky_manager.cpp",
"${CESFWK_SERVICES_DIR}/src/common_event_subscriber_manager.cpp",
"${CESFWK_SERVICES_DIR}/src/inner_common_event_manager.cpp",
"${CESFWK_SERVICES_DIR}/src/ordered_event_handler.cpp",
"${CESFWK_SERVICES_DIR}/src/publish_manager.cpp",
"${CESFWK_SERVICES_DIR}/src/subscriber_death_recipient.cpp",
"${CESFWK_SERVICES_DIR}/src/system_time.cpp",
]
configs = [ ":cesfwk_services_config" ]
public_configs = [ ":cesfwk_services_public_config" ]
deps = [
"${CESFWK_INNERKITS_DIR}:cesfwk_innerkits",
"${CESFWK_KITS_DIR}:cesfwk_kits",
"${event_common_path}:libevent_common",
"//foundation/aafwk/standard/interfaces/innerkits/want:want",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler",
"//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//utils/native/base:utils",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
]
subsystem_name = "notification"
part_name = "ces_standard"
}
@@ -0,0 +1,30 @@
/*
* 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_EVENT_CESFWK_SERVICES_INCLUDE_BMS_DEATH_RECIPIENT_H
#define FOUNDATION_EVENT_CESFWK_SERVICES_INCLUDE_BMS_DEATH_RECIPIENT_H
#include "iremote_object.h"
namespace OHOS {
namespace EventFwk {
class BMSDeathRecipient : public IRemoteObject::DeathRecipient {
public:
virtual void OnRemoteDied(const wptr<IRemoteObject> &wptrDeath);
};
} // namespace EventFwk
} // namespace OHOS
#endif // FOUNDATION_EVENT_CESFWK_SERVICES_INCLUDE_BMS_DEATH_RECIPIENT_H
@@ -0,0 +1,55 @@
/*
* 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_EVENT_CESFWK_SERVICES_INCLUDE_BUNDLE_MANAGER_HELPER_H
#define FOUNDATION_EVENT_CESFWK_SERVICES_INCLUDE_BUNDLE_MANAGER_HELPER_H
#include <string>
#include "bms_death_recipient.h"
#include "bundle_mgr_interface.h"
#include "iremote_object.h"
#include "refbase.h"
#include "singleton.h"
namespace OHOS {
namespace EventFwk {
class BundleManagerHelper : public DelayedSingleton<BundleManagerHelper> {
public:
using IBundleMgr = OHOS::AppExecFwk::IBundleMgr;
BundleManagerHelper();
virtual ~BundleManagerHelper() override;
bool CheckIsSystemAppByUid(uid_t uid);
std::string GetBundleName(int uid);
bool CheckPermission(const std::string &bundleName, const std::string &permission);
void ClearBundleManagerHelper();
private:
bool GetBundleMgrProxy();
private:
sptr<IBundleMgr> sptrBundleMgr_;
std::mutex mutex_;
sptr<BMSDeathRecipient> bmsDeath_;
};
} // namespace EventFwk
} // namespace OHOS
#endif // FOUNDATION_EVENT_CESFWK_SERVICES_INCLUDE_BUNDLE_MANAGER_HELPER_H
+97
View File
@@ -0,0 +1,97 @@
/*
* 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_EVENT_CESFWK_SERVICES_INCLUDE_COMMON_EVENT_CONTROL_MANAGER_H
#define FOUNDATION_EVENT_CESFWK_SERVICES_INCLUDE_COMMON_EVENT_CONTROL_MANAGER_H
#include "common_event_data.h"
#include "common_event_permission_manager.h"
#include "common_event_publish_info.h"
#include "common_event_record.h"
#include "ordered_event_handler.h"
#include "ordered_event_record.h"
namespace OHOS {
namespace EventFwk {
class CommonEventControlManager : public std::enable_shared_from_this<CommonEventControlManager> {
public:
CommonEventControlManager();
~CommonEventControlManager();
bool PublishCommonEvent(const CommonEventRecord &eventRecord, const sptr<IRemoteObject> &commonEventListener);
std::shared_ptr<OrderedEventRecord> GetMatchingOrderedReceiver(sptr<IRemoteObject> proxy);
bool FinishReceiverAction(std::shared_ptr<OrderedEventRecord> recordPtr, const int &code,
const std::string &receiverData, const bool &abortEvent);
void CurrentOrderedEventTimeout(bool isFromMsg);
void ProcessNextOrderedEvent(bool isSendMsg);
bool PublishFreezeCommonEvent(const uid_t &uid);
private:
bool ProcessUnorderedEvent(const CommonEventRecord &eventRecord);
bool GetUnorderedEventHandler();
bool NotifyUnorderedEvent(const CommonEventRecord &eventRecord);
bool ProcessOrderedEvent(
const CommonEventRecord &commonEventRecord, const sptr<IRemoteObject> &commonEventListener);
bool GetOrderedEventHandler();
bool EnqueueOrderedRecord(const std::shared_ptr<OrderedEventRecord> &eventRecordPtr);
bool ScheduleOrderedCommonEvent();
bool NotifyOrderedEvent(std::shared_ptr<OrderedEventRecord> &eventRecordPtr, int index);
bool SetTimeout(int64_t timeoutTime);
bool CancelTimeout();
bool FinishReceiverLocked(std::shared_ptr<OrderedEventRecord> recordPtr, const int &code,
const std::string &receiverData, const bool &abortEvent);
int CheckPermission(const EventSubscriberRecord &subscriberRecord, const CommonEventRecord &eventRecord);
bool CheckSubcriberPermission(const Permission &permission, const EventSubscriberRecord &subscriberRecord);
void SetTime(int recIdx, std::shared_ptr<OrderedEventRecord> &sp, bool timeoutMessage);
void CheckSubscriberRequiredPermission(const std::string &subscriberRequiredPermission,
const CommonEventRecord &eventRecord, const EventSubscriberRecord &subscriberRecord, bool &skip);
void CheckPublisherRequiredPermissions(const std::vector<std::string> &publisherRequiredPermissions,
const EventSubscriberRecord &subscriberRecord, const CommonEventRecord &eventRecord, bool &skip);
bool NotifyFreezeEvents(const EventSubscriberRecord &subscriberRecord, const CommonEventRecord &eventRecord);
private:
std::shared_ptr<EventHandler> handler_;
std::shared_ptr<OrderedEventHandler> handlerOrdered_;
std::vector<std::shared_ptr<OrderedEventRecord>> orderedEventQueue_;
bool pendingTimeoutMessage_;
bool scheduled_;
const int64_t TIMEOUT; // How long we allow a receiver to run before giving up on it. Unit: ms
};
} // namespace EventFwk
} // namespace OHOS
#endif // FOUNDATION_EVENT_CESFWK_SERVICES_INCLUDE_COMMON_EVENT_CONTROL_MANAGER_H
@@ -0,0 +1,75 @@
/*
* 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_EVENT_CESFWK_SERVICES_INCLUDE_COMMON_EVENT_MANAGER_SERVICE_H
#define FOUNDATION_EVENT_CESFWK_SERVICES_INCLUDE_COMMON_EVENT_MANAGER_SERVICE_H
#include "common_event_stub.h"
#include "event_handler.h"
#include "inner_common_event_manager.h"
#include "nocopyable.h"
#include "system_ability.h"
namespace OHOS {
namespace EventFwk {
enum class ServiceRunningState { STATE_NOT_START, STATE_RUNNING };
class CommonEventManagerService : public SystemAbility, public CommonEventStub {
public:
DECLEAR_SYSTEM_ABILITY(CommonEventManagerService);
CommonEventManagerService();
virtual ~CommonEventManagerService() override;
virtual bool PublishCommonEvent(const CommonEventData &event, const CommonEventPublishInfo &publishinfo,
const sptr<IRemoteObject> &commonEventListener) override;
virtual bool SubscribeCommonEvent(
const CommonEventSubscribeInfo &subscriberInfo, const sptr<IRemoteObject> &commonEventListener) override;
virtual bool UnsubscribeCommonEvent(const sptr<IRemoteObject> &commonEventListener) override;
virtual bool GetStickyCommonEvent(const std::string &event, CommonEventData &eventData) override;
virtual bool DumpState(const std::string &event, std::vector<std::string> &state) override;
virtual bool FinishReceiver(const sptr<IRemoteObject> &proxy, const int &code, const std::string &receiverData,
const bool &abortEvent) override;
virtual bool Freeze(const uid_t &uid) override;
virtual bool Unfreeze(const uid_t &uid) override;
private:
ErrCode Init();
// the function that overrided from SystemAbility
virtual void OnStart() override;
virtual void OnStop() override;
bool IsReady() const;
private:
std::shared_ptr<InnerCommonEventManager> innerCommonEventManager_;
ServiceRunningState serviceRunningState_ = ServiceRunningState::STATE_NOT_START;
std::shared_ptr<EventRunner> runner_;
std::shared_ptr<EventHandler> handler_;
DISALLOW_COPY_AND_MOVE(CommonEventManagerService);
};
} // namespace EventFwk
} // namespace OHOS
#endif // FOUNDATION_EVENT_CESFWK_SERVICES_INCLUDE_COMMON_EVENT_MANAGER_SERVICE_H
@@ -0,0 +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_EVENT_CESFWK_SERVICES_INCLUDE_COMMON_EVENT_MATCH_PERMISSION_H
#define FOUNDATION_EVENT_CESFWK_SERVICES_INCLUDE_COMMON_EVENT_MATCH_PERMISSION_H
#include <map>
#include <string>
#include <vector>
#include "singleton.h"
namespace OHOS {
namespace EventFwk {
struct Permission {
enum permissionState {
DEFAULT,
AND,
OR,
} state;
std::vector<std::string> names;
Permission() : state(DEFAULT)
{}
};
class CommonEventPermissionManager : public DelayedSingleton<CommonEventPermissionManager> {
public:
CommonEventPermissionManager();
~CommonEventPermissionManager() = default;
void Init();
Permission GetEventPermission(std::string event);
private:
std::multimap<std::string, Permission> multimap_;
};
} // namespace EventFwk
} // namespace OHOS
#endif // FOUNDATION_EVENT_CESFWK_SERVICES_INCLUDE_COMMON_EVENT_MATCH_PERMISSION_H
@@ -0,0 +1,39 @@
/*
* 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_EVENT_CESFWK_SERVICES_INCLUDE_COMMON_EVENT_RECORD_H
#define FOUNDATION_EVENT_CESFWK_SERVICES_INCLUDE_COMMON_EVENT_RECORD_H
#include "common_event_data.h"
#include "common_event_publish_info.h"
namespace OHOS {
namespace EventFwk {
struct CommonEventRecord {
std::shared_ptr<CommonEventData> commonEventData;
std::shared_ptr<CommonEventPublishInfo> publishInfo;
struct tm recordTime;
pid_t pid;
uid_t uid;
std::string bundleName;
bool isSystemEvent;
CommonEventRecord() : commonEventData(nullptr), publishInfo(nullptr), pid(0), uid(0), isSystemEvent(false)
{}
};
} // namespace EventFwk
} // namespace OHOS
#endif // FOUNDATION_EVENT_CESFWK_SERVICES_INCLUDE_COMMON_EVENT_RECORD_H
@@ -0,0 +1,62 @@
/*
* 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_EVENT_CESFWK_SERVICES_INCLUDE_COMMON_EVENT_STICKY_MANAGER_H
#define FOUNDATION_EVENT_CESFWK_SERVICES_INCLUDE_COMMON_EVENT_STICKY_MANAGER_H
#include <string>
#include <map>
#include "common_event_data.h"
#include "common_event_publish_info.h"
#include "common_event_record.h"
#include "common_event_subscribe_info.h"
#include "singleton.h"
namespace OHOS {
namespace EventFwk {
class CommonEventStickyManager : public DelayedSingleton<CommonEventStickyManager> {
public:
using CommonEventRecordPtr = std::shared_ptr<CommonEventRecord>;
using CommonEventDataPtr = std::shared_ptr<CommonEventData>;
using CommonEventPublishInfoPtr = std::shared_ptr<CommonEventPublishInfo>;
using SubscribeInfoPtr = std::shared_ptr<CommonEventSubscribeInfo>;
int FindStickyEvents(const SubscribeInfoPtr &subscriberInfo, std::vector<CommonEventRecordPtr> &commonEventRecords);
bool GetStickyCommonEvent(const std::string &event, CommonEventData &eventData);
int UpdateStickyEvent(const CommonEventRecord &eventRecord);
void DumpState(const std::string &event, std::vector<std::string> &state);
private:
void FindStickyEventsLocked(
const std::vector<std::string> &events, std::vector<CommonEventRecordPtr> &commonEventRecords);
bool GetStickyCommonEventLocked(const std::string &event, CommonEventData &eventData);
int UpdateStickyEventLocked(const std::string &event, const CommonEventRecordPtr &record);
void GetStickyCommonEventRecordsLocked(const std::string &event, std::vector<CommonEventRecordPtr> &records);
private:
std::mutex mutex_;
std::map<std::string, CommonEventRecordPtr> commonEventRecords_;
};
} // namespace EventFwk
} // namespace OHOS
#endif // FOUNDATION_EVENT_CESFWK_SERVICES_INCLUDE_COMMON_EVENT_STICKY_MANAGER_H
@@ -0,0 +1,111 @@
/*
* 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_EVENT_CESFWK_SERVICES_INCLUDE_COMMON_EVENT_SUBSCRIBER_MANAGER_H
#define FOUNDATION_EVENT_CESFWK_SERVICES_INCLUDE_COMMON_EVENT_SUBSCRIBER_MANAGER_H
#include <string>
#include <map>
#include <set>
#include <vector>
#include "singleton.h"
#include "refbase.h"
#include "iremote_object.h"
#include "want.h"
#include "common_event_record.h"
#include "common_event_subscribe_info.h"
#include "subscriber_death_recipient.h"
namespace OHOS {
namespace EventFwk {
struct EventSubscriberRecord {
std::shared_ptr<CommonEventSubscribeInfo> eventSubscriberInfo;
sptr<IRemoteObject> commonEventListener;
struct tm recordTime;
pid_t pid;
uid_t uid;
std::string bundleName;
bool isFreeze;
int64_t freezeTime;
EventSubscriberRecord()
: eventSubscriberInfo(nullptr), commonEventListener(nullptr), pid(0), uid(0), isFreeze(false), freezeTime(0)
{}
};
struct FrozenEventRecord {
std::shared_ptr<EventSubscriberRecord> subscriberRecordPtr;
std::vector<std::shared_ptr<CommonEventRecord>> eventRecordPtrs;
FrozenEventRecord() : subscriberRecordPtr(nullptr)
{}
};
inline bool operator<(const std::shared_ptr<EventSubscriberRecord> &a, const std::shared_ptr<EventSubscriberRecord> &b)
{
return a->eventSubscriberInfo->GetPriority() > b->eventSubscriberInfo->GetPriority();
}
using SubscriberRecordPtr = std::shared_ptr<EventSubscriberRecord>;
using SubscribeInfoPtr = std::shared_ptr<CommonEventSubscribeInfo>;
using EventRecordPtr = std::shared_ptr<CommonEventRecord>;
class CommonEventSubscriberManager : public DelayedSingleton<CommonEventSubscriberManager> {
public:
CommonEventSubscriberManager();
virtual ~CommonEventSubscriberManager() override;
int InsertSubscriber(const SubscribeInfoPtr &eventSubscriberInfo, const sptr<IRemoteObject> &commonEventListener,
const struct tm &recordTime, const pid_t &pid, const uid_t &uid, const std::string &bundleName);
int RemoveSubscriber(const sptr<IRemoteObject> &commonEventListener);
std::vector<SubscriberRecordPtr> GetSubscriberRecords(const Want &want);
void UpdateFreezeInfo(const uid_t &uid, const bool &freezeState, const int64_t &freezeTime = 0);
void InsertFrozenEvents(const SubscriberRecordPtr &eventListener, const CommonEventRecord &eventRecord);
std::map<SubscriberRecordPtr, std::vector<EventRecordPtr>> GetFrozenEvents(const uid_t &uid);
void DumpState(const std::string &event, std::vector<std::string> &state);
private:
int InsertSubscriberRecordLocked(const std::vector<std::string> &events, const SubscriberRecordPtr &record);
int RemoveSubscriberRecordLocked(const sptr<IRemoteObject> &commonEventListener);
void GetSubscriberRecordsByWantLocked(const Want &want, std::vector<SubscriberRecordPtr> &records);
void GetSubscriberRecordsByEventLocked(const std::string &event, std::vector<SubscriberRecordPtr> &records);
void RemoveFrozenEventsBySubscriber(const SubscriberRecordPtr &subscriberRecord);
void RemoveFrozenEvents(const uid_t &uid);
private:
std::mutex mutex_;
sptr<IRemoteObject::DeathRecipient> death_;
std::map<std::string, std::multiset<SubscriberRecordPtr>> eventSubscribers_;
std::vector<SubscriberRecordPtr> subscribers_;
std::map<uid_t, std::map<SubscriberRecordPtr, std::vector<EventRecordPtr>>> frozenEvents_;
const time_t FREEZE_EVENT_TIMEOUT;
};
} // namespace EventFwk
} // namespace OHOS
#endif // FOUNDATION_EVENT_CESFWK_SERVICES_INCLUDE_COMMON_EVENT_SUBSCRIBER_MANAGER_H
@@ -0,0 +1,61 @@
/*
* 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_EVENT_CESFWK_SERVICES_INCLUDE_INNER_COMMON_EVENT_MANAGER_H
#define FOUNDATION_EVENT_CESFWK_SERVICES_INCLUDE_INNER_COMMON_EVENT_MANAGER_H
#include "common_event_control_manager.h"
#include "icommon_event.h"
namespace OHOS {
namespace EventFwk {
class InnerCommonEventManager {
public:
InnerCommonEventManager();
virtual ~InnerCommonEventManager(){};
bool PublishCommonEvent(const CommonEventData &data, const CommonEventPublishInfo &publishinfo,
const sptr<IRemoteObject> &commonEventListener, const struct tm &recordTime, const pid_t &pid, const uid_t &uid,
const std::string &bundleName);
bool SubscribeCommonEvent(const CommonEventSubscribeInfo &subscriberInfo,
const sptr<IRemoteObject> &commonEventListener, const struct tm &recordTime, const pid_t &pid, const uid_t &uid,
const std::string &bundleName);
bool UnsubscribeCommonEvent(sptr<IRemoteObject> &commonEventListener);
bool GetStickyCommonEvent(const std::string &event, CommonEventData &eventData);
void DumpState(const std::string &event, std::vector<std::string> &state);
void FinishReceiver(
const sptr<IRemoteObject> &proxy, const int &code, const std::string &receiverData, const bool &abortEvent);
bool Freeze(const uid_t &uid);
bool Unfreeze(const uid_t &uid);
private:
int64_t GetNowSysTime();
private:
std::shared_ptr<CommonEventControlManager> controlPtr_;
DISALLOW_COPY_AND_MOVE(InnerCommonEventManager);
};
} // namespace EventFwk
} // namespace OHOS
#endif // FOUNDATION_EVENT_CESFWK_SERVICES_INCLUDE_INNER_COMMON_EVENT_MANAGER_H
@@ -0,0 +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_EVENT_CESFWK_SERVICES_INCLUDE_ORDERED_EVENT_HANDLER_H
#define FOUNDATION_EVENT_CESFWK_SERVICES_INCLUDE_ORDERED_EVENT_HANDLER_H
#include "event_handler.h"
namespace OHOS {
namespace EventFwk {
using EventHandler = OHOS::AppExecFwk::EventHandler;
using EventRunner = OHOS::AppExecFwk::EventRunner;
using InnerEvent = OHOS::AppExecFwk::InnerEvent;
class CommonEventControlManager;
class OrderedEventHandler : public EventHandler {
public:
OrderedEventHandler(
const std::shared_ptr<EventRunner> &runner, const std::shared_ptr<CommonEventControlManager> &controlManager);
virtual ~OrderedEventHandler() override;
virtual void ProcessEvent(const InnerEvent::Pointer &event) override;
enum {
ORDERED_EVENT_START = 1,
ORDERED_EVENT_TIMEOUT,
};
private:
std::shared_ptr<CommonEventControlManager> controlManager_;
};
} // namespace EventFwk
} // namespace OHOS
#endif // FOUNDATION_EVENT_CESFWK_SERVICES_INCLUDE_ORDERED_EVENT_HANDLER_H
+76
View File
@@ -0,0 +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.
*/
#ifndef FOUNDATION_EVENT_CESFWK_SERVICES_INCLUDE_ORDERED_EVENT_RECORD_H
#define FOUNDATION_EVENT_CESFWK_SERVICES_INCLUDE_ORDERED_EVENT_RECORD_H
#include "common_event_record.h"
#include "common_event_subscriber_manager.h"
namespace OHOS {
namespace EventFwk {
struct OrderedEventRecord : public CommonEventRecord {
enum EventState_ {
IDLE = 0,
RECEIVEING,
RECEIVED,
};
enum DeliveryState_ {
DELIVERY_PENDING = 0,
DELIVERY_DELIVERED,
DELIVERY_SKIPPED,
DELIVERY_TIMEOUT,
};
std::vector<std::shared_ptr<EventSubscriberRecord>> receivers;
sptr<IRemoteObject> resultTo;
sptr<IRemoteObject> curReceiver;
std::vector<int> deliveryState;
int enqueueClockTime;
int64_t dispatchTime;
int64_t receiverTime;
int64_t finishTime;
int nextReceiver;
int state;
bool resultAbort;
OrderedEventRecord()
: resultTo(nullptr),
curReceiver(nullptr),
enqueueClockTime(0),
dispatchTime(0),
receiverTime(0),
finishTime(0),
nextReceiver(0),
state(0),
resultAbort(false)
{}
inline void FillCommonEventRecord(const CommonEventRecord &commonEventRecord)
{
commonEventData = commonEventRecord.commonEventData;
publishInfo = commonEventRecord.publishInfo;
recordTime = commonEventRecord.recordTime;
pid = commonEventRecord.pid;
uid = commonEventRecord.uid;
bundleName = commonEventRecord.bundleName;
isSystemEvent = commonEventRecord.isSystemEvent;
}
};
} // namespace EventFwk
} // namespace OHOS
#endif // FOUNDATION_EVENT_CESFWK_SERVICES_INCLUDE_ORDERED_EVENT_RECORD_H
+41
View File
@@ -0,0 +1,41 @@
/*
* 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_EVENT_CESFWK_SERVICES_INCLUDE_PUBLIC_MANAGER_H
#define FOUNDATION_EVENT_CESFWK_SERVICES_INCLUDE_PUBLIC_MANAGER_H
#include <stdint.h>
#include "singleton.h"
namespace OHOS {
namespace EventFwk {
class PublishManager : public DelayedSingleton<PublishManager> {
public:
PublishManager();
~PublishManager();
bool CheckValid();
private:
int64_t lastPublishTime_;
int publishNum_;
const int floodAttachMax_;
const int floodAttachIntervalMax_;
};
} // namespace EventFwk
} // namespace OHOS
#endif // FOUNDATION_EVENT_CESFWK_SERVICES_INCLUDE_PUBLIC_MANAGER_H
@@ -0,0 +1,34 @@
/*
* 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 SUBSCRIBER_DEATH_RECIPIENT_H
#define SUBSCRIBER_DEATH_RECIPIENT_H
#include "iremote_object.h"
namespace OHOS {
namespace EventFwk {
class SubscriberDeathRecipient : public IRemoteObject::DeathRecipient {
public:
SubscriberDeathRecipient() = default;
virtual ~SubscriberDeathRecipient() = default;
virtual void OnRemoteDied(const wptr<IRemoteObject> &remote);
};
} // namespace EventFwk
} // namespace OHOS
#endif // !defined(SUBSCRIBER_DEATH_RECIPIENT_H)
+30
View File
@@ -0,0 +1,30 @@
/*
* 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_EVENT_CESFWK_SERVICES_INCLUDE_SYSTEM_TIME_H
#define FOUNDATION_EVENT_CESFWK_SERVICES_INCLUDE_SYSTEM_TIME_H
#include "singleton.h"
namespace OHOS {
namespace EventFwk {
class SystemTime {
public:
static int64_t GetNowSysTime();
};
} // namespace EventFwk
} // namespace OHOS
#endif // FOUNDATION_EVENT_CESFWK_SERVICES_INCLUDE_SYSTEM_TIME_H
@@ -0,0 +1,43 @@
/*
* 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 "bms_death_recipient.h"
#include "bundle_manager_helper.h"
#include "event_log_wrapper.h"
#include "singleton.h"
namespace OHOS {
namespace EventFwk {
void BMSDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &wptrDeath)
{
EVENT_LOGI("bundle manager service died, remove the proxy object");
if (wptrDeath == nullptr) {
EVENT_LOGE("wptrDeath is null");
return;
}
sptr<IRemoteObject> object = wptrDeath.promote();
if (!object) {
EVENT_LOGE("object is null");
return;
}
DelayedSingleton<BundleManagerHelper>::GetInstance()->ClearBundleManagerHelper();
return;
}
} // namespace EventFwk
} // namespace OHOS
@@ -0,0 +1,134 @@
/*
* 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 "bundle_manager_helper.h"
#include "bundle_constants.h"
#include "errors.h"
#include "event_log_wrapper.h"
#include "iservice_registry.h"
#include "system_ability_definition.h"
namespace OHOS {
namespace EventFwk {
using namespace OHOS::AppExecFwk::Constants;
BundleManagerHelper::BundleManagerHelper() : sptrBundleMgr_(nullptr), bmsDeath_(nullptr)
{}
BundleManagerHelper::~BundleManagerHelper()
{}
std::string BundleManagerHelper::GetBundleName(int uid)
{
EVENT_LOGI("enter");
std::lock_guard<std::mutex> lock(mutex_);
std::string bundleName = "";
if (!GetBundleMgrProxy()) {
return bundleName;
}
sptrBundleMgr_->GetBundleNameForUid(uid, bundleName);
return bundleName;
}
bool BundleManagerHelper::CheckIsSystemAppByUid(uid_t uid)
{
EVENT_LOGI("enter");
std::lock_guard<std::mutex> lock(mutex_);
bool isSystemApp = false;
if (!GetBundleMgrProxy()) {
return isSystemApp;
}
isSystemApp = sptrBundleMgr_->CheckIsSystemAppByUid(uid);
return isSystemApp;
}
bool BundleManagerHelper::CheckPermission(const std::string &bundleName, const std::string &permission)
{
EVENT_LOGI("enter");
std::lock_guard<std::mutex> lock(mutex_);
if (!GetBundleMgrProxy()) {
return false;
}
int ret = sptrBundleMgr_->CheckPermission(bundleName, permission);
if (ret != PERMISSION_GRANTED) {
return false;
}
return true;
}
bool BundleManagerHelper::GetBundleMgrProxy()
{
EVENT_LOGD("enter");
if (!sptrBundleMgr_) {
sptr<ISystemAbilityManager> systemAbilityManager =
SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (!systemAbilityManager) {
EVENT_LOGE("Failed to get system ability mgr.");
return false;
}
sptr<IRemoteObject> remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
if (!remoteObject) {
EVENT_LOGE("Failed to get bundle manager service.");
return false;
}
sptrBundleMgr_ = iface_cast<IBundleMgr>(remoteObject);
if ((!sptrBundleMgr_) || (!sptrBundleMgr_->AsObject())) {
EVENT_LOGE("Failed to get system bundle manager services ability");
return false;
}
bmsDeath_ = new BMSDeathRecipient();
if (!bmsDeath_) {
EVENT_LOGE("Failed to create death Recipient ptr BMSDeathRecipient");
return false;
}
if (!sptrBundleMgr_->AsObject()->AddDeathRecipient(bmsDeath_)) {
EVENT_LOGE("Failed to add death recipient");
return false;
}
}
return true;
}
void BundleManagerHelper::ClearBundleManagerHelper()
{
EVENT_LOGI("enter");
std::lock_guard<std::mutex> lock(mutex_);
if ((sptrBundleMgr_ != nullptr) && (sptrBundleMgr_->AsObject() != nullptr)) {
sptrBundleMgr_->AsObject()->RemoveDeathRecipient(bmsDeath_);
}
sptrBundleMgr_ = nullptr;
}
} // namespace EventFwk
} // namespace OHOS
+630
View File
@@ -0,0 +1,630 @@
/*
* 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 "common_event_control_manager.h"
#include "bundle_manager_helper.h"
#include "common_event_subscriber_manager.h"
#include "datetime_ex.h"
#include "event_log_wrapper.h"
#include "ievent_receive.h"
#include "system_time.h"
namespace OHOS {
namespace EventFwk {
#define TENSECONDS 10000
using frozenRecords = std::map<std::shared_ptr<EventSubscriberRecord>, std::vector<std::shared_ptr<CommonEventRecord>>>;
CommonEventControlManager::CommonEventControlManager()
: handler_(nullptr), handlerOrdered_(nullptr), pendingTimeoutMessage_(false), scheduled_(false), TIMEOUT(TENSECONDS)
{
EVENT_LOGD("enter");
}
CommonEventControlManager::~CommonEventControlManager()
{
EVENT_LOGD("enter");
}
bool CommonEventControlManager::PublishCommonEvent(
const CommonEventRecord &eventRecord, const sptr<IRemoteObject> &commonEventListener)
{
EVENT_LOGI("enter");
bool ret = false;
if (!eventRecord.publishInfo->IsOrdered()) {
ret = ProcessUnorderedEvent(eventRecord);
} else {
ret = ProcessOrderedEvent(eventRecord, commonEventListener);
}
return ret;
}
bool CommonEventControlManager::PublishFreezeCommonEvent(const uid_t &uid)
{
EVENT_LOGI("enter");
if (!GetUnorderedEventHandler()) {
return false;
}
std::shared_ptr<CommonEventSubscriberManager> spinstance =
DelayedSingleton<CommonEventSubscriberManager>::GetInstance();
frozenRecords frozenEventRecords = spinstance->GetFrozenEvents(uid);
EVENT_LOGD("frozenEventRecords size: %{public}d", frozenEventRecords.size());
for (auto record : frozenEventRecords) {
EVENT_LOGD("CommonEventRecord size: %{public}d", record.second.size());
for (auto vec : record.second) {
EVENT_LOGD("subscriber proxy: %{public}p", &(record.first->commonEventListener));
std::function<void()> innerCallback =
std::bind(&CommonEventControlManager::NotifyFreezeEvents, this, *(record.first), *vec);
handler_->PostImmediateTask(innerCallback);
}
}
return true;
}
bool CommonEventControlManager::NotifyFreezeEvents(
const EventSubscriberRecord &subscriberRecord, const CommonEventRecord &eventRecord)
{
EVENT_LOGI("enter");
EVENT_LOGD("subscriber proxy: %{public}p", &subscriberRecord.commonEventListener);
EVENT_LOGD("subscriber uid: %{public}d", subscriberRecord.uid);
EVENT_LOGD("subscriber isFreeze: %{public}d", subscriberRecord.isFreeze);
EVENT_LOGD("subscriber freezeTime: %{public}lld", subscriberRecord.freezeTime);
EVENT_LOGD("CommonEvent Action: %{public}s", eventRecord.commonEventData->GetWant().GetAction().c_str());
EVENT_LOGD("CommonEvent Type: %{public}s", eventRecord.commonEventData->GetWant().GetType().c_str());
sptr<IEventReceive> commonEventListenerProxy = iface_cast<IEventReceive>(subscriberRecord.commonEventListener);
if (!commonEventListenerProxy) {
EVENT_LOGE("Fail to get IEventReceive proxy");
return false;
}
int ret = CheckPermission(subscriberRecord, eventRecord);
if (ret != OrderedEventRecord::DELIVERY_DELIVERED) {
EVENT_LOGE("check permission is failed");
return false;
}
commonEventListenerProxy->NotifyEvent(*(eventRecord.commonEventData), false, eventRecord.publishInfo->IsSticky());
return true;
}
bool CommonEventControlManager::GetUnorderedEventHandler()
{
if (!handler_) {
handler_ = std::make_shared<EventHandler>(EventRunner::Create());
if (!handler_) {
EVENT_LOGE("Failed to create UnorderedEventHandler");
return false;
}
}
return true;
}
bool CommonEventControlManager::NotifyUnorderedEvent(const CommonEventRecord &eventRecord)
{
EVENT_LOGI("enter");
std::shared_ptr<CommonEventSubscriberManager> spinstance =
DelayedSingleton<CommonEventSubscriberManager>::GetInstance();
for (auto vec : spinstance->GetSubscriberRecords(eventRecord.commonEventData->GetWant())) {
EVENT_LOGD("vec->uid: %{public}d", vec->uid);
EVENT_LOGD("vec->isFreeze: %{public}d", vec->isFreeze);
if (vec->isFreeze) {
DelayedSingleton<CommonEventSubscriberManager>::GetInstance()->InsertFrozenEvents(vec, eventRecord);
} else {
sptr<IEventReceive> commonEventListenerProxy = iface_cast<IEventReceive>(vec->commonEventListener);
if (!commonEventListenerProxy) {
EVENT_LOGE("Failed to get IEventReceive proxy");
continue;
}
int ret = CheckPermission(*vec, eventRecord);
if (ret == OrderedEventRecord::DELIVERY_DELIVERED) {
commonEventListenerProxy->NotifyEvent(
*(eventRecord.commonEventData), false, eventRecord.publishInfo->IsSticky());
}
}
}
return true;
}
bool CommonEventControlManager::ProcessUnorderedEvent(const CommonEventRecord &eventRecord)
{
EVENT_LOGI("enter");
bool ret = false;
if (!GetUnorderedEventHandler()) {
return ret;
}
std::function<void()> innerCallback =
std::bind(&CommonEventControlManager::NotifyUnorderedEvent, this, eventRecord);
if (eventRecord.isSystemEvent) {
ret = handler_->PostImmediateTask(innerCallback);
} else {
ret = handler_->PostTask(innerCallback);
}
return ret;
}
std::shared_ptr<OrderedEventRecord> CommonEventControlManager::GetMatchingOrderedReceiver(sptr<IRemoteObject> proxy)
{
EVENT_LOGI("enter");
if (orderedEventQueue_.size() > 0) {
std::shared_ptr<OrderedEventRecord> firstRecord = orderedEventQueue_.front();
if ((firstRecord != nullptr) && (firstRecord->curReceiver == proxy)) {
return firstRecord;
}
}
return nullptr;
}
bool CommonEventControlManager::GetOrderedEventHandler()
{
if (!handlerOrdered_) {
handlerOrdered_ = std::make_shared<OrderedEventHandler>(EventRunner::Create(), shared_from_this());
if (!handlerOrdered_) {
EVENT_LOGE("Failed to create OrderedEventHandler");
return false;
}
}
return true;
}
bool CommonEventControlManager::ProcessOrderedEvent(
const CommonEventRecord &commonEventRecord, const sptr<IRemoteObject> &commonEventListener)
{
EVENT_LOGI("enter");
bool ret = false;
if (!GetOrderedEventHandler()) {
return ret;
}
std::shared_ptr<OrderedEventRecord> eventRecord = std::make_shared<OrderedEventRecord>();
if (eventRecord == nullptr) {
EVENT_LOGE("eventRecord is null");
return ret;
}
std::shared_ptr<CommonEventSubscriberManager> spinstance =
DelayedSingleton<CommonEventSubscriberManager>::GetInstance();
eventRecord->FillCommonEventRecord(commonEventRecord);
eventRecord->resultTo = commonEventListener;
eventRecord->state = OrderedEventRecord::IDLE;
eventRecord->nextReceiver = 0;
eventRecord->receivers = spinstance->GetSubscriberRecords(commonEventRecord.commonEventData->GetWant());
for (auto vec : eventRecord->receivers) {
eventRecord->deliveryState.emplace_back(OrderedEventRecord::DELIVERY_PENDING);
}
EnqueueOrderedRecord(eventRecord);
ret = ScheduleOrderedCommonEvent();
return ret;
}
bool CommonEventControlManager::EnqueueOrderedRecord(const std::shared_ptr<OrderedEventRecord> &eventRecordPtr)
{
if (eventRecordPtr == nullptr) {
EVENT_LOGE("eventRecordPtr is null");
return false;
}
orderedEventQueue_.emplace_back(eventRecordPtr);
return true;
}
bool CommonEventControlManager::ScheduleOrderedCommonEvent()
{
EVENT_LOGI("enter");
if (scheduled_) {
return true;
}
scheduled_ = true;
return handlerOrdered_->SendEvent(InnerEvent::Get(OrderedEventHandler::ORDERED_EVENT_START));
}
bool CommonEventControlManager::NotifyOrderedEvent(std::shared_ptr<OrderedEventRecord> &eventRecordPtr, int index)
{
EVENT_LOGI("enter with index %{public}d", index);
if (eventRecordPtr == nullptr) {
EVENT_LOGE("eventRecordPtr = nullptr");
return false;
}
int receiverNum = eventRecordPtr->receivers.size();
if ((index < 0) || (index >= receiverNum)) {
EVENT_LOGE("Invalid index (= %{public}d)", index);
return false;
}
int ret = CheckPermission(*(eventRecordPtr->receivers[index]), *eventRecordPtr);
if (ret == OrderedEventRecord::DELIVERY_SKIPPED) {
eventRecordPtr->deliveryState[index] = ret;
} else if (ret == OrderedEventRecord::DELIVERY_DELIVERED) {
if (eventRecordPtr->receivers[index]->isFreeze) {
EVENT_LOGD("vec->uid: %{public}d", eventRecordPtr->receivers[index]->uid);
EVENT_LOGD("vec->isFreeze: %{public}d", eventRecordPtr->receivers[index]->isFreeze);
DelayedSingleton<CommonEventSubscriberManager>::GetInstance()->InsertFrozenEvents(
eventRecordPtr->receivers[index], *eventRecordPtr);
eventRecordPtr->deliveryState[index] = OrderedEventRecord::DELIVERY_SKIPPED;
eventRecordPtr->curReceiver = nullptr;
return true;
}
eventRecordPtr->deliveryState[index] = ret;
eventRecordPtr->curReceiver = eventRecordPtr->receivers[index]->commonEventListener;
eventRecordPtr->state = OrderedEventRecord::RECEIVEING;
sptr<IEventReceive> receiver = iface_cast<IEventReceive>(eventRecordPtr->curReceiver);
if (!receiver) {
EVENT_LOGE("Failed to get IEventReceive proxy");
eventRecordPtr->curReceiver = nullptr;
return false;
}
eventRecordPtr->state = OrderedEventRecord::RECEIVED;
receiver->NotifyEvent(*(eventRecordPtr->commonEventData), true, eventRecordPtr->publishInfo->IsSticky());
}
return true;
}
void CommonEventControlManager::ProcessNextOrderedEvent(bool isSendMsg)
{
EVENT_LOGI("enter");
if (isSendMsg) {
scheduled_ = false;
}
std::shared_ptr<OrderedEventRecord> sp = nullptr;
do {
if (orderedEventQueue_.size() == 0) {
return;
}
sp = orderedEventQueue_.front();
bool forceReceive = false;
int numReceivers = sp->receivers.size();
int64_t nowSysTime = SystemTime::GetNowSysTime();
if (sp->dispatchTime > 0) {
if ((numReceivers > 0) && (nowSysTime > sp->dispatchTime + (2 * TIMEOUT * numReceivers))) {
CurrentOrderedEventTimeout(false);
forceReceive = true;
sp->state = OrderedEventRecord::IDLE;
}
}
if (sp->state != OrderedEventRecord::IDLE) {
return;
}
if ((sp->receivers.size() == 0) || (sp->nextReceiver >= numReceivers) || sp->resultAbort || forceReceive) {
// No more receivers for this ordered common event, then process the final result receiver
if (sp->resultTo != nullptr) {
EVENT_LOGI("Process the final subscriber");
sptr<IEventReceive> receiver = iface_cast<IEventReceive>(sp->resultTo);
if (!receiver) {
EVENT_LOGE("Failed to get IEventReceive proxy");
return;
}
receiver->NotifyEvent(*(sp->commonEventData), true, sp->publishInfo->IsSticky());
sp->resultTo = nullptr;
}
CancelTimeout();
orderedEventQueue_.erase(orderedEventQueue_.begin());
sp = nullptr;
}
} while (sp == nullptr);
int recIdx = sp->nextReceiver++;
SetTime(recIdx, sp, pendingTimeoutMessage_);
NotifyOrderedEvent(sp, recIdx);
if (sp->curReceiver == nullptr) {
sp->state = OrderedEventRecord::IDLE;
ScheduleOrderedCommonEvent();
}
return;
}
bool CommonEventControlManager::SetTimeout(int64_t timeoutTime)
{
EVENT_LOGI("enter");
bool ret = true;
if (!pendingTimeoutMessage_) {
pendingTimeoutMessage_ = true;
ret = handlerOrdered_->SendTimingEvent(OrderedEventHandler::ORDERED_EVENT_TIMEOUT, timeoutTime);
}
return ret;
}
bool CommonEventControlManager::CancelTimeout()
{
EVENT_LOGI("enter");
if (pendingTimeoutMessage_) {
pendingTimeoutMessage_ = false;
handlerOrdered_->RemoveEvent(OrderedEventHandler::ORDERED_EVENT_TIMEOUT);
}
return true;
}
void CommonEventControlManager::CurrentOrderedEventTimeout(bool isFromMsg)
{
EVENT_LOGI("enter");
if (isFromMsg) {
pendingTimeoutMessage_ = false;
}
if (orderedEventQueue_.size() == 0) {
return;
}
int64_t nowSysTime = SystemTime::GetNowSysTime();
std::shared_ptr<OrderedEventRecord> sp = orderedEventQueue_.front();
if (isFromMsg) {
int64_t timeoutTime = sp->receiverTime + TIMEOUT;
if (timeoutTime > nowSysTime) {
SetTimeout(timeoutTime);
return;
}
}
// The processing of current receiver has timeout
sp->receiverTime = nowSysTime;
if (sp->nextReceiver > 0) {
std::shared_ptr<EventSubscriberRecord> subscriberRecord = sp->receivers[sp->nextReceiver - 1];
EVENT_LOGW("Timeout: When %{public}s (pid = %{public}d, uid = %{public}d) process common event %{public}s",
subscriberRecord->bundleName.c_str(),
subscriberRecord->pid,
subscriberRecord->uid,
sp->commonEventData->GetWant().GetAction().c_str());
sp->deliveryState[sp->nextReceiver - 1] = OrderedEventRecord::DELIVERY_TIMEOUT;
}
// Forced to finish the current receiver to process the next receiver
int code = sp->commonEventData->GetCode();
const std::string &strRef = sp->commonEventData->GetData();
bool abort = sp->resultAbort;
FinishReceiverLocked(sp, code, strRef, abort);
ScheduleOrderedCommonEvent();
return;
}
bool CommonEventControlManager::FinishReceiverLocked(std::shared_ptr<OrderedEventRecord> recordPtr, const int &code,
const std::string &receiverData, const bool &abortEvent)
{
EVENT_LOGI("enter");
if (recordPtr == nullptr) {
EVENT_LOGE("recordPtr is null");
return false;
}
EVENT_LOGI("enter recordPtr->state=%{public}d", recordPtr->state);
int state = recordPtr->state;
recordPtr->state = OrderedEventRecord::IDLE;
recordPtr->curReceiver = nullptr;
recordPtr->commonEventData->SetCode(code);
recordPtr->commonEventData->SetData(receiverData);
recordPtr->resultAbort = abortEvent;
return state == OrderedEventRecord::RECEIVED;
}
bool CommonEventControlManager::FinishReceiverAction(std::shared_ptr<OrderedEventRecord> recordPtr, const int &code,
const std::string &receiverData, const bool &abortEvent)
{
EVENT_LOGI("enter");
if (recordPtr == nullptr) {
EVENT_LOGE("recordPtr is nullptr");
return false;
}
bool doNext = false;
doNext = FinishReceiverLocked(recordPtr, code, receiverData, abortEvent);
if (doNext) {
ProcessNextOrderedEvent(false);
}
return true;
}
void CommonEventControlManager::CheckSubscriberRequiredPermission(const std::string &subscriberRequiredPermission,
const CommonEventRecord &eventRecord, const EventSubscriberRecord &subscriberRecord, bool &skip)
{
bool ret = false;
if (!subscriberRequiredPermission.empty()) {
ret = DelayedSingleton<BundleManagerHelper>::GetInstance()->CheckPermission(
eventRecord.bundleName, subscriberRequiredPermission);
if (!ret) {
EVENT_LOGW("No permission to send common event %{public}s "
"from %{public}s (pid = %{public}d, uid = %{public}d) "
"to %{public}s (pid = %{public}d, uid = %{public}d) "
"due to registered subscriber require %{public}s",
eventRecord.commonEventData->GetWant().GetAction().c_str(),
eventRecord.bundleName.c_str(),
eventRecord.pid,
eventRecord.uid,
subscriberRecord.bundleName.c_str(),
subscriberRecord.pid,
subscriberRecord.uid,
subscriberRequiredPermission.c_str());
skip = true;
}
}
}
void CommonEventControlManager::CheckPublisherRequiredPermissions(
const std::vector<std::string> &publisherRequiredPermissions, const EventSubscriberRecord &subscriberRecord,
const CommonEventRecord &eventRecord, bool &skip)
{
bool ret = false;
if ((!skip) && (publisherRequiredPermissions.size() > 0)) {
for (auto publisherRequiredPermission : publisherRequiredPermissions) {
ret = DelayedSingleton<BundleManagerHelper>::GetInstance()->CheckPermission(
subscriberRecord.bundleName, publisherRequiredPermission);
if (!ret) {
skip = true;
EVENT_LOGW("No permission to receive common event %{public}s "
"to %{public}s (pid = %{public}d, uid = %{public}d) "
"due to publisher %{public}s (pid = %{public}d, uid = %{public}d) requires %{public}s",
eventRecord.commonEventData->GetWant().GetAction().c_str(),
subscriberRecord.bundleName.c_str(),
subscriberRecord.pid,
subscriberRecord.uid,
eventRecord.bundleName.c_str(),
eventRecord.pid,
eventRecord.uid,
publisherRequiredPermission.c_str());
break;
}
}
}
}
int CommonEventControlManager::CheckPermission(
const EventSubscriberRecord &subscriberRecord, const CommonEventRecord &eventRecord)
{
EVENT_LOGI("enter");
bool skip = false;
bool ret = false;
std::string subscriberRequiredPermission = subscriberRecord.eventSubscriberInfo->GetPermission();
std::vector<std::string> publisherRequiredPermissions = eventRecord.publishInfo->GetSubscriberPermissions();
Permission per = DelayedSingleton<CommonEventPermissionManager>::GetInstance()->GetEventPermission(
eventRecord.commonEventData->GetWant().GetAction());
ret = CheckSubcriberPermission(per, subscriberRecord);
EVENT_LOGI("after CheckSubcriberPermission and ret = %{public}d", ret);
if (!ret) {
return OrderedEventRecord::DELIVERY_SKIPPED;
}
CheckSubscriberRequiredPermission(subscriberRequiredPermission, eventRecord, subscriberRecord, skip);
CheckPublisherRequiredPermissions(publisherRequiredPermissions, subscriberRecord, eventRecord, skip);
if (skip) {
return OrderedEventRecord::DELIVERY_SKIPPED;
}
return OrderedEventRecord::DELIVERY_DELIVERED;
}
bool CommonEventControlManager::CheckSubcriberPermission(
const Permission &permission, const EventSubscriberRecord &subscriberRecord)
{
EVENT_LOGI("enter");
EVENT_LOGI("size = %{public}d", permission.names.size());
bool ret = false;
if (permission.names.size() < 1) {
return true;
}
if (permission.names.size() == 1) {
ret = DelayedSingleton<BundleManagerHelper>::GetInstance()->CheckPermission(
subscriberRecord.bundleName, permission.names[0]);
} else {
if (permission.state == Permission::AND) {
for (auto vec : permission.names) {
ret = DelayedSingleton<BundleManagerHelper>::GetInstance()->CheckPermission(
subscriberRecord.bundleName, vec);
if (!ret) {
break;
}
}
} else if (permission.state == Permission::OR) {
for (auto vec : permission.names) {
ret = DelayedSingleton<BundleManagerHelper>::GetInstance()->CheckPermission(
subscriberRecord.bundleName, vec);
if (ret) {
break;
}
}
}
}
return ret;
}
void CommonEventControlManager::SetTime(int recIdx, std::shared_ptr<OrderedEventRecord> &sp, bool timeoutMessage)
{
EVENT_LOGI("enter");
sp->receiverTime = SystemTime::GetNowSysTime();
if (recIdx == 0) {
sp->dispatchTime = sp->receiverTime;
}
if (!timeoutMessage) {
int64_t timeoutTime = sp->receiverTime + TIMEOUT;
SetTimeout(timeoutTime);
}
return;
}
} // namespace EventFwk
} // namespace OHOS
@@ -0,0 +1,264 @@
/*
* 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 "common_event_manager_service.h"
#include "bundle_manager_helper.h"
#include "datetime_ex.h"
#include "event_log_wrapper.h"
#include "ipc_skeleton.h"
#include "system_ability_definition.h"
namespace OHOS {
namespace EventFwk {
const bool REGISTER_RESULT =
SystemAbility::MakeAndRegisterAbility(DelayedSingleton<CommonEventManagerService>::GetInstance().get());
CommonEventManagerService::CommonEventManagerService()
: SystemAbility(COMMON_EVENT_SERVICE_ID, true),
serviceRunningState_(ServiceRunningState::STATE_NOT_START),
runner_(nullptr),
handler_(nullptr)
{
EVENT_LOGI("instance created");
innerCommonEventManager_ = std::make_shared<InnerCommonEventManager>();
}
CommonEventManagerService::~CommonEventManagerService()
{
EVENT_LOGI("instance destroyed");
}
void CommonEventManagerService::OnStart()
{
EVENT_LOGI("ready to start service");
if (serviceRunningState_ == ServiceRunningState::STATE_RUNNING) {
EVENT_LOGW("Failed to start service since it's already running");
return;
}
ErrCode errCode = Init();
if (FAILED(errCode)) {
EVENT_LOGE("Failed to init, errCode: %{public}08x", errCode);
return;
}
serviceRunningState_ = ServiceRunningState::STATE_RUNNING;
EVENT_LOGI("start service success");
}
void CommonEventManagerService::OnStop()
{
EVENT_LOGI("ready to stop service");
serviceRunningState_ = ServiceRunningState::STATE_NOT_START;
if (handler_) {
handler_.reset();
}
if (runner_) {
runner_.reset();
}
EVENT_LOGI("stop service success");
}
ErrCode CommonEventManagerService::Init()
{
EVENT_LOGI("ready to init");
if (!innerCommonEventManager_) {
EVENT_LOGE("Failed to init without inner service");
return ERR_INVALID_OPERATION;
}
runner_ = EventRunner::Create(true);
if (!runner_) {
EVENT_LOGE("Failed to init due to create runner error");
return ERR_INVALID_OPERATION;
}
handler_ = std::make_shared<EventHandler>(runner_);
if (!handler_) {
EVENT_LOGE("Failed to init due to create handler error");
return ERR_INVALID_OPERATION;
}
if (!Publish(this)) {
EVENT_LOGE("Failed to publish CommonEventManagerService to SystemAbilityMgr");
return ERR_INVALID_OPERATION;
}
EVENT_LOGI("init success");
return ERR_OK;
}
bool CommonEventManagerService::IsReady() const
{
if (!innerCommonEventManager_) {
EVENT_LOGE("innerCommonEventManager is null");
return false;
}
if (!handler_) {
EVENT_LOGE("handler is null");
return false;
}
return true;
}
bool CommonEventManagerService::PublishCommonEvent(const CommonEventData &event,
const CommonEventPublishInfo &publishinfo, const sptr<IRemoteObject> &commonEventListener)
{
EVENT_LOGI("enter");
if (!IsReady()) {
return false;
}
struct tm recordTime = {0};
if (!GetSystemCurrentTime(&recordTime)) {
EVENT_LOGE("Failed to GetSystemCurrentTime");
return false;
}
pid_t callingPid = IPCSkeleton::GetCallingPid();
uid_t callingUid = IPCSkeleton::GetCallingUid();
std::string bundleName = DelayedSingleton<BundleManagerHelper>::GetInstance()->GetBundleName(callingUid);
std::function<void()> PublishCommonEventFunc = std::bind(&InnerCommonEventManager::PublishCommonEvent,
innerCommonEventManager_,
event,
publishinfo,
commonEventListener,
recordTime,
callingPid,
callingUid,
bundleName);
return handler_->PostTask(PublishCommonEventFunc);
}
bool CommonEventManagerService::SubscribeCommonEvent(
const CommonEventSubscribeInfo &subscriberInfo, const sptr<IRemoteObject> &commonEventListener)
{
EVENT_LOGI("enter");
if (!IsReady()) {
return false;
}
struct tm recordTime = {0};
if (!GetSystemCurrentTime(&recordTime)) {
EVENT_LOGE("Failed to GetSystemCurrentTime");
return false;
}
pid_t callingPid = IPCSkeleton::GetCallingPid();
uid_t callingUid = IPCSkeleton::GetCallingUid();
std::string bundleName = DelayedSingleton<BundleManagerHelper>::GetInstance()->GetBundleName(callingUid);
std::function<void()> SubscribeCommonEventFunc = std::bind(&InnerCommonEventManager::SubscribeCommonEvent,
innerCommonEventManager_,
subscriberInfo,
commonEventListener,
recordTime,
callingPid,
callingUid,
bundleName);
return handler_->PostTask(SubscribeCommonEventFunc);
}
bool CommonEventManagerService::UnsubscribeCommonEvent(const sptr<IRemoteObject> &commonEventListener)
{
EVENT_LOGI("enter");
if (!IsReady()) {
return false;
}
std::function<void()> UnsubscribeCommonEventFunc =
std::bind(&InnerCommonEventManager::UnsubscribeCommonEvent, innerCommonEventManager_, commonEventListener);
return handler_->PostTask(UnsubscribeCommonEventFunc);
}
bool CommonEventManagerService::GetStickyCommonEvent(const std::string &event, CommonEventData &eventData)
{
EVENT_LOGI("enter");
if (!IsReady()) {
return false;
}
if (event.empty()) {
EVENT_LOGE("event is empty");
return false;
}
return innerCommonEventManager_->GetStickyCommonEvent(event, eventData);
}
bool CommonEventManagerService::DumpState(const std::string &event, std::vector<std::string> &state)
{
EVENT_LOGI("enter");
if (!IsReady()) {
return false;
}
innerCommonEventManager_->DumpState(event, state);
return true;
}
bool CommonEventManagerService::FinishReceiver(
const sptr<IRemoteObject> &proxy, const int &code, const std::string &receiverData, const bool &abortEvent)
{
EVENT_LOGI("enter");
if (!IsReady()) {
return false;
}
std::function<void()> FinishReceiverFunc = std::bind(
&InnerCommonEventManager::FinishReceiver, innerCommonEventManager_, proxy, code, receiverData, abortEvent);
return handler_->PostTask(FinishReceiverFunc);
}
bool CommonEventManagerService::Freeze(const uid_t &uid)
{
EVENT_LOGI("enter");
if (!IsReady()) {
return false;
}
std::function<void()> FreezeFunc = std::bind(&InnerCommonEventManager::Freeze, innerCommonEventManager_, uid);
return handler_->PostImmediateTask(FreezeFunc);
}
bool CommonEventManagerService::Unfreeze(const uid_t &uid)
{
EVENT_LOGI("enter");
if (!IsReady()) {
return false;
}
std::function<void()> UnfreezeFunc = std::bind(&InnerCommonEventManager::Unfreeze, innerCommonEventManager_, uid);
return handler_->PostImmediateTask(UnfreezeFunc);
}
} // namespace EventFwk
} // namespace OHOS
@@ -0,0 +1,352 @@
/*
* 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 "common_event_permission_manager.h"
#include "event_log_wrapper.h"
namespace OHOS {
namespace EventFwk {
const int REVERSE = 3;
CommonEventPermissionManager::CommonEventPermissionManager()
{
Init();
}
void CommonEventPermissionManager::Init()
{
EVENT_LOGI("enter");
Permission per;
per.names.reserve(REVERSE);
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.RECEIVER_STARTUP_COMPLETED");
multimap_.insert(std::make_pair("COMMON_EVENT_BOOT_COMPLETED", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.RECEIVER_STARTUP_COMPLETED");
multimap_.insert(std::make_pair("COMMON_EVENT_LOCKED_BOOT_COMPLETED", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("oohos.permission.MANAGE_USERS");
multimap_.insert(std::make_pair("COMMON_EVENT_USER_SWITCHED", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.INTERACT_ACROSS_USERS");
multimap_.insert(std::make_pair("COMMON_EVENT_USER_STARTING", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.INTERACT_ACROSS_USERS");
multimap_.insert(std::make_pair("COMMON_EVENT_USER_STOPPING", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.LOCATION");
multimap_.insert(std::make_pair("COMMON_EVENT_WIFI_SCAN_FINISHED", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.GET_WIFI_INFO");
multimap_.insert(std::make_pair("COMMON_EVENT_WIFI_RSSI_VALU", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.GET_WIFI_INFO");
multimap_.insert(std::make_pair("COMMON_EVENT_WIFI_AP_STA_JOIN", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.GET_WIFI_INFO");
multimap_.insert(std::make_pair("COMMON_EVENT_WIFI_AP_STA_LEAVE", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.MPLINK_CHANGE_STATE");
multimap_.insert(std::make_pair("COMMON_EVENT_WIFI_MPLINK_STATE_CHANGE", per));
per.names.clear();
per.state = Permission::AND;
per.names.emplace_back("ohos.permission.GET_WIFI_INFO");
per.names.emplace_back("ohos.permission.LOCATION");
multimap_.insert(std::make_pair("COMMON_EVENT_WIFI_P2P_CONN_STATE", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.GET_WIFI_INFO");
multimap_.insert(std::make_pair("COMMON_EVENT_WIFI_P2P_STATE_CHANGED", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.GET_WIFI_INFO");
multimap_.insert(std::make_pair("COMMON_EVENT_WIFI_P2P_PEERS_STATE_CHANGED", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.GET_WIFI_INFO");
multimap_.insert(std::make_pair("COMMON_EVENT_WIFI_P2P_PEERS_DISCOVERY_STATE_CHANGED", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.GET_WIFI_INFO");
multimap_.insert(std::make_pair("COMMON_EVENT_WIFI_P2P_CURRENT_DEVICE_STATE_CHANGED", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.GET_WIFI_INFO");
multimap_.insert(std::make_pair("COMMON_EVENT_WIFI_P2P_GROUP_STATE_CHANGED", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.USE_BLUETOOTH");
multimap_.insert(std::make_pair("COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_CONNECT_STATE_UPDATE", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.USE_BLUETOOTH");
multimap_.insert(std::make_pair("COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_CURRENT_DEVICE_UPDATE", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.USE_BLUETOOTH");
multimap_.insert(std::make_pair("COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_AUDIO_STATE_UPDATE", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.USE_BLUETOOTH");
multimap_.insert(std::make_pair("COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CONNECT_STATE_UPDATE", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.USE_BLUETOOTH");
multimap_.insert(std::make_pair("COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CURRENT_DEVICE_UPDATE", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.USE_BLUETOOTH");
multimap_.insert(std::make_pair("COMMON_EVENT_BLUETOOTH_A2DPSOURCE_PLAYING_STATE_UPDATE", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.USE_BLUETOOTH");
multimap_.insert(std::make_pair("COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CODEC_VALUE_UPDATE", per));
per.names.clear();
per.state = Permission::AND;
per.names.emplace_back("ohos.permission.USE_BLUETOOTH");
per.names.emplace_back("ohos.permission.LOCATION");
multimap_.insert(std::make_pair("COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_DISCOVERED", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.USE_BLUETOOTH");
multimap_.insert(std::make_pair("COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CLASS_VALUE_UPDATE", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.USE_BLUETOOTH");
multimap_.insert(std::make_pair("COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_ACL_CONNECTED", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.USE_BLUETOOTH");
multimap_.insert(std::make_pair("COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_ACL_DISCONNECTED", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.USE_BLUETOOTH");
multimap_.insert(std::make_pair("COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_NAME_UPDATE", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.USE_BLUETOOTH");
multimap_.insert(std::make_pair("COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIR_STATE", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.USE_BLUETOOTH");
multimap_.insert(std::make_pair("COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_BATTERY_VALUE_UPDATE", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.DISCOVER_BLUETOOTH");
multimap_.insert(std::make_pair("COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_UUID_VALUE", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.DISCOVER_BLUETOOTH");
multimap_.insert(std::make_pair("COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIRING_REQ", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.USE_BLUETOOTH");
multimap_.insert(std::make_pair("COMMON_EVENT_BLUETOOTH_HOST_STATE_UPDATE", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.USE_BLUETOOTH");
multimap_.insert(std::make_pair("COMMON_EVENT_BLUETOOTH_HOST_REQ_ENABLE", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.USE_BLUETOOTH");
multimap_.insert(std::make_pair("COMMON_EVENT_BLUETOOTH_HOST_REQ_DISABLE", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.USE_BLUETOOTH");
multimap_.insert(std::make_pair("COMMON_EVENT_BLUETOOTH_HOST_SCAN_MODE_UPDATE", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.USE_BLUETOOTH");
multimap_.insert(std::make_pair("COMMON_EVENT_BLUETOOTH_HOST_DISCOVERY_STARTED", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.USE_BLUETOOTH");
multimap_.insert(std::make_pair("COMMON_EVENT_BLUETOOTH_HOST_DISCOVERY_FINISHED", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.USE_BLUETOOTH");
multimap_.insert(std::make_pair("COMMON_EVENT_BLUETOOTH_HOST_NAME_UPDATE", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.USE_BLUETOOTH");
multimap_.insert(std::make_pair("COMMON_EVENT_BLUETOOTH_A2DPSINK_CONNECT_STATE_UPDATE", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.USE_BLUETOOTH");
multimap_.insert(std::make_pair("COMMON_EVENT_BLUETOOTH_A2DPSINK_PLAYING_STATE_UPDATE", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.USE_BLUETOOTH permission");
multimap_.insert(std::make_pair("COMMON_EVENT_BLUETOOTH_A2DPSINK_AUDIO_STATE_UPDATE", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.MANAGE_SECURE_SETTINGS");
multimap_.insert(std::make_pair("COMMON_EVENT_NFC_ACTION_RF_FIELD_ON_DETECTED", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.MANAGE_SECURE_SETTINGS");
multimap_.insert(std::make_pair("COMMON_EVENT_NFC_ACTION_RF_FIELD_OFF_DETECTED", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.MANAGE_USERS");
multimap_.insert(std::make_pair("COMMON_EVENT_USER_ADDED", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.MANAGE_USERS");
multimap_.insert(std::make_pair("COMMON_EVENT_USER_REMOVED", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.LISTEN_BUNDLE_CHANGE");
multimap_.insert(std::make_pair("COMMON_EVENT_ABILITY_ADDED", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.LISTEN_BUNDLE_CHANGE");
multimap_.insert(std::make_pair("COMMON_EVENT_ABILITY_REMOVED", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.LISTEN_BUNDLE_CHANGE");
multimap_.insert(std::make_pair("COMMON_EVENT_ABILITY_UPDATED", per));
per.names.clear();
per.state = Permission::OR;
per.names.emplace_back("ohos.permission.WRITE_USER_STORAGE");
per.names.emplace_back("ohos.permission.READ_USER_STORAGE");
multimap_.insert(std::make_pair("COMMON_EVENT_DISK_REMOVED", per));
per.names.clear();
per.state = Permission::OR;
per.names.emplace_back("ohos.permission.WRITE_USER_STORAGE");
per.names.emplace_back("ohos.permission.READ_USER_STORAGE");
multimap_.insert(std::make_pair("COMMON_EVENT_DISK_UNMOUNTED", per));
per.names.clear();
per.state = Permission::OR;
per.names.emplace_back("ohos.permission.WRITE_USER_STORAGE");
per.names.emplace_back("ohos.permission.READ_USER_STORAGE");
multimap_.insert(std::make_pair("COMMON_EVENT_DISK_MOUNTED", per));
per.names.clear();
per.state = Permission::OR;
per.names.emplace_back("ohos.permission.WRITE_USER_STORAGE");
per.names.emplace_back("ohos.permission.READ_USER_STORAGE");
multimap_.insert(std::make_pair("COMMON_EVENT_DISK_BAD_REMOVAL", per));
per.names.clear();
per.state = Permission::OR;
per.names.emplace_back("ohos.permission.WRITE_USER_STORAGE");
per.names.emplace_back("ohos.permission.READ_USER_STORAGE");
multimap_.insert(std::make_pair("COMMON_EVENT_DISK_UNMOUNTABLE", per));
per.names.clear();
per.state = Permission::OR;
per.names.emplace_back("ohos.permission.WRITE_USER_STORAGE");
per.names.emplace_back("ohos.permission.READ_USER_STORAGE");
multimap_.insert(std::make_pair("COMMON_EVENT_DISK_EJECT", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.GET_APP_ACCOUNTS");
multimap_.insert(std::make_pair("COMMON_EVENT_VISIBLE_ACCOUNTS_UPDATED", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS");
multimap_.insert(std::make_pair("COMMON_EVENT_ACCOUNT_DELETED", per));
per.names.clear();
per.state = Permission::DEFAULT;
per.names.emplace_back("ohos.permission.RECEIVER_STARTUP_COMPLETED");
multimap_.insert(std::make_pair("COMMON_EVENT_FOUNDATION_READY", per));
}
Permission CommonEventPermissionManager::GetEventPermission(std::string event)
{
EVENT_LOGI("enter");
Permission per;
auto iter = multimap_.begin();
for (; iter != multimap_.end(); ++iter) {
if (!event.compare(iter->first)) {
break;
}
}
if (iter == multimap_.end()) {
return per;
}
return iter->second;
}
} // namespace EventFwk
} // namespace OHOS
@@ -0,0 +1,229 @@
/*
* 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 "common_event_sticky_manager.h"
#include "errors.h"
#include "event_log_wrapper.h"
namespace OHOS {
namespace EventFwk {
int CommonEventStickyManager::FindStickyEvents(
const SubscribeInfoPtr &subscriberInfo, std::vector<CommonEventRecordPtr> &commonEventRecords)
{
EVENT_LOGI("enter");
if (subscriberInfo == nullptr) {
EVENT_LOGE("subscriberInfo is null");
return ERR_INVALID_VALUE;
}
auto events = subscriberInfo->GetMatchingSkills().GetEvents();
if (events.size() == 0) {
EVENT_LOGW("No subscribed events");
return ERR_INVALID_VALUE;
}
FindStickyEventsLocked(events, commonEventRecords);
return ERR_OK;
}
bool CommonEventStickyManager::GetStickyCommonEvent(const std::string &event, CommonEventData &eventData)
{
EVENT_LOGI("enter");
if (event.empty()) {
EVENT_LOGE("Invalid event name");
return false;
}
return GetStickyCommonEventLocked(event, eventData);
}
int CommonEventStickyManager::UpdateStickyEvent(const CommonEventRecord &eventRecord)
{
EVENT_LOGI("enter");
auto commonEventRecordPtr = std::make_shared<CommonEventRecord>(eventRecord);
if (commonEventRecordPtr == nullptr) {
EVENT_LOGE("Failed to create CommonEventRecord");
return ERR_INVALID_VALUE;
}
std::string event = commonEventRecordPtr->commonEventData->GetWant().GetAction();
return UpdateStickyEventLocked(event, commonEventRecordPtr);
}
void CommonEventStickyManager::DumpState(const std::string &event, std::vector<std::string> &state)
{
EVENT_LOGI("enter");
std::vector<CommonEventRecordPtr> records;
GetStickyCommonEventRecordsLocked(event, records);
if (records.size() == 0) {
state.emplace_back("Sticky Events:\tNo information");
return;
}
int num = 0;
for (auto record : records) {
num++;
std::string no = std::to_string(num);
if (num == 1) {
no = "Sticky Events:\tTotal " + std::to_string(records.size()) + "information\nNO " + no + "\n";
} else {
no = "NO " + no + "\n";
}
char systime[80];
strftime(systime, sizeof(char) * 80, "%Y%m%d %I:%M %p", &record->recordTime);
std::string recordTime = "\tTime: " + std::string(systime) + "\n";
std::string pid = "\tPID: " + std::to_string(record->pid) + "\n";
std::string uid = "\tUID: " + std::to_string(record->uid) + "\n";
std::string bundleName = "\tBundleName: " + record->bundleName + "\n";
std::string permission = "\tRequiredPermission: ";
std::string separator;
int permissionNum = 0;
for (auto permissionVec : record->publishInfo->GetSubscriberPermissions()) {
if (permissionNum == 0) {
separator = "";
} else {
separator = ", ";
}
permission = permission + separator + permissionVec;
permissionNum++;
}
permission = permission + "\n";
std::string isSticky;
if (record->publishInfo->IsSticky()) {
isSticky = "\tIsSticky: true\n";
} else {
isSticky = "\tIsSticky: false\n";
}
std::string isOrdered;
if (record->publishInfo->IsOrdered()) {
isOrdered = "\tIsOrdered: true\n";
} else {
isOrdered = "\tIsOrdered: false\n";
}
std::string isSystemEvent = record->isSystemEvent ? "true" : "false";
isSystemEvent = "\tIsSystemEvent: " + isSystemEvent + "\n";
std::string action = "\t\tAction: " + record->commonEventData->GetWant().GetAction() + "\n";
std::string entities = "\t\tEntity: ";
int entityNum = 0;
for (auto entitiesVec : record->commonEventData->GetWant().GetEntities()) {
if (entityNum == 0) {
separator = "";
} else {
separator = ", ";
}
entities = entities + separator + entitiesVec;
entityNum++;
}
entities = entities + "\n";
std::string scheme = "\t\tScheme: " + record->commonEventData->GetWant().GetScheme() + "\n";
std::string uri = "\t\tUri: " + record->commonEventData->GetWant().GetUriString() + "\n";
std::string flags = "\t\tFlags: " + std::to_string(record->commonEventData->GetWant().GetFlags()) + "\n";
std::string type = "\t\tType: " + record->commonEventData->GetWant().GetType() + "\n";
std::string bundle = "\t\tBundleName: " + record->commonEventData->GetWant().GetBundle() + "\n";
std::string ability =
"\t\tAbilityName: " + record->commonEventData->GetWant().GetElement().GetAbilityName() + "\n";
std::string deviced = "\t\tDevicedID: " + record->commonEventData->GetWant().GetElement().GetDeviceID() + "\n";
std::string want = "\tWant:\n" + action + entities + scheme + uri + flags + type + bundle + ability + deviced;
std::string code = "\tCode:" + std::to_string(record->commonEventData->GetCode()) + "\n";
std::string data = "\tData:" + record->commonEventData->GetData() + "\n";
std::string dumpInfo = no + recordTime + pid + uid + bundleName + permission + isSticky + isOrdered +
isSystemEvent + want + code + data;
state.emplace_back(dumpInfo);
}
}
void CommonEventStickyManager::FindStickyEventsLocked(
const std::vector<std::string> &events, std::vector<CommonEventRecordPtr> &commonEventRecords)
{
std::lock_guard<std::mutex> lock(mutex_);
for (auto event : events) {
auto it = commonEventRecords_.find(event);
if (it != commonEventRecords_.end()) {
commonEventRecords.emplace_back(it->second);
}
}
}
bool CommonEventStickyManager::GetStickyCommonEventLocked(const std::string &event, CommonEventData &eventData)
{
std::lock_guard<std::mutex> lock(mutex_);
auto it = commonEventRecords_.find(event);
if (it != commonEventRecords_.end()) {
eventData = *(it->second->commonEventData);
return true;
}
return false;
}
int CommonEventStickyManager::UpdateStickyEventLocked(const std::string &event, const CommonEventRecordPtr &record)
{
if (event.empty()) {
EVENT_LOGE("Invalid event name");
return ERR_INVALID_VALUE;
}
if (record == nullptr) {
EVENT_LOGE("Invalid common event record");
return ERR_INVALID_VALUE;
}
std::lock_guard<std::mutex> lock(mutex_);
commonEventRecords_[event] = record;
return ERR_OK;
}
void CommonEventStickyManager::GetStickyCommonEventRecordsLocked(
const std::string &event, std::vector<CommonEventRecordPtr> &records)
{
std::lock_guard<std::mutex> lock(mutex_);
if (event.empty()) {
for (auto record : commonEventRecords_) {
records.emplace_back(record.second);
}
} else {
auto recordItem = commonEventRecords_.find(event);
if (recordItem != commonEventRecords_.end()) {
records.emplace_back(recordItem->second);
}
}
}
} // namespace EventFwk
} // namespace OHOS
@@ -0,0 +1,399 @@
/*
* 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 <time.h>
#include "common_event_subscriber_manager.h"
#include "event_log_wrapper.h"
namespace OHOS {
namespace EventFwk {
#define FREEZE_TIMEOUT_SECOND 120
const int LENGTH = 80;
CommonEventSubscriberManager::CommonEventSubscriberManager()
: death_(sptr<IRemoteObject::DeathRecipient>(new SubscriberDeathRecipient())),
FREEZE_EVENT_TIMEOUT(FREEZE_TIMEOUT_SECOND)
{
EVENT_LOGI("CommonEventSubscriberManager instance created");
}
CommonEventSubscriberManager::~CommonEventSubscriberManager()
{
EVENT_LOGI("CommonEventSubscriberManager instance destoryed");
}
int CommonEventSubscriberManager::InsertSubscriber(const SubscribeInfoPtr &eventSubscriberInfo,
const sptr<IRemoteObject> &commonEventListener, const struct tm &recordTime, const pid_t &pid, const uid_t &uid,
const std::string &bundleName)
{
EVENT_LOGI("enter");
if (eventSubscriberInfo == nullptr) {
EVENT_LOGE("eventSubscriberInfo is null");
return ERR_INVALID_VALUE;
}
if (commonEventListener == nullptr) {
EVENT_LOGE("commonEventListener is null");
return ERR_INVALID_VALUE;
}
std::vector<std::string> events = eventSubscriberInfo->GetMatchingSkills().GetEvents();
if (events.size() <= 0) {
EVENT_LOGE("No subscribed events");
return ERR_INVALID_VALUE;
}
auto record = std::make_shared<EventSubscriberRecord>();
if (record == nullptr) {
EVENT_LOGE("Failed to create EventSubscriberRecord");
return ERR_INVALID_VALUE;
}
record->eventSubscriberInfo = eventSubscriberInfo;
record->commonEventListener = commonEventListener;
record->recordTime = recordTime;
record->pid = pid;
record->uid = uid;
record->bundleName = bundleName;
if (death_ != nullptr) {
commonEventListener->AddDeathRecipient(death_);
}
return InsertSubscriberRecordLocked(events, record);
}
int CommonEventSubscriberManager::RemoveSubscriber(const sptr<IRemoteObject> &commonEventListener)
{
EVENT_LOGI("enter");
if (commonEventListener == nullptr) {
EVENT_LOGE("commonEventListener is null");
return ERR_INVALID_VALUE;
}
if (death_ != nullptr) {
commonEventListener->RemoveDeathRecipient(death_);
}
return RemoveSubscriberRecordLocked(commonEventListener);
}
std::vector<std::shared_ptr<EventSubscriberRecord>> CommonEventSubscriberManager::GetSubscriberRecords(const Want &want)
{
EVENT_LOGI("enter");
auto records = std::vector<SubscriberRecordPtr>();
GetSubscriberRecordsByWantLocked(want, records);
return records;
}
void CommonEventSubscriberManager::DumpState(const std::string &event, std::vector<std::string> &state)
{
EVENT_LOGI("enter");
std::vector<SubscriberRecordPtr> records;
GetSubscriberRecordsByEventLocked(event, records);
if (records.size() == 0) {
state.emplace_back("Subscribers:\tNo information");
return;
}
int num = 0;
for (auto record : records) {
num++;
std::string no = std::to_string(num);
if (num == 1) {
no = "Subscribers:\tTotal " + std::to_string(records.size()) + " subscribers\nNO " + no + "\n";
} else {
no = "NO " + no + "\n";
}
char systime[LENGTH];
strftime(systime, sizeof(char) * LENGTH, "%Y%m%d %I:%M %p", &record->recordTime);
std::string recordTime = "\tTime: " + std::string(systime) + "\n";
std::string pid = "\tPID: " + std::to_string(record->pid) + "\n";
std::string uid = "\tUID: " + std::to_string(record->uid) + "\n";
std::string bundleName = "\tBundleName: " + record->bundleName + "\n";
std::string priority = "\tPriority: " + std::to_string(record->eventSubscriberInfo->GetPriority()) + "\n";
std::string permission = "\tPermission: " + record->eventSubscriberInfo->GetPermission() + "\n";
std::string deviceId = "\tDevicedID: " + record->eventSubscriberInfo->GetDeviceId() + "\n";
std::string events = "\t\tEvent: ";
std::string separator;
for (int eventNum = 0; eventNum < record->eventSubscriberInfo->GetMatchingSkills().CountEvent(); ++eventNum) {
if (eventNum == 0) {
separator = "";
} else {
separator = ", ";
}
events = events + separator + record->eventSubscriberInfo->GetMatchingSkills().GetEvent(eventNum);
}
events = events + "\n";
std::string entities = "\t\tEntity: ";
for (int entityNum = 0; entityNum < record->eventSubscriberInfo->GetMatchingSkills().CountEntities();
++entityNum) {
if (entityNum == 0) {
separator = "";
} else {
separator = ", ";
}
entities = entities + separator + record->eventSubscriberInfo->GetMatchingSkills().GetEntity(entityNum);
}
entities = entities + "\n";
std::string scheme = "\t\tScheme: ";
for (int schemeNum = 0; schemeNum < record->eventSubscriberInfo->GetMatchingSkills().CountSchemes();
++schemeNum) {
if (schemeNum == 0) {
separator = "";
} else {
separator = ", ";
}
scheme = scheme + separator + record->eventSubscriberInfo->GetMatchingSkills().GetScheme(schemeNum);
}
scheme = scheme + "\n";
std::string matchingSkills = "\tMatchingSkills:\n" + events + entities + scheme;
std::string isFreeze = record->isFreeze ? "true" : "false";
isFreeze = "\tIsFreeze: " + isFreeze + "\n";
std::string freezeTime = "\tFreezeTime: " + std::to_string(record->freezeTime) + "\n";
std::string dumpInfo = no + recordTime + pid + uid + bundleName + priority + permission + deviceId +
matchingSkills + isFreeze + freezeTime;
state.emplace_back(dumpInfo);
}
}
int CommonEventSubscriberManager::InsertSubscriberRecordLocked(
const std::vector<std::string> &events, const SubscriberRecordPtr &record)
{
if (events.size() == 0) {
EVENT_LOGE("No subscribed events");
return ERR_INVALID_VALUE;
}
if (record == nullptr) {
EVENT_LOGE("record is null");
return ERR_INVALID_VALUE;
}
std::lock_guard<std::mutex> lock(mutex_);
for (auto event : events) {
auto infoItem = eventSubscribers_.find(event);
if (infoItem != eventSubscribers_.end()) {
infoItem->second.insert(record);
} else {
std::multiset<SubscriberRecordPtr> EventSubscribersPtr;
EventSubscribersPtr.insert(record);
eventSubscribers_[event] = EventSubscribersPtr;
}
}
subscribers_.emplace_back(record);
return ERR_OK;
}
int CommonEventSubscriberManager::RemoveSubscriberRecordLocked(const sptr<IRemoteObject> &commonEventListener)
{
if (commonEventListener == nullptr) {
EVENT_LOGE("commonEventListener is null");
return ERR_INVALID_VALUE;
}
std::lock_guard<std::mutex> lock(mutex_);
std::vector<std::string> events;
for (auto it = subscribers_.begin(); it != subscribers_.end(); ++it) {
if (commonEventListener == (*it)->commonEventListener) {
RemoveFrozenEventsBySubscriber((*it));
(*it)->commonEventListener = nullptr;
events = (*it)->eventSubscriberInfo->GetMatchingSkills().GetEvents();
subscribers_.erase(it);
break;
}
}
for (auto event : events) {
for (auto it = eventSubscribers_[event].begin(); it != eventSubscribers_[event].end(); ++it) {
if ((commonEventListener == (*it)->commonEventListener) || ((*it)->commonEventListener == nullptr)) {
(*it)->commonEventListener = nullptr;
eventSubscribers_[event].erase(it);
break;
}
}
if (eventSubscribers_[event].size() == 0) {
eventSubscribers_.erase(event);
}
}
return ERR_OK;
}
void CommonEventSubscriberManager::GetSubscriberRecordsByWantLocked(
const Want &want, std::vector<SubscriberRecordPtr> &records)
{
std::lock_guard<std::mutex> lock(mutex_);
if (eventSubscribers_.size() <= 0) {
return;
}
auto recordsItem = eventSubscribers_.find(want.GetAction());
if (recordsItem == eventSubscribers_.end()) {
return;
}
std::multiset<SubscriberRecordPtr> subscriberRecords = recordsItem->second;
for (auto it = subscriberRecords.begin(); it != subscriberRecords.end(); it++) {
if ((*it)->eventSubscriberInfo->GetMatchingSkills().Match(want)) {
records.emplace_back(*it);
}
}
}
void CommonEventSubscriberManager::GetSubscriberRecordsByEventLocked(
const std::string &event, std::vector<SubscriberRecordPtr> &records)
{
std::lock_guard<std::mutex> lock(mutex_);
if (event.empty()) {
records = subscribers_;
} else {
auto infoItem = eventSubscribers_.find(event);
if (infoItem != eventSubscribers_.end()) {
for (auto recordPtr : infoItem->second) {
records.emplace_back(recordPtr);
}
}
}
}
void CommonEventSubscriberManager::UpdateFreezeInfo(
const uid_t &uid, const bool &freezeState, const int64_t &freezeTime)
{
EVENT_LOGI("enter");
std::lock_guard<std::mutex> lock(mutex_);
std::vector<std::string> events;
for (auto recordPtr : subscribers_) {
if (recordPtr->uid == uid) {
if (freezeState) {
recordPtr->freezeTime = freezeTime;
} else {
recordPtr->freezeTime = 0;
}
recordPtr->isFreeze = freezeState;
EVENT_LOGI("recordPtr->uid: %{public}d", recordPtr->uid);
EVENT_LOGI("recordPtr->isFreeze: %{public}d", recordPtr->isFreeze);
}
}
}
void CommonEventSubscriberManager::InsertFrozenEvents(
const SubscriberRecordPtr &subscriberRecord, const CommonEventRecord &eventRecord)
{
EVENT_LOGI("enter");
if (subscriberRecord == nullptr) {
EVENT_LOGE("subscriberRecord is null");
return;
}
auto record = std::make_shared<CommonEventRecord>(eventRecord);
std::lock_guard<std::mutex> lock(mutex_);
auto frozenRecordsItem = frozenEvents_.find(subscriberRecord->uid);
if (frozenRecordsItem != frozenEvents_.end()) {
auto eventRecordsItem = frozenRecordsItem->second.find(subscriberRecord);
if (eventRecordsItem != frozenRecordsItem->second.end()) {
eventRecordsItem->second.push_back(record);
time_t backRecordTime = mktime(&eventRecordsItem->second.back()->recordTime);
time_t frontRecordTime = mktime(&eventRecordsItem->second.front()->recordTime);
EVENT_LOGD("backRecordTime: %{public}ld", backRecordTime);
EVENT_LOGD("frontRecordTime: %{public}ld", frontRecordTime);
time_t timeDiff = backRecordTime - frontRecordTime;
EVENT_LOGD("timeDiff: %{public}ld", timeDiff);
if (timeDiff > FREEZE_EVENT_TIMEOUT) {
eventRecordsItem->second.erase(eventRecordsItem->second.begin());
}
} else {
std::vector<EventRecordPtr> EventRecords;
EventRecords.push_back(record);
frozenRecordsItem->second[subscriberRecord] = EventRecords;
}
} else {
std::map<SubscriberRecordPtr, std::vector<EventRecordPtr>> frozenRecords;
std::vector<EventRecordPtr> EventRecords;
EventRecords.push_back(record);
frozenRecords[subscriberRecord] = EventRecords;
frozenEvents_[subscriberRecord->uid] = frozenRecords;
}
}
std::map<SubscriberRecordPtr, std::vector<EventRecordPtr>> CommonEventSubscriberManager::GetFrozenEvents(
const uid_t &uid)
{
EVENT_LOGI("enter");
std::map<SubscriberRecordPtr, std::vector<EventRecordPtr>> frozenEvents;
std::lock_guard<std::mutex> lock(mutex_);
auto infoItem = frozenEvents_.find(uid);
if (infoItem != frozenEvents_.end()) {
frozenEvents = infoItem->second;
}
RemoveFrozenEvents(uid);
return frozenEvents;
}
void CommonEventSubscriberManager::RemoveFrozenEvents(const uid_t &uid)
{
EVENT_LOGI("enter");
auto infoItem = frozenEvents_.find(uid);
if (infoItem != frozenEvents_.end()) {
frozenEvents_.erase(uid);
}
}
void CommonEventSubscriberManager::RemoveFrozenEventsBySubscriber(const SubscriberRecordPtr &subscriberRecord)
{
EVENT_LOGI("enter");
auto frozenRecordsItem = frozenEvents_.find(subscriberRecord->uid);
if (frozenRecordsItem != frozenEvents_.end()) {
auto eventRecordsItems = frozenRecordsItem->second.find(subscriberRecord);
if (eventRecordsItems != frozenRecordsItem->second.end()) {
frozenRecordsItem->second.erase(subscriberRecord);
}
}
}
} // namespace EventFwk
} // namespace OHOS
@@ -0,0 +1,198 @@
/*
* 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 "inner_common_event_manager.h"
#include "bundle_manager_helper.h"
#include "common_event_support.h"
#include "common_event_subscriber_manager.h"
#include "common_event_sticky_manager.h"
#include "event_log_wrapper.h"
#include "system_time.h"
namespace OHOS {
namespace EventFwk {
InnerCommonEventManager::InnerCommonEventManager() : controlPtr_(std::make_shared<CommonEventControlManager>())
{}
bool InnerCommonEventManager::PublishCommonEvent(const CommonEventData &data, const CommonEventPublishInfo &publishInfo,
const sptr<IRemoteObject> &commonEventListener, const struct tm &recordTime, const pid_t &pid, const uid_t &uid,
const std::string &bundleName)
{
EVENT_LOGI("enter pid = %{public}d, uid = %{public}d", pid, uid);
if (data.GetWant().GetAction().empty()) {
EVENT_LOGE("the commonEventdata action is null");
return false;
}
if ((!publishInfo.IsOrdered()) && (commonEventListener != nullptr)) {
EVENT_LOGE("When publishing unordered events, the subscriber object is not required.");
return false;
}
std::string action = data.GetWant().GetAction();
bool isSystemEvent = DelayedSingleton<CommonEventSupport>::GetInstance()->IsSystemEvent(action);
bool isSystemApp = DelayedSingleton<BundleManagerHelper>::GetInstance()->CheckIsSystemAppByUid(uid);
if (isSystemEvent) {
EVENT_LOGI("System common event");
if (!isSystemApp) {
EVENT_LOGE(
"No permission to send a system common event from %{public}s(pid = %{public}d, uid = %{public}d)",
bundleName.c_str(),
pid,
uid);
return false;
}
}
CommonEventRecord eventRecord;
eventRecord.commonEventData = std::make_shared<CommonEventData>(data);
eventRecord.publishInfo = std::make_shared<CommonEventPublishInfo>(publishInfo);
eventRecord.recordTime = recordTime;
eventRecord.pid = pid;
eventRecord.uid = uid;
eventRecord.bundleName = bundleName;
eventRecord.isSystemEvent = isSystemEvent;
if (publishInfo.IsSticky()) {
const std::string permission = "ohos.permission.COMMONEVENT_STICKY";
bool ret = DelayedSingleton<BundleManagerHelper>::GetInstance()->CheckPermission(bundleName, permission);
if (!ret) {
EVENT_LOGE(
"No permission to send a sticky common event from %s{public} (pid = %{public}d, uid = %{public}d)",
bundleName.c_str(),
pid,
uid);
return false;
}
DelayedSingleton<CommonEventStickyManager>::GetInstance()->UpdateStickyEvent(eventRecord);
}
if (!controlPtr_) {
EVENT_LOGE("CommonEventControlManager ptr is nullptr");
return false;
}
controlPtr_->PublishCommonEvent(eventRecord, commonEventListener);
return true;
}
bool InnerCommonEventManager::SubscribeCommonEvent(const CommonEventSubscribeInfo &subscriberInfo,
const sptr<IRemoteObject> &commonEventListener, const struct tm &recordTime, const pid_t &pid, const uid_t &uid,
const std::string &bundleName)
{
EVENT_LOGI("enter");
if (subscriberInfo.GetMatchingSkills().CountEvent() == 0) {
EVENT_LOGE("the subscriber has no event");
return false;
}
if (commonEventListener == nullptr) {
EVENT_LOGE("InnerCommonEventManager::SubscribeCommonEvent:commonEventListener == nullptr");
return false;
}
std::shared_ptr<CommonEventSubscribeInfo> sp = std::make_shared<CommonEventSubscribeInfo>(subscriberInfo);
DelayedSingleton<CommonEventSubscriberManager>::GetInstance()->InsertSubscriber(
sp, commonEventListener, recordTime, pid, uid, bundleName);
return true;
};
bool InnerCommonEventManager::UnsubscribeCommonEvent(sptr<IRemoteObject> &commonEventListener)
{
EVENT_LOGI("enter");
if (commonEventListener == nullptr) {
EVENT_LOGE("InnerCommonEventManager::UnsubscribeCommonEvent:commonEventListener == nullptr");
return false;
}
if (!controlPtr_) {
EVENT_LOGE("CommonEventControlManager ptr is nullptr");
return false;
}
std::shared_ptr<OrderedEventRecord> sp = controlPtr_->GetMatchingOrderedReceiver(commonEventListener);
if (sp) {
EVENT_LOGI("Unsubscribe the subscriber who is waiting to receive finish feedback");
int code = sp->commonEventData->GetCode();
std::string data = sp->commonEventData->GetData();
controlPtr_->FinishReceiverAction(sp, code, data, sp->resultAbort);
}
DelayedSingleton<CommonEventSubscriberManager>::GetInstance()->RemoveSubscriber(commonEventListener);
return true;
}
bool InnerCommonEventManager::GetStickyCommonEvent(const std::string &event, CommonEventData &eventData)
{
EVENT_LOGI("enter");
return DelayedSingleton<CommonEventStickyManager>::GetInstance()->GetStickyCommonEvent(event, eventData);
}
void InnerCommonEventManager::DumpState(const std::string &event, std::vector<std::string> &state)
{
EVENT_LOGI("enter");
DelayedSingleton<CommonEventSubscriberManager>::GetInstance()->DumpState(event, state);
DelayedSingleton<CommonEventStickyManager>::GetInstance()->DumpState(event, state);
return;
}
void InnerCommonEventManager::FinishReceiver(
const sptr<IRemoteObject> &proxy, const int &code, const std::string &receiverData, const bool &abortEvent)
{
EVENT_LOGI("enter");
if (!controlPtr_) {
EVENT_LOGE("CommonEventControlManager ptr is nullptr");
return;
}
std::shared_ptr<OrderedEventRecord> sp = controlPtr_->GetMatchingOrderedReceiver(proxy);
if (sp) {
controlPtr_->FinishReceiverAction(sp, code, receiverData, abortEvent);
}
return;
}
bool InnerCommonEventManager::Freeze(const uid_t &uid)
{
EVENT_LOGI("enter");
DelayedSingleton<CommonEventSubscriberManager>::GetInstance()->UpdateFreezeInfo(
uid, true, SystemTime::GetNowSysTime());
return true;
}
bool InnerCommonEventManager::Unfreeze(const uid_t &uid)
{
EVENT_LOGI("enter");
DelayedSingleton<CommonEventSubscriberManager>::GetInstance()->UpdateFreezeInfo(uid, false);
return controlPtr_->PublishFreezeCommonEvent(uid);
}
} // namespace EventFwk
} // namespace OHOS
@@ -0,0 +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 "ordered_event_handler.h"
#include "common_event_control_manager.h"
#include "event_log_wrapper.h"
namespace OHOS {
namespace EventFwk {
OrderedEventHandler::OrderedEventHandler(
const std::shared_ptr<EventRunner> &runner, const std::shared_ptr<CommonEventControlManager> &controlManager)
: EventHandler(runner), controlManager_(controlManager)
{
EVENT_LOGD("OrderedEventHandler is created");
}
OrderedEventHandler::~OrderedEventHandler()
{
EVENT_LOGD("OrderedEventHandler is destroyed");
}
void OrderedEventHandler::ProcessEvent(const InnerEvent::Pointer &event)
{
if (!controlManager_) {
EVENT_LOGE("CommonEventControlManager ptr is nullptr");
return;
}
switch (event->GetInnerEventId()) {
case ORDERED_EVENT_START: {
EVENT_LOGI("ORDERED_EVENT_START");
controlManager_->ProcessNextOrderedEvent(true);
break;
}
case ORDERED_EVENT_TIMEOUT: {
EVENT_LOGI("ORDERED_EVENT_TIMEOUT");
controlManager_->CurrentOrderedEventTimeout(true);
break;
}
default: {
EVENT_LOGW("the eventId is not supported");
break;
}
}
}
} // namespace EventFwk
} // namespace OHOS
+63
View File
@@ -0,0 +1,63 @@
/*
* 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 "publish_manager.h"
#include "event_log_wrapper.h"
#include "system_time.h"
namespace OHOS {
namespace EventFwk {
#define FLOOD_ATTACH_MAX 20
#define FLOOD_ATTACH_INTERVAL_MAX 5
PublishManager::PublishManager()
: lastPublishTime_(0),
publishNum_(0),
floodAttachMax_(FLOOD_ATTACH_MAX),
floodAttachIntervalMax_(FLOOD_ATTACH_INTERVAL_MAX)
{}
PublishManager::~PublishManager()
{}
bool PublishManager::CheckValid()
{
EVENT_LOGI("enter");
bool isValid = false;
int64_t nowSystemTime = SystemTime::GetNowSysTime();
EVENT_LOGI("nowSystemTime = %{public}lld, lastPublishTime_ = %{public}lld, interval = %{public}lld",
nowSystemTime,
lastPublishTime_,
nowSystemTime - lastPublishTime_);
if (nowSystemTime - lastPublishTime_ < floodAttachIntervalMax_) {
publishNum_++;
} else {
publishNum_ = 0;
}
lastPublishTime_ = nowSystemTime;
if (publishNum_ <= floodAttachMax_) {
isValid = true;
}
return isValid;
}
} // namespace EventFwk
} // namespace OHOS
@@ -0,0 +1,42 @@
/*
* 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 "subscriber_death_recipient.h"
#include "common_event_subscriber_manager.h"
#include "event_log_wrapper.h"
namespace OHOS {
namespace EventFwk {
void SubscriberDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &remote)
{
EVENT_LOGI("OnRemoteDied start");
if (remote == nullptr) {
EVENT_LOGE("remote object is null");
return;
}
sptr<IRemoteObject> object = remote.promote();
if (!object) {
EVENT_LOGE("object is null");
return;
}
DelayedSingleton<CommonEventSubscriberManager>::GetInstance()->RemoveSubscriber(object);
EVENT_LOGI("OnRemoteDied end");
}
} // namespace EventFwk
} // namespace OHOS
+37
View File
@@ -0,0 +1,37 @@
/*
* 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 "system_time.h"
#include "event_log_wrapper.h"
#include "inner_event.h"
namespace OHOS {
namespace EventFwk {
using namespace OHOS::AppExecFwk;
int64_t SystemTime::GetNowSysTime()
{
EVENT_LOGI("enter");
InnerEvent::TimePoint nowSys = InnerEvent::Clock::now();
auto epoch = nowSys.time_since_epoch();
auto value = std::chrono::duration_cast<std::chrono::milliseconds>(epoch);
int64_t duration = value.count();
return duration;
}
} // namespace EventFwk
} // namespace OHOS
@@ -0,0 +1,412 @@
/*
* 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_EVENT_CESFWK_SERVICES_TEST_UNITTEST_MOCK_INCLUDE_MOCK_BUNDLE_MANAGER_H
#define FOUNDATION_EVENT_CESFWK_SERVICES_TEST_UNITTEST_MOCK_INCLUDE_MOCK_BUNDLE_MANAGER_H
#include <vector>
#include "ability_info.h"
#include "application_info.h"
#include "bundle_mgr_host.h"
#include "bundle_mgr_interface.h"
#include "hilog_wrapper.h"
#include "ohos/aafwk/content/want.h"
#include "iremote_proxy.h"
#include "iremote_stub.h"
namespace OHOS {
namespace AppExecFwk {
class MockBundleMgrService : public BundleMgrHost {
public:
MockBundleMgrService()
{
HILOG_ERROR("BundleMgrService::BundleMgrService");
}
/**
* @brief Obtains the ApplicationInfo based on a given bundle name.
* @param appName Indicates the application bundle name to be queried.
* @param flag Indicates the flag used to specify information contained
* in the ApplicationInfo object that will be returned.
* @param userId Indicates the user ID.
* @param appInfo Indicates the obtained ApplicationInfo object.
* @return Returns true if the application is successfully obtained; returns false otherwise.
*/
virtual bool GetApplicationInfo(
const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo) override
{
return true;
}
/**
* @brief Obtains information about all installed applications of a specified user.
* @param flag Indicates the flag used to specify information contained
* in the ApplicationInfo objects that will be returned.
* @param userId Indicates the user ID.
* @param appInfos Indicates all of the obtained ApplicationInfo objects.
* @return Returns true if the application is successfully obtained; returns false otherwise.
*/
virtual bool GetApplicationInfos(
const ApplicationFlag flag, const int userId, std::vector<ApplicationInfo> &appInfos) override
{
return true;
}
/**
* @brief Obtains the BundleInfo based on a given bundle name.
* @param bundleName Indicates the application bundle name to be queried.
* @param flag Indicates the information contained in the BundleInfo object to be returned.
* @param bundleInfo Indicates the obtained BundleInfo object.
* @return Returns true if the BundleInfo is successfully obtained; returns false otherwise.
*/
virtual bool GetBundleInfo(const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo) override
{
return true;
}
/**
* @brief Obtains BundleInfo of all bundles available in the system.
* @param flag Indicates the flag used to specify information contained in the BundleInfo that will be returned.
* @param bundleInfos Indicates all of the obtained BundleInfo objects.
* @return Returns true if the BundleInfos is successfully obtained; returns false otherwise.
*/
virtual bool GetBundleInfos(const BundleFlag flag, std::vector<BundleInfo> &bundleInfos) override
{
return true;
};
/**
* @brief Obtains the application UID based on the given bundle name and user ID.
* @param bundleName Indicates the bundle name of the application.
* @param userId Indicates the user ID.
* @return Returns the uid if successfully obtained; returns -1 otherwise.
*/
virtual int GetUidByBundleName(const std::string &bundleName, const int userId) override
{
return 0;
}
/**
* @brief Obtains the bundle name of a specified application based on the given UID.
* @param uid Indicates the uid.
* @param bundleName Indicates the obtained bundle name.
* @return Returns true if the bundle name is successfully obtained; returns false otherwise.
*/
virtual bool GetBundleNameForUid(const int uid, std::string &bundleName) override
{
bundleName = "hello";
return true;
}
/**
* @brief Obtains an array of all group IDs associated with a specified bundle.
* @param bundleName Indicates the bundle name.
* @param gids Indicates the group IDs associated with the specified bundle.
* @return Returns true if the gids is successfully obtained; returns false otherwise.
*/
virtual bool GetBundleGids(const std::string &bundleName, std::vector<int> &gids) override
{
return true;
}
/**
* @brief Obtains the type of a specified application based on the given bundle name.
* @param bundleName Indicates the bundle name.
* @return Returns "system" if the bundle is a system application; returns "third-party" otherwise.
*/
virtual std::string GetAppType(const std::string &bundleName) override
{
return "";
}
/**
* @brief Check whether the app is system app by it's UID.
* @param uid Indicates the uid.
* @return Returns true if the bundle is a system application; returns false otherwise.
*/
virtual bool CheckIsSystemAppByUid(const int uid) override;
/**
* @brief Obtains the BundleInfo of application bundles based on the specified metaData.
* @param metaData Indicates the metadata to get in the bundle.
* @param bundleInfos Indicates all of the obtained BundleInfo objects.
* @return Returns true if the BundleInfos is successfully obtained; returns false otherwise.
*/
virtual bool GetBundleInfosByMetaData(const std::string &metaData, std::vector<BundleInfo> &bundleInfos) override
{
return true;
}
/**
* @brief Query the AbilityInfo by the given Want.
* @param want Indicates the information of the ability.
* @param abilityInfo Indicates the obtained AbilityInfo object.
* @return Returns true if the AbilityInfo is successfully obtained; returns false otherwise.
*/
virtual bool QueryAbilityInfo(const AAFwk::Want &want, AbilityInfo &abilityInfo) override
{
return true;
}
/**
* @brief Query the AbilityInfo by ability.uri in config.json.
* @param abilityUri Indicates the uri of the ability.
* @param abilityInfo Indicates the obtained AbilityInfo object.
* @return Returns true if the AbilityInfo is successfully obtained; returns false otherwise.
*/
virtual bool QueryAbilityInfoByUri(const std::string &abilityUri, AbilityInfo &abilityInfo) override
{
return true;
}
/**
* @brief Obtains the BundleInfo of all keep-alive applications in the system.
* @param bundleInfos Indicates all of the obtained BundleInfo objects.
* @return Returns true if the BundleInfos is successfully obtained; returns false otherwise.
*/
virtual bool QueryKeepAliveBundleInfos(std::vector<BundleInfo> &bundleInfos) override
{
return true;
};
/**
* @brief Obtains the label of a specified ability.
* @param bundleName Indicates the bundle name.
* @param className Indicates the ability class name.
* @return Returns the label of the ability if exist; returns empty string otherwise.
*/
virtual std::string GetAbilityLabel(const std::string &bundleName, const std::string &className) override
{
return "";
}
/**
* @brief Obtains information about an application bundle contained in a ohos Ability Package (HAP).
* @param hapFilePath Indicates the absolute file path of the HAP.
* @param flag Indicates the information contained in the BundleInfo object to be returned.
* @param bundleInfo Indicates the obtained BundleInfo object.
* @return Returns true if the BundleInfo is successfully obtained; returns false otherwise.
*/
virtual bool GetBundleArchiveInfo(
const std::string &hapFilePath, const BundleFlag flag, BundleInfo &bundleInfo) override
{
return true;
}
/**
* @brief Obtain the HAP module info of a specific ability.
* @param abilityInfo Indicates the ability.
* @param hapModuleInfo Indicates the obtained HapModuleInfo object.
* @return Returns true if the HapModuleInfo is successfully obtained; returns false otherwise.
*/
virtual bool GetHapModuleInfo(const AbilityInfo &abilityInfo, HapModuleInfo &hapModuleInfo) override
{
return true;
}
/**
* @brief Obtains the Want for starting the main ability of an application based on the given bundle name.
* @param bundleName Indicates the bundle name.
* @param want Indicates the obtained launch Want object.
* @return Returns true if the launch Want object is successfully obtained; returns false otherwise.
*/
virtual bool GetLaunchWantForBundle(const std::string &bundleName, Want &want) override
{
return true;
}
/**
* @brief Confirms with the permission management module to check whether a request prompt is required for granting
* a certain permission.
* @param bundleName Indicates the name of the bundle to check.
* @param permission Indicates the permission to check.
* @param userId Indicates the user id.
* @return Returns true if the current application does not have the permission and the user does not turn off
* further requests; returns false if the current application already has the permission, the permission is rejected
* by the system, or the permission is denied by the user and the user has turned off further requests.
*/
virtual bool CanRequestPermission(
const std::string &bundleName, const std::string &permissionName, const int userId) override
{
return true;
}
/**
* @brief Checks whether the publickeys of two bundles are the same.
* @param firstBundleName Indicates the first bundle name.
* @param secondBundleName Indicates the second bundle name.
* @return Returns SIGNATURE_UNKNOWN_BUNDLE if at least one of the given bundles is not found;
* returns SIGNATURE_NOT_MATCHED if their publickeys are different;
* returns SIGNATURE_MATCHED if their publickeys are the same.
*/
virtual int CheckPublicKeys(const std::string &firstBundleName, const std::string &secondBundleName) override
{
return 0;
}
/**
* @brief Checks whether a specified bundle has been granted a specific permission.
* @param bundleName Indicates the name of the bundle to check.
* @param permission Indicates the permission to check.
* @return Returns 0 if the bundle has the permission; returns -1 otherwise.
*/
virtual int CheckPermission(const std::string &bundleName, const std::string &permission) override;
/**
* @brief Obtains detailed information about a specified permission.
* @param permissionName Indicates the name of the ohos permission.
* @param permissionDef Indicates the object containing detailed information about the given ohos permission.
* @return Returns true if the PermissionDef object is successfully obtained; returns false otherwise.
*/
virtual bool GetPermissionDef(const std::string &permissionName, PermissionDef &permissionDef) override
{
return true;
}
/**
* @brief Obtains all known permission groups in the system.
* @param permissionDefs Indicates the list of objects containing the permission group information.
* @return Returns true if the PermissionDef objects is successfully obtained; returns false otherwise.
*/
virtual bool GetAllPermissionGroupDefs(std::vector<PermissionDef> &permissionDefs) override
{
return true;
}
/**
* @brief Obtains all known permission groups in the system.
* @param permissions Indicates the permission array.
* @param appNames Indicates the list of application names that have the specified permissions.
* @return Returns true if the application names is successfully obtained; returns false otherwise.
*/
virtual bool GetAppsGrantedPermissions(
const std::vector<std::string> &permissions, std::vector<std::string> &appNames) override
{
return true;
}
/**
* @brief Requests a certain permission from user.
* @param bundleName Indicates the name of the bundle to request permission.
* @param permission Indicates the permission to request permission.
* @param userId Indicates the user id.
* @return Returns true if the permission request successfully; returns false otherwise.
*/
virtual bool RequestPermissionFromUser(
const std::string &bundleName, const std::string &permission, const int userId) override
{
return true;
}
/**
* @brief Checks whether the system has a specified capability.
* @param capName Indicates the name of the system feature to check.
* @return Returns true if the given feature specified by name is available in the system; returns false otherwise.
*/
virtual bool HasSystemCapability(const std::string &capName) override
{
return true;
}
/**
* @brief Obtains the capabilities that are available in the system.
* @param systemCaps Indicates the list of capabilities available in the system.
* @return Returns true if capabilities in the system are successfully obtained; returns false otherwise.
*/
virtual bool GetSystemAvailableCapabilities(std::vector<std::string> &systemCaps) override
{
return true;
}
/**
* @brief Checks whether the current device has been started in safe mode.
* @return Returns true if the device is in safe mode; returns false otherwise.
*/
virtual bool IsSafeMode() override
{
return true;
}
/**
* @brief Clears cache data of a specified application.
* @param bundleName Indicates the bundle name of the application whose cache data is to be cleared.
* @param cleanCacheCallback Indicates the callback to be invoked for returning the operation result.
* @return Returns true if this function is successfully called; returns false otherwise.
*/
virtual bool CleanBundleCacheFiles(
const std::string &bundleName, const sptr<ICleanCacheCallback> &cleanCacheCallback) override
{
return true;
}
/**
* @brief Clears application running data of a specified application.
* @param bundleName Indicates the bundle name of the application whose data is to be cleared.
* @return Returns true if the data cleared successfully; returns false otherwise.
*/
virtual bool CleanBundleDataFiles(const std::string &bundleName) override
{
return true;
}
/**
* @brief Register the specific bundle status callback.
* @param bundleStatusCallback Indicates the callback to be invoked for returning the bundle status changed result.
* @return Returns true if this function is successfully called; returns false otherwise.
*/
virtual bool RegisterBundleStatusCallback(const sptr<IBundleStatusCallback> &bundleStatusCallback) override
{
return true;
}
/**
* @brief Clear the specific bundle status callback.
* @param bundleStatusCallback Indicates the callback to be cleared.
* @return Returns true if this function is successfully called; returns false otherwise.
*/
virtual bool ClearBundleStatusCallback(const sptr<IBundleStatusCallback> &bundleStatusCallback) override
{
return true;
}
/**
* @brief Unregister all the callbacks of status changed.
* @return Returns true if this function is successfully called; returns false otherwise.
*/
virtual bool UnregisterBundleStatusCallback() override
{
return true;
}
/**
* @brief Dump the bundle informations with specific flags.
* @param flag Indicates the information contained in the dump result.
* @param bundleName Indicates the bundle name if needed.
* @param result Indicates the dump information result.
* @return Returns true if the dump result is successfully obtained; returns false otherwise.
*/
virtual bool DumpInfos(const DumpFlag flag, const std::string &bundleName, std::string &result) override
{
return true;
}
/**
* @brief Checks whether a specified application is enabled.
* @param bundleName Indicates the bundle name of the application.
* @return Returns true if the application is enabled; returns false otherwise.
*/
virtual bool IsApplicationEnabled(const std::string &bundleName) override
{
return true;
}
/**
* @brief Sets whether to enable a specified application.
* @param bundleName Indicates the bundle name of the application.
* @param isEnable Specifies whether to enable the application.
* The value true means to enable it, and the value false means to disable it.
* @return Returns true if the application is enabled; returns false otherwise.
*/
virtual bool SetApplicationEnabled(const std::string &bundleName, bool isEnable) override
{
return true;
}
/**
* @brief Obtains the interface used to install and uninstall bundles.
* @return Returns a pointer to IBundleInstaller class if exist; returns nullptr otherwise.
*/
virtual sptr<IBundleInstaller> GetBundleInstaller() override
{
return nullptr;
}
void MockSetIsSystemApp(bool isSystemApp);
private:
bool isSystemApp_ = false;
bool isSystemAppMock_ = false;
};
} // namespace AppExecFwk
} // namespace OHOS
#endif // FOUNDATION_EVENT_CESFWK_SERVICES_TEST_UNITTEST_MOCK_INCLUDE_MOCK_BUNDLE_MANAGER_H
@@ -0,0 +1,44 @@
/*
* 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 "hilog_wrapper.h"
#include "iservice_registry.h"
#include "system_ability_manager.h"
namespace OHOS {
SystemAbilityManagerClient &SystemAbilityManagerClient::GetInstance()
{
HILOG_ERROR(" SystemAbilityManagerClient::GetInstance()");
static auto instance = new SystemAbilityManagerClient();
return *instance;
}
sptr<ISystemAbilityManager> SystemAbilityManagerClient::GetSystemAbilityManager()
{
HILOG_ERROR(" SystemAbilityManagerClient::GetSystemAbilityManager()");
return SystemAbilityManager::GetInstance();
}
sptr<IRemoteObject> SystemAbilityManagerClient::GetRegistryRemoteObject()
{
HILOG_ERROR("SystemAbilityManagerClient::GetRegistryRemoteObject()");
return nullptr;
}
void SystemAbilityManagerClient::DestroySystemAbilityManagerObject()
{
HILOG_ERROR("SystemAbilityManagerClient::DestroySystemAbilityManagerObject()");
}
} // namespace OHOS
@@ -0,0 +1,46 @@
/*
* 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 "ability_info.h"
#include "application_info.h"
#include "mock_bundle_manager.h"
namespace OHOS {
namespace AppExecFwk {
void MockBundleMgrService::MockSetIsSystemApp(bool isSystemApp)
{
isSystemAppMock_ = true;
isSystemApp_ = isSystemApp;
}
bool MockBundleMgrService::CheckIsSystemAppByUid(const int uid)
{
HILOG_ERROR("MockBundleMgrService::CheckIsSystemAppByUid beagin**********");
if (isSystemAppMock_) {
return isSystemApp_;
}
return (uid < 1000) ? false : true;
}
int MockBundleMgrService::CheckPermission(const std::string &bundleName, const std::string &permission)
{
if (!bundleName.compare("hello")) {
return 0;
} else {
return -1;
}
}
} // namespace AppExecFwk
} // namespace OHOS
@@ -0,0 +1,25 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ipc_object_stub.h"
namespace OHOS {
namespace AppExecFwk {} // namespace AppExecFwk
using namespace OHOS::AppExecFwk;
bool IPCObjectStub::AddDeathRecipient(const sptr<DeathRecipient> &recipient)
{
return true;
}
} // namespace OHOS
@@ -0,0 +1,299 @@
/*
* 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 "system_ability_manager.h"
#include <cinttypes>
#include <unistd.h>
#include "ability_death_recipient.h"
#include "datetime_ex.h"
#include "errors.h"
#include "hilog_wrapper.h"
#include "if_local_ability_manager.h"
#include "local_ability_manager_proxy.h"
#include "sam_log.h"
#include "string_ex.h"
#include "system_ability_connection_callback_proxy.h"
#include "system_ability_definition.h"
#include "tools.h"
using namespace std;
namespace OHOS {
std::mutex SystemAbilityManager::instanceLock;
sptr<SystemAbilityManager> SystemAbilityManager::instance;
SystemAbilityManager::SystemAbilityManager()
{}
SystemAbilityManager::~SystemAbilityManager()
{}
void SystemAbilityManager::Init()
{}
const sptr<DBinderService> SystemAbilityManager::GetDBinder() const
{
return nullptr;
}
sptr<SystemAbilityManager> SystemAbilityManager::GetInstance()
{
HILOG_ERROR("SystemAbilityManager::GetInstance");
std::lock_guard<std::mutex> autoLock(instanceLock);
if (instance == nullptr) {
instance = new SystemAbilityManager;
}
return instance;
}
void SystemAbilityManager::DoSADataStorageInit()
{}
sptr<IRemoteObject> SystemAbilityManager::GetSystemAbility(int32_t systemAbilityId)
{
HILOG_ERROR("SystemAbilityManager::GetSystemAbility");
auto iter = abilityMap_.find(systemAbilityId);
if (iter != abilityMap_.end()) {
return iter->second.remoteObj;
}
HILOG_ERROR("SystemAbilityManager::GetSystemAbility nullptr");
return nullptr;
}
bool SystemAbilityManager::GetSystemAbilityInfoList(int32_t systemAbilityId, const std::u16string &capability,
std::list<std::shared_ptr<SystemAbilityInfo>> &saInfoList)
{
return true;
}
sptr<IRemoteObject> SystemAbilityManager::CheckLocalAbilityManager(const u16string &strName)
{
return nullptr;
}
sptr<IRemoteObject> SystemAbilityManager::GetSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
{
return nullptr;
}
sptr<IRemoteObject> SystemAbilityManager::CheckSystemAbility(int32_t systemAbilityId)
{
return nullptr;
}
bool SystemAbilityManager::CheckDistributedPermission()
{
return true;
}
sptr<IRemoteObject> SystemAbilityManager::CheckSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
{
return nullptr;
}
int32_t SystemAbilityManager::FindSystemAbilityManagerNotify(int32_t systemAbilityId, int code)
{
return 0;
}
int32_t SystemAbilityManager::FindSystemAbilityManagerNotify(
int32_t systemAbilityId, const std::string &deviceId, int code)
{
return ERR_OK;
}
bool SystemAbilityManager::IsNameInValid(const std::u16string &name)
{
return false;
}
int32_t SystemAbilityManager::AddOnDemandSystemAbilityInfo(
int32_t systemAbilityId, const std::u16string &localAbilityManagerName)
{
return ERR_OK;
}
int32_t SystemAbilityManager::RecycleOnDemandSystemAbility()
{
return ERR_OK;
}
int32_t SystemAbilityManager::StartOnDemandAbility(int32_t systemAbilityId)
{
return ERR_INVALID_VALUE;
}
sptr<IRemoteObject> SystemAbilityManager::CheckSystemAbility(int32_t systemAbilityId, bool &isExist)
{
return nullptr;
}
int32_t SystemAbilityManager::ConnectSystemAbility(
int32_t systemAbilityId, const sptr<ISystemAbilityConnectionCallback> &connectionCallback)
{
return ERR_OK;
}
int32_t SystemAbilityManager::DisConnectSystemAbility(
int32_t systemAbilityId, const sptr<ISystemAbilityConnectionCallback> &connectionCallback)
{
return ERR_OK;
}
bool SystemAbilityManager::CheckCapability(const std::u16string &capability)
{
return true;
}
int32_t SystemAbilityManager::AddLocalAbilityManager(const u16string &strName, const sptr<IRemoteObject> &ability)
{
return ERR_OK;
}
void SystemAbilityManager::DoInsertSaData(
const u16string &strName, const sptr<IRemoteObject> &ability, const SAExtraProp &extraProp)
{}
void SystemAbilityManager::DeleteStartingAbilityMember(int32_t systemAbilityId)
{}
int32_t SystemAbilityManager::RemoveSystemAbility(int32_t systemAbilityId)
{
abilityMap_.clear();
return ERR_OK;
}
int32_t SystemAbilityManager::RemoveLocalAbilityManager(const u16string &strName)
{
return ERR_OK;
}
int32_t SystemAbilityManager::RemoveLocalAbilityManager(const sptr<IRemoteObject> &ability)
{
return ERR_OK;
}
int32_t SystemAbilityManager::RemoveSystemAbility(const sptr<IRemoteObject> &ability)
{
return ERR_OK;
}
vector<u16string> SystemAbilityManager::ListSystemAbilities(unsigned int dumpFlags)
{
vector<u16string> list;
return list;
}
u16string SystemAbilityManager::GetSystemAbilityName(int32_t index)
{
return u16string();
}
int32_t SystemAbilityManager::SubscribeSystemAbility(int32_t systemAbilityId, const u16string &listenerName)
{
return ERR_OK;
}
int32_t SystemAbilityManager::UnSubscribeSystemAbility(int32_t systemAbilityId, const u16string &listenerName)
{
return ERR_OK;
}
const std::u16string SystemAbilityManager::CheckOnDemandSystemAbility(int32_t systemAbilityId)
{
return deviceName_;
}
void SystemAbilityManager::SetDeviceName(const u16string &name)
{}
const u16string &SystemAbilityManager::GetDeviceName() const
{
return deviceName_;
}
bool SystemAbilityManager::GetDeviceId(string &deviceId)
{
return false;
}
void SystemAbilityManager::NotifyRemoteSaDied(const std::u16string &name)
{}
void SystemAbilityManager::NotifyRemoteDeviceOffline(const std::string &deviceId)
{}
void SystemAbilityManager::ParseRemoteSaName(const std::u16string &name, std::string &deviceId, std::u16string &saName)
{}
void SystemAbilityManager::OnDemandConnected(int32_t systemAbilityId, const sptr<IRemoteObject> &ability)
{}
int32_t SystemAbilityManager::AddSystemAbility(
int32_t systemAbilityId, const sptr<IRemoteObject> &ability, const SAExtraProp &extraProp)
{
SAInfo saInfo;
saInfo.remoteObj = ability;
saInfo.isDistributed = extraProp.isDistributed;
saInfo.capability = extraProp.capability;
saInfo.permission = Str16ToStr8(extraProp.permission);
abilityMap_[systemAbilityId] = std::move(saInfo);
return 0;
}
bool SystemAbilityManager::IsLocalDeviceId(const std::string &deviceId)
{
return false;
}
bool SystemAbilityManager::CheckRemoteSa(const std::string &saName, std::string &selectedDeviceId)
{
return false;
}
bool SystemAbilityManager::CheckPermission(const std::string &permission)
{
return true;
}
int32_t SystemAbilityManager::AddSystemCapability(const string &sysCap)
{
int32_t ret = ERR_INVALID_VALUE;
return ret;
}
vector<string> SystemAbilityManager::GetSystemAvailableCapabilities()
{
vector<string> sysCaps;
return sysCaps;
}
int32_t SystemAbilityManager::RegisterSystemReadyCallback(const sptr<IRemoteObject> &systemReadyCallback)
{
return ERR_OK;
}
int32_t SystemAbilityManager::GetCoreSystemAbilityList(vector<int32_t> &coreSaList, int dumpMode)
{
return ERR_OK;
}
bool SystemAbilityManager::HasSystemCapability(const string &sysCap)
{
return false;
}
} // namespace OHOS
@@ -0,0 +1,160 @@
/*
* 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 "system_ability_manager_stub.h"
#include "errors.h"
#include "ipc_skeleton.h"
#include "ipc_types.h"
#include "sam_log.h"
#include "string_ex.h"
#include "system_ability_info.h"
#include "tools.h"
namespace OHOS {
SystemAbilityManagerStub::SystemAbilityManagerStub()
{}
int32_t SystemAbilityManagerStub::OnRemoteRequest(
uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option)
{
return 0;
}
bool SystemAbilityManagerStub::EnforceInterceToken(MessageParcel &data)
{
return false;
}
int32_t SystemAbilityManagerStub::GetSystemAbilityInfoListInner(MessageParcel &data, MessageParcel &reply)
{
return ERR_NONE;
}
int32_t SystemAbilityManagerStub::CheckLocalAbilityInner(MessageParcel &data, MessageParcel &reply)
{
return ERR_NONE;
}
int32_t SystemAbilityManagerStub::AddLocalAbilityInner(MessageParcel &data, MessageParcel &reply)
{
return 0;
}
int32_t SystemAbilityManagerStub::RemoveLocalAbilityInner(MessageParcel &data, MessageParcel &reply)
{
return 0;
}
int32_t SystemAbilityManagerStub::ListSystemAbilityInner(MessageParcel &data, MessageParcel &reply)
{
return 0;
}
int32_t SystemAbilityManagerStub::SubsSystemAbilityInner(MessageParcel &data, MessageParcel &reply)
{
return 0;
}
int32_t SystemAbilityManagerStub::UnSubsSystemAbilityInner(MessageParcel &data, MessageParcel &reply)
{
return 0;
}
int32_t SystemAbilityManagerStub::CheckRemtSystemAbilityInner(MessageParcel &data, MessageParcel &reply)
{
return 0;
}
int32_t SystemAbilityManagerStub::CheckRemtSystemAbilityForJavaInner(MessageParcel &data, MessageParcel &reply)
{
return 0;
}
int32_t SystemAbilityManagerStub::AddOndemandSystemAbilityInner(MessageParcel &data, MessageParcel &reply)
{
return 0;
}
int32_t SystemAbilityManagerStub::RecycleOndemandSystemAbilityInner(MessageParcel &data, MessageParcel &reply)
{
return 0;
}
int32_t SystemAbilityManagerStub::CheckSystemAbilityImmeInner(MessageParcel &data, MessageParcel &reply)
{
return 0;
}
int32_t SystemAbilityManagerStub::ConnOndemandSystemAbilityInner(MessageParcel &data, MessageParcel &reply)
{
return 0;
}
int32_t SystemAbilityManagerStub::DisConnOndemandSystemAbilityInner(MessageParcel &data, MessageParcel &reply)
{
return 0;
}
int32_t SystemAbilityManagerStub::CheckOndemandSystemAbilityInner(MessageParcel &data, MessageParcel &reply)
{
return 0;
}
int32_t SystemAbilityManagerStub::GetDeviceIdInner(MessageParcel &data, MessageParcel &reply)
{
return 0;
}
int32_t SystemAbilityManagerStub::UnmarshalingSaExtraProp(MessageParcel &data, SAExtraProp &extraProp)
{
return 0;
}
int32_t SystemAbilityManagerStub::AddSystemAbilityInner(MessageParcel &data, MessageParcel &reply)
{
return 0;
}
int32_t SystemAbilityManagerStub::GetSystemAbilityInner(MessageParcel &data, MessageParcel &reply)
{
return 0;
}
int32_t SystemAbilityManagerStub::CheckSystemAbilityInner(MessageParcel &data, MessageParcel &reply)
{
return 0;
}
int32_t SystemAbilityManagerStub::RemoveSystemAbilityInner(MessageParcel &data, MessageParcel &reply)
{
return 0;
}
int32_t SystemAbilityManagerStub::GetHapIdMultiuser(int32_t uid)
{
return 0;
}
bool SystemAbilityManagerStub::CanRequest()
{
return true;
}
bool SystemAbilityManagerStub::IsSystemApp(int32_t callingUid)
{
return true;
}
} // namespace OHOS
+36
View File
@@ -0,0 +1,36 @@
#
# 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("//base/notification/ces_standard/event.gni")
cflags = []
config("module_test_config") {
include_dirs = [ "//third_party/json/include" ]
configs = []
if (target_cpu == "arm") {
cflags += [ "-DBINDER_IPC_32BIT" ]
}
}
group("moduletest") {
testonly = true
deps = [
"common_event_services_module_test:moduletest_ces",
"common_event_services_publish_ordered_module_test:moduletest_cesOrdered",
]
}
@@ -0,0 +1,104 @@
#
# 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("//base/notification/ces_standard/event.gni")
import("//build/test.gni")
module_output_path = "ces_standard/mouduletest"
ohos_moduletest("cesModuleTest") {
module_out_path = module_output_path
sources = [
"//base/notification/ces_standard/cesfwk/services/test/mock/src/iservice_registry.cpp",
"//base/notification/ces_standard/cesfwk/services/test/mock/src/mock_bundle_manager.cpp",
"//base/notification/ces_standard/cesfwk/services/test/mock/src/mock_ipc.cpp",
"//base/notification/ces_standard/cesfwk/services/test/mock/src/system_ability_manager.cpp",
"//base/notification/ces_standard/cesfwk/services/test/mock/src/system_ability_manager_stub.cpp",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_mgr_host.cpp",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_mgr_proxy.cpp",
"common_event_services_module_test.cpp",
]
configs = [ "//base/notification/ces_standard/test/systemtest/common/ces:cesfwk_kits_test_config" ]
include_dirs = [
"//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include",
"//foundation/aafwk/standard/interfaces/innerkits/base/include",
"//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content",
"//foundation/aafwk/standard/services/abilitymgr/include/",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include",
"//foundation/appexecfwk/standard/services/bundlemgr/include",
"//foundation/aafwk/standard/services/common/include",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr",
"//foundation/communication/ipc/ipc/dnetwork_temp",
"//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/include",
"//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include",
"//foundation/distributedschedule/dmsfwk/utils/native/include",
"//foundation/distributedschedule/safwk/services/safwk/include",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include",
"//foundation/distributedschedule/samgr/services/lsamgr/include",
"//foundation/distributedschedule/samgr/services/samgr/native/include",
"//foundation/distributedschedule/samgr/utils/native/include",
"//base/notification/ces_standard/cesfwk/innerkits/include",
"//base/notification/ces_standard/cesfwk/kits/native/include",
"//base/notification/ces_standard/cesfwk/services/include",
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/include",
"//base/notification/ces_standard/common/log/include",
"//third_party/json/include",
"//utils/native/base/include",
"//utils/system/safwk/native/include",
]
cflags = []
if (target_cpu == "arm") {
cflags += [ "-DBINDER_IPC_32BIT" ]
}
deps = [
"//base/notification/ces_standard/cesfwk/innerkits:cesfwk_innerkits",
"//base/notification/ces_standard/cesfwk/kits/native:cesfwk_kits",
"//base/notification/ces_standard/cesfwk/services:cesfwk_services",
"//base/notification/ces_standard/common:libevent_common",
"//foundation/aafwk/standard/interfaces/innerkits/want:want",
"//foundation/appexecfwk/standard/common:libappexecfwk_common",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler",
"//foundation/appexecfwk/standard/services/bundlemgr:libbms",
"//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//third_party/googletest:gtest_main",
"//utils/native/base:utils",
]
defines = [
"APP_LOG_TAG = \"CesFwkKitsTest\"",
"LOG_DOMAIN = 0xD002200",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"ipc:libdbinder",
]
}
group("moduletest_ces") {
testonly = true
deps = [ ":cesModuleTest" ]
}
@@ -0,0 +1,103 @@
#
# 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("//base/notification/ces_standard/event.gni")
import("//build/test.gni")
module_output_path = "ces_standard/mouduletest"
ohos_moduletest("CesPublishOrderedEventModuleTest") {
module_out_path = module_output_path
sources = [
"//base/notification/ces_standard/cesfwk/services/test/mock/src/iservice_registry.cpp",
"//base/notification/ces_standard/cesfwk/services/test/mock/src/mock_bundle_manager.cpp",
"//base/notification/ces_standard/cesfwk/services/test/mock/src/mock_ipc.cpp",
"//base/notification/ces_standard/cesfwk/services/test/mock/src/system_ability_manager.cpp",
"//base/notification/ces_standard/cesfwk/services/test/mock/src/system_ability_manager_stub.cpp",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_mgr_host.cpp",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_mgr_proxy.cpp",
"common_event_services_publish_ordered_module_test.cpp",
]
configs = [ "//base/notification/ces_standard/test/systemtest/common/ces:cesfwk_kits_test_config" ]
include_dirs = [
"//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include",
"//foundation/aafwk/standard/interfaces/innerkits/base/include",
"//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content",
"//foundation/aafwk/standard/services/abilitymgr/include/",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include",
"//foundation/appexecfwk/standard/services/bundlemgr/include",
"//foundation/aafwk/standard/services/common/include",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr",
"//foundation/communication/ipc/ipc/dnetwork_temp",
"//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/include",
"//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include",
"//foundation/distributedschedule/dmsfwk/utils/native/include",
"//foundation/distributedschedule/safwk/services/safwk/include",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include",
"//foundation/distributedschedule/samgr/services/lsamgr/include",
"//foundation/distributedschedule/samgr/services/samgr/native/include",
"//foundation/distributedschedule/samgr/utils/native/include",
"//base/notification/ces_standard/cesfwk/innerkits/include",
"//base/notification/ces_standard/cesfwk/kits/native/include",
"//base/notification/ces_standard/cesfwk/services/include",
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/include",
"//base/notification/ces_standard/common/log/include",
"//third_party/json/include",
"//utils/native/base/include",
"//utils/system/safwk/native/include",
]
cflags = []
if (target_cpu == "arm") {
cflags += [ "-DBINDER_IPC_32BIT" ]
}
deps = [
"//base/notification/ces_standard/cesfwk/innerkits:cesfwk_innerkits",
"//base/notification/ces_standard/cesfwk/kits/native:cesfwk_kits",
"//base/notification/ces_standard/cesfwk/services:cesfwk_services",
"//base/notification/ces_standard/common:libevent_common",
"//foundation/aafwk/standard/interfaces/innerkits/want:want",
"//foundation/appexecfwk/standard/common:libappexecfwk_common",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler",
"//foundation/appexecfwk/standard/services/bundlemgr:libbms",
"//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//third_party/googletest:gtest_main",
"//utils/native/base:utils",
]
defines = [
"APP_LOG_TAG = \"CesFwkKitsTest\"",
"LOG_DOMAIN = 0xD002200",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"ipc:libdbinder",
]
}
group("moduletest_cesOrdered") {
testonly = true
deps = [ ":CesPublishOrderedEventModuleTest" ]
}
+375
View File
@@ -0,0 +1,375 @@
# 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/test.gni")
module_output_path = "ces_standard/cesfwk/services"
config("cesfwk_services_config") {
visibility = [ ":*" ]
include_dirs = [
"//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include",
"//foundation/aafwk/standard/interfaces/innerkits/base/include",
"//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content",
"//foundation/aafwk/standard/services/abilitymgr/include/",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include",
"//foundation/appexecfwk/standard/services/bundlemgr/include",
"//foundation/aafwk/standard/services/common/include",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr",
"//foundation/communication/ipc/ipc/dnetwork_temp",
"//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/app_distributeddata/include",
"//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include",
"//foundation/distributedschedule/dmsfwk/utils/native/include",
"//foundation/distributedschedule/safwk/services/safwk/include",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include",
"//foundation/distributedschedule/samgr/services/lsamgr/include",
"//foundation/distributedschedule/samgr/services/samgr/native/include",
"//foundation/distributedschedule/samgr/utils/native/include",
"//base/notification/ces_standard/cesfwk/innerkits/include",
"//base/notification/ces_standard/cesfwk/kits/native/include",
"//base/notification/ces_standard/cesfwk/services/include",
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/include",
"//base/notification/ces_standard/common/log/include",
"//third_party/json/include",
"//utils/native/base/include",
"//utils/system/safwk/native/include",
]
cflags = []
if (target_cpu == "arm") {
cflags += [ "-DBINDER_IPC_32BIT" ]
}
}
ohos_unittest("common_event_publish_system_event_test") {
module_out_path = module_output_path
sources = [
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/src/iservice_registry.cpp",
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/src/mock_bundle_manager.cpp",
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/src/mock_ipc.cpp",
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/src/mock_system_ability_manager.cpp",
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/src/mock_system_ability_manager_stub.cpp",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_mgr_host.cpp",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_mgr_proxy.cpp",
"common_event_publish_system_event_test.cpp",
]
configs = [ ":cesfwk_services_config" ]
deps = [
"//base/notification/ces_standard/cesfwk/innerkits:cesfwk_innerkits",
"//base/notification/ces_standard/cesfwk/kits/native:cesfwk_kits",
"//base/notification/ces_standard/cesfwk/services:cesfwk_services",
"//base/notification/ces_standard/common:libevent_common",
"//foundation/aafwk/standard/interfaces/innerkits/want:want",
"//foundation/appexecfwk/standard/common:libappexecfwk_common",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler",
"//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//third_party/googletest:gtest_main",
"//utils/native/base:utils",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"ipc:libdbinder",
]
}
ohos_unittest("common_event_dump_test") {
module_out_path = module_output_path
sources = [
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/src/iservice_registry.cpp",
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/src/mock_bundle_manager.cpp",
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/src/mock_ipc.cpp",
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/src/mock_system_ability_manager.cpp",
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/src/mock_system_ability_manager_stub.cpp",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_mgr_host.cpp",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_mgr_proxy.cpp",
"common_event_dump_test.cpp",
]
configs = [ ":cesfwk_services_config" ]
deps = [
"//base/notification/ces_standard/cesfwk/innerkits:cesfwk_innerkits",
"//base/notification/ces_standard/cesfwk/kits/native:cesfwk_kits",
"//base/notification/ces_standard/cesfwk/services:cesfwk_services",
"//base/notification/ces_standard/common:libevent_common",
"//foundation/aafwk/standard/interfaces/innerkits/want:want",
"//foundation/appexecfwk/standard/common:libappexecfwk_common",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler",
"//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//third_party/googletest:gtest_main",
"//utils/native/base:utils",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"ipc:libdbinder",
]
}
ohos_unittest("common_event_freeze_test") {
module_out_path = module_output_path
sources = [
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/src/iservice_registry.cpp",
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/src/mock_bundle_manager.cpp",
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/src/mock_ipc.cpp",
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/src/mock_system_ability_manager.cpp",
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/src/mock_system_ability_manager_stub.cpp",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_mgr_host.cpp",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_mgr_proxy.cpp",
"common_event_freeze_test.cpp",
]
configs = [ ":cesfwk_services_config" ]
deps = [
"//base/notification/ces_standard/cesfwk/innerkits:cesfwk_innerkits",
"//base/notification/ces_standard/cesfwk/kits/native:cesfwk_kits",
"//base/notification/ces_standard/cesfwk/services:cesfwk_services",
"//base/notification/ces_standard/common:libevent_common",
"//foundation/aafwk/standard/interfaces/innerkits/want:want",
"//foundation/appexecfwk/standard/common:libappexecfwk_common",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler",
"//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//third_party/googletest:gtest_main",
"//utils/native/base:utils",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"ipc:libdbinder",
]
}
ohos_unittest("common_event_sticky_test") {
module_out_path = module_output_path
sources = [
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/src/iservice_registry.cpp",
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/src/mock_bundle_manager.cpp",
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/src/mock_ipc.cpp",
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/src/mock_system_ability_manager.cpp",
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/src/mock_system_ability_manager_stub.cpp",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_mgr_host.cpp",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_mgr_proxy.cpp",
"common_event_sticky_test.cpp",
]
configs = [ ":cesfwk_services_config" ]
deps = [
"//base/notification/ces_standard/cesfwk/innerkits:cesfwk_innerkits",
"//base/notification/ces_standard/cesfwk/kits/native:cesfwk_kits",
"//base/notification/ces_standard/cesfwk/services:cesfwk_services",
"//base/notification/ces_standard/common:libevent_common",
"//foundation/aafwk/standard/interfaces/innerkits/want:want",
"//foundation/appexecfwk/standard/common:libappexecfwk_common",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler",
"//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//third_party/googletest:gtest_main",
"//utils/native/base:utils",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"ipc:libdbinder",
]
}
ohos_unittest("common_event_subscribe_unit_test") {
module_out_path = module_output_path
sources = [
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/src/iservice_registry.cpp",
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/src/mock_bundle_manager.cpp",
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/src/mock_ipc.cpp",
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/src/mock_system_ability_manager.cpp",
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/src/mock_system_ability_manager_stub.cpp",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_mgr_host.cpp",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_mgr_proxy.cpp",
"common_event_subscribe_unit_test.cpp",
]
configs = [ ":cesfwk_services_config" ]
deps = [
"//base/notification/ces_standard/cesfwk/innerkits:cesfwk_innerkits",
"//base/notification/ces_standard/cesfwk/kits/native:cesfwk_kits",
"//base/notification/ces_standard/cesfwk/services:cesfwk_services",
"//base/notification/ces_standard/common:libevent_common",
"//foundation/aafwk/standard/interfaces/innerkits/want:want",
"//foundation/appexecfwk/standard/common:libappexecfwk_common",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler",
"//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//third_party/googletest:gtest_main",
"//utils/native/base:utils",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"ipc:libdbinder",
]
}
ohos_unittest("common_event_unsubscribe_unit_test") {
module_out_path = module_output_path
sources = [
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/src/iservice_registry.cpp",
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/src/mock_bundle_manager.cpp",
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/src/mock_system_ability_manager.cpp",
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/src/mock_system_ability_manager_stub.cpp",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_mgr_host.cpp",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_mgr_proxy.cpp",
"common_event_unsubscribe_unit_test.cpp",
]
configs = [ ":cesfwk_services_config" ]
deps = [
"//base/notification/ces_standard/cesfwk/innerkits:cesfwk_innerkits",
"//base/notification/ces_standard/cesfwk/kits/native:cesfwk_kits",
"//base/notification/ces_standard/cesfwk/services:cesfwk_services",
"//base/notification/ces_standard/common:libevent_common",
"//foundation/aafwk/standard/interfaces/innerkits/want:want",
"//foundation/appexecfwk/standard/common:libappexecfwk_common",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler",
"//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//third_party/googletest:gtest_main",
"//utils/native/base:utils",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"ipc:libdbinder",
]
}
ohos_unittest("common_event_publish_ordered_event_unit_test") {
module_out_path = module_output_path
sources = [
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/src/iservice_registry.cpp",
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/src/mock_bundle_manager.cpp",
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/src/mock_ipc.cpp",
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/src/mock_system_ability_manager.cpp",
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/src/mock_system_ability_manager_stub.cpp",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_mgr_host.cpp",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_mgr_proxy.cpp",
"common_event_publish_ordered_event_unit_test.cpp",
]
configs = [ ":cesfwk_services_config" ]
deps = [
"//base/notification/ces_standard/cesfwk/innerkits:cesfwk_innerkits",
"//base/notification/ces_standard/cesfwk/kits/native:cesfwk_kits",
"//base/notification/ces_standard/cesfwk/services:cesfwk_services",
"//base/notification/ces_standard/common:libevent_common",
"//foundation/aafwk/standard/interfaces/innerkits/want:want",
"//foundation/appexecfwk/standard/common:libappexecfwk_common",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler",
"//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//third_party/googletest:gtest_main",
"//utils/native/base:utils",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"ipc:libdbinder",
]
}
ohos_unittest("common_event_publish_permission_event_unit_test") {
module_out_path = module_output_path
sources = [
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/src/iservice_registry.cpp",
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/src/mock_bundle_manager.cpp",
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/src/mock_ipc.cpp",
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/src/mock_system_ability_manager.cpp",
"//base/notification/ces_standard/cesfwk/services/test/unittest/mock/src/mock_system_ability_manager_stub.cpp",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_mgr_host.cpp",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/src/bundlemgr/bundle_mgr_proxy.cpp",
"common_event_publish_permission_event_unit_test.cpp",
]
configs = [ ":cesfwk_services_config" ]
deps = [
"//base/notification/ces_standard/cesfwk/innerkits:cesfwk_innerkits",
"//base/notification/ces_standard/cesfwk/kits/native:cesfwk_kits",
"//base/notification/ces_standard/cesfwk/services:cesfwk_services",
"//base/notification/ces_standard/common:libevent_common",
"//foundation/aafwk/standard/interfaces/innerkits/want:want",
"//foundation/appexecfwk/standard/common:libappexecfwk_common",
"//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base",
"//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler",
"//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk",
"//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy",
"//third_party/googletest:gtest_main",
"//utils/native/base:utils",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"ipc:libdbinder",
]
}
group("unittest") {
testonly = true
deps = []
deps += [
":common_event_dump_test",
":common_event_freeze_test",
":common_event_publish_ordered_event_unit_test",
":common_event_publish_permission_event_unit_test",
":common_event_publish_system_event_test",
":common_event_sticky_test",
":common_event_subscribe_unit_test",
":common_event_unsubscribe_unit_test",
]
}
+999
View File
@@ -0,0 +1,999 @@
/*
* 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 <iostream>
#define private public
#define protected public
#include "common_event.h"
#include "common_event_manager_service.h"
#undef private
#undef protected
#include "inner_common_event_manager.h"
#include "iservice_registry.h"
#include "mock_bundle_manager.h"
#include "system_ability_definition.h"
#include <gtest/gtest.h>
using namespace testing::ext;
using namespace OHOS::EventFwk;
namespace {
const std::string EVENT = "com.ces.test.event";
const std::string ENTITY = "com.ces.test.entity";
const std::string SCHEME = "com.ces.test.scheme";
const std::string PERMISSION = "com.ces.test.permission";
const std::string DEVICEDID = "deviceId";
const std::string TYPE = "type";
const std::string BUNDLE = "BundleName";
const std::string ABILITY = "AbilityName";
const int PRIORITY = 1;
const int FLAG = 1;
const int CODE = 1;
const std::string DATA = "DATA";
const std::string EVENT2 = "com.ces.test.event2";
const std::string ENTITY2 = "com.ces.test.entity2";
const std::string SCHEME2 = "com.ces.test.scheme2";
const std::string PERMISSION2 = "com.ces.test.permission2";
const std::string DEVICEDID2 = "deviceId2";
const std::string TYPE2 = "type2";
const std::string BUNDLE2 = "BundleName";
const std::string ABILITY2 = "AbilityName";
const int PRIORITY2 = 2;
const int FLAG2 = 2;
const int CODE2 = 2;
const std::string DATA2 = "DATA2";
const std::string EVENT3 = "com.ces.test.event3";
} // namespace
static OHOS::sptr<OHOS::IRemoteObject> bundleObject = nullptr;
class CommonEventDumpTest : public testing::Test {
public:
CommonEventDumpTest()
{}
~CommonEventDumpTest()
{}
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
void dumpInfoCount(const std::vector<std::string> &state, int desSubscribersCount, int desStickyCount)
{
int subscribersNum = 0;
int stickyNum = 0;
bool subFlag = false;
for (auto vec : state) {
GTEST_LOG_(INFO) << vec;
auto pos = vec.find("Subscribers:");
if (pos != string::npos) {
subFlag = true;
}
pos = vec.find("Sticky Events:");
if (pos != string::npos) {
subFlag = false;
}
if (subFlag) {
subscribersNum++;
} else {
stickyNum++;
}
}
EXPECT_EQ(subscribersNum, desSubscribersCount);
EXPECT_EQ(stickyNum, desStickyCount);
}
};
class SubscriberTest : public CommonEventSubscriber {
public:
SubscriberTest(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp)
{}
~SubscriberTest()
{}
virtual void OnReceiveEvent(const CommonEventData &data)
{}
};
void CommonEventDumpTest::SetUpTestCase(void)
{
bundleObject = new OHOS::AppExecFwk::MockBundleMgrService();
OHOS::sptr<OHOS::ISystemAbilityManager> systemAbilityManager =
OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
OHOS::ISystemAbilityManager::SAExtraProp saExtraProp;
systemAbilityManager->AddSystemAbility(OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, bundleObject, saExtraProp);
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->OnStart();
}
void CommonEventDumpTest::TearDownTestCase(void)
{
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->OnStop();
}
void CommonEventDumpTest::SetUp(void)
{}
void CommonEventDumpTest::TearDown(void)
{}
static void SetMatchingSkills(MatchingSkills& matchingSkills)
{
matchingSkills.AddEvent(EVENT);
matchingSkills.AddEvent(EVENT2);
matchingSkills.AddEntity(ENTITY);
matchingSkills.AddEntity(ENTITY2);
matchingSkills.AddScheme(SCHEME);
matchingSkills.AddScheme(SCHEME2);
}
static void SetSubscriberInfo1(CommonEventListener *&listener, MatchingSkills& matchingSkills)
{
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
subscriberInfo.SetPriority(PRIORITY);
subscriberInfo.SetPermission(PERMISSION);
subscriberInfo.SetDeviceId(DEVICEDID);
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
listener = new CommonEventListener(subscriber);
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->SubscribeCommonEvent(
subscriberInfo, listener->AsObject());
}
static void SetSubscriberInfo2(CommonEventListener *&listener2, MatchingSkills& matchingSkills)
{
CommonEventSubscribeInfo subscriberInfo2(matchingSkills);
subscriberInfo2.SetPriority(PRIORITY2);
subscriberInfo2.SetPermission(PERMISSION2);
subscriberInfo2.SetDeviceId(DEVICEDID2);
std::shared_ptr<SubscriberTest> subscriber2 = std::make_shared<SubscriberTest>(subscriberInfo2);
listener2 = new CommonEventListener(subscriber2);
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->SubscribeCommonEvent(
subscriberInfo2, listener2->AsObject());
}
static void Test0100Publish1()
{
Want want;
want.SetAction(EVENT);
want.AddEntity(ENTITY);
want.AddEntity(ENTITY2);
want.SetType(TYPE);
want.SetFlags(FLAG);
OHOS::AppExecFwk::ElementName element;
element.SetBundleName(BUNDLE);
element.SetAbilityName(ABILITY);
element.SetDeviceID(DEVICEDID);
want.SetElement(element);
// make common event data
CommonEventData data;
data.SetWant(want);
data.SetCode(CODE);
data.SetData(DATA);
// make publish info
CommonEventPublishInfo publishInfo;
publishInfo.SetSticky(false);
std::vector<std::string> permissions;
permissions.emplace_back(PERMISSION);
publishInfo.SetSubscriberPermissions(permissions);
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->PublishCommonEvent(data, publishInfo, nullptr);
}
static void Test0100Publish2()
{
Want want2;
want2.SetAction(EVENT2);
want2.AddEntity(ENTITY);
want2.AddEntity(ENTITY2);
want2.SetType(TYPE2);
want2.SetFlags(FLAG2);
OHOS::AppExecFwk::ElementName element2;
element2.SetBundleName(BUNDLE);
element2.SetAbilityName(ABILITY);
element2.SetDeviceID(DEVICEDID);
want2.SetElement(element2);
// make common event data
CommonEventData data2;
data2.SetWant(want2);
data2.SetCode(CODE2);
data2.SetData(DATA2);
// make publish info
CommonEventPublishInfo publishInfo2;
publishInfo2.SetSticky(false);
std::vector<std::string> permissions;
permissions.emplace_back(PERMISSION2);
publishInfo2.SetSubscriberPermissions(permissions);
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->PublishCommonEvent(data2, publishInfo2, nullptr);
}
static void Test0200Publish1()
{
Want want;
want.SetAction(EVENT);
want.AddEntity(ENTITY);
want.AddEntity(ENTITY2);
want.SetType(TYPE);
want.SetFlags(FLAG);
OHOS::AppExecFwk::ElementName element;
element.SetBundleName(BUNDLE);
element.SetAbilityName(ABILITY);
element.SetDeviceID(DEVICEDID);
want.SetElement(element);
// make common event data
CommonEventData data;
data.SetWant(want);
data.SetCode(CODE);
data.SetData(DATA);
// make publish info
CommonEventPublishInfo publishInfo;
publishInfo.SetSticky(true);
std::vector<std::string> permissions;
permissions.emplace_back(PERMISSION);
publishInfo.SetSubscriberPermissions(permissions);
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->PublishCommonEvent(data, publishInfo, nullptr);
}
static void Test0200Publish2()
{
Want want2;
want2.SetAction(EVENT2);
want2.AddEntity(ENTITY);
want2.AddEntity(ENTITY2);
want2.SetType(TYPE2);
want2.SetFlags(FLAG2);
OHOS::AppExecFwk::ElementName element2;
element2.SetBundleName(BUNDLE);
element2.SetAbilityName(ABILITY);
element2.SetDeviceID(DEVICEDID);
want2.SetElement(element2);
// make common event data
CommonEventData data2;
data2.SetWant(want2);
data2.SetCode(CODE2);
data2.SetData(DATA2);
// make publish info
CommonEventPublishInfo publishInfo2;
publishInfo2.SetSticky(true);
std::vector<std::string> permissions;
permissions.emplace_back(PERMISSION2);
publishInfo2.SetSubscriberPermissions(permissions);
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->PublishCommonEvent(data2, publishInfo2, nullptr);
}
/*
* @tc.number: CommonEventDumpTest_0100
* @tc.name: test dump
* @tc.desc: Verify after subscribe can get subscriber info to do uid is not right
*/
HWTEST_F(CommonEventDumpTest, CommonEventDumpTest_0100, Function | MediumTest | Level1)
{
/* Subscribe */
MatchingSkills matchingSkills;
CommonEventListener *listener = nullptr;
CommonEventListener *listener2 = nullptr;
SetMatchingSkills(matchingSkills);
SetSubscriberInfo1(listener, matchingSkills);
SetSubscriberInfo2(listener2, matchingSkills);
/* Publish */
Test0100Publish1();
Test0100Publish2();
sleep(1);
std::vector<std::string> state;
bool dumpResult = OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->DumpState("", state);
EXPECT_EQ(true, dumpResult);
GTEST_LOG_(INFO) << "get state size:" << state.size();
dumpInfoCount(state, 2, 1);
EXPECT_EQ("Sticky Events:\tNo information", state[2]);
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->UnsubscribeCommonEvent(listener->AsObject());
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->UnsubscribeCommonEvent(listener2->AsObject());
}
/*
* @tc.number: CommonEventDumpTest_0200
* @tc.name: test dump
* @tc.desc: Verify after subscribe can get subscriber info to do uid is not right
*/
HWTEST_F(CommonEventDumpTest, CommonEventDumpTest_0200, Function | MediumTest | Level1)
{
/* Subscribe */
MatchingSkills matchingSkills;
CommonEventListener *listener = nullptr;
CommonEventListener *listener2 = nullptr;
SetMatchingSkills(matchingSkills);
SetSubscriberInfo1(listener, matchingSkills);
SetSubscriberInfo2(listener2, matchingSkills);
/* Publish */
Test0200Publish1();
Test0200Publish2();
sleep(1);
std::vector<std::string> state;
bool dumpResult = OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->DumpState("", state);
EXPECT_EQ(true, dumpResult);
GTEST_LOG_(INFO) << "get state size:" << state.size();
dumpInfoCount(state, 2, 2);
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->UnsubscribeCommonEvent(listener->AsObject());
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->UnsubscribeCommonEvent(listener2->AsObject());
}
/*
* @tc.number: CommonEventDumpTest_0300
* @tc.name: test dump
* @tc.desc: Verify after subscribe can get subscriber info to do uid is not right
*/
HWTEST_F(CommonEventDumpTest, CommonEventDumpTest_0300, Function | MediumTest | Level1)
{
/* Publish */
// make a want
Want want;
want.SetAction(EVENT);
want.AddEntity(ENTITY);
want.AddEntity(ENTITY2);
want.SetType(TYPE);
want.SetFlags(FLAG);
OHOS::AppExecFwk::ElementName element;
element.SetBundleName(BUNDLE);
element.SetAbilityName(ABILITY);
element.SetDeviceID(DEVICEDID);
want.SetElement(element);
// make common event data
CommonEventData data;
data.SetWant(want);
// make publish info
CommonEventPublishInfo publishInfo;
publishInfo.SetSticky(true);
std::vector<std::string> permissions;
permissions.emplace_back(PERMISSION);
publishInfo.SetSubscriberPermissions(permissions);
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->PublishCommonEvent(data, publishInfo, nullptr);
// make a want
Want want2;
want2.SetAction(EVENT2);
want2.AddEntity(ENTITY);
want2.AddEntity(ENTITY2);
want2.SetType(TYPE2);
want2.SetFlags(FLAG2);
OHOS::AppExecFwk::ElementName element2;
element2.SetBundleName(BUNDLE);
element2.SetAbilityName(ABILITY);
element2.SetDeviceID(DEVICEDID);
want2.SetElement(element2);
// make common event data
CommonEventData data2;
data2.SetWant(want2);
// make publish info
CommonEventPublishInfo publishInfo2;
publishInfo2.SetSticky(true);
permissions.emplace_back(PERMISSION2);
publishInfo2.SetSubscriberPermissions(permissions);
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->PublishCommonEvent(data2, publishInfo2, nullptr);
sleep(1);
std::vector<std::string> state;
bool dumpResult = OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->DumpState("", state);
EXPECT_EQ(true, dumpResult);
GTEST_LOG_(INFO) << "get state size:" << state.size();
dumpInfoCount(state, 1, 2);
EXPECT_EQ("Subscribers:\tNo information", state[0]);
}
/*
* @tc.number: CommonEventDumpTest_0400
* @tc.name: test dump
* @tc.desc: Verify after subscribe can get subscriber info to do uid is not right
*/
HWTEST_F(CommonEventDumpTest, CommonEventDumpTest_0400, Function | MediumTest | Level1)
{
/* Subscribe */
MatchingSkills matchingSkills;
matchingSkills.AddEvent(EVENT);
matchingSkills.AddScheme(SCHEME);
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
subscriberInfo.SetPriority(PRIORITY);
subscriberInfo.SetPermission(PERMISSION);
subscriberInfo.SetDeviceId(DEVICEDID);
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
CommonEventListener *listener = new CommonEventListener(subscriber);
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->SubscribeCommonEvent(
subscriberInfo, listener->AsObject());
sleep(1);
std::vector<std::string> state;
bool dumpResult = OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->DumpState("", state);
EXPECT_EQ(true, dumpResult);
GTEST_LOG_(INFO) << "get state size:" << state.size();
dumpInfoCount(state, 1, 2);
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->UnsubscribeCommonEvent(listener->AsObject());
}
/*
* @tc.number: CommonEventDumpTest_0500
* @tc.name: test dump
* @tc.desc: Verify after subscribe can get subscriber info to do uid is not right
*/
HWTEST_F(CommonEventDumpTest, CommonEventDumpTest_0500, Function | MediumTest | Level1)
{
/* Subscribe */
MatchingSkills matchingSkills;
matchingSkills.AddEvent(EVENT);
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
subscriberInfo.SetPriority(PRIORITY);
subscriberInfo.SetPermission(PERMISSION);
subscriberInfo.SetDeviceId(DEVICEDID);
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
CommonEventListener *listener = new CommonEventListener(subscriber);
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->SubscribeCommonEvent(
subscriberInfo, listener->AsObject());
sleep(1);
std::vector<std::string> state;
bool dumpResult = OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->DumpState("", state);
EXPECT_EQ(true, dumpResult);
GTEST_LOG_(INFO) << "get state size:" << state.size();
dumpInfoCount(state, 1, 2);
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->UnsubscribeCommonEvent(listener->AsObject());
}
/*
* @tc.number: CommonEventDumpTest_0600
* @tc.name: test dump
* @tc.desc: Verify after subscribe can get subscriber info to do uid is not right
*/
HWTEST_F(CommonEventDumpTest, CommonEventDumpTest_0600, Function | MediumTest | Level1)
{
/* Subscribe */
MatchingSkills matchingSkills;
matchingSkills.AddEvent(EVENT);
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
subscriberInfo.SetPermission(PERMISSION);
subscriberInfo.SetDeviceId(DEVICEDID);
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
CommonEventListener *listener = new CommonEventListener(subscriber);
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->SubscribeCommonEvent(
subscriberInfo, listener->AsObject());
sleep(1);
std::vector<std::string> state;
bool dumpResult = OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->DumpState("", state);
EXPECT_EQ(true, dumpResult);
GTEST_LOG_(INFO) << "get state size:" << state.size();
dumpInfoCount(state, 1, 2);
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->UnsubscribeCommonEvent(listener->AsObject());
}
/*
* @tc.number: CommonEventDumpTest_0700
* @tc.name: test dump
* @tc.desc: Verify after subscribe can get subscriber info to do uid is not right
*/
HWTEST_F(CommonEventDumpTest, CommonEventDumpTest_0700, Function | MediumTest | Level1)
{
/* Subscribe */
MatchingSkills matchingSkills;
matchingSkills.AddEvent(EVENT);
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
subscriberInfo.SetDeviceId(DEVICEDID);
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
CommonEventListener *listener = new CommonEventListener(subscriber);
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->SubscribeCommonEvent(
subscriberInfo, listener->AsObject());
sleep(1);
std::vector<std::string> state;
bool dumpResult = OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->DumpState("", state);
EXPECT_EQ(true, dumpResult);
GTEST_LOG_(INFO) << "get state size:" << state.size();
dumpInfoCount(state, 1, 2);
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->UnsubscribeCommonEvent(listener->AsObject());
}
/*
* @tc.number: CommonEventDumpTest_0800
* @tc.name: test dump
* @tc.desc: Verify after subscribe can get subscriber info to do uid is not right
*/
HWTEST_F(CommonEventDumpTest, CommonEventDumpTest_0800, Function | MediumTest | Level1)
{
/* Subscribe */
MatchingSkills matchingSkills;
matchingSkills.AddEvent(EVENT);
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
CommonEventListener *listener = new CommonEventListener(subscriber);
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->SubscribeCommonEvent(
subscriberInfo, listener->AsObject());
sleep(1);
std::vector<std::string> state;
bool dumpResult = OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->DumpState("", state);
EXPECT_EQ(true, dumpResult);
GTEST_LOG_(INFO) << "get state size:" << state.size();
dumpInfoCount(state, 1, 2);
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->UnsubscribeCommonEvent(listener->AsObject());
}
/*
* @tc.number: CommonEventDumpTest_0900
* @tc.name: test dump
* @tc.desc: Verify after subscribe can get subscriber info to do uid is not right
*/
HWTEST_F(CommonEventDumpTest, CommonEventDumpTest_0900, Function | MediumTest | Level1)
{
/* Subscribe */
MatchingSkills matchingSkills;
matchingSkills.AddEvent(EVENT);
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
CommonEventListener *listener = new CommonEventListener(subscriber);
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->SubscribeCommonEvent(
subscriberInfo, listener->AsObject());
sleep(1);
std::vector<std::string> state;
bool dumpResult = OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->DumpState(EVENT3, state);
EXPECT_EQ(true, dumpResult);
GTEST_LOG_(INFO) << "get state size:" << state.size();
dumpInfoCount(state, 1, 1);
EXPECT_EQ("Subscribers:\tNo information", state[0]);
EXPECT_EQ("Sticky Events:\tNo information", state[1]);
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->UnsubscribeCommonEvent(listener->AsObject());
}
void Test100Publish1()
{
Want want;
want.SetAction(EVENT);
want.AddEntity(ENTITY);
want.AddEntity(ENTITY2);
want.SetType(TYPE);
want.SetFlags(FLAG);
OHOS::AppExecFwk::ElementName element;
element.SetBundleName(BUNDLE);
element.SetAbilityName(ABILITY);
element.SetDeviceID(DEVICEDID);
want.SetElement(element);
// make common event data
CommonEventData data;
data.SetWant(want);
// make publish info
CommonEventPublishInfo publishInfo;
publishInfo.SetSticky(true);
std::vector<std::string> permissions;
permissions.emplace_back(PERMISSION);
publishInfo.SetSubscriberPermissions(permissions);
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->PublishCommonEvent(data, publishInfo, nullptr);
}
void Test100Publish2()
{
Want want2;
want2.SetAction(EVENT2);
want2.AddEntity(ENTITY);
want2.AddEntity(ENTITY2);
want2.SetType(TYPE2);
want2.SetFlags(FLAG2);
OHOS::AppExecFwk::ElementName element2;
element2.SetBundleName(BUNDLE);
element2.SetAbilityName(ABILITY);
element2.SetDeviceID(DEVICEDID);
want2.SetElement(element2);
// make common event data
CommonEventData data2;
data2.SetWant(want2);
// make publish info
CommonEventPublishInfo publishInfo2;
publishInfo2.SetSticky(true);
std::vector<std::string> permissions;
permissions.emplace_back(PERMISSION2);
publishInfo2.SetSubscriberPermissions(permissions);
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->PublishCommonEvent(data2, publishInfo2, nullptr);
}
/*
* @tc.number: CommonEventDumpTest_1000
* @tc.name: test dump
* @tc.desc: Verify after subscribe can get subscriber info to do uid is not right
*/
HWTEST_F(CommonEventDumpTest, CommonEventDumpTest_1000, TestSize.Level1)
{
/* Subscribe */
MatchingSkills matchingSkills;
CommonEventListener *listener = nullptr;
CommonEventListener *listener2 = nullptr;
SetMatchingSkills(matchingSkills);
SetSubscriberInfo1(listener, matchingSkills);
SetSubscriberInfo2(listener2, matchingSkills);
/* Publish */
//Publish1
Test100Publish1();
//Publish1
Test100Publish2();
sleep(1);
std::vector<std::string> state;
bool dumpResult = OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->DumpState(EVENT2, state);
EXPECT_EQ(true, dumpResult);
GTEST_LOG_(INFO) << "get state size:" << state.size();
dumpInfoCount(state, 2, 1);
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->UnsubscribeCommonEvent(listener->AsObject());
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->UnsubscribeCommonEvent(listener2->AsObject());
}
/*
* @tc.number: CommonEventDumpTest_1100
* @tc.name: test dump
* @tc.desc: Verify after subscribe can get subscriber info to do uid is not right
*/
HWTEST_F(CommonEventDumpTest, CommonEventDumpTest_1100, Function | MediumTest | Level1)
{
/* Publish */
// make a want
Want want;
want.SetAction(EVENT);
want.SetType(TYPE);
want.SetFlags(FLAG);
OHOS::AppExecFwk::ElementName element;
element.SetBundleName(BUNDLE);
element.SetAbilityName(ABILITY);
element.SetDeviceID(DEVICEDID);
want.SetElement(element);
// make common event data
CommonEventData data;
data.SetWant(want);
// make publish info
CommonEventPublishInfo publishInfo;
publishInfo.SetSticky(true);
std::vector<std::string> permissions;
permissions.emplace_back(PERMISSION);
publishInfo.SetSubscriberPermissions(permissions);
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->PublishCommonEvent(data, publishInfo, nullptr);
sleep(1);
std::vector<std::string> state;
bool dumpResult = OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->DumpState("", state);
EXPECT_EQ(true, dumpResult);
GTEST_LOG_(INFO) << "get state size:" << state.size();
dumpInfoCount(state, 1, 2);
}
/*
* @tc.number: CommonEventDumpTest_1200
* @tc.name: test dump
* @tc.desc: Verify after subscribe can get subscriber info to do uid is not right
*/
HWTEST_F(CommonEventDumpTest, CommonEventDumpTest_1200, Function | MediumTest | Level1)
{
/* Publish */
// make a want
Want want;
want.SetAction(EVENT);
want.SetFlags(FLAG);
OHOS::AppExecFwk::ElementName element;
element.SetBundleName(BUNDLE);
element.SetAbilityName(ABILITY);
element.SetDeviceID(DEVICEDID);
want.SetElement(element);
// make common event data
CommonEventData data;
data.SetWant(want);
// make publish info
CommonEventPublishInfo publishInfo;
publishInfo.SetSticky(true);
std::vector<std::string> permissions;
permissions.emplace_back(PERMISSION);
publishInfo.SetSubscriberPermissions(permissions);
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->PublishCommonEvent(data, publishInfo, nullptr);
sleep(1);
std::vector<std::string> state;
bool dumpResult = OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->DumpState("", state);
EXPECT_EQ(true, dumpResult);
GTEST_LOG_(INFO) << "get state size:" << state.size();
dumpInfoCount(state, 1, 2);
}
/*
* @tc.number: CommonEventDumpTest_1300
* @tc.name: test dump
* @tc.desc: Verify after subscribe can get subscriber info to do uid is not right
*/
HWTEST_F(CommonEventDumpTest, CommonEventDumpTest_1300, Function | MediumTest | Level1)
{
/* Publish */
// make a want
Want want;
want.SetAction(EVENT);
OHOS::AppExecFwk::ElementName element;
element.SetBundleName(BUNDLE);
element.SetAbilityName(ABILITY);
element.SetDeviceID(DEVICEDID);
want.SetElement(element);
// make common event data
CommonEventData data;
data.SetWant(want);
// make publish info
CommonEventPublishInfo publishInfo;
publishInfo.SetSticky(true);
std::vector<std::string> permissions;
permissions.emplace_back(PERMISSION);
publishInfo.SetSubscriberPermissions(permissions);
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->PublishCommonEvent(data, publishInfo, nullptr);
sleep(1);
std::vector<std::string> state;
bool dumpResult = OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->DumpState("", state);
EXPECT_EQ(true, dumpResult);
GTEST_LOG_(INFO) << "get state size:" << state.size();
dumpInfoCount(state, 1, 2);
}
/*
* @tc.number: CommonEventDumpTest_1400
* @tc.name: test dump
* @tc.desc: Verify after subscribe can get subscriber info to do uid is not right
*/
HWTEST_F(CommonEventDumpTest, CommonEventDumpTest_1400, Function | MediumTest | Level1)
{
/* Publish */
// make a want
Want want;
want.SetAction(EVENT);
OHOS::AppExecFwk::ElementName element;
element.SetAbilityName(ABILITY);
element.SetDeviceID(DEVICEDID);
want.SetElement(element);
// make common event data
CommonEventData data;
data.SetWant(want);
// make publish info
CommonEventPublishInfo publishInfo;
publishInfo.SetSticky(true);
std::vector<std::string> permissions;
permissions.emplace_back(PERMISSION);
publishInfo.SetSubscriberPermissions(permissions);
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->PublishCommonEvent(data, publishInfo, nullptr);
sleep(1);
std::vector<std::string> state;
bool dumpResult = OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->DumpState("", state);
EXPECT_EQ(true, dumpResult);
GTEST_LOG_(INFO) << "get state size:" << state.size();
dumpInfoCount(state, 1, 2);
}
/*
* @tc.number: CommonEventDumpTest_1500
* @tc.name: test dump
* @tc.desc: Verify after subscribe can get subscriber info to do uid is not right
*/
HWTEST_F(CommonEventDumpTest, CommonEventDumpTest_1500, Function | MediumTest | Level1)
{
/* Publish */
// make a want
Want want;
want.SetAction(EVENT);
OHOS::AppExecFwk::ElementName element;
element.SetDeviceID(DEVICEDID);
want.SetElement(element);
// make common event data
CommonEventData data;
data.SetWant(want);
// make publish info
CommonEventPublishInfo publishInfo;
publishInfo.SetSticky(true);
std::vector<std::string> permissions;
permissions.emplace_back(PERMISSION);
publishInfo.SetSubscriberPermissions(permissions);
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->PublishCommonEvent(data, publishInfo, nullptr);
sleep(1);
std::vector<std::string> state;
bool dumpResult = OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->DumpState("", state);
EXPECT_EQ(true, dumpResult);
GTEST_LOG_(INFO) << "get state size:" << state.size();
dumpInfoCount(state, 1, 2);
}
/*
* @tc.number: CommonEventDumpTest_1600
* @tc.name: test dump
* @tc.desc: Verify after subscribe can get subscriber info to do uid is not right
*/
HWTEST_F(CommonEventDumpTest, CommonEventDumpTest_1600, Function | MediumTest | Level1)
{
/* Publish */
// make a want
Want want;
want.SetAction(EVENT);
// make common event data
CommonEventData data;
data.SetWant(want);
// make publish info
CommonEventPublishInfo publishInfo;
publishInfo.SetSticky(true);
std::vector<std::string> permissions;
permissions.emplace_back(PERMISSION);
publishInfo.SetSubscriberPermissions(permissions);
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->PublishCommonEvent(data, publishInfo, nullptr);
sleep(1);
std::vector<std::string> state;
bool dumpResult = OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->DumpState("", state);
EXPECT_EQ(true, dumpResult);
GTEST_LOG_(INFO) << "get state size:" << state.size();
dumpInfoCount(state, 1, 2);
}
/*
* @tc.number: CommonEventDumpTest_1700
* @tc.name: test dump
* @tc.desc: Verify after subscribe can get subscriber info to do uid is not right
*/
HWTEST_F(CommonEventDumpTest, CommonEventDumpTest_1700, Function | MediumTest | Level1)
{
/* Publish */
// make a want
Want want;
want.SetAction(EVENT);
// make common event data
CommonEventData data;
data.SetWant(want);
// make publish info
CommonEventPublishInfo publishInfo;
publishInfo.SetSticky(true);
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->PublishCommonEvent(data, publishInfo, nullptr);
sleep(1);
std::vector<std::string> state;
bool dumpResult = OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->DumpState("", state);
EXPECT_EQ(true, dumpResult);
GTEST_LOG_(INFO) << "get state size:" << state.size();
dumpInfoCount(state, 1, 2);
}
+521
View File
@@ -0,0 +1,521 @@
/*
* 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 <gtest/gtest.h>
#define UNIT_TEST
#include "system_ability_definition.h"
#include "mock_bundle_manager.h"
#include "iservice_registry.h"
#include "inner_common_event_manager.h"
#include "common_event_sticky_manager.h"
#include "errors.h"
#define private public
#define protected public
#include "common_event.h"
#include "common_event_manager_service.h"
#include "common_event_manager.h"
#undef private
#undef protected
#include "datetime_ex.h"
using namespace testing::ext;
using namespace OHOS::EventFwk;
namespace {
const std::string EVENTCASE1 = "com.ces.test.event.case1";
const std::string EVENTCASE2 = "com.ces.test.event.case2";
const std::string EVENTCASE3 = "com.ces.test.event.case3";
const std::string EVENTCASE4 = "com.ces.test.event.case4";
const std::string EVENTCASE5 = "com.ces.test.event.case5";
const std::string EVENTCASE6 = "com.ces.test.event.case6";
const std::string EVENTCASE7 = "com.ces.test.event.case7";
const std::string INNITDATA = "com.ces.test.initdata";
const std::string CHANGEDATA = "com.ces.test.changedata";
const std::string CHANGEDATA2 = "com.ces.test.changedata2";
const int INNITCODE = 0;
const int CHANGECODE = 1;
const int CHANGECODE2 = 2;
const uid_t UID = 1;
const uid_t UID2 = 2;
const int PUBLISH_SLEEP = 1;
const int FREEZE_SLEEP = 10;
const int FREEZE_SLEEP2 = 120;
bool isFreeze_uid = false;
bool isFreeze_uid2 = false;
std::mutex mtx;
} // namespace
static OHOS::sptr<OHOS::IRemoteObject> bundleObject = nullptr;
OHOS::sptr<OHOS::IRemoteObject> commonEventListener;
OHOS::sptr<OHOS::IRemoteObject> commonEventListener2;
OHOS::sptr<OHOS::IRemoteObject> commonEventListener3;
class CommonEventFreezeTest : public testing::Test {
public:
CommonEventFreezeTest()
{}
~CommonEventFreezeTest()
{}
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
bool SubscribeCommonEvent(const std::shared_ptr<CommonEventSubscriber> &subscriber, uid_t callingUid,
OHOS::sptr<OHOS::IRemoteObject> &commonEventListener);
bool PublishCommonEvent(const CommonEventData &data, const CommonEventPublishInfo &publishInfo,
const std::shared_ptr<CommonEventSubscriber> &subscriber, OHOS::sptr<OHOS::IRemoteObject> &commonEventListener);
static bool FinishReceiver(
const OHOS::sptr<OHOS::IRemoteObject> &proxy, const int &code, const std::string &data, const bool &abortEvent);
bool Freeze(const uid_t &uid);
bool Unfreeze(const uid_t &uid);
void AsyncProcess();
private:
std::shared_ptr<EventRunner> runner_;
static std::shared_ptr<EventHandler> handler_;
static std::shared_ptr<InnerCommonEventManager> innerCommonEventManager_;
};
class SubscriberTest : public CommonEventSubscriber {
public:
SubscriberTest(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp)
{
handler_ = std::make_shared<EventHandler>(EventRunner::Create());
};
~SubscriberTest(){
};
virtual void OnReceiveEvent(const CommonEventData &data)
{
std::string action = data.GetWant().GetAction();
if (action == EVENTCASE1) {
ProcessSubscriberTestCase1(data);
} else if (action == EVENTCASE2) {
ProcessSubscriberTestCase2(data);
} else {
}
};
private:
void ProcessSubscriberTestCase1(CommonEventData data)
{
GTEST_LOG_(INFO) << "Subscriber1: Type: " << data.GetWant().GetType();
if (!IsOrderedCommonEvent()) {
return;
}
EXPECT_EQ(INNITCODE, data.GetCode());
EXPECT_EQ(INNITDATA, data.GetData());
std::shared_ptr<AsyncCommonEventResult> result = GoAsyncCommonEvent();
std::function<void()> asyncProcessFunc = std::bind(&SubscriberTest::AsyncProcess, this, commonEventListener);
handler_->PostTask(asyncProcessFunc);
}
void ProcessSubscriberTestCase2(CommonEventData data)
{
GTEST_LOG_(INFO) << "Subscriber1: Type: " << data.GetWant().GetType();
EXPECT_EQ(INNITCODE, data.GetCode());
EXPECT_EQ(INNITDATA, data.GetData());
}
void AsyncProcess(OHOS::sptr<OHOS::IRemoteObject> commonEventListener)
{
bool finishReceiverResult =
CommonEventFreezeTest::FinishReceiver(commonEventListener, CHANGECODE, CHANGEDATA, false);
EXPECT_EQ(true, finishReceiverResult);
}
private:
std::shared_ptr<EventHandler> handler_;
};
class SubscriberTest2 : public CommonEventSubscriber {
public:
SubscriberTest2(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp)
{
handler_ = std::make_shared<EventHandler>(EventRunner::Create());
};
~SubscriberTest2(){
};
virtual void OnReceiveEvent(const CommonEventData &data)
{
std::string action = data.GetWant().GetAction();
if (action == EVENTCASE1) {
ProcessSubscriberTest2Case1(data);
} else if (action == EVENTCASE2) {
ProcessSubscriberTest2Case2(data);
} else {
}
};
private:
void ProcessSubscriberTest2Case1(CommonEventData data)
{
GTEST_LOG_(INFO) << "Subscriber2: Type: " << data.GetWant().GetType();
if (!IsOrderedCommonEvent()) {
return;
}
if (!isFreeze_uid) {
EXPECT_EQ(CHANGECODE, data.GetCode());
EXPECT_EQ(CHANGEDATA, data.GetData());
} else {
EXPECT_EQ(INNITCODE, data.GetCode());
EXPECT_EQ(INNITDATA, data.GetData());
}
std::shared_ptr<AsyncCommonEventResult> result = GoAsyncCommonEvent();
std::function<void()> asyncProcessFunc = std::bind(&SubscriberTest2::AsyncProcess, this, commonEventListener2);
handler_->PostTask(asyncProcessFunc);
}
void ProcessSubscriberTest2Case2(CommonEventData data)
{
GTEST_LOG_(INFO) << "Subscriber2: Type: " << data.GetWant().GetType();
EXPECT_EQ(INNITCODE, data.GetCode());
EXPECT_EQ(INNITDATA, data.GetData());
}
void AsyncProcess(OHOS::sptr<OHOS::IRemoteObject> commonEventListener)
{
bool finishReceiverResult =
CommonEventFreezeTest::FinishReceiver(commonEventListener, CHANGECODE2, CHANGEDATA2, false);
EXPECT_EQ(true, finishReceiverResult);
}
private:
std::shared_ptr<EventHandler> handler_;
};
class SubscriberTestLast : public CommonEventSubscriber {
public:
SubscriberTestLast() : CommonEventSubscriber()
{
handler_ = std::make_shared<EventHandler>(EventRunner::Create());
};
SubscriberTestLast(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp)
{
handler_ = std::make_shared<EventHandler>(EventRunner::Create());
};
~SubscriberTestLast(){
};
virtual void OnReceiveEvent(const CommonEventData &data)
{
std::string action = data.GetWant().GetAction();
if (action == EVENTCASE1) {
ProcessSubscriberTestLastCase1(data);
} else if (action == EVENTCASE2) {
ProcessSubscriberTestLastCase2(data);
} else {
}
};
private:
void ProcessSubscriberTestLastCase1(CommonEventData data)
{
GTEST_LOG_(INFO) << "SubscriberLast: Type: " << data.GetWant().GetType();
if (!isFreeze_uid2) {
EXPECT_EQ(CHANGECODE2, data.GetCode());
EXPECT_EQ(CHANGEDATA2, data.GetData());
} else {
if (!isFreeze_uid) {
EXPECT_EQ(CHANGECODE, data.GetCode());
EXPECT_EQ(CHANGEDATA, data.GetData());
} else {
EXPECT_EQ(INNITCODE, data.GetCode());
EXPECT_EQ(INNITDATA, data.GetData());
}
}
std::shared_ptr<AsyncCommonEventResult> result = GoAsyncCommonEvent();
std::function<void()> asyncProcessFunc =
std::bind(&SubscriberTestLast::AsyncProcess, this, commonEventListener3);
handler_->PostTask(asyncProcessFunc);
}
void ProcessSubscriberTestLastCase2(CommonEventData data)
{}
void AsyncProcess(OHOS::sptr<OHOS::IRemoteObject> commonEventListener)
{
bool finishReceiverResult =
CommonEventFreezeTest::FinishReceiver(commonEventListener, CHANGECODE2, CHANGEDATA2, false);
EXPECT_EQ(true, finishReceiverResult);
}
private:
std::shared_ptr<EventHandler> handler_;
};
std::shared_ptr<EventHandler> CommonEventFreezeTest::handler_ = nullptr;
std::shared_ptr<InnerCommonEventManager> CommonEventFreezeTest::innerCommonEventManager_ = nullptr;
void CommonEventFreezeTest::SetUpTestCase(void)
{
bundleObject = new OHOS::AppExecFwk::MockBundleMgrService();
OHOS::sptr<OHOS::ISystemAbilityManager> systemAbilityManager =
OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
OHOS::ISystemAbilityManager::SAExtraProp saExtraProp;
systemAbilityManager->AddSystemAbility(OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, bundleObject, saExtraProp);
}
void CommonEventFreezeTest::TearDownTestCase(void)
{}
void CommonEventFreezeTest::SetUp(void)
{
runner_ = EventRunner::Create(true);
if (!runner_) {
return;
}
handler_ = std::make_shared<EventHandler>(runner_);
innerCommonEventManager_ = std::make_shared<InnerCommonEventManager>();
}
void CommonEventFreezeTest::TearDown(void)
{}
bool CommonEventFreezeTest::SubscribeCommonEvent(const std::shared_ptr<CommonEventSubscriber> &subscriber,
uid_t callingUid, OHOS::sptr<OHOS::IRemoteObject> &commonEventListener)
{
OHOS::sptr<IEventReceive> listener = new CommonEventListener(subscriber);
if (!listener) {
return false;
}
commonEventListener = listener->AsObject();
struct tm recordTime = {0};
if (!OHOS::GetSystemCurrentTime(&recordTime)) {
return false;
}
pid_t callingPid = 0;
std::string bundleName = "";
std::function<void()> SubscribeCommonEventFunc = std::bind(&InnerCommonEventManager::SubscribeCommonEvent,
innerCommonEventManager_,
subscriber->GetSubscribeInfo(),
commonEventListener,
recordTime,
callingPid,
callingUid,
bundleName);
return handler_->PostTask(SubscribeCommonEventFunc);
}
bool CommonEventFreezeTest::PublishCommonEvent(const CommonEventData &data, const CommonEventPublishInfo &publishInfo,
const std::shared_ptr<CommonEventSubscriber> &subscriber, OHOS::sptr<OHOS::IRemoteObject> &commonEventListener)
{
if (commonEventListener == nullptr && publishInfo.IsOrdered()) {
OHOS::sptr<IEventReceive> listener = new CommonEventListener(subscriber);
if (!listener) {
return false;
}
commonEventListener = listener->AsObject();
} else if (!publishInfo.IsOrdered()) {
commonEventListener = nullptr;
}
struct tm recordTime = {0};
if (!OHOS::GetSystemCurrentTime(&recordTime)) {
return false;
}
pid_t callingPid = 0;
uid_t callingUid = 0;
std::string bundleName = "";
std::function<void()> PublishCommonEventFunc = std::bind(&InnerCommonEventManager::PublishCommonEvent,
innerCommonEventManager_,
data,
publishInfo,
commonEventListener,
recordTime,
callingPid,
callingUid,
bundleName);
return handler_->PostTask(PublishCommonEventFunc);
}
bool CommonEventFreezeTest::FinishReceiver(
const OHOS::sptr<OHOS::IRemoteObject> &proxy, const int &code, const std::string &data, const bool &abortEvent)
{
std::function<void()> FinishReceiverFunc =
std::bind(&InnerCommonEventManager::FinishReceiver, innerCommonEventManager_, proxy, code, data, abortEvent);
return handler_->PostTask(FinishReceiverFunc);
}
bool CommonEventFreezeTest::Freeze(const uid_t &uid)
{
std::function<void()> FreezeFunc = std::bind(&InnerCommonEventManager::Freeze, innerCommonEventManager_, uid);
return handler_->PostImmediateTask(FreezeFunc);
}
bool CommonEventFreezeTest::Unfreeze(const uid_t &uid)
{
std::function<void()> UnfreezeFunc = std::bind(&InnerCommonEventManager::Unfreeze, innerCommonEventManager_, uid);
return handler_->PostImmediateTask(UnfreezeFunc);
}
void CommonEventFreezeTest::AsyncProcess()
{
isFreeze_uid = false;
isFreeze_uid2 = false;
sleep(FREEZE_SLEEP);
GTEST_LOG_(INFO) << "Subscriber1 Freeze";
Freeze(UID);
GTEST_LOG_(INFO) << "Subscriber2 Freeze";
Freeze(UID2);
isFreeze_uid = true;
isFreeze_uid2 = true;
sleep(FREEZE_SLEEP);
GTEST_LOG_(INFO) << "Subscriber1 Unfreeze";
Unfreeze(UID);
isFreeze_uid = false;
sleep(FREEZE_SLEEP2);
GTEST_LOG_(INFO) << "Subscriber2 Unfreeze";
Unfreeze(UID2);
isFreeze_uid2 = false;
sleep(FREEZE_SLEEP);
mtx.unlock();
}
HWTEST_F(CommonEventFreezeTest, CommonEventFreezeTest_001, TestSize.Level1)
{
/* Subscribe */
// make matching skills
MatchingSkills matchingSkills;
matchingSkills.AddEvent(EVENTCASE1);
// make subcriber info
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
// make a subcriber object
std::shared_ptr<SubscriberTest> subscriberTest = std::make_shared<SubscriberTest>(subscriberInfo);
// subscribe a common event
bool subscribeResult = SubscribeCommonEvent(subscriberTest, UID, commonEventListener);
EXPECT_EQ(true, subscribeResult);
// make another matching skills
MatchingSkills matchingSkillsAnother;
matchingSkillsAnother.AddEvent(EVENTCASE1);
// make another subcriber info
CommonEventSubscribeInfo subscriberInfo2(matchingSkillsAnother);
// make another subcriber object
std::shared_ptr<SubscriberTest2> subscriberTest2 = std::make_shared<SubscriberTest2>(subscriberInfo2);
// subscribe another event
bool subscribeResult2 = SubscribeCommonEvent(subscriberTest2, UID2, commonEventListener2);
EXPECT_EQ(true, subscribeResult2);
mtx.lock();
auto handler = std::make_shared<EventHandler>(EventRunner::Create());
std::function<void()> asyncProcessFunc = std::bind(&CommonEventFreezeTest::AsyncProcess, this);
handler->PostTask(asyncProcessFunc);
std::shared_ptr<SubscriberTestLast> subscriber = std::make_shared<SubscriberTestLast>();
/* Publish */
int i = 0;
while (!mtx.try_lock()) {
// make a want
Want want;
want.SetAction(EVENTCASE1);
i++;
want.SetType(std::to_string(i));
GTEST_LOG_(INFO) << "PublishCommonEvent: Type: " << std::to_string(i);
// make common event data
CommonEventData data;
data.SetWant(want);
data.SetData(INNITDATA);
data.SetCode(INNITCODE);
CommonEventPublishInfo publishInfo;
publishInfo.SetOrdered(true);
sleep(PUBLISH_SLEEP);
// publish order event
bool publishResult = PublishCommonEvent(data, publishInfo, subscriber, commonEventListener3);
EXPECT_EQ(true, publishResult);
}
sleep(PUBLISH_SLEEP);
mtx.unlock();
}
HWTEST_F(CommonEventFreezeTest, CommonEventFreezeTest_002, TestSize.Level1)
{
/* Subscribe */
// make matching skills
MatchingSkills matchingSkills;
matchingSkills.AddEvent(EVENTCASE2);
// make subcriber info
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
// make a subcriber object
std::shared_ptr<SubscriberTest> subscriberTest = std::make_shared<SubscriberTest>(subscriberInfo);
// subscribe a common event
bool subscribeResult = SubscribeCommonEvent(subscriberTest, UID, commonEventListener);
EXPECT_EQ(true, subscribeResult);
// make another matching skills
MatchingSkills matchingSkillsAnother;
matchingSkillsAnother.AddEvent(EVENTCASE2);
// make another subcriber info
CommonEventSubscribeInfo subscriberInfo2(matchingSkillsAnother);
// make another subcriber object
std::shared_ptr<SubscriberTest2> subscriberTest2 = std::make_shared<SubscriberTest2>(subscriberInfo2);
// subscribe another event
bool subscribeResult2 = SubscribeCommonEvent(subscriberTest2, UID2, commonEventListener2);
EXPECT_EQ(true, subscribeResult2);
mtx.lock();
auto handler = std::make_shared<EventHandler>(EventRunner::Create());
std::function<void()> asyncProcessFunc = std::bind(&CommonEventFreezeTest::AsyncProcess, this);
handler->PostTask(asyncProcessFunc);
std::shared_ptr<SubscriberTestLast> subscriber = nullptr;
/* Publish */
int i = 0;
while (!mtx.try_lock()) {
// make a want
Want want;
want.SetAction(EVENTCASE2);
i++;
want.SetType(std::to_string(i));
GTEST_LOG_(INFO) << "PublishCommonEvent: Type: " << std::to_string(i);
// make common event data
CommonEventData data;
data.SetWant(want);
data.SetData(INNITDATA);
data.SetCode(INNITCODE);
CommonEventPublishInfo publishInfo;
sleep(PUBLISH_SLEEP);
// publish order event
bool publishResult = PublishCommonEvent(data, publishInfo, subscriber, commonEventListener3);
EXPECT_EQ(true, publishResult);
}
sleep(PUBLISH_SLEEP);
mtx.unlock();
}
@@ -0,0 +1,869 @@
/*
* 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 "common_event.h"
// redefine private and protected since testcase need to invoke and test private function
#define private public
#define protected public
#include "common_event_control_manager.h"
#include "common_event_manager_service.h"
#undef private
#undef protected
#include "iservice_registry.h"
#include "mock_bundle_manager.h"
#include "system_ability_definition.h"
#include <gtest/gtest.h>
using namespace testing::ext;
using namespace OHOS::EventFwk;
namespace {
const std::string EVENT = "com.ces.test.event";
const std::string ENTITY = "com.ces.test.entity";
const std::string ACTION = "acion";
std::mutex mtx;
static OHOS::sptr<OHOS::IRemoteObject> bundleObject = nullptr;
CommonEventManagerService commonEventManagerService;
InnerCommonEventManager innerCommonEventManager;
std::shared_ptr<CommonEventControlManager> commonEventControlManager = std::make_shared<CommonEventControlManager>();
std::shared_ptr<EventHandler> handler_;
} // namespace
class CommonEventPublishOrderedEventUnitTest : public testing::Test {
public:
CommonEventPublishOrderedEventUnitTest()
{}
~CommonEventPublishOrderedEventUnitTest()
{}
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
class SubscriberTest : public CommonEventSubscriber {
public:
explicit SubscriberTest(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp)
{}
~SubscriberTest()
{}
virtual void OnReceiveEvent(const CommonEventData &data)
{
GTEST_LOG_(INFO) << "OnReceiveEvent receive";
mtx.unlock();
}
};
class LoggerTest : public OHOS::AppExecFwk::Logger {
public:
/**
* Processes the content of a specified string.
* @param message the content of a specified string.
*/
void Log(const std::string &line)
{
GTEST_LOG_(INFO) << line;
}
virtual ~LoggerTest()
{}
};
void CommonEventPublishOrderedEventUnitTest::SetUpTestCase(void)
{
handler_ = std::make_shared<EventHandler>(EventRunner::Create(true));
auto task = []() {
std::shared_ptr<LoggerTest> logtest = std::make_shared<LoggerTest>();
EventRunner::GetMainEventRunner()->SetLogger(logtest);
EventRunner::GetMainEventRunner()->Run();
};
handler_->PostTask(task);
bundleObject = new OHOS::AppExecFwk::MockBundleMgrService();
OHOS::sptr<OHOS::ISystemAbilityManager> systemAbilityManager =
OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
OHOS::ISystemAbilityManager::SAExtraProp saExtraProp;
systemAbilityManager->AddSystemAbility(OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, bundleObject, saExtraProp);
}
void CommonEventPublishOrderedEventUnitTest::TearDownTestCase(void)
{
EventRunner::GetMainEventRunner()->Stop();
}
void CommonEventPublishOrderedEventUnitTest::SetUp(void)
{
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->OnStart();
}
void CommonEventPublishOrderedEventUnitTest::TearDown(void)
{
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->OnStop();
}
/*
* @tc.number: CommonEventPublishOrderedUnitTest_0100
* @tc.name: test CommonEventPublishOrderedEventUnitTest
* @tc.desc: system run normally CaseDescription: Verify PublishCommonEvent success
*/
HWTEST_F(CommonEventPublishOrderedEventUnitTest, CommonEventPublishOrderedUnitTest_0100, Function | MediumTest | Level1)
{
/* Publish */
// make a want
Want want;
want.SetAction(EVENT);
want.AddEntity(ENTITY);
// make common event data
CommonEventData data;
data.SetWant(want);
// make publish infoPRIORITY
CommonEventPublishInfo publishInfo;
publishInfo.SetOrdered(true);
bool result = OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->PublishCommonEvent(
data, publishInfo, nullptr);
EXPECT_EQ(true, result);
}
/*
* @tc.number: CommonEventPublishOrderedUnitTest_0200
* @tc.name: test CommonEventPublishOrderedEventUnitTest
* @tc.desc: Verify PublishCommonEvent false because servie stop
*/
HWTEST_F(CommonEventPublishOrderedEventUnitTest, CommonEventPublishOrderedUnitTest_0200, Function | MediumTest | Level1)
{
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->OnStop();
/* Publish */
// make a want
Want want;
want.SetAction(EVENT);
want.AddEntity(ENTITY);
// make common event data
CommonEventData data;
data.SetWant(want);
// make publish infoPRIORITY
CommonEventPublishInfo publishInfo;
publishInfo.SetOrdered(true);
bool result = OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->PublishCommonEvent(
data, publishInfo, nullptr);
EXPECT_EQ(false, result);
}
/*
* @tc.number: CommonEventPublishOrderedUnitTest_0300
* @tc.name: test FinishReceiver
* @tc.desc: Verify FinishReceiver return false bacause service stop
*/
HWTEST_F(CommonEventPublishOrderedEventUnitTest, CommonEventPublishOrderedUnitTest_0300, Function | MediumTest | Level1)
{
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->OnStop();
MatchingSkills matchingSkills;
matchingSkills.AddEvent(EVENT);
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
CommonEventListener *proxy = new CommonEventListener(subscriber);
bool result = OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->FinishReceiver(
proxy, 0, "receiverdata", true);
EXPECT_EQ(false, result);
}
/*
* @tc.number: CommonEventPublishOrderedUnitTest_0400
* @tc.name: test Init
* @tc.desc: Verify Init fail because innerCommonEventManager_ is null
*/
HWTEST_F(CommonEventPublishOrderedEventUnitTest, CommonEventPublishOrderedUnitTest_0400, Function | MediumTest | Level1)
{
commonEventManagerService.innerCommonEventManager_ = nullptr;
OHOS::ErrCode code = commonEventManagerService.Init();
EXPECT_EQ(OHOS::ERR_INVALID_OPERATION, code);
}
/*
* @tc.number: CommonEventPublishOrderedUnitTest_0500
* @tc.name: test IsReady
* @tc.desc: Verify IsReady fail because innerCommonEventManager_ is null
*/
HWTEST_F(CommonEventPublishOrderedEventUnitTest, CommonEventPublishOrderedUnitTest_0500, Function | MediumTest | Level1)
{
commonEventManagerService.innerCommonEventManager_ = nullptr;
bool result = commonEventManagerService.IsReady();
EXPECT_EQ(false, result);
}
/*
* @tc.number: CommonEventPublishOrderedUnitTest_0600
* @tc.name: test IsReady
* @tc.desc: Verify IsReady fail because handler_ is null
*/
HWTEST_F(CommonEventPublishOrderedEventUnitTest, CommonEventPublishOrderedUnitTest_0600, Function | MediumTest | Level1)
{
commonEventManagerService.handler_ = nullptr;
bool result = commonEventManagerService.IsReady();
EXPECT_EQ(false, result);
}
/*
* @tc.number: CommonEventPublishOrderedUnitTest_0700
* @tc.name: test PublishCommonEvent
* @tc.desc: Verify InnerCommonEventManager PublishCommonEvent success
*/
HWTEST_F(CommonEventPublishOrderedEventUnitTest, CommonEventPublishOrderedUnitTest_0700, Function | MediumTest | Level1)
{
// make a want
Want want;
want.SetAction(ACTION);
// make common event data
CommonEventData data;
data.SetWant(want);
// make publish info
CommonEventPublishInfo publishInfo;
publishInfo.SetOrdered(true);
MatchingSkills matchingSkills;
// make subcriber info
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
// make a subcriber object
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
OHOS::sptr<CommonEventListener> commonEventListener = new CommonEventListener(subscriber);
mtx.lock();
struct tm curTime{0};
// publish ordered event
bool result =
innerCommonEventManager.PublishCommonEvent(data, publishInfo, commonEventListener, curTime, 0, 0, "bundlename");
EXPECT_EQ(true, result);
int count = 0;
while (!mtx.try_lock()) {
if (count == 0) {
GTEST_LOG_(INFO) << "Wait OnReceive callback function process";
count = 1;
} else {
usleep(100 * 1000);
}
}
mtx.unlock();
GTEST_LOG_(INFO) << "Testcase finished";
}
/*
* @tc.number: CommonEventPublishOrderedUnitTest_0800
* @tc.name: test PublishCommonEvent
* @tc.desc: Verify InnerCommonEventManager PublishCommonEvent fail because data has no aciton
*/
HWTEST_F(CommonEventPublishOrderedEventUnitTest, CommonEventPublishOrderedUnitTest_0800, Function | MediumTest | Level1)
{
// make common event data
CommonEventData data;
// make publish info
CommonEventPublishInfo publishInfo;
publishInfo.SetOrdered(true);
MatchingSkills matchingSkills;
// make subcriber info
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
// make a subcriber object
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
// make commonEventListener
OHOS::sptr<CommonEventListener> commonEventListener = new CommonEventListener(subscriber);
struct tm curTime{0};
// publish ordered event
bool result =
innerCommonEventManager.PublishCommonEvent(data, publishInfo, commonEventListener, curTime, 0, 0, "bundlename");
EXPECT_EQ(false, result);
}
/*
* @tc.number: CommonEventPublishOrderedUnitTest_0900
* @tc.name: test PublishCommonEvent
* @tc.desc: Verify CommonEventControlManager PublishCommonEvent success
*/
HWTEST_F(CommonEventPublishOrderedEventUnitTest, CommonEventPublishOrderedUnitTest_0900, Function | MediumTest | Level1)
{
// make a commonEventRecord
Want want;
want.SetAction(ACTION);
CommonEventData eventRef;
eventRef.SetWant(want);
CommonEventPublishInfo publishinfoRef;
std::shared_ptr<CommonEventData> commonEventData = std::make_shared<CommonEventData>(eventRef);
std::shared_ptr<CommonEventPublishInfo> publishInfo = std::make_shared<CommonEventPublishInfo>(publishinfoRef);
publishInfo->SetOrdered(true);
CommonEventRecord commonEventRecord;
commonEventRecord.commonEventData = commonEventData;
commonEventRecord.publishInfo = publishInfo;
commonEventRecord.pid = 0;
commonEventRecord.uid = 0;
commonEventRecord.bundleName = "bundleName";
// make subcriber info
MatchingSkills matchingSkills;
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
// make subcriber
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
// make commone event listener
OHOS::sptr<CommonEventListener> commonEventListener = new CommonEventListener(subscriber);
OHOS::sptr<OHOS::IRemoteObject> commonEventListenerPtr(commonEventListener);
mtx.lock();
bool result = commonEventControlManager->PublishCommonEvent(commonEventRecord, commonEventListenerPtr);
EXPECT_EQ(true, result);
int count = 0;
while (!mtx.try_lock()) {
if (count == 0) {
GTEST_LOG_(INFO) << "Wait OnReceive callback function process";
count = 1;
} else {
usleep(100 * 1000);
}
}
mtx.unlock();
GTEST_LOG_(INFO) << "Testcase finished";
}
/*
* @tc.number: CommonEventPublishOrderedUnitTest_1000
* @tc.name: test ProcessOrderedEvent
* @tc.desc: Verify CommonEventControlManager ProcessOrderedEvent success
*/
HWTEST_F(CommonEventPublishOrderedEventUnitTest, CommonEventPublishOrderedUnitTest_1000, Function | MediumTest | Level1)
{
// make common event record
std::shared_ptr<CommonEventData> commonEventData = std::make_shared<CommonEventData>();
std::shared_ptr<CommonEventPublishInfo> publishInfo = std::make_shared<CommonEventPublishInfo>();
publishInfo->SetOrdered(true);
CommonEventRecord commonEventRecord;
commonEventRecord.commonEventData = commonEventData;
commonEventRecord.publishInfo = publishInfo;
commonEventRecord.pid = 0;
commonEventRecord.uid = 0;
commonEventRecord.bundleName = "bundleName";
// make subcriber info
MatchingSkills matchingSkills;
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
// make subcriber
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
// make commone event listener
OHOS::sptr<CommonEventListener> commonEventListener = new CommonEventListener(subscriber);
OHOS::sptr<OHOS::IRemoteObject> commonEventListenerPtr(commonEventListener);
mtx.lock();
bool result = commonEventControlManager->ProcessOrderedEvent(commonEventRecord, commonEventListenerPtr);
EXPECT_EQ(true, result);
int count = 0;
while (!mtx.try_lock()) {
if (count == 0) {
GTEST_LOG_(INFO) << "Wait OnReceive callback function process";
count = 1;
} else {
usleep(100 * 1000);
}
}
mtx.unlock();
GTEST_LOG_(INFO) << "Testcase finished";
}
/*
* @tc.number: CommonEventPublishOrderedUnitTest_1100
* @tc.name: test EnqueueOrderedRecord eventRecordPtr is null
* @tc.desc: Verify EnqueueOrderedRecord eventRecordPtr is null orderedEventQueue_ size is 0
*/
HWTEST_F(CommonEventPublishOrderedEventUnitTest, CommonEventPublishOrderedUnitTest_1100, Function | MediumTest | Level1)
{
bool result = commonEventControlManager->EnqueueOrderedRecord(nullptr);
EXPECT_EQ(false, result);
}
/*
* @tc.number: CommonEventPublishOrderedUnitTest_1200
* @tc.name: test EnqueueOrderedRecord
* @tc.desc: Verify EnqueueOrderedRecord success
*/
HWTEST_F(CommonEventPublishOrderedEventUnitTest, CommonEventPublishOrderedUnitTest_1200, Function | MediumTest | Level1)
{
// make common event record
std::shared_ptr<CommonEventData> commonEventData = std::make_shared<CommonEventData>();
std::shared_ptr<CommonEventPublishInfo> publishInfo = std::make_shared<CommonEventPublishInfo>();
// make ordered event record
std::shared_ptr<OrderedEventRecord> eventRecord = std::make_shared<OrderedEventRecord>();
eventRecord->commonEventData = commonEventData;
eventRecord->publishInfo = publishInfo;
eventRecord->resultTo = nullptr;
eventRecord->state = OrderedEventRecord::IDLE;
eventRecord->nextReceiver = 0;
bool result = commonEventControlManager->EnqueueOrderedRecord(eventRecord);
EXPECT_EQ(true, result);
}
/*
* @tc.number: CommonEventPublishOrderedUnitTest_1300
* @tc.name: test ScheduleOrderedCommonEvent
* @tc.desc: Verify ScheduleOrderedCommonEvent success when scheduled is true
*/
HWTEST_F(CommonEventPublishOrderedEventUnitTest, CommonEventPublishOrderedUnitTest_1300, Function | MediumTest | Level1)
{
commonEventControlManager->scheduled_ = true;
bool result = commonEventControlManager->ScheduleOrderedCommonEvent();
EXPECT_EQ(true, result);
}
/*
* @tc.number: CommonEventPublishOrderedUnitTest_1400
* @tc.name: test ScheduleOrderedCommonEvent
* @tc.desc: Verify ScheduleOrderedCommonEvent success when scheduled is false
*/
HWTEST_F(CommonEventPublishOrderedEventUnitTest, CommonEventPublishOrderedUnitTest_1400, Function | MediumTest | Level1)
{
commonEventControlManager->scheduled_ = false;
bool result = commonEventControlManager->ScheduleOrderedCommonEvent();
EXPECT_EQ(true, result);
GTEST_LOG_(INFO) << "Testcase finished";
}
/*
* @tc.number: CommonEventPublishOrderedUnitTest_1500
* @tc.name: test FinishReceiverLocked
* @tc.desc: Verify FinishReceiverLocked return true because eventRecord state is received
*/
HWTEST_F(CommonEventPublishOrderedEventUnitTest, CommonEventPublishOrderedUnitTest_1500, Function | MediumTest | Level1)
{
// make common event record
std::shared_ptr<CommonEventData> commonEventData = std::make_shared<CommonEventData>();
std::shared_ptr<CommonEventPublishInfo> publishInfo = std::make_shared<CommonEventPublishInfo>();
// make ordered event record
std::shared_ptr<OrderedEventRecord> eventRecord = std::make_shared<OrderedEventRecord>();
eventRecord->commonEventData = commonEventData;
eventRecord->publishInfo = publishInfo;
eventRecord->resultTo = nullptr;
eventRecord->state = OrderedEventRecord::RECEIVED;
eventRecord->nextReceiver = 0;
std::string receiverData = "receiverData";
bool result = commonEventControlManager->FinishReceiverLocked(eventRecord, 0, receiverData, false);
EXPECT_EQ(true, result);
}
/*
* @tc.number: CommonEventPublishOrderedUnitTest_1600
* @tc.name: test FinishReceiverLocked
* @tc.desc: Verify FinishReceiverLocked return false eventRecord state is idle
*/
HWTEST_F(CommonEventPublishOrderedEventUnitTest, CommonEventPublishOrderedUnitTest_1600, Function | MediumTest | Level1)
{
// make common event record
std::shared_ptr<CommonEventData> commonEventData = std::make_shared<CommonEventData>();
std::shared_ptr<CommonEventPublishInfo> publishInfo = std::make_shared<CommonEventPublishInfo>();
// make ordered event record
std::shared_ptr<OrderedEventRecord> eventRecord = std::make_shared<OrderedEventRecord>();
eventRecord->commonEventData = commonEventData;
eventRecord->publishInfo = publishInfo;
eventRecord->resultTo = nullptr;
eventRecord->state = OrderedEventRecord::IDLE;
eventRecord->nextReceiver = 0;
std::string receiverData = "receiverData";
bool result = commonEventControlManager->FinishReceiverLocked(eventRecord, 0, receiverData, false);
EXPECT_EQ(false, result);
}
/*
* @tc.number: CommonEventPublishOrderedUnitTest_1700
* @tc.name: test FinishReceiverLocked recordPtr is null
* @tc.desc: Verify FinishReceiverLocked recordPtr is null return false
*/
HWTEST_F(CommonEventPublishOrderedEventUnitTest, CommonEventPublishOrderedUnitTest_1700, Function | MediumTest | Level1)
{
std::string receiverData = "receiverData";
bool result = commonEventControlManager->FinishReceiverLocked(nullptr, 0, receiverData, false);
EXPECT_EQ(false, result);
}
/*
* @tc.number: CommonEventPublishOrderedUnitTest_1800
* @tc.name: test GetOrderedEventHandler handlerOrdered_ is not null
* @tc.desc: Verify GetOrderedEventHandler handlerOrdered_ is not return true
*/
HWTEST_F(CommonEventPublishOrderedEventUnitTest, CommonEventPublishOrderedUnitTest_1800, Function | MediumTest | Level1)
{
commonEventControlManager->handlerOrdered_ =
std::make_shared<OrderedEventHandler>(EventRunner::Create(), commonEventControlManager);
bool result = commonEventControlManager->GetOrderedEventHandler();
EXPECT_EQ(true, result);
}
/*
* @tc.number: CommonEventPublishOrderedUnitTest_1900
* @tc.name: test CurrentOrderedEventTimeout orderedEventQueue_ is null
* @tc.desc: Verify CurrentOrderedEventTimeout fail because orderedEventQueue_ is null
*/
HWTEST_F(CommonEventPublishOrderedEventUnitTest, CommonEventPublishOrderedUnitTest_1900, Function | MediumTest | Level1)
{
commonEventControlManager->orderedEventQueue_.clear();
commonEventControlManager->CurrentOrderedEventTimeout(true);
bool result = false;
if (commonEventControlManager->orderedEventQueue_.size() == 0) {
result = true;
}
EXPECT_EQ(true, result);
commonEventControlManager->orderedEventQueue_.clear();
}
/*
* @tc.number: CommonEventPublishOrderedUnitTest_2000
* @tc.name: test CurrentOrderedEventTimeout
* @tc.desc: Verify CurrentOrderedEventTimeout success with eventRecord->nextReceiver = 0;
*/
HWTEST_F(CommonEventPublishOrderedEventUnitTest, CommonEventPublishOrderedUnitTest_2000, Function | MediumTest | Level1)
{
// make common event record
std::shared_ptr<CommonEventData> commonEventData = std::make_shared<CommonEventData>();
std::shared_ptr<CommonEventPublishInfo> publishInfo = std::make_shared<CommonEventPublishInfo>();
// make ordered event record
std::shared_ptr<OrderedEventRecord> eventRecord = std::make_shared<OrderedEventRecord>();
eventRecord->commonEventData = commonEventData;
eventRecord->publishInfo = publishInfo;
eventRecord->resultTo = nullptr;
eventRecord->state = OrderedEventRecord::IDLE;
eventRecord->nextReceiver = 0;
// enqueue ordered record
commonEventControlManager->scheduled_ = true;
commonEventControlManager->EnqueueOrderedRecord(eventRecord);
commonEventControlManager->CurrentOrderedEventTimeout(true);
bool result = false;
if (commonEventControlManager->orderedEventQueue_.size() > 0) {
result = true;
}
EXPECT_EQ(true, result);
commonEventControlManager->orderedEventQueue_.clear();
}
/*
* @tc.number: CommonEventPublishOrderedUnitTest_2100
* @tc.name: test CurrentOrderedEventTimeout
* @tc.desc: Verify CurrentOrderedEventTimeout success with eventRecord->nextReceiver = 1;
*/
HWTEST_F(CommonEventPublishOrderedEventUnitTest, CommonEventPublishOrderedUnitTest_2100, Function | MediumTest | Level1)
{
// make event record
std::shared_ptr<CommonEventData> commonEventData = std::make_shared<CommonEventData>();
std::shared_ptr<CommonEventPublishInfo> publishInfo = std::make_shared<CommonEventPublishInfo>();
std::shared_ptr<EventSubscriberRecord> subscriberRecord = std::make_shared<EventSubscriberRecord>();
std::shared_ptr<OrderedEventRecord> eventRecord = std::make_shared<OrderedEventRecord>();
eventRecord->commonEventData = commonEventData;
eventRecord->publishInfo = publishInfo;
eventRecord->resultTo = nullptr;
eventRecord->state = OrderedEventRecord::IDLE;
eventRecord->nextReceiver = 1;
eventRecord->deliveryState.emplace_back(OrderedEventRecord::DELIVERY_PENDING);
eventRecord->receivers.emplace_back(subscriberRecord);
commonEventControlManager->scheduled_ = true;
bool ret = commonEventControlManager->EnqueueOrderedRecord(eventRecord);
EXPECT_EQ(true, ret);
commonEventControlManager->CurrentOrderedEventTimeout(true);
bool result = false;
if (commonEventControlManager->orderedEventQueue_.front()->nextReceiver > 0) {
GTEST_LOG_(INFO) << std::to_string(commonEventControlManager->orderedEventQueue_.front()->nextReceiver);
result = true;
}
EXPECT_EQ(true, result);
commonEventControlManager->orderedEventQueue_.clear();
}
/*
* @tc.number: CommonEventPublishOrderedUnitTest_2200
* @tc.name: test CancelTimeout
* @tc.desc: Verify CancelTimeout return true when pendingTimeoutMessage is true
*/
HWTEST_F(CommonEventPublishOrderedEventUnitTest, CommonEventPublishOrderedUnitTest_2200, Function | MediumTest | Level1)
{
commonEventControlManager->pendingTimeoutMessage_ = true;
bool result = commonEventControlManager->CancelTimeout();
EXPECT_EQ(true, result);
}
/*
* @tc.number: CommonEventPublishOrderedUnitTest_2300
* @tc.name: test CancelTimeout
* @tc.desc: Verify CancelTimeout return true when pendingTimeoutMessage is false
*/
HWTEST_F(CommonEventPublishOrderedEventUnitTest, CommonEventPublishOrderedUnitTest_2300, Function | MediumTest | Level1)
{
bool result = false;
commonEventControlManager->pendingTimeoutMessage_ = false;
result = commonEventControlManager->CancelTimeout();
EXPECT_EQ(true, result);
}
/*
* @tc.number: CommonEventPublishOrderedUnitTest_2400
* @tc.name: test PublishCommonEvent
* @tc.desc: 1.Set thread mode handler
* 2.Verify InnerCommonEventManager PublishCommonEvent success
*/
HWTEST_F(CommonEventPublishOrderedEventUnitTest, CommonEventPublishOrderedUnitTest_2400, Function | MediumTest | Level1)
{
// make a want
Want want;
want.SetAction(ACTION);
// make common event data
CommonEventData data;
data.SetWant(want);
// make publish info
CommonEventPublishInfo publishInfo;
publishInfo.SetOrdered(true);
MatchingSkills matchingSkills;
// make subcriber info
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
subscriberInfo.SetThreadMode(CommonEventSubscribeInfo::ThreadMode::HANDLER);
// make a subcriber object
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
OHOS::sptr<CommonEventListener> commonEventListener = new CommonEventListener(subscriber);
mtx.lock();
struct tm curTime{0};
// publish ordered event
bool result =
innerCommonEventManager.PublishCommonEvent(data, publishInfo, commonEventListener, curTime, 0, 0, "bundlename");
EXPECT_EQ(true, result);
int count = 0;
while (!mtx.try_lock()) {
if (count == 0) {
GTEST_LOG_(INFO) << "Wait OnReceive callback function process";
count = 1;
} else {
usleep(100 * 1000);
}
}
mtx.unlock();
GTEST_LOG_(INFO) << "Testcase finished";
}
/*
* @tc.number: CommonEventPublishOrderedEventUnitTest_2500
* @tc.name: test PublishCommonEvent
* @tc.desc: 1.Set thread mode POST
* 2.Verify InnerCommonEventManager PublishCommonEvent success
*/
HWTEST_F(CommonEventPublishOrderedEventUnitTest, CommonEventPublishOrderedUnitTest_2500, Function | MediumTest | Level1)
{
// make a want
Want want;
want.SetAction(ACTION);
// make common event data
CommonEventData data;
data.SetWant(want);
// make publish info
CommonEventPublishInfo publishInfo;
publishInfo.SetOrdered(true);
MatchingSkills matchingSkills;
// make subcriber info
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
subscriberInfo.SetThreadMode(CommonEventSubscribeInfo::ThreadMode::POST);
// make a subcriber object
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
OHOS::sptr<CommonEventListener> commonEventListener = new CommonEventListener(subscriber);
mtx.lock();
struct tm curTime{0};
// publish ordered event
bool result =
innerCommonEventManager.PublishCommonEvent(data, publishInfo, commonEventListener, curTime, 0, 0, "bundlename");
EXPECT_EQ(true, result);
int count = 0;
while (!mtx.try_lock()) {
if (count == 0) {
GTEST_LOG_(INFO) << "Wait OnReceive callback function process";
count = 1;
} else {
usleep(100 * 1000);
}
}
mtx.unlock();
GTEST_LOG_(INFO) << "Testcase finished";
}
/*
* @tc.number: CommonEventPublishOrderedEventUnitTest_2600
* @tc.name: test PublishCommonEvent
* @tc.desc: 1.Set thread mode ASYNC
* 2.Verify InnerCommonEventManager PublishCommonEvent success
*/
HWTEST_F(CommonEventPublishOrderedEventUnitTest, CommonEventPublishOrderedUnitTest_2600, Function | MediumTest | Level1)
{
// make a want
Want want;
want.SetAction(ACTION);
// make common event data
CommonEventData data;
data.SetWant(want);
// make publish info
CommonEventPublishInfo publishInfo;
publishInfo.SetOrdered(true);
MatchingSkills matchingSkills;
// make subcriber info
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
subscriberInfo.SetThreadMode(CommonEventSubscribeInfo::ThreadMode::ASYNC);
// make a subcriber object
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
OHOS::sptr<CommonEventListener> commonEventListener = new CommonEventListener(subscriber);
mtx.lock();
struct tm curTime{0};
// publish ordered event
bool result =
innerCommonEventManager.PublishCommonEvent(data, publishInfo, commonEventListener, curTime, 0, 0, "bundlename");
EXPECT_EQ(true, result);
int count = 0;
while (!mtx.try_lock()) {
if (count == 0) {
GTEST_LOG_(INFO) << "Wait OnReceive callback function process";
count = 1;
} else {
usleep(100 * 1000);
}
}
mtx.unlock();
GTEST_LOG_(INFO) << "Testcase finished";
}
/*
* @tc.number: CommonEventPublishOrderedEventUnitTest_2700
* @tc.name: test PublishCommonEvent
* @tc.desc: 1.Set thread mode BACKGROUND
* 2.Verify InnerCommonEventManager PublishCommonEvent success
*/
HWTEST_F(CommonEventPublishOrderedEventUnitTest, CommonEventPublishOrderedUnitTest_2700, Function | MediumTest | Level1)
{
// make a want
Want want;
want.SetAction(ACTION);
// make common event data
CommonEventData data;
data.SetWant(want);
// make publish info
CommonEventPublishInfo publishInfo;
publishInfo.SetOrdered(true);
MatchingSkills matchingSkills;
// make subcriber info
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
subscriberInfo.SetThreadMode(CommonEventSubscribeInfo::ThreadMode::BACKGROUND);
// make a subcriber object
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
OHOS::sptr<CommonEventListener> commonEventListener = new CommonEventListener(subscriber);
mtx.lock();
struct tm curTime{0};
// publish ordered event
bool result =
innerCommonEventManager.PublishCommonEvent(data, publishInfo, commonEventListener, curTime, 0, 0, "bundlename");
EXPECT_EQ(true, result);
int count = 0;
while (!mtx.try_lock()) {
if (count == 0) {
GTEST_LOG_(INFO) << "Wait OnReceive callback function process";
count = 1;
} else {
usleep(100 * 1000);
}
}
mtx.unlock();
GTEST_LOG_(INFO) << "Testcase finished";
}
@@ -0,0 +1,925 @@
/*
* 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 "common_event.h"
// redefine private and protected since testcase need to invoke and test private function
#define private public
#define protected public
#include "common_event_control_manager.h"
#include "common_event_manager_service.h"
#undef private
#undef protected
#include "common_event_manager.h"
#include "common_event_record.h"
#include "common_event_support.h"
#include "mock_bundle_manager.h"
#include "iremote_object.h"
#include "iservice_registry.h"
#include "refbase.h"
#include "system_ability_definition.h"
#include <gtest/gtest.h>
using namespace testing::ext;
using namespace OHOS;
using namespace OHOS::EventFwk;
namespace {
const std::string EVENT = "com.ces.test.event";
const std::string ENTITY = "com.ces.test.entity";
const int SLEEPTIEM = 1;
} // namespace
enum DeliveryState_ {
DELIVERY_PENDING = 0,
DELIVERY_DELIVERED,
DELIVERY_SKIPPED,
DELIVERY_TIMEOUT,
};
static OHOS::sptr<OHOS::IRemoteObject> bundleObject = nullptr;
class CommonEventPublishPermissionEventUnitTest : public testing::Test {
public:
CommonEventPublishPermissionEventUnitTest()
{}
~CommonEventPublishPermissionEventUnitTest()
{}
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
class SubscriberTest : public CommonEventSubscriber {
public:
SubscriberTest(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp)
{}
~SubscriberTest()
{}
virtual void OnReceiveEvent(const CommonEventData &data)
{}
};
class SubscriberTest1 : public CommonEventSubscriber {
public:
SubscriberTest1(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp)
{}
~SubscriberTest1()
{}
virtual void OnReceiveEvent(const CommonEventData &data)
{}
};
void CommonEventPublishPermissionEventUnitTest::SetUpTestCase(void)
{
bundleObject = new OHOS::AppExecFwk::MockBundleMgrService();
OHOS::sptr<OHOS::ISystemAbilityManager> systemAbilityManager =
OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
OHOS::ISystemAbilityManager::SAExtraProp saExtraProp;
systemAbilityManager->AddSystemAbility(OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, bundleObject, saExtraProp);
}
void CommonEventPublishPermissionEventUnitTest::TearDownTestCase(void)
{}
void CommonEventPublishPermissionEventUnitTest::SetUp(void)
{}
void CommonEventPublishPermissionEventUnitTest::TearDown(void)
{}
/*
* @tc.number: CommonEventPublishPermissionEventUnitTest_0100
* @tc.name: test unordered event permission
* @tc.desc: 1. subcriber permisssion is not empty
* 2. publish permission is not empty
*/
HWTEST_F(CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_0100,
Function | MediumTest | Level1)
{
GTEST_LOG_(INFO)
<< "CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_0100, TestSize.Level1";
InnerCommonEventManager inner;
struct tm curTime{0};
/* subscriber */
MatchingSkills matchingSkillsObj;
matchingSkillsObj.AddEvent("1234");
CommonEventSubscribeInfo subscriberInfo(matchingSkillsObj);
subscriberInfo.SetPermission("123");
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
auto listener = sptr<IRemoteObject>(new CommonEventListener(subscriber));
inner.SubscribeCommonEvent(subscriberInfo, listener, curTime, 0, 1000, "hello");
/* Publish */
Want want;
want.SetAction("1234");
CommonEventData data;
data.SetWant(want);
std::vector<std::string> subscriberPermissions;
subscriberPermissions.emplace_back("456");
CommonEventPublishInfo publishInfo;
publishInfo.SetOrdered(false);
publishInfo.SetSubscriberPermissions(subscriberPermissions);
bool result = inner.PublishCommonEvent(data, publishInfo, nullptr, curTime, 0, 1000, "hello");
sleep(SLEEPTIEM);
EXPECT_EQ(true, result);
inner.UnsubscribeCommonEvent(listener);
}
/*
* @tc.number: CommonEventPublishPermissionEventUnitTest_0200
* @tc.name: test ordered event permission
* @tc.desc: 1. subcriber permisssion is not empty
* 2. publish permission is not empty
*/
HWTEST_F(CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_0200,
Function | MediumTest | Level1)
{
GTEST_LOG_(INFO)
<< "CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_0200, TestSize.Level1";
/* subscriber */
InnerCommonEventManager inner;
struct tm curTime{0};
MatchingSkills matchingSkillsObj;
matchingSkillsObj.AddEvent("1234");
CommonEventSubscribeInfo subscriberInfo(matchingSkillsObj);
subscriberInfo.SetPermission("123");
subscriberInfo.SetPriority(1);
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
auto listener = sptr<IRemoteObject>(new CommonEventListener(subscriber));
inner.SubscribeCommonEvent(subscriberInfo, listener, curTime, 0, 1000, "hello");
/* Publish */
Want want;
want.SetAction("1234");
CommonEventData data;
data.SetWant(want);
CommonEventPublishInfo publishInfo;
std::vector<std::string> subscriberPermissions;
publishInfo.SetOrdered(true);
subscriberPermissions.emplace_back("456");
publishInfo.SetSubscriberPermissions(subscriberPermissions);
bool result = inner.PublishCommonEvent(data, publishInfo, listener, curTime, 0, 1000, "hello");
sleep(SLEEPTIEM);
EXPECT_EQ(true, result);
inner.UnsubscribeCommonEvent(listener);
}
/*
* @tc.number: CommonEventPublishPermissionEventUnitTest_0300
* @tc.name: test unordered event permission
* @tc.desc: 1. subcriber permisssion is empty
* 2. publish permission is not empty
*/
HWTEST_F(CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_0300,
Function | MediumTest | Level1)
{
GTEST_LOG_(INFO)
<< "CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_0300, TestSize.Level1";
/* subscriber */
InnerCommonEventManager inner;
struct tm curTime{0};
MatchingSkills matchingSkillsObj;
matchingSkillsObj.AddEvent("1234");
CommonEventSubscribeInfo subscriberInfo(matchingSkillsObj);
subscriberInfo.SetPermission("");
subscriberInfo.SetPriority(1);
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
auto listener = sptr<IRemoteObject>(new CommonEventListener(subscriber));
inner.SubscribeCommonEvent(subscriberInfo, listener, curTime, 0, 1000, "hello");
/* Publish */
Want want;
want.SetAction("1234");
CommonEventData data;
data.SetWant(want);
CommonEventPublishInfo publishInfo;
std::vector<std::string> subscriberPermissions;
publishInfo.SetOrdered(false);
subscriberPermissions.emplace_back("456");
publishInfo.SetSubscriberPermissions(subscriberPermissions);
bool result = inner.PublishCommonEvent(data, publishInfo, nullptr, curTime, 0, 1000, "hello");
sleep(SLEEPTIEM);
EXPECT_EQ(true, result);
inner.UnsubscribeCommonEvent(listener);
}
/*
* @tc.number: CommonEventPublishPermissionEventUnitTest_0400
* @tc.name: test ordered event permission
* @tc.desc: 1. subcriber permisssion is empty
* 2. publish permission is not empty
*/
HWTEST_F(CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_0400,
Function | MediumTest | Level1)
{
GTEST_LOG_(INFO)
<< "CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_0400, TestSize.Level1";
/* subscriber */
InnerCommonEventManager inner;
struct tm curTime{0};
MatchingSkills matchingSkillsObj;
matchingSkillsObj.AddEvent("1234");
CommonEventSubscribeInfo subscriberInfo(matchingSkillsObj);
subscriberInfo.SetPermission("");
subscriberInfo.SetPriority(1);
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
auto listener = sptr<IRemoteObject>(new CommonEventListener(subscriber));
inner.SubscribeCommonEvent(subscriberInfo, listener, curTime, 0, 1000, "hello");
/* Publish */
Want want;
want.SetAction("1234");
CommonEventData data;
data.SetWant(want);
CommonEventPublishInfo publishInfo;
std::vector<std::string> subscriberPermissions;
publishInfo.SetOrdered(true);
subscriberPermissions.emplace_back("456");
publishInfo.SetSubscriberPermissions(subscriberPermissions);
bool result = inner.PublishCommonEvent(data, publishInfo, listener, curTime, 0, 1000, "hello");
sleep(SLEEPTIEM);
EXPECT_EQ(true, result);
inner.UnsubscribeCommonEvent(listener);
}
/*
* @tc.number: CommonEventPublishPermissionEventUnitTest_0500
* @tc.name: test CommonEventControlManager permission
* @tc.desc: 1. subcriber permisssion is empty
* 2. publish permission is empty
*/
HWTEST_F(CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_0500,
Function | MediumTest | Level1)
{
GTEST_LOG_(INFO)
<< "CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_0500, TestSize.Level1";
CommonEventSubscribeInfo commonEventSubscriberInfo;
commonEventSubscriberInfo.SetPermission("");
std::shared_ptr<CommonEventSubscribeInfo> commonEventSubscriberInfoSptr =
std::make_shared<CommonEventSubscribeInfo>(commonEventSubscriberInfo);
EventSubscriberRecord eventSubRecord;
eventSubRecord.eventSubscriberInfo = commonEventSubscriberInfoSptr;
eventSubRecord.bundleName = "hello";
CommonEventPublishInfo commonEventPublishInfo;
commonEventPublishInfo.SetSubscriberPermissions(std::vector<std::string>());
std::shared_ptr<CommonEventPublishInfo> commonEventPublishInfoSptr =
std::make_shared<CommonEventPublishInfo>(commonEventPublishInfo);
Want want;
want.SetAction("1234");
std::shared_ptr<CommonEventData> spCommonEventData = std::make_shared<CommonEventData>();
spCommonEventData->SetWant(want);
CommonEventRecord commonEventRecord;
commonEventRecord.publishInfo = commonEventPublishInfoSptr;
commonEventRecord.bundleName = "hello";
commonEventRecord.commonEventData = spCommonEventData;
CommonEventControlManager commonEventControlManager;
int ret = commonEventControlManager.CheckPermission(eventSubRecord, commonEventRecord);
EXPECT_EQ(DELIVERY_DELIVERED, ret);
}
/*
* @tc.number: CommonEventPublishPermissionEventUnitTest_0600
* @tc.name: test CommonEventControlManager permission
* @tc.desc: 1. subcriber permisssion is not empty
* 2. publish permission is empty
* 3. function CheckPermission return DELIVERY_SKIPPED
*/
HWTEST_F(CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_0600,
Function | MediumTest | Level1)
{
GTEST_LOG_(INFO)
<< "CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_0600, TestSize.Level1";
CommonEventSubscribeInfo commonEventSubscriberInfo;
commonEventSubscriberInfo.SetPermission("12345");
std::shared_ptr<CommonEventSubscribeInfo> commonEventSubscriberInfoSptr =
std::make_shared<CommonEventSubscribeInfo>(commonEventSubscriberInfo);
EventSubscriberRecord eventSubRecord;
eventSubRecord.eventSubscriberInfo = commonEventSubscriberInfoSptr;
eventSubRecord.bundleName = "hello";
CommonEventPublishInfo commonEventPublishInfo;
commonEventPublishInfo.SetSubscriberPermissions(std::vector<std::string>());
std::shared_ptr<CommonEventPublishInfo> commonEventPublishInfoSptr =
std::make_shared<CommonEventPublishInfo>(commonEventPublishInfo);
Want want;
want.SetAction("1234");
std::shared_ptr<CommonEventData> spCommonEventData = std::make_shared<CommonEventData>();
spCommonEventData->SetWant(want);
CommonEventRecord commonEventRecord;
commonEventRecord.publishInfo = commonEventPublishInfoSptr;
commonEventRecord.bundleName = "hello world";
commonEventRecord.commonEventData = spCommonEventData;
CommonEventControlManager commonEventControlManager;
int ret = commonEventControlManager.CheckPermission(eventSubRecord, commonEventRecord);
EXPECT_EQ(DELIVERY_SKIPPED, ret);
}
/*
* @tc.number: CommonEventPublishPermissionEventUnitTest_0700
* @tc.name: test CommonEventControlManager permission
* @tc.desc: 1. subcriber permisssion is not empty
* 2. publish permission is empty
* 3. function CheckPermission return DELIVERY_DELIVERED
*/
HWTEST_F(CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_0700,
Function | MediumTest | Level1)
{
GTEST_LOG_(INFO)
<< "CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_0700, TestSize.Level1";
CommonEventSubscribeInfo commonEventSubscriberInfo;
commonEventSubscriberInfo.SetPermission("12345");
std::shared_ptr<CommonEventSubscribeInfo> commonEventSubscriberInfoSptr =
std::make_shared<CommonEventSubscribeInfo>(commonEventSubscriberInfo);
EventSubscriberRecord eventSubRecord;
eventSubRecord.eventSubscriberInfo = commonEventSubscriberInfoSptr;
CommonEventPublishInfo commonEventPublishInfo;
commonEventPublishInfo.SetSubscriberPermissions(std::vector<std::string>());
std::shared_ptr<CommonEventPublishInfo> commonEventPublishInfoSptr =
std::make_shared<CommonEventPublishInfo>(commonEventPublishInfo);
Want want;
want.SetAction("1234");
std::shared_ptr<CommonEventData> spCommonEventData = std::make_shared<CommonEventData>();
spCommonEventData->SetWant(want);
CommonEventRecord commonEventRecord;
commonEventRecord.publishInfo = commonEventPublishInfoSptr;
commonEventRecord.bundleName = "hello";
commonEventRecord.commonEventData = spCommonEventData;
CommonEventControlManager commonEventControlManager;
int ret = commonEventControlManager.CheckPermission(eventSubRecord, commonEventRecord);
EXPECT_EQ(DELIVERY_DELIVERED, ret);
}
/*
* @tc.number: CommonEventPublishPermissionEventUnitTest_0800
* @tc.name: test CommonEventControlManager permission
* @tc.desc: 1. subcriber permisssion is empty
* 2. publish permission is not empty
* 3. function CheckPermission return DELIVERY_DELIVERED
*/
HWTEST_F(CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_0800,
Function | MediumTest | Level1)
{
GTEST_LOG_(INFO)
<< "CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_0800, TestSize.Level1";
CommonEventSubscribeInfo commonEventSubscriberInfo;
commonEventSubscriberInfo.SetPermission("");
std::shared_ptr<CommonEventSubscribeInfo> commonEventSubscriberInfoSptr =
std::make_shared<CommonEventSubscribeInfo>(commonEventSubscriberInfo);
EventSubscriberRecord eventSubRecord;
eventSubRecord.eventSubscriberInfo = commonEventSubscriberInfoSptr;
eventSubRecord.bundleName = "hello";
CommonEventPublishInfo commonEventPublishInfo;
std::vector<std::string> vecstr;
vecstr.emplace_back("456");
commonEventPublishInfo.SetSubscriberPermissions(vecstr);
std::shared_ptr<CommonEventPublishInfo> commonEventPublishInfoSptr =
std::make_shared<CommonEventPublishInfo>(commonEventPublishInfo);
Want want;
want.SetAction("1234");
std::shared_ptr<CommonEventData> spCommonEventData = std::make_shared<CommonEventData>();
spCommonEventData->SetWant(want);
CommonEventRecord commonEventRecord;
commonEventRecord.publishInfo = commonEventPublishInfoSptr;
commonEventRecord.commonEventData = spCommonEventData;
CommonEventControlManager commonEventControlManager;
int ret = commonEventControlManager.CheckPermission(eventSubRecord, commonEventRecord);
EXPECT_EQ(DELIVERY_DELIVERED, ret);
}
/*
* @tc.number: CommonEventPublishPermissionEventUnitTest_0900
* @tc.name: test CommonEventControlManager permission
* @tc.desc: 1. subcriber permisssion is empty
* 2. publish permission is not empty
* 3. function CheckPermission return DELIVERY_SKIPPED
*/
HWTEST_F(CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_0900,
Function | MediumTest | Level1)
{
GTEST_LOG_(INFO)
<< "CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_0900, TestSize.Level1";
CommonEventSubscribeInfo commonEventSubscriberInfo;
commonEventSubscriberInfo.SetPermission("");
std::shared_ptr<CommonEventSubscribeInfo> commonEventSubscriberInfoSptr =
std::make_shared<CommonEventSubscribeInfo>(commonEventSubscriberInfo);
EventSubscriberRecord eventSubRecord;
eventSubRecord.eventSubscriberInfo = commonEventSubscriberInfoSptr;
eventSubRecord.bundleName = "hello world";
CommonEventPublishInfo commonEventPublishInfo;
std::vector<std::string> vecstr;
vecstr.emplace_back("456");
commonEventPublishInfo.SetSubscriberPermissions(vecstr);
std::shared_ptr<CommonEventPublishInfo> commonEventPublishInfoSptr =
std::make_shared<CommonEventPublishInfo>(commonEventPublishInfo);
Want want;
want.SetAction("1234");
std::shared_ptr<CommonEventData> spCommonEventData = std::make_shared<CommonEventData>();
spCommonEventData->SetWant(want);
CommonEventRecord commonEventRecord;
commonEventRecord.publishInfo = commonEventPublishInfoSptr;
commonEventRecord.commonEventData = spCommonEventData;
CommonEventControlManager commonEventControlManager;
int ret = commonEventControlManager.CheckPermission(eventSubRecord, commonEventRecord);
EXPECT_EQ(DELIVERY_SKIPPED, ret);
}
/*
* @tc.number: CommonEventPublishPermissionEventUnitTest_1000
* @tc.name: test CommonEventControlManager permission
* @tc.desc: 1. subcriber permisssion is not empty
* 2. publish permission is not empty
* 3. function subcriber CheckPermission return DELIVERY_DELIVERED
*/
HWTEST_F(CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_1000,
Function | MediumTest | Level1)
{
GTEST_LOG_(INFO)
<< "CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_1000, TestSize.Level1";
CommonEventSubscribeInfo commonEventSubscriberInfo;
commonEventSubscriberInfo.SetPermission("12345");
std::shared_ptr<CommonEventSubscribeInfo> commonEventSubscriberInfoSptr =
std::make_shared<CommonEventSubscribeInfo>(commonEventSubscriberInfo);
EventSubscriberRecord eventSubRecord;
eventSubRecord.eventSubscriberInfo = commonEventSubscriberInfoSptr;
eventSubRecord.bundleName = "hello";
CommonEventPublishInfo commonEventPublishInfo;
std::vector<std::string> vecstr;
vecstr.emplace_back("456");
commonEventPublishInfo.SetSubscriberPermissions(vecstr);
std::shared_ptr<CommonEventPublishInfo> commonEventPublishInfoSptr =
std::make_shared<CommonEventPublishInfo>(commonEventPublishInfo);
Want want;
want.SetAction("1234");
std::shared_ptr<CommonEventData> spCommonEventData = std::make_shared<CommonEventData>();
spCommonEventData->SetWant(want);
CommonEventRecord commonEventRecord;
commonEventRecord.publishInfo = commonEventPublishInfoSptr;
commonEventRecord.bundleName = "hello";
commonEventRecord.commonEventData = spCommonEventData;
CommonEventControlManager commonEventControlManager;
int ret = commonEventControlManager.CheckPermission(eventSubRecord, commonEventRecord);
EXPECT_EQ(DELIVERY_DELIVERED, ret);
}
/*
* @tc.number: CommonEventPublishPermissionEventUnitTest_1100
* @tc.name: test CommonEventControlManager permission
* @tc.desc: 1. subcriber permisssion is not empty
* 2. publish permission is not empty
* 3. function subcriber CheckPermission return DELIVERY_SKIPPED
*/
HWTEST_F(CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_1100,
Function | MediumTest | Level1)
{
GTEST_LOG_(INFO)
<< "CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_1100, TestSize.Level1";
CommonEventSubscribeInfo commonEventSubscriberInfo;
commonEventSubscriberInfo.SetPermission("12345");
std::shared_ptr<CommonEventSubscribeInfo> commonEventSubscriberInfoSptr =
std::make_shared<CommonEventSubscribeInfo>(commonEventSubscriberInfo);
EventSubscriberRecord eventSubRecord;
eventSubRecord.eventSubscriberInfo = commonEventSubscriberInfoSptr;
eventSubRecord.bundleName = "hello world";
CommonEventPublishInfo commonEventPublishInfo;
std::vector<std::string> vecstr;
vecstr.emplace_back("456");
commonEventPublishInfo.SetSubscriberPermissions(vecstr);
std::shared_ptr<CommonEventPublishInfo> commonEventPublishInfoSptr =
std::make_shared<CommonEventPublishInfo>(commonEventPublishInfo);
Want want;
want.SetAction("1234");
std::shared_ptr<CommonEventData> spCommonEventData = std::make_shared<CommonEventData>();
spCommonEventData->SetWant(want);
CommonEventRecord commonEventRecord;
commonEventRecord.publishInfo = commonEventPublishInfoSptr;
commonEventRecord.bundleName = "hello";
commonEventRecord.commonEventData = spCommonEventData;
CommonEventControlManager commonEventControlManager;
int ret = commonEventControlManager.CheckPermission(eventSubRecord, commonEventRecord);
EXPECT_EQ(DELIVERY_SKIPPED, ret);
}
/*
* @tc.number: CommonEventPublishPermissionEventUnitTest_1200
* @tc.name: test CommonEventControlManager permission
* @tc.desc: 1. subcriber permisssion is not empty
* 2. publish permission is not empty
* 3. function subcriber CheckPermission return DELIVERY_SKIPPED
*/
HWTEST_F(CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_1200,
Function | MediumTest | Level1)
{
GTEST_LOG_(INFO)
<< "CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_1200, TestSize.Level1";
CommonEventSubscribeInfo commonEventSubscriberInfo;
commonEventSubscriberInfo.SetPermission("12345");
std::shared_ptr<CommonEventSubscribeInfo> commonEventSubscriberInfoSptr =
std::make_shared<CommonEventSubscribeInfo>(commonEventSubscriberInfo);
EventSubscriberRecord eventSubRecord;
eventSubRecord.eventSubscriberInfo = commonEventSubscriberInfoSptr;
eventSubRecord.bundleName = "hello";
CommonEventPublishInfo commonEventPublishInfo;
std::vector<std::string> vecstr;
vecstr.emplace_back("456");
commonEventPublishInfo.SetSubscriberPermissions(vecstr);
std::shared_ptr<CommonEventPublishInfo> commonEventPublishInfoSptr =
std::make_shared<CommonEventPublishInfo>(commonEventPublishInfo);
Want want;
want.SetAction("1234");
std::shared_ptr<CommonEventData> spCommonEventData = std::make_shared<CommonEventData>();
spCommonEventData->SetWant(want);
CommonEventRecord commonEventRecord;
commonEventRecord.publishInfo = commonEventPublishInfoSptr;
commonEventRecord.bundleName = "hello world";
commonEventRecord.commonEventData = spCommonEventData;
CommonEventControlManager commonEventControlManager;
int ret = commonEventControlManager.CheckPermission(eventSubRecord, commonEventRecord);
EXPECT_EQ(DELIVERY_SKIPPED, ret);
}
/*
* @tc.number: CommonEventPublishPermissionEventUnitTest_1300
* @tc.name: test CommonEventControlManager permission
* @tc.desc: 1. subcriber permisssion is not empty
* 2. publish permission is not empty
* 3. function subcriber CheckPermission return DELIVERY_SKIPPED
*/
HWTEST_F(CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_1300,
Function | MediumTest | Level1)
{
GTEST_LOG_(INFO)
<< "CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_1300, TestSize.Level1";
CommonEventSubscribeInfo commonEventSubscriberInfo;
commonEventSubscriberInfo.SetPermission("12345");
std::shared_ptr<CommonEventSubscribeInfo> commonEventSubscriberInfoSptr =
std::make_shared<CommonEventSubscribeInfo>(commonEventSubscriberInfo);
EventSubscriberRecord eventSubRecord;
eventSubRecord.eventSubscriberInfo = commonEventSubscriberInfoSptr;
eventSubRecord.bundleName = "hello world";
CommonEventPublishInfo commonEventPublishInfo;
std::vector<std::string> vecstr;
vecstr.emplace_back("456");
commonEventPublishInfo.SetSubscriberPermissions(vecstr);
std::shared_ptr<CommonEventPublishInfo> commonEventPublishInfoSptr =
std::make_shared<CommonEventPublishInfo>(commonEventPublishInfo);
Want want;
want.SetAction("1234");
std::shared_ptr<CommonEventData> spCommonEventData = std::make_shared<CommonEventData>();
spCommonEventData->SetWant(want);
CommonEventRecord commonEventRecord;
commonEventRecord.publishInfo = commonEventPublishInfoSptr;
commonEventRecord.bundleName = "hello world";
commonEventRecord.commonEventData = spCommonEventData;
CommonEventControlManager commonEventControlManager;
int ret = commonEventControlManager.CheckPermission(eventSubRecord, commonEventRecord);
EXPECT_EQ(DELIVERY_SKIPPED, ret);
}
/*
* @tc.number: CommonEventPublishPermissionEventUnitTest_1400
* @tc.name: test InnerCommonEventManager permission
* @tc.desc: function CheckPermission return true
*/
HWTEST_F(CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_1400,
Function | MediumTest | Level1)
{
GTEST_LOG_(INFO)
<< "CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_1400, TestSize.Level1";
InnerCommonEventManager inner;
struct tm curTime;
Want want;
want.SetAction("1234");
CommonEventData data;
data.SetWant(want);
CommonEventPublishInfo publishInfo;
publishInfo.SetOrdered(true);
publishInfo.SetSticky(true);
bool ret = inner.PublishCommonEvent(data, publishInfo, nullptr, curTime, 0, 1000, "hello");
EXPECT_EQ(true, ret);
}
/*
* @tc.number: CommonEventPublishPermissionEventUnitTest_1500
* @tc.name: test InnerCommonEventManager permission
* @tc.desc: function CheckPermission return false
*/
HWTEST_F(CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_1500,
Function | MediumTest | Level1)
{
GTEST_LOG_(INFO)
<< "CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_1500, TestSize.Level1";
InnerCommonEventManager inner;
struct tm curTime;
Want want;
want.SetAction("1234");
CommonEventData data;
data.SetWant(want);
CommonEventPublishInfo publishInfo;
publishInfo.SetOrdered(true);
publishInfo.SetSticky(true);
bool ret = inner.PublishCommonEvent(data, publishInfo, nullptr, curTime, 0, 1000, "hello world");
EXPECT_EQ(false, ret);
}
/*
* @tc.number: CommonEventPublishPermissionEventUnitTest_1600
* @tc.name: test InnerCommonEventManager permission
* @tc.desc: function CheckPermission return false
*/
HWTEST_F(CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_1600,
Function | MediumTest | Level1)
{
GTEST_LOG_(INFO)
<< "CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_1600, TestSize.Level1";
CommonEventSubscribeInfo commonEventSubscriberInfo;
commonEventSubscriberInfo.SetPermission("ohos.permission.GET_WIFI_INFO");
std::shared_ptr<CommonEventSubscribeInfo> commonEventSubscriberInfoSptr =
std::make_shared<CommonEventSubscribeInfo>(commonEventSubscriberInfo);
EventSubscriberRecord eventSubRecord;
eventSubRecord.eventSubscriberInfo = commonEventSubscriberInfoSptr;
eventSubRecord.bundleName = "hello";
CommonEventPublishInfo commonEventPublishInfo;
std::vector<std::string> vecstr;
vecstr.emplace_back("456");
commonEventPublishInfo.SetSubscriberPermissions(vecstr);
std::shared_ptr<CommonEventPublishInfo> commonEventPublishInfoSptr =
std::make_shared<CommonEventPublishInfo>(commonEventPublishInfo);
Want want;
want.SetAction("COMMON_EVENT_WIFI_AP_STA_JOIN");
std::shared_ptr<CommonEventData> spCommonEventData = std::make_shared<CommonEventData>();
spCommonEventData->SetWant(want);
CommonEventRecord commonEventRecord;
commonEventRecord.publishInfo = commonEventPublishInfoSptr;
commonEventRecord.bundleName = "hello";
commonEventRecord.commonEventData = spCommonEventData;
CommonEventControlManager commonEventControlManager;
int ret = commonEventControlManager.CheckPermission(eventSubRecord, commonEventRecord);
EXPECT_EQ(DELIVERY_DELIVERED, ret);
}
/*
* @tc.number: CommonEventPublishPermissionEventUnitTest_1700
* @tc.name: test InnerCommonEventManager permission
* @tc.desc: function CheckPermission return false
*/
HWTEST_F(CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_1700,
Function | MediumTest | Level1)
{
GTEST_LOG_(INFO)
<< "CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_1700, TestSize.Level1";
CommonEventSubscribeInfo commonEventSubscriberInfo;
commonEventSubscriberInfo.SetPermission("1234");
std::shared_ptr<CommonEventSubscribeInfo> commonEventSubscriberInfoSptr =
std::make_shared<CommonEventSubscribeInfo>(commonEventSubscriberInfo);
EventSubscriberRecord eventSubRecord;
eventSubRecord.eventSubscriberInfo = commonEventSubscriberInfoSptr;
eventSubRecord.bundleName = "hello";
CommonEventPublishInfo commonEventPublishInfo;
std::vector<std::string> vecstr;
vecstr.emplace_back("456");
commonEventPublishInfo.SetSubscriberPermissions(vecstr);
std::shared_ptr<CommonEventPublishInfo> commonEventPublishInfoSptr =
std::make_shared<CommonEventPublishInfo>(commonEventPublishInfo);
Want want;
want.SetAction("COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_DISCOVERED");
std::shared_ptr<CommonEventData> spCommonEventData = std::make_shared<CommonEventData>();
spCommonEventData->SetWant(want);
CommonEventRecord commonEventRecord;
commonEventRecord.publishInfo = commonEventPublishInfoSptr;
commonEventRecord.bundleName = "hello";
commonEventRecord.commonEventData = spCommonEventData;
CommonEventControlManager commonEventControlManager;
int ret = commonEventControlManager.CheckPermission(eventSubRecord, commonEventRecord);
EXPECT_EQ(DELIVERY_DELIVERED, ret);
}
/*
* @tc.number: CommonEventPublishPermissionEventUnitTest_1800
* @tc.name: test InnerCommonEventManager permission
* @tc.desc: function CheckPermission return false
*/
HWTEST_F(CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_1800,
Function | MediumTest | Level1)
{
GTEST_LOG_(INFO)
<< "CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_1800, TestSize.Level1";
CommonEventSubscribeInfo commonEventSubscriberInfo;
commonEventSubscriberInfo.SetPermission("1234");
std::shared_ptr<CommonEventSubscribeInfo> commonEventSubscriberInfoSptr =
std::make_shared<CommonEventSubscribeInfo>(commonEventSubscriberInfo);
EventSubscriberRecord eventSubRecord;
eventSubRecord.eventSubscriberInfo = commonEventSubscriberInfoSptr;
eventSubRecord.bundleName = "hello";
CommonEventPublishInfo commonEventPublishInfo;
std::vector<std::string> vecstr;
vecstr.emplace_back("456");
commonEventPublishInfo.SetSubscriberPermissions(vecstr);
std::shared_ptr<CommonEventPublishInfo> commonEventPublishInfoSptr =
std::make_shared<CommonEventPublishInfo>(commonEventPublishInfo);
Want want;
want.SetAction("COMMON_EVENT_DISK_REMOVED");
std::shared_ptr<CommonEventData> spCommonEventData = std::make_shared<CommonEventData>();
spCommonEventData->SetWant(want);
CommonEventRecord commonEventRecord;
commonEventRecord.publishInfo = commonEventPublishInfoSptr;
commonEventRecord.bundleName = "hello";
commonEventRecord.commonEventData = spCommonEventData;
CommonEventControlManager commonEventControlManager;
int ret = commonEventControlManager.CheckPermission(eventSubRecord, commonEventRecord);
EXPECT_EQ(DELIVERY_DELIVERED, ret);
}
/*
* @tc.number: CommonEventPublishPermissionEventUnitTest_1900
* @tc.name: test InnerCommonEventManager permission
* @tc.desc: function CheckPermission return false
*/
HWTEST_F(CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_1900,
Function | MediumTest | Level1)
{
GTEST_LOG_(INFO)
<< "CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_1900, TestSize.Level1";
CommonEventSubscribeInfo commonEventSubscriberInfo;
commonEventSubscriberInfo.SetPermission("1234");
std::shared_ptr<CommonEventSubscribeInfo> commonEventSubscriberInfoSptr =
std::make_shared<CommonEventSubscribeInfo>(commonEventSubscriberInfo);
EventSubscriberRecord eventSubRecord;
eventSubRecord.eventSubscriberInfo = commonEventSubscriberInfoSptr;
eventSubRecord.bundleName = "hello";
CommonEventPublishInfo commonEventPublishInfo;
std::vector<std::string> vecstr;
vecstr.emplace_back("456");
commonEventPublishInfo.SetSubscriberPermissions(vecstr);
std::shared_ptr<CommonEventPublishInfo> commonEventPublishInfoSptr =
std::make_shared<CommonEventPublishInfo>(commonEventPublishInfo);
Want want;
want.SetAction("COMMON_EVENT_DISK_REMOVED");
std::shared_ptr<CommonEventData> spCommonEventData = std::make_shared<CommonEventData>();
spCommonEventData->SetWant(want);
CommonEventRecord commonEventRecord;
commonEventRecord.publishInfo = commonEventPublishInfoSptr;
commonEventRecord.bundleName = "hello";
commonEventRecord.commonEventData = spCommonEventData;
CommonEventControlManager commonEventControlManager;
int ret = commonEventControlManager.CheckPermission(eventSubRecord, commonEventRecord);
EXPECT_EQ(DELIVERY_DELIVERED, ret);
}
/*
* @tc.number: CommonEventPublishPermissionEventUnitTest_2000
* @tc.name: test InnerCommonEventManager permission
* @tc.desc: function CheckPermission return false null
*/
HWTEST_F(CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_2000,
Function | MediumTest | Level1)
{
GTEST_LOG_(INFO)
<< "CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_2000, TestSize.Level1";
CommonEventSubscribeInfo commonEventSubscriberInfo;
commonEventSubscriberInfo.SetPermission("1234");
std::shared_ptr<CommonEventSubscribeInfo> commonEventSubscriberInfoSptr =
std::make_shared<CommonEventSubscribeInfo>(commonEventSubscriberInfo);
EventSubscriberRecord eventSubRecord;
eventSubRecord.eventSubscriberInfo = commonEventSubscriberInfoSptr;
eventSubRecord.bundleName = "hello";
CommonEventPublishInfo commonEventPublishInfo;
std::vector<std::string> vecstr;
vecstr.emplace_back("456");
commonEventPublishInfo.SetSubscriberPermissions(vecstr);
std::shared_ptr<CommonEventPublishInfo> commonEventPublishInfoSptr =
std::make_shared<CommonEventPublishInfo>(commonEventPublishInfo);
Want want;
want.SetAction("COMMON_EVENT_USB_DEVICE_ATTACHED");
std::shared_ptr<CommonEventData> spCommonEventData = std::make_shared<CommonEventData>();
spCommonEventData->SetWant(want);
CommonEventRecord commonEventRecord;
commonEventRecord.publishInfo = commonEventPublishInfoSptr;
commonEventRecord.bundleName = "hello";
commonEventRecord.commonEventData = spCommonEventData;
CommonEventControlManager commonEventControlManager;
int ret = commonEventControlManager.CheckPermission(eventSubRecord, commonEventRecord);
EXPECT_EQ(DELIVERY_DELIVERED, ret);
}
/*
* @tc.number: CommonEventPublishPermissionEventUnitTest_2100
* @tc.name: test InnerCommonEventManager permission
* @tc.desc: function CheckPermission return false not find
*/
HWTEST_F(CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_2100,
Function | MediumTest | Level1)
{
GTEST_LOG_(INFO)
<< "CommonEventPublishPermissionEventUnitTest, CommonEventPublishPermissionEventUnitTest_2100, TestSize.Level1";
CommonEventSubscribeInfo commonEventSubscriberInfo;
commonEventSubscriberInfo.SetPermission("1234");
std::shared_ptr<CommonEventSubscribeInfo> commonEventSubscriberInfoSptr =
std::make_shared<CommonEventSubscribeInfo>(commonEventSubscriberInfo);
EventSubscriberRecord eventSubRecord;
eventSubRecord.eventSubscriberInfo = commonEventSubscriberInfoSptr;
eventSubRecord.bundleName = "hello";
CommonEventPublishInfo commonEventPublishInfo;
std::vector<std::string> vecstr;
vecstr.emplace_back("456");
commonEventPublishInfo.SetSubscriberPermissions(vecstr);
std::shared_ptr<CommonEventPublishInfo> commonEventPublishInfoSptr =
std::make_shared<CommonEventPublishInfo>(commonEventPublishInfo);
Want want;
want.SetAction("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
std::shared_ptr<CommonEventData> spCommonEventData = std::make_shared<CommonEventData>();
spCommonEventData->SetWant(want);
CommonEventRecord commonEventRecord;
commonEventRecord.publishInfo = commonEventPublishInfoSptr;
commonEventRecord.bundleName = "hello";
commonEventRecord.commonEventData = spCommonEventData;
CommonEventControlManager commonEventControlManager;
int ret = commonEventControlManager.CheckPermission(eventSubRecord, commonEventRecord);
EXPECT_EQ(DELIVERY_DELIVERED, ret);
}
@@ -0,0 +1,134 @@
/*
* 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 "common_event.h"
#include "common_event_support.h"
#include "inner_common_event_manager.h"
#include "iservice_registry.h"
#include "mock_bundle_manager.h"
#include "system_ability_definition.h"
#include <gtest/gtest.h>
using namespace testing::ext;
using namespace OHOS::EventFwk;
namespace {
const int PID = 0;
const int UID = 1000; // system app
} // namespace
static OHOS::sptr<OHOS::IRemoteObject> bundleObject = nullptr;
class CommonEventPublishSystemEventTest : public testing::Test {
public:
CommonEventPublishSystemEventTest()
{}
~CommonEventPublishSystemEventTest()
{}
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
public:
InnerCommonEventManager innerCommonEventManager;
};
void CommonEventPublishSystemEventTest::SetUpTestCase(void)
{
bundleObject = new OHOS::AppExecFwk::MockBundleMgrService();
OHOS::sptr<OHOS::ISystemAbilityManager> systemAbilityManager =
OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
OHOS::ISystemAbilityManager::SAExtraProp saExtraProp;
systemAbilityManager->AddSystemAbility(OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, bundleObject, saExtraProp);
}
void CommonEventPublishSystemEventTest::TearDownTestCase(void)
{}
void CommonEventPublishSystemEventTest::SetUp(void)
{}
void CommonEventPublishSystemEventTest::TearDown(void)
{}
class SubscriberTest : public CommonEventSubscriber {
public:
SubscriberTest(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp)
{}
~SubscriberTest()
{}
virtual void OnReceiveEvent(const CommonEventData &data)
{}
};
/*
* @tc.number: CommonEventPublishSystemEventTest_0100
* @tc.name: test PublishCommonEvent
* @tc.desc: Verify Publish Systme CommonEvent success
*/
HWTEST_F(CommonEventPublishSystemEventTest, CommonEventPublishSystemEventTest_0100, Function | MediumTest | Level1)
{
/* Publish */
// make a want
Want want;
want.SetAction(CommonEventSupport::COMMON_EVENT_LOCKED_BOOT_COMPLETED);
// make common event data
CommonEventData data;
data.SetWant(want);
// make publish info
CommonEventPublishInfo publishInfo;
publishInfo.SetOrdered(false);
struct tm curTime;
// publish system event
bool publishResult =
innerCommonEventManager.PublishCommonEvent(data, publishInfo, nullptr, curTime, PID, UID, "bundlename");
EXPECT_EQ(true, publishResult);
}
/*
* @tc.number: CommonEventPublishSystemEventTest_0200
* @tc.name: test PublishCommonEvent
* @tc.desc: Verify Publish Systme CommonEvent fail because is not systemapp
*/
HWTEST_F(CommonEventPublishSystemEventTest, CommonEventPublishSystemEventTest_0200, Function | MediumTest | Level1)
{
/* Publish */
// make a want
Want want;
want.SetAction(CommonEventSupport::COMMON_EVENT_LOCKED_BOOT_COMPLETED);
// make common event data
CommonEventData data;
data.SetWant(want);
// make publish info
CommonEventPublishInfo publishInfo;
publishInfo.SetOrdered(false);
struct tm curTime;
// publish system event
bool publishResult =
innerCommonEventManager.PublishCommonEvent(data, publishInfo, nullptr, curTime, PID, 0, "bundlename");
EXPECT_EQ(false, publishResult);
}
@@ -0,0 +1,476 @@
/*
* 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.
*/
#define UNIT_TEST
#define private public
#define protected public
#include "common_event.h"
#include "common_event_manager.h"
#include "common_event_manager_service.h"
#include "common_event_sticky_manager.h"
#undef private
#undef protected
#include "errors.h"
#include "inner_common_event_manager.h"
#include "iservice_registry.h"
#include "mock_bundle_manager.h"
#include "system_ability_definition.h"
#include <gtest/gtest.h>
using namespace testing::ext;
using namespace OHOS::EventFwk;
namespace {
const std::string EVENT = "com.ces.test.event";
const std::string EVENT2 = "com.ces.test.event2";
const std::string EVENT3 = "com.ces.test.event3";
const std::string EVENT4 = "com.ces.test.event4";
const std::string EVENT5 = "com.ces.test.event5";
const std::string EVENT6 = "com.ces.test.event6";
const std::string TYPE = "com.ces.test.type";
const std::string TYPE2 = "com.ces.test.type2";
const std::string PERMISSION = "com.ces.test.permission";
const std::string STRING_EVENT = "com.ces.event";
const std::string STRING_DATA = "data";
} // namespace
static OHOS::sptr<OHOS::IRemoteObject> bundleObject = nullptr;
class CommonEventStickyTest : public testing::Test {
public:
CommonEventStickyTest()
{}
~CommonEventStickyTest()
{}
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
class SubscriberTest : public CommonEventSubscriber {
public:
SubscriberTest(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp)
{}
~SubscriberTest()
{}
virtual void OnReceiveEvent(const CommonEventData &data)
{}
};
void CommonEventStickyTest::SetUpTestCase(void)
{
bundleObject = new OHOS::AppExecFwk::MockBundleMgrService();
OHOS::sptr<OHOS::ISystemAbilityManager> systemAbilityManager =
OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
OHOS::ISystemAbilityManager::SAExtraProp saExtraProp;
systemAbilityManager->AddSystemAbility(OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, bundleObject, saExtraProp);
}
void CommonEventStickyTest::TearDownTestCase(void)
{}
void CommonEventStickyTest::SetUp(void)
{
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->OnStart();
}
void CommonEventStickyTest::TearDown(void)
{
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->OnStop();
}
/*
* @tc.number: CommonEventStickyTest_0100
* @tc.name: test StickyCommonEvent
* @tc.desc: Gets the published sticky event
*/
HWTEST_F(CommonEventStickyTest, CommonEventStickyTest_0100, Function | MediumTest | Level1)
{
/* Publish */
// make a want
Want want;
want.SetAction(EVENT);
want.SetType(TYPE);
// make common event data
CommonEventData data;
data.SetWant(want);
// make publish info
CommonEventPublishInfo publishInfo;
publishInfo.SetSticky(true);
bool publishResult = OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->PublishCommonEvent(
data, publishInfo, nullptr);
EXPECT_EQ(true, publishResult);
sleep(1);
CommonEventData Stickydata;
bool StickyResult =
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->GetStickyCommonEvent(EVENT, Stickydata);
EXPECT_EQ(true, StickyResult);
EXPECT_EQ(EVENT, Stickydata.GetWant().GetAction());
EXPECT_EQ(TYPE, Stickydata.GetWant().GetType());
}
/*
* @tc.number: CommonEventStickyTest_0200
* @tc.name: test StickyCommonEvent
* @tc.desc: Confirm whether the acquired sticky event data is the latest released
*/
HWTEST_F(CommonEventStickyTest, CommonEventStickyTest_0200, Function | MediumTest | Level1)
{
/* Publish */
// make a want
Want want;
want.SetAction(EVENT2);
want.SetType(TYPE);
// make common event data
CommonEventData data;
data.SetWant(want);
// make publish info
CommonEventPublishInfo publishInfo;
publishInfo.SetSticky(true);
bool publishResult = OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->PublishCommonEvent(
data, publishInfo, nullptr);
EXPECT_EQ(true, publishResult);
// make a want
Want want2;
want2.SetAction(EVENT2);
want2.SetType(TYPE2);
// make common event data
CommonEventData data2;
data2.SetWant(want2);
publishResult = OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->PublishCommonEvent(
data2, publishInfo, nullptr);
EXPECT_EQ(true, publishResult);
sleep(1);
CommonEventData Stickydata;
bool StickyResult =
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->GetStickyCommonEvent(EVENT2, Stickydata);
EXPECT_EQ(true, StickyResult);
EXPECT_EQ(EVENT2, Stickydata.GetWant().GetAction());
EXPECT_EQ(TYPE2, Stickydata.GetWant().GetType());
}
/*
* @tc.number: CommonEventStickyTest_0300
* @tc.name: test StickyCommonEvent
* @tc.desc: The event parameter of the obtained sticky event is ""
*/
HWTEST_F(CommonEventStickyTest, CommonEventStickyTest_0300, Function | MediumTest | Level1)
{
/* Publish */
// make a want
Want want;
want.SetAction(EVENT3);
want.SetType(TYPE);
// make common event data
CommonEventData data;
data.SetWant(want);
// make publish info
CommonEventPublishInfo publishInfo;
publishInfo.SetSticky(true);
bool publishResult = OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->PublishCommonEvent(
data, publishInfo, nullptr);
EXPECT_EQ(true, publishResult);
CommonEventData Stickydata;
bool StickyResult =
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->GetStickyCommonEvent("", Stickydata);
EXPECT_EQ(false, StickyResult);
}
/*
* @tc.number: CommonEventStickyTest_0400
* @tc.name: test StickyCommonEvent
* @tc.desc: Get an unpublished sticky event
*/
HWTEST_F(CommonEventStickyTest, CommonEventStickyTest_0400, Function | MediumTest | Level1)
{
/* Publish */
// make a want
Want want;
want.SetAction(EVENT4);
want.SetType(TYPE);
// make common event data
CommonEventData data;
data.SetWant(want);
// make publish info
CommonEventPublishInfo publishInfo;
publishInfo.SetSticky(true);
bool publishResult = OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->PublishCommonEvent(
data, publishInfo, nullptr);
EXPECT_EQ(true, publishResult);
CommonEventData Stickydata;
bool StickyResult =
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->GetStickyCommonEvent(EVENT6, Stickydata);
EXPECT_EQ(false, StickyResult);
}
/*
* @tc.number: CommonEventStickyTest_0500
* @tc.name: test StickyCommonEvent
* @tc.desc: Gets a non sticky event
*/
HWTEST_F(CommonEventStickyTest, CommonEventStickyTest_0500, Function | MediumTest | Level1)
{
/* Publish */
// make a want
Want want;
want.SetAction(EVENT5);
want.SetType(TYPE);
// make common event data
CommonEventData data;
data.SetWant(want);
// make publish info
CommonEventPublishInfo publishInfo;
publishInfo.SetSticky(false);
bool publishResult = OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->PublishCommonEvent(
data, publishInfo, nullptr);
EXPECT_EQ(true, publishResult);
CommonEventData Stickydata;
bool StickyResult =
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->GetStickyCommonEvent(EVENT5, Stickydata);
EXPECT_EQ(false, StickyResult);
}
/*
* @tc.number: FindStickyEvents_0600
* @tc.name: Find events of no subscriber info
* @tc.desc: Get invalid return value.
*/
HWTEST_F(CommonEventStickyTest, FindStickyEvents_0600, TestSize.Level0)
{
// make a vector of records
std::vector<std::shared_ptr<CommonEventRecord>> records;
// get common event sticky manager
auto stickyManagerPtr = OHOS::DelayedSingleton<CommonEventStickyManager>::GetInstance();
// find sticky events
int result = stickyManagerPtr->FindStickyEvents(nullptr, records);
EXPECT_EQ(result, OHOS::ERR_INVALID_VALUE);
}
/*
* @tc.number: FindStickyEvents_0700
* @tc.name: Fail to find events of subscriber info
* @tc.desc: No event would be pushed into common event records.
*/
HWTEST_F(CommonEventStickyTest, FindStickyEvents_0700, TestSize.Level0)
{
// make matching skills
MatchingSkills matchingSkills;
matchingSkills.AddEvent(STRING_EVENT);
// make subcriber info
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
auto subscriberInfoPtr = std::make_shared<CommonEventSubscribeInfo>(subscriberInfo);
// make a vector of records
std::vector<std::shared_ptr<CommonEventRecord>> records;
// get common event sticky manager
auto stickyManagerPtr = OHOS::DelayedSingleton<CommonEventStickyManager>::GetInstance();
// find sticky events
int result = stickyManagerPtr->FindStickyEvents(subscriberInfoPtr, records);
// check result of finding sticky events
EXPECT_EQ(result, OHOS::ERR_OK);
}
/*
* @tc.number: FindStickyEvents_0800
* @tc.name: Succeed to find events of subscriber info
* @tc.desc: Found events would be pushed into common event records.
*/
HWTEST_F(CommonEventStickyTest, FindStickyEvents_0800, TestSize.Level0)
{
// make matching skills
MatchingSkills matchingSkills;
matchingSkills.AddEvent(STRING_EVENT);
// make subcriber info
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
auto subscriberInfoPtr = std::make_shared<CommonEventSubscribeInfo>(subscriberInfo);
// make a vector of records
std::vector<std::shared_ptr<CommonEventRecord>> records;
// check size of the records
EXPECT_EQ((int)records.size(), 0);
// make a want
Want want;
want.SetAction(STRING_EVENT);
// make common event data
CommonEventData data;
data.SetWant(want);
// make a publish info and set it unordered
CommonEventPublishInfo publishInfo;
publishInfo.SetOrdered(false);
// make a record
auto recordPtr = std::make_shared<CommonEventRecord>();
recordPtr->commonEventData = std::make_shared<CommonEventData>(data);
recordPtr->publishInfo = std::make_shared<CommonEventPublishInfo>(publishInfo);
// get common event sticky manager
auto stickyManagerPtr = OHOS::DelayedSingleton<CommonEventStickyManager>::GetInstance();
// add a record in common event sticky manager
stickyManagerPtr->commonEventRecords_[STRING_EVENT] = recordPtr;
// find sticky events
int result = stickyManagerPtr->FindStickyEvents(subscriberInfoPtr, records);
// check result of finding sticky events
EXPECT_EQ(result, OHOS::ERR_OK);
// check size of the records
EXPECT_EQ((int)records.size(), 1);
// check the action
auto action = records.front()->commonEventData->GetWant().GetAction();
EXPECT_EQ(action, STRING_EVENT);
}
/*
* @tc.number: UpdateStickyEvent_0900
* @tc.name: Update an unexisting record
* @tc.desc: A new record would be added.
*/
HWTEST_F(CommonEventStickyTest, UpdateStickyEvent_0900, TestSize.Level0)
{
// make a want
Want want;
want.SetAction(STRING_EVENT);
// make common event data
CommonEventData data;
data.SetWant(want);
auto dataPtr = std::make_shared<CommonEventData>(data);
// make a publish info and set it unordered
CommonEventPublishInfo publishInfo;
publishInfo.SetOrdered(false);
auto publishInfoPtr = std::make_shared<CommonEventPublishInfo>(publishInfo);
// get common event sticky manager
auto stickyManagerPtr = OHOS::DelayedSingleton<CommonEventStickyManager>::GetInstance();
// update sticky event
CommonEventRecord eventRecord;
eventRecord.publishInfo = publishInfoPtr;
eventRecord.commonEventData = dataPtr;
int result = stickyManagerPtr->UpdateStickyEvent(eventRecord);
// check result of updating sticky event
EXPECT_EQ(result, OHOS::ERR_OK);
// get record the event
auto recordPtr = stickyManagerPtr->commonEventRecords_[STRING_EVENT];
// check record of the event
EXPECT_NE(recordPtr, nullptr);
// check the action
auto action = recordPtr->commonEventData->GetWant().GetAction();
EXPECT_EQ(action, STRING_EVENT);
}
/*
* @tc.number: UpdateStickyEvent_1000
* @tc.name: Update an existing record
* @tc.desc: The existing record would be updated.
*/
HWTEST_F(CommonEventStickyTest, UpdateStickyEvent_1000, TestSize.Level0)
{
// get common event sticky manager
auto stickyManagerPtr = OHOS::DelayedSingleton<CommonEventStickyManager>::GetInstance();
// get record of the event
auto recordPtr = stickyManagerPtr->commonEventRecords_[STRING_EVENT];
// make a want
Want want;
want.SetAction(STRING_EVENT);
// make common event data
CommonEventData data;
data.SetWant(want);
recordPtr->commonEventData = std::make_shared<CommonEventData>(data);
// check the data
EXPECT_EQ(recordPtr->commonEventData->GetData(), "");
// make a publish info and set it unordered
CommonEventPublishInfo publishInfo;
publishInfo.SetOrdered(false);
recordPtr->publishInfo = std::make_shared<CommonEventPublishInfo>(publishInfo);
// make a new want
Want newWant;
newWant.SetAction(STRING_EVENT);
// make common event data
CommonEventData newData;
newData.SetWant(newWant);
newData.SetData(STRING_DATA);
auto newDataPtr = std::make_shared<CommonEventData>(newData);
// make a publish info and set it unordered
CommonEventPublishInfo newPublishInfo;
newPublishInfo.SetOrdered(false);
auto newPublishInfoPtr = std::make_shared<CommonEventPublishInfo>(newPublishInfo);
// update sticky event
CommonEventRecord eventRecord;
eventRecord.publishInfo = newPublishInfoPtr;
eventRecord.commonEventData = newDataPtr;
int result = stickyManagerPtr->UpdateStickyEvent(eventRecord);
// check result of updating sticky event
EXPECT_EQ(result, OHOS::ERR_OK);
// get record the event
recordPtr = stickyManagerPtr->commonEventRecords_[STRING_EVENT];
// check record of the event
EXPECT_NE(recordPtr, nullptr);
// check the action
auto action = recordPtr->commonEventData->GetWant().GetAction();
EXPECT_EQ(action, STRING_EVENT);
// check the data
auto updatedData = recordPtr->commonEventData->GetData();
EXPECT_EQ(updatedData, STRING_DATA);
}
@@ -0,0 +1,484 @@
/*
* 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.
*/
#define private public
#define protected public
#include "common_event.h"
#include "common_event_manager_service.h"
#undef private
#undef protected
#include "iservice_registry.h"
#include "mock_bundle_manager.h"
#include "system_ability_definition.h"
#include <gtest/gtest.h>
using namespace testing::ext;
using namespace OHOS::EventFwk;
namespace {
const std::string EVENT = "com.ces.test.event";
const std::string ENTITY = "com.ces.test.entity";
const std::string SCHEME = "com.ces.test.scheme";
const std::string PERMISSION = "com.ces.test.permission";
const std::string DEVICEDID = "deviceId";
const int PRIORITY = 1;
} // namespace
static OHOS::sptr<OHOS::IRemoteObject> bundleObject = nullptr;
class CommonEventSubscribeUnitTest : public testing::Test {
public:
CommonEventSubscribeUnitTest()
{}
~CommonEventSubscribeUnitTest()
{}
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
class SubscriberTest : public CommonEventSubscriber {
public:
SubscriberTest(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp)
{}
~SubscriberTest()
{}
virtual void OnReceiveEvent(const CommonEventData &data)
{}
};
class CommonEventStubTest : public CommonEventStub {
public:
CommonEventStubTest()
{}
virtual bool PublishCommonEvent(const CommonEventData &event, const CommonEventPublishInfo &publishinfo,
const OHOS::sptr<IRemoteObject> &commonEventListener)
{
return false;
}
virtual bool SubscribeCommonEvent(
const CommonEventSubscribeInfo &subscriberInfo, const OHOS::sptr<IRemoteObject> &commonEventListener)
{
return false;
}
virtual bool UnsubscribeCommonEvent(const OHOS::sptr<IRemoteObject> &commonEventListener)
{
return false;
}
virtual bool DumpState(const std::string &event, std::vector<std::string> &state)
{
return false;
}
virtual ~CommonEventStubTest()
{}
virtual bool FinishReceiver(const OHOS::sptr<IRemoteObject> &proxy, const int &code,
const std::string &receiverData, const bool &abortEvent)
{
return false;
}
};
class EventReceiveStubTest : public EventReceiveStub {
public:
EventReceiveStubTest()
{}
~EventReceiveStubTest()
{}
virtual void NotifyEvent(const CommonEventData &commonEventData, const bool &ordered, const bool &sticky)
{}
};
void CommonEventSubscribeUnitTest::SetUpTestCase(void)
{
bundleObject = new OHOS::AppExecFwk::MockBundleMgrService();
OHOS::sptr<OHOS::ISystemAbilityManager> systemAbilityManager =
OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
OHOS::ISystemAbilityManager::SAExtraProp saExtraProp;
systemAbilityManager->AddSystemAbility(OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, bundleObject, saExtraProp);
}
void CommonEventSubscribeUnitTest::TearDownTestCase(void)
{}
void CommonEventSubscribeUnitTest::SetUp(void)
{
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->OnStart();
}
void CommonEventSubscribeUnitTest::TearDown(void)
{
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->OnStop();
}
/*
* @tc.number: CommonEventSubscribeUnitTest_0100
* @tc.name: test SubscribeCommonEvent
* @tc.desc: Verify SubscribeCommonEvent success
*/
HWTEST_F(CommonEventSubscribeUnitTest, CommonEventSubscribeUnitTest_0100, Function | MediumTest | Level1)
{
// make matching skills
MatchingSkills matchingSkills;
matchingSkills.AddEvent(EVENT);
matchingSkills.AddEntity(ENTITY);
matchingSkills.AddScheme(SCHEME);
// make subcriber info
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
subscriberInfo.SetPriority(PRIORITY);
subscriberInfo.SetPermission(PERMISSION);
subscriberInfo.SetDeviceId(DEVICEDID);
// make subscriber
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
// make common event listner
CommonEventListener *listener = new CommonEventListener(subscriber);
// SubscribeCommonEvent
bool result = OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->SubscribeCommonEvent(
subscriberInfo, listener->AsObject());
EXPECT_EQ(true, result);
}
/*
* @tc.number: CommonEventSubscribeUnitTest_0200
* @tc.name: test SubscribeCommonEvent
* @tc.desc: Verify SubscribeCommonEvent fail bacause service stop
*/
HWTEST_F(CommonEventSubscribeUnitTest, CommonEventSubscribeUnitTest_0200, Function | MediumTest | Level1)
{
// OnStop
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->OnStop();
// make matching skills
MatchingSkills matchingSkills;
matchingSkills.AddEvent(EVENT);
matchingSkills.AddEntity(ENTITY);
matchingSkills.AddScheme(SCHEME);
// make subcriber info
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
subscriberInfo.SetPriority(PRIORITY);
subscriberInfo.SetPermission(PERMISSION);
subscriberInfo.SetDeviceId(DEVICEDID);
// make subscriber
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
// make common event listner
CommonEventListener *listener = new CommonEventListener(subscriber);
// SubscribeCommonEvent
bool result = OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->SubscribeCommonEvent(
subscriberInfo, listener->AsObject());
EXPECT_EQ(false, result);
}
/*
* @tc.number: CommonEventSubscribeUnitTest_0300
* @tc.name: test subscribe event
* @tc.desc: InnerCommonEventManager subscribe common event success
*/
HWTEST_F(CommonEventSubscribeUnitTest, CommonEventSubscribeUnitTest_0300, Function | MediumTest | Level1)
{
// make subcriber info
MatchingSkills matchingSkills;
matchingSkills.AddEvent(EVENT);
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
// make subscriber
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
// make common event listner
OHOS::sptr<CommonEventListener> commonEventListener = new CommonEventListener(subscriber);
OHOS::sptr<OHOS::IRemoteObject> commonEventListenerPtr(commonEventListener);
// SubscribeCommonEvent
struct tm curTime{0};
InnerCommonEventManager innerCommonEventManager;
EXPECT_EQ(
true, innerCommonEventManager.SubscribeCommonEvent(subscriberInfo, commonEventListenerPtr, curTime, 0, 0, ""));
}
/*
* @tc.number: CommonEventSubscribeUnitTest_0400
* @tc.name: test subscribe event
* @tc.desc: InnerCommonEventManager subscribe common event fail because subscriberInfo has not event
*/
HWTEST_F(CommonEventSubscribeUnitTest, CommonEventSubscribeUnitTest_0400, Function | MediumTest | Level1)
{
// make subcriber info
MatchingSkills matchingSkills;
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
// make subscriber
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
// make common event listner
OHOS::sptr<CommonEventListener> commonEventListener = new CommonEventListener(subscriber);
OHOS::sptr<OHOS::IRemoteObject> commonEventListenerPtr(commonEventListener);
// SubscribeCommonEvent
InnerCommonEventManager innerCommonEventManager;
struct tm curTime{0};
EXPECT_EQ(
false, innerCommonEventManager.SubscribeCommonEvent(subscriberInfo, commonEventListenerPtr, curTime, 0, 0, ""));
}
/*
* @tc.number: CommonEventSubscribeUnitTest_0500
* @tc.name: test subscribe event
* @tc.desc: 1. subscribe common event
* 2. fail subscribe common event, inner common event manager
* common event listener is null
*/
HWTEST_F(CommonEventSubscribeUnitTest, CommonEventSubscribeUnitTest_0500, Function | MediumTest | Level1)
{
// make subcriber info
MatchingSkills matchingSkills;
matchingSkills.AddEvent(EVENT);
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
// SubscribeCommonEvent
InnerCommonEventManager innerCommonEventManager;
OHOS::sptr<OHOS::IRemoteObject> sp(nullptr);
struct tm curTime;
EXPECT_EQ(false, innerCommonEventManager.SubscribeCommonEvent(subscriberInfo, sp, curTime, 0, 0, ""));
}
/*
* @tc.number: CommonEventSubscribeUnitTest_0600
* @tc.name: test subscribe event
* @tc.desc: subscribe common event success
*/
HWTEST_F(CommonEventSubscribeUnitTest, CommonEventSubscribeUnitTest_0600, Function | MediumTest | Level1)
{
// make subcriber info
MatchingSkills matchingSkills;
matchingSkills.AddEvent(EVENT);
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
std::shared_ptr<CommonEventSubscribeInfo> subscribeInfoPtr =
std::make_shared<CommonEventSubscribeInfo>(subscriberInfo);
// make subscriber
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
// make common event listner
OHOS::sptr<CommonEventListener> commonEventListener = new CommonEventListener(subscriber);
OHOS::sptr<OHOS::IRemoteObject> commonEventListenerPtr(commonEventListener);
// InsertSubscriber
struct tm curTime{0};
CommonEventSubscriberManager commonEventSubscriberManager;
int result = commonEventSubscriberManager.InsertSubscriber(
subscribeInfoPtr, commonEventListener, curTime, 0, 0, "bundlename");
EXPECT_EQ(OHOS::ERR_OK, result);
}
/*
* @tc.number: CommonEventSubscribeUnitTest_0700
* @tc.name: test subscribe event
* @tc.desc: 1. subscribe common event
* 2. fail subscribe common event , common event subscriber manager
* event subscriber info is null
*/
HWTEST_F(CommonEventSubscribeUnitTest, CommonEventSubscribeUnitTest_0700, Function | MediumTest | Level1)
{
// make subcriber info
MatchingSkills matchingSkills;
matchingSkills.AddEvent(EVENT);
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
// make subscriber
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
// make common event listener
OHOS::sptr<CommonEventListener> commonEventListener = new CommonEventListener(subscriber);
OHOS::sptr<OHOS::IRemoteObject> commonEventListenerPtr(commonEventListener);
// InsertSubscriber
CommonEventSubscriberManager commonEventSubscriberManager;
struct tm curTime{0};
int result =
commonEventSubscriberManager.InsertSubscriber(nullptr, commonEventListenerPtr, curTime, 0, 0, "bundlename");
EXPECT_EQ(OHOS::ERR_INVALID_VALUE, result);
}
/*
* @tc.number: CommonEventSubscribeUnitTest_0800
* @tc.name: test subscribe event
* @tc.desc: 1. subscribe common event
* 2. fail subscribe common event , common event subscriber manager
* event common event listener is null
*/
HWTEST_F(CommonEventSubscribeUnitTest, CommonEventSubscribeUnitTest_0800, Function | MediumTest | Level1)
{
// make subcriber info
MatchingSkills matchingSkills;
matchingSkills.AddEvent(EVENT);
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
std::shared_ptr<CommonEventSubscribeInfo> subscribeInfoPtr =
std::make_shared<CommonEventSubscribeInfo>(subscriberInfo);
// make subcriber
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
// InsertSubscriber
struct tm curTime{0};
CommonEventSubscriberManager commonEventSubscriberManager;
int result = commonEventSubscriberManager.InsertSubscriber(subscribeInfoPtr, nullptr, curTime, 0, 0, "bundlename");
EXPECT_EQ(OHOS::ERR_INVALID_VALUE, result);
}
/*
* @tc.number: CommonEventSubscribeUnitTest_0900
* @tc.name: test subscribe event
* @tc.desc: 1. subscribe common event
* 2. fail subscribe common event , common event subscriber manager
* event size is null
*/
HWTEST_F(CommonEventSubscribeUnitTest, CommonEventSubscribeUnitTest_0900, Function | MediumTest | Level1)
{
// make subcriber info
MatchingSkills matchingSkills;
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
std::shared_ptr<CommonEventSubscribeInfo> subscribeInfoPtr =
std::make_shared<CommonEventSubscribeInfo>(subscriberInfo);
// make subscriber
CommonEventStubTest CommonEventStubTest;
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
// make commone event listener
OHOS::sptr<CommonEventListener> commonEventListener = new CommonEventListener(subscriber);
std::shared_ptr<InnerCommonEventManager> innerCommonEventManager = std::make_shared<InnerCommonEventManager>();
OHOS::sptr<OHOS::IRemoteObject> commonEventListenerPtr(commonEventListener);
// InsertSubscriber
struct tm curTime{0};
CommonEventSubscriberManager commonEventSubscriberManager;
int result = commonEventSubscriberManager.InsertSubscriber(
subscribeInfoPtr, commonEventListenerPtr, curTime, 0, 0, "bundlename");
EXPECT_EQ(OHOS::ERR_INVALID_VALUE, result);
}
/*
* @tc.number: CommonEventSubscribeUnitTest_1000
* @tc.name: ttest subscribe event
* @tc.desc: insert subscriber record locked success
*/
HWTEST_F(CommonEventSubscribeUnitTest, CommonEventSubscribeUnitTest_1000, Function | MediumTest | Level1)
{
// make subcriber info
MatchingSkills matchingSkills;
matchingSkills.AddEvent(EVENT);
matchingSkills.AddEvent(ENTITY);
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
// make subcriber
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
// make commone event listener
OHOS::sptr<CommonEventListener> commonEventListener = new CommonEventListener(subscriber);
OHOS::sptr<OHOS::IRemoteObject> commonEventListenerPtr(commonEventListener);
// make events
std::vector<std::string> events = subscriberInfo.GetMatchingSkills().GetEvents();
// make record
struct tm recordTime{0};
auto record = std::make_shared<EventSubscriberRecord>();
record->eventSubscriberInfo = std::make_shared<CommonEventSubscribeInfo>(subscriberInfo);
record->commonEventListener = commonEventListenerPtr;
record->recordTime = recordTime;
record->pid = 0;
record->uid = 0;
record->bundleName = "bundleName";
// InsertSubscriberRecordLocked
CommonEventSubscriberManager commonEventSubscriberManager;
int result = commonEventSubscriberManager.InsertSubscriberRecordLocked(events, record);
EXPECT_EQ(OHOS::ERR_OK, result);
}
/*
* @tc.number: CommonEventSubscribeUnitTest_1100
* @tc.name: test subscribe event
* @tc.desc: insert subscriber record locked fail because events size is 0
*/
HWTEST_F(CommonEventSubscribeUnitTest, CommonEventSubscribeUnitTest_1100, Function | MediumTest | Level1)
{
// make subcriber info
MatchingSkills matchingSkills;
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
// make subcriber
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
// make commone event listener
OHOS::sptr<CommonEventListener> commonEventListener = new CommonEventListener(subscriber);
OHOS::sptr<OHOS::IRemoteObject> commonEventListenerPtr(commonEventListener);
// make events
std::vector<std::string> events = subscriberInfo.GetMatchingSkills().GetEvents();
// make record
struct tm recordTime{0};
auto record = std::make_shared<EventSubscriberRecord>();
record->eventSubscriberInfo = std::make_shared<CommonEventSubscribeInfo>(subscriberInfo);
record->commonEventListener = commonEventListenerPtr;
record->recordTime = recordTime;
record->pid = 0;
record->uid = 0;
record->bundleName = "bundleName";
// InsertSubscriberRecordLocked
CommonEventSubscriberManager commonEventSubscriberManager;
int result = commonEventSubscriberManager.InsertSubscriberRecordLocked(events, record);
EXPECT_EQ(OHOS::ERR_INVALID_VALUE, result);
}
/*
* @tc.number: CommonEventSubscribeUnitTest_1200
* @tc.name: test subscribe event
* @tc.desc: insert subscriber record locked fail because record is nullptr
*/
HWTEST_F(CommonEventSubscribeUnitTest, CommonEventSubscribeUnitTest_1200, Function | MediumTest | Level1)
{
// make subcriber info
MatchingSkills matchingSkills;
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
// make events
std::vector<std::string> events = subscriberInfo.GetMatchingSkills().GetEvents();
CommonEventSubscriberManager commonEventSubscriberManager;
// InsertSubscriberRecordLocked
int result = commonEventSubscriberManager.InsertSubscriberRecordLocked(events, nullptr);
EXPECT_EQ(OHOS::ERR_INVALID_VALUE, result);
}
@@ -0,0 +1,304 @@
/*
* 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 "common_event.h"
#define private public
#define protected public
#include "common_event_manager_service.h"
#include "common_event_subscriber_manager.h"
#undef private
#undef protected
#include "iservice_registry.h"
#include "mock_bundle_manager.h"
#include "system_ability_definition.h"
#include <gtest/gtest.h>
using namespace testing::ext;
using namespace OHOS::EventFwk;
namespace {
const std::string EVENT = "com.ces.test.event";
const std::string ENTITY = "com.ces.test.entity";
const std::string SCHEME = "com.ces.test.scheme";
const std::string PERMISSION = "com.ces.test.permission";
const std::string DEVICEDID = "deviceId";
const int PRIORITY = 1;
} // namespace
static OHOS::sptr<OHOS::IRemoteObject> bundleObject = nullptr;
class CommonEventUnSubscribeUnitTest : public testing::Test {
public:
CommonEventUnSubscribeUnitTest()
{}
~CommonEventUnSubscribeUnitTest()
{}
static void SetUpTestCase(void);
static void TearDownTestCase(void);
void SetUp();
void TearDown();
};
class SubscriberTest : public CommonEventSubscriber {
public:
SubscriberTest(const CommonEventSubscribeInfo &sp) : CommonEventSubscriber(sp)
{}
~SubscriberTest()
{}
virtual void OnReceiveEvent(const CommonEventData &data)
{}
};
void CommonEventUnSubscribeUnitTest::SetUpTestCase(void)
{
bundleObject = new OHOS::AppExecFwk::MockBundleMgrService();
OHOS::sptr<OHOS::ISystemAbilityManager> systemAbilityManager =
OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
OHOS::ISystemAbilityManager::SAExtraProp saExtraProp;
systemAbilityManager->AddSystemAbility(OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, bundleObject, saExtraProp);
}
void CommonEventUnSubscribeUnitTest::TearDownTestCase(void)
{}
void CommonEventUnSubscribeUnitTest::SetUp(void)
{
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->OnStart();
}
void CommonEventUnSubscribeUnitTest::TearDown(void)
{
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->OnStop();
}
/*
* @tc.number: CommonEventUnSubscribeUnitTest_0100
* @tc.name: test SubscribeCommonEvent
* @tc.desc: Verify UnSubscribeCommonEvent success
*/
HWTEST_F(CommonEventUnSubscribeUnitTest, CommonEventUnSubscribeUnitTest_0100, Function | MediumTest | Level1)
{
// make matching skills
MatchingSkills matchingSkills;
matchingSkills.AddEvent(EVENT);
matchingSkills.AddEntity(ENTITY);
matchingSkills.AddScheme(SCHEME);
// make subcriber info
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
subscriberInfo.SetPriority(PRIORITY);
subscriberInfo.SetPermission(PERMISSION);
subscriberInfo.SetDeviceId(DEVICEDID);
// make subscriber
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
// make common event listner
CommonEventListener *listener = new CommonEventListener(subscriber);
// UnsubscribeCommonEvent
bool result =
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->UnsubscribeCommonEvent(listener->AsObject());
EXPECT_EQ(true, result);
}
/*
* @tc.number: CommonEventUnSubscribeUnitTest_0200
* @tc.name: test SubscribeCommonEvent
* @tc.desc: Verify UnSubscribeCommonEvent fail bacause service stop
*/
HWTEST_F(CommonEventUnSubscribeUnitTest, CommonEventUnSubscribeUnitTest_0200, Function | MediumTest | Level1)
{
// stop
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->OnStop();
// make matching skills
MatchingSkills matchingSkills;
matchingSkills.AddEvent(EVENT);
matchingSkills.AddEntity(ENTITY);
matchingSkills.AddScheme(SCHEME);
// make subcriber info
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
subscriberInfo.SetPriority(PRIORITY);
subscriberInfo.SetPermission(PERMISSION);
subscriberInfo.SetDeviceId(DEVICEDID);
// make subscriber
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
// make common event listner
CommonEventListener *listener = new CommonEventListener(subscriber);
bool result =
OHOS::DelayedSingleton<CommonEventManagerService>::GetInstance()->UnsubscribeCommonEvent(listener->AsObject());
EXPECT_EQ(false, result);
}
/*
* @tc.number: CommonEventUnSubscribeUnitTest_0300
* @tc.name: exception
* @tc.desc: verify InnerCommonEventManager UnsubscribeCommonEvent function success
*/
HWTEST_F(CommonEventUnSubscribeUnitTest, CommonEventUnSubscribeUnitTest_0300, Function | MediumTest | Level1)
{
// make subcriber info
MatchingSkills matchingSkills;
matchingSkills.AddEvent(EVENT);
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
// make subscriber
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
// make common event listner
OHOS::sptr<CommonEventListener> commonEventListener = new CommonEventListener(subscriber);
OHOS::sptr<OHOS::IRemoteObject> commonEventListenerPtr(commonEventListener);
// UnsubscribeCommonEvent
InnerCommonEventManager innerCommonEventManager;
EXPECT_EQ(true, innerCommonEventManager.UnsubscribeCommonEvent(commonEventListenerPtr));
}
/*
* @tc.number: CommonEventUnSubscribeUnitTest_0400
* @tc.name: exception
* @tc.desc: When the CommonEventListener does not exist,
* verify InnerCommonEventManager UnsubscribeCommonEvent function return value.
*/
HWTEST_F(CommonEventUnSubscribeUnitTest, CommonEventUnSubscribeUnitTest_0400, Function | MediumTest | Level1)
{
std::shared_ptr<InnerCommonEventManager> innerCommonEventManager = std::make_shared<InnerCommonEventManager>();
OHOS::sptr<OHOS::IRemoteObject> sp(nullptr);
EXPECT_EQ(false, innerCommonEventManager->UnsubscribeCommonEvent(sp));
}
/*
* @tc.number: CommonEventUnSubscribeUnitTest_0500
* @tc.name: exception
* @tc.desc: verify CommonEventSubscriberManager RemoveSubscriber success
*/
HWTEST_F(CommonEventUnSubscribeUnitTest, CommonEventUnSubscribeUnitTest_0500, Function | MediumTest | Level1)
{
// make subcriber info
MatchingSkills matchingSkills;
matchingSkills.AddEvent(EVENT);
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
// make subscriber
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
// make common event listner
OHOS::sptr<CommonEventListener> commonEventListener = new CommonEventListener(subscriber);
OHOS::sptr<OHOS::IRemoteObject> commonEventListenerPtr(commonEventListener);
// RemoveSubscriber
CommonEventSubscriberManager commonEventSubscriberManager;
int result = commonEventSubscriberManager.RemoveSubscriber(commonEventListenerPtr);
EXPECT_EQ(OHOS::ERR_OK, result);
}
/*
* @tc.number: CommonEventUnSubscribeUnitTest_0600
* @tc.name: exception
* @tc.desc: When the CommonEventListener does not exist,
* verify RemoveSubscriber fail.
*/
HWTEST_F(CommonEventUnSubscribeUnitTest, CommonEventUnSubscribeUnitTest_0600, Function | MediumTest | Level1)
{
CommonEventSubscriberManager commonEventSubscriberManager;
EXPECT_EQ(OHOS::ERR_INVALID_VALUE, commonEventSubscriberManager.RemoveSubscriber(nullptr));
}
/*
* @tc.number: CommonEventUnSubscribeUnitTest_0700
* @tc.name: exception
* @tc.desc: When the death_ is not null, verify RemoveSubscriber fail.
*/
HWTEST_F(CommonEventUnSubscribeUnitTest, CommonEventUnSubscribeUnitTest_0700, Function | MediumTest | Level1)
{
// make matching skills
MatchingSkills matchingSkills;
matchingSkills.AddEvent(EVENT);
matchingSkills.AddEntity(ENTITY);
matchingSkills.AddScheme(SCHEME);
// make subcriber info
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
subscriberInfo.SetPriority(PRIORITY);
subscriberInfo.SetPermission(PERMISSION);
subscriberInfo.SetDeviceId(DEVICEDID);
// make a subcriber
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
// make common event listner
OHOS::sptr<CommonEventListener> commonEventListener = new CommonEventListener(subscriber);
// RemoveSubscriber
CommonEventSubscriberManager commonEventSubscriberManager;
commonEventSubscriberManager.death_ = nullptr;
EXPECT_EQ(OHOS::ERR_OK, commonEventSubscriberManager.RemoveSubscriber(commonEventListener));
}
/*
* @tc.number: CommonEventUnSubscribeUnitTest_0800
* @tc.name: exception
* @tc.desc: verify RemoveSubscriberRecordLocked success.
*/
HWTEST_F(CommonEventUnSubscribeUnitTest, CommonEventUnSubscribeUnitTest_0800, Function | MediumTest | Level1)
{
// make subcriber info
MatchingSkills matchingSkills;
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
// make subcriber
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
// make commone event listener
OHOS::sptr<CommonEventListener> commonEventListener = new CommonEventListener(subscriber);
OHOS::sptr<OHOS::IRemoteObject> commonEventListenerPtr(commonEventListener);
// RemoveSubscriber
CommonEventSubscriberManager commonEventSubscriberManager;
EXPECT_EQ(OHOS::ERR_OK, commonEventSubscriberManager.RemoveSubscriberRecordLocked(commonEventListenerPtr));
}
/*
* @tc.number: CommonEventUnSubscribeUnitTest_0900
* @tc.name: exception
* @tc.desc: When the commonEventListener is null, verify RemoveSubscriberRecordLocked success.
*/
HWTEST_F(CommonEventUnSubscribeUnitTest, CommonEventUnSubscribeUnitTest_0900, Function | MediumTest | Level1)
{
// make subcriber info
MatchingSkills matchingSkills;
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
// make subcriber
std::shared_ptr<SubscriberTest> subscriber = std::make_shared<SubscriberTest>(subscriberInfo);
// make commone event listener
OHOS::sptr<CommonEventListener> commonEventListener = new CommonEventListener(subscriber);
OHOS::sptr<OHOS::IRemoteObject> commonEventListenerPtr(commonEventListener);
// RemoveSubscriber
CommonEventSubscriberManager commonEventSubscriberManager;
EXPECT_EQ(OHOS::ERR_INVALID_VALUE, commonEventSubscriberManager.RemoveSubscriberRecordLocked(nullptr));
}

Some files were not shown because too many files have changed in this diff Show More