diff --git a/data_object/.clang-format b/data_object/.clang-format index acad20138c758e45571591664df6f2a7e243248c..5ef4a6186f0d3a7bc9310968553377fa214e3a56 100644 --- a/data_object/.clang-format +++ b/data_object/.clang-format @@ -1,187 +1,187 @@ -Language: Cpp - -AccessModifierOffset: -4 - -AlignAfterOpenBracket: DontAlign - -AlignConsecutiveAssignments: false - -AlignConsecutiveDeclarations: false - -AlignOperands: true - -AlignTrailingComments: true - -AllowAllParametersOfDeclarationOnNextLine: false -AllowShortBlocksOnASingleLine: false - -AllowShortCaseLabelsOnASingleLine: false - -AllowShortFunctionsOnASingleLine: None - -AllowShortIfStatementsOnASingleLine: false - -AllowShortLoopsOnASingleLine: false - -AlwaysBreakAfterDefinitionReturnType: None - -AlwaysBreakAfterReturnType: None - -AlwaysBreakBeforeMultilineStrings: false - -AlwaysBreakTemplateDeclarations: false - -BinPackArguments: true - -BinPackParameters: true - -BreakBeforeBinaryOperators: NonAssignment - -BreakBeforeBraces: Custom - -AlignEscapedNewlines: Left - -BreakBeforeInheritanceComma: false - -BreakBeforeTernaryOperators: true - -BreakConstructorInitializersBeforeComma: false -BreakConstructorInitializers: BeforeColon - -BreakInheritanceList: BeforeComma -BreakAfterJavaFieldAnnotations: false -BreakStringLiterals: true - -ColumnLimit: 119 - -CommentPragmas: '^ NOLINT' -CompactNamespaces: false - -ConstructorInitializerAllOnOneLineOrOnePerLine: false - -ConstructorInitializerIndentWidth: 4 - -ContinuationIndentWidth: 4 -Cpp11BracedListStyle: false - -DerivePointerAlignment: false - -PointerAlignment: Right - -ExperimentalAutoDetectBinPacking: false - -FixNamespaceComments: true - -ForEachMacros: - - foreach - - Q_FOREACH - - BOOST_FOREACH -IncludeBlocks: Regroup - -IncludeCategories: - - Regex: '^' - Priority: 2 - - Regex: '^<.*\.h>' - Priority: 1 - - Regex: '^<.*' - Priority: 2 - - Regex: '.*' - Priority: 3 -IncludeIsMainRegex: '([-_](test|benchmark))?$' - -IndentCaseLabels: true -IndentPPDirectives: None - -IndentWidth: 4 - -IndentWrappedFunctionNames: false - -JavaScriptQuotes: Leave -JavaScriptWrapImports: true - -KeepEmptyLinesAtTheStartOfBlocks: false - -MacroBlockBegin: '[A-Z_]+_BEGIN\(.*\)$' - -MacroBlockEnd: '.[A-Z_]+_END\(.*\)$' - -MaxEmptyLinesToKeep: 1 - -NamespaceIndentation: None - -ObjCBinPackProtocolList: Never - -ObjCBlockIndentWidth: 4 - -ObjCSpaceAfterProperty: false - -ObjCSpaceBeforeProtocolList: true - -PenaltyBreakBeforeFirstCallParameter: 1000 - -PenaltyBreakComment: 100 - -PenaltyBreakFirstLessLess: 5 - -PenaltyBreakString: 10 - -PenaltyBreakTemplateDeclaration: 10 - -PenaltyExcessCharacter: 20 - -PenaltyReturnTypeOnItsOwnLine: 50 - -PenaltyBreakAssignment: 10 - -ReflowComments: false - -SortIncludes: true - -SortUsingDeclarations: true - -SpaceAfterCStyleCast: false - -SpaceAfterTemplateKeyword: false - -SpaceBeforeAssignmentOperators: true -SpaceBeforeCpp11BracedList: false -SpaceBeforeCtorInitializerColon: true -SpaceBeforeInheritanceColon: true - -SpaceBeforeParens: ControlStatements -SpaceBeforeRangeBasedForLoopColon: true - -SpaceInEmptyParentheses: false - -SpacesBeforeTrailingComments: 1 - -SpacesInAngles: false - -SpacesInContainerLiterals: true - -SpacesInCStyleCastParentheses: false - -SpacesInParentheses: false - -SpacesInSquareBrackets: false - -Standard: Cpp11 - -TabWidth: 4 - -UseTab: Never - -BraceWrapping: - AfterClass: false - AfterControlStatement: false - AfterEnum: false - AfterFunction: true - AfterNamespace: false - AfterObjCDeclaration: false - AfterStruct: false - AfterUnion: false - AfterExternBlock: false - BeforeCatch: false - BeforeElse: false - -DisableFormat: false +Language: Cpp + +AccessModifierOffset: -4 + +AlignAfterOpenBracket: DontAlign + +AlignConsecutiveAssignments: false + +AlignConsecutiveDeclarations: false + +AlignOperands: true + +AlignTrailingComments: true + +AllowAllParametersOfDeclarationOnNextLine: false +AllowShortBlocksOnASingleLine: false + +AllowShortCaseLabelsOnASingleLine: false + +AllowShortFunctionsOnASingleLine: None + +AllowShortIfStatementsOnASingleLine: false + +AllowShortLoopsOnASingleLine: false + +AlwaysBreakAfterDefinitionReturnType: None + +AlwaysBreakAfterReturnType: None + +AlwaysBreakBeforeMultilineStrings: false + +AlwaysBreakTemplateDeclarations: false + +BinPackArguments: true + +BinPackParameters: true + +BreakBeforeBinaryOperators: NonAssignment + +BreakBeforeBraces: Custom + +AlignEscapedNewlines: Left + +BreakBeforeInheritanceComma: false + +BreakBeforeTernaryOperators: true + +BreakConstructorInitializersBeforeComma: false +BreakConstructorInitializers: BeforeColon + +BreakInheritanceList: BeforeComma +BreakAfterJavaFieldAnnotations: false +BreakStringLiterals: true + +ColumnLimit: 119 + +CommentPragmas: '^ NOLINT' +CompactNamespaces: false + +ConstructorInitializerAllOnOneLineOrOnePerLine: false + +ConstructorInitializerIndentWidth: 4 + +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: false + +DerivePointerAlignment: false + +PointerAlignment: Right + +ExperimentalAutoDetectBinPacking: false + +FixNamespaceComments: true + +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IncludeBlocks: Regroup + +IncludeCategories: + - Regex: '^' + Priority: 2 + - Regex: '^<.*\.h>' + Priority: 1 + - Regex: '^<.*' + Priority: 2 + - Regex: '.*' + Priority: 3 +IncludeIsMainRegex: '([-_](test|benchmark))?$' + +IndentCaseLabels: true +IndentPPDirectives: None + +IndentWidth: 4 + +IndentWrappedFunctionNames: false + +JavaScriptQuotes: Leave +JavaScriptWrapImports: true + +KeepEmptyLinesAtTheStartOfBlocks: false + +MacroBlockBegin: '[A-Z_]+_BEGIN\(.*\)$' + +MacroBlockEnd: '.[A-Z_]+_END\(.*\)$' + +MaxEmptyLinesToKeep: 1 + +NamespaceIndentation: None + +ObjCBinPackProtocolList: Never + +ObjCBlockIndentWidth: 4 + +ObjCSpaceAfterProperty: false + +ObjCSpaceBeforeProtocolList: true + +PenaltyBreakBeforeFirstCallParameter: 1000 + +PenaltyBreakComment: 100 + +PenaltyBreakFirstLessLess: 5 + +PenaltyBreakString: 10 + +PenaltyBreakTemplateDeclaration: 10 + +PenaltyExcessCharacter: 20 + +PenaltyReturnTypeOnItsOwnLine: 50 + +PenaltyBreakAssignment: 10 + +ReflowComments: false + +SortIncludes: true + +SortUsingDeclarations: true + +SpaceAfterCStyleCast: false + +SpaceAfterTemplateKeyword: false + +SpaceBeforeAssignmentOperators: true +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true + +SpaceBeforeParens: ControlStatements +SpaceBeforeRangeBasedForLoopColon: true + +SpaceInEmptyParentheses: false + +SpacesBeforeTrailingComments: 1 + +SpacesInAngles: false + +SpacesInContainerLiterals: true + +SpacesInCStyleCastParentheses: false + +SpacesInParentheses: false + +SpacesInSquareBrackets: false + +Standard: Cpp11 + +TabWidth: 4 + +UseTab: Never + +BraceWrapping: + AfterClass: false + AfterControlStatement: false + AfterEnum: false + AfterFunction: true + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: false + AfterUnion: false + AfterExternBlock: false + BeforeCatch: false + BeforeElse: false + +DisableFormat: false diff --git a/data_object/README_zh.md b/data_object/README_zh.md index cb996762df1b27e32ad7cbd075ebe6b23719bfe1..8521780396e95d30577f225d3fa93745fe603eb7 100644 --- a/data_object/README_zh.md +++ b/data_object/README_zh.md @@ -73,12 +73,12 @@ import distributedObject from '@ohos.data.distributedDataObject' 针对分布式数据对象,有以下开发实例可供参考: -[备忘录应用](https://gitee.com/openharmony/distributeddatamgr_objectstore/tree/master/samples/distributedNotepad) +[备忘录应用](https://gitee.com/openharmony/distributeddatamgr_data_object/tree/master/samples/distributedNotepad) 分布式数据对象在备忘录应用中,通过分布式数据对象框架,当用户在某一端设备上新增备忘录事件,修改编辑事件标题和内容以及清空事件列表时,产生的数据变更结果均可以同步刷新显现在可信组网内其他设备上。 ## 相关仓 -- [分布式数据对象开发指导](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/database/database-distributedobject-guidelines.md) +- [分布式数据对象开发指导](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/database/data-sync-of-distributed-data-object.md) - [分布式数据对象API文档](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-data-distributedobject.md) - [distributeddatamgr\_datamgr](https://gitee.com/openharmony/distributeddatamgr_datamgr) - [third\_party\_sqlite](https://gitee.com/openharmony/third_party_sqlite) diff --git a/data_object/frameworks/innerkitsimpl/include/adaptor/hitrace.h b/data_object/frameworks/innerkitsimpl/include/adaptor/hitrace.h index 7ceb5980aa3b4a68beca3ea49dd196da29acdc90..447ff538b314877dad7197a205467a7b4ab5be1b 100644 --- a/data_object/frameworks/innerkitsimpl/include/adaptor/hitrace.h +++ b/data_object/frameworks/innerkitsimpl/include/adaptor/hitrace.h @@ -1,37 +1,37 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef DATA_OBJECT_HITRACE_H -#define DATA_OBJECT_HITRACE_H - -#include "hitrace_meter.h" - -namespace OHOS { -namespace ObjectStore { -class DataObjectHiTrace final { -public: - inline DataObjectHiTrace(const std::string &value) - { - StartTrace(HITRACE_TAG_DISTRIBUTEDDATA, value); - } - - inline ~DataObjectHiTrace() - { - FinishTrace(HITRACE_TAG_DISTRIBUTEDDATA); - } -}; -} // namespace ObjectStore -} // namespace OHOS - -#endif // DATA_OBJECT_HITRACE_H +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef DATA_OBJECT_HITRACE_H +#define DATA_OBJECT_HITRACE_H + +#include "hitrace_meter.h" + +namespace OHOS { +namespace ObjectStore { +class DataObjectHiTrace final { +public: + inline DataObjectHiTrace(const std::string &value) + { + StartTrace(HITRACE_TAG_DISTRIBUTEDDATA, value); + } + + inline ~DataObjectHiTrace() + { + FinishTrace(HITRACE_TAG_DISTRIBUTEDDATA); + } +}; +} // namespace ObjectStore +} // namespace OHOS + +#endif // DATA_OBJECT_HITRACE_H diff --git a/data_object/frameworks/innerkitsimpl/include/communicator/dev_manager.h b/data_object/frameworks/innerkitsimpl/include/communicator/dev_manager.h index ce68638934815bce201245bc6e2be961d5f212ef..d9376ece7df420a6aac7b8c26940e817e5d7e61b 100644 --- a/data_object/frameworks/innerkitsimpl/include/communicator/dev_manager.h +++ b/data_object/frameworks/innerkitsimpl/include/communicator/dev_manager.h @@ -1,38 +1,38 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef DATA_OBJECT_DEV_MANAGER_H -#define DATA_OBJECT_DEV_MANAGER_H -#include -#include -namespace OHOS { -namespace ObjectStore { -class DevManager { -public: - static DevManager *GetInstance() - { - static DevManager *instance = new DevManager(); - return instance; - } - void RegisterDevCallback(); - std::string GetUuidByNodeId(const std::string &nodeId) const; - -private: - DevManager(); - ~DevManager(); - int32_t Init(); -}; -} // namespace ObjectStore -} // namespace OHOS +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef DATA_OBJECT_DEV_MANAGER_H +#define DATA_OBJECT_DEV_MANAGER_H +#include +#include +namespace OHOS { +namespace ObjectStore { +class DevManager { +public: + static DevManager *GetInstance() + { + static DevManager *instance = new DevManager(); + return instance; + } + void RegisterDevCallback(); + std::string GetUuidByNodeId(const std::string &nodeId) const; + +private: + DevManager(); + ~DevManager(); + int32_t Init(); +}; +} // namespace ObjectStore +} // namespace OHOS #endif // DATA_OBJECT_DEV_MANAGER_H \ No newline at end of file diff --git a/data_object/frameworks/innerkitsimpl/src/communicator/dev_manager.cpp b/data_object/frameworks/innerkitsimpl/src/communicator/dev_manager.cpp index 0d6442f4a98f7c2a82806b3ac7b2d094e989f51d..ff58820afa5b1a3b2fc79185aa5e8a3435a38384 100644 --- a/data_object/frameworks/innerkitsimpl/src/communicator/dev_manager.cpp +++ b/data_object/frameworks/innerkitsimpl/src/communicator/dev_manager.cpp @@ -1,152 +1,152 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "dev_manager.h" - -#include -#include - -#include "device_manager.h" -#include "device_manager_callback.h" -#include "dm_device_info.h" -#include "softbus_adapter.h" -#include "app_types.h" - -namespace OHOS { -namespace ObjectStore { -using namespace OHOS::DistributedHardware; -constexpr int32_t DM_OK = 0; -constexpr int32_t DM_ERROR = -1; -constexpr const char *PKG_NAME = "ohos.objectstore"; -class DMStateCallback : public DeviceStateCallback { -public: - explicit DMStateCallback(std::shared_ptr softBusAdapter) : softBusAdapter_(softBusAdapter){}; - void OnDeviceOnline(const DmDeviceInfo &deviceInfo) override; - void OnDeviceOffline(const DmDeviceInfo &deviceInfo) override; - void OnDeviceChanged(const DmDeviceInfo &deviceInfo) override; - void OnDeviceReady(const DmDeviceInfo &deviceInfo) override; - -private: - std::shared_ptr softBusAdapter_; - void NotifyAll(const DmDeviceInfo &deviceInfo, DeviceChangeType type); -}; - -void DMStateCallback::OnDeviceOnline(const DmDeviceInfo &deviceInfo) -{ - std::string uuid = DevManager::GetInstance()->GetUuidByNodeId(std::string(deviceInfo.networkId)); - LOG_INFO("[Online] id:%{public}s, name:%{public}s, typeId:%{public}d", SoftBusAdapter::ToBeAnonymous(uuid).c_str(), - deviceInfo.deviceName, deviceInfo.deviceTypeId); - NotifyAll(deviceInfo, DeviceChangeType::DEVICE_ONLINE); -} - -void DMStateCallback::OnDeviceOffline(const DmDeviceInfo &deviceInfo) -{ - std::string uuid = DevManager::GetInstance()->GetUuidByNodeId(std::string(deviceInfo.networkId)); - LOG_INFO("[Offline] id:%{public}s, name:%{public}s, typeId:%{public}d", - SoftBusAdapter::ToBeAnonymous(uuid).c_str(), deviceInfo.deviceName, deviceInfo.deviceTypeId); - NotifyAll(deviceInfo, DeviceChangeType::DEVICE_OFFLINE); -} - -void DMStateCallback::OnDeviceChanged(const DmDeviceInfo &deviceInfo) -{ - std::string uuid = DevManager::GetInstance()->GetUuidByNodeId(std::string(deviceInfo.networkId)); - LOG_INFO("[InfoChange] id:%{public}s, name:%{public}s", SoftBusAdapter::ToBeAnonymous(uuid).c_str(), - deviceInfo.deviceName); -} - -void DMStateCallback::OnDeviceReady(const DmDeviceInfo &deviceInfo) -{ -} - -class DmDeathCallback : public DmInitCallback { -public: - explicit DmDeathCallback(DevManager &devManager) : devManager_(devManager){}; - void OnRemoteDied() override; - -private: - DevManager &devManager_; -}; - -void DmDeathCallback::OnRemoteDied() -{ - LOG_INFO("dm device manager died, init it again"); - devManager_.RegisterDevCallback(); -} - -void DMStateCallback::NotifyAll(const DmDeviceInfo &deviceInfo, DeviceChangeType type) -{ - DeviceInfo di = { std::string(deviceInfo.networkId), std::string(deviceInfo.deviceName), - std::to_string(deviceInfo.deviceTypeId) }; - softBusAdapter_->NotifyAll(di, type); -} - -DevManager::DevManager() -{ -} - -DevManager::~DevManager() -{ -} - -int32_t DevManager::Init() -{ - auto &deviceManager = DeviceManager::GetInstance(); - auto deviceInitCallback = std::make_shared(*this); - auto deviceStateCallback = std::make_shared(SoftBusAdapter::GetInstance()); - int32_t status = deviceManager.InitDeviceManager(PKG_NAME, deviceInitCallback); - if (status != DM_OK) { - return status; - } - status = deviceManager.RegisterDevStateCallback(PKG_NAME, "", deviceStateCallback); - return status; -} - -void DevManager::RegisterDevCallback() -{ - int32_t status = Init(); - if (status == DM_OK) { - return; - } - LOG_INFO("register device callback failed, try again."); - std::thread th = std::thread([this]() { - pthread_setname_np(pthread_self(), "Data_Object_InitDevManager"); - constexpr int RETRY_TIMES = 300; - int i = 0; - int32_t status = DM_ERROR; - while (i++ < RETRY_TIMES) { - status = Init(); - if (status == DM_OK) { - break; - } - std::this_thread::sleep_for(std::chrono::milliseconds(100)); - } - LOG_INFO("register device callback exit now: %{public}d times, status: %{public}d", i, status); - }); - th.detach(); -} - -std::string DevManager::GetUuidByNodeId(const std::string &nodeId) const -{ - std::string uuid = ""; - int32_t ret = DistributedHardware::DeviceManager::GetInstance().GetEncryptedUuidByNetworkId( - "ohos.objectstore", nodeId.c_str(), uuid); - if (ret != DM_OK) { - LOG_WARN("GetEncryptedUuidByNetworkId error, nodeId:%{public}s", SoftBusAdapter::ToBeAnonymous(nodeId).c_str()); - return ""; - } - return uuid; -} - -} // namespace ObjectStore +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "dev_manager.h" + +#include +#include + +#include "device_manager.h" +#include "device_manager_callback.h" +#include "dm_device_info.h" +#include "softbus_adapter.h" +#include "app_types.h" + +namespace OHOS { +namespace ObjectStore { +using namespace OHOS::DistributedHardware; +constexpr int32_t DM_OK = 0; +constexpr int32_t DM_ERROR = -1; +constexpr const char *PKG_NAME = "ohos.objectstore"; +class DMStateCallback : public DeviceStateCallback { +public: + explicit DMStateCallback(std::shared_ptr softBusAdapter) : softBusAdapter_(softBusAdapter){}; + void OnDeviceOnline(const DmDeviceInfo &deviceInfo) override; + void OnDeviceOffline(const DmDeviceInfo &deviceInfo) override; + void OnDeviceChanged(const DmDeviceInfo &deviceInfo) override; + void OnDeviceReady(const DmDeviceInfo &deviceInfo) override; + +private: + std::shared_ptr softBusAdapter_; + void NotifyAll(const DmDeviceInfo &deviceInfo, DeviceChangeType type); +}; + +void DMStateCallback::OnDeviceOnline(const DmDeviceInfo &deviceInfo) +{ + std::string uuid = DevManager::GetInstance()->GetUuidByNodeId(std::string(deviceInfo.networkId)); + LOG_INFO("[Online] id:%{public}s, name:%{public}s, typeId:%{public}d", SoftBusAdapter::ToBeAnonymous(uuid).c_str(), + deviceInfo.deviceName, deviceInfo.deviceTypeId); + NotifyAll(deviceInfo, DeviceChangeType::DEVICE_ONLINE); +} + +void DMStateCallback::OnDeviceOffline(const DmDeviceInfo &deviceInfo) +{ + std::string uuid = DevManager::GetInstance()->GetUuidByNodeId(std::string(deviceInfo.networkId)); + LOG_INFO("[Offline] id:%{public}s, name:%{public}s, typeId:%{public}d", + SoftBusAdapter::ToBeAnonymous(uuid).c_str(), deviceInfo.deviceName, deviceInfo.deviceTypeId); + NotifyAll(deviceInfo, DeviceChangeType::DEVICE_OFFLINE); +} + +void DMStateCallback::OnDeviceChanged(const DmDeviceInfo &deviceInfo) +{ + std::string uuid = DevManager::GetInstance()->GetUuidByNodeId(std::string(deviceInfo.networkId)); + LOG_INFO("[InfoChange] id:%{public}s, name:%{public}s", SoftBusAdapter::ToBeAnonymous(uuid).c_str(), + deviceInfo.deviceName); +} + +void DMStateCallback::OnDeviceReady(const DmDeviceInfo &deviceInfo) +{ +} + +class DmDeathCallback : public DmInitCallback { +public: + explicit DmDeathCallback(DevManager &devManager) : devManager_(devManager){}; + void OnRemoteDied() override; + +private: + DevManager &devManager_; +}; + +void DmDeathCallback::OnRemoteDied() +{ + LOG_INFO("dm device manager died, init it again"); + devManager_.RegisterDevCallback(); +} + +void DMStateCallback::NotifyAll(const DmDeviceInfo &deviceInfo, DeviceChangeType type) +{ + DeviceInfo di = { std::string(deviceInfo.networkId), std::string(deviceInfo.deviceName), + std::to_string(deviceInfo.deviceTypeId) }; + softBusAdapter_->NotifyAll(di, type); +} + +DevManager::DevManager() +{ +} + +DevManager::~DevManager() +{ +} + +int32_t DevManager::Init() +{ + auto &deviceManager = DeviceManager::GetInstance(); + auto deviceInitCallback = std::make_shared(*this); + auto deviceStateCallback = std::make_shared(SoftBusAdapter::GetInstance()); + int32_t status = deviceManager.InitDeviceManager(PKG_NAME, deviceInitCallback); + if (status != DM_OK) { + return status; + } + status = deviceManager.RegisterDevStateCallback(PKG_NAME, "", deviceStateCallback); + return status; +} + +void DevManager::RegisterDevCallback() +{ + int32_t status = Init(); + if (status == DM_OK) { + return; + } + LOG_INFO("register device callback failed, try again."); + std::thread th = std::thread([this]() { + pthread_setname_np(pthread_self(), "Data_Object_InitDevManager"); + constexpr int RETRY_TIMES = 300; + int i = 0; + int32_t status = DM_ERROR; + while (i++ < RETRY_TIMES) { + status = Init(); + if (status == DM_OK) { + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } + LOG_INFO("register device callback exit now: %{public}d times, status: %{public}d", i, status); + }); + th.detach(); +} + +std::string DevManager::GetUuidByNodeId(const std::string &nodeId) const +{ + std::string uuid = ""; + int32_t ret = DistributedHardware::DeviceManager::GetInstance().GetEncryptedUuidByNetworkId( + "ohos.objectstore", nodeId.c_str(), uuid); + if (ret != DM_OK) { + LOG_WARN("GetEncryptedUuidByNetworkId error, nodeId:%{public}s", SoftBusAdapter::ToBeAnonymous(nodeId).c_str()); + return ""; + } + return uuid; +} + +} // namespace ObjectStore } // namespace OHOS \ No newline at end of file diff --git a/data_object/frameworks/innerkitsimpl/test/distributedtest/data_object_test/BUILD.gn b/data_object/frameworks/innerkitsimpl/test/distributedtest/data_object_test/BUILD.gn index 0cedf2944a0f8e9fe961831f825af966e04228a2..4dc42ecac6a2e99aaffc0c16640b6ce66eabd00e 100644 --- a/data_object/frameworks/innerkitsimpl/test/distributedtest/data_object_test/BUILD.gn +++ b/data_object/frameworks/innerkitsimpl/test/distributedtest/data_object_test/BUILD.gn @@ -36,6 +36,7 @@ ohos_distributedtest("DistributedTest") { external_deps = [ "access_token:libaccesstoken_sdk", "access_token:libnativetoken", + "access_token:libtoken_setproc", "c_utils:utils", "dsoftbus:softbus_client", "hilog_native:libhilog", @@ -43,7 +44,6 @@ ohos_distributedtest("DistributedTest") { ] deps = [ - "//base/security/access_token/interfaces/innerkits/token_setproc:libtoken_setproc", "//foundation/distributeddatamgr/data_object/interfaces/innerkits:distributeddataobject_static", "//third_party/googletest:gtest_main", ] @@ -57,6 +57,7 @@ ohos_distributedtest("DistributedTestAgent") { external_deps = [ "access_token:libaccesstoken_sdk", "access_token:libnativetoken", + "access_token:libtoken_setproc", "c_utils:utils", "dsoftbus:softbus_client", "hilog_native:libhilog", @@ -64,7 +65,6 @@ ohos_distributedtest("DistributedTestAgent") { ] deps = [ - "//base/security/access_token/interfaces/innerkits/token_setproc:libtoken_setproc", "//foundation/distributeddatamgr/data_object/interfaces/innerkits:distributeddataobject_static", "//third_party/googletest:gtest_main", ] diff --git a/data_object/frameworks/innerkitsimpl/test/fuzztest/objectstore_fuzzer/BUILD.gn b/data_object/frameworks/innerkitsimpl/test/fuzztest/objectstore_fuzzer/BUILD.gn index f9af7db1cfa4abd369e4771e067801112e9a461c..be2e6b54f4470c8aecf3f739d41e252276fb93ce 100644 --- a/data_object/frameworks/innerkitsimpl/test/fuzztest/objectstore_fuzzer/BUILD.gn +++ b/data_object/frameworks/innerkitsimpl/test/fuzztest/objectstore_fuzzer/BUILD.gn @@ -33,8 +33,8 @@ ohos_fuzztest("ObjectStoreFuzzTest") { configs = [ ":module_private_config" ] deps = [ - "../../../../../../kv_store/frameworks/libs/distributeddb:distributeddb", "//foundation/distributeddatamgr/data_object/interfaces/innerkits:distributeddataobject_static", + "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb:distributeddb", ] external_deps = [ "hilog_native:libhilog" ] diff --git a/data_object/frameworks/innerkitsimpl/test/unittest/BUILD.gn b/data_object/frameworks/innerkitsimpl/test/unittest/BUILD.gn index be2c3496038eed2b75c514933193e2e938677a2b..e31f191fc2fa642b7f6ddfd1e0532db43732099d 100644 --- a/data_object/frameworks/innerkitsimpl/test/unittest/BUILD.gn +++ b/data_object/frameworks/innerkitsimpl/test/unittest/BUILD.gn @@ -53,11 +53,11 @@ ohos_unittest("NativeObjectStoreTest") { external_deps = [ "access_token:libaccesstoken_sdk", "access_token:libnativetoken", + "access_token:libtoken_setproc", "hilog_native:libhilog", ] deps = [ - "//base/security/access_token/interfaces/innerkits/token_setproc:libtoken_setproc", "//foundation/distributeddatamgr/data_object/interfaces/innerkits:distributeddataobject_static", "//third_party/googletest:gmock", "//third_party/googletest:gtest_main", diff --git a/data_object/frameworks/innerkitsimpl/test/unittest/mock/include/mock_app_data_change_listener.h b/data_object/frameworks/innerkitsimpl/test/unittest/mock/include/mock_app_data_change_listener.h index 4e5342f5b6755f0b4e12ebad40454443fdb700ca..e903734e62b1f0f8e965119b4adf187bdc4999be 100644 --- a/data_object/frameworks/innerkitsimpl/test/unittest/mock/include/mock_app_data_change_listener.h +++ b/data_object/frameworks/innerkitsimpl/test/unittest/mock/include/mock_app_data_change_listener.h @@ -1,30 +1,30 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef DATA_OBJECT_MOCK_APP_DATA_CHANGE_LISTENER_H -#define DATA_OBJECT_MOCK_APP_DATA_CHANGE_LISTENER_H - -#include -#include "app_data_change_listener.h" - -namespace OHOS { -namespace ObjectStore { -class MockAppDataChangeListener : public AppDataChangeListener { - MOCK_CONST_METHOD4(OnMessage, - void(const DeviceInfo &info, const uint8_t *ptr, const int size, const PipeInfo &pipeInfo)); -}; -} // namespace ObjectStore -} // namespace OHOS - -#endif // DATA_OBJECT_MOCK_APP_DATA_CHANGE_LISTENER_H +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef DATA_OBJECT_MOCK_APP_DATA_CHANGE_LISTENER_H +#define DATA_OBJECT_MOCK_APP_DATA_CHANGE_LISTENER_H + +#include +#include "app_data_change_listener.h" + +namespace OHOS { +namespace ObjectStore { +class MockAppDataChangeListener : public AppDataChangeListener { + MOCK_CONST_METHOD4(OnMessage, + void(const DeviceInfo &info, const uint8_t *ptr, const int size, const PipeInfo &pipeInfo)); +}; +} // namespace ObjectStore +} // namespace OHOS + +#endif // DATA_OBJECT_MOCK_APP_DATA_CHANGE_LISTENER_H diff --git a/data_object/frameworks/innerkitsimpl/test/unittest/mock/include/mock_app_device_change_listener.h b/data_object/frameworks/innerkitsimpl/test/unittest/mock/include/mock_app_device_change_listener.h index 6460a436b95cd373235abf09725ee6ff8ca6bce8..09aff6e8e410c80af1722f2e3bfc6574e1888f4f 100644 --- a/data_object/frameworks/innerkitsimpl/test/unittest/mock/include/mock_app_device_change_listener.h +++ b/data_object/frameworks/innerkitsimpl/test/unittest/mock/include/mock_app_device_change_listener.h @@ -1,29 +1,29 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#ifndef DATA_OBJECT_MOCK_APP_DEVICE_CHANGE_LISTENER_H -#define DATA_OBJECT_MOCK_APP_DEVICE_CHANGE_LISTENER_H - -#include -#include "app_device_status_change_listener.h" - -namespace OHOS { -namespace ObjectStore { -class MockAppDeviceStatusChangeListener : public AppDeviceStatusChangeListener { - MOCK_CONST_METHOD2(OnDeviceChanged, void(const DeviceInfo &info, const DeviceChangeType &type)); -}; -} // namespace ObjectStore -} // namespace OHOS - -#endif // DATA_OBJECT_MOCK_APP_DEVICE_CHANGE_LISTENER_H +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef DATA_OBJECT_MOCK_APP_DEVICE_CHANGE_LISTENER_H +#define DATA_OBJECT_MOCK_APP_DEVICE_CHANGE_LISTENER_H + +#include +#include "app_device_status_change_listener.h" + +namespace OHOS { +namespace ObjectStore { +class MockAppDeviceStatusChangeListener : public AppDeviceStatusChangeListener { + MOCK_CONST_METHOD2(OnDeviceChanged, void(const DeviceInfo &info, const DeviceChangeType &type)); +}; +} // namespace ObjectStore +} // namespace OHOS + +#endif // DATA_OBJECT_MOCK_APP_DEVICE_CHANGE_LISTENER_H diff --git a/data_object/frameworks/innerkitsimpl/test/unittest/mock/src/mock_soft_bus.cpp b/data_object/frameworks/innerkitsimpl/test/unittest/mock/src/mock_soft_bus.cpp index 5ee21e5155138100013378158b44e80efdfe929b..9151c97a5575a4b591c7d7f27b7d81d9809c34bb 100644 --- a/data_object/frameworks/innerkitsimpl/test/unittest/mock/src/mock_soft_bus.cpp +++ b/data_object/frameworks/innerkitsimpl/test/unittest/mock/src/mock_soft_bus.cpp @@ -1,90 +1,90 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include -#include - -#include "softbus_bus_center.h" - -static std::map> sessionListeners; -static std::map callbacks_; - -int OpenSession(const char *mySessionName, const char *peerSessionName, const char *peerDeviceId, const char *groupId, - const SessionAttribute *attr) -{ - return -1; -} - -int SendBytes(int sessionId, const void *data, unsigned int len) -{ - return -1; -} - -int RemoveSessionServer(const char *pkgName, const char *sessionName) -{ - const char *invalidSessionName = "INVALID_SESSION_NAME"; - const char *closeFailedSessionName = "REMOVE_FAILED_SESSION_NAME"; - if (!strcmp(sessionName, invalidSessionName)) { - return -1; - } - if (!strcmp(sessionName, closeFailedSessionName)) { - return -1; - } - return 0; -} -int GetMySessionName(int sessionId, char *sessionName, unsigned int len) -{ - return -1; -} -int GetPeerSessionName(int sessionId, char *sessionName, unsigned int len) -{ - return 0; -} -int GetPeerDeviceId(int sessionId, char *devId, unsigned int len) -{ - return 0; -} -void CloseSession(int sessionId){}; -int GetSessionSide(int sessionId) -{ - return 1; -}; - -int32_t GetLocalNodeDeviceInfo(const char *pkgName, NodeBasicInfo *info) -{ - return -1; -} - -int32_t GetAllNodeDeviceInfo(const char *pkgName, NodeBasicInfo **info, int32_t *infoNum) -{ - return -1; -} - -int32_t GetNodeKeyInfo(const char *pkgName, const char *networkId, NodeDeviceInfoKey key, uint8_t *info, - int32_t infoLen) -{ - return -1; -} - -int CreateSessionServer(const char *pkgName, const char *sessionName, const ISessionListener *listener) -{ - const char *invalidSessionName = "INVALID_SESSION_NAME"; - if (!strcmp(sessionName, invalidSessionName)) { - return -1; - } - return 0; +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include + +#include "softbus_bus_center.h" + +static std::map> sessionListeners; +static std::map callbacks_; + +int OpenSession(const char *mySessionName, const char *peerSessionName, const char *peerDeviceId, const char *groupId, + const SessionAttribute *attr) +{ + return -1; +} + +int SendBytes(int sessionId, const void *data, unsigned int len) +{ + return -1; +} + +int RemoveSessionServer(const char *pkgName, const char *sessionName) +{ + const char *invalidSessionName = "INVALID_SESSION_NAME"; + const char *closeFailedSessionName = "REMOVE_FAILED_SESSION_NAME"; + if (!strcmp(sessionName, invalidSessionName)) { + return -1; + } + if (!strcmp(sessionName, closeFailedSessionName)) { + return -1; + } + return 0; +} +int GetMySessionName(int sessionId, char *sessionName, unsigned int len) +{ + return -1; +} +int GetPeerSessionName(int sessionId, char *sessionName, unsigned int len) +{ + return 0; +} +int GetPeerDeviceId(int sessionId, char *devId, unsigned int len) +{ + return 0; +} +void CloseSession(int sessionId){}; +int GetSessionSide(int sessionId) +{ + return 1; +}; + +int32_t GetLocalNodeDeviceInfo(const char *pkgName, NodeBasicInfo *info) +{ + return -1; +} + +int32_t GetAllNodeDeviceInfo(const char *pkgName, NodeBasicInfo **info, int32_t *infoNum) +{ + return -1; +} + +int32_t GetNodeKeyInfo(const char *pkgName, const char *networkId, NodeDeviceInfoKey key, uint8_t *info, + int32_t infoLen) +{ + return -1; +} + +int CreateSessionServer(const char *pkgName, const char *sessionName, const ISessionListener *listener) +{ + const char *invalidSessionName = "INVALID_SESSION_NAME"; + if (!strcmp(sessionName, invalidSessionName)) { + return -1; + } + return 0; } \ No newline at end of file diff --git a/data_object/frameworks/innerkitsimpl/test/unittest/src/app_pipe_mgr_test.cpp b/data_object/frameworks/innerkitsimpl/test/unittest/src/app_pipe_mgr_test.cpp index 59ea357c7b88d828cd75bf4f27a9a8fa30310be9..5d2dc4f0f6985a4b992bf50e7b12dd26b6cc1098 100644 --- a/data_object/frameworks/innerkitsimpl/test/unittest/src/app_pipe_mgr_test.cpp +++ b/data_object/frameworks/innerkitsimpl/test/unittest/src/app_pipe_mgr_test.cpp @@ -1,278 +1,278 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include - -#include "app_pipe_mgr.h" -#include "app_types.h" -#include "auto_launch_export.h" -#include "ipc_skeleton.h" -#include "objectstore_errors.h" -#include "mock_app_data_change_listener.h" - -namespace { -using namespace testing::ext; -using namespace OHOS::ObjectStore; - -class NativeAppPipeMgrTest : public testing::Test { -public: - static void SetUpTestCase(void); - static void TearDownTestCase(void); - void SetUp(); - void TearDown(); -}; - -void NativeAppPipeMgrTest::SetUpTestCase(void) -{ - // input testsuit setup step,setup invoked before all testcases -} - -void NativeAppPipeMgrTest::TearDownTestCase(void) -{ - // input testsuit teardown step,teardown invoked after all testcases -} - -void NativeAppPipeMgrTest::SetUp(void) -{ - // input testcase setup step,setup invoked before each testcases -} - -void NativeAppPipeMgrTest::TearDown(void) -{ - // input testcase teardown step,teardown invoked after each testcases -} - -/** - * @tc.name: NativeAppPipeMgrTest_StartWatchDataChange_001 - * @tc.desc: test NativeAppPipeMgrTest StartWatchDataChange. argument invalid - * @tc.type: FUNC - */ -HWTEST_F(NativeAppPipeMgrTest, NativeAppPipeMgrTest_StartWatchDataChange_001, TestSize.Level1) -{ - PipeInfo pipeInfo = {""}; - AppDataChangeListener *observer = new MockAppDataChangeListener(); - AppPipeMgr *appPipeMgr = new AppPipeMgr(); - auto ret = appPipeMgr->StartWatchDataChange(observer, pipeInfo); - EXPECT_EQ(Status::INVALID_ARGUMENT, ret); -} - -/** - * @tc.name: NativeAppPipeMgrTest_StartWatchDataChange_002 - * @tc.desc: test NativeAppPipeMgrTest StartWatchDataChange. pipId not found. - * @tc.type: FUNC - */ -HWTEST_F(NativeAppPipeMgrTest, NativeAppPipeMgrTest_StartWatchDataChange_002, TestSize.Level1) -{ - PipeInfo pipeInfo = { "pipId01" }; - AppDataChangeListener *observer = new MockAppDataChangeListener(); - AppPipeMgr *appPipeMgr = new AppPipeMgr(); - auto ret = appPipeMgr->StartWatchDataChange(observer, pipeInfo); - EXPECT_EQ(Status::ERROR, ret); -} - -/** - * @tc.name: NativeAppPipeMgrTest_StopWatchDataChange_001 - * @tc.desc: test NativeAppPipeMgrTest StopWatchDataChange. argument invalid - * @tc.type: FUNC - */ -HWTEST_F(NativeAppPipeMgrTest, NativeAppPipeMgrTest_StopWatchDataChange_001, TestSize.Level1) -{ - PipeInfo pipeInfo = { "pipId01" }; - AppPipeMgr *appPipeMgr = new AppPipeMgr(); - auto ret = appPipeMgr->StopWatchDataChange(nullptr, pipeInfo); - EXPECT_EQ(Status::INVALID_ARGUMENT, ret); -} - -/** - * @tc.name: NativeAppPipeMgrTest_StopWatchDataChange_002 - * @tc.desc: test NativeAppPipeMgrTest StopWatchDataChange. - * @tc.type: FUNC - */ -HWTEST_F(NativeAppPipeMgrTest, NativeAppPipeMgrTest_StopWatchDataChange_002, TestSize.Level1) -{ - PipeInfo pipeInfo = { "pipId01" }; - AppPipeMgr *appPipeMgr = new AppPipeMgr(); - AppDataChangeListener *observer = new MockAppDataChangeListener(); - auto ret = appPipeMgr->StopWatchDataChange(observer, pipeInfo); - EXPECT_EQ(Status::ERROR, ret); -} - -/** - * @tc.name: NativeAppPipeMgrTest_StopWatchDataChange_003 - * @tc.desc: test NativeAppPipeMgrTest StopWatchDataChange. - * @tc.type: FUNC - */ -HWTEST_F(NativeAppPipeMgrTest, NativeAppPipeMgrTest_StopWatchDataChange_003, TestSize.Level1) -{ - PipeInfo pipeInfo = { "pipId01" }; - AppPipeMgr *appPipeMgr = new AppPipeMgr(); - AppDataChangeListener *observer = new MockAppDataChangeListener(); - auto ret = appPipeMgr->StopWatchDataChange(observer, pipeInfo); - EXPECT_EQ(Status::ERROR, ret); -} - -/** - * @tc.name: NativeAppPipeMgrTest_Start_001 - * @tc.desc: test NativeAppPipeMgrTest Start. pipInfo is empty - * @tc.type: FUNC - */ -HWTEST_F(NativeAppPipeMgrTest, NativeAppPipeMgrTest_Start_001, TestSize.Level1) -{ - PipeInfo pipeInfo = {}; - AppPipeMgr *appPipeMgr = new AppPipeMgr(); - auto ret = appPipeMgr->Start(pipeInfo); - EXPECT_EQ(Status::INVALID_ARGUMENT, ret); -} - -/** - * @tc.name: NativeAppPipeMgrTest_Start_002 - * @tc.desc: test NativeAppPipeMgrTest Start. invalid pipInfo - * @tc.type: FUNC - */ -HWTEST_F(NativeAppPipeMgrTest, NativeAppPipeMgrTest_Start_002, TestSize.Level1) -{ - PipeInfo pipeInfo = {"INVALID_SESSION_NAME"}; - AppPipeMgr *appPipeMgr = new AppPipeMgr(); - auto ret = appPipeMgr->Start(pipeInfo); - EXPECT_EQ(Status::ILLEGAL_STATE, ret); -} - -/** - * @tc.name: NativeAppPipeMgrTest_Start_003 - * @tc.desc: test NativeAppPipeMgrTest Start. - * @tc.type: FUNC - */ -HWTEST_F(NativeAppPipeMgrTest, NativeAppPipeMgrTest_Start_003, TestSize.Level1) -{ - PipeInfo pipeInfo = { "pipInfo01" }; - AppPipeMgr *appPipeMgr = new AppPipeMgr(); - auto ret = appPipeMgr->Start(pipeInfo); - EXPECT_EQ(Status::SUCCESS, ret); - ret = appPipeMgr->Stop(pipeInfo); - EXPECT_EQ(Status::SUCCESS, ret); -} - -/** - * @tc.name: NativeAppPipeMgrTest_Start_004 - * @tc.desc: test NativeAppPipeMgrTest Start. repeat start - * @tc.type: FUNC - */ -HWTEST_F(NativeAppPipeMgrTest, NativeAppPipeMgrTest_Start_004, TestSize.Level1) -{ - PipeInfo pipeInfo = { "pipInfo01" }; - AppPipeMgr *appPipeMgr = new AppPipeMgr(); - auto ret = appPipeMgr->Start(pipeInfo); - EXPECT_EQ(Status::SUCCESS, ret); - ret = appPipeMgr->Start(pipeInfo); - EXPECT_EQ(Status::REPEATED_REGISTER, ret); - ret = appPipeMgr->Stop(pipeInfo); - EXPECT_EQ(Status::SUCCESS, ret); -} - -/** - * @tc.name: NativeAppPipeMgrTest_Stop_001 - * @tc.desc: test NativeAppPipeMgrTest Stop. pipInfo not found. - * @tc.type: FUNC - */ -HWTEST_F(NativeAppPipeMgrTest, NativeAppPipeMgrTest_Stop_001, TestSize.Level1) -{ - PipeInfo pipeInfo = { "pipInfo01" }; - AppPipeMgr *appPipeMgr = new AppPipeMgr(); - auto ret = appPipeMgr->Stop(pipeInfo); - EXPECT_EQ(Status::KEY_NOT_FOUND, ret); -} - -/** - * @tc.name: NativeAppPipeMgrTest_Stop_002 - * @tc.desc: test NativeAppPipeMgrTest Stop. RemoveSessionServer failed - * @tc.type: FUNC - */ -HWTEST_F(NativeAppPipeMgrTest, NativeAppPipeMgrTest_Stop_002, TestSize.Level1) -{ - PipeInfo pipeInfo = { "REMOVE_FAILED_SESSION_NAME" }; - AppPipeMgr *appPipeMgr = new AppPipeMgr(); - auto ret = appPipeMgr->Start(pipeInfo); - EXPECT_EQ(Status::SUCCESS, ret); - ret = appPipeMgr->Stop(pipeInfo); - EXPECT_EQ(Status::ERROR, ret); -} - -/** - * @tc.name: NativeAppPipeMgrTest_SendData_001 - * @tc.desc: test NativeAppPipeMgrTest SendData. input is invalid - * @tc.type: FUNC - */ -HWTEST_F(NativeAppPipeMgrTest, NativeAppPipeMgrTest_SendData_001, TestSize.Level1) -{ - PipeInfo pipeInfo = {}; - DeviceId deviceId = {"devideId01"}; - int size = 1; - uint8_t tmpNum = 1; - uint8_t *ptr = &tmpNum; - MessageInfo messageInfo = {MessageType::DEFAULT}; - AppPipeMgr *appPipeMgr = new AppPipeMgr(); - auto ret = appPipeMgr->SendData(pipeInfo, deviceId, ptr, size, messageInfo); - EXPECT_EQ(Status::ERROR, ret); -} - -/** - * @tc.name: NativeAppPipeMgrTest_SendData_002 - * @tc.desc: test NativeAppPipeMgrTest SendData. pipInfo not found - * @tc.type: FUNC - */ -HWTEST_F(NativeAppPipeMgrTest, NativeAppPipeMgrTest_SendData_002, TestSize.Level1) -{ - PipeInfo pipeInfo = {"pipInfo02"}; - DeviceId deviceId = {"devideId02"}; - int size = 1; - uint8_t tmpNum = 1; - uint8_t *ptr = &tmpNum; - MessageInfo messageInfo = { MessageType::DEFAULT }; - AppPipeMgr *appPipeMgr = new AppPipeMgr(); - auto ret = appPipeMgr->SendData(pipeInfo, deviceId, ptr, size, messageInfo); - EXPECT_EQ(Status::KEY_NOT_FOUND, ret); -} - -/** - * @tc.name: NativeAppPipeMgrTest_IsSameStartedOnPeer_001 - * @tc.desc: test NativeAppPipeMgrTest IsSameStartedOnPeer. pipInfo or deviceId is empty - * @tc.type: FUNC - */ -HWTEST_F(NativeAppPipeMgrTest, NativeAppPipeMgrTest_IsSameStartedOnPeer_001, TestSize.Level1) -{ - PipeInfo pipeInfo = { "pipInfo01" }; - DeviceId deviceId = {}; - AppPipeMgr *appPipeMgr = new AppPipeMgr(); - auto ret = appPipeMgr->IsSameStartedOnPeer(pipeInfo, deviceId); - EXPECT_EQ(false, ret); -} - -/** - * @tc.name: NativeAppPipeMgrTest_IsSameStartedOnPeer_002 - * @tc.desc: test NativeAppPipeMgrTest IsSameStartedOnPeer. pipInfo not found - * @tc.type: FUNC - */ -HWTEST_F(NativeAppPipeMgrTest, NativeAppPipeMgrTest_IsSameStartedOnPeer_002, TestSize.Level1) -{ - PipeInfo pipeInfo = { "pipInfo02" }; - DeviceId deviceId = {"deviceId02"}; - AppPipeMgr *appPipeMgr = new AppPipeMgr(); - auto ret = appPipeMgr->IsSameStartedOnPeer(pipeInfo, deviceId); - EXPECT_EQ(false, ret); -} - -} +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +#include "app_pipe_mgr.h" +#include "app_types.h" +#include "auto_launch_export.h" +#include "ipc_skeleton.h" +#include "objectstore_errors.h" +#include "mock_app_data_change_listener.h" + +namespace { +using namespace testing::ext; +using namespace OHOS::ObjectStore; + +class NativeAppPipeMgrTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void NativeAppPipeMgrTest::SetUpTestCase(void) +{ + // input testsuit setup step,setup invoked before all testcases +} + +void NativeAppPipeMgrTest::TearDownTestCase(void) +{ + // input testsuit teardown step,teardown invoked after all testcases +} + +void NativeAppPipeMgrTest::SetUp(void) +{ + // input testcase setup step,setup invoked before each testcases +} + +void NativeAppPipeMgrTest::TearDown(void) +{ + // input testcase teardown step,teardown invoked after each testcases +} + +/** + * @tc.name: NativeAppPipeMgrTest_StartWatchDataChange_001 + * @tc.desc: test NativeAppPipeMgrTest StartWatchDataChange. argument invalid + * @tc.type: FUNC + */ +HWTEST_F(NativeAppPipeMgrTest, NativeAppPipeMgrTest_StartWatchDataChange_001, TestSize.Level1) +{ + PipeInfo pipeInfo = {""}; + AppDataChangeListener *observer = new MockAppDataChangeListener(); + AppPipeMgr *appPipeMgr = new AppPipeMgr(); + auto ret = appPipeMgr->StartWatchDataChange(observer, pipeInfo); + EXPECT_EQ(Status::INVALID_ARGUMENT, ret); +} + +/** + * @tc.name: NativeAppPipeMgrTest_StartWatchDataChange_002 + * @tc.desc: test NativeAppPipeMgrTest StartWatchDataChange. pipId not found. + * @tc.type: FUNC + */ +HWTEST_F(NativeAppPipeMgrTest, NativeAppPipeMgrTest_StartWatchDataChange_002, TestSize.Level1) +{ + PipeInfo pipeInfo = { "pipId01" }; + AppDataChangeListener *observer = new MockAppDataChangeListener(); + AppPipeMgr *appPipeMgr = new AppPipeMgr(); + auto ret = appPipeMgr->StartWatchDataChange(observer, pipeInfo); + EXPECT_EQ(Status::ERROR, ret); +} + +/** + * @tc.name: NativeAppPipeMgrTest_StopWatchDataChange_001 + * @tc.desc: test NativeAppPipeMgrTest StopWatchDataChange. argument invalid + * @tc.type: FUNC + */ +HWTEST_F(NativeAppPipeMgrTest, NativeAppPipeMgrTest_StopWatchDataChange_001, TestSize.Level1) +{ + PipeInfo pipeInfo = { "pipId01" }; + AppPipeMgr *appPipeMgr = new AppPipeMgr(); + auto ret = appPipeMgr->StopWatchDataChange(nullptr, pipeInfo); + EXPECT_EQ(Status::INVALID_ARGUMENT, ret); +} + +/** + * @tc.name: NativeAppPipeMgrTest_StopWatchDataChange_002 + * @tc.desc: test NativeAppPipeMgrTest StopWatchDataChange. + * @tc.type: FUNC + */ +HWTEST_F(NativeAppPipeMgrTest, NativeAppPipeMgrTest_StopWatchDataChange_002, TestSize.Level1) +{ + PipeInfo pipeInfo = { "pipId01" }; + AppPipeMgr *appPipeMgr = new AppPipeMgr(); + AppDataChangeListener *observer = new MockAppDataChangeListener(); + auto ret = appPipeMgr->StopWatchDataChange(observer, pipeInfo); + EXPECT_EQ(Status::ERROR, ret); +} + +/** + * @tc.name: NativeAppPipeMgrTest_StopWatchDataChange_003 + * @tc.desc: test NativeAppPipeMgrTest StopWatchDataChange. + * @tc.type: FUNC + */ +HWTEST_F(NativeAppPipeMgrTest, NativeAppPipeMgrTest_StopWatchDataChange_003, TestSize.Level1) +{ + PipeInfo pipeInfo = { "pipId01" }; + AppPipeMgr *appPipeMgr = new AppPipeMgr(); + AppDataChangeListener *observer = new MockAppDataChangeListener(); + auto ret = appPipeMgr->StopWatchDataChange(observer, pipeInfo); + EXPECT_EQ(Status::ERROR, ret); +} + +/** + * @tc.name: NativeAppPipeMgrTest_Start_001 + * @tc.desc: test NativeAppPipeMgrTest Start. pipInfo is empty + * @tc.type: FUNC + */ +HWTEST_F(NativeAppPipeMgrTest, NativeAppPipeMgrTest_Start_001, TestSize.Level1) +{ + PipeInfo pipeInfo = {}; + AppPipeMgr *appPipeMgr = new AppPipeMgr(); + auto ret = appPipeMgr->Start(pipeInfo); + EXPECT_EQ(Status::INVALID_ARGUMENT, ret); +} + +/** + * @tc.name: NativeAppPipeMgrTest_Start_002 + * @tc.desc: test NativeAppPipeMgrTest Start. invalid pipInfo + * @tc.type: FUNC + */ +HWTEST_F(NativeAppPipeMgrTest, NativeAppPipeMgrTest_Start_002, TestSize.Level1) +{ + PipeInfo pipeInfo = {"INVALID_SESSION_NAME"}; + AppPipeMgr *appPipeMgr = new AppPipeMgr(); + auto ret = appPipeMgr->Start(pipeInfo); + EXPECT_EQ(Status::ILLEGAL_STATE, ret); +} + +/** + * @tc.name: NativeAppPipeMgrTest_Start_003 + * @tc.desc: test NativeAppPipeMgrTest Start. + * @tc.type: FUNC + */ +HWTEST_F(NativeAppPipeMgrTest, NativeAppPipeMgrTest_Start_003, TestSize.Level1) +{ + PipeInfo pipeInfo = { "pipInfo01" }; + AppPipeMgr *appPipeMgr = new AppPipeMgr(); + auto ret = appPipeMgr->Start(pipeInfo); + EXPECT_EQ(Status::SUCCESS, ret); + ret = appPipeMgr->Stop(pipeInfo); + EXPECT_EQ(Status::SUCCESS, ret); +} + +/** + * @tc.name: NativeAppPipeMgrTest_Start_004 + * @tc.desc: test NativeAppPipeMgrTest Start. repeat start + * @tc.type: FUNC + */ +HWTEST_F(NativeAppPipeMgrTest, NativeAppPipeMgrTest_Start_004, TestSize.Level1) +{ + PipeInfo pipeInfo = { "pipInfo01" }; + AppPipeMgr *appPipeMgr = new AppPipeMgr(); + auto ret = appPipeMgr->Start(pipeInfo); + EXPECT_EQ(Status::SUCCESS, ret); + ret = appPipeMgr->Start(pipeInfo); + EXPECT_EQ(Status::REPEATED_REGISTER, ret); + ret = appPipeMgr->Stop(pipeInfo); + EXPECT_EQ(Status::SUCCESS, ret); +} + +/** + * @tc.name: NativeAppPipeMgrTest_Stop_001 + * @tc.desc: test NativeAppPipeMgrTest Stop. pipInfo not found. + * @tc.type: FUNC + */ +HWTEST_F(NativeAppPipeMgrTest, NativeAppPipeMgrTest_Stop_001, TestSize.Level1) +{ + PipeInfo pipeInfo = { "pipInfo01" }; + AppPipeMgr *appPipeMgr = new AppPipeMgr(); + auto ret = appPipeMgr->Stop(pipeInfo); + EXPECT_EQ(Status::KEY_NOT_FOUND, ret); +} + +/** + * @tc.name: NativeAppPipeMgrTest_Stop_002 + * @tc.desc: test NativeAppPipeMgrTest Stop. RemoveSessionServer failed + * @tc.type: FUNC + */ +HWTEST_F(NativeAppPipeMgrTest, NativeAppPipeMgrTest_Stop_002, TestSize.Level1) +{ + PipeInfo pipeInfo = { "REMOVE_FAILED_SESSION_NAME" }; + AppPipeMgr *appPipeMgr = new AppPipeMgr(); + auto ret = appPipeMgr->Start(pipeInfo); + EXPECT_EQ(Status::SUCCESS, ret); + ret = appPipeMgr->Stop(pipeInfo); + EXPECT_EQ(Status::ERROR, ret); +} + +/** + * @tc.name: NativeAppPipeMgrTest_SendData_001 + * @tc.desc: test NativeAppPipeMgrTest SendData. input is invalid + * @tc.type: FUNC + */ +HWTEST_F(NativeAppPipeMgrTest, NativeAppPipeMgrTest_SendData_001, TestSize.Level1) +{ + PipeInfo pipeInfo = {}; + DeviceId deviceId = {"devideId01"}; + int size = 1; + uint8_t tmpNum = 1; + uint8_t *ptr = &tmpNum; + MessageInfo messageInfo = {MessageType::DEFAULT}; + AppPipeMgr *appPipeMgr = new AppPipeMgr(); + auto ret = appPipeMgr->SendData(pipeInfo, deviceId, ptr, size, messageInfo); + EXPECT_EQ(Status::ERROR, ret); +} + +/** + * @tc.name: NativeAppPipeMgrTest_SendData_002 + * @tc.desc: test NativeAppPipeMgrTest SendData. pipInfo not found + * @tc.type: FUNC + */ +HWTEST_F(NativeAppPipeMgrTest, NativeAppPipeMgrTest_SendData_002, TestSize.Level1) +{ + PipeInfo pipeInfo = {"pipInfo02"}; + DeviceId deviceId = {"devideId02"}; + int size = 1; + uint8_t tmpNum = 1; + uint8_t *ptr = &tmpNum; + MessageInfo messageInfo = { MessageType::DEFAULT }; + AppPipeMgr *appPipeMgr = new AppPipeMgr(); + auto ret = appPipeMgr->SendData(pipeInfo, deviceId, ptr, size, messageInfo); + EXPECT_EQ(Status::KEY_NOT_FOUND, ret); +} + +/** + * @tc.name: NativeAppPipeMgrTest_IsSameStartedOnPeer_001 + * @tc.desc: test NativeAppPipeMgrTest IsSameStartedOnPeer. pipInfo or deviceId is empty + * @tc.type: FUNC + */ +HWTEST_F(NativeAppPipeMgrTest, NativeAppPipeMgrTest_IsSameStartedOnPeer_001, TestSize.Level1) +{ + PipeInfo pipeInfo = { "pipInfo01" }; + DeviceId deviceId = {}; + AppPipeMgr *appPipeMgr = new AppPipeMgr(); + auto ret = appPipeMgr->IsSameStartedOnPeer(pipeInfo, deviceId); + EXPECT_EQ(false, ret); +} + +/** + * @tc.name: NativeAppPipeMgrTest_IsSameStartedOnPeer_002 + * @tc.desc: test NativeAppPipeMgrTest IsSameStartedOnPeer. pipInfo not found + * @tc.type: FUNC + */ +HWTEST_F(NativeAppPipeMgrTest, NativeAppPipeMgrTest_IsSameStartedOnPeer_002, TestSize.Level1) +{ + PipeInfo pipeInfo = { "pipInfo02" }; + DeviceId deviceId = {"deviceId02"}; + AppPipeMgr *appPipeMgr = new AppPipeMgr(); + auto ret = appPipeMgr->IsSameStartedOnPeer(pipeInfo, deviceId); + EXPECT_EQ(false, ret); +} + +} diff --git a/data_object/frameworks/innerkitsimpl/test/unittest/src/communicator_test.cpp b/data_object/frameworks/innerkitsimpl/test/unittest/src/communicator_test.cpp index 8d6d3adb68de6f123ca441e9c8e6024ef9be69fe..9a1d62d8be8b6dae3af70b2c7ac4b55e35645407 100644 --- a/data_object/frameworks/innerkitsimpl/test/unittest/src/communicator_test.cpp +++ b/data_object/frameworks/innerkitsimpl/test/unittest/src/communicator_test.cpp @@ -1,470 +1,470 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include -#include - -#include "auto_launch_export.h" -#include "objectstore_errors.h" -#include "ipc_skeleton.h" -#include "accesstoken_kit.h" -#include "nativetoken_kit.h" -#include "token_setproc.h" -#include "app_types.h" -#include "softbus_adapter.h" -#include "dev_manager.h" -#include "app_device_status_change_listener.h" -#include "app_data_change_listener.h" -#include "mock_app_device_change_listener.h" -#include "mock_app_data_change_listener.h" - -using namespace testing::ext; -using namespace OHOS::Security::AccessToken; -using namespace OHOS::ObjectStore; - -namespace { -constexpr int32_t HEAD_SIZE = 3; -constexpr const char *REPLACE_CHAIN = "***"; -constexpr const char *DEFAULT_ANONYMOUS = "******"; - -class NativeCommunicatorTest : public testing::Test { -public: - static void SetUpTestCase(void); - static void TearDownTestCase(void); - void SetUp(); - void TearDown(); -}; - -void NativeCommunicatorTest::SetUpTestCase(void) -{ - // input testsuit setup step,setup invoked before all testcases -} - -void NativeCommunicatorTest::TearDownTestCase(void) -{ - // input testsuit teardown step,teardown invoked after all testcases -} - -void NativeCommunicatorTest::SetUp(void) -{ - // input testcase setup step,setup invoked before each testcases -} - -void NativeCommunicatorTest::TearDown(void) -{ - // input testcase teardown step,teardown invoked after each testcases -} - -/** - * @tc.name: SoftBusAdapter_StartWatchDeviceChange_001 - * @tc.desc: test SoftBusAdapter NotifyAll. - * @tc.type: FUNC - */ -HWTEST_F(NativeCommunicatorTest, StartWatchDeviceChange_001, TestSize.Level1) -{ - PipeInfo pipeInfo = { "pipInfo001" }; - SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); - MockAppDeviceStatusChangeListener *mockAppDeviceStatusChangeListener = new MockAppDeviceStatusChangeListener(); - auto ret = softBusAdapter->StartWatchDeviceChange(mockAppDeviceStatusChangeListener, pipeInfo); - EXPECT_EQ(Status::SUCCESS, ret); - delete softBusAdapter; - delete mockAppDeviceStatusChangeListener; -} - -/** - * @tc.name: SoftBusAdapter_StartWatchDeviceChange_002 - * @tc.desc: test SoftBusAdapter NotifyAll. input parameter of observer is null - * @tc.type: FUNC - */ -HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_StartWatchDeviceChange_002, TestSize.Level1) -{ - PipeInfo pipeInfo = { "pipInfo002" }; - SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); - MockAppDeviceStatusChangeListener *mockAppDeviceStatusChangeListener = nullptr; - auto ret = softBusAdapter->StartWatchDeviceChange(mockAppDeviceStatusChangeListener, pipeInfo); - EXPECT_EQ(Status::ERROR, ret); - delete softBusAdapter; -} - -/** - * @tc.name: SoftBusAdapter_StartWatchDeviceChange_003 - * @tc.desc: test SoftBusAdapter StartWatchDeviceChange. insert the same observer - * @tc.type: FUNC - */ -HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_StartWatchDeviceChange_003, TestSize.Level1) -{ - PipeInfo pipeInfo = { "pipInfo003" }; - SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); - MockAppDeviceStatusChangeListener *mockAppDeviceStatusChangeListener = new MockAppDeviceStatusChangeListener(); - auto ret = softBusAdapter->StartWatchDeviceChange(mockAppDeviceStatusChangeListener, pipeInfo); - EXPECT_EQ(Status::SUCCESS, ret); - ret = softBusAdapter->StartWatchDeviceChange(mockAppDeviceStatusChangeListener, pipeInfo); - EXPECT_EQ(Status::ERROR, ret); - delete softBusAdapter; - delete mockAppDeviceStatusChangeListener; -} - -/** - * @tc.name: SoftBusAdapter_StopWatchDeviceChange_001 - * @tc.desc: test SoftBusAdapter StopWatchDeviceChange. - * @tc.type: FUNC - */ -HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_StopWatchDeviceChange_001, TestSize.Level1) -{ - PipeInfo pipeInfo = { "pipInfo001" }; - SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); - MockAppDeviceStatusChangeListener *mockAppDeviceStatusChangeListener = new MockAppDeviceStatusChangeListener(); - auto ret = softBusAdapter->StartWatchDeviceChange(mockAppDeviceStatusChangeListener, pipeInfo); - EXPECT_EQ(Status::SUCCESS, ret); - ret = softBusAdapter->StopWatchDeviceChange(mockAppDeviceStatusChangeListener, pipeInfo); - EXPECT_EQ(Status::SUCCESS, ret); - delete softBusAdapter; - delete mockAppDeviceStatusChangeListener; -} - -/** - * @tc.name: SoftBusAdapter_StopWatchDeviceChange_002 - * @tc.desc: test SoftBusAdapter StopWatchDeviceChange. - * @tc.type: FUNC - */ -HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_StopWatchDeviceChange_002, TestSize.Level1) -{ - PipeInfo pipeInfo = { "pipInfo002" }; - SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); - MockAppDeviceStatusChangeListener *mockAppDeviceStatusChangeListener = new MockAppDeviceStatusChangeListener(); - auto ret = softBusAdapter->StartWatchDeviceChange(mockAppDeviceStatusChangeListener, pipeInfo); - EXPECT_EQ(Status::SUCCESS, ret); - ret = softBusAdapter->StopWatchDeviceChange(nullptr, pipeInfo); - EXPECT_EQ(Status::ERROR, ret); - delete softBusAdapter; - delete mockAppDeviceStatusChangeListener; -} - -/** - * @tc.name: SoftBusAdapter_StopWatchDeviceChange_003 - * @tc.desc: test SoftBusAdapter StopWatchDeviceChange. - * @tc.type: FUNC - */ -HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_StopWatchDeviceChange_003, TestSize.Level1) -{ - PipeInfo pipeInfo = { "pipInfo003" }; - SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); - MockAppDeviceStatusChangeListener *mockAppDeviceStatusChangeListener1 = new MockAppDeviceStatusChangeListener(); - MockAppDeviceStatusChangeListener *mockAppDeviceStatusChangeListener2 = new MockAppDeviceStatusChangeListener(); - auto ret = softBusAdapter->StartWatchDeviceChange(mockAppDeviceStatusChangeListener1, pipeInfo); - EXPECT_EQ(Status::SUCCESS, ret); - ret = softBusAdapter->StopWatchDeviceChange(mockAppDeviceStatusChangeListener2, pipeInfo); - EXPECT_EQ(Status::ERROR, ret); - delete softBusAdapter; - delete mockAppDeviceStatusChangeListener1; - delete mockAppDeviceStatusChangeListener2; -} - -/** - * @tc.name: SoftBusAdapter_IsSameStartedOnPeer_001 - * @tc.desc: test SoftBusAdapter NotifyAll. - * @tc.type: FUNC - */ -HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_IsSameStartedOnPeer_001, TestSize.Level1) -{ - PipeInfo pipeInfo = { "pipInfo001" }; - DeviceId deviceId = { "deviceId01" }; - SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); - auto ret = softBusAdapter->IsSameStartedOnPeer(pipeInfo, deviceId); - EXPECT_EQ(false, ret); - delete softBusAdapter; -} - -/** - * @tc.name: SoftBusAdapter_IsSameStartedOnPeer_002 - * @tc.desc: test SoftBusAdapter IsSameStartedOnPeer. - * @tc.type: FUNC - */ -HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_IsSameStartedOnPeer_002, TestSize.Level1) -{ - PipeInfo pipeInfo = { "pipInfo002" }; - DeviceId deviceId = { "deviceId02" }; - SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); - std::string sessionName = "pipInfo002deviceId02"; - softBusAdapter->InsertSession(sessionName); - auto ret = softBusAdapter->IsSameStartedOnPeer(pipeInfo, deviceId); - EXPECT_EQ(true, ret); - softBusAdapter->DeleteSession(sessionName); - delete softBusAdapter; -} - -/** - * @tc.name: SoftBusAdapter_StartWatchDataChange_001 - * @tc.desc: test SoftBusAdapter StartWatchDataChange. - * @tc.type: FUNC - */ -HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_StartWatchDataChange_001, TestSize.Level1) -{ - PipeInfo pipeInfo = { "pipInfo001" }; - SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); - AppDataChangeListener *observer = new MockAppDataChangeListener(); - auto ret = softBusAdapter->StartWatchDataChange(observer, pipeInfo); - EXPECT_EQ(Status::SUCCESS, ret); - delete softBusAdapter; - delete observer; -} - -/** - * @tc.name: SoftBusAdapter_StartWatchDataChange_002 - * @tc.desc: test SoftBusAdapter StartWatchDataChange. insert the same observer - * @tc.type: FUNC - */ -HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_StartWatchDataChange_002, TestSize.Level1) -{ - PipeInfo pipeInfo = { "pipInfo002" }; - SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); - AppDataChangeListener *observer = new MockAppDataChangeListener(); - auto ret = softBusAdapter->StartWatchDataChange(observer, pipeInfo); - ret = softBusAdapter->StartWatchDataChange(observer, pipeInfo); - EXPECT_EQ(Status::ERROR, ret); - delete softBusAdapter; - delete observer; -} - -/** - * @tc.name: SoftBusAdapter_StartWatchDataChange_003 - * @tc.desc: test SoftBusAdapter StartWatchDataChange. observer is nullptr - * @tc.type: FUNC - */ -HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_StartWatchDataChange_003, TestSize.Level1) -{ - PipeInfo pipeInfo = { "pipInfo002" }; - SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); - auto ret = softBusAdapter->StartWatchDataChange(nullptr, pipeInfo); - EXPECT_EQ(Status::INVALID_ARGUMENT, ret); - delete softBusAdapter; -} - -/** - * @tc.name: SoftBusAdapter_StopWatchDataChange_001 - * @tc.desc: test SoftBusAdapter StartWatchDataChange. - * @tc.type: FUNC - */ -HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_StopWatchDataChange_001, TestSize.Level1) -{ - PipeInfo pipeInfo = { "pipInfo001" }; - SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); - AppDataChangeListener *observer = new MockAppDataChangeListener(); - auto ret = softBusAdapter->StartWatchDataChange(observer, pipeInfo); - EXPECT_EQ(Status::SUCCESS, ret); - softBusAdapter->StopWatchDataChange(observer, pipeInfo); - EXPECT_EQ(Status::SUCCESS, ret); - delete softBusAdapter; - delete observer; -} - -/** - * @tc.name: SoftBusAdapter_StopWatchDataChange_002 - * @tc.desc: test SoftBusAdapter StartWatchDataChange. - * @tc.type: FUNC - */ -HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_StopWatchDataChange_002, TestSize.Level1) -{ - PipeInfo pipeInfo = { "pipInfo001" }; - SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); - auto ret = softBusAdapter->StopWatchDataChange(nullptr, pipeInfo); - EXPECT_EQ(Status::ERROR, ret); - delete softBusAdapter; -} - -/** - * @tc.name: SoftBusAdapter_ToBeAnonymous_001 - * @tc.desc: test SoftBusAdapter ToBeAnonymous. - * @tc.type: FUNC - */ -HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_ToBeAnonymous_001, TestSize.Level1) -{ - std::string name = "na"; - SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); - auto ret = softBusAdapter->ToBeAnonymous(name); - EXPECT_EQ(DEFAULT_ANONYMOUS, ret); - delete softBusAdapter; -} - -/** - * @tc.name: SoftBusAdapter_ToBeAnonymous_002 - * @tc.desc: test SoftBusAdapter ToBeAnonymous. - * @tc.type: FUNC - */ -HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_ToBeAnonymous_002, TestSize.Level1) -{ - std::string name = "name"; - SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); - auto ret = softBusAdapter->ToBeAnonymous(name); - EXPECT_EQ(name.substr(0, HEAD_SIZE) + REPLACE_CHAIN, ret); - delete softBusAdapter; -} - -/** - * @tc.name: SoftBusAdapter_GetLocalBasicInfo_001 - * @tc.desc: test SoftBusAdapter GetLocalBasicInfo. - * @tc.type: FUNC - */ -HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_GetLocalBasicInfo_001, TestSize.Level1) -{ - SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); - auto ret = softBusAdapter->GetLocalBasicInfo(); - EXPECT_EQ(true, ret.deviceId.empty()); - EXPECT_EQ(true, ret.deviceName.empty()); - EXPECT_EQ(true, ret.deviceType.empty()); - delete softBusAdapter; -} - -/** - * @tc.name: SoftBusAdapter_GetRemoteNodesBasicInfo_002 - * @tc.desc: test SoftBusAdapter GetRemoteNodesBasicInfo. - * @tc.type: FUNC - */ -HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_GetLocalBasicInfo_002, TestSize.Level1) -{ - SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); - auto ret = softBusAdapter->GetRemoteNodesBasicInfo(); - EXPECT_EQ(true, ret.empty()); - delete softBusAdapter; -} - -/** - * @tc.name: SoftBusAdapter_UpdateRelationship_001 - * @tc.desc: test SoftBusAdapter UpdateRelationship. - * @tc.type: FUNC - */ -HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_UpdateRelationship_001, TestSize.Level1) -{ - std::string networdId01 = "networdId01"; - SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); - softBusAdapter->UpdateRelationship(networdId01, DeviceChangeType::DEVICE_ONLINE); - auto ret = softBusAdapter->ToNodeID(""); - EXPECT_EQ(networdId01, ret); - softBusAdapter->UpdateRelationship(networdId01, DeviceChangeType::DEVICE_OFFLINE); - delete softBusAdapter; -} - -/** - * @tc.name: SoftBusAdapter_UpdateRelationship_002 - * @tc.desc: test SoftBusAdapter UpdateRelationship. - * @tc.type: FUNC - */ -HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_UpdateRelationship_002, TestSize.Level1) -{ - std::string networdId01 = "networdId01"; - std::string networdId02 = "networdId02"; - SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); - softBusAdapter->UpdateRelationship(networdId01, DeviceChangeType::DEVICE_ONLINE); - softBusAdapter->UpdateRelationship(networdId02, DeviceChangeType::DEVICE_ONLINE); - softBusAdapter->UpdateRelationship(networdId02, DeviceChangeType::DEVICE_OFFLINE); - auto ret = softBusAdapter->ToNodeID(""); - EXPECT_EQ(networdId01, ret); - softBusAdapter->UpdateRelationship(networdId01, DeviceChangeType::DEVICE_OFFLINE); - delete softBusAdapter; -} - -/** - * @tc.name: SoftBusAdapter_UpdateRelationship_003 - * @tc.desc: test SoftBusAdapter UpdateRelationship. - * @tc.type: FUNC - */ -HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_UpdateRelationship_003, TestSize.Level1) -{ - std::string networdId01 = "networdId01"; - std::string networdId02 = "networdId02"; - SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); - softBusAdapter->UpdateRelationship(networdId01, DeviceChangeType::DEVICE_ONLINE); - softBusAdapter->UpdateRelationship(networdId01, DeviceChangeType::DEVICE_ONLINE); - auto ret = softBusAdapter->ToNodeID(""); - EXPECT_EQ(networdId01, ret); - softBusAdapter->UpdateRelationship(networdId01, DeviceChangeType::DEVICE_OFFLINE); - delete softBusAdapter; -} - -/** - * @tc.name: SoftBusAdapter_UpdateRelationship_004 - * @tc.desc: test SoftBusAdapter UpdateRelationship. - * @tc.type: FUNC - */ -HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_UpdateRelationship_004, TestSize.Level1) -{ - std::string networdId01 = "networdId01"; - std::string networdId02 = "networdId02"; - SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); - softBusAdapter->UpdateRelationship(networdId01, DeviceChangeType::DEVICE_ONLINE); - softBusAdapter->UpdateRelationship(networdId02, DeviceChangeType::DEVICE_OFFLINE); - auto ret = softBusAdapter->ToNodeID(""); - EXPECT_EQ(networdId01, ret); - softBusAdapter->UpdateRelationship(networdId01, DeviceChangeType::DEVICE_OFFLINE); - delete softBusAdapter; -} - -/** - * @tc.name: SoftBusAdapter_RemoveSessionServerAdapter_001 - * @tc.desc: test SoftBusAdapter RemoveSessionServerAdapter. - * @tc.type: FUNC - */ -HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_RemoveSessionServerAdapter_001, TestSize.Level1) -{ - std::string sessionName = "sessionName01"; - SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); - auto ret = softBusAdapter->RemoveSessionServerAdapter(sessionName); - EXPECT_EQ(SUCCESS, ret); - delete softBusAdapter; -} - -/** - * @tc.name: SoftBusAdapter_GetDeviceList_001 - * @tc.desc: test SoftBusAdapter GetLocalDevice. - * @tc.type: FUNC - */ -HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_GetDeviceList_001, TestSize.Level1) -{ - SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); - auto ret = softBusAdapter->GetDeviceList(); - EXPECT_EQ(true, ret.empty()); - delete softBusAdapter; -} - -/** - * @tc.name: SoftBusAdapter_GetLocalDevice_001 - * @tc.desc: test SoftBusAdapter GetLocalDevice. - * @tc.type: FUNC - */ -HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_GetLocalDevice_001, TestSize.Level1) -{ - SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); - auto ret = softBusAdapter->GetLocalDevice(); - EXPECT_EQ(true, ret.deviceId.empty()); - EXPECT_EQ(true, ret.deviceName.empty()); - EXPECT_EQ(true, ret.deviceType.empty()); - delete softBusAdapter; -} - - -/** - * @tc.name: DevManager_GetUuidByNodeId_001 - * @tc.desc: test DevManager GetUuidByNodeId. - * @tc.type: FUNC - */ -HWTEST_F(NativeCommunicatorTest, DevManager_GetUuidByNodeId_001, TestSize.Level1) -{ - std::string nodeId = "nodeId01"; - auto ret = DevManager::GetInstance()->GetUuidByNodeId(nodeId); - EXPECT_EQ(true, ret.empty()); -} +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include + +#include "auto_launch_export.h" +#include "objectstore_errors.h" +#include "ipc_skeleton.h" +#include "accesstoken_kit.h" +#include "nativetoken_kit.h" +#include "token_setproc.h" +#include "app_types.h" +#include "softbus_adapter.h" +#include "dev_manager.h" +#include "app_device_status_change_listener.h" +#include "app_data_change_listener.h" +#include "mock_app_device_change_listener.h" +#include "mock_app_data_change_listener.h" + +using namespace testing::ext; +using namespace OHOS::Security::AccessToken; +using namespace OHOS::ObjectStore; + +namespace { +constexpr int32_t HEAD_SIZE = 3; +constexpr const char *REPLACE_CHAIN = "***"; +constexpr const char *DEFAULT_ANONYMOUS = "******"; + +class NativeCommunicatorTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void NativeCommunicatorTest::SetUpTestCase(void) +{ + // input testsuit setup step,setup invoked before all testcases +} + +void NativeCommunicatorTest::TearDownTestCase(void) +{ + // input testsuit teardown step,teardown invoked after all testcases +} + +void NativeCommunicatorTest::SetUp(void) +{ + // input testcase setup step,setup invoked before each testcases +} + +void NativeCommunicatorTest::TearDown(void) +{ + // input testcase teardown step,teardown invoked after each testcases +} + +/** + * @tc.name: SoftBusAdapter_StartWatchDeviceChange_001 + * @tc.desc: test SoftBusAdapter NotifyAll. + * @tc.type: FUNC + */ +HWTEST_F(NativeCommunicatorTest, StartWatchDeviceChange_001, TestSize.Level1) +{ + PipeInfo pipeInfo = { "pipInfo001" }; + SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); + MockAppDeviceStatusChangeListener *mockAppDeviceStatusChangeListener = new MockAppDeviceStatusChangeListener(); + auto ret = softBusAdapter->StartWatchDeviceChange(mockAppDeviceStatusChangeListener, pipeInfo); + EXPECT_EQ(Status::SUCCESS, ret); + delete softBusAdapter; + delete mockAppDeviceStatusChangeListener; +} + +/** + * @tc.name: SoftBusAdapter_StartWatchDeviceChange_002 + * @tc.desc: test SoftBusAdapter NotifyAll. input parameter of observer is null + * @tc.type: FUNC + */ +HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_StartWatchDeviceChange_002, TestSize.Level1) +{ + PipeInfo pipeInfo = { "pipInfo002" }; + SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); + MockAppDeviceStatusChangeListener *mockAppDeviceStatusChangeListener = nullptr; + auto ret = softBusAdapter->StartWatchDeviceChange(mockAppDeviceStatusChangeListener, pipeInfo); + EXPECT_EQ(Status::ERROR, ret); + delete softBusAdapter; +} + +/** + * @tc.name: SoftBusAdapter_StartWatchDeviceChange_003 + * @tc.desc: test SoftBusAdapter StartWatchDeviceChange. insert the same observer + * @tc.type: FUNC + */ +HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_StartWatchDeviceChange_003, TestSize.Level1) +{ + PipeInfo pipeInfo = { "pipInfo003" }; + SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); + MockAppDeviceStatusChangeListener *mockAppDeviceStatusChangeListener = new MockAppDeviceStatusChangeListener(); + auto ret = softBusAdapter->StartWatchDeviceChange(mockAppDeviceStatusChangeListener, pipeInfo); + EXPECT_EQ(Status::SUCCESS, ret); + ret = softBusAdapter->StartWatchDeviceChange(mockAppDeviceStatusChangeListener, pipeInfo); + EXPECT_EQ(Status::ERROR, ret); + delete softBusAdapter; + delete mockAppDeviceStatusChangeListener; +} + +/** + * @tc.name: SoftBusAdapter_StopWatchDeviceChange_001 + * @tc.desc: test SoftBusAdapter StopWatchDeviceChange. + * @tc.type: FUNC + */ +HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_StopWatchDeviceChange_001, TestSize.Level1) +{ + PipeInfo pipeInfo = { "pipInfo001" }; + SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); + MockAppDeviceStatusChangeListener *mockAppDeviceStatusChangeListener = new MockAppDeviceStatusChangeListener(); + auto ret = softBusAdapter->StartWatchDeviceChange(mockAppDeviceStatusChangeListener, pipeInfo); + EXPECT_EQ(Status::SUCCESS, ret); + ret = softBusAdapter->StopWatchDeviceChange(mockAppDeviceStatusChangeListener, pipeInfo); + EXPECT_EQ(Status::SUCCESS, ret); + delete softBusAdapter; + delete mockAppDeviceStatusChangeListener; +} + +/** + * @tc.name: SoftBusAdapter_StopWatchDeviceChange_002 + * @tc.desc: test SoftBusAdapter StopWatchDeviceChange. + * @tc.type: FUNC + */ +HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_StopWatchDeviceChange_002, TestSize.Level1) +{ + PipeInfo pipeInfo = { "pipInfo002" }; + SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); + MockAppDeviceStatusChangeListener *mockAppDeviceStatusChangeListener = new MockAppDeviceStatusChangeListener(); + auto ret = softBusAdapter->StartWatchDeviceChange(mockAppDeviceStatusChangeListener, pipeInfo); + EXPECT_EQ(Status::SUCCESS, ret); + ret = softBusAdapter->StopWatchDeviceChange(nullptr, pipeInfo); + EXPECT_EQ(Status::ERROR, ret); + delete softBusAdapter; + delete mockAppDeviceStatusChangeListener; +} + +/** + * @tc.name: SoftBusAdapter_StopWatchDeviceChange_003 + * @tc.desc: test SoftBusAdapter StopWatchDeviceChange. + * @tc.type: FUNC + */ +HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_StopWatchDeviceChange_003, TestSize.Level1) +{ + PipeInfo pipeInfo = { "pipInfo003" }; + SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); + MockAppDeviceStatusChangeListener *mockAppDeviceStatusChangeListener1 = new MockAppDeviceStatusChangeListener(); + MockAppDeviceStatusChangeListener *mockAppDeviceStatusChangeListener2 = new MockAppDeviceStatusChangeListener(); + auto ret = softBusAdapter->StartWatchDeviceChange(mockAppDeviceStatusChangeListener1, pipeInfo); + EXPECT_EQ(Status::SUCCESS, ret); + ret = softBusAdapter->StopWatchDeviceChange(mockAppDeviceStatusChangeListener2, pipeInfo); + EXPECT_EQ(Status::ERROR, ret); + delete softBusAdapter; + delete mockAppDeviceStatusChangeListener1; + delete mockAppDeviceStatusChangeListener2; +} + +/** + * @tc.name: SoftBusAdapter_IsSameStartedOnPeer_001 + * @tc.desc: test SoftBusAdapter NotifyAll. + * @tc.type: FUNC + */ +HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_IsSameStartedOnPeer_001, TestSize.Level1) +{ + PipeInfo pipeInfo = { "pipInfo001" }; + DeviceId deviceId = { "deviceId01" }; + SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); + auto ret = softBusAdapter->IsSameStartedOnPeer(pipeInfo, deviceId); + EXPECT_EQ(false, ret); + delete softBusAdapter; +} + +/** + * @tc.name: SoftBusAdapter_IsSameStartedOnPeer_002 + * @tc.desc: test SoftBusAdapter IsSameStartedOnPeer. + * @tc.type: FUNC + */ +HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_IsSameStartedOnPeer_002, TestSize.Level1) +{ + PipeInfo pipeInfo = { "pipInfo002" }; + DeviceId deviceId = { "deviceId02" }; + SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); + std::string sessionName = "pipInfo002deviceId02"; + softBusAdapter->InsertSession(sessionName); + auto ret = softBusAdapter->IsSameStartedOnPeer(pipeInfo, deviceId); + EXPECT_EQ(true, ret); + softBusAdapter->DeleteSession(sessionName); + delete softBusAdapter; +} + +/** + * @tc.name: SoftBusAdapter_StartWatchDataChange_001 + * @tc.desc: test SoftBusAdapter StartWatchDataChange. + * @tc.type: FUNC + */ +HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_StartWatchDataChange_001, TestSize.Level1) +{ + PipeInfo pipeInfo = { "pipInfo001" }; + SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); + AppDataChangeListener *observer = new MockAppDataChangeListener(); + auto ret = softBusAdapter->StartWatchDataChange(observer, pipeInfo); + EXPECT_EQ(Status::SUCCESS, ret); + delete softBusAdapter; + delete observer; +} + +/** + * @tc.name: SoftBusAdapter_StartWatchDataChange_002 + * @tc.desc: test SoftBusAdapter StartWatchDataChange. insert the same observer + * @tc.type: FUNC + */ +HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_StartWatchDataChange_002, TestSize.Level1) +{ + PipeInfo pipeInfo = { "pipInfo002" }; + SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); + AppDataChangeListener *observer = new MockAppDataChangeListener(); + auto ret = softBusAdapter->StartWatchDataChange(observer, pipeInfo); + ret = softBusAdapter->StartWatchDataChange(observer, pipeInfo); + EXPECT_EQ(Status::ERROR, ret); + delete softBusAdapter; + delete observer; +} + +/** + * @tc.name: SoftBusAdapter_StartWatchDataChange_003 + * @tc.desc: test SoftBusAdapter StartWatchDataChange. observer is nullptr + * @tc.type: FUNC + */ +HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_StartWatchDataChange_003, TestSize.Level1) +{ + PipeInfo pipeInfo = { "pipInfo002" }; + SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); + auto ret = softBusAdapter->StartWatchDataChange(nullptr, pipeInfo); + EXPECT_EQ(Status::INVALID_ARGUMENT, ret); + delete softBusAdapter; +} + +/** + * @tc.name: SoftBusAdapter_StopWatchDataChange_001 + * @tc.desc: test SoftBusAdapter StartWatchDataChange. + * @tc.type: FUNC + */ +HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_StopWatchDataChange_001, TestSize.Level1) +{ + PipeInfo pipeInfo = { "pipInfo001" }; + SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); + AppDataChangeListener *observer = new MockAppDataChangeListener(); + auto ret = softBusAdapter->StartWatchDataChange(observer, pipeInfo); + EXPECT_EQ(Status::SUCCESS, ret); + softBusAdapter->StopWatchDataChange(observer, pipeInfo); + EXPECT_EQ(Status::SUCCESS, ret); + delete softBusAdapter; + delete observer; +} + +/** + * @tc.name: SoftBusAdapter_StopWatchDataChange_002 + * @tc.desc: test SoftBusAdapter StartWatchDataChange. + * @tc.type: FUNC + */ +HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_StopWatchDataChange_002, TestSize.Level1) +{ + PipeInfo pipeInfo = { "pipInfo001" }; + SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); + auto ret = softBusAdapter->StopWatchDataChange(nullptr, pipeInfo); + EXPECT_EQ(Status::ERROR, ret); + delete softBusAdapter; +} + +/** + * @tc.name: SoftBusAdapter_ToBeAnonymous_001 + * @tc.desc: test SoftBusAdapter ToBeAnonymous. + * @tc.type: FUNC + */ +HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_ToBeAnonymous_001, TestSize.Level1) +{ + std::string name = "na"; + SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); + auto ret = softBusAdapter->ToBeAnonymous(name); + EXPECT_EQ(DEFAULT_ANONYMOUS, ret); + delete softBusAdapter; +} + +/** + * @tc.name: SoftBusAdapter_ToBeAnonymous_002 + * @tc.desc: test SoftBusAdapter ToBeAnonymous. + * @tc.type: FUNC + */ +HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_ToBeAnonymous_002, TestSize.Level1) +{ + std::string name = "name"; + SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); + auto ret = softBusAdapter->ToBeAnonymous(name); + EXPECT_EQ(name.substr(0, HEAD_SIZE) + REPLACE_CHAIN, ret); + delete softBusAdapter; +} + +/** + * @tc.name: SoftBusAdapter_GetLocalBasicInfo_001 + * @tc.desc: test SoftBusAdapter GetLocalBasicInfo. + * @tc.type: FUNC + */ +HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_GetLocalBasicInfo_001, TestSize.Level1) +{ + SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); + auto ret = softBusAdapter->GetLocalBasicInfo(); + EXPECT_EQ(true, ret.deviceId.empty()); + EXPECT_EQ(true, ret.deviceName.empty()); + EXPECT_EQ(true, ret.deviceType.empty()); + delete softBusAdapter; +} + +/** + * @tc.name: SoftBusAdapter_GetRemoteNodesBasicInfo_002 + * @tc.desc: test SoftBusAdapter GetRemoteNodesBasicInfo. + * @tc.type: FUNC + */ +HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_GetLocalBasicInfo_002, TestSize.Level1) +{ + SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); + auto ret = softBusAdapter->GetRemoteNodesBasicInfo(); + EXPECT_EQ(true, ret.empty()); + delete softBusAdapter; +} + +/** + * @tc.name: SoftBusAdapter_UpdateRelationship_001 + * @tc.desc: test SoftBusAdapter UpdateRelationship. + * @tc.type: FUNC + */ +HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_UpdateRelationship_001, TestSize.Level1) +{ + std::string networdId01 = "networdId01"; + SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); + softBusAdapter->UpdateRelationship(networdId01, DeviceChangeType::DEVICE_ONLINE); + auto ret = softBusAdapter->ToNodeID(""); + EXPECT_EQ(networdId01, ret); + softBusAdapter->UpdateRelationship(networdId01, DeviceChangeType::DEVICE_OFFLINE); + delete softBusAdapter; +} + +/** + * @tc.name: SoftBusAdapter_UpdateRelationship_002 + * @tc.desc: test SoftBusAdapter UpdateRelationship. + * @tc.type: FUNC + */ +HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_UpdateRelationship_002, TestSize.Level1) +{ + std::string networdId01 = "networdId01"; + std::string networdId02 = "networdId02"; + SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); + softBusAdapter->UpdateRelationship(networdId01, DeviceChangeType::DEVICE_ONLINE); + softBusAdapter->UpdateRelationship(networdId02, DeviceChangeType::DEVICE_ONLINE); + softBusAdapter->UpdateRelationship(networdId02, DeviceChangeType::DEVICE_OFFLINE); + auto ret = softBusAdapter->ToNodeID(""); + EXPECT_EQ(networdId01, ret); + softBusAdapter->UpdateRelationship(networdId01, DeviceChangeType::DEVICE_OFFLINE); + delete softBusAdapter; +} + +/** + * @tc.name: SoftBusAdapter_UpdateRelationship_003 + * @tc.desc: test SoftBusAdapter UpdateRelationship. + * @tc.type: FUNC + */ +HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_UpdateRelationship_003, TestSize.Level1) +{ + std::string networdId01 = "networdId01"; + std::string networdId02 = "networdId02"; + SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); + softBusAdapter->UpdateRelationship(networdId01, DeviceChangeType::DEVICE_ONLINE); + softBusAdapter->UpdateRelationship(networdId01, DeviceChangeType::DEVICE_ONLINE); + auto ret = softBusAdapter->ToNodeID(""); + EXPECT_EQ(networdId01, ret); + softBusAdapter->UpdateRelationship(networdId01, DeviceChangeType::DEVICE_OFFLINE); + delete softBusAdapter; +} + +/** + * @tc.name: SoftBusAdapter_UpdateRelationship_004 + * @tc.desc: test SoftBusAdapter UpdateRelationship. + * @tc.type: FUNC + */ +HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_UpdateRelationship_004, TestSize.Level1) +{ + std::string networdId01 = "networdId01"; + std::string networdId02 = "networdId02"; + SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); + softBusAdapter->UpdateRelationship(networdId01, DeviceChangeType::DEVICE_ONLINE); + softBusAdapter->UpdateRelationship(networdId02, DeviceChangeType::DEVICE_OFFLINE); + auto ret = softBusAdapter->ToNodeID(""); + EXPECT_EQ(networdId01, ret); + softBusAdapter->UpdateRelationship(networdId01, DeviceChangeType::DEVICE_OFFLINE); + delete softBusAdapter; +} + +/** + * @tc.name: SoftBusAdapter_RemoveSessionServerAdapter_001 + * @tc.desc: test SoftBusAdapter RemoveSessionServerAdapter. + * @tc.type: FUNC + */ +HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_RemoveSessionServerAdapter_001, TestSize.Level1) +{ + std::string sessionName = "sessionName01"; + SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); + auto ret = softBusAdapter->RemoveSessionServerAdapter(sessionName); + EXPECT_EQ(SUCCESS, ret); + delete softBusAdapter; +} + +/** + * @tc.name: SoftBusAdapter_GetDeviceList_001 + * @tc.desc: test SoftBusAdapter GetLocalDevice. + * @tc.type: FUNC + */ +HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_GetDeviceList_001, TestSize.Level1) +{ + SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); + auto ret = softBusAdapter->GetDeviceList(); + EXPECT_EQ(true, ret.empty()); + delete softBusAdapter; +} + +/** + * @tc.name: SoftBusAdapter_GetLocalDevice_001 + * @tc.desc: test SoftBusAdapter GetLocalDevice. + * @tc.type: FUNC + */ +HWTEST_F(NativeCommunicatorTest, SoftBusAdapter_GetLocalDevice_001, TestSize.Level1) +{ + SoftBusAdapter *softBusAdapter = new SoftBusAdapter(); + auto ret = softBusAdapter->GetLocalDevice(); + EXPECT_EQ(true, ret.deviceId.empty()); + EXPECT_EQ(true, ret.deviceName.empty()); + EXPECT_EQ(true, ret.deviceType.empty()); + delete softBusAdapter; +} + + +/** + * @tc.name: DevManager_GetUuidByNodeId_001 + * @tc.desc: test DevManager GetUuidByNodeId. + * @tc.type: FUNC + */ +HWTEST_F(NativeCommunicatorTest, DevManager_GetUuidByNodeId_001, TestSize.Level1) +{ + std::string nodeId = "nodeId01"; + auto ret = DevManager::GetInstance()->GetUuidByNodeId(nodeId); + EXPECT_EQ(true, ret.empty()); +} } \ No newline at end of file diff --git a/data_object/frameworks/innerkitsimpl/test/unittest/src/process_communicator_impl_test.cpp b/data_object/frameworks/innerkitsimpl/test/unittest/src/process_communicator_impl_test.cpp index 2a16bf5b60600d08408c8fc1e0a6d24e1021c5cb..dd1c69f4f096daf9adc8ef3aa7080dbf9a1f1130 100644 --- a/data_object/frameworks/innerkitsimpl/test/unittest/src/process_communicator_impl_test.cpp +++ b/data_object/frameworks/innerkitsimpl/test/unittest/src/process_communicator_impl_test.cpp @@ -1,212 +1,212 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "process_communicator_impl.h" - -#include -#include -#include - -#include "app_types.h" -#include "auto_launch_export.h" -#include "ipc_skeleton.h" -#include "objectstore_errors.h" - -namespace { -using namespace testing::ext; -using namespace OHOS::ObjectStore; - -static constexpr uint32_t MTU_SIZE = 4096 * 1024; - -class NativeProcessCommunicatorImplTest : public testing::Test { -public: - static void SetUpTestCase(void); - static void TearDownTestCase(void); - void SetUp(); - void TearDown(); -}; - -void NativeProcessCommunicatorImplTest::SetUpTestCase(void) -{ - // input testsuit setup step,setup invoked before all testcases -} - -void NativeProcessCommunicatorImplTest::TearDownTestCase(void) -{ - // input testsuit teardown step,teardown invoked after all testcases -} - -void NativeProcessCommunicatorImplTest::SetUp(void) -{ - // input testcase setup step,setup invoked before each testcases -} - -void NativeProcessCommunicatorImplTest::TearDown(void) -{ - // input testcase teardown step,teardown invoked after each testcases -} - -/** - * @tc.name: ProcessCommunicatorImpl_Start_Stop_001 - * @tc.desc: test ProcessCommunicatorImpl Start and Stop. - * @tc.type: FUNC - */ -HWTEST_F(NativeProcessCommunicatorImplTest, ProcessCommunicatorImpl_Start_Stop_001, TestSize.Level1) -{ - std::string processLabel = "INVALID_SESSION_NAME"; - ProcessCommunicatorImpl *processCommunicator = new ProcessCommunicatorImpl(); - auto ret = processCommunicator->Start(processLabel); - EXPECT_EQ(DistributedDB::DBStatus::DB_ERROR, ret); - ret = processCommunicator->Stop(); - EXPECT_EQ(DistributedDB::DBStatus::DB_ERROR, ret); - delete processCommunicator; -} - -/** - * @tc.name: ProcessCommunicatorImpl_RegOnDeviceChange_001 - * @tc.desc: test ProcessCommunicatorImpl RegOnDeviceChange. - * @tc.type: FUNC - */ -HWTEST_F(NativeProcessCommunicatorImplTest, ProcessCommunicatorImpl_RegOnDeviceChange_001, TestSize.Level1) -{ - ProcessCommunicatorImpl *processCommunicator = new ProcessCommunicatorImpl(); - auto ret = - processCommunicator->RegOnDeviceChange([](const DistributedDB::DeviceInfos &devInfo, bool isOnline) -> void { - return; - }); - EXPECT_EQ(DistributedDB::DBStatus::OK, ret); - ret = processCommunicator->RegOnDeviceChange(nullptr); - EXPECT_EQ(DistributedDB::DBStatus::OK, ret); - delete processCommunicator; -} - -/** - * @tc.name: ProcessCommunicatorImpl_RegOnDeviceChange_002 - * @tc.desc: test ProcessCommunicatorImpl RegOnDeviceChange. - * @tc.type: FUNC - */ -HWTEST_F(NativeProcessCommunicatorImplTest, ProcessCommunicatorImpl_RegOnDeviceChange_002, TestSize.Level1) -{ - ProcessCommunicatorImpl *processCommunicator = new ProcessCommunicatorImpl(); - auto ret = - processCommunicator->RegOnDeviceChange([](const DistributedDB::DeviceInfos &devInfo, bool isOnline) -> void { - return; - }); - EXPECT_EQ(DistributedDB::DBStatus::OK, ret); - ret = processCommunicator->RegOnDeviceChange([](const DistributedDB::DeviceInfos &devInfo, bool isOnline) -> void { - return; - }); - EXPECT_EQ(DistributedDB::DBStatus::DB_ERROR, ret); - ret = processCommunicator->RegOnDeviceChange(nullptr); - EXPECT_EQ(DistributedDB::DBStatus::OK, ret); - delete processCommunicator; -} - -/** - * @tc.name: ProcessCommunicatorImpl_RegOnDeviceChange_003 - * @tc.desc: test ProcessCommunicatorImpl RegOnDeviceChange. - * @tc.type: FUNC - */ -HWTEST_F(NativeProcessCommunicatorImplTest, ProcessCommunicatorImpl_RegOnDeviceChange_003, TestSize.Level1) -{ - ProcessCommunicatorImpl *processCommunicator = new ProcessCommunicatorImpl(); - auto ret = - processCommunicator->RegOnDeviceChange([](const DistributedDB::DeviceInfos &devInfo, bool isOnline) -> void { - return; - }); - EXPECT_EQ(DistributedDB::DBStatus::OK, ret); - ret = processCommunicator->RegOnDeviceChange(nullptr); - EXPECT_EQ(DistributedDB::DBStatus::OK, ret); - ret = processCommunicator->RegOnDeviceChange(nullptr); - EXPECT_EQ(DistributedDB::DBStatus::DB_ERROR, ret); - delete processCommunicator; -} - -/** - * @tc.name: ProcessCommunicatorImpl_RegOnDataReceive_001 - * @tc.desc: test ProcessCommunicatorImpl RegOnDataReceive. - * @tc.type: FUNC - */ -HWTEST_F(NativeProcessCommunicatorImplTest, ProcessCommunicatorImpl_RegOnDataReceive_001, TestSize.Level1) -{ - ProcessCommunicatorImpl *processCommunicator = new ProcessCommunicatorImpl(); - auto ret = processCommunicator->RegOnDataReceive( - [](const DistributedDB::DeviceInfos &srcDevInfo, const uint8_t *data, uint32_t length) -> void { - return; - }); - EXPECT_EQ(DistributedDB::DBStatus::DB_ERROR, ret); - delete processCommunicator; -} - -/** - * @tc.name: ProcessCommunicatorImpl_RegOnDataReceive_002 - * @tc.desc: test ProcessCommunicatorImpl RegOnDataReceive. - * @tc.type: FUNC - */ -HWTEST_F(NativeProcessCommunicatorImplTest, ProcessCommunicatorImpl_RegOnDataReceive_002, TestSize.Level1) -{ - ProcessCommunicatorImpl *processCommunicator = new ProcessCommunicatorImpl(); - auto ret = processCommunicator->RegOnDataReceive(nullptr); - EXPECT_EQ(DistributedDB::DBStatus::DB_ERROR, ret); - delete processCommunicator; -} - -/** - * @tc.name: ProcessCommunicatorImpl_SendData_001 - * @tc.desc: test ProcessCommunicatorImpl SendData. - * @tc.type: FUNC - */ -HWTEST_F(NativeProcessCommunicatorImplTest, ProcessCommunicatorImpl_SendData_001, TestSize.Level1) -{ - std::string processLabel = "processLabel01"; - DistributedDB::DeviceInfos deviceInfos = { "identifier" }; - uint8_t data = 1; - uint32_t length = 1; - ProcessCommunicatorImpl *processCommunicator = new ProcessCommunicatorImpl(); - auto ret = processCommunicator->SendData(deviceInfos, &data, length); - EXPECT_EQ(DistributedDB::DBStatus::DB_ERROR, ret); - delete processCommunicator; -} - -/** - * @tc.name: ProcessCommunicatorImpl_GetMtuSize_001 - * @tc.desc: test ProcessCommunicatorImpl GetMtuSize. - * @tc.type: FUNC - */ -HWTEST_F(NativeProcessCommunicatorImplTest, ProcessCommunicatorImpl_GetMtuSize_001, TestSize.Level1) -{ - ProcessCommunicatorImpl *processCommunicator = new ProcessCommunicatorImpl(); - DistributedDB::DeviceInfos deviceInfos = { "identifier" }; - auto ret = processCommunicator->GetMtuSize(deviceInfos); - EXPECT_EQ(MTU_SIZE, ret); - ret = processCommunicator->GetMtuSize(); - EXPECT_EQ(MTU_SIZE, ret); - delete processCommunicator; -} - -/** - * @tc.name: ProcessCommunicatorImpl_IsSameProcessLabelStartedOnPeerDevice_001 - * @tc.desc: test ProcessCommunicatorImpl IsSameProcessLabelStartedOnPeerDevice. - * @tc.type: FUNC - */ -HWTEST_F(NativeProcessCommunicatorImplTest, IsSameProcessLabelStartedOnPeerDevice_001, TestSize.Level1) -{ - ProcessCommunicatorImpl *processCommunicator = new ProcessCommunicatorImpl(); - DistributedDB::DeviceInfos deviceInfos = { "identifier" }; - auto ret = processCommunicator->IsSameProcessLabelStartedOnPeerDevice(deviceInfos); - EXPECT_EQ(false, ret); - delete processCommunicator; -} -} +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "process_communicator_impl.h" + +#include +#include +#include + +#include "app_types.h" +#include "auto_launch_export.h" +#include "ipc_skeleton.h" +#include "objectstore_errors.h" + +namespace { +using namespace testing::ext; +using namespace OHOS::ObjectStore; + +static constexpr uint32_t MTU_SIZE = 4096 * 1024; + +class NativeProcessCommunicatorImplTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void NativeProcessCommunicatorImplTest::SetUpTestCase(void) +{ + // input testsuit setup step,setup invoked before all testcases +} + +void NativeProcessCommunicatorImplTest::TearDownTestCase(void) +{ + // input testsuit teardown step,teardown invoked after all testcases +} + +void NativeProcessCommunicatorImplTest::SetUp(void) +{ + // input testcase setup step,setup invoked before each testcases +} + +void NativeProcessCommunicatorImplTest::TearDown(void) +{ + // input testcase teardown step,teardown invoked after each testcases +} + +/** + * @tc.name: ProcessCommunicatorImpl_Start_Stop_001 + * @tc.desc: test ProcessCommunicatorImpl Start and Stop. + * @tc.type: FUNC + */ +HWTEST_F(NativeProcessCommunicatorImplTest, ProcessCommunicatorImpl_Start_Stop_001, TestSize.Level1) +{ + std::string processLabel = "INVALID_SESSION_NAME"; + ProcessCommunicatorImpl *processCommunicator = new ProcessCommunicatorImpl(); + auto ret = processCommunicator->Start(processLabel); + EXPECT_EQ(DistributedDB::DBStatus::DB_ERROR, ret); + ret = processCommunicator->Stop(); + EXPECT_EQ(DistributedDB::DBStatus::DB_ERROR, ret); + delete processCommunicator; +} + +/** + * @tc.name: ProcessCommunicatorImpl_RegOnDeviceChange_001 + * @tc.desc: test ProcessCommunicatorImpl RegOnDeviceChange. + * @tc.type: FUNC + */ +HWTEST_F(NativeProcessCommunicatorImplTest, ProcessCommunicatorImpl_RegOnDeviceChange_001, TestSize.Level1) +{ + ProcessCommunicatorImpl *processCommunicator = new ProcessCommunicatorImpl(); + auto ret = + processCommunicator->RegOnDeviceChange([](const DistributedDB::DeviceInfos &devInfo, bool isOnline) -> void { + return; + }); + EXPECT_EQ(DistributedDB::DBStatus::OK, ret); + ret = processCommunicator->RegOnDeviceChange(nullptr); + EXPECT_EQ(DistributedDB::DBStatus::OK, ret); + delete processCommunicator; +} + +/** + * @tc.name: ProcessCommunicatorImpl_RegOnDeviceChange_002 + * @tc.desc: test ProcessCommunicatorImpl RegOnDeviceChange. + * @tc.type: FUNC + */ +HWTEST_F(NativeProcessCommunicatorImplTest, ProcessCommunicatorImpl_RegOnDeviceChange_002, TestSize.Level1) +{ + ProcessCommunicatorImpl *processCommunicator = new ProcessCommunicatorImpl(); + auto ret = + processCommunicator->RegOnDeviceChange([](const DistributedDB::DeviceInfos &devInfo, bool isOnline) -> void { + return; + }); + EXPECT_EQ(DistributedDB::DBStatus::OK, ret); + ret = processCommunicator->RegOnDeviceChange([](const DistributedDB::DeviceInfos &devInfo, bool isOnline) -> void { + return; + }); + EXPECT_EQ(DistributedDB::DBStatus::DB_ERROR, ret); + ret = processCommunicator->RegOnDeviceChange(nullptr); + EXPECT_EQ(DistributedDB::DBStatus::OK, ret); + delete processCommunicator; +} + +/** + * @tc.name: ProcessCommunicatorImpl_RegOnDeviceChange_003 + * @tc.desc: test ProcessCommunicatorImpl RegOnDeviceChange. + * @tc.type: FUNC + */ +HWTEST_F(NativeProcessCommunicatorImplTest, ProcessCommunicatorImpl_RegOnDeviceChange_003, TestSize.Level1) +{ + ProcessCommunicatorImpl *processCommunicator = new ProcessCommunicatorImpl(); + auto ret = + processCommunicator->RegOnDeviceChange([](const DistributedDB::DeviceInfos &devInfo, bool isOnline) -> void { + return; + }); + EXPECT_EQ(DistributedDB::DBStatus::OK, ret); + ret = processCommunicator->RegOnDeviceChange(nullptr); + EXPECT_EQ(DistributedDB::DBStatus::OK, ret); + ret = processCommunicator->RegOnDeviceChange(nullptr); + EXPECT_EQ(DistributedDB::DBStatus::DB_ERROR, ret); + delete processCommunicator; +} + +/** + * @tc.name: ProcessCommunicatorImpl_RegOnDataReceive_001 + * @tc.desc: test ProcessCommunicatorImpl RegOnDataReceive. + * @tc.type: FUNC + */ +HWTEST_F(NativeProcessCommunicatorImplTest, ProcessCommunicatorImpl_RegOnDataReceive_001, TestSize.Level1) +{ + ProcessCommunicatorImpl *processCommunicator = new ProcessCommunicatorImpl(); + auto ret = processCommunicator->RegOnDataReceive( + [](const DistributedDB::DeviceInfos &srcDevInfo, const uint8_t *data, uint32_t length) -> void { + return; + }); + EXPECT_EQ(DistributedDB::DBStatus::DB_ERROR, ret); + delete processCommunicator; +} + +/** + * @tc.name: ProcessCommunicatorImpl_RegOnDataReceive_002 + * @tc.desc: test ProcessCommunicatorImpl RegOnDataReceive. + * @tc.type: FUNC + */ +HWTEST_F(NativeProcessCommunicatorImplTest, ProcessCommunicatorImpl_RegOnDataReceive_002, TestSize.Level1) +{ + ProcessCommunicatorImpl *processCommunicator = new ProcessCommunicatorImpl(); + auto ret = processCommunicator->RegOnDataReceive(nullptr); + EXPECT_EQ(DistributedDB::DBStatus::DB_ERROR, ret); + delete processCommunicator; +} + +/** + * @tc.name: ProcessCommunicatorImpl_SendData_001 + * @tc.desc: test ProcessCommunicatorImpl SendData. + * @tc.type: FUNC + */ +HWTEST_F(NativeProcessCommunicatorImplTest, ProcessCommunicatorImpl_SendData_001, TestSize.Level1) +{ + std::string processLabel = "processLabel01"; + DistributedDB::DeviceInfos deviceInfos = { "identifier" }; + uint8_t data = 1; + uint32_t length = 1; + ProcessCommunicatorImpl *processCommunicator = new ProcessCommunicatorImpl(); + auto ret = processCommunicator->SendData(deviceInfos, &data, length); + EXPECT_EQ(DistributedDB::DBStatus::DB_ERROR, ret); + delete processCommunicator; +} + +/** + * @tc.name: ProcessCommunicatorImpl_GetMtuSize_001 + * @tc.desc: test ProcessCommunicatorImpl GetMtuSize. + * @tc.type: FUNC + */ +HWTEST_F(NativeProcessCommunicatorImplTest, ProcessCommunicatorImpl_GetMtuSize_001, TestSize.Level1) +{ + ProcessCommunicatorImpl *processCommunicator = new ProcessCommunicatorImpl(); + DistributedDB::DeviceInfos deviceInfos = { "identifier" }; + auto ret = processCommunicator->GetMtuSize(deviceInfos); + EXPECT_EQ(MTU_SIZE, ret); + ret = processCommunicator->GetMtuSize(); + EXPECT_EQ(MTU_SIZE, ret); + delete processCommunicator; +} + +/** + * @tc.name: ProcessCommunicatorImpl_IsSameProcessLabelStartedOnPeerDevice_001 + * @tc.desc: test ProcessCommunicatorImpl IsSameProcessLabelStartedOnPeerDevice. + * @tc.type: FUNC + */ +HWTEST_F(NativeProcessCommunicatorImplTest, IsSameProcessLabelStartedOnPeerDevice_001, TestSize.Level1) +{ + ProcessCommunicatorImpl *processCommunicator = new ProcessCommunicatorImpl(); + DistributedDB::DeviceInfos deviceInfos = { "identifier" }; + auto ret = processCommunicator->IsSameProcessLabelStartedOnPeerDevice(deviceInfos); + EXPECT_EQ(false, ret); + delete processCommunicator; +} +} diff --git a/data_object/interfaces/innerkits/BUILD.gn b/data_object/interfaces/innerkits/BUILD.gn index 0869ce974a377be658c07530428fd5ba8f1821ba..aa391f48758b7302cf57c8ba999ddd42ada0435b 100644 --- a/data_object/interfaces/innerkits/BUILD.gn +++ b/data_object/interfaces/innerkits/BUILD.gn @@ -23,7 +23,6 @@ config("objectstore_config") { "../../frameworks/innerkitsimpl/include/communicator", "../../frameworks/innerkitsimpl/include", "../../interfaces/innerkits", - "//third_party/bounds_checking_function/include", "//foundation/distributeddatamgr/kv_store/frameworks/common", ] diff --git a/data_object/interfaces/jskits/BUILD.gn b/data_object/interfaces/jskits/BUILD.gn index d8d771bfafd3649e7e3eff58de715fd6244885fc..482dd348069fed7f44cc1db1d11ec97212af70cf 100644 --- a/data_object/interfaces/jskits/BUILD.gn +++ b/data_object/interfaces/jskits/BUILD.gn @@ -54,8 +54,6 @@ config("objectstore_config") { "../../frameworks/innerkitsimpl/include/common", "../../frameworks/innerkitsimpl/include/communicator", "../../interfaces/innerkits", - "//third_party/bounds_checking_function/include", - "//foundation/ability/ability_runtime/interfaces/kits/native/appkit/ability_runtime/context", "//foundation/distributeddatamgr/kv_store/frameworks/common", "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/interfaces/include", "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/interfaces/include/relational", @@ -111,6 +109,7 @@ ohos_shared_library("distributeddataobject") { ":distributed_data_object_abc", ":distributed_data_object_js", "//foundation/distributeddatamgr/data_object/interfaces/innerkits:distributeddataobject_impl", + "//third_party/bounds_checking_function:libsec_shared", "//third_party/libuv:uv", ] external_deps = [ diff --git a/data_share/CMakeLists.txt b/data_share/CMakeLists.txt index 7e9a49be069c02a1e961fdb04c9cfa5cc361e82e..2a20e43ce0ac6b8a41a67f1cfaeebb502c188e78 100644 --- a/data_share/CMakeLists.txt +++ b/data_share/CMakeLists.txt @@ -17,6 +17,7 @@ aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/provider/src aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/proxy/src data_share_src) aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/common/src data_share_src) aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/dataShare/src data_share_src) +aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/observer/src data_share_src) #aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/datashare_ext_ability data_share_src) #aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/datashare_ext_ability_context data_share_src) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/common/include) @@ -25,6 +26,7 @@ include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/provider/inclu include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/proxy/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/common/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/dataShare/include) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/observer/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/interfaces/inner_api/common/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/interfaces/inner_api/consumer/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/interfaces/inner_api/provider/include) diff --git a/data_share/frameworks/js/napi/common/include/datashare_js_utils.h b/data_share/frameworks/js/napi/common/include/datashare_js_utils.h index 1118a8ecfc093013f3c15ff19d7499a6d2ae60a5..cf2630d3f7152db9e42403361bff313027591282 100644 --- a/data_share/frameworks/js/napi/common/include/datashare_js_utils.h +++ b/data_share/frameworks/js/napi/common/include/datashare_js_utils.h @@ -22,6 +22,7 @@ #include #include +#include "datashare_template.h" #include "datashare_value_object.h" #include "napi/native_api.h" #include "napi/native_common.h" @@ -35,6 +36,23 @@ do { } \ } while (0) +#define NAPI_ASSERT_CALL_ERRCODE(env, assertion, call, retVal) \ + do { \ + if (!(assertion)) { \ + call; \ + return retVal; \ + } \ + } while (0) + +#define NAPI_ASSERT_CALL_ERRCODE_SYNC(env, assertion, call, error, retVal) \ + do { \ + if (!(assertion)) { \ + call; \ + napi_throw_error((env), std::to_string((error)->GetCode()).c_str(), (error)->GetMessage().c_str()); \ + return retVal; \ + } \ + } while (0) + namespace OHOS { namespace DataShare { class DataShareJSUtils final { @@ -49,6 +67,10 @@ public: static std::string ConvertAny2String(napi_env env, const napi_value jsValue); static std::string UnwrapStringFromJS(napi_env env, napi_value param, const std::string &defaultValue = ""); static DataShareValueObject Convert2ValueObject(napi_env env, napi_value value, bool &status); + static Template Convert2Template(napi_env env, napi_value value); + static TemplateId Convert2TemplateId(napi_env env, napi_value value); + static Data Convert2PublishedData(napi_env env, napi_value value); + static sptr Convert2Ashmem(napi_env env, napi_value value); static napi_value Convert2JSValue(napi_env env, const std::monostate &value = {}); static napi_value Convert2JSValue(napi_env env, const std::vector &value); @@ -58,13 +80,29 @@ public: static napi_value Convert2JSValue(napi_env env, int64_t value); static napi_value Convert2JSValue(napi_env env, double value); static napi_value Convert2JSValue(napi_env env, bool value); - static napi_value Convert2JSValue(napi_env env, const std::map& value); + static napi_value Convert2JSValue(napi_env env, const std::map &value); template - static napi_value Convert2JSValue(napi_env env, const std::variant& value); + static napi_value Convert2JSValue(napi_env env, const std::variant &value); + static napi_value Convert2JSValue(napi_env env, const TemplateId &templateId); + static napi_value Convert2JSValue(napi_env env, const RdbChangeNode &changeNode); + static napi_value Convert2JSValue(napi_env env, sptr &ashmem); + static napi_value Convert2JSValue(napi_env env, PublishedDataItem &publishedDataItem); + static napi_value Convert2JSValue(napi_env env, std::vector &publishedDataItems); + static napi_value Convert2JSValue(napi_env env, PublishedDataChangeNode &changeNode); + static napi_value Convert2JSValue(napi_env env, const OperationResult &results); + static napi_value Convert2JSValue(napi_env env, const std::vector &results); static std::vector ConvertU8Vector(napi_env env, napi_value jsValue); static bool Equals(napi_env env, napi_value value, napi_ref copy); + static bool UnwrapPublishedDataItem(napi_env env, napi_value value, PublishedDataItem &publishedDataItem); + static bool UnwrapPublishedDataItemVector(napi_env env, napi_value value, + std::vector &publishedDataItems); + static bool UnwrapTemplatePredicates(napi_env env, napi_value jsPredicates, + std::vector &predicates); + static bool UnwrapStringByPropertyName(napi_env env, napi_value jsObject, const char *propertyName, + std::string &value); + static bool IsArrayForNapiValue(napi_env env, napi_value param, uint32_t &arraySize); private: template static napi_value ReadVariant(napi_env env, uint32_t step, uint32_t index, const _VTp &output) diff --git a/data_share/frameworks/js/napi/common/include/napi_datashare_values_bucket.h b/data_share/frameworks/js/napi/common/include/napi_datashare_values_bucket.h index bc5a88d0a2f343ee5749f5fac265d1faea40d80c..1c80ed4153acc0d8681d019f452e693c6fdbcf09 100644 --- a/data_share/frameworks/js/napi/common/include/napi_datashare_values_bucket.h +++ b/data_share/frameworks/js/napi/common/include/napi_datashare_values_bucket.h @@ -1,31 +1,31 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef NAPI_DATASHARE_VALUES_BUCKET_H -#define NAPI_DATASHARE_VALUES_BUCKET_H - -#include "napi/native_api.h" -#include "napi/native_common.h" -#include "napi/native_node_api.h" -#include "datashare_values_bucket.h" -#include "datashare_js_utils.h" - -namespace OHOS { -namespace DataShare { -napi_value NewInstance(napi_env env, DataShareValuesBucket &valuesBucket); -bool GetValueBucketObject(DataShareValuesBucket &valuesBucket, const napi_env &env, const napi_value &arg); -} // namespace DataShare -} // namespace OHOS -#endif // NAPI_DATASHARE_VALUES_BUCKET_H +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NAPI_DATASHARE_VALUES_BUCKET_H +#define NAPI_DATASHARE_VALUES_BUCKET_H + +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" +#include "datashare_values_bucket.h" +#include "datashare_js_utils.h" + +namespace OHOS { +namespace DataShare { +napi_value NewInstance(napi_env env, DataShareValuesBucket &valuesBucket); +bool GetValueBucketObject(DataShareValuesBucket &valuesBucket, const napi_env &env, const napi_value &arg); +} // namespace DataShare +} // namespace OHOS +#endif // NAPI_DATASHARE_VALUES_BUCKET_H diff --git a/data_share/frameworks/js/napi/common/src/datashare_js_utils.cpp b/data_share/frameworks/js/napi/common/src/datashare_js_utils.cpp index 651d4ef85ceeca0c5c180a208de8ecd872593bdc..a06422731ed0b6a2ae2ad860781516196d126e01 100644 --- a/data_share/frameworks/js/napi/common/src/datashare_js_utils.cpp +++ b/data_share/frameworks/js/napi/common/src/datashare_js_utils.cpp @@ -14,8 +14,9 @@ */ #include "datashare_js_utils.h" -#include "datashare_log.h" +#include "datashare_log.h" +#include "napi_ashmem.h" #include "securec.h" namespace OHOS { @@ -273,31 +274,25 @@ std::string DataShareJSUtils::UnwrapStringFromJS(napi_env env, napi_value param, return value; } - DataShareValueObject DataShareJSUtils::Convert2ValueObject(napi_env env, napi_value value, bool &status) { napi_valuetype valueType = napi_undefined; napi_typeof(env, value, &valueType); status = true; if (valueType == napi_string) { - LOG_DEBUG("ValueObject is string"); std::string valueString = DataShareJSUtils::UnwrapStringFromJS(env, value); return valueString; } else if (valueType == napi_number) { - LOG_DEBUG("ValueObject is number"); double valueNumber = 0; napi_get_value_double(env, value, &valueNumber); return valueNumber; } else if (valueType == napi_boolean) { - LOG_DEBUG("ValueObject is boolean"); bool valueBool = false; napi_get_value_bool(env, value, &valueBool); return valueBool; } else if (valueType == napi_null) { - LOG_DEBUG("ValueObject is null"); return {}; } else if (valueType == napi_object) { - LOG_DEBUG("ValueObject is Uint8Array"); std::vector valueBlob = DataShareJSUtils::Convert2U8Vector(env, value); return valueBlob; } else { @@ -320,5 +315,417 @@ bool DataShareJSUtils::Equals(napi_env env, napi_value value, napi_ref copy) napi_strict_equals(env, value, copyValue, &isEqual); return isEqual; } + +napi_value DataShareJSUtils::Convert2JSValue(napi_env env, const TemplateId &templateId) +{ + napi_value tplId = nullptr; + napi_create_object(env, &tplId); + napi_value subscriberId = Convert2JSValue(env, std::to_string(templateId.subscriberId_)); + if (subscriberId == nullptr) { + return nullptr; + } + napi_value bundleName = nullptr; + bundleName = Convert2JSValue(env, templateId.bundleName_); + if (bundleName == nullptr) { + return nullptr; + } + napi_set_named_property(env, tplId, "subscriberId", subscriberId); + napi_set_named_property(env, tplId, "bundleName", bundleName); + return tplId; +} + +napi_value DataShareJSUtils::Convert2JSValue(napi_env env, const RdbChangeNode &changeNode) +{ + napi_value jsRdbChangeNode = nullptr; + napi_create_object(env, &jsRdbChangeNode); + + napi_value uri = nullptr; + uri = Convert2JSValue(env, changeNode.uri_); + if (uri == nullptr) { + return nullptr; + } + napi_value templateId = nullptr; + templateId = Convert2JSValue(env, changeNode.templateId_); + if (templateId == nullptr) { + return nullptr; + } + napi_value data = Convert2JSValue(env, changeNode.data_); + if (data == nullptr) { + return nullptr; + } + napi_set_named_property(env, jsRdbChangeNode, "uri", uri); + napi_set_named_property(env, jsRdbChangeNode, "templateId", templateId); + napi_set_named_property(env, jsRdbChangeNode, "data", data); + return jsRdbChangeNode; +} + +napi_value DataShareJSUtils::Convert2JSValue(napi_env env, sptr &ashmem) +{ + napi_value global = nullptr; + napi_status status = napi_get_global(env, &global); + if (status != napi_ok) { + LOG_ERROR("get napi global failed"); + return nullptr; + } + napi_value constructor = nullptr; + status = napi_get_named_property(env, global, "AshmemConstructor_", &constructor); + if (status != napi_ok) { + LOG_ERROR("get Ashmem constructor failed"); + return nullptr; + } + napi_value jsAshmem; + status = napi_new_instance(env, constructor, 0, nullptr, &jsAshmem); + if (status != napi_ok) { + LOG_ERROR("failed to construct js Ashmem"); + return nullptr; + } + + NAPIAshmem *napiAshmem = nullptr; + napi_unwrap(env, jsAshmem, (void **)&napiAshmem); + if (napiAshmem == nullptr) { + LOG_ERROR("napiAshmem is null"); + return nullptr; + } + napiAshmem->SetAshmem(ashmem); + return jsAshmem; +} + +napi_value DataShareJSUtils::Convert2JSValue(napi_env env, PublishedDataItem &publishedDataItem) +{ + napi_value jsPublishedDataItem = nullptr; + napi_create_object(env, &jsPublishedDataItem); + + napi_value key = Convert2JSValue(env, publishedDataItem.key_); + if (key == nullptr) { + return nullptr; + } + + napi_value subscriberId = nullptr; + subscriberId = Convert2JSValue(env, std::to_string(publishedDataItem.subscriberId_)); + if (subscriberId == nullptr) { + return nullptr; + } + + napi_value data = nullptr; + if (publishedDataItem.IsAshmem()) { + sptr ashmem = publishedDataItem.MoveOutAshmem(); + if (ashmem == nullptr) { + LOG_ERROR("MoveOutAshmem null Ashmem"); + return nullptr; + } + data = Convert2JSValue(env, ashmem); + } else { + data = Convert2JSValue(env, std::get(publishedDataItem.GetData())); + } + if (data == nullptr) { + return nullptr; + } + + napi_set_named_property(env, jsPublishedDataItem, "key", key); + napi_set_named_property(env, jsPublishedDataItem, "subscriberId", subscriberId); + napi_set_named_property(env, jsPublishedDataItem, "data", data); + return jsPublishedDataItem; +} + +napi_value DataShareJSUtils::Convert2JSValue(napi_env env, std::vector &publishedDataItems) +{ + napi_value jsValue; + napi_status status = napi_create_array_with_length(env, publishedDataItems.size(), &jsValue); + if (status != napi_ok) { + return nullptr; + } + + for (size_t i = 0; i < publishedDataItems.size(); ++i) { + napi_set_element(env, jsValue, i, Convert2JSValue(env, publishedDataItems[i])); + } + return jsValue; +} + +napi_value DataShareJSUtils::Convert2JSValue(napi_env env, PublishedDataChangeNode &changeNode) +{ + napi_value jsPublishedDataChangeNode = nullptr; + napi_create_object(env, &jsPublishedDataChangeNode); + + napi_value bundleName = nullptr; + bundleName = Convert2JSValue(env, changeNode.ownerBundleName_); + if (bundleName == nullptr) { + return nullptr; + } + napi_value data = nullptr; + data = Convert2JSValue(env, changeNode.datas_); + if (data == nullptr) { + return nullptr; + } + napi_set_named_property(env, jsPublishedDataChangeNode, "bundleName", bundleName); + napi_set_named_property(env, jsPublishedDataChangeNode, "data", data); + return jsPublishedDataChangeNode; +} + +napi_value DataShareJSUtils::Convert2JSValue(napi_env env, const OperationResult &results) +{ + napi_value jsOperationResult = nullptr; + napi_create_object(env, &jsOperationResult); + + napi_value key = nullptr; + key = Convert2JSValue(env, results.key_); + if (key == nullptr) { + return nullptr; + } + + napi_value result = nullptr; + result = Convert2JSValue(env, results.errCode_); + if (result == nullptr) { + return nullptr; + } + napi_set_named_property(env, jsOperationResult, "key", key); + napi_set_named_property(env, jsOperationResult, "result", result); + return jsOperationResult; +} + +napi_value DataShareJSUtils::Convert2JSValue(napi_env env, const std::vector &results) +{ + napi_value jsValue; + napi_status status = napi_create_array_with_length(env, results.size(), &jsValue); + if (status != napi_ok) { + return nullptr; + } + + for (size_t i = 0; i < results.size(); ++i) { + napi_set_element(env, jsValue, i, Convert2JSValue(env, results[i])); + } + return jsValue; +} + +bool DataShareJSUtils::UnwrapTemplatePredicates(napi_env env, napi_value jsPredicates, + std::vector &predicates) +{ + napi_value keys = nullptr; + napi_get_property_names(env, jsPredicates, &keys); + uint32_t arrLen = 0; + napi_status status = napi_get_array_length(env, keys, &arrLen); + if (status != napi_ok) { + LOG_ERROR("UnwrapTemplatePredicates error"); + return false; + } + LOG_DEBUG("TemplatePredicates length : %{public}u", arrLen); + for (size_t i = 0; i < arrLen; ++i) { + napi_value key = nullptr; + status = napi_get_element(env, keys, i, &key); + if (status != napi_ok) { + LOG_ERROR("UnwrapTemplatePredicates err"); + return false; + } + napi_value value = nullptr; + status = napi_get_property(env, jsPredicates, key, &value); + if (status != napi_ok) { + LOG_ERROR("UnwrapTemplatePredicates err"); + return false; + } + std::string keyStr = UnwrapStringFromJS(env, key); + std::string valueStr = UnwrapStringFromJS(env, value); + PredicateTemplateNode node(keyStr, valueStr); + predicates.emplace_back(node); + } + return true; +} + +Template DataShareJSUtils::Convert2Template(napi_env env, napi_value value) +{ + napi_valuetype valueType = napi_undefined; + napi_typeof(env, value, &valueType); + if (valueType != napi_object) { + LOG_ERROR("Convert2Template error, value is not object"); + return {}; + } + napi_value jsPredicates; + auto status = napi_get_named_property(env, value, "predicates", &jsPredicates); + if (status != napi_ok) { + LOG_ERROR("Convert predicates failed"); + return {}; + } + std::vector predicates; + if (!UnwrapTemplatePredicates(env, jsPredicates, predicates)) { + LOG_ERROR("UnwrapTemplateNodeVector failed"); + return {}; + } + + std::string scheduler; + if (!UnwrapStringByPropertyName(env, value, "scheduler", scheduler)) { + LOG_ERROR("Convert scheduler failed"); + return {}; + } + Template tpl(predicates, scheduler); + return tpl; +} + +TemplateId DataShareJSUtils::Convert2TemplateId(napi_env env, napi_value value) +{ + napi_valuetype valueType = napi_undefined; + napi_typeof(env, value, &valueType); + if (valueType != napi_object) { + LOG_ERROR("Convert2TemplateId error, value is not object"); + return {}; + } + + TemplateId templateId; + std::string strSubId; + if (!UnwrapStringByPropertyName(env, value, "subscriberId", strSubId)) { + LOG_ERROR("Convert subscriberId failed"); + return {}; + } + templateId.subscriberId_ = atoll(strSubId.c_str()); + if (!UnwrapStringByPropertyName(env, value, "bundleNameOfOwner", templateId.bundleName_)) { + LOG_ERROR("Convert bundleNameOfOwner failed"); + return {}; + } + return templateId; +} + +bool DataShareJSUtils::UnwrapPublishedDataItem(napi_env env, napi_value jsObject, PublishedDataItem &publishedDataItem) +{ + napi_valuetype valueType = napi_undefined; + napi_typeof(env, jsObject, &valueType); + if (valueType != napi_object) { + LOG_ERROR("UnwrapPublishedDataItem error, value is not object"); + return false; + } + + if (!UnwrapStringByPropertyName(env, jsObject, "key", publishedDataItem.key_)) { + LOG_ERROR("Convert key failed"); + return false; + } + std::string keyStr = "data"; + napi_value jsDataKey = Convert2JSValue(env, keyStr); + napi_value jsDataValue = nullptr; + napi_get_property(env, jsObject, jsDataKey, &jsDataValue); + napi_typeof(env, jsDataValue, &valueType); + if (valueType == napi_object) { + sptr ashmem = Convert2Ashmem(env, jsDataValue); + if (ashmem == nullptr) { + LOG_ERROR("Convert ashmem failed"); + return false; + } + publishedDataItem.SetAshmem(ashmem); + } else if (valueType == napi_string) { + publishedDataItem.Set(Convert2String(env, jsDataValue)); + } else { + LOG_ERROR("Convert dataValue failed, type is %{public}d", valueType); + return false; + } + std::string strSubId; + if (!UnwrapStringByPropertyName(env, jsObject, "subscriberId", strSubId)) { + LOG_ERROR("Convert subscriberId failed"); + return false; + } + publishedDataItem.subscriberId_ = atoll(strSubId.c_str()); + return true; +} + +bool DataShareJSUtils::IsArrayForNapiValue(napi_env env, napi_value param, uint32_t &arraySize) +{ + bool isArray = false; + arraySize = 0; + + if (napi_is_array(env, param, &isArray) != napi_ok || isArray == false) { + return false; + } + + if (napi_get_array_length(env, param, &arraySize) != napi_ok) { + return false; + } + return true; +} + +bool DataShareJSUtils::UnwrapPublishedDataItemVector(napi_env env, napi_value value, + std::vector &publishedDataItems) +{ + uint32_t arraySize = 0; + + if (!IsArrayForNapiValue(env, value, arraySize)) { + LOG_ERROR("IsArrayForNapiValue is false"); + return false; + } + + for (uint32_t i = 0; i < arraySize; i++) { + napi_value jsValue = nullptr; + if (napi_get_element(env, value, i, &jsValue) != napi_ok) { + LOG_ERROR("napi_get_element is false"); + return false; + } + + PublishedDataItem publishedDataItem; + if (!UnwrapPublishedDataItem(env, jsValue, publishedDataItem)) { + LOG_ERROR("UnwrapPublishedDataItem failed"); + return false; + } + publishedDataItems.emplace_back(std::move(publishedDataItem)); + } + return true; +} + +Data DataShareJSUtils::Convert2PublishedData(napi_env env, napi_value value) +{ + napi_valuetype valueType = napi_undefined; + napi_typeof(env, value, &valueType); + if (valueType != napi_object) { + LOG_ERROR("Convert2PublishedData error, value is not object"); + return {}; + } + Data data; + if (!UnwrapPublishedDataItemVector(env, value, data.datas_)) { + LOG_ERROR("UnwrapPublishedDataItems failed"); + return {}; + } + return data; +} + +sptr DataShareJSUtils::Convert2Ashmem(napi_env env, napi_value value) +{ + napi_value global = nullptr; + napi_get_global(env, &global); + napi_value constructor = nullptr; + napi_status status = napi_get_named_property(env, global, "AshmemConstructor_", &constructor); + if (status != napi_ok) { + LOG_ERROR("get Ashmem constructor failed"); + return nullptr; + } + bool isAshmem = false; + napi_instanceof(env, value, constructor, &isAshmem); + if (!isAshmem) { + LOG_ERROR("parameter is not instanceof Ashmem"); + return nullptr; + } + NAPIAshmem *napiAshmem = nullptr; + napi_unwrap(env, value, (void **)&napiAshmem); + if (napiAshmem == nullptr) { + LOG_ERROR("napiAshmem is null"); + return nullptr; + } + sptr nativeAshmem = napiAshmem->GetAshmem(); + return nativeAshmem; +} + +bool DataShareJSUtils::UnwrapStringByPropertyName( + napi_env env, napi_value jsObject, const char *propertyName, std::string &value) +{ + napi_value jsResult = nullptr; + auto status = napi_get_named_property(env, jsObject, propertyName, &jsResult); + if (status != napi_ok) { + LOG_ERROR("Convert bundleNameOfOwner failed"); + return false; + } + if (jsResult == nullptr) { + LOG_ERROR("Convert bundleNameOfOwner failed"); + return false; + } + napi_valuetype valueType = napi_undefined; + napi_typeof(env, jsResult, &valueType); + if (valueType != napi_string) { + LOG_ERROR("Convert2PublishedData error, value is not object"); + return false; + } + value = DataShareJSUtils::Convert2String(env, jsResult); + return true; +} } // namespace DataShare } // namespace OHOS \ No newline at end of file diff --git a/data_share/frameworks/js/napi/common/src/datashare_result_set_proxy.cpp b/data_share/frameworks/js/napi/common/src/datashare_result_set_proxy.cpp index cab484adb07531defe7ec68dcc9e6c7e33412a66..a5a94e5636c1db6b9e5c0ed8a5f71a1404457aab 100644 --- a/data_share/frameworks/js/napi/common/src/datashare_result_set_proxy.cpp +++ b/data_share/frameworks/js/napi/common/src/datashare_result_set_proxy.cpp @@ -128,7 +128,7 @@ napi_value DataShareResultSetProxy::Initialize(napi_env env, napi_callback_info DataShareResultSetProxy::~DataShareResultSetProxy() { - LOG_INFO("DataShareResultSetProxy destructor!"); + LOG_DEBUG("DataShareResultSetProxy destructor!"); if (resultSet_ != nullptr && !resultSet_->IsClosed()) { resultSet_->Close(); } diff --git a/data_share/frameworks/js/napi/common/src/napi_datashare_values_bucket.cpp b/data_share/frameworks/js/napi/common/src/napi_datashare_values_bucket.cpp index 426c1765b19792ce5e9c3aea18abd88f411a0471..b2fa731b4aba45e1c991d26b43fb889a37b711bb 100644 --- a/data_share/frameworks/js/napi/common/src/napi_datashare_values_bucket.cpp +++ b/data_share/frameworks/js/napi/common/src/napi_datashare_values_bucket.cpp @@ -1,82 +1,81 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "napi_datashare_values_bucket.h" - -#include "datashare_log.h" -#include "datashare_js_utils.h" -#include "datashare_value_object.h" - -#include "securec.h" - -namespace OHOS { -namespace DataShare { -napi_value NewInstance(napi_env env, DataShareValuesBucket &valuesBucket) -{ - napi_value ret; - NAPI_CALL(env, napi_create_object(env, &ret)); - const auto &valuesMap = valuesBucket.valuesMap; - for (auto it = valuesMap.begin(); it != valuesMap.end(); ++it) { - std::string key = it->first; - auto valueObject = it->second; - napi_value value = DataShareJSUtils::Convert2JSValue(env, valueObject); - if (value == nullptr) { - continue; - } - NAPI_CALL(env, napi_set_named_property(env, ret, key.c_str(), value)); - } - - return ret; -} - -bool UnWrapValuesBucket(DataShareValuesBucket &valuesBucket, const napi_env &env, const napi_value &arg) -{ - napi_value keys = 0; - napi_get_property_names(env, arg, &keys); - uint32_t arrLen = 0; - napi_status status = napi_get_array_length(env, keys, &arrLen); - if (status != napi_ok) { - LOG_ERROR("ValuesBucket err"); - return false; - } - LOG_DEBUG("ValuesBucket num : %{public}u", arrLen); - for (size_t i = 0; i < arrLen; ++i) { - napi_value key = 0; - status = napi_get_element(env, keys, i, &key); - if (status != napi_ok) { - LOG_ERROR("ValuesBucket err"); - return false; - } - std::string keyStr = DataShareJSUtils::UnwrapStringFromJS(env, key); - napi_value value = 0; - napi_get_property(env, arg, key, &value); - - bool ret; - DataShareValueObject valueObject = DataShareJSUtils::Convert2ValueObject(env, value, ret); - if (!ret) { - LOG_ERROR("ValuesBucket err"); - return false; - } - valuesBucket.Put(keyStr, valueObject); - } - return true; -} - -bool GetValueBucketObject(DataShareValuesBucket &valuesBucket, const napi_env &env, const napi_value &arg) -{ - return UnWrapValuesBucket(valuesBucket, env, arg); -} -} // namespace DataShare +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "napi_datashare_values_bucket.h" + +#include "datashare_log.h" +#include "datashare_js_utils.h" +#include "datashare_value_object.h" + +#include "securec.h" + +namespace OHOS { +namespace DataShare { +napi_value NewInstance(napi_env env, DataShareValuesBucket &valuesBucket) +{ + napi_value ret; + NAPI_CALL(env, napi_create_object(env, &ret)); + const auto &valuesMap = valuesBucket.valuesMap; + for (auto it = valuesMap.begin(); it != valuesMap.end(); ++it) { + std::string key = it->first; + auto valueObject = it->second; + napi_value value = DataShareJSUtils::Convert2JSValue(env, valueObject); + if (value == nullptr) { + continue; + } + NAPI_CALL(env, napi_set_named_property(env, ret, key.c_str(), value)); + } + + return ret; +} + +bool UnWrapValuesBucket(DataShareValuesBucket &valuesBucket, const napi_env &env, const napi_value &arg) +{ + napi_value keys = 0; + napi_get_property_names(env, arg, &keys); + uint32_t arrLen = 0; + napi_status status = napi_get_array_length(env, keys, &arrLen); + if (status != napi_ok) { + LOG_ERROR("ValuesBucket err"); + return false; + } + for (size_t i = 0; i < arrLen; ++i) { + napi_value key = 0; + status = napi_get_element(env, keys, i, &key); + if (status != napi_ok) { + LOG_ERROR("ValuesBucket err"); + return false; + } + std::string keyStr = DataShareJSUtils::UnwrapStringFromJS(env, key); + napi_value value = 0; + napi_get_property(env, arg, key, &value); + + bool ret; + DataShareValueObject valueObject = DataShareJSUtils::Convert2ValueObject(env, value, ret); + if (!ret) { + LOG_ERROR("ValuesBucket err"); + return false; + } + valuesBucket.Put(keyStr, valueObject); + } + return true; +} + +bool GetValueBucketObject(DataShareValuesBucket &valuesBucket, const napi_env &env, const napi_value &arg) +{ + return UnWrapValuesBucket(valuesBucket, env, arg); +} +} // namespace DataShare } // namespace OHOS \ No newline at end of file diff --git a/data_share/frameworks/js/napi/dataShare/BUILD.gn b/data_share/frameworks/js/napi/dataShare/BUILD.gn index 63ac72ccb749ff6457b9afc9c2def2b659ce6a07..f7e68b1d22e71d0146a341916c178607ce51e72e 100644 --- a/data_share/frameworks/js/napi/dataShare/BUILD.gn +++ b/data_share/frameworks/js/napi/dataShare/BUILD.gn @@ -19,6 +19,7 @@ ohos_shared_library("datashare") { "${datashare_napi_path}/dataShare/include", "${datashare_common_napi_path}/include", "${datashare_common_native_path}/include", + "${datashare_napi_path}/observer/include", ] sources = [ @@ -27,6 +28,8 @@ ohos_shared_library("datashare") { "${datashare_napi_path}/dataShare/src/napi_datashare_inner_observer.cpp", "${datashare_napi_path}/dataShare/src/napi_datashare_observer.cpp", "${datashare_napi_path}/dataShare/src/native_datashare_module.cpp", + "${datashare_napi_path}/observer/src/napi_observer.cpp", + "${datashare_napi_path}/observer/src/napi_subscriber_manager.cpp", ] deps = [ diff --git a/data_share/frameworks/js/napi/dataShare/include/data_share_common.h b/data_share/frameworks/js/napi/dataShare/include/data_share_common.h index 8fa9c22ab33603b650be758233caba3a6058b0f9..07474f80d8cba945333755efec3545fd2e773e09 100644 --- a/data_share/frameworks/js/napi/dataShare/include/data_share_common.h +++ b/data_share/frameworks/js/napi/dataShare/include/data_share_common.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -19,7 +19,7 @@ #include "napi/native_api.h" #include "napi/native_common.h" #include "napi/native_node_api.h" -#include "napi_common.h" +#include "napi_common_data.h" #include "datashare_helper.h" using Ability = OHOS::AppExecFwk::Ability; diff --git a/data_share/frameworks/js/napi/dataShare/include/napi_datashare_helper.h b/data_share/frameworks/js/napi/dataShare/include/napi_datashare_helper.h index f7368ec5052be2d7baac78fcf5ca6b35f432e495..21e06ba9a44b0d5857819325e412e3a39320bc62 100644 --- a/data_share/frameworks/js/napi/dataShare/include/napi_datashare_helper.h +++ b/data_share/frameworks/js/napi/dataShare/include/napi_datashare_helper.h @@ -17,9 +17,11 @@ #define NAPI_DATASHARE_HELPER_H #include + +#include "napi_subscriber_manager.h" #include "async_call.h" -#include "datashare_helper.h" #include "data_share_common.h" +#include "datashare_helper.h" #include "napi_datashare_observer.h" namespace OHOS { @@ -40,24 +42,36 @@ public: static napi_value Napi_NormalizeUri(napi_env env, napi_callback_info info); static napi_value Napi_DenormalizeUri(napi_env env, napi_callback_info info); static napi_value Napi_NotifyChange(napi_env env, napi_callback_info info); + static napi_value Napi_AddTemplate(napi_env env, napi_callback_info info); + static napi_value Napi_DelTemplate(napi_env env, napi_callback_info info); + static napi_value Napi_Publish(napi_env env, napi_callback_info info); + static napi_value Napi_GetPublishedData(napi_env env, napi_callback_info info); + private: static napi_value GetConstructor(napi_env env); static napi_value Initialize(napi_env env, napi_callback_info info); + static napi_value Napi_SubscribeRdbObserver(napi_env env, size_t argc, napi_value *argv, napi_value self); + static napi_value Napi_UnsubscribeRdbObserver(napi_env env, size_t argc, napi_value *argv, napi_value self); + static napi_value Napi_SubscribePublishedObserver(napi_env env, size_t argc, napi_value *argv, napi_value self); + static napi_value Napi_UnsubscribePublishedObserver(napi_env env, size_t argc, napi_value *argv, napi_value self); bool HasRegisteredObserver(napi_env env, std::list> &list, napi_value callback); void RegisteredObserver(napi_env env, const std::string &uri, napi_value callback); void UnRegisteredObserver(napi_env env, const std::string &uri, napi_value callback); void UnRegisteredObserver(napi_env env, const std::string &uri); - + static bool GetOptions(napi_env env, napi_value jsValue, CreateOptions &options); std::shared_ptr datashareHelper_ = nullptr; std::map>> observerMap_; - std::mutex listMutex_ {}; + std::mutex listMutex_{}; + std::shared_ptr jsRdbObsManager_ = nullptr; + std::shared_ptr jsPublishedObsManager_ = nullptr; struct CreateContextInfo : public AsyncCall::Context { napi_env env = nullptr; napi_ref ref = nullptr; bool isStageMode = true; - std::string strUri = ""; + CreateOptions options; + std::string strUri; std::shared_ptr contextF = nullptr; std::shared_ptr contextS = nullptr; std::shared_ptr dataShareHelper = nullptr; @@ -86,6 +100,9 @@ private: std::vector values; std::string mimeTypeFilter; DatashareBusinessError businessError; + Data publishData; + std::string bundleName; + std::vector results; ContextInfo() : Context(nullptr, nullptr) {}; ContextInfo(InputAction input, OutputAction output) : Context(std::move(input), std::move(output)) {}; @@ -107,6 +124,6 @@ private: } }; }; -} // namespace DataShare -} // namespace OHOS +} // namespace DataShare +} // namespace OHOS #endif /* NAPI_DATASHARE_HELPER_H */ diff --git a/data_share/frameworks/js/napi/dataShare/include/napi_datashare_inner_observer.h b/data_share/frameworks/js/napi/dataShare/include/napi_datashare_inner_observer.h index f38e63c06a35e3f68a1a7e80e683823c48ed17b7..efe95abe0024c3c9afdab16745d0a0e66be4cbde 100644 --- a/data_share/frameworks/js/napi/dataShare/include/napi_datashare_inner_observer.h +++ b/data_share/frameworks/js/napi/dataShare/include/napi_datashare_inner_observer.h @@ -1,47 +1,47 @@ -/* - * Copyright (c) 2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef NAPI_DATASHARE_INNER_OBSERVER_H -#define NAPI_DATASHARE_INNER_OBSERVER_H - -#include - -#include "napi/native_common.h" -#include "napi/native_api.h" -#include "napi/native_node_api.h" - -namespace OHOS { -namespace DataShare { -class NAPIInnerObserver : public std::enable_shared_from_this { -public: - NAPIInnerObserver(napi_env env, napi_value callback); - void OnChange(); - void DeleteReference(); - napi_ref GetCallback(); -private: - static void OnComplete(uv_work_t *work, int status); - struct ObserverWorker { - std::weak_ptr observer_; - ObserverWorker(std::shared_ptr observerIn) - : observer_(observerIn) {} - }; - - napi_env env_ = nullptr; - napi_ref ref_ = nullptr; - uv_loop_s *loop_ = nullptr; -}; -} // namespace DataShare -} // namespace OHOS +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NAPI_DATASHARE_INNER_OBSERVER_H +#define NAPI_DATASHARE_INNER_OBSERVER_H + +#include + +#include "napi/native_common.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" + +namespace OHOS { +namespace DataShare { +class NAPIInnerObserver : public std::enable_shared_from_this { +public: + NAPIInnerObserver(napi_env env, napi_value callback); + void OnChange(); + void DeleteReference(); + napi_ref GetCallback(); +private: + static void OnComplete(uv_work_t *work, int status); + struct ObserverWorker { + std::weak_ptr observer_; + ObserverWorker(std::shared_ptr observerIn) + : observer_(observerIn) {} + }; + + napi_env env_ = nullptr; + napi_ref ref_ = nullptr; + uv_loop_s *loop_ = nullptr; +}; +} // namespace DataShare +} // namespace OHOS #endif //NAPI_DATASHARE_INNER_OBSERVER_H \ No newline at end of file diff --git a/data_share/frameworks/js/napi/dataShare/src/async_call.cpp b/data_share/frameworks/js/napi/dataShare/src/async_call.cpp index 7ce19f082616e14c0db3026c29f064f32d3e9784..471c686a431b033600eafbd455719607cc70a875 100644 --- a/data_share/frameworks/js/napi/dataShare/src/async_call.cpp +++ b/data_share/frameworks/js/napi/dataShare/src/async_call.cpp @@ -64,7 +64,7 @@ napi_value AsyncCall::Call(napi_env env, Context::ExecAction exec) } napi_async_work work = context_->work; napi_value resource = nullptr; - napi_create_string_utf8(env, "AsyncCall", NAPI_AUTO_LENGTH, &resource); + napi_create_string_utf8(env, "DataShareAsyncCall", NAPI_AUTO_LENGTH, &resource); napi_create_async_work(env, nullptr, resource, AsyncCall::OnExecute, AsyncCall::OnComplete, context_, &work); context_->work = work; context_ = nullptr; diff --git a/data_share/frameworks/js/napi/dataShare/src/napi_datashare_helper.cpp b/data_share/frameworks/js/napi/dataShare/src/napi_datashare_helper.cpp index 59b76a7e73f392a93d267957f4db674f90dd259f..bd335a96d64b74b2901711fc6fa6e043cab087f7 100644 --- a/data_share/frameworks/js/napi/dataShare/src/napi_datashare_helper.cpp +++ b/data_share/frameworks/js/napi/dataShare/src/napi_datashare_helper.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -15,13 +15,14 @@ #include "napi_datashare_helper.h" -#include "napi_common_util.h" +#include "data_proxy_observer_stub.h" #include "datashare_helper.h" #include "datashare_log.h" -#include "napi_base_context.h" -#include "napi_datashare_values_bucket.h" #include "datashare_predicates_proxy.h" #include "datashare_result_set_proxy.h" +#include "napi_base_context.h" +#include "napi_common_util.h" +#include "napi_datashare_values_bucket.h" using namespace OHOS::AAFwk; using namespace OHOS::AppExecFwk; @@ -29,7 +30,6 @@ using namespace OHOS::AppExecFwk; namespace OHOS { namespace DataShare { static constexpr int MAX_ARGC = 6; - static DataSharePredicates UnwrapDataSharePredicates(napi_env env, napi_value value) { auto predicates = DataSharePredicatesProxy::GetNativePredicates(env, value); @@ -40,8 +40,7 @@ static DataSharePredicates UnwrapDataSharePredicates(napi_env env, napi_value va return DataSharePredicates(predicates->GetOperationList()); } -static bool UnwrapValuesBucketArrayFromJS(napi_env env, napi_value param, - std::vector &value) +static bool UnwrapValuesBucketArrayFromJS(napi_env env, napi_value param, std::vector &value) { uint32_t arraySize = 0; napi_value jsValue = nullptr; @@ -88,72 +87,81 @@ static bool GetUri(napi_env env, napi_value jsValue, std::string &uri) return true; } +bool NapiDataShareHelper::GetOptions(napi_env env, napi_value jsValue, CreateOptions &options) +{ + napi_valuetype type = napi_undefined; + napi_typeof(env, jsValue, &type); + if (type != napi_object) { + LOG_ERROR("CreateOptions is not object"); + return false; + } + napi_value isProxyJs = nullptr; + napi_status status = napi_get_named_property(env, jsValue, "isProxy", &isProxyJs); + if (status != napi_ok) { + LOG_ERROR("napi_get_named_property failed %{public}d", status); + return false; + } + napi_typeof(env, isProxyJs, &type); + if (type != napi_boolean) { + LOG_ERROR("CreateOptions.isProxy is not bool"); + return false; + } + status = napi_get_value_bool(env, isProxyJs, &options.isProxy_); + if (status != napi_ok) { + LOG_ERROR("napi_get_value_bool failed %{public}d", status); + return false; + } + options.enabled_ = true; + return true; +} + napi_value NapiDataShareHelper::Napi_CreateDataShareHelper(napi_env env, napi_callback_info info) { auto ctxInfo = std::make_shared(); auto input = [ctxInfo](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status { - if (argc != 2 && argc != 3) { - ctxInfo->error = std::make_shared("2 or 3"); - return napi_invalid_arg; + NAPI_ASSERT_CALL_ERRCODE(env, argc == 2 || argc == 3 || argc == 4, + ctxInfo->error = std::make_shared("2 or 3 or 4"), napi_invalid_arg); + ctxInfo->contextS = OHOS::AbilityRuntime::GetStageModeContext(env, argv[0]); + NAPI_ASSERT_CALL_ERRCODE(env, ctxInfo->contextS != nullptr, + ctxInfo->error = std::make_shared("contextS", "not nullptr"), napi_invalid_arg); + NAPI_ASSERT_CALL_ERRCODE(env, GetUri(env, argv[1], ctxInfo->strUri), + ctxInfo->error = std::make_shared("uri", "string"), napi_invalid_arg); + Uri uri(ctxInfo->strUri); + if (uri.GetScheme() == "datashareproxy") { + NAPI_ASSERT_CALL_ERRCODE(env, argc == 3 || argc == 4, + ctxInfo->error = std::make_shared("3 or 4"), napi_invalid_arg); + NAPI_ASSERT_CALL_ERRCODE(env, GetOptions(env, argv[2], ctxInfo->options), + ctxInfo->error = std::make_shared("option", "CreateOption"), napi_invalid_arg); } - bool isStageMode = false; - napi_status status = AbilityRuntime::IsStageContext(env, argv[0], isStageMode); - if (status != napi_ok || !isStageMode) { - ctxInfo->isStageMode = false; - auto ability = OHOS::AbilityRuntime::GetCurrentAbility(env); - if (!GetUri(env, argv[0], ctxInfo->strUri)) { - ctxInfo->error = std::make_shared("uri", "string"); - return napi_invalid_arg; - } - - if (ability == nullptr) { - ctxInfo->error = std::make_shared("ability", "not nullptr"); - return napi_invalid_arg; - } - ctxInfo->contextF = ability->GetContext(); - } else { - ctxInfo->contextS = OHOS::AbilityRuntime::GetStageModeContext(env, argv[0]); - if (!GetUri(env, argv[1], ctxInfo->strUri)) { - ctxInfo->error = std::make_shared("uri", "string"); - return napi_invalid_arg; - } - - if (ctxInfo->contextS == nullptr) { - ctxInfo->error = std::make_shared("contextS", "not nullptr"); - return napi_invalid_arg; - } - } - napi_value helperProxy = nullptr; - status = napi_new_instance(env, GetConstructor(env), argc, argv, &helperProxy); - if ((helperProxy == nullptr) || (status != napi_ok)) { - ctxInfo->error = std::make_shared(); - return napi_generic_failure; - } + napi_status status = napi_new_instance(env, GetConstructor(env), argc, argv, &helperProxy); + NAPI_ASSERT_CALL_ERRCODE(env, helperProxy != nullptr && status == napi_ok, + ctxInfo->error = std::make_shared(), napi_generic_failure); napi_create_reference(env, helperProxy, 1, &(ctxInfo->ref)); ctxInfo->env = env; return napi_ok; }; auto output = [ctxInfo](napi_env env, napi_value *result) -> napi_status { - if (ctxInfo->dataShareHelper == nullptr) { - ctxInfo->error = std::make_shared(); - return napi_generic_failure; - } + NAPI_ASSERT_CALL_ERRCODE(env, ctxInfo->dataShareHelper != nullptr, + ctxInfo->error = std::make_shared(), napi_generic_failure); napi_status status = napi_get_reference_value(env, ctxInfo->ref, result); + NAPI_ASSERT_CALL_ERRCODE(env, result != nullptr, + ctxInfo->error = std::make_shared(), napi_generic_failure); NapiDataShareHelper *proxy = nullptr; status = napi_unwrap(env, *result, reinterpret_cast(&proxy)); - if (proxy == nullptr) { - LOG_ERROR("proxy is nullptr"); - return status; - } + NAPI_ASSERT_CALL_ERRCODE(env, proxy != nullptr, ctxInfo->error = std::make_shared(), + status); + proxy->jsRdbObsManager_ = std::make_shared(ctxInfo->dataShareHelper); + proxy->jsPublishedObsManager_ = std::make_shared(ctxInfo->dataShareHelper); proxy->datashareHelper_ = std::move(ctxInfo->dataShareHelper); return status; }; auto exec = [ctxInfo](AsyncCall::Context *ctx) { - if (ctxInfo->isStageMode && ctxInfo->contextS != nullptr) { + if (ctxInfo->options.enabled_) { + ctxInfo->options.token_ = ctxInfo->contextS->GetToken(); + ctxInfo->dataShareHelper = DataShareHelper::Creator(ctxInfo->strUri, ctxInfo->options); + } else { ctxInfo->dataShareHelper = DataShareHelper::Creator(ctxInfo->contextS->GetToken(), ctxInfo->strUri); - } else if (!ctxInfo->isStageMode && ctxInfo->contextF != nullptr) { - ctxInfo->dataShareHelper = DataShareHelper::Creator(ctxInfo->contextF, ctxInfo->strUri); } }; ctxInfo->SetAction(std::move(input), std::move(output)); @@ -175,6 +183,10 @@ napi_value NapiDataShareHelper::GetConstructor(napi_env env) DECLARE_NAPI_FUNCTION("normalizeUri", Napi_NormalizeUri), DECLARE_NAPI_FUNCTION("denormalizeUri", Napi_DenormalizeUri), DECLARE_NAPI_FUNCTION("notifyChange", Napi_NotifyChange), + DECLARE_NAPI_FUNCTION("addTemplate", Napi_AddTemplate), + DECLARE_NAPI_FUNCTION("delTemplate", Napi_DelTemplate), + DECLARE_NAPI_FUNCTION("publish", Napi_Publish), + DECLARE_NAPI_FUNCTION("getPublishedData", Napi_GetPublishedData), }; NAPI_CALL(env, napi_define_class(env, "DataShareHelper", NAPI_AUTO_LENGTH, Initialize, nullptr, sizeof(clzDes) / sizeof(napi_property_descriptor), clzDes, &cons)); @@ -196,10 +208,16 @@ napi_value NapiDataShareHelper::Initialize(napi_env env, napi_callback_info info if (proxy == nullptr) { return nullptr; } - auto finalize = [](napi_env env, void * data, void * hint) { + auto finalize = [](napi_env env, void *data, void *hint) { NapiDataShareHelper *proxy = reinterpret_cast(data); + if (proxy->jsRdbObsManager_ == nullptr || proxy->jsPublishedObsManager_ == nullptr) { + LOG_ERROR("proxy->jsManager_ is nullptr"); + delete proxy; + return; + } + proxy->jsRdbObsManager_->DelObservers(env, nullptr); + proxy->jsPublishedObsManager_->DelObservers(env, nullptr); delete proxy; - LOG_INFO("NapiDataShareHelper has been deleted successfully!"); }; if (napi_wrap(env, self, proxy, finalize, nullptr, nullptr) != napi_ok) { finalize(env, proxy, nullptr); @@ -625,38 +643,189 @@ napi_value NapiDataShareHelper::Napi_NotifyChange(napi_env env, napi_callback_in return asyncCall.Call(env, exec); } -napi_value NapiDataShareHelper::Napi_On(napi_env env, napi_callback_info info) +napi_value NapiDataShareHelper::Napi_AddTemplate(napi_env env, napi_callback_info info) { napi_value self = nullptr; size_t argc = MAX_ARGC; - napi_value argv[MAX_ARGC] = {nullptr}; + napi_value argv[MAX_ARGC] = { nullptr }; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &self, nullptr)); - NAPI_ASSERT(env, argc == ARGS_THREE, "wrong count of args"); + std::shared_ptr error = nullptr; + NAPI_ASSERT_CALL_ERRCODE_SYNC(env, argc == ARGS_THREE, error = std::make_shared("3"), error, + nullptr); NapiDataShareHelper *proxy = nullptr; NAPI_CALL_BASE(env, napi_unwrap(env, self, reinterpret_cast(&proxy)), nullptr); NAPI_ASSERT_BASE(env, proxy != nullptr, "there is no NapiDataShareHelper instance", nullptr); NAPI_ASSERT_BASE(env, proxy->datashareHelper_ != nullptr, "there is no DataShareHelper instance", nullptr); + napi_valuetype valueType; + NAPI_CALL(env, napi_typeof(env, argv[0], &valueType)); + NAPI_ASSERT_CALL_ERRCODE_SYNC(env, valueType == napi_string, + error = std::make_shared("uri", "string"), error, nullptr); + std::string uri = DataShareJSUtils::Convert2String(env, argv[0]); + NAPI_ASSERT_BASE(env, !uri.empty(), "convert uri failed", nullptr); + + NAPI_CALL(env, napi_typeof(env, argv[1], &valueType)); + NAPI_ASSERT_CALL_ERRCODE_SYNC(env, valueType == napi_string, + error = std::make_shared("subscriberId", "string"), error, nullptr); + std::string subscriberId = DataShareJSUtils::Convert2String(env, argv[1]); + + NAPI_CALL(env, napi_typeof(env, argv[PARAM2], &valueType)); + NAPI_ASSERT_CALL_ERRCODE_SYNC(env, valueType == napi_object, + error = std::make_shared("template", "Template"), error, nullptr); + Template tpl = DataShareJSUtils::Convert2Template(env, argv[PARAM2]); + + auto res = proxy->datashareHelper_->AddQueryTemplate(uri, atoll(subscriberId.c_str()), tpl); + return DataShareJSUtils::Convert2JSValue(env, res); +} + +napi_value NapiDataShareHelper::Napi_DelTemplate(napi_env env, napi_callback_info info) +{ + napi_value self = nullptr; + size_t argc = MAX_ARGC; + napi_value argv[MAX_ARGC] = { nullptr }; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &self, nullptr)); + std::shared_ptr error = nullptr; + NAPI_ASSERT_CALL_ERRCODE_SYNC(env, argc == ARGS_TWO, error = std::make_shared("2"), error, + nullptr); + + NapiDataShareHelper *proxy = nullptr; + NAPI_CALL_BASE(env, napi_unwrap(env, self, reinterpret_cast(&proxy)), nullptr); + NAPI_ASSERT_BASE(env, proxy != nullptr, "there is no NapiDataShareHelper instance", nullptr); + NAPI_ASSERT_BASE(env, proxy->datashareHelper_ != nullptr, "there is no DataShareHelper instance", nullptr); + + napi_valuetype valueType; + NAPI_CALL(env, napi_typeof(env, argv[0], &valueType)); + NAPI_ASSERT_CALL_ERRCODE_SYNC(env, valueType == napi_string, + error = std::make_shared("uri", "string"), error, nullptr); + std::string uri = DataShareJSUtils::Convert2String(env, argv[0]); + NAPI_ASSERT_BASE(env, !uri.empty(), "convert uri failed", nullptr); + + NAPI_CALL(env, napi_typeof(env, argv[1], &valueType)); + NAPI_ASSERT_CALL_ERRCODE_SYNC(env, valueType == napi_string, + error = std::make_shared("subscriberId", "string"), error, nullptr); + std::string subscriberId = DataShareJSUtils::Convert2String(env, argv[1]); + + auto res = proxy->datashareHelper_->DelQueryTemplate(uri, atoll(subscriberId.c_str())); + return DataShareJSUtils::Convert2JSValue(env, res); +} + +napi_value NapiDataShareHelper::Napi_Publish(napi_env env, napi_callback_info info) +{ + auto context = std::make_shared(); + auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status { + if (argc != 2 && argc != 3 && argc != 4) { + context->error = std::make_shared("2 or 3 or 4"); + return napi_invalid_arg; + } + napi_valuetype valueType; + NAPI_CALL_BASE(env, napi_typeof(env, argv[0], &valueType), napi_invalid_arg); + NAPI_ASSERT_CALL_ERRCODE(env, valueType == napi_object, + context->error = std::make_shared("data", "Data"), napi_invalid_arg); + NAPI_CALL_BASE(env, napi_typeof(env, argv[1], &valueType), napi_invalid_arg); + NAPI_ASSERT_CALL_ERRCODE(env, valueType == napi_string, + context->error = std::make_shared("bundleName", "string"), napi_invalid_arg); + if (argc > 2) { + NAPI_CALL_BASE(env, napi_typeof(env, argv[PARAM2], &valueType), napi_invalid_arg); + if (valueType == napi_number) { + napi_get_value_int32(env, argv[PARAM2], &(context->publishData.version_)); + } + } + context->publishData = DataShareJSUtils::Convert2PublishedData(env, argv[0]); + context->bundleName = DataShareJSUtils::Convert2String(env, argv[1]); + return napi_ok; + }; + auto output = [context](napi_env env, napi_value *result) -> napi_status { + NAPI_ASSERT_BASE(env, context->status == napi_ok, "exec failed", napi_generic_failure); + *result = DataShareJSUtils::Convert2JSValue(env, context->results); + context->results.clear(); + return napi_ok; + }; + auto exec = [context](AsyncCall::Context *ctx) { + if (context->proxy->datashareHelper_ == nullptr) { + LOG_ERROR("dataShareHelper_ is nullptr"); + return; + } + context->results = + context->proxy->datashareHelper_->Publish(context->publishData, context->bundleName); + context->status = napi_ok; + }; + context->SetAction(std::move(input), std::move(output)); + AsyncCall asyncCall(env, info, context); + return asyncCall.Call(env, exec); +} + +napi_value NapiDataShareHelper::Napi_GetPublishedData(napi_env env, napi_callback_info info) +{ + auto context = std::make_shared(); + auto input = [context](napi_env env, size_t argc, napi_value *argv, napi_value self) -> napi_status { + if (argc != 1 && argc != 2) { + context->error = std::make_shared("1 or 2"); + return napi_invalid_arg; + } + napi_valuetype valueType; + NAPI_CALL_BASE(env, napi_typeof(env, argv[0], &valueType), napi_invalid_arg); + NAPI_ASSERT_CALL_ERRCODE(env, valueType == napi_string, + context->error = std::make_shared("bundleName", "string"), napi_invalid_arg); + context->bundleName = DataShareJSUtils::Convert2String(env, argv[0]); + return napi_ok; + }; + auto output = [context](napi_env env, napi_value *result) -> napi_status { + NAPI_ASSERT_BASE(env, context->status == napi_ok, "exec failed", napi_generic_failure); + *result = DataShareJSUtils::Convert2JSValue(env, context->publishData.datas_); + return napi_ok; + }; + auto exec = [context](AsyncCall::Context *ctx) { + if (context->proxy->datashareHelper_ == nullptr) { + LOG_ERROR("dataShareHelper_ is nullptr"); + return; + } + context->publishData = context->proxy->datashareHelper_->GetPublishedData(context->bundleName); + context->status = napi_ok; + }; + context->SetAction(std::move(input), std::move(output)); + AsyncCall asyncCall(env, info, context); + return asyncCall.Call(env, exec); +} + +napi_value NapiDataShareHelper::Napi_On(napi_env env, napi_callback_info info) +{ + napi_value self = nullptr; + size_t argc = MAX_ARGC; + napi_value argv[MAX_ARGC] = { nullptr }; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &self, nullptr)); + NAPI_ASSERT(env, argc == ARGS_THREE || argc == ARGS_FOUR, "wrong count of args"); + napi_valuetype valueType; NAPI_CALL(env, napi_typeof(env, argv[0], &valueType)); if (valueType != napi_string) { LOG_ERROR("type is not string"); return nullptr; } + std::string type = DataShareJSUtils::Convert2String(env, argv[0]); + if (type == "rdbDataChange") { + return Napi_SubscribeRdbObserver(env, argc, argv, self); + } else if (type == "publishedDataChange") { + return Napi_SubscribePublishedObserver(env, argc, argv, self); + } if (type != "dataChange") { LOG_ERROR("wrong register type : %{public}s", type.c_str()); return nullptr; } + NapiDataShareHelper *proxy = nullptr; + NAPI_CALL_BASE(env, napi_unwrap(env, self, reinterpret_cast(&proxy)), nullptr); + NAPI_ASSERT_BASE(env, proxy != nullptr, "there is no NapiDataShareHelper instance", nullptr); + NAPI_ASSERT_BASE(env, proxy->datashareHelper_ != nullptr, "there is no DataShareHelper instance", nullptr); + NAPI_CALL(env, napi_typeof(env, argv[1], &valueType)); NAPI_ASSERT_BASE(env, valueType == napi_string, "uri is not string", nullptr); std::string uri = DataShareJSUtils::Convert2String(env, argv[1]); - NAPI_CALL(env, napi_typeof(env, argv[2], &valueType)); + NAPI_CALL(env, napi_typeof(env, argv[PARAM2], &valueType)); NAPI_ASSERT_BASE(env, valueType == napi_function, "callback is not a function", nullptr); - + proxy->RegisteredObserver(env, uri, argv[PARAM2]); return nullptr; } @@ -665,14 +834,9 @@ napi_value NapiDataShareHelper::Napi_Off(napi_env env, napi_callback_info info) { napi_value self = nullptr; size_t argc = MAX_ARGC; - napi_value argv[MAX_ARGC] = {nullptr}; + napi_value argv[MAX_ARGC] = { nullptr }; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &self, nullptr)); - NAPI_ASSERT(env, argc == ARGS_TWO || argc == ARGS_THREE, "wrong count of args"); - - NapiDataShareHelper *proxy = nullptr; - NAPI_CALL_BASE(env, napi_unwrap(env, self, reinterpret_cast(&proxy)), nullptr); - NAPI_ASSERT_BASE(env, proxy != nullptr, "there is no NapiDataShareHelper instance", nullptr); - NAPI_ASSERT_BASE(env, proxy->datashareHelper_ != nullptr, "there is no DataShareHelper instance", nullptr); + NAPI_ASSERT(env, argc == ARGS_TWO || argc == ARGS_THREE || argc == ARGS_FOUR, "wrong count of args"); napi_valuetype valueType; NAPI_CALL(env, napi_typeof(env, argv[0], &valueType)); @@ -680,12 +844,23 @@ napi_value NapiDataShareHelper::Napi_Off(napi_env env, napi_callback_info info) LOG_ERROR("type is not string"); return nullptr; } + std::string type = DataShareJSUtils::Convert2String(env, argv[0]); + if (type == "rdbDataChange") { + return Napi_UnsubscribeRdbObserver(env, argc, argv, self); + } else if (type == "publishedDataChange") { + return Napi_UnsubscribePublishedObserver(env, argc, argv, self); + } if (type != "dataChange") { LOG_ERROR("wrong register type : %{public}s", type.c_str()); return nullptr; } + NapiDataShareHelper *proxy = nullptr; + NAPI_CALL_BASE(env, napi_unwrap(env, self, reinterpret_cast(&proxy)), nullptr); + NAPI_ASSERT_BASE(env, proxy != nullptr, "there is no NapiDataShareHelper instance", nullptr); + NAPI_ASSERT_BASE(env, proxy->datashareHelper_ != nullptr, "there is no DataShareHelper instance", nullptr); + NAPI_CALL(env, napi_typeof(env, argv[1], &valueType)); NAPI_ASSERT_BASE(env, valueType == napi_string, "uri is not string", nullptr); std::string uri = DataShareJSUtils::Convert2String(env, argv[1]); @@ -774,5 +949,163 @@ void NapiDataShareHelper::UnRegisteredObserver(napi_env env, const std::string & } observerMap_.erase(uri); } -} // namespace DataShare -} // namespace OHOS + +napi_value NapiDataShareHelper::Napi_SubscribeRdbObserver(napi_env env, size_t argc, napi_value *argv, napi_value self) +{ + std::vector results; + napi_value jsResults = DataShareJSUtils::Convert2JSValue(env, results); + std::shared_ptr error = nullptr; + NAPI_ASSERT_CALL_ERRCODE_SYNC(env, argc == ARGS_FOUR, error = std::make_shared("4"), error, + jsResults); + + NapiDataShareHelper *proxy = nullptr; + NAPI_CALL_BASE(env, napi_unwrap(env, self, reinterpret_cast(&proxy)), jsResults); + NAPI_ASSERT_BASE(env, proxy != nullptr, "there is no NapiDataShareHelper instance", jsResults); + NAPI_ASSERT_BASE(env, proxy->datashareHelper_ != nullptr, "there is no DataShareHelper instance", jsResults); + + napi_valuetype valueType; + NAPI_CALL(env, napi_typeof(env, argv[1], &valueType)); + NAPI_ASSERT_CALL_ERRCODE_SYNC(env, valueType == napi_object, + error = std::make_shared("uris", "Array"), error, jsResults); + std::vector uris = + DataShareJSUtils::Convert2StrVector(env, argv[1], DataShareJSUtils::DEFAULT_BUF_SIZE); + + NAPI_CALL(env, napi_typeof(env, argv[PARAM2], &valueType)); + NAPI_ASSERT_CALL_ERRCODE_SYNC(env, valueType == napi_object, + error = std::make_shared("templateId", "TemplateId"), error, jsResults); + TemplateId templateId = DataShareJSUtils::Convert2TemplateId(env, argv[PARAM2]); + + NAPI_CALL(env, napi_typeof(env, argv[PARAM3], &valueType)); + NAPI_ASSERT_CALL_ERRCODE_SYNC(env, valueType == napi_function, + error = std::make_shared("callback", "function"), error, jsResults); + + if (proxy->jsRdbObsManager_ == nullptr) { + LOG_ERROR("proxy->jsManager_ is nullptr"); + return jsResults; + } + results = proxy->jsRdbObsManager_->AddObservers(env, argv[PARAM3], uris, templateId); + return DataShareJSUtils::Convert2JSValue(env, results); +} + +napi_value NapiDataShareHelper::Napi_UnsubscribeRdbObserver(napi_env env, size_t argc, napi_value *argv, + napi_value self) +{ + std::vector results; + napi_value jsResults = DataShareJSUtils::Convert2JSValue(env, results); + std::shared_ptr error = nullptr; + NAPI_ASSERT_CALL_ERRCODE_SYNC(env, argc == ARGS_THREE || argc == ARGS_FOUR, + error = std::make_shared("3 or 4"), error, jsResults); + + NapiDataShareHelper *proxy = nullptr; + NAPI_CALL_BASE(env, napi_unwrap(env, self, reinterpret_cast(&proxy)), jsResults); + NAPI_ASSERT_BASE(env, proxy != nullptr, "there is no NapiDataShareHelper instance", jsResults); + NAPI_ASSERT_BASE(env, proxy->datashareHelper_ != nullptr, "there is no DataShareHelper instance", jsResults); + + napi_valuetype valueType; + NAPI_CALL(env, napi_typeof(env, argv[1], &valueType)); + NAPI_ASSERT_CALL_ERRCODE_SYNC(env, valueType == napi_object, + error = std::make_shared("uris", "Array"), error, jsResults); + std::vector uris = + DataShareJSUtils::Convert2StrVector(env, argv[1], DataShareJSUtils::DEFAULT_BUF_SIZE); + + NAPI_CALL(env, napi_typeof(env, argv[PARAM2], &valueType)); + NAPI_ASSERT_CALL_ERRCODE_SYNC(env, valueType == napi_object, + error = std::make_shared("templateId", "TemplateId"), error, jsResults); + TemplateId templateId = DataShareJSUtils::Convert2TemplateId(env, argv[2]); + + if (proxy->jsRdbObsManager_ == nullptr) { + LOG_ERROR("proxy->jsManager_ is nullptr"); + return jsResults; + } + + if (argc == ARGS_FOUR) { + NAPI_CALL(env, napi_typeof(env, argv[PARAM3], &valueType)); + NAPI_ASSERT_CALL_ERRCODE_SYNC(env, valueType == napi_function, + error = std::make_shared("callback", "function"), error, jsResults); + results = proxy->jsRdbObsManager_->DelObservers(env, argv[PARAM3], uris, templateId); + return DataShareJSUtils::Convert2JSValue(env, results); + } + results = proxy->jsRdbObsManager_->DelObservers(env, nullptr, uris, templateId); + return DataShareJSUtils::Convert2JSValue(env, results); +} + +napi_value NapiDataShareHelper::Napi_SubscribePublishedObserver(napi_env env, size_t argc, napi_value *argv, + napi_value self) +{ + std::vector results; + napi_value jsResults = DataShareJSUtils::Convert2JSValue(env, results); + std::shared_ptr error = nullptr; + NAPI_ASSERT_CALL_ERRCODE_SYNC(env, argc == ARGS_FOUR, error = std::make_shared("4"), error, + jsResults); + + NapiDataShareHelper *proxy = nullptr; + NAPI_CALL_BASE(env, napi_unwrap(env, self, reinterpret_cast(&proxy)), jsResults); + NAPI_ASSERT_BASE(env, proxy != nullptr, "there is no NapiDataShareHelper instance", jsResults); + NAPI_ASSERT_BASE(env, proxy->datashareHelper_ != nullptr, "there is no DataShareHelper instance", jsResults); + + napi_valuetype valueType; + NAPI_CALL(env, napi_typeof(env, argv[1], &valueType)); + NAPI_ASSERT_CALL_ERRCODE_SYNC(env, valueType == napi_object, + error = std::make_shared("uris", "Array"), error, jsResults); + std::vector uris = + DataShareJSUtils::Convert2StrVector(env, argv[1], DataShareJSUtils::DEFAULT_BUF_SIZE); + + NAPI_CALL(env, napi_typeof(env, argv[PARAM2], &valueType)); + NAPI_ASSERT_CALL_ERRCODE_SYNC(env, valueType == napi_string, + error = std::make_shared("subscriberId", "string"), error, jsResults); + std::string subscriberId = DataShareJSUtils::Convert2String(env, argv[PARAM2]); + + NAPI_CALL(env, napi_typeof(env, argv[PARAM3], &valueType)); + NAPI_ASSERT_CALL_ERRCODE_SYNC(env, valueType == napi_function, + error = std::make_shared("callback", "function"), error, jsResults); + + if (proxy->jsPublishedObsManager_ == nullptr) { + LOG_ERROR("proxy->jsPublishedObsManager_ is nullptr"); + return jsResults; + } + results = proxy->jsPublishedObsManager_->AddObservers(env, argv[PARAM3], uris, atoll(subscriberId.c_str())); + return DataShareJSUtils::Convert2JSValue(env, results); +} + +napi_value NapiDataShareHelper::Napi_UnsubscribePublishedObserver(napi_env env, size_t argc, napi_value *argv, + napi_value self) +{ + std::vector results; + napi_value jsResults = DataShareJSUtils::Convert2JSValue(env, results); + std::shared_ptr error = nullptr; + NAPI_ASSERT_CALL_ERRCODE_SYNC(env, argc == ARGS_THREE || argc == ARGS_FOUR, + error = std::make_shared("3 or 4"), error, jsResults); + + NapiDataShareHelper *proxy = nullptr; + NAPI_CALL_BASE(env, napi_unwrap(env, self, reinterpret_cast(&proxy)), jsResults); + NAPI_ASSERT_BASE(env, proxy != nullptr, "there is no NapiDataShareHelper instance", jsResults); + NAPI_ASSERT_BASE(env, proxy->datashareHelper_ != nullptr, "there is no DataShareHelper instance", jsResults); + + napi_valuetype valueType; + NAPI_CALL(env, napi_typeof(env, argv[1], &valueType)); + NAPI_ASSERT_CALL_ERRCODE_SYNC(env, valueType == napi_object, + error = std::make_shared("uris", "Array"), error, jsResults); + std::vector uris = + DataShareJSUtils::Convert2StrVector(env, argv[1], DataShareJSUtils::DEFAULT_BUF_SIZE); + + NAPI_CALL(env, napi_typeof(env, argv[PARAM2], &valueType)); + NAPI_ASSERT_CALL_ERRCODE_SYNC(env, valueType == napi_number, + error = std::make_shared("subscriberId", "string"), error, jsResults); + std::string subscriberId = DataShareJSUtils::Convert2String(env, argv[PARAM2]); + if (proxy->jsPublishedObsManager_ == nullptr) { + LOG_ERROR("proxy->jsPublishedObsManager_ is nullptr"); + return jsResults; + } + + if (argc == ARGS_FOUR) { + NAPI_CALL(env, napi_typeof(env, argv[PARAM3], &valueType)); + NAPI_ASSERT_CALL_ERRCODE_SYNC(env, valueType == napi_function, + error = std::make_shared("callback", "function"), error, jsResults); + results = proxy->jsPublishedObsManager_->DelObservers(env, argv[PARAM3], uris, atoll(subscriberId.c_str())); + return DataShareJSUtils::Convert2JSValue(env, results); + } + results = proxy->jsPublishedObsManager_->DelObservers(env, nullptr, uris, atoll(subscriberId.c_str())); + return DataShareJSUtils::Convert2JSValue(env, results); +} +} // namespace DataShare +} // namespace OHOS diff --git a/data_share/frameworks/js/napi/dataShare/src/napi_datashare_inner_observer.cpp b/data_share/frameworks/js/napi/dataShare/src/napi_datashare_inner_observer.cpp index c2a21b3b3c281ee097793974a87e0ca98bb957d3..31e074c2d5f8983ab7f86ad8938a4b5f73400e57 100644 --- a/data_share/frameworks/js/napi/dataShare/src/napi_datashare_inner_observer.cpp +++ b/data_share/frameworks/js/napi/dataShare/src/napi_datashare_inner_observer.cpp @@ -1,100 +1,100 @@ -/* - * Copyright (c) 2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "napi_datashare_observer.h" - -#include -#include "datashare_log.h" - -namespace OHOS { -namespace DataShare { -NAPIInnerObserver::NAPIInnerObserver(napi_env env, napi_value callback) - : env_(env) -{ - napi_create_reference(env, callback, 1, &ref_); - napi_get_uv_event_loop(env, &loop_); -} - -void NAPIInnerObserver::OnComplete(uv_work_t *work, int status) -{ - LOG_DEBUG("uv_queue_work start"); - std::shared_ptr innerWorker(reinterpret_cast(work->data)); - auto observer = innerWorker->observer_.lock(); - if (observer == nullptr || observer->ref_ == nullptr) { - delete work; - LOG_ERROR("innerWorker->observer_->ref_ is nullptr"); - return; - } - napi_handle_scope scope = nullptr; - napi_open_handle_scope(observer->env_, &scope); - if (scope == nullptr) { - delete work; - return; - } - napi_value callback = nullptr; - napi_value args[2] = {0}; - napi_value global = nullptr; - napi_value result; - napi_get_reference_value(observer->env_, observer->ref_, &callback); - napi_get_global(observer->env_, &global); - napi_status callStatus = napi_call_function(observer->env_, global, callback, 2, args, &result); - napi_close_handle_scope(observer->env_, scope); - if (callStatus != napi_ok) { - LOG_ERROR("napi_call_function failed status : %{public}d", callStatus); - } - delete work; -} - -void NAPIInnerObserver::OnChange() -{ - LOG_DEBUG("NAPIInnerObserver Start"); - if (ref_ == nullptr) { - LOG_ERROR("ref_ is nullptr"); - return; - } - ObserverWorker *observerWorker = new (std::nothrow)ObserverWorker(shared_from_this()); - if (observerWorker == nullptr) { - LOG_ERROR("Failed to create observerWorker"); - return; - } - uv_work_t *work = new (std::nothrow)uv_work_t(); - if (work == nullptr) { - delete observerWorker; - LOG_ERROR("Failed to create uv work"); - return; - } - work->data = observerWorker; - int ret = uv_queue_work(loop_, work, [](uv_work_t *work) {}, NAPIInnerObserver::OnComplete); - if (ret != 0) { - LOG_ERROR("uv_queue_work failed"); - delete observerWorker; - delete work; - } -} - -void NAPIInnerObserver::DeleteReference() -{ - if (ref_ != nullptr) { - napi_delete_reference(env_, ref_); - ref_ = nullptr; - } -} - -napi_ref NAPIInnerObserver::GetCallback() -{ - return ref_; -} -} // namespace DataShare +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "napi_datashare_observer.h" + +#include +#include "datashare_log.h" + +namespace OHOS { +namespace DataShare { +NAPIInnerObserver::NAPIInnerObserver(napi_env env, napi_value callback) + : env_(env) +{ + napi_create_reference(env, callback, 1, &ref_); + napi_get_uv_event_loop(env, &loop_); +} + +void NAPIInnerObserver::OnComplete(uv_work_t *work, int status) +{ + LOG_DEBUG("uv_queue_work start"); + std::shared_ptr innerWorker(reinterpret_cast(work->data)); + auto observer = innerWorker->observer_.lock(); + if (observer == nullptr || observer->ref_ == nullptr) { + delete work; + LOG_ERROR("innerWorker->observer_->ref_ is nullptr"); + return; + } + napi_handle_scope scope = nullptr; + napi_open_handle_scope(observer->env_, &scope); + if (scope == nullptr) { + delete work; + return; + } + napi_value callback = nullptr; + napi_value args[2] = {0}; + napi_value global = nullptr; + napi_value result; + napi_get_reference_value(observer->env_, observer->ref_, &callback); + napi_get_global(observer->env_, &global); + napi_status callStatus = napi_call_function(observer->env_, global, callback, 2, args, &result); + napi_close_handle_scope(observer->env_, scope); + if (callStatus != napi_ok) { + LOG_ERROR("napi_call_function failed status : %{public}d", callStatus); + } + delete work; +} + +void NAPIInnerObserver::OnChange() +{ + LOG_DEBUG("NAPIInnerObserver Start"); + if (ref_ == nullptr) { + LOG_ERROR("ref_ is nullptr"); + return; + } + ObserverWorker *observerWorker = new (std::nothrow)ObserverWorker(shared_from_this()); + if (observerWorker == nullptr) { + LOG_ERROR("Failed to create observerWorker"); + return; + } + uv_work_t *work = new (std::nothrow)uv_work_t(); + if (work == nullptr) { + delete observerWorker; + LOG_ERROR("Failed to create uv work"); + return; + } + work->data = observerWorker; + int ret = uv_queue_work(loop_, work, [](uv_work_t *work) {}, NAPIInnerObserver::OnComplete); + if (ret != 0) { + LOG_ERROR("uv_queue_work failed"); + delete observerWorker; + delete work; + } +} + +void NAPIInnerObserver::DeleteReference() +{ + if (ref_ != nullptr) { + napi_delete_reference(env_, ref_); + ref_ = nullptr; + } +} + +napi_ref NAPIInnerObserver::GetCallback() +{ + return ref_; +} +} // namespace DataShare } // namespace OHOS \ No newline at end of file diff --git a/data_share/frameworks/js/napi/observer/include/napi_observer.h b/data_share/frameworks/js/napi/observer/include/napi_observer.h new file mode 100644 index 0000000000000000000000000000000000000000..56554fec825e6f5cc05c5f8ac665609df60724df --- /dev/null +++ b/data_share/frameworks/js/napi/observer/include/napi_observer.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NAPI_RDB_OBSERVER_H +#define NAPI_RDB_OBSERVER_H + +#include + +#include "datashare_template.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" + +namespace OHOS { +namespace DataShare { +class NapiObserver { +public: + NapiObserver(napi_env env, napi_value callback); + ~NapiObserver(); + virtual bool operator==(const NapiObserver &rhs) const; + virtual bool operator!=(const NapiObserver &rhs) const; + NapiObserver& operator=(NapiObserver &&rhs) = default; +protected: + static void CallbackFunc(uv_work_t *work, int status); + napi_env env_ = nullptr; + napi_ref ref_ = nullptr; + uv_loop_s *loop_ = nullptr; +}; + +class NapiRdbObserver final: public NapiObserver, public std::enable_shared_from_this { +public: + NapiRdbObserver(napi_env env, napi_value callback) : NapiObserver(env, callback) {}; + void OnChange(const RdbChangeNode &changeNode); +}; + +class NapiPublishedObserver final: public NapiObserver, public std::enable_shared_from_this { +public: + NapiPublishedObserver(napi_env env, napi_value callback) : NapiObserver(env, callback) {}; + void OnChange(PublishedDataChangeNode &changeNode); +}; + +struct ObserverWorker { + std::weak_ptr observer_; + std::function getParam; + explicit ObserverWorker(std::shared_ptr observerIn) : observer_(observerIn) {} +}; +} // namespace DataShare +} // namespace OHOS +#endif //NAPI_RDB_OBSERVER_H diff --git a/data_share/frameworks/js/napi/observer/include/napi_subscriber_manager.h b/data_share/frameworks/js/napi/observer/include/napi_subscriber_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..264d6d7c9c3dbdef8ca7ad988306bb5f89842669 --- /dev/null +++ b/data_share/frameworks/js/napi/observer/include/napi_subscriber_manager.h @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NAPI_RDB_SUBSCRIBER_MANAGER_H +#define NAPI_RDB_SUBSCRIBER_MANAGER_H + +#include +#include + +#include "callbacks_manager.h" +#include "datashare_helper.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" +#include "napi_observer.h" + +namespace OHOS { +namespace DataShare { +class NapiRdbSubscriberManager : public CallbacksManager { +public: + using Key = RdbObserverMapKey; + using Observer = NapiRdbObserver; + using BaseCallbacks = CallbacksManager; + explicit NapiRdbSubscriberManager(std::weak_ptr dataShareHelper) + : dataShareHelper_(dataShareHelper){}; + std::vector AddObservers(napi_env env, napi_value callback, const std::vector &uris, + const TemplateId &templateId); + std::vector DelObservers(napi_env env, napi_value callback, + const std::vector &uris = std::vector(), + const TemplateId &templateId = TemplateId()); + void Emit(const RdbChangeNode &changeNode); + +private: + std::weak_ptr dataShareHelper_; +}; + +class NapiPublishedSubscriberManager : public CallbacksManager { +public: + using Key = PublishedObserverMapKey; + using Observer = NapiPublishedObserver; + using BaseCallbacks = CallbacksManager; + explicit NapiPublishedSubscriberManager(std::weak_ptr dataShareHelper) + : dataShareHelper_(dataShareHelper){}; + std::vector AddObservers(napi_env env, napi_value callback, const std::vector &uris, + int64_t subscriberId); + std::vector DelObservers(napi_env env, napi_value callback, + const std::vector &uris = std::vector(), int64_t subscriberId = 0); + void Emit(const PublishedDataChangeNode &changeNode); + +private: + std::weak_ptr dataShareHelper_; +}; +} // namespace DataShare +} // namespace OHOS +#endif //NAPI_RDB_SUBSCRIBER_MANAGER_H diff --git a/data_share/frameworks/js/napi/observer/src/napi_observer.cpp b/data_share/frameworks/js/napi/observer/src/napi_observer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2ce5e1489d3c1f7ec5c099a311fd85de69d8444c --- /dev/null +++ b/data_share/frameworks/js/napi/observer/src/napi_observer.cpp @@ -0,0 +1,156 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "napi_observer.h" + +#include "datashare_js_utils.h" +#include "datashare_log.h" + +namespace OHOS { +namespace DataShare { +NapiObserver::NapiObserver(napi_env env, napi_value callback) : env_(env) +{ + napi_create_reference(env, callback, 1, &ref_); + napi_get_uv_event_loop(env, &loop_); +} + +void NapiObserver::CallbackFunc(uv_work_t *work, int status) +{ + LOG_DEBUG("RdbObsCallbackFunc start"); + std::shared_ptr innerWorker(reinterpret_cast(work->data)); + std::shared_ptr observer = innerWorker->observer_.lock(); + if (observer == nullptr || observer->ref_ == nullptr) { + delete work; + LOG_ERROR("rdbObserver->ref_ is nullptr"); + return; + } + napi_handle_scope scope = nullptr; + napi_open_handle_scope(observer->env_, &scope); + if (scope == nullptr) { + delete work; + return; + } + napi_value callback = nullptr; + napi_value param[2]; + napi_value global = nullptr; + napi_value result; + napi_get_reference_value(observer->env_, observer->ref_, &callback); + napi_get_global(observer->env_, &global); + napi_get_undefined(observer->env_, ¶m[0]); + param[1] = innerWorker->getParam(observer->env_); + napi_status callStatus = napi_call_function(observer->env_, global, callback, 2, param, &result); + napi_close_handle_scope(observer->env_, scope); + if (callStatus != napi_ok) { + LOG_ERROR("napi_call_function failed status : %{public}d", callStatus); + } + delete work; +} + +NapiObserver::~NapiObserver() +{ + if (ref_ != nullptr) { + napi_delete_reference(env_, ref_); + ref_ = nullptr; + } +} + +bool NapiObserver::operator==(const NapiObserver &rhs) const +{ + if (ref_ == nullptr) { + return (rhs.ref_ == nullptr); + } + + napi_value value1 = nullptr; + napi_get_reference_value(env_, ref_, &value1); + + napi_value value2 = nullptr; + napi_get_reference_value(env_, ref_, &value2); + + bool isEqual = false; + napi_strict_equals(env_, value1, value2, &isEqual); + return isEqual; +} + +bool NapiObserver::operator!=(const NapiObserver &rhs) const +{ + return !(rhs == *this); +} + +void NapiRdbObserver::OnChange(const RdbChangeNode &changeNode) +{ + LOG_DEBUG("NapiRdbObserver onchange Start"); + if (ref_ == nullptr) { + LOG_ERROR("ref_ is nullptr"); + return; + } + ObserverWorker *observerWorker = new (std::nothrow) ObserverWorker(shared_from_this()); + if (observerWorker == nullptr) { + LOG_ERROR("Failed to create observerWorker"); + return; + } + observerWorker->getParam = [changeNode](napi_env env) { + return DataShareJSUtils::Convert2JSValue(env, changeNode); + }; + + uv_work_t *work = new (std::nothrow) uv_work_t(); + if (work == nullptr) { + delete observerWorker; + LOG_ERROR("Failed to create uv work"); + return; + } + work->data = observerWorker; + int ret = uv_queue_work( + loop_, work, [](uv_work_t *work) {}, CallbackFunc); + if (ret != 0) { + LOG_ERROR("uv_queue_work failed"); + delete observerWorker; + delete work; + } +} + +void NapiPublishedObserver::OnChange(PublishedDataChangeNode &changeNode) +{ + LOG_DEBUG("NapiPublishedObserver onchange Start"); + if (ref_ == nullptr) { + LOG_ERROR("ref_ is nullptr"); + return; + } + ObserverWorker *observerWorker = new (std::nothrow) ObserverWorker(shared_from_this()); + if (observerWorker == nullptr) { + LOG_ERROR("Failed to create observerWorker"); + return; + } + std::shared_ptr node = std::make_shared(std::move(changeNode)); + observerWorker->getParam = [node](napi_env env) { + return DataShareJSUtils::Convert2JSValue(env, *node); + }; + + uv_work_t *work = new (std::nothrow) uv_work_t(); + if (work == nullptr) { + delete observerWorker; + LOG_ERROR("Failed to create uv work"); + return; + } + work->data = observerWorker; + int ret = uv_queue_work( + loop_, work, [](uv_work_t *work) {}, CallbackFunc); + if (ret != 0) { + LOG_ERROR("uv_queue_work failed"); + delete observerWorker; + delete work; + } +} +} // namespace DataShare +} // namespace OHOS diff --git a/data_share/frameworks/js/napi/observer/src/napi_subscriber_manager.cpp b/data_share/frameworks/js/napi/observer/src/napi_subscriber_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ffd6bf198a044e5acf54ac5dcf31ce27d4d9bdf0 --- /dev/null +++ b/data_share/frameworks/js/napi/observer/src/napi_subscriber_manager.cpp @@ -0,0 +1,202 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "napi_subscriber_manager.h" + +#include "datashare_log.h" + +namespace OHOS { +namespace DataShare { +std::vector NapiRdbSubscriberManager::AddObservers( + napi_env env, napi_value callback, const std::vector &uris, const TemplateId &templateId) +{ + auto datashareHelper = dataShareHelper_.lock(); + if (datashareHelper == nullptr) { + LOG_ERROR("datashareHelper is nullptr"); + return std::vector(); + } + + std::vector keys; + std::for_each(uris.begin(), uris.end(), [&keys, &templateId](auto &uri) { + keys.emplace_back(uri, templateId); + }); + return BaseCallbacks::AddObservers(keys, std::make_shared(env, callback), + [&datashareHelper, &templateId, this](const std::vector &firstAddKeys, + const std::shared_ptr observer, std::vector &opResult) { + std::vector firstAddUris; + std::for_each(firstAddKeys.begin(), firstAddKeys.end(), [&firstAddUris](auto &result) { + firstAddUris.emplace_back(result); + }); + if (firstAddUris.empty()) { + return; + } + auto subResults = + datashareHelper->SubscribeRdbData(firstAddUris, templateId, [this](const RdbChangeNode &changeNode) { + Emit(changeNode); + }); + std::vector failedKeys; + for (auto &subResult : subResults) { + opResult.emplace_back(subResult); + if (subResult.errCode_ != E_OK) { + failedKeys.emplace_back(subResult.key_, templateId); + LOG_WARN("registered failed, uri is %{public}s", subResult.key_.c_str()); + } + } + if (failedKeys.size() > 0) { + BaseCallbacks::DelObservers(failedKeys, observer); + } + }); +} + +std::vector NapiRdbSubscriberManager::DelObservers( + napi_env env, napi_value callback, const std::vector &uris, const TemplateId &templateId) +{ + auto dataShareHelper = dataShareHelper_.lock(); + if (dataShareHelper == nullptr) { + LOG_ERROR("nativeManager is nullptr"); + return std::vector(); + } + std::vector keys; + std::for_each(uris.begin(), uris.end(), [&keys, &templateId](auto &uri) { + keys.emplace_back(uri, templateId); + }); + return BaseCallbacks::DelObservers(keys, + callback == nullptr ? nullptr : std::make_shared(env, callback), + [&dataShareHelper, &templateId, &callback, &uris](const std::vector &lastDelKeys, + const std::shared_ptr &observer, std::vector &opResult) { + // delete all obs + if (callback == nullptr && uris.empty()) { + dataShareHelper->UnsubscribeRdbData(); + return; + } + + std::vector lastDelUris; + std::for_each(lastDelKeys.begin(), lastDelKeys.end(), [&lastDelUris](auto &result) { + lastDelUris.emplace_back(result); + }); + if (lastDelUris.empty()) { + return; + } + auto unsubResult = dataShareHelper->UnsubscribeRdbData(lastDelUris, templateId); + opResult.insert(opResult.end(), unsubResult.begin(), unsubResult.end()); + }); +} + +void NapiRdbSubscriberManager::Emit(const RdbChangeNode &changeNode) +{ + Key key(changeNode.uri_, changeNode.templateId_); + auto callbacks = BaseCallbacks::GetEnabledObservers(key); + for (auto &obs : callbacks) { + if (obs != nullptr) { + obs->OnChange(changeNode); + } + } +} + +std::vector NapiPublishedSubscriberManager::AddObservers( + napi_env env, napi_value callback, const std::vector &uris, int64_t subscriberId) +{ + auto dataShareHelper = dataShareHelper_.lock(); + if (dataShareHelper == nullptr) { + LOG_ERROR("datashareHelper is nullptr"); + return std::vector(); + } + + std::vector keys; + std::for_each(uris.begin(), uris.end(), [&keys, &subscriberId](auto &uri) { + keys.emplace_back(uri, subscriberId); + }); + return BaseCallbacks::AddObservers(keys, std::make_shared(env, callback), + [&dataShareHelper, &subscriberId, this](const std::vector &firstAddKeys, + const std::shared_ptr observer, std::vector &opResult) { + std::vector firstAddUris; + std::for_each(firstAddKeys.begin(), firstAddKeys.end(), [&firstAddUris](auto &result) { + firstAddUris.emplace_back(result); + }); + if (firstAddUris.empty()) { + return; + } + auto subResults = dataShareHelper->SubscribePublishedData( + firstAddUris, subscriberId, [this](const PublishedDataChangeNode &changeNode) { + Emit(changeNode); + }); + std::vector failedKeys; + for (auto &subResult : subResults) { + opResult.emplace_back(subResult); + if (subResult.errCode_ != E_OK) { + failedKeys.emplace_back(subResult.key_, subscriberId); + LOG_WARN("registered failed, uri is %{public}s", subResult.key_.c_str()); + } + } + if (failedKeys.size() > 0) { + BaseCallbacks::DelObservers(failedKeys, observer); + } + }); +} + +std::vector NapiPublishedSubscriberManager::DelObservers( + napi_env env, napi_value callback, const std::vector &uris, int64_t subscriberId) +{ + auto dataShareHelper = dataShareHelper_.lock(); + if (dataShareHelper == nullptr) { + LOG_ERROR("nativeManager is nullptr"); + return std::vector(); + } + std::vector keys; + std::for_each(uris.begin(), uris.end(), [&keys, &subscriberId](auto &uri) { + keys.emplace_back(uri, subscriberId); + }); + return BaseCallbacks::DelObservers(keys, + callback == nullptr ? nullptr : std::make_shared(env, callback), + [&dataShareHelper, &subscriberId, &callback, &uris](const std::vector &lastDelKeys, + const std::shared_ptr &observer, std::vector &opResult) { + // delete all obs + if (callback == nullptr && uris.empty()) { + dataShareHelper->UnsubscribePublishedData(); + return; + } + + std::vector lastDelUris; + std::for_each(lastDelKeys.begin(), lastDelKeys.end(), [&lastDelUris](auto &result) { + lastDelUris.emplace_back(result); + }); + if (lastDelUris.empty()) { + return; + } + auto unsubResult = dataShareHelper->UnsubscribePublishedData(lastDelUris, subscriberId); + opResult.insert(opResult.end(), unsubResult.begin(), unsubResult.end()); + }); +} + +void NapiPublishedSubscriberManager::Emit(const PublishedDataChangeNode &changeNode) +{ + std::map, PublishedDataChangeNode> results; + for (auto &data : changeNode.datas_) { + PublishedObserverMapKey key(data.key_, data.subscriberId_); + auto callbacks = BaseCallbacks::GetEnabledObservers(key); + if (callbacks.empty()) { + LOG_WARN("%{private}s nobody subscribe, but still notify", data.key_.c_str()); + } + for (auto const &obs : callbacks) { + results[obs].datas_.emplace_back(data.key_, data.subscriberId_, data.GetData()); + } + } + for (auto &[callback, node] : results) { + node.ownerBundleName_ = changeNode.ownerBundleName_; + callback->OnChange(node); + } +} +} // namespace DataShare +} // namespace OHOS diff --git a/data_share/frameworks/native/common/include/base_proxy.h b/data_share/frameworks/native/common/include/base_proxy.h index 7f63ded212779e7c810aac569a2a81334d11eb3a..4de2110a8b8bfdf6b4bc19625dfc1925bb199d69 100644 --- a/data_share/frameworks/native/common/include/base_proxy.h +++ b/data_share/frameworks/native/common/include/base_proxy.h @@ -15,12 +15,14 @@ #include #include -#include "uri.h" -#include "datashare_values_bucket.h" +#include "data_proxy_observer.h" +#include "datashare_business_error.h" #include "datashare_predicates.h" #include "datashare_result_set.h" -#include "datashare_business_error.h" +#include "datashare_template.h" +#include "datashare_values_bucket.h" +#include "uri.h" #ifndef DATA_SHARE_BASE_PROXY_H #define DATA_SHARE_BASE_PROXY_H @@ -178,15 +180,47 @@ public: */ virtual Uri DenormalizeUri(const Uri &uri) = 0; -/** -* @brief Obtains the MIME types of files supported. -* -* @param uri Indicates the path of the files to obtain. -* @param mimeTypeFilter Indicates the MIME types of the files to obtain. This parameter cannot be null. -* -* @return Returns the matched MIME types. If there is no match, null is returned. -*/ -virtual std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) = 0; + /** + * @brief Obtains the MIME types of files supported. + * + * @param uri Indicates the path of the files to obtain. + * @param mimeTypeFilter Indicates the MIME types of the files to obtain. This parameter cannot be null. + * + * @return Returns the matched MIME types. If there is no match, null is returned. + */ + virtual std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) = 0; + + virtual int AddQueryTemplate(const std::string &uri, int64_t subscriberId, Template &tpl) = 0; + + virtual int DelQueryTemplate(const std::string &uri, int64_t subscriberId) = 0; + + virtual std::vector Publish(const Data &data, const std::string &bundleName) = 0; + + virtual Data GetPublishedData(const std::string &bundleName) = 0; + + virtual std::vector SubscribeRdbData(const std::vector &uris, + const TemplateId &templateId, const sptr &observer) = 0; + + virtual std::vector UnSubscribeRdbData( + const std::vector &uris, const TemplateId &templateId) = 0; + + virtual std::vector EnableSubscribeRdbData(const std::vector &uris, + const TemplateId &templateId) = 0; + + virtual std::vector DisableSubscribeRdbData(const std::vector &uris, + const TemplateId &templateId) = 0; + + virtual std::vector SubscribePublishedData(const std::vector &uris, + int64_t subscriberId, const sptr &observer) = 0; + + virtual std::vector UnSubscribePublishedData(const std::vector &uris, + int64_t subscriberId) = 0; + + virtual std::vector EnableSubscribePublishedData(const std::vector &uris, + int64_t subscriberId) = 0; + + virtual std::vector DisableSubscribePublishedData(const std::vector &uris, + int64_t subscriberId) = 0; }; } } diff --git a/data_share/frameworks/native/common/include/callbacks_manager.h b/data_share/frameworks/native/common/include/callbacks_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..ea5cd55c15590a793c3d18a2c16beb6080273071 --- /dev/null +++ b/data_share/frameworks/native/common/include/callbacks_manager.h @@ -0,0 +1,247 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DATA_SHARE_CALLBACKS_MANAGER_H +#define DATA_SHARE_CALLBACKS_MANAGER_H +#include +#include +#include + +#include "datashare_errno.h" +#include "datashare_template.h" + +namespace OHOS::DataShare { +template +class CallbacksManager { +public: + std::vector AddObservers(const std::vector &keys, const std::shared_ptr observer, + std::function &, const std::shared_ptr &observer, std::vector &)>); + std::vector DelObservers(const std::vector &keys, + const std::shared_ptr observer = nullptr, + std::function &, const std::shared_ptr &observer, std::vector &)> + processOnLastDel = CallbacksManager::DefaultProcess); + std::vector EnableObservers( + const std::vector &keys, std::function &, std::vector &)>); + + std::vector DisableObservers(const std::vector &keys, + std::function &, std::vector &)> processOnLastDel = + CallbacksManager::DefaultProcess2); + std::vector> GetEnabledObservers(const Key &); + int GetEnabledSubscriberSize(); +private: + static void DefaultProcess2(const std::vector &, std::vector &){}; + static void DefaultProcess( + const std::vector &, const std::shared_ptr &observer, std::vector &){}; + struct ObserverNode { + std::shared_ptr observer_; + bool enabled_; + ObserverNode(const std::shared_ptr &observer) : observer_(observer) + { + enabled_ = true; + }; + ObserverNode(const std::shared_ptr &observer, bool enabled) + : observer_(observer), enabled_(enabled){}; + }; + bool IsRegistered(const Observer &, const std::vector &); + std::recursive_mutex mutex_{}; + std::map> callbacks_; +}; + +template +std::vector CallbacksManager::AddObservers(const std::vector &keys, + const std::shared_ptr observer, + std::function &, const std::shared_ptr &observer, + std::vector &)> processOnFirstAdd) +{ + std::vector result; + std::vector firstRegisterKey; + { + std::lock_guard lck(mutex_); + for (auto &key : keys) { + std::vector> enabledObservers = GetEnabledObservers(key); + if (enabledObservers.size() == 0) { + callbacks_[key].emplace_back(ObserverNode(observer)); + firstRegisterKey.emplace_back(key); + continue; + } + if (IsRegistered(*observer, callbacks_[key])) { + result.emplace_back(static_cast(key), E_REGISTERED_REPEATED); + continue; + } + callbacks_[key].emplace_back(observer); + result.emplace_back(key, E_OK); + } + } + processOnFirstAdd(firstRegisterKey, observer, result); + return result; +} + +template +bool CallbacksManager::IsRegistered(const Observer &observer, const std::vector &observers) +{ + for (auto &item : observers) { + if (*(item.observer_) == observer) { + return true; + } + } + return false; +} + +template +std::vector CallbacksManager::DelObservers(const std::vector &keys, + const std::shared_ptr observer, std::function &, + const std::shared_ptr &, std::vector &)> processOnLastDel) +{ + std::vector result; + std::vector lastDelKeys; + { + std::lock_guard lck(mutex_); + if (keys.empty() && observer == nullptr) { + for (auto &it : callbacks_) { + lastDelKeys.emplace_back(it.first); + } + callbacks_.clear(); + } + for (auto &key : keys) { + auto it = callbacks_.find(key); + if (it == callbacks_.end()) { + result.emplace_back(key, E_UNREGISTERED_EMPTY); + continue; + } + if (observer == nullptr) { + callbacks_.erase(key); + lastDelKeys.emplace_back(key); + continue; + } + if (!IsRegistered(*observer, it->second)) { + result.emplace_back(key, E_UNREGISTERED_EMPTY); + continue; + } + std::vector &callbacks = it->second; + auto callbackIt = callbacks.begin(); + while (callbackIt != callbacks.end()) { + if (!(*(callbackIt->observer_) == *observer)) { + callbackIt++; + continue; + } + callbackIt = callbacks.erase(callbackIt); + } + if (!it->second.empty()) { + result.emplace_back(key, E_OK); + continue; + } + callbacks_.erase(key); + lastDelKeys.emplace_back(key); + } + if (lastDelKeys.empty()) { + return result; + } + } + processOnLastDel(lastDelKeys, observer, result); + return result; +} + +template +std::vector> CallbacksManager::GetEnabledObservers(const Key &inputKey) +{ + std::lock_guard lck(mutex_); + auto it = callbacks_.find(inputKey); + if (it == callbacks_.end()) { + return std::vector>(); + } + std::vector> results; + for (const auto &value : it->second) { + if (value.enabled_ && value.observer_ != nullptr) { + results.emplace_back(value.observer_); + } + } + return results; +} + +template +std::vector CallbacksManager::EnableObservers(const std::vector &keys, + std::function &, std::vector &)> processOnFirstEnabled) +{ + std::vector result; + std::vector firstRegisterKey; + { + std::lock_guard lck(mutex_); + for (auto &key : keys) { + auto it = callbacks_.find(key); + if (it == callbacks_.end()) { + result.emplace_back(key, E_SUBSCRIBER_NOT_EXIST); + continue; + } + std::vector> enabledObservers = GetEnabledObservers(key); + for (auto &item: callbacks_[key]) { + item.enabled_ = true; + } + if (!enabledObservers.empty()) { + result.emplace_back(key, E_OK); + continue; + } + firstRegisterKey.emplace_back(key); + } + } + processOnFirstEnabled(firstRegisterKey, result); + return result; +} + +template +std::vector CallbacksManager::DisableObservers(const std::vector &keys, + std::function &, std::vector &)> processOnLastDisable) +{ + std::vector result; + std::vector lastDisabledKeys; + { + std::lock_guard lck(mutex_); + for (auto &key : keys) { + auto it = callbacks_.find(key); + if (it == callbacks_.end()) { + result.emplace_back(key, E_SUBSCRIBER_NOT_EXIST); + continue; + } + std::vector> enabledObservers = GetEnabledObservers(key); + for (auto &item: callbacks_[key]) { + item.enabled_ = false; + } + if (enabledObservers.empty()) { + result.emplace_back(key, E_OK); + continue; + } + lastDisabledKeys.emplace_back(key); + } + } + processOnLastDisable(lastDisabledKeys, result); + return result; +} +template +int CallbacksManager::GetEnabledSubscriberSize() +{ + int count = 0; + std::lock_guard lck(mutex_); + for (auto &[key, value] : callbacks_) { + for (const auto &callback:value) { + if (callback.enabled_) { + count++; + } + } + } + return count; +} +} // namespace OHOS::DataShare +#endif // DATA_SHARE_CALLBACKS_MANAGER_H diff --git a/data_share/frameworks/native/common/include/datashare_abs_result_set.h b/data_share/frameworks/native/common/include/datashare_abs_result_set.h index 755f294a5492c5e63e8a300e914a601c481a37e4..8adebda8b097bc4a9287d6b076d5f26b453c7eeb 100644 --- a/data_share/frameworks/native/common/include/datashare_abs_result_set.h +++ b/data_share/frameworks/native/common/include/datashare_abs_result_set.h @@ -1,68 +1,68 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DATASHARE_ABS_RESULT_SET_H -#define DATASHARE_ABS_RESULT_SET_H - -#include -#include -#include "basic/result_set.h" - -namespace OHOS { -namespace DataShare { -class DataShareAbsResultSet : public ResultSet { -public: - DataShareAbsResultSet(); - virtual ~DataShareAbsResultSet(); - virtual int GetRowCount(int &count) override; - virtual int GetAllColumnNames(std::vector &columnNames) override; - virtual int GetBlob(int columnIndex, std::vector &blob) override; - virtual int GetString(int columnIndex, std::string &value) override; - virtual int GetInt(int columnIndex, int &value) override; - virtual int GetLong(int columnIndex, int64_t &value) override; - virtual int GetDouble(int columnIndex, double &value) override; - virtual int IsColumnNull(int columnIndex, bool &isNull) override; - virtual int GoToRow(int position) override; - virtual int GetDataType(int columnIndex, DataType &dataType) override; - int GetRowIndex(int &position) const override; - int GoTo(int offset) override; - int GoToFirstRow() override; - int GoToLastRow() override; - int GoToNextRow() override; - int GoToPreviousRow() override; - int IsAtFirstRow(bool &result) const override; - int IsAtLastRow(bool &result) override; - int IsStarted(bool &result) const override; - int IsEnded(bool &result) override; - int GetColumnCount(int &count) override; - int GetColumnIndex(const std::string &columnName, int &columnIndex) override; - int GetColumnName(int columnIndex, std::string &columnName) override; - bool IsClosed() const override; - int Close() override; - -protected: - // The default position of the result set - static const int INIT_POS = -1; - // Current row position - int rowPos_; - int count_; - // Indicates whether the result set is closed - bool isClosed_; - std::map indexCache_; -}; -} // namespace DataShare -} // namespace OHOS - -#endif +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DATASHARE_ABS_RESULT_SET_H +#define DATASHARE_ABS_RESULT_SET_H + +#include +#include +#include "basic/result_set.h" + +namespace OHOS { +namespace DataShare { +class DataShareAbsResultSet : public ResultSet { +public: + DataShareAbsResultSet(); + virtual ~DataShareAbsResultSet(); + virtual int GetRowCount(int &count) override; + virtual int GetAllColumnNames(std::vector &columnNames) override; + virtual int GetBlob(int columnIndex, std::vector &blob) override; + virtual int GetString(int columnIndex, std::string &value) override; + virtual int GetInt(int columnIndex, int &value) override; + virtual int GetLong(int columnIndex, int64_t &value) override; + virtual int GetDouble(int columnIndex, double &value) override; + virtual int IsColumnNull(int columnIndex, bool &isNull) override; + virtual int GoToRow(int position) override; + virtual int GetDataType(int columnIndex, DataType &dataType) override; + int GetRowIndex(int &position) const override; + int GoTo(int offset) override; + int GoToFirstRow() override; + int GoToLastRow() override; + int GoToNextRow() override; + int GoToPreviousRow() override; + int IsAtFirstRow(bool &result) const override; + int IsAtLastRow(bool &result) override; + int IsStarted(bool &result) const override; + int IsEnded(bool &result) override; + int GetColumnCount(int &count) override; + int GetColumnIndex(const std::string &columnName, int &columnIndex) override; + int GetColumnName(int columnIndex, std::string &columnName) override; + bool IsClosed() const override; + int Close() override; + +protected: + // The default position of the result set + static const int INIT_POS = -1; + // Current row position + int rowPos_; + int count_; + // Indicates whether the result set is closed + bool isClosed_; + std::map indexCache_; +}; +} // namespace DataShare +} // namespace OHOS + +#endif diff --git a/data_share/frameworks/native/common/include/datashare_block_writer_impl.h b/data_share/frameworks/native/common/include/datashare_block_writer_impl.h index 97b70c8f80efcdd19059a03ace123c3ea356e017..dbe2dea9e98a6b2b6785a84d1e7bde6ddfa75dec 100644 --- a/data_share/frameworks/native/common/include/datashare_block_writer_impl.h +++ b/data_share/frameworks/native/common/include/datashare_block_writer_impl.h @@ -1,100 +1,100 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DATASHARE_BLOCK_WRITER_IMPL_H -#define DATASHARE_BLOCK_WRITER_IMPL_H - -#include "shared_block.h" -#include "result_set_bridge.h" -#include "datashare_errno.h" - -namespace OHOS { -namespace DataShare { -/** - * This class stores a set of rows from a database in a buffer, - * which is used as the set of query result. - */ -class DataShareBlockWriterImpl : public virtual ResultSetBridge::Writer { -public: - /** - * SharedBlock constructor. - */ - DataShareBlockWriterImpl(); - - /** - * SharedBlock constructor. - */ - DataShareBlockWriterImpl(const std::string &name, size_t size); - - /** - * SharedBlock Deconstruction. - */ - virtual ~DataShareBlockWriterImpl(); - - /** - * Allocate a row unit and its directory. - */ - int AllocRow() override; - - /** - * Write Null data to the shared block. - */ - virtual int Write(uint32_t column) override; - - /** - * Write long data to the shared block. - */ - virtual int Write(uint32_t column, int64_t value) override; - - /** - * Write Double data to the shared block. - */ - virtual int Write(uint32_t column, double value) override; - - /** - * Write blob data to the shared block. - */ - virtual int Write(uint32_t column, const uint8_t *value, size_t Size) override; - - /** - * Write string data to the shared block. - */ - virtual int Write(uint32_t column, const char *value, size_t sizeIncludingNull) override; - - /** - * Get Block - */ - AppDataFwk::SharedBlock *GetBlock() const; - -private: - /** - * The fd of shared memory - */ - bool GetCurrentRowIndex(uint32_t &rowIndex); - - /** - * Convert ShareBlock error code to DataShare format - */ - int ConvertErrorCode(int shareBlockErr) - { - return shareBlockErr == AppDataFwk::SharedBlock::SHARED_BLOCK_OK ? E_OK : E_ERROR; - } - -private: - AppDataFwk::SharedBlock *shareBlock_; -}; -} // namespace DataShare -} // namespace OHOS -#endif +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DATASHARE_BLOCK_WRITER_IMPL_H +#define DATASHARE_BLOCK_WRITER_IMPL_H + +#include "shared_block.h" +#include "result_set_bridge.h" +#include "datashare_errno.h" + +namespace OHOS { +namespace DataShare { +/** + * This class stores a set of rows from a database in a buffer, + * which is used as the set of query result. + */ +class DataShareBlockWriterImpl : public virtual ResultSetBridge::Writer { +public: + /** + * SharedBlock constructor. + */ + DataShareBlockWriterImpl(); + + /** + * SharedBlock constructor. + */ + DataShareBlockWriterImpl(const std::string &name, size_t size); + + /** + * SharedBlock Deconstruction. + */ + virtual ~DataShareBlockWriterImpl(); + + /** + * Allocate a row unit and its directory. + */ + int AllocRow() override; + + /** + * Write Null data to the shared block. + */ + virtual int Write(uint32_t column) override; + + /** + * Write long data to the shared block. + */ + virtual int Write(uint32_t column, int64_t value) override; + + /** + * Write Double data to the shared block. + */ + virtual int Write(uint32_t column, double value) override; + + /** + * Write blob data to the shared block. + */ + virtual int Write(uint32_t column, const uint8_t *value, size_t Size) override; + + /** + * Write string data to the shared block. + */ + virtual int Write(uint32_t column, const char *value, size_t sizeIncludingNull) override; + + /** + * Get Block + */ + AppDataFwk::SharedBlock *GetBlock() const; + +private: + /** + * The fd of shared memory + */ + bool GetCurrentRowIndex(uint32_t &rowIndex); + + /** + * Convert ShareBlock error code to DataShare format + */ + int ConvertErrorCode(int shareBlockErr) + { + return shareBlockErr == AppDataFwk::SharedBlock::SHARED_BLOCK_OK ? E_OK : E_ERROR; + } + +private: + AppDataFwk::SharedBlock *shareBlock_; +}; +} // namespace DataShare +} // namespace OHOS +#endif diff --git a/data_share/frameworks/native/common/include/datashare_itypes_utils.h b/data_share/frameworks/native/common/include/datashare_itypes_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..25e27ebc45b20fc2c27ed0cd18a57b18bdaa3046 --- /dev/null +++ b/data_share/frameworks/native/common/include/datashare_itypes_utils.h @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DATASHARE_COMMON_ITYPES_UTIL_H +#define DATASHARE_COMMON_ITYPES_UTIL_H + +#include "datashare_predicates.h" +#include "datashare_template.h" +#include "datashare_values_bucket.h" +#include "itypes_util.h" +#include "uri.h" + +namespace OHOS::ITypesUtil { +using Predicates = DataShare::DataSharePredicates; +using Operation = DataShare::OperationItem; +using PublishedDataItem = DataShare::PublishedDataItem; +using Data = DataShare::Data; +using TemplateId = DataShare::TemplateId; +using PredicateTemplateNode = DataShare::PredicateTemplateNode; +using RdbChangeNode = DataShare::RdbChangeNode; +using PublishedDataChangeNode = DataShare::PublishedDataChangeNode; +using OperationResult = DataShare::OperationResult; +using DataShareValuesBucket = DataShare::DataShareValuesBucket; +using AshmemNode = DataShare::AshmemNode; + + +template<> +bool Marshalling(const Predicates &bucket, MessageParcel &parcel); + +template<> +bool Unmarshalling(Predicates &predicates, MessageParcel &parcel); + +template<> +bool Marshalling(const Operation &operation, MessageParcel &parcel); + +template<> +bool Unmarshalling(Operation &operation, MessageParcel &parcel); + +template<> +bool Unmarshalling(PublishedDataItem &dataItem, MessageParcel &parcel); + +template<> +bool Unmarshalling(PublishedDataItem &dataItem, MessageParcel &parcel); + +template<> +bool Marshalling(const PublishedDataItem &templateId, MessageParcel &parcel); + +template<> +bool Marshalling(const Data &data, MessageParcel &parcel); + +template<> +bool Unmarshalling(Data &data, MessageParcel &parcel); + +template<> +bool Marshalling(const DataShareValuesBucket &bucket, MessageParcel &parcel); + +template<> +bool Unmarshalling(DataShareValuesBucket &bucket, MessageParcel &parcel); + +template<> +bool Marshalling(const AshmemNode &node, MessageParcel &parcel); + +template<> +bool Unmarshalling(AshmemNode &node, MessageParcel &parcel); + +template<> +bool Marshalling(const Uri &node, MessageParcel &parcel); + +template<> +bool Unmarshalling(Uri &node, MessageParcel &parcel); + +template<> +bool Unmarshalling(TemplateId &templateId, MessageParcel &parcel); + +template<> +bool Marshalling(const PredicateTemplateNode &predicateTemplateNode, MessageParcel &parcel); + +template<> +bool Unmarshalling(PredicateTemplateNode &predicateTemplateNode, MessageParcel &parcel); + +template<> +bool Marshalling(const RdbChangeNode &changeNode, MessageParcel &parcel); + +template<> +bool Unmarshalling(RdbChangeNode &changeNode, MessageParcel &parcel); + +template<> +bool Marshalling(const PublishedDataChangeNode &changeNode, MessageParcel &parcel); + +template<> +bool Unmarshalling(PublishedDataChangeNode &changeNode, MessageParcel &parcel); + +template<> +bool Marshalling(const OperationResult &operationResult, MessageParcel &parcel); + +template<> +bool Unmarshalling(OperationResult &predicateTemplateNode, MessageParcel &parcel); + +template<> +bool Marshalling(const TemplateId &changeNode, MessageParcel &parcel); +} +#endif diff --git a/data_share/frameworks/native/common/include/datashare_shared_result_set.h b/data_share/frameworks/native/common/include/datashare_shared_result_set.h index c8a5fc6fd3fdc36439434760fe6761bf98b48ff4..1128164ac34d16b3296ff0fff41faae277d79d74 100644 --- a/data_share/frameworks/native/common/include/datashare_shared_result_set.h +++ b/data_share/frameworks/native/common/include/datashare_shared_result_set.h @@ -1,44 +1,44 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DATASHARE_SHARED_RESULT_SET_H -#define DATASHARE_SHARED_RESULT_SET_H - -#include -#include "shared_block.h" - -namespace OHOS { -namespace DataShare { -class DataShareSharedResultSet { -public: - DataShareSharedResultSet() {} - ~DataShareSharedResultSet() {} - /** - * Obtains a block from the {@link SharedResultSet} - */ - virtual AppDataFwk::SharedBlock *GetBlock() const = 0; - /** - * Adds the data of a {@code SharedResultSet} to a {@link SharedBlock} - */ - virtual void FillBlock(int startRowIndex, AppDataFwk::SharedBlock *block) = 0; - /** - * Called when the position of the result set changes - */ - virtual bool OnGo(int oldRowIndex, int newRowIndex, int *cachedIndex) = 0; -}; -} // namespace DataShare -} // namespace OHOS - +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DATASHARE_SHARED_RESULT_SET_H +#define DATASHARE_SHARED_RESULT_SET_H + +#include +#include "shared_block.h" + +namespace OHOS { +namespace DataShare { +class DataShareSharedResultSet { +public: + DataShareSharedResultSet() {} + ~DataShareSharedResultSet() {} + /** + * Obtains a block from the {@link SharedResultSet} + */ + virtual AppDataFwk::SharedBlock *GetBlock() const = 0; + /** + * Adds the data of a {@code SharedResultSet} to a {@link SharedBlock} + */ + virtual void FillBlock(int startRowIndex, AppDataFwk::SharedBlock *block) = 0; + /** + * Called when the position of the result set changes + */ + virtual bool OnGo(int oldRowIndex, int newRowIndex, int *cachedIndex) = 0; +}; +} // namespace DataShare +} // namespace OHOS + #endif \ No newline at end of file diff --git a/data_share/frameworks/native/common/include/datashare_string_utils.h b/data_share/frameworks/native/common/include/datashare_string_utils.h index 6aa6ec923623e825fe14e6c3fac98fb480ab70f2..82b377282255798c769504cfcd8a9ced0723c3d9 100644 --- a/data_share/frameworks/native/common/include/datashare_string_utils.h +++ b/data_share/frameworks/native/common/include/datashare_string_utils.h @@ -1,38 +1,38 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DATASHARE_STRINGUTILS_H -#define DATASHARE_STRINGUTILS_H - - -#include -#include - -namespace OHOS { -namespace DataShare { -class DataShareStringUtils { -public: - static std::string SurroundWithQuote(std::string value, std::string quote); - static std::string SurroundWithFunction(std::string function, std::string separator, - std::vector array); - -private: - DataShareStringUtils(); - ~DataShareStringUtils(); -}; -} // namespace DataShare -} // namespace OHOS - +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DATASHARE_STRINGUTILS_H +#define DATASHARE_STRINGUTILS_H + + +#include +#include + +namespace OHOS { +namespace DataShare { +class DataShareStringUtils { +public: + static std::string SurroundWithQuote(std::string value, std::string quote); + static std::string SurroundWithFunction(std::string function, std::string separator, + std::vector array); + +private: + DataShareStringUtils(); + ~DataShareStringUtils(); +}; +} // namespace DataShare +} // namespace OHOS + #endif \ No newline at end of file diff --git a/data_share/frameworks/native/common/include/shared_block.h b/data_share/frameworks/native/common/include/shared_block.h index 1230171c00e05fb17989e153451dc6f3fb6f7953..6c872f4697d4c857a0676b02e3ccdf2166fc5aee 100644 --- a/data_share/frameworks/native/common/include/shared_block.h +++ b/data_share/frameworks/native/common/include/shared_block.h @@ -1,330 +1,330 @@ -/* - * 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 SHARED_BLOCK_H -#define SHARED_BLOCK_H - -#include - -#include -#include -#include "message_parcel.h" -#include "parcel.h" -#include "securec.h" - -namespace OHOS { -namespace AppDataFwk { -static const uint32_t INVALID_ROW_RECORD = 0xFFFFFFFF; -/** - * This class stores a set of rows from a database in a buffer, - * which is used as the set of query result. - */ -class SharedBlock { -public: - /* Cell Unit types. */ - enum { - CELL_UNIT_TYPE_NULL = 0, - CELL_UNIT_TYPE_INTEGER = 1, - CELL_UNIT_TYPE_FLOAT = 2, - CELL_UNIT_TYPE_STRING = 3, - CELL_UNIT_TYPE_BLOB = 4, - }; - - /* SharedBlock error types. */ - enum { - SHARED_BLOCK_OK = 0, - SHARED_BLOCK_BAD_VALUE = 1, - SHARED_BLOCK_NO_MEMORY = 2, - SHARED_BLOCK_INVALID_OPERATION = 3, - SHARED_BLOCK_ASHMEM_ERROR = 4, - SHARED_BLOCK_SET_PORT_ERROR = 5, - }; - - /* Cell Unit */ - struct CellUnit { - int32_t type; - union { - double doubleValue; - int64_t longValue; - struct { - uint32_t offset; - uint32_t size; - } stringOrBlobValue; - } cell; - } __attribute((packed)); - - /** - * SharedBlock constructor. - */ - SharedBlock(const std::string &name, sptr ashmem, size_t size, bool readOnly); - - /** - * SharedBlock constructor. - */ - ~SharedBlock(); - - /** - * Init current shared block. - */ - bool Init(); - - /** - * Create a shared block. - */ - static int Create(const std::string &name, size_t size, SharedBlock *&outSharedBlock); - - /** - * Clear current shared block. - */ - int Clear(); - - /** - * Set a shared block column. - */ - int SetColumnNum(uint32_t numColumns); - - /** - * Allocate a row unit and its directory. - */ - int AllocRow(); - - /** - * Release the value of the last row. - */ - int FreeLastRow(); - - /** - * Put blob data to the shared block. - */ - int PutBlob(uint32_t row, uint32_t column, const void *value, size_t Size); - - /** - * Put string data to the shared block. - */ - int PutString(uint32_t row, uint32_t column, const char *value, size_t sizeIncludingNull); - - /** - * Put long data to the shared block. - */ - int PutLong(uint32_t row, uint32_t column, int64_t value); - - /** - * Put Double data to the shared block. - */ - int PutDouble(uint32_t row, uint32_t column, double value); - - /** - * Put Null data to the shared block. - */ - int PutNull(uint32_t row, uint32_t column); - - /** - * Gets the cell unit at the specified row and column. - */ - CellUnit *GetCellUnit(uint32_t row, uint32_t column); - - /** - * Get string type data from cell unit. - */ - const char *GetCellUnitValueString(CellUnit *cellUnit, size_t *outSizeIncludingNull) - { - *outSizeIncludingNull = cellUnit->cell.stringOrBlobValue.size; - return static_cast( - OffsetToPtr(cellUnit->cell.stringOrBlobValue.offset, cellUnit->cell.stringOrBlobValue.size)); - } - - /** - * Get blob type data from cell unit. - */ - const void *GetCellUnitValueBlob(CellUnit *cellUnit, size_t *outSize) - { - *outSize = cellUnit->cell.stringOrBlobValue.size; - return OffsetToPtr(cellUnit->cell.stringOrBlobValue.offset, cellUnit->cell.stringOrBlobValue.size); - } - - /** - * The mHeader of the current result set. - */ - const void *GetHeader() - { - return mHeader; - } - - /** - * Size of the used byte in the block. - */ - size_t GetUsedBytes() - { - return mHeader->unusedOffset; - } - - /** - * The name of the current result set. - */ - std::string Name() - { - return mName; - } - - /** - * The size of the current result set. - */ - size_t Size() - { - return mSize; - } - - /** - * The row number of the current result set. - */ - uint32_t GetRowNum() - { - return mHeader->rowNums; - } - - /** - * The column number of the current result set. - */ - uint32_t GetColumnNum() - { - return mHeader->columnNums; - } - - int WriteMessageParcel(MessageParcel &parcel); - - static int ReadMessageParcel(MessageParcel &parcel, SharedBlock *&block); - /** - * Write raw data in block. - */ - size_t SetRawData(const void *rawData, size_t size); - /** - * The fd of shared memory - */ - int GetFd() - { - if (ashmem_ == nullptr) { - return -1; - } - return ashmem_->GetAshmemFd(); - } - - uint32_t GetStartPos() - { - return mHeader->startPos_; - } - - uint32_t GetLastPos() - { - return mHeader->lastPos_; - } - - uint32_t GetBlockPos() - { - return mHeader->blockPos_; - } - - void SetStartPos(uint32_t startPos) - { - mHeader->startPos_ = startPos; - } - - void SetLastPos(uint32_t lastPos) - { - mHeader->lastPos_ = lastPos; - } - - void SetBlockPos(uint32_t blockPos) - { - mHeader->blockPos_ = blockPos; - } - -private: - std::string mName; - sptr ashmem_; - void *mData; - size_t mSize; - bool mReadOnly; - static const size_t ROW_OFFSETS_NUM = 100; - /** - * Default setting for SQLITE_MAX_COLUMN is 2000. - * We can set it at compile time to as large as 32767 - */ - static const size_t COL_MAX_NUM = 32767; - - struct SharedBlockHeader { - /* Offset of the lowest unused byte in the block. */ - uint32_t unusedOffset; - /* Offset of the first row group. */ - uint32_t firstRowGroupOffset; - /* Row numbers of the row group block. */ - uint32_t rowNums; - /* Column numbers of the row group block. */ - uint32_t columnNums; - /* start position of the current block. */ - uint32_t startPos_; - /* last position of the current block. */ - uint32_t lastPos_; - /* current position of the current block. */ - uint32_t blockPos_; - }; - - struct RowGroupHeader { - uint32_t rowOffsets[ROW_OFFSETS_NUM]; - uint32_t nextGroupOffset; - }; - - SharedBlockHeader *mHeader; - - /** - * Allocate a portion of the block. Returns the offset of the allocation. - * Returns 0 if there isn't enough space. - */ - uint32_t Alloc(size_t size, bool aligned = false); - - inline uint32_t *GetRowOffset(uint32_t row); - - uint32_t *AllocRowOffset(); - - int PutBlobOrString(uint32_t row, uint32_t column, const void *value, size_t size, int32_t type); - - static int CreateSharedBlock(const std::string &name, size_t size, sptr ashmem, - SharedBlock *&outSharedBlock); - - uint32_t OffsetFromPtr(void *ptr); - - inline void *OffsetToPtr(uint32_t offset, uint32_t bufferSize = 0) - { - if (offset >= mSize) { - return nullptr; - } - if (offset + bufferSize > mSize) { - return nullptr; - } - return static_cast(mData) + offset; - } - - /** - * Convert utf8 string to utf16. - */ - static std::u16string ToUtf16(const std::string& str); - - /** - * Convert utf16 string to utf8. - */ - static std::string ToUtf8(const std::u16string& str16); -}; -} // namespace AppDataFwk -} // namespace OHOS -#endif +/* + * 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 SHARED_BLOCK_H +#define SHARED_BLOCK_H + +#include + +#include +#include +#include "message_parcel.h" +#include "parcel.h" +#include "securec.h" + +namespace OHOS { +namespace AppDataFwk { +static const uint32_t INVALID_ROW_RECORD = 0xFFFFFFFF; +/** + * This class stores a set of rows from a database in a buffer, + * which is used as the set of query result. + */ +class SharedBlock { +public: + /* Cell Unit types. */ + enum { + CELL_UNIT_TYPE_NULL = 0, + CELL_UNIT_TYPE_INTEGER = 1, + CELL_UNIT_TYPE_FLOAT = 2, + CELL_UNIT_TYPE_STRING = 3, + CELL_UNIT_TYPE_BLOB = 4, + }; + + /* SharedBlock error types. */ + enum { + SHARED_BLOCK_OK = 0, + SHARED_BLOCK_BAD_VALUE = 1, + SHARED_BLOCK_NO_MEMORY = 2, + SHARED_BLOCK_INVALID_OPERATION = 3, + SHARED_BLOCK_ASHMEM_ERROR = 4, + SHARED_BLOCK_SET_PORT_ERROR = 5, + }; + + /* Cell Unit */ + struct CellUnit { + int32_t type; + union { + double doubleValue; + int64_t longValue; + struct { + uint32_t offset; + uint32_t size; + } stringOrBlobValue; + } cell; + } __attribute((packed)); + + /** + * SharedBlock constructor. + */ + SharedBlock(const std::string &name, sptr ashmem, size_t size, bool readOnly); + + /** + * SharedBlock constructor. + */ + ~SharedBlock(); + + /** + * Init current shared block. + */ + bool Init(); + + /** + * Create a shared block. + */ + static int Create(const std::string &name, size_t size, SharedBlock *&outSharedBlock); + + /** + * Clear current shared block. + */ + int Clear(); + + /** + * Set a shared block column. + */ + int SetColumnNum(uint32_t numColumns); + + /** + * Allocate a row unit and its directory. + */ + int AllocRow(); + + /** + * Release the value of the last row. + */ + int FreeLastRow(); + + /** + * Put blob data to the shared block. + */ + int PutBlob(uint32_t row, uint32_t column, const void *value, size_t Size); + + /** + * Put string data to the shared block. + */ + int PutString(uint32_t row, uint32_t column, const char *value, size_t sizeIncludingNull); + + /** + * Put long data to the shared block. + */ + int PutLong(uint32_t row, uint32_t column, int64_t value); + + /** + * Put Double data to the shared block. + */ + int PutDouble(uint32_t row, uint32_t column, double value); + + /** + * Put Null data to the shared block. + */ + int PutNull(uint32_t row, uint32_t column); + + /** + * Gets the cell unit at the specified row and column. + */ + CellUnit *GetCellUnit(uint32_t row, uint32_t column); + + /** + * Get string type data from cell unit. + */ + const char *GetCellUnitValueString(CellUnit *cellUnit, size_t *outSizeIncludingNull) + { + *outSizeIncludingNull = cellUnit->cell.stringOrBlobValue.size; + return static_cast( + OffsetToPtr(cellUnit->cell.stringOrBlobValue.offset, cellUnit->cell.stringOrBlobValue.size)); + } + + /** + * Get blob type data from cell unit. + */ + const void *GetCellUnitValueBlob(CellUnit *cellUnit, size_t *outSize) + { + *outSize = cellUnit->cell.stringOrBlobValue.size; + return OffsetToPtr(cellUnit->cell.stringOrBlobValue.offset, cellUnit->cell.stringOrBlobValue.size); + } + + /** + * The mHeader of the current result set. + */ + const void *GetHeader() + { + return mHeader; + } + + /** + * Size of the used byte in the block. + */ + size_t GetUsedBytes() + { + return mHeader->unusedOffset; + } + + /** + * The name of the current result set. + */ + std::string Name() + { + return mName; + } + + /** + * The size of the current result set. + */ + size_t Size() + { + return mSize; + } + + /** + * The row number of the current result set. + */ + uint32_t GetRowNum() + { + return mHeader->rowNums; + } + + /** + * The column number of the current result set. + */ + uint32_t GetColumnNum() + { + return mHeader->columnNums; + } + + int WriteMessageParcel(MessageParcel &parcel); + + static int ReadMessageParcel(MessageParcel &parcel, SharedBlock *&block); + /** + * Write raw data in block. + */ + size_t SetRawData(const void *rawData, size_t size); + /** + * The fd of shared memory + */ + int GetFd() + { + if (ashmem_ == nullptr) { + return -1; + } + return ashmem_->GetAshmemFd(); + } + + uint32_t GetStartPos() + { + return mHeader->startPos_; + } + + uint32_t GetLastPos() + { + return mHeader->lastPos_; + } + + uint32_t GetBlockPos() + { + return mHeader->blockPos_; + } + + void SetStartPos(uint32_t startPos) + { + mHeader->startPos_ = startPos; + } + + void SetLastPos(uint32_t lastPos) + { + mHeader->lastPos_ = lastPos; + } + + void SetBlockPos(uint32_t blockPos) + { + mHeader->blockPos_ = blockPos; + } + +private: + std::string mName; + sptr ashmem_; + void *mData; + size_t mSize; + bool mReadOnly; + static const size_t ROW_OFFSETS_NUM = 100; + /** + * Default setting for SQLITE_MAX_COLUMN is 2000. + * We can set it at compile time to as large as 32767 + */ + static const size_t COL_MAX_NUM = 32767; + + struct SharedBlockHeader { + /* Offset of the lowest unused byte in the block. */ + uint32_t unusedOffset; + /* Offset of the first row group. */ + uint32_t firstRowGroupOffset; + /* Row numbers of the row group block. */ + uint32_t rowNums; + /* Column numbers of the row group block. */ + uint32_t columnNums; + /* start position of the current block. */ + uint32_t startPos_; + /* last position of the current block. */ + uint32_t lastPos_; + /* current position of the current block. */ + uint32_t blockPos_; + }; + + struct RowGroupHeader { + uint32_t rowOffsets[ROW_OFFSETS_NUM]; + uint32_t nextGroupOffset; + }; + + SharedBlockHeader *mHeader; + + /** + * Allocate a portion of the block. Returns the offset of the allocation. + * Returns 0 if there isn't enough space. + */ + uint32_t Alloc(size_t size, bool aligned = false); + + inline uint32_t *GetRowOffset(uint32_t row); + + uint32_t *AllocRowOffset(); + + int PutBlobOrString(uint32_t row, uint32_t column, const void *value, size_t size, int32_t type); + + static int CreateSharedBlock(const std::string &name, size_t size, sptr ashmem, + SharedBlock *&outSharedBlock); + + uint32_t OffsetFromPtr(void *ptr); + + inline void *OffsetToPtr(uint32_t offset, uint32_t bufferSize = 0) + { + if (offset >= mSize) { + return nullptr; + } + if (offset + bufferSize > mSize) { + return nullptr; + } + return static_cast(mData) + offset; + } + + /** + * Convert utf8 string to utf16. + */ + static std::u16string ToUtf16(const std::string& str); + + /** + * Convert utf16 string to utf8. + */ + static std::string ToUtf8(const std::u16string& str16); +}; +} // namespace AppDataFwk +} // namespace OHOS +#endif diff --git a/data_share/frameworks/native/common/src/datashare_abs_result_set.cpp b/data_share/frameworks/native/common/src/datashare_abs_result_set.cpp index d006905e9597ab2e253c02f1a0040eed2e49a67b..e2795c932e8fe3dfc2c55d6afd806dfc6b3cd072 100644 --- a/data_share/frameworks/native/common/src/datashare_abs_result_set.cpp +++ b/data_share/frameworks/native/common/src/datashare_abs_result_set.cpp @@ -1,253 +1,253 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#define LOG_TAG "DataShareAbsResultSet" -#include "datashare_abs_result_set.h" - -#include -#include - -#include "adaptor.h" -#include "datashare_errno.h" -#include "datashare_log.h" - -namespace OHOS { -namespace DataShare { -DataShareAbsResultSet::DataShareAbsResultSet() : rowPos_(INIT_POS), count_(-1), isClosed_(false) -{} - -DataShareAbsResultSet::~DataShareAbsResultSet() {} - -int DataShareAbsResultSet::GetRowCount(int &count) -{ - return E_OK; -} - -int DataShareAbsResultSet::GetAllColumnNames(std::vector &columnNames) -{ - return E_OK; -} - -int DataShareAbsResultSet::GetBlob(int columnIndex, std::vector &blob) -{ - return E_OK; -} - -int DataShareAbsResultSet::GetString(int columnIndex, std::string &value) -{ - return E_OK; -} - -int DataShareAbsResultSet::GetInt(int columnIndex, int &value) -{ - return E_OK; -} - -int DataShareAbsResultSet::GetLong(int columnIndex, int64_t &value) -{ - return E_OK; -} - -int DataShareAbsResultSet::GetDouble(int columnIndex, double &value) -{ - return E_OK; -} - -int DataShareAbsResultSet::IsColumnNull(int columnIndex, bool &isNull) -{ - return E_OK; -} - -int DataShareAbsResultSet::GoToRow(int position) -{ - return E_OK; -} - -int DataShareAbsResultSet::GetDataType(int columnIndex, DataType &dataType) -{ - return E_OK; -} - -int DataShareAbsResultSet::GetRowIndex(int &position) const -{ - position = rowPos_; - return E_OK; -} - -int DataShareAbsResultSet::GoTo(int offset) -{ - int ret = GoToRow(rowPos_ + offset); - if (ret != E_OK) { - LOG_WARN("return GoTo ret is wrong!"); - } - return ret; -} - -int DataShareAbsResultSet::GoToFirstRow() -{ - DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); - int ret = GoToRow(0); - if (ret != E_OK) { - LOG_WARN("return GoToFirstRow ret is wrong!"); - } - return ret; -} - -int DataShareAbsResultSet::GoToLastRow() -{ - int rowCnt = 0; - int ret = GetRowCount(rowCnt); - if (ret != E_OK) { - LOG_WARN("return GoToLastRow.GetRowCount ret is wrong!"); - return ret; - } - - ret = GoToRow(rowCnt - 1); - if (ret != E_OK) { - LOG_WARN("return GoToLastRow.GoToRow ret is wrong!"); - } - return ret; -} - -int DataShareAbsResultSet::GoToNextRow() -{ - int ret = GoToRow(rowPos_ + 1); - if (ret != E_OK) { - LOG_WARN("return GoToNextRow ret is wrong!"); - } - return ret; -} - -int DataShareAbsResultSet::GoToPreviousRow() -{ - int ret = GoToRow(rowPos_ - 1); - if (ret != E_OK) { - LOG_WARN("return GoToPreviousRow ret is wrong!"); - } - return ret; -} - -int DataShareAbsResultSet::IsAtFirstRow(bool &result) const -{ - result = (rowPos_ == 0); - return E_OK; -} - -int DataShareAbsResultSet::IsAtLastRow(bool &result) -{ - int rowCnt = 0; - int ret = GetRowCount(rowCnt); - if (ret != E_OK) { - LOG_ERROR("return GetRowCount ret is wrong!"); - return ret; - } - result = (rowPos_ == (rowCnt - 1)); - return E_OK; -} - -int DataShareAbsResultSet::IsStarted(bool &result) const -{ - result = (rowPos_ != INIT_POS); - return E_OK; -} - -int DataShareAbsResultSet::IsEnded(bool &result) -{ - int rowCnt = 0; - int ret = GetRowCount(rowCnt); - if (ret != E_OK) { - LOG_ERROR("return GetRowCount ret is wrong!"); - return ret; - } - result = (rowCnt == 0) ? true : (rowPos_ == rowCnt); - return E_OK; -} - -int DataShareAbsResultSet::GetColumnCount(int &count) -{ - if (count_ == -1) { - std::vector columnNames; - int ret = GetAllColumnNames(columnNames); - if (ret != E_OK) { - LOG_ERROR("return GetAllColumnNames ret is wrong!"); - return ret; - } - count_ = static_cast(columnNames.size()); - } - count = count_; - return E_OK; -} - -int DataShareAbsResultSet::GetColumnIndex(const std::string &columnName, int &columnIndex) -{ - if (indexCache_.find(columnName) != indexCache_.end()) { - columnIndex = indexCache_[columnName]; - return E_OK; - } - auto periodIndex = columnName.rfind('.'); - std::string columnNameLower = columnName; - if (periodIndex != std::string::npos) { - columnNameLower = columnNameLower.substr(periodIndex + 1); - } - transform(columnNameLower.begin(), columnNameLower.end(), columnNameLower.begin(), ::tolower); - std::vector columnNames; - int ret = GetAllColumnNames(columnNames); - if (ret != E_OK) { - LOG_ERROR("return GetAllColumnNames ret is wrong!"); - return ret; - } - - columnIndex = 0; - for (const auto& name : columnNames) { - std::string lowerName = name; - transform(name.begin(), name.end(), lowerName.begin(), ::tolower); - if (lowerName == columnNameLower) { - indexCache_[columnName] = columnIndex; - return E_OK; - } - columnIndex++; - } - columnIndex = -1; - return E_ERROR; -} - -int DataShareAbsResultSet::GetColumnName(int columnIndex, std::string &columnName) -{ - int rowCnt = 0; - int ret = GetColumnCount(rowCnt); - if (ret != E_OK) { - LOG_ERROR("return GetColumnCount ret is wrong!"); - return ret; - } - if (columnIndex >= rowCnt || columnIndex < 0) { - return E_INVALID_COLUMN_INDEX; - } - std::vector columnNames; - GetAllColumnNames(columnNames); - columnName = columnNames[columnIndex]; - return E_OK; -} - -bool DataShareAbsResultSet::IsClosed() const -{ - return isClosed_; -} - -int DataShareAbsResultSet::Close() -{ - isClosed_ = true; - return E_OK; -} -} // namespace DataShare +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#define LOG_TAG "DataShareAbsResultSet" +#include "datashare_abs_result_set.h" + +#include +#include + +#include "adaptor.h" +#include "datashare_errno.h" +#include "datashare_log.h" + +namespace OHOS { +namespace DataShare { +DataShareAbsResultSet::DataShareAbsResultSet() : rowPos_(INIT_POS), count_(-1), isClosed_(false) +{} + +DataShareAbsResultSet::~DataShareAbsResultSet() {} + +int DataShareAbsResultSet::GetRowCount(int &count) +{ + return E_OK; +} + +int DataShareAbsResultSet::GetAllColumnNames(std::vector &columnNames) +{ + return E_OK; +} + +int DataShareAbsResultSet::GetBlob(int columnIndex, std::vector &blob) +{ + return E_OK; +} + +int DataShareAbsResultSet::GetString(int columnIndex, std::string &value) +{ + return E_OK; +} + +int DataShareAbsResultSet::GetInt(int columnIndex, int &value) +{ + return E_OK; +} + +int DataShareAbsResultSet::GetLong(int columnIndex, int64_t &value) +{ + return E_OK; +} + +int DataShareAbsResultSet::GetDouble(int columnIndex, double &value) +{ + return E_OK; +} + +int DataShareAbsResultSet::IsColumnNull(int columnIndex, bool &isNull) +{ + return E_OK; +} + +int DataShareAbsResultSet::GoToRow(int position) +{ + return E_OK; +} + +int DataShareAbsResultSet::GetDataType(int columnIndex, DataType &dataType) +{ + return E_OK; +} + +int DataShareAbsResultSet::GetRowIndex(int &position) const +{ + position = rowPos_; + return E_OK; +} + +int DataShareAbsResultSet::GoTo(int offset) +{ + int ret = GoToRow(rowPos_ + offset); + if (ret != E_OK) { + LOG_WARN("return GoTo ret is wrong!"); + } + return ret; +} + +int DataShareAbsResultSet::GoToFirstRow() +{ + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); + int ret = GoToRow(0); + if (ret != E_OK) { + LOG_WARN("return GoToFirstRow ret is wrong!"); + } + return ret; +} + +int DataShareAbsResultSet::GoToLastRow() +{ + int rowCnt = 0; + int ret = GetRowCount(rowCnt); + if (ret != E_OK) { + LOG_WARN("return GoToLastRow.GetRowCount ret is wrong!"); + return ret; + } + + ret = GoToRow(rowCnt - 1); + if (ret != E_OK) { + LOG_WARN("return GoToLastRow.GoToRow ret is wrong!"); + } + return ret; +} + +int DataShareAbsResultSet::GoToNextRow() +{ + int ret = GoToRow(rowPos_ + 1); + if (ret != E_OK) { + LOG_WARN("return GoToNextRow ret is wrong!"); + } + return ret; +} + +int DataShareAbsResultSet::GoToPreviousRow() +{ + int ret = GoToRow(rowPos_ - 1); + if (ret != E_OK) { + LOG_WARN("return GoToPreviousRow ret is wrong!"); + } + return ret; +} + +int DataShareAbsResultSet::IsAtFirstRow(bool &result) const +{ + result = (rowPos_ == 0); + return E_OK; +} + +int DataShareAbsResultSet::IsAtLastRow(bool &result) +{ + int rowCnt = 0; + int ret = GetRowCount(rowCnt); + if (ret != E_OK) { + LOG_ERROR("return GetRowCount ret is wrong!"); + return ret; + } + result = (rowPos_ == (rowCnt - 1)); + return E_OK; +} + +int DataShareAbsResultSet::IsStarted(bool &result) const +{ + result = (rowPos_ != INIT_POS); + return E_OK; +} + +int DataShareAbsResultSet::IsEnded(bool &result) +{ + int rowCnt = 0; + int ret = GetRowCount(rowCnt); + if (ret != E_OK) { + LOG_ERROR("return GetRowCount ret is wrong!"); + return ret; + } + result = (rowCnt == 0) ? true : (rowPos_ == rowCnt); + return E_OK; +} + +int DataShareAbsResultSet::GetColumnCount(int &count) +{ + if (count_ == -1) { + std::vector columnNames; + int ret = GetAllColumnNames(columnNames); + if (ret != E_OK) { + LOG_ERROR("return GetAllColumnNames ret is wrong!"); + return ret; + } + count_ = static_cast(columnNames.size()); + } + count = count_; + return E_OK; +} + +int DataShareAbsResultSet::GetColumnIndex(const std::string &columnName, int &columnIndex) +{ + if (indexCache_.find(columnName) != indexCache_.end()) { + columnIndex = indexCache_[columnName]; + return E_OK; + } + auto periodIndex = columnName.rfind('.'); + std::string columnNameLower = columnName; + if (periodIndex != std::string::npos) { + columnNameLower = columnNameLower.substr(periodIndex + 1); + } + transform(columnNameLower.begin(), columnNameLower.end(), columnNameLower.begin(), ::tolower); + std::vector columnNames; + int ret = GetAllColumnNames(columnNames); + if (ret != E_OK) { + LOG_ERROR("return GetAllColumnNames ret is wrong!"); + return ret; + } + + columnIndex = 0; + for (const auto& name : columnNames) { + std::string lowerName = name; + transform(name.begin(), name.end(), lowerName.begin(), ::tolower); + if (lowerName == columnNameLower) { + indexCache_[columnName] = columnIndex; + return E_OK; + } + columnIndex++; + } + columnIndex = -1; + return E_ERROR; +} + +int DataShareAbsResultSet::GetColumnName(int columnIndex, std::string &columnName) +{ + int rowCnt = 0; + int ret = GetColumnCount(rowCnt); + if (ret != E_OK) { + LOG_ERROR("return GetColumnCount ret is wrong!"); + return ret; + } + if (columnIndex >= rowCnt || columnIndex < 0) { + return E_INVALID_COLUMN_INDEX; + } + std::vector columnNames; + GetAllColumnNames(columnNames); + columnName = columnNames[columnIndex]; + return E_OK; +} + +bool DataShareAbsResultSet::IsClosed() const +{ + return isClosed_; +} + +int DataShareAbsResultSet::Close() +{ + isClosed_ = true; + return E_OK; +} +} // namespace DataShare } // namespace OHOS \ No newline at end of file diff --git a/data_share/frameworks/native/common/src/datashare_block_writer_impl.cpp b/data_share/frameworks/native/common/src/datashare_block_writer_impl.cpp index 8442cc02f811088b9ada86628644f3576e1098ff..0bd75dce310da3c4aa22fdc734f741b4696a0f9e 100644 --- a/data_share/frameworks/native/common/src/datashare_block_writer_impl.cpp +++ b/data_share/frameworks/native/common/src/datashare_block_writer_impl.cpp @@ -1,113 +1,113 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "datashare_block_writer_impl.h" -#include "datashare_log.h" -#include "datashare_errno.h" - -namespace OHOS { -namespace DataShare { -DataShareBlockWriterImpl::DataShareBlockWriterImpl() : shareBlock_(nullptr) -{ -} - -DataShareBlockWriterImpl::DataShareBlockWriterImpl(const std::string &name, size_t size) - : shareBlock_(nullptr) -{ - AppDataFwk::SharedBlock::Create(name, size, shareBlock_); -} - -DataShareBlockWriterImpl::~DataShareBlockWriterImpl() -{ -} - -int DataShareBlockWriterImpl::AllocRow() -{ - if (shareBlock_ == nullptr) { - LOG_ERROR("shareBlock_ is nullptr"); - return E_ERROR; - } - return ConvertErrorCode(shareBlock_->AllocRow()); -} - -int DataShareBlockWriterImpl::Write(uint32_t column) -{ - uint32_t currentRowIndex = 0; - if (!GetCurrentRowIndex(currentRowIndex)) { - LOG_ERROR("Write null fail"); - return E_ERROR; - } - return ConvertErrorCode(shareBlock_->PutNull(currentRowIndex, column)); -} - -int DataShareBlockWriterImpl::Write(uint32_t column, int64_t value) -{ - uint32_t currentRowIndex = 0; - if (!GetCurrentRowIndex(currentRowIndex)) { - LOG_ERROR("Write long fail"); - return E_ERROR; - } - return ConvertErrorCode(shareBlock_->PutLong(currentRowIndex, column, value)); -} - -int DataShareBlockWriterImpl::Write(uint32_t column, double value) -{ - uint32_t currentRowIndex = 0; - if (!GetCurrentRowIndex(currentRowIndex)) { - LOG_ERROR("Write double fail"); - return E_ERROR; - } - return ConvertErrorCode(shareBlock_->PutDouble(currentRowIndex, column, value)); -} - -int DataShareBlockWriterImpl::Write(uint32_t column, const uint8_t *value, size_t size) -{ - uint32_t currentRowIndex = 0; - if (!GetCurrentRowIndex(currentRowIndex)) { - LOG_ERROR("Write blob fail"); - return E_ERROR; - } - return ConvertErrorCode(shareBlock_->PutBlob(currentRowIndex, column, value, size)); -} - -int DataShareBlockWriterImpl::Write(uint32_t column, const char *value, size_t sizeIncludingNull) -{ - uint32_t currentRowIndex = 0; - if (!GetCurrentRowIndex(currentRowIndex)) { - LOG_ERROR("Write string fail"); - return E_ERROR; - } - return ConvertErrorCode(shareBlock_->PutString(currentRowIndex, column, value, sizeIncludingNull)); -} - -AppDataFwk::SharedBlock *DataShareBlockWriterImpl::GetBlock() const -{ - return shareBlock_; -} - -bool DataShareBlockWriterImpl::GetCurrentRowIndex(uint32_t &rowIndex) -{ - if (shareBlock_ == nullptr) { - LOG_ERROR("shareBlock_ is nullptr"); - return false; - } - uint32_t rowNum = shareBlock_->GetRowNum(); - if (rowNum > 0) { - rowIndex = rowNum - 1; - return true; - } - return false; -} -} // namespace DataShare -} // namespace OHOS +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "datashare_block_writer_impl.h" +#include "datashare_log.h" +#include "datashare_errno.h" + +namespace OHOS { +namespace DataShare { +DataShareBlockWriterImpl::DataShareBlockWriterImpl() : shareBlock_(nullptr) +{ +} + +DataShareBlockWriterImpl::DataShareBlockWriterImpl(const std::string &name, size_t size) + : shareBlock_(nullptr) +{ + AppDataFwk::SharedBlock::Create(name, size, shareBlock_); +} + +DataShareBlockWriterImpl::~DataShareBlockWriterImpl() +{ +} + +int DataShareBlockWriterImpl::AllocRow() +{ + if (shareBlock_ == nullptr) { + LOG_ERROR("shareBlock_ is nullptr"); + return E_ERROR; + } + return ConvertErrorCode(shareBlock_->AllocRow()); +} + +int DataShareBlockWriterImpl::Write(uint32_t column) +{ + uint32_t currentRowIndex = 0; + if (!GetCurrentRowIndex(currentRowIndex)) { + LOG_ERROR("Write null fail"); + return E_ERROR; + } + return ConvertErrorCode(shareBlock_->PutNull(currentRowIndex, column)); +} + +int DataShareBlockWriterImpl::Write(uint32_t column, int64_t value) +{ + uint32_t currentRowIndex = 0; + if (!GetCurrentRowIndex(currentRowIndex)) { + LOG_ERROR("Write long fail"); + return E_ERROR; + } + return ConvertErrorCode(shareBlock_->PutLong(currentRowIndex, column, value)); +} + +int DataShareBlockWriterImpl::Write(uint32_t column, double value) +{ + uint32_t currentRowIndex = 0; + if (!GetCurrentRowIndex(currentRowIndex)) { + LOG_ERROR("Write double fail"); + return E_ERROR; + } + return ConvertErrorCode(shareBlock_->PutDouble(currentRowIndex, column, value)); +} + +int DataShareBlockWriterImpl::Write(uint32_t column, const uint8_t *value, size_t size) +{ + uint32_t currentRowIndex = 0; + if (!GetCurrentRowIndex(currentRowIndex)) { + LOG_ERROR("Write blob fail"); + return E_ERROR; + } + return ConvertErrorCode(shareBlock_->PutBlob(currentRowIndex, column, value, size)); +} + +int DataShareBlockWriterImpl::Write(uint32_t column, const char *value, size_t sizeIncludingNull) +{ + uint32_t currentRowIndex = 0; + if (!GetCurrentRowIndex(currentRowIndex)) { + LOG_ERROR("Write string fail"); + return E_ERROR; + } + return ConvertErrorCode(shareBlock_->PutString(currentRowIndex, column, value, sizeIncludingNull)); +} + +AppDataFwk::SharedBlock *DataShareBlockWriterImpl::GetBlock() const +{ + return shareBlock_; +} + +bool DataShareBlockWriterImpl::GetCurrentRowIndex(uint32_t &rowIndex) +{ + if (shareBlock_ == nullptr) { + LOG_ERROR("shareBlock_ is nullptr"); + return false; + } + uint32_t rowNum = shareBlock_->GetRowNum(); + if (rowNum > 0) { + rowIndex = rowNum - 1; + return true; + } + return false; +} +} // namespace DataShare +} // namespace OHOS diff --git a/data_share/frameworks/native/common/src/datashare_itypes_utils.cpp b/data_share/frameworks/native/common/src/datashare_itypes_utils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8021a298ea3cb599fb10806b86157a8fd746d066 --- /dev/null +++ b/data_share/frameworks/native/common/src/datashare_itypes_utils.cpp @@ -0,0 +1,188 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "datashare_itypes_utils.h" +#include "datashare_log.h" + +namespace OHOS::ITypesUtil { +using namespace OHOS::DataShare; +template<> +bool Marshalling(const Predicates &predicates, MessageParcel &parcel) +{ + const auto &operations = predicates.GetOperationList(); + int16_t mode = predicates.GetSettingMode(); + return ITypesUtil::Marshal(parcel, operations, predicates.GetWhereClause(), predicates.GetWhereArgs(), + predicates.GetOrder(), mode); +} + +template<> +bool Unmarshalling(Predicates &predicates, MessageParcel &parcel) +{ + std::vector operations{}; + std::string whereClause = ""; + std::vector whereArgs; + std::string order = ""; + int16_t mode = DataShare::INVALID_MODE; + if (!ITypesUtil::Unmarshal(parcel, operations, whereClause, whereArgs, order, mode)) { + return false; + } + DataShare::DataSharePredicates tmpPredicates(operations); + tmpPredicates.SetWhereClause(whereClause); + tmpPredicates.SetWhereArgs(whereArgs); + tmpPredicates.SetOrder(order); + tmpPredicates.SetSettingMode(mode); + predicates = tmpPredicates; + return true; +} + +template<> +bool Marshalling(const Operation &operation, MessageParcel &parcel) +{ + return ITypesUtil::Marshal(parcel, operation.operation, operation.singleParams, operation.multiParams); +} + +template<> +bool Unmarshalling(Operation &operation, MessageParcel &parcel) +{ + return ITypesUtil::Unmarshal(parcel, operation.operation, operation.singleParams, operation.multiParams); +} + +template<> +bool Unmarshalling(PublishedDataItem &dataItem, MessageParcel &parcel) +{ + return ITypesUtil::Unmarshal(parcel, dataItem.key_, dataItem.subscriberId_, dataItem.value_); +} + +template<> +bool Marshalling(const PublishedDataItem &dataItem, MessageParcel &parcel) +{ + return ITypesUtil::Marshal(parcel, dataItem.key_, dataItem.subscriberId_, dataItem.value_); +} + +template<> +bool Marshalling(const Data &data, MessageParcel &parcel) +{ + return ITypesUtil::Marshal(parcel, data.datas_, data.version_); +} + +template<> +bool Unmarshalling(Data &data, MessageParcel &parcel) +{ + return ITypesUtil::Unmarshal(parcel, data.datas_, data.version_); +} + +template<> +bool Unmarshalling(TemplateId &templateId, MessageParcel &parcel) +{ + return ITypesUtil::Unmarshal(parcel, templateId.subscriberId_, templateId.bundleName_); +} + +template<> +bool Marshalling(const TemplateId &templateId, MessageParcel &parcel) +{ + return ITypesUtil::Marshal(parcel, templateId.subscriberId_, templateId.bundleName_); +} + +template<> +bool Marshalling(const PredicateTemplateNode &predicateTemplateNode, MessageParcel &parcel) +{ + return ITypesUtil::Marshal(parcel, predicateTemplateNode.key_, predicateTemplateNode.selectSql_); +} + +template<> +bool Unmarshalling(PredicateTemplateNode &predicateTemplateNode, MessageParcel &parcel) +{ + return ITypesUtil::Unmarshal(parcel, predicateTemplateNode.key_, predicateTemplateNode.selectSql_); +} + +template<> +bool Marshalling(const RdbChangeNode &changeNode, MessageParcel &parcel) +{ + return ITypesUtil::Marshal(parcel, changeNode.uri_, changeNode.templateId_, changeNode.data_); +} + +template<> +bool Unmarshalling(RdbChangeNode &changeNode, MessageParcel &parcel) +{ + return ITypesUtil::Unmarshal(parcel, changeNode.uri_, changeNode.templateId_, changeNode.data_); +} + +template<> +bool Marshalling(const PublishedDataChangeNode &changeNode, MessageParcel &parcel) +{ + return ITypesUtil::Marshal(parcel, changeNode.ownerBundleName_, changeNode.datas_); +} + +template<> +bool Unmarshalling(PublishedDataChangeNode &changeNode, MessageParcel &parcel) +{ + return ITypesUtil::Unmarshal(parcel, changeNode.ownerBundleName_, changeNode.datas_); +} + +template<> +bool Marshalling(const OperationResult &operationResult, MessageParcel &parcel) +{ + return ITypesUtil::Marshal(parcel, operationResult.key_, operationResult.errCode_); +} + +template<> +bool Unmarshalling(OperationResult &predicateTemplateNode, MessageParcel &parcel) +{ + return ITypesUtil::Unmarshal(parcel, predicateTemplateNode.key_, predicateTemplateNode.errCode_); +} + +template<> +bool Unmarshalling(AshmemNode &node, MessageParcel &parcel) +{ + node.isManaged = true; + node.ashmem = parcel.ReadAshmem(); + return true; +} + +template<> +bool Marshalling(const AshmemNode &node, MessageParcel &parcel) +{ + return parcel.WriteAshmem(node.ashmem); +} + +template<> +bool Marshalling(const Uri &node, MessageParcel &parcel) +{ + return parcel.WriteParcelable(&node); +} + +template<> +bool Unmarshalling(Uri &node, MessageParcel &parcel) +{ + auto uri = std::shared_ptr(parcel.ReadParcelable()); + if (uri == nullptr) { + return false; + } + node = *uri; + return true; +} + +template<> +bool Marshalling(const DataShareValuesBucket &bucket, MessageParcel &parcel) +{ + return ITypesUtil::Marshal(parcel, bucket.valuesMap); +} + +template<> +bool Unmarshalling(DataShareValuesBucket &bucket, MessageParcel &parcel) +{ + return ITypesUtil::Unmarshal(parcel, bucket.valuesMap); +} +} // namespace OHOS::ITypesUtil diff --git a/data_share/frameworks/native/common/src/datashare_result_set.cpp b/data_share/frameworks/native/common/src/datashare_result_set.cpp index 271671ec62711ec32d49a616cdaf63201b2398c7..4ad05d1aa2117e2358a15d6a782ce1f97a7fb4ab 100644 --- a/data_share/frameworks/native/common/src/datashare_result_set.cpp +++ b/data_share/frameworks/native/common/src/datashare_result_set.cpp @@ -1,431 +1,430 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "datashare_result_set.h" - -#include - -#include - -#include "adaptor.h" -#include "datashare_errno.h" -#include "datashare_log.h" -#include "parcel.h" -#include "shared_block.h" -#include "string_ex.h" - -namespace OHOS { -namespace DataShare { -namespace { - // The default position of the cursor - static const int INITIAL_POS = -1; - static const size_t DEFAULT_SHARE_BLOCK_SIZE = 2 * 1024 * 1024; -} // namespace -int DataShareResultSet::blockId_ = 0; -DataShareResultSet::DataShareResultSet() -{ -} - -DataShareResultSet::DataShareResultSet(std::shared_ptr &bridge) - : bridge_(bridge) -{ - std::string name = "DataShare" + std::to_string(blockId_++); - blockWriter_ = std::make_shared(name, DEFAULT_SHARE_BLOCK_SIZE); - if (blockWriter_ == nullptr) { - return; - } - sharedBlock_ = blockWriter_->GetBlock(); - if (sharedBlock_ == nullptr) { - return; - } -} - -DataShareResultSet::~DataShareResultSet() -{ - Close(); -} - -int DataShareResultSet::GetAllColumnNames(std::vector &columnNames) -{ - if (bridge_ == nullptr) { - LOG_ERROR("bridge_ is null!"); - return E_ERROR; - } - return bridge_->GetAllColumnNames(columnNames); -} - -int DataShareResultSet::GetRowCount(int &count) -{ - if (bridge_ == nullptr) { - LOG_ERROR("bridge_ is null!"); - return E_ERROR; - } - return bridge_->GetRowCount(count); -} - -bool DataShareResultSet::OnGo(int startRowIndex, int targetRowIndex, int *cachedIndex) -{ - if (bridge_ == nullptr || blockWriter_ == nullptr || sharedBlock_ == nullptr) { - LOG_ERROR("bridge_ or blockWriter_ or sharedBlock_ is null!"); - return false; - } - std::vector columnNames; - GetAllColumnNames(columnNames); - sharedBlock_->Clear(); - sharedBlock_->SetColumnNum(columnNames.size()); - int result = bridge_->OnGo(startRowIndex, targetRowIndex, *blockWriter_); - if (cachedIndex != nullptr) { - *cachedIndex = result; - } - if (result < 0) { - return false; - } - return true; -} - -void DataShareResultSet::FillBlock(int startRowIndex, AppDataFwk::SharedBlock *block) -{ - return; -} - -/** - * Get current shared block - */ -AppDataFwk::SharedBlock *DataShareResultSet::GetBlock() const -{ - return sharedBlock_; -} - -int DataShareResultSet::GetDataType(int columnIndex, DataType &dataType) -{ - int rowCount = 0; - GetRowCount(rowCount); - AppDataFwk::SharedBlock::CellUnit *cellUnit = - sharedBlock_->GetCellUnit(static_cast(rowPos_) - startRowPos_, static_cast(columnIndex)); - if (!cellUnit) { - LOG_ERROR("cellUnit is null!"); - return E_ERROR; - } - dataType = (DataType)cellUnit->type; - return E_OK; -} - -int DataShareResultSet::GoToRow(int position) -{ - if (sharedBlock_ == nullptr) { - LOG_ERROR("sharedBlock_ is null!"); - return E_ERROR; - } - int rowCnt = 0; - GetRowCount(rowCnt); - if (position >= rowCnt) { - rowPos_ = rowCnt; - return E_ERROR; - } - if (position < 0) { - rowPos_ = INITIAL_POS; - return E_ERROR; - } - if (position == rowPos_) { - return E_OK; - } - bool result = true; - if (position > endRowPos_ || position < startRowPos_) { - int endPos = -1; - result = OnGo(position, rowCnt - 1, &endPos); - if (result) { - startRowPos_ = position; - endRowPos_ = endPos; - } - } - - if (!result) { - rowPos_ = INITIAL_POS; - startRowPos_ = INITIAL_POS; - endRowPos_ = INITIAL_POS; - return E_ERROR; - } else { - rowPos_ = position; - return E_OK; - } -} - -int DataShareResultSet::GetBlob(int columnIndex, std::vector &value) -{ - int errorCode = CheckState(columnIndex); - if (errorCode != E_OK) { - return errorCode; - } - - AppDataFwk::SharedBlock::CellUnit *cellUnit = sharedBlock_->GetCellUnit(rowPos_ - startRowPos_, columnIndex); - if (!cellUnit) { - LOG_ERROR("cellUnit is null!"); - return E_ERROR; - } - - value.resize(0); - int type = cellUnit->type; - if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_BLOB - || type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_STRING) { - size_t size; - const auto *blob = static_cast(sharedBlock_->GetCellUnitValueBlob(cellUnit, &size)); - if (size == 0 || blob == nullptr) { - LOG_WARN("blob data is empty!"); - } else { - value.resize(size); - value.assign(blob, blob + size); - } - return E_OK; - } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_INTEGER) { - return E_OK; - } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_NULL) { - return E_OK; - } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_FLOAT) { - return E_OK; - } else { - LOG_ERROR("AppDataFwk::SharedBlock::nothing !"); - return E_INVALID_OBJECT_TYPE; - } -} - -int DataShareResultSet::GetString(int columnIndex, std::string &value) -{ - if (sharedBlock_ == nullptr) { - LOG_ERROR("sharedBlock is null!"); - return E_ERROR; - } - AppDataFwk::SharedBlock::CellUnit *cellUnit = sharedBlock_->GetCellUnit(rowPos_ - startRowPos_, columnIndex); - if (!cellUnit) { - LOG_ERROR("cellUnit is null!"); - return E_ERROR; - } - int type = cellUnit->type; - if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_STRING) { - size_t sizeIncludingNull; - value = std::string(sharedBlock_->GetCellUnitValueString(cellUnit, &sizeIncludingNull)); - return E_OK; - } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_NULL) { - return E_ERROR; - } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_INTEGER) { - int64_t tempValue = cellUnit->cell.longValue; - value = std::to_string(tempValue); - return E_OK; - } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_FLOAT) { - double tempValue = cellUnit->cell.doubleValue; - std::ostringstream os; - if (os << tempValue) { - value = os.str(); - } - return E_OK; - } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_BLOB) { - return E_ERROR; - } else { - LOG_ERROR("GetString is failed!"); - return E_ERROR; - } -} - -int DataShareResultSet::GetInt(int columnIndex, int &value) -{ - if (sharedBlock_ == nullptr) { - LOG_ERROR("sharedBlock is null!"); - return E_ERROR; - } - AppDataFwk::SharedBlock::CellUnit *cellUnit = sharedBlock_->GetCellUnit(rowPos_ - startRowPos_, columnIndex); - if (!cellUnit) { - LOG_ERROR("cellUnit is null!"); - return E_ERROR; - } - value = (int)cellUnit->cell.longValue; - return E_OK; -} - -int DataShareResultSet::GetLong(int columnIndex, int64_t &value) -{ - if (sharedBlock_ == nullptr) { - LOG_ERROR("sharedBlock is null!"); - return E_ERROR; - } - AppDataFwk::SharedBlock::CellUnit *cellUnit = sharedBlock_->GetCellUnit(rowPos_ - startRowPos_, columnIndex); - if (!cellUnit) { - LOG_ERROR("cellUnit is null!"); - return E_ERROR; - } - - int type = cellUnit->type; - - if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_INTEGER) { - value = cellUnit->cell.longValue; - return E_OK; - } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_STRING) { - size_t sizeIncludingNull; - const char *tempValue = sharedBlock_->GetCellUnitValueString(cellUnit, &sizeIncludingNull); - value = ((sizeIncludingNull > 1) && (tempValue != nullptr)) ? long(strtoll(tempValue, nullptr, 0)) : 0L; - return E_OK; - } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_FLOAT) { - value = (int64_t)cellUnit->cell.doubleValue; - return E_OK; - } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_NULL) { - value = 0L; - return E_OK; - } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_BLOB) { - value = 0L; - return E_OK; - } else { - LOG_ERROR("Nothing !"); - return E_INVALID_OBJECT_TYPE; - } -} - -int DataShareResultSet::GetDouble(int columnIndex, double &value) -{ - int errorCode = CheckState(columnIndex); - if (errorCode != E_OK) { - return errorCode; - } - AppDataFwk::SharedBlock::CellUnit *cellUnit = sharedBlock_->GetCellUnit(rowPos_ - startRowPos_, columnIndex); - if (!cellUnit) { - LOG_ERROR("cellUnit is null!"); - return E_ERROR; - } - int type = cellUnit->type; - if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_FLOAT) { - value = cellUnit->cell.doubleValue; - return E_OK; - } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_STRING) { - size_t sizeIncludingNull; - const char *tempValue = sharedBlock_->GetCellUnitValueString(cellUnit, &sizeIncludingNull); - value = ((sizeIncludingNull > 1) && (tempValue != nullptr)) ? strtod(tempValue, nullptr) : 0.0; - return E_OK; - } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_INTEGER) { - value = static_cast(cellUnit->cell.longValue); - return E_OK; - } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_NULL) { - value = 0.0; - return E_OK; - } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_BLOB) { - value = 0.0; - return E_OK; - } else { - LOG_ERROR("AppDataFwk::SharedBlock::nothing !"); - value = 0.0; - return E_INVALID_OBJECT_TYPE; - } -} - -int DataShareResultSet::IsColumnNull(int columnIndex, bool &isNull) -{ - int errorCode = CheckState(columnIndex); - if (errorCode != E_OK) { - return errorCode; - } - AppDataFwk::SharedBlock::CellUnit *cellUnit = sharedBlock_->GetCellUnit(rowPos_ - startRowPos_, columnIndex); - if (!cellUnit) { - LOG_ERROR("cellUnit is null!"); - return E_ERROR; - } - if (cellUnit->type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_NULL) { - isNull = true; - return E_OK; - } - isNull = false; - return E_OK; -} - -int DataShareResultSet::Close() -{ - DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); - DataShareAbsResultSet::Close(); - ClosedBlock(); - bridge_ = nullptr; - return E_OK; -} - -/** - * Allocates a new shared block to an {@link DataShareResultSet} - */ -void DataShareResultSet::SetBlock(AppDataFwk::SharedBlock *block) -{ - if (sharedBlock_ != block) { - ClosedBlock(); - sharedBlock_ = block; - } -} - -/** - * Checks whether an {@code DataShareResultSet} object contains shared blocks - */ -bool DataShareResultSet::HasBlock() const -{ - return sharedBlock_ != nullptr; -} - -/** - * Closes a shared block that is not empty in this {@code DataShareResultSet} object - */ -void DataShareResultSet::ClosedBlock() -{ - if (sharedBlock_ != nullptr) { - delete sharedBlock_; - sharedBlock_ = nullptr; - } -} - -void DataShareResultSet::Finalize() -{ - Close(); -} - -/** - * Check current status - */ -int DataShareResultSet::CheckState(int columnIndex) -{ - if (sharedBlock_ == nullptr) { - LOG_ERROR("sharedBlock is null!"); - return E_ERROR; - } - int cnt = 0; - GetColumnCount(cnt); - if (columnIndex >= cnt || columnIndex < 0) { - return E_INVALID_COLUMN_INDEX; - } - if (rowPos_ == INITIAL_POS) { - return E_INVALID_STATEMENT; - } - return E_OK; -} - -bool DataShareResultSet::Marshalling(MessageParcel &parcel) -{ - if (sharedBlock_ == nullptr) { - LOG_ERROR("sharedBlock is null."); - return false; - } - return sharedBlock_->WriteMessageParcel(parcel); -} - -bool DataShareResultSet::Unmarshalling(MessageParcel &parcel) -{ - if (sharedBlock_ != nullptr) { - return false; - } - int result = AppDataFwk::SharedBlock::ReadMessageParcel(parcel, sharedBlock_); - if (result < 0) { - LOG_ERROR("create from parcel error is %{public}d.", result); - } - return true; -} -} // namespace DataShare +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "datashare_result_set.h" + +#include +#include + +#include "adaptor.h" +#include "datashare_errno.h" +#include "datashare_log.h" +#include "parcel.h" +#include "shared_block.h" +#include "string_ex.h" + +namespace OHOS { +namespace DataShare { +namespace { + // The default position of the cursor + static const int INITIAL_POS = -1; + static const size_t DEFAULT_SHARE_BLOCK_SIZE = 2 * 1024 * 1024; +} // namespace +int DataShareResultSet::blockId_ = 0; +DataShareResultSet::DataShareResultSet() +{ +} + +DataShareResultSet::DataShareResultSet(std::shared_ptr &bridge) + : bridge_(bridge) +{ + std::string name = "DataShare" + std::to_string(blockId_++); + blockWriter_ = std::make_shared(name, DEFAULT_SHARE_BLOCK_SIZE); + if (blockWriter_ == nullptr) { + return; + } + sharedBlock_ = blockWriter_->GetBlock(); + if (sharedBlock_ == nullptr) { + return; + } +} + +DataShareResultSet::~DataShareResultSet() +{ + Close(); +} + +int DataShareResultSet::GetAllColumnNames(std::vector &columnNames) +{ + if (bridge_ == nullptr) { + LOG_ERROR("bridge_ is null!"); + return E_ERROR; + } + return bridge_->GetAllColumnNames(columnNames); +} + +int DataShareResultSet::GetRowCount(int &count) +{ + if (bridge_ == nullptr) { + LOG_ERROR("bridge_ is null!"); + return E_ERROR; + } + return bridge_->GetRowCount(count); +} + +bool DataShareResultSet::OnGo(int startRowIndex, int targetRowIndex, int *cachedIndex) +{ + if (bridge_ == nullptr || blockWriter_ == nullptr || sharedBlock_ == nullptr) { + LOG_ERROR("bridge_ or blockWriter_ or sharedBlock_ is null!"); + return false; + } + std::vector columnNames; + GetAllColumnNames(columnNames); + sharedBlock_->Clear(); + sharedBlock_->SetColumnNum(columnNames.size()); + int result = bridge_->OnGo(startRowIndex, targetRowIndex, *blockWriter_); + if (cachedIndex != nullptr) { + *cachedIndex = result; + } + if (result < 0) { + return false; + } + return true; +} + +void DataShareResultSet::FillBlock(int startRowIndex, AppDataFwk::SharedBlock *block) +{ + return; +} + +/** + * Get current shared block + */ +AppDataFwk::SharedBlock *DataShareResultSet::GetBlock() const +{ + return sharedBlock_; +} + +int DataShareResultSet::GetDataType(int columnIndex, DataType &dataType) +{ + int rowCount = 0; + GetRowCount(rowCount); + AppDataFwk::SharedBlock::CellUnit *cellUnit = + sharedBlock_->GetCellUnit(static_cast(rowPos_) - startRowPos_, static_cast(columnIndex)); + if (!cellUnit) { + LOG_ERROR("cellUnit is null!"); + return E_ERROR; + } + dataType = (DataType)cellUnit->type; + return E_OK; +} + +int DataShareResultSet::GoToRow(int position) +{ + if (sharedBlock_ == nullptr) { + LOG_ERROR("sharedBlock_ is null!"); + return E_ERROR; + } + int rowCnt = 0; + GetRowCount(rowCnt); + if (position >= rowCnt) { + rowPos_ = rowCnt; + return E_ERROR; + } + if (position < 0) { + rowPos_ = INITIAL_POS; + return E_ERROR; + } + if (position == rowPos_) { + return E_OK; + } + bool result = true; + if (position > endRowPos_ || position < startRowPos_) { + int endPos = -1; + result = OnGo(position, rowCnt - 1, &endPos); + if (result) { + startRowPos_ = position; + endRowPos_ = endPos; + } + } + + if (!result) { + rowPos_ = INITIAL_POS; + startRowPos_ = INITIAL_POS; + endRowPos_ = INITIAL_POS; + return E_ERROR; + } else { + rowPos_ = position; + return E_OK; + } +} + +int DataShareResultSet::GetBlob(int columnIndex, std::vector &value) +{ + int errorCode = CheckState(columnIndex); + if (errorCode != E_OK) { + return errorCode; + } + + AppDataFwk::SharedBlock::CellUnit *cellUnit = sharedBlock_->GetCellUnit(rowPos_ - startRowPos_, columnIndex); + if (!cellUnit) { + LOG_ERROR("cellUnit is null!"); + return E_ERROR; + } + + value.resize(0); + int type = cellUnit->type; + if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_BLOB + || type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_STRING) { + size_t size; + const auto *blob = static_cast(sharedBlock_->GetCellUnitValueBlob(cellUnit, &size)); + if (size == 0 || blob == nullptr) { + LOG_WARN("blob data is empty!"); + } else { + value.resize(size); + value.assign(blob, blob + size); + } + return E_OK; + } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_INTEGER) { + return E_OK; + } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_NULL) { + return E_OK; + } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_FLOAT) { + return E_OK; + } else { + LOG_ERROR("AppDataFwk::SharedBlock::nothing !"); + return E_INVALID_OBJECT_TYPE; + } +} + +int DataShareResultSet::GetString(int columnIndex, std::string &value) +{ + if (sharedBlock_ == nullptr) { + LOG_ERROR("sharedBlock is null!"); + return E_ERROR; + } + AppDataFwk::SharedBlock::CellUnit *cellUnit = sharedBlock_->GetCellUnit(rowPos_ - startRowPos_, columnIndex); + if (!cellUnit) { + LOG_ERROR("cellUnit is null!"); + return E_ERROR; + } + int type = cellUnit->type; + if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_STRING) { + size_t sizeIncludingNull; + value = std::string(sharedBlock_->GetCellUnitValueString(cellUnit, &sizeIncludingNull)); + return E_OK; + } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_NULL) { + return E_ERROR; + } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_INTEGER) { + int64_t tempValue = cellUnit->cell.longValue; + value = std::to_string(tempValue); + return E_OK; + } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_FLOAT) { + double tempValue = cellUnit->cell.doubleValue; + std::ostringstream os; + if (os << tempValue) { + value = os.str(); + } + return E_OK; + } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_BLOB) { + return E_ERROR; + } else { + LOG_ERROR("GetString is failed!"); + return E_ERROR; + } +} + +int DataShareResultSet::GetInt(int columnIndex, int &value) +{ + if (sharedBlock_ == nullptr) { + LOG_ERROR("sharedBlock is null!"); + return E_ERROR; + } + AppDataFwk::SharedBlock::CellUnit *cellUnit = sharedBlock_->GetCellUnit(rowPos_ - startRowPos_, columnIndex); + if (!cellUnit) { + LOG_ERROR("cellUnit is null!"); + return E_ERROR; + } + value = (int)cellUnit->cell.longValue; + return E_OK; +} + +int DataShareResultSet::GetLong(int columnIndex, int64_t &value) +{ + if (sharedBlock_ == nullptr) { + LOG_ERROR("sharedBlock is null!"); + return E_ERROR; + } + AppDataFwk::SharedBlock::CellUnit *cellUnit = sharedBlock_->GetCellUnit(rowPos_ - startRowPos_, columnIndex); + if (!cellUnit) { + LOG_ERROR("cellUnit is null!"); + return E_ERROR; + } + + int type = cellUnit->type; + + if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_INTEGER) { + value = cellUnit->cell.longValue; + return E_OK; + } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_STRING) { + size_t sizeIncludingNull; + const char *tempValue = sharedBlock_->GetCellUnitValueString(cellUnit, &sizeIncludingNull); + value = ((sizeIncludingNull > 1) && (tempValue != nullptr)) ? long(strtoll(tempValue, nullptr, 0)) : 0L; + return E_OK; + } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_FLOAT) { + value = (int64_t)cellUnit->cell.doubleValue; + return E_OK; + } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_NULL) { + value = 0L; + return E_OK; + } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_BLOB) { + value = 0L; + return E_OK; + } else { + LOG_ERROR("Nothing !"); + return E_INVALID_OBJECT_TYPE; + } +} + +int DataShareResultSet::GetDouble(int columnIndex, double &value) +{ + int errorCode = CheckState(columnIndex); + if (errorCode != E_OK) { + return errorCode; + } + AppDataFwk::SharedBlock::CellUnit *cellUnit = sharedBlock_->GetCellUnit(rowPos_ - startRowPos_, columnIndex); + if (!cellUnit) { + LOG_ERROR("cellUnit is null!"); + return E_ERROR; + } + int type = cellUnit->type; + if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_FLOAT) { + value = cellUnit->cell.doubleValue; + return E_OK; + } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_STRING) { + size_t sizeIncludingNull; + const char *tempValue = sharedBlock_->GetCellUnitValueString(cellUnit, &sizeIncludingNull); + value = ((sizeIncludingNull > 1) && (tempValue != nullptr)) ? strtod(tempValue, nullptr) : 0.0; + return E_OK; + } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_INTEGER) { + value = static_cast(cellUnit->cell.longValue); + return E_OK; + } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_NULL) { + value = 0.0; + return E_OK; + } else if (type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_BLOB) { + value = 0.0; + return E_OK; + } else { + LOG_ERROR("AppDataFwk::SharedBlock::nothing !"); + value = 0.0; + return E_INVALID_OBJECT_TYPE; + } +} + +int DataShareResultSet::IsColumnNull(int columnIndex, bool &isNull) +{ + int errorCode = CheckState(columnIndex); + if (errorCode != E_OK) { + return errorCode; + } + AppDataFwk::SharedBlock::CellUnit *cellUnit = sharedBlock_->GetCellUnit(rowPos_ - startRowPos_, columnIndex); + if (!cellUnit) { + LOG_ERROR("cellUnit is null!"); + return E_ERROR; + } + if (cellUnit->type == AppDataFwk::SharedBlock::CELL_UNIT_TYPE_NULL) { + isNull = true; + return E_OK; + } + isNull = false; + return E_OK; +} + +int DataShareResultSet::Close() +{ + DISTRIBUTED_DATA_HITRACE(std::string(__FUNCTION__)); + DataShareAbsResultSet::Close(); + ClosedBlock(); + bridge_ = nullptr; + return E_OK; +} + +/** + * Allocates a new shared block to an {@link DataShareResultSet} + */ +void DataShareResultSet::SetBlock(AppDataFwk::SharedBlock *block) +{ + if (sharedBlock_ != block) { + ClosedBlock(); + sharedBlock_ = block; + } +} + +/** + * Checks whether an {@code DataShareResultSet} object contains shared blocks + */ +bool DataShareResultSet::HasBlock() const +{ + return sharedBlock_ != nullptr; +} + +/** + * Closes a shared block that is not empty in this {@code DataShareResultSet} object + */ +void DataShareResultSet::ClosedBlock() +{ + if (sharedBlock_ != nullptr) { + delete sharedBlock_; + sharedBlock_ = nullptr; + } +} + +void DataShareResultSet::Finalize() +{ + Close(); +} + +/** + * Check current status + */ +int DataShareResultSet::CheckState(int columnIndex) +{ + if (sharedBlock_ == nullptr) { + LOG_ERROR("sharedBlock is null!"); + return E_ERROR; + } + int cnt = 0; + GetColumnCount(cnt); + if (columnIndex >= cnt || columnIndex < 0) { + return E_INVALID_COLUMN_INDEX; + } + if (rowPos_ == INITIAL_POS) { + return E_INVALID_STATEMENT; + } + return E_OK; +} + +bool DataShareResultSet::Marshalling(MessageParcel &parcel) +{ + if (sharedBlock_ == nullptr) { + LOG_ERROR("sharedBlock is null."); + return false; + } + return sharedBlock_->WriteMessageParcel(parcel); +} + +bool DataShareResultSet::Unmarshalling(MessageParcel &parcel) +{ + if (sharedBlock_ != nullptr) { + return false; + } + int result = AppDataFwk::SharedBlock::ReadMessageParcel(parcel, sharedBlock_); + if (result < 0) { + LOG_ERROR("create from parcel error is %{public}d.", result); + } + return true; +} +} // namespace DataShare } // namespace OHOS \ No newline at end of file diff --git a/data_share/frameworks/native/common/src/datashare_string_utils.cpp b/data_share/frameworks/native/common/src/datashare_string_utils.cpp index 8732d35d39c20840bbb676f8c6d9b3e0fb3635f1..1db79753e9d0903dfb102f83695842901981d46c 100644 --- a/data_share/frameworks/native/common/src/datashare_string_utils.cpp +++ b/data_share/frameworks/native/common/src/datashare_string_utils.cpp @@ -1,51 +1,51 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "datashare_string_utils.h" - -namespace OHOS { -namespace DataShare { -std::string DataShareStringUtils::SurroundWithQuote(std::string value, std::string quote) -{ - if (value.empty()) { - return value; - } - std::string str = quote + value + quote; - return str; -} - -// Join array members as parameters of a function call. -std::string DataShareStringUtils::SurroundWithFunction(std::string function, std::string separator, - std::vector array) -{ - std::string builder(function); - builder += "("; - bool isFirst = true; - for (auto text : array) { - if (!isFirst) { - builder = builder + " " + separator + " "; - } else { - isFirst = false; - } - builder += text; - } - builder += ")"; - return builder; -} - -DataShareStringUtils::DataShareStringUtils() {} -DataShareStringUtils::~DataShareStringUtils() {} -} // namespace DataShare +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "datashare_string_utils.h" + +namespace OHOS { +namespace DataShare { +std::string DataShareStringUtils::SurroundWithQuote(std::string value, std::string quote) +{ + if (value.empty()) { + return value; + } + std::string str = quote + value + quote; + return str; +} + +// Join array members as parameters of a function call. +std::string DataShareStringUtils::SurroundWithFunction(std::string function, std::string separator, + std::vector array) +{ + std::string builder(function); + builder += "("; + bool isFirst = true; + for (auto text : array) { + if (!isFirst) { + builder = builder + " " + separator + " "; + } else { + isFirst = false; + } + builder += text; + } + builder += ")"; + return builder; +} + +DataShareStringUtils::DataShareStringUtils() {} +DataShareStringUtils::~DataShareStringUtils() {} +} // namespace DataShare } // namespace OHOS \ No newline at end of file diff --git a/data_share/frameworks/native/common/src/shared_block.cpp b/data_share/frameworks/native/common/src/shared_block.cpp index 493802066f373b49ff207d8707633a2da9edba20..bdf19918b439ac984a0730d916306eafec04bcc5 100644 --- a/data_share/frameworks/native/common/src/shared_block.cpp +++ b/data_share/frameworks/native/common/src/shared_block.cpp @@ -1,461 +1,461 @@ -/* - * 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 "shared_block.h" -#include -#include -#include -#include -#include - -#include -#include - -#include "string_ex.h" -#include "datashare_log.h" - -namespace OHOS { -namespace AppDataFwk { -using namespace OHOS::DataShare; -SharedBlock::SharedBlock(const std::string &name, sptr ashmem, size_t size, bool readOnly) - : mName(name), ashmem_(ashmem), mSize(size), mReadOnly(readOnly), mHeader(nullptr) -{ -} - -SharedBlock::~SharedBlock() -{ - if (ashmem_ != nullptr) { - ashmem_->UnmapAshmem(); - ashmem_->CloseAshmem(); - LOG_DEBUG("SharedBlock: close ashmem"); - } -} - -std::u16string SharedBlock::ToUtf16(const std::string& str) -{ - return OHOS::Str8ToStr16(str); -} - -std::string SharedBlock::ToUtf8(const std::u16string& str16) -{ - return OHOS::Str16ToStr8(str16); -} - -bool SharedBlock::Init() -{ - mData = const_cast(ashmem_->ReadFromAshmem(sizeof(SharedBlockHeader), 0)); - mHeader = static_cast(mData); - if (mHeader == nullptr) { - return false; - } - return true; -} - -int SharedBlock::CreateSharedBlock(const std::string &name, size_t size, sptr ashmem, - SharedBlock *&outSharedBlock) -{ - outSharedBlock = new SharedBlock(name, ashmem, size, false); - if (outSharedBlock == nullptr) { - LOG_ERROR("CreateSharedBlock: new SharedBlock error."); - return SHARED_BLOCK_BAD_VALUE; - } - - if (!outSharedBlock->Init()) { - delete outSharedBlock; - outSharedBlock = nullptr; - LOG_ERROR("CreateSharedBlock: mHeader is null."); - return SHARED_BLOCK_ASHMEM_ERROR; - } - return SHARED_BLOCK_OK; -} - -int SharedBlock::Create(const std::string &name, size_t size, SharedBlock *&outSharedBlock) -{ - std::string ashmemName = "SharedBlock:" + name; - - sptr ashmem = Ashmem::CreateAshmem(ashmemName.c_str(), size); - if (ashmem == nullptr) { - LOG_ERROR("SharedBlock: CreateAshmem function error."); - return SHARED_BLOCK_ASHMEM_ERROR; - } - - bool ret = ashmem->MapReadAndWriteAshmem(); - if (!ret) { - LOG_ERROR("SharedBlock: MapReadAndWriteAshmem function error."); - ashmem->CloseAshmem(); - return SHARED_BLOCK_SET_PORT_ERROR; - } - - int result = CreateSharedBlock(name, size, ashmem, outSharedBlock); - if (result == SHARED_BLOCK_OK) { - return SHARED_BLOCK_OK; - } - ashmem->UnmapAshmem(); - ashmem->CloseAshmem(); - outSharedBlock = nullptr; - return result; -} - -int SharedBlock::WriteMessageParcel(MessageParcel &parcel) -{ - return parcel.WriteString16(ToUtf16(mName)) && parcel.WriteAshmem(ashmem_); -} - -int SharedBlock::ReadMessageParcel(MessageParcel &parcel, SharedBlock *&block) -{ - std::string name = ToUtf8(parcel.ReadString16()); - sptr ashmem = parcel.ReadAshmem(); - if (ashmem == nullptr) { - LOG_ERROR("ReadMessageParcel: No ashmem in the parcel."); - return SHARED_BLOCK_BAD_VALUE; - } - bool ret = ashmem->MapReadAndWriteAshmem(); - if (!ret) { - LOG_ERROR("ReadMessageParcel: MapReadAndWriteAshmem function error."); - ashmem->CloseAshmem(); - return SHARED_BLOCK_SET_PORT_ERROR; - } - block = new (std::nothrow) SharedBlock(name, ashmem, ashmem->GetAshmemSize(), true); - if (block == nullptr) { - LOG_ERROR("ReadMessageParcel new SharedBlock error."); - return SHARED_BLOCK_BAD_VALUE; - } - if (!block->Init()) { - delete block; - block = nullptr; - LOG_ERROR("ReadMessageParcel: mHeader is null."); - return SHARED_BLOCK_ASHMEM_ERROR; - } - - LOG_DEBUG("Created SharedBlock from parcel: unusedOffset=%{private}" PRIu32 ", " - "rowNums=%{private}" PRIu32 ", columnNums=%{private}" PRIu32 ", mSize=%{private}d", - block->mHeader->unusedOffset, block->mHeader->rowNums, block->mHeader->columnNums, - static_cast(block->mSize)); - - return SHARED_BLOCK_OK; -} - -int SharedBlock::Clear() -{ - if (mReadOnly) { - return SHARED_BLOCK_INVALID_OPERATION; - } - - mHeader->unusedOffset = sizeof(SharedBlockHeader) + sizeof(RowGroupHeader); - mHeader->firstRowGroupOffset = sizeof(SharedBlockHeader); - mHeader->rowNums = 0; - mHeader->columnNums = 0; - mHeader->startPos_ = 0; - mHeader->lastPos_ = 0; - mHeader->blockPos_ = 0; - - RowGroupHeader *firstGroup = static_cast(OffsetToPtr(mHeader->firstRowGroupOffset)); - if (!firstGroup) { - LOG_ERROR("Failed to get group in clear()."); - return SHARED_BLOCK_BAD_VALUE; - } - firstGroup->nextGroupOffset = 0; - return SHARED_BLOCK_OK; -} - -int SharedBlock::SetColumnNum(uint32_t numColumns) -{ - if (mReadOnly) { - return SHARED_BLOCK_INVALID_OPERATION; - } - - uint32_t cur = mHeader->columnNums; - if ((cur > 0 || mHeader->rowNums > 0) && cur != numColumns) { - LOG_ERROR("Trying to go from %{public}" PRIu32 " columns to %{public}" PRIu32 "", cur, numColumns); - return SHARED_BLOCK_INVALID_OPERATION; - } - if (numColumns > COL_MAX_NUM) { - LOG_ERROR("Trying to set %{public}" PRIu32 " columns out of size", numColumns); - return SHARED_BLOCK_INVALID_OPERATION; - } - mHeader->columnNums = numColumns; - return SHARED_BLOCK_OK; -} - -int SharedBlock::AllocRow() -{ - if (mReadOnly) { - return SHARED_BLOCK_INVALID_OPERATION; - } - - uint32_t *rowOffset = AllocRowOffset(); - if (rowOffset == nullptr) { - return SHARED_BLOCK_NO_MEMORY; - } - - /* Allocate the units for the field directory */ - size_t fieldDirSize = mHeader->columnNums * sizeof(CellUnit); - - /* Aligned */ - uint32_t fieldDirOffset = Alloc(fieldDirSize, true); - if (!fieldDirOffset) { - mHeader->rowNums--; - LOG_INFO("Alloc the row failed, so back out the new row accounting from allocRowoffset %{public}" PRIu32 "", - mHeader->rowNums); - return SHARED_BLOCK_NO_MEMORY; - } - - CellUnit *fieldDir = static_cast(OffsetToPtr(fieldDirOffset)); - if (fieldDir == nullptr) { - return SHARED_BLOCK_BAD_VALUE; - } - int result = memset_s(fieldDir, fieldDirSize, 0, fieldDirSize); - if (result != 0) { - LOG_ERROR("Set memory failed"); - return SHARED_BLOCK_NO_MEMORY; - } - - *rowOffset = fieldDirOffset; - return SHARED_BLOCK_OK; -} - -int SharedBlock::FreeLastRow() -{ - if (mReadOnly) { - return SHARED_BLOCK_INVALID_OPERATION; - } - - if (mHeader->rowNums > 0) { - mHeader->rowNums--; - } - - return SHARED_BLOCK_OK; -} - -uint32_t SharedBlock::Alloc(size_t size, bool aligned) -{ - /* Number of unused offsets in the header */ - uint32_t offsetDigit = 3; - uint32_t padding = aligned ? (~mHeader->unusedOffset + 1) & offsetDigit : 0; - uint32_t offset = mHeader->unusedOffset + padding; - uint32_t nextFreeOffset; - - if (offset + size > mSize) { - LOG_ERROR("SharedBlock is full: requested allocation %{public}zu bytes," - " free space %{public}zu bytes, block size %{public}zu bytes", - size, mSize - mHeader->unusedOffset, mSize); - return 0; - } - nextFreeOffset = offset + size; - mHeader->unusedOffset = nextFreeOffset; - return offset; -} - -inline uint32_t *SharedBlock::GetRowOffset(uint32_t row) -{ - uint32_t rowPos = row; - - RowGroupHeader *group = static_cast(OffsetToPtr(mHeader->firstRowGroupOffset)); - if (group == nullptr) { - LOG_ERROR("Failed to get group in getRowOffset()."); - return nullptr; - } - - while (rowPos >= ROW_OFFSETS_NUM) { - group = static_cast(OffsetToPtr(group->nextGroupOffset)); - if (group == nullptr) { - LOG_ERROR("Failed to get group in OffsetToPtr(group->nextGroupOffset) when while loop."); - return nullptr; - } - rowPos -= ROW_OFFSETS_NUM; - } - - return &group->rowOffsets[rowPos]; -} - -uint32_t *SharedBlock::AllocRowOffset() -{ - uint32_t rowPos = mHeader->rowNums; - - RowGroupHeader *group = static_cast(OffsetToPtr(mHeader->firstRowGroupOffset)); - if (group == nullptr) { - LOG_ERROR("Failed to get group in allocRowOffset()."); - return nullptr; - } - - while (rowPos > ROW_OFFSETS_NUM) { - group = static_cast(OffsetToPtr(group->nextGroupOffset)); - if (group == nullptr) { - LOG_ERROR("Failed to get group in OffsetToPtr(group->nextGroupOffset) when while loop."); - return nullptr; - } - rowPos -= ROW_OFFSETS_NUM; - } - if (rowPos == ROW_OFFSETS_NUM) { - if (!group->nextGroupOffset) { - /* Aligned */ - group->nextGroupOffset = Alloc(sizeof(RowGroupHeader), true); - if (!group->nextGroupOffset) { - return nullptr; - } - } - group = static_cast(OffsetToPtr(group->nextGroupOffset)); - if (group == nullptr) { - LOG_ERROR("Failed to get group in OffsetToPtr(group->nextGroupOffset)."); - return nullptr; - } - group->nextGroupOffset = 0; - rowPos = 0; - } - - mHeader->rowNums += 1; - return &group->rowOffsets[rowPos]; -} - -SharedBlock::CellUnit *SharedBlock::GetCellUnit(uint32_t row, uint32_t column) -{ - if (row >= mHeader->rowNums || column >= mHeader->columnNums) { - LOG_ERROR("Failed to read row %{public}" PRIu32 ", column %{public}" PRIu32 " from a SharedBlock" - " which has %{public}" PRIu32 " rows, %{public}" PRIu32 " columns.", - row, column, mHeader->rowNums, mHeader->columnNums); - return nullptr; - } - - uint32_t *rowOffset = GetRowOffset(row); - if (!rowOffset) { - LOG_ERROR("Failed to find rowOffset for row %{public}" PRIu32 ".", row); - return nullptr; - } - - CellUnit *cellUnit = static_cast(OffsetToPtr(*rowOffset)); - if (!cellUnit) { - LOG_ERROR("Failed to find cellUnit for rowOffset %{public}" PRIu32 ".", *rowOffset); - return nullptr; - } - - return &cellUnit[column]; -} - -int SharedBlock::PutBlob(uint32_t row, uint32_t column, const void *value, size_t size) -{ - return PutBlobOrString(row, column, value, size, CELL_UNIT_TYPE_BLOB); -} - -int SharedBlock::PutString(uint32_t row, uint32_t column, const char *value, size_t sizeIncludingNull) -{ - return PutBlobOrString(row, column, value, sizeIncludingNull, CELL_UNIT_TYPE_STRING); -} - -int SharedBlock::PutBlobOrString(uint32_t row, uint32_t column, const void *value, size_t size, int32_t type) -{ - if (mReadOnly) { - return SHARED_BLOCK_INVALID_OPERATION; - } - - CellUnit *cellUnit = GetCellUnit(row, column); - if (!cellUnit) { - return SHARED_BLOCK_BAD_VALUE; - } - - uint32_t offset = Alloc(size); - if (!offset) { - return SHARED_BLOCK_NO_MEMORY; - } - - void *ptr = OffsetToPtr(offset); - if (!ptr) { - return SHARED_BLOCK_NO_MEMORY; - } - - if (size != 0) { - errno_t result = memcpy_s(ptr, size, value, size); - if (result != EOK) { - return SHARED_BLOCK_NO_MEMORY; - } - } - - cellUnit->type = type; - cellUnit->cell.stringOrBlobValue.offset = offset; - cellUnit->cell.stringOrBlobValue.size = size; - return SHARED_BLOCK_OK; -} - -int SharedBlock::PutLong(uint32_t row, uint32_t column, int64_t value) -{ - if (mReadOnly) { - return SHARED_BLOCK_INVALID_OPERATION; - } - - CellUnit *cellUnit = GetCellUnit(row, column); - if (!cellUnit) { - return SHARED_BLOCK_BAD_VALUE; - } - - cellUnit->type = CELL_UNIT_TYPE_INTEGER; - cellUnit->cell.longValue = value; - return SHARED_BLOCK_OK; -} - -int SharedBlock::PutDouble(uint32_t row, uint32_t column, double value) -{ - if (mReadOnly) { - return SHARED_BLOCK_INVALID_OPERATION; - } - - CellUnit *cellUnit = GetCellUnit(row, column); - if (!cellUnit) { - return SHARED_BLOCK_BAD_VALUE; - } - - cellUnit->type = CELL_UNIT_TYPE_FLOAT; - cellUnit->cell.doubleValue = value; - return SHARED_BLOCK_OK; -} - -int SharedBlock::PutNull(uint32_t row, uint32_t column) -{ - if (mReadOnly) { - return SHARED_BLOCK_INVALID_OPERATION; - } - - CellUnit *cellUnit = GetCellUnit(row, column); - if (!cellUnit) { - return SHARED_BLOCK_BAD_VALUE; - } - - cellUnit->type = CELL_UNIT_TYPE_NULL; - cellUnit->cell.stringOrBlobValue.offset = 0; - cellUnit->cell.stringOrBlobValue.size = 0; - return SHARED_BLOCK_OK; -} - -size_t SharedBlock::SetRawData(const void *rawData, size_t size) -{ - if (size <= 0) { - LOG_ERROR("SharedBlock rawData is less than or equal to 0M"); - return SHARED_BLOCK_INVALID_OPERATION; - } - if (size > mSize) { - LOG_ERROR("SharedBlock size is %{public}zu, current byteArray size is %{public}zu", mSize, size); - return SHARED_BLOCK_NO_MEMORY; - } - - int result = memcpy_s(mHeader, mSize, rawData, size); - if (result != 0) { - return SHARED_BLOCK_NO_MEMORY; - } - return SHARED_BLOCK_OK; -} - -uint32_t SharedBlock::OffsetFromPtr(void *ptr) -{ - return static_cast(ptr) - static_cast(mData); -} -} // namespace AppDataFwk -} // namespace OHOS +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "shared_block.h" +#include +#include +#include +#include +#include + +#include +#include + +#include "string_ex.h" +#include "datashare_log.h" + +namespace OHOS { +namespace AppDataFwk { +using namespace OHOS::DataShare; +SharedBlock::SharedBlock(const std::string &name, sptr ashmem, size_t size, bool readOnly) + : mName(name), ashmem_(ashmem), mSize(size), mReadOnly(readOnly), mHeader(nullptr) +{ +} + +SharedBlock::~SharedBlock() +{ + if (ashmem_ != nullptr) { + ashmem_->UnmapAshmem(); + ashmem_->CloseAshmem(); + LOG_DEBUG("SharedBlock: close ashmem"); + } +} + +std::u16string SharedBlock::ToUtf16(const std::string& str) +{ + return OHOS::Str8ToStr16(str); +} + +std::string SharedBlock::ToUtf8(const std::u16string& str16) +{ + return OHOS::Str16ToStr8(str16); +} + +bool SharedBlock::Init() +{ + mData = const_cast(ashmem_->ReadFromAshmem(sizeof(SharedBlockHeader), 0)); + mHeader = static_cast(mData); + if (mHeader == nullptr) { + return false; + } + return true; +} + +int SharedBlock::CreateSharedBlock(const std::string &name, size_t size, sptr ashmem, + SharedBlock *&outSharedBlock) +{ + outSharedBlock = new SharedBlock(name, ashmem, size, false); + if (outSharedBlock == nullptr) { + LOG_ERROR("CreateSharedBlock: new SharedBlock error."); + return SHARED_BLOCK_BAD_VALUE; + } + + if (!outSharedBlock->Init()) { + delete outSharedBlock; + outSharedBlock = nullptr; + LOG_ERROR("CreateSharedBlock: mHeader is null."); + return SHARED_BLOCK_ASHMEM_ERROR; + } + return SHARED_BLOCK_OK; +} + +int SharedBlock::Create(const std::string &name, size_t size, SharedBlock *&outSharedBlock) +{ + std::string ashmemName = "SharedBlock:" + name; + + sptr ashmem = Ashmem::CreateAshmem(ashmemName.c_str(), size); + if (ashmem == nullptr) { + LOG_ERROR("SharedBlock: CreateAshmem function error."); + return SHARED_BLOCK_ASHMEM_ERROR; + } + + bool ret = ashmem->MapReadAndWriteAshmem(); + if (!ret) { + LOG_ERROR("SharedBlock: MapReadAndWriteAshmem function error."); + ashmem->CloseAshmem(); + return SHARED_BLOCK_SET_PORT_ERROR; + } + + int result = CreateSharedBlock(name, size, ashmem, outSharedBlock); + if (result == SHARED_BLOCK_OK) { + return SHARED_BLOCK_OK; + } + ashmem->UnmapAshmem(); + ashmem->CloseAshmem(); + outSharedBlock = nullptr; + return result; +} + +int SharedBlock::WriteMessageParcel(MessageParcel &parcel) +{ + return parcel.WriteString16(ToUtf16(mName)) && parcel.WriteAshmem(ashmem_); +} + +int SharedBlock::ReadMessageParcel(MessageParcel &parcel, SharedBlock *&block) +{ + std::string name = ToUtf8(parcel.ReadString16()); + sptr ashmem = parcel.ReadAshmem(); + if (ashmem == nullptr) { + LOG_ERROR("ReadMessageParcel: No ashmem in the parcel."); + return SHARED_BLOCK_BAD_VALUE; + } + bool ret = ashmem->MapReadAndWriteAshmem(); + if (!ret) { + LOG_ERROR("ReadMessageParcel: MapReadAndWriteAshmem function error."); + ashmem->CloseAshmem(); + return SHARED_BLOCK_SET_PORT_ERROR; + } + block = new (std::nothrow) SharedBlock(name, ashmem, ashmem->GetAshmemSize(), true); + if (block == nullptr) { + LOG_ERROR("ReadMessageParcel new SharedBlock error."); + return SHARED_BLOCK_BAD_VALUE; + } + if (!block->Init()) { + delete block; + block = nullptr; + LOG_ERROR("ReadMessageParcel: mHeader is null."); + return SHARED_BLOCK_ASHMEM_ERROR; + } + + LOG_DEBUG("Created SharedBlock from parcel: unusedOffset=%{private}" PRIu32 ", " + "rowNums=%{private}" PRIu32 ", columnNums=%{private}" PRIu32 ", mSize=%{private}d", + block->mHeader->unusedOffset, block->mHeader->rowNums, block->mHeader->columnNums, + static_cast(block->mSize)); + + return SHARED_BLOCK_OK; +} + +int SharedBlock::Clear() +{ + if (mReadOnly) { + return SHARED_BLOCK_INVALID_OPERATION; + } + + mHeader->unusedOffset = sizeof(SharedBlockHeader) + sizeof(RowGroupHeader); + mHeader->firstRowGroupOffset = sizeof(SharedBlockHeader); + mHeader->rowNums = 0; + mHeader->columnNums = 0; + mHeader->startPos_ = 0; + mHeader->lastPos_ = 0; + mHeader->blockPos_ = 0; + + RowGroupHeader *firstGroup = static_cast(OffsetToPtr(mHeader->firstRowGroupOffset)); + if (!firstGroup) { + LOG_ERROR("Failed to get group in clear()."); + return SHARED_BLOCK_BAD_VALUE; + } + firstGroup->nextGroupOffset = 0; + return SHARED_BLOCK_OK; +} + +int SharedBlock::SetColumnNum(uint32_t numColumns) +{ + if (mReadOnly) { + return SHARED_BLOCK_INVALID_OPERATION; + } + + uint32_t cur = mHeader->columnNums; + if ((cur > 0 || mHeader->rowNums > 0) && cur != numColumns) { + LOG_ERROR("Trying to go from %{public}" PRIu32 " columns to %{public}" PRIu32 "", cur, numColumns); + return SHARED_BLOCK_INVALID_OPERATION; + } + if (numColumns > COL_MAX_NUM) { + LOG_ERROR("Trying to set %{public}" PRIu32 " columns out of size", numColumns); + return SHARED_BLOCK_INVALID_OPERATION; + } + mHeader->columnNums = numColumns; + return SHARED_BLOCK_OK; +} + +int SharedBlock::AllocRow() +{ + if (mReadOnly) { + return SHARED_BLOCK_INVALID_OPERATION; + } + + uint32_t *rowOffset = AllocRowOffset(); + if (rowOffset == nullptr) { + return SHARED_BLOCK_NO_MEMORY; + } + + /* Allocate the units for the field directory */ + size_t fieldDirSize = mHeader->columnNums * sizeof(CellUnit); + + /* Aligned */ + uint32_t fieldDirOffset = Alloc(fieldDirSize, true); + if (!fieldDirOffset) { + mHeader->rowNums--; + LOG_INFO("Alloc the row failed, so back out the new row accounting from allocRowoffset %{public}" PRIu32 "", + mHeader->rowNums); + return SHARED_BLOCK_NO_MEMORY; + } + + CellUnit *fieldDir = static_cast(OffsetToPtr(fieldDirOffset)); + if (fieldDir == nullptr) { + return SHARED_BLOCK_BAD_VALUE; + } + int result = memset_s(fieldDir, fieldDirSize, 0, fieldDirSize); + if (result != 0) { + LOG_ERROR("Set memory failed"); + return SHARED_BLOCK_NO_MEMORY; + } + + *rowOffset = fieldDirOffset; + return SHARED_BLOCK_OK; +} + +int SharedBlock::FreeLastRow() +{ + if (mReadOnly) { + return SHARED_BLOCK_INVALID_OPERATION; + } + + if (mHeader->rowNums > 0) { + mHeader->rowNums--; + } + + return SHARED_BLOCK_OK; +} + +uint32_t SharedBlock::Alloc(size_t size, bool aligned) +{ + /* Number of unused offsets in the header */ + uint32_t offsetDigit = 3; + uint32_t padding = aligned ? (~mHeader->unusedOffset + 1) & offsetDigit : 0; + uint32_t offset = mHeader->unusedOffset + padding; + uint32_t nextFreeOffset; + + if (offset + size > mSize) { + LOG_ERROR("SharedBlock is full: requested allocation %{public}zu bytes," + " free space %{public}zu bytes, block size %{public}zu bytes", + size, mSize - mHeader->unusedOffset, mSize); + return 0; + } + nextFreeOffset = offset + size; + mHeader->unusedOffset = nextFreeOffset; + return offset; +} + +inline uint32_t *SharedBlock::GetRowOffset(uint32_t row) +{ + uint32_t rowPos = row; + + RowGroupHeader *group = static_cast(OffsetToPtr(mHeader->firstRowGroupOffset)); + if (group == nullptr) { + LOG_ERROR("Failed to get group in getRowOffset()."); + return nullptr; + } + + while (rowPos >= ROW_OFFSETS_NUM) { + group = static_cast(OffsetToPtr(group->nextGroupOffset)); + if (group == nullptr) { + LOG_ERROR("Failed to get group in OffsetToPtr(group->nextGroupOffset) when while loop."); + return nullptr; + } + rowPos -= ROW_OFFSETS_NUM; + } + + return &group->rowOffsets[rowPos]; +} + +uint32_t *SharedBlock::AllocRowOffset() +{ + uint32_t rowPos = mHeader->rowNums; + + RowGroupHeader *group = static_cast(OffsetToPtr(mHeader->firstRowGroupOffset)); + if (group == nullptr) { + LOG_ERROR("Failed to get group in allocRowOffset()."); + return nullptr; + } + + while (rowPos > ROW_OFFSETS_NUM) { + group = static_cast(OffsetToPtr(group->nextGroupOffset)); + if (group == nullptr) { + LOG_ERROR("Failed to get group in OffsetToPtr(group->nextGroupOffset) when while loop."); + return nullptr; + } + rowPos -= ROW_OFFSETS_NUM; + } + if (rowPos == ROW_OFFSETS_NUM) { + if (!group->nextGroupOffset) { + /* Aligned */ + group->nextGroupOffset = Alloc(sizeof(RowGroupHeader), true); + if (!group->nextGroupOffset) { + return nullptr; + } + } + group = static_cast(OffsetToPtr(group->nextGroupOffset)); + if (group == nullptr) { + LOG_ERROR("Failed to get group in OffsetToPtr(group->nextGroupOffset)."); + return nullptr; + } + group->nextGroupOffset = 0; + rowPos = 0; + } + + mHeader->rowNums += 1; + return &group->rowOffsets[rowPos]; +} + +SharedBlock::CellUnit *SharedBlock::GetCellUnit(uint32_t row, uint32_t column) +{ + if (row >= mHeader->rowNums || column >= mHeader->columnNums) { + LOG_ERROR("Failed to read row %{public}" PRIu32 ", column %{public}" PRIu32 " from a SharedBlock" + " which has %{public}" PRIu32 " rows, %{public}" PRIu32 " columns.", + row, column, mHeader->rowNums, mHeader->columnNums); + return nullptr; + } + + uint32_t *rowOffset = GetRowOffset(row); + if (!rowOffset) { + LOG_ERROR("Failed to find rowOffset for row %{public}" PRIu32 ".", row); + return nullptr; + } + + CellUnit *cellUnit = static_cast(OffsetToPtr(*rowOffset)); + if (!cellUnit) { + LOG_ERROR("Failed to find cellUnit for rowOffset %{public}" PRIu32 ".", *rowOffset); + return nullptr; + } + + return &cellUnit[column]; +} + +int SharedBlock::PutBlob(uint32_t row, uint32_t column, const void *value, size_t size) +{ + return PutBlobOrString(row, column, value, size, CELL_UNIT_TYPE_BLOB); +} + +int SharedBlock::PutString(uint32_t row, uint32_t column, const char *value, size_t sizeIncludingNull) +{ + return PutBlobOrString(row, column, value, sizeIncludingNull, CELL_UNIT_TYPE_STRING); +} + +int SharedBlock::PutBlobOrString(uint32_t row, uint32_t column, const void *value, size_t size, int32_t type) +{ + if (mReadOnly) { + return SHARED_BLOCK_INVALID_OPERATION; + } + + CellUnit *cellUnit = GetCellUnit(row, column); + if (!cellUnit) { + return SHARED_BLOCK_BAD_VALUE; + } + + uint32_t offset = Alloc(size); + if (!offset) { + return SHARED_BLOCK_NO_MEMORY; + } + + void *ptr = OffsetToPtr(offset); + if (!ptr) { + return SHARED_BLOCK_NO_MEMORY; + } + + if (size != 0) { + errno_t result = memcpy_s(ptr, size, value, size); + if (result != EOK) { + return SHARED_BLOCK_NO_MEMORY; + } + } + + cellUnit->type = type; + cellUnit->cell.stringOrBlobValue.offset = offset; + cellUnit->cell.stringOrBlobValue.size = size; + return SHARED_BLOCK_OK; +} + +int SharedBlock::PutLong(uint32_t row, uint32_t column, int64_t value) +{ + if (mReadOnly) { + return SHARED_BLOCK_INVALID_OPERATION; + } + + CellUnit *cellUnit = GetCellUnit(row, column); + if (!cellUnit) { + return SHARED_BLOCK_BAD_VALUE; + } + + cellUnit->type = CELL_UNIT_TYPE_INTEGER; + cellUnit->cell.longValue = value; + return SHARED_BLOCK_OK; +} + +int SharedBlock::PutDouble(uint32_t row, uint32_t column, double value) +{ + if (mReadOnly) { + return SHARED_BLOCK_INVALID_OPERATION; + } + + CellUnit *cellUnit = GetCellUnit(row, column); + if (!cellUnit) { + return SHARED_BLOCK_BAD_VALUE; + } + + cellUnit->type = CELL_UNIT_TYPE_FLOAT; + cellUnit->cell.doubleValue = value; + return SHARED_BLOCK_OK; +} + +int SharedBlock::PutNull(uint32_t row, uint32_t column) +{ + if (mReadOnly) { + return SHARED_BLOCK_INVALID_OPERATION; + } + + CellUnit *cellUnit = GetCellUnit(row, column); + if (!cellUnit) { + return SHARED_BLOCK_BAD_VALUE; + } + + cellUnit->type = CELL_UNIT_TYPE_NULL; + cellUnit->cell.stringOrBlobValue.offset = 0; + cellUnit->cell.stringOrBlobValue.size = 0; + return SHARED_BLOCK_OK; +} + +size_t SharedBlock::SetRawData(const void *rawData, size_t size) +{ + if (size <= 0) { + LOG_ERROR("SharedBlock rawData is less than or equal to 0M"); + return SHARED_BLOCK_INVALID_OPERATION; + } + if (size > mSize) { + LOG_ERROR("SharedBlock size is %{public}zu, current byteArray size is %{public}zu", mSize, size); + return SHARED_BLOCK_NO_MEMORY; + } + + int result = memcpy_s(mHeader, mSize, rawData, size); + if (result != 0) { + return SHARED_BLOCK_NO_MEMORY; + } + return SHARED_BLOCK_OK; +} + +uint32_t SharedBlock::OffsetFromPtr(void *ptr) +{ + return static_cast(ptr) - static_cast(mData); +} +} // namespace AppDataFwk +} // namespace OHOS diff --git a/data_share/frameworks/native/consumer/include/connection_factory.h b/data_share/frameworks/native/consumer/include/connection_factory.h index 0d741e5ad0b6f9ec3995f5ea721fa474ffabaac7..26379376ffe8dc31955568fd207e47607123a56f 100644 --- a/data_share/frameworks/native/consumer/include/connection_factory.h +++ b/data_share/frameworks/native/consumer/include/connection_factory.h @@ -26,6 +26,7 @@ class ConnectionFactory { public: ~ConnectionFactory() = default; std::shared_ptr GetConnection(Uri &uri, const sptr token); + std::shared_ptr GetConnection(const Uri &uri, const CreateOptions &options); static ConnectionFactory& GetInstance(); private: diff --git a/data_share/frameworks/native/consumer/include/datashare_proxy.h b/data_share/frameworks/native/consumer/include/datashare_proxy.h index 90616dee7d272b274a66a74371e94e9b2851203c..81bef576cbf2564dba8e3667b22618a6e6759335 100644 --- a/data_share/frameworks/native/consumer/include/datashare_proxy.h +++ b/data_share/frameworks/native/consumer/include/datashare_proxy.h @@ -18,6 +18,7 @@ #include #include + #include "idatashare.h" namespace OHOS { @@ -58,10 +59,41 @@ public: virtual Uri DenormalizeUri(const Uri &uri) override; + int AddQueryTemplate(const std::string &uri, int64_t subscriberId, Template &tpl) override; + + int DelQueryTemplate(const std::string &uri, int64_t subscriberId) override; + + std::vector Publish(const Data &data, const std::string &bundleName) override; + + Data GetPublishedData(const std::string &bundleName) override; + + std::vector SubscribeRdbData(const std::vector &uris, const TemplateId &templateId, + const sptr &observer) override; + + std::vector UnSubscribeRdbData( + const std::vector &uris, const TemplateId &templateId) override; + + std::vector EnableSubscribeRdbData( + const std::vector &uris, const TemplateId &templateId) override; + + std::vector DisableSubscribeRdbData( + const std::vector &uris, const TemplateId &templateId) override; + + std::vector SubscribePublishedData(const std::vector &uris, int64_t subscriberId, + const sptr &observer) override; + + std::vector UnSubscribePublishedData( + const std::vector &uris, int64_t subscriberId) override; + + std::vector EnableSubscribePublishedData( + const std::vector &uris, int64_t subscriberId) override; + + std::vector DisableSubscribePublishedData( + const std::vector &uris, int64_t subscriberId) override; + private: static inline BrokerDelegator delegator_; }; } // namespace DataShare } // namespace OHOS #endif // DATASHARE_PROXY_H - diff --git a/data_share/frameworks/native/consumer/src/connection_factory.cpp b/data_share/frameworks/native/consumer/src/connection_factory.cpp index 2576f1a42cc789f071aeb78dabcaf47a9d491857..c411541db3ddfc49d88b8acc846ed52a279a186a 100644 --- a/data_share/frameworks/native/consumer/src/connection_factory.cpp +++ b/data_share/frameworks/native/consumer/src/connection_factory.cpp @@ -39,6 +39,21 @@ std::shared_ptr ConnectionFactory::GetConnection(Uri &uri, cons }); } +std::shared_ptr ConnectionFactory::GetConnection(const Uri &uri, const CreateOptions &options) +{ + if (options.isProxy_ && service_->ConnectDataShare(uri, options.token_)) { + return service_; + } + + sptr connection = new (std::nothrow) DataShareConnection(uri, options.token_); + if (connection == nullptr) { + LOG_ERROR("Factory Create DataShareConnection failed."); + return nullptr; + } + return std::shared_ptr( + connection.GetRefPtr(), [holder = connection](const auto *) {}); +} + ConnectionFactory& ConnectionFactory::GetInstance() { static ConnectionFactory manager; diff --git a/data_share/frameworks/native/consumer/src/datashare_connection.cpp b/data_share/frameworks/native/consumer/src/datashare_connection.cpp index 58e11e2d992f4e6d92839288ca15cbd9c40b5e2c..14b7471027ff4763a801dee051f2bcc6d2767ea4 100644 --- a/data_share/frameworks/native/consumer/src/datashare_connection.cpp +++ b/data_share/frameworks/native/consumer/src/datashare_connection.cpp @@ -90,7 +90,7 @@ bool DataShareConnection::ConnectDataShareExtAbility(const Uri &uri, const sptr< std::unique_lock lock(condition_.mutex); if (condition_.condition.wait_for(lock, std::chrono::seconds(WAIT_TIME), [this] { return dataShareProxy_ != nullptr; })) { - LOG_INFO("connect ability ended successfully"); + LOG_DEBUG("connect ability ended successfully"); } return dataShareProxy_ != nullptr; } @@ -112,7 +112,7 @@ void DataShareConnection::DisconnectDataShareExtAbility() std::unique_lock lock(condition_.mutex); if (condition_.condition.wait_for(lock, std::chrono::seconds(WAIT_TIME), [this] { return dataShareProxy_ == nullptr; })) { - LOG_INFO("disconnect ability successfully"); + LOG_DEBUG("disconnect ability successfully"); } else { LOG_INFO("disconnect timeout"); } diff --git a/data_share/frameworks/native/consumer/src/datashare_helper.cpp b/data_share/frameworks/native/consumer/src/datashare_helper.cpp index 829b1c36cf7086914f5fec786c9d01d2f660c82e..f46362903d7f3d7e60f59c4b51315e4f67bde4db 100644 --- a/data_share/frameworks/native/consumer/src/datashare_helper.cpp +++ b/data_share/frameworks/native/consumer/src/datashare_helper.cpp @@ -16,6 +16,7 @@ #include "datashare_helper.h" #include "connection_factory.h" +#include "concurrent_map.h" #include "data_ability_observer_interface.h" #include "data_ability_observer_stub.h" #include "dataobs_mgr_client.h" @@ -26,7 +27,11 @@ namespace OHOS { namespace DataShare { using namespace AppExecFwk; namespace { -const std::string SCHEME_DATASHARE = "datashare"; +static constexpr const char *SCHEME_DATASHARE = "datashare"; +static constexpr const char *SCHEME_DATASHARE_PROXY = "datashareproxy"; +static constexpr const char *FILE_SCHEMA = "file"; +static constexpr const char *DATA_SHARE_PREFIX = "datashare:///"; +static constexpr const char *FILE_PREFIX = "file://"; constexpr int INVALID_VALUE = -1; } // namespace class ObserverImpl : public AAFwk::DataAbilityObserverStub { @@ -37,11 +42,20 @@ public: void OnChangeExt(const ChangeInfo &info); static DataShareObserver::ChangeInfo ConvertInfo(const AAFwk::ChangeInfo &info); static AAFwk::ChangeInfo ConvertInfo(const DataShareObserver::ChangeInfo &info); - + static sptr GetObserver(const Uri& uri, const std::shared_ptr &observer); + static bool FindObserver(const Uri& uri, const std::shared_ptr &observer); + static bool DeleteObserver(const Uri& uri, const std::shared_ptr &observer); private: + struct ObserverParam { + sptr obs_; + std::list uris_; + }; std::shared_ptr dataShareObserver_; + static ConcurrentMap observers_; }; +ConcurrentMap ObserverImpl::observers_; + DataShareHelper::DataShareHelper(const sptr &token, const Uri &uri, std::shared_ptr dataShareConnection) { @@ -58,10 +72,31 @@ DataShareHelper::DataShareHelper(const sptr &token, const Uri &ur isDataShareService_ = (uri_.GetQuery().find("Proxy=true") != std::string::npos); } +DataShareHelper::DataShareHelper(const CreateOptions &options, const Uri &uri, + std::shared_ptr dataShareConnection) +{ + token_ = options.token_; + uri_ = uri; + isDataShareService_ = options.isProxy_; + connection_ = dataShareConnection; + rdbSubscriberManager_ = std::make_shared(); + publishedDataSubscriberManager_ = + std::make_shared(); +} + DataShareHelper::~DataShareHelper() { } +std::string DataShareHelper::TransferUriPrefix(const std::string &originPrefix, const std::string &replacedPrefix, + const std::string &originUriStr) +{ + if (originUriStr.find(originPrefix) != 0) { + return originUriStr; + } + return replacedPrefix + originUriStr.substr(originPrefix.length()); +} + /** * @brief You can use this method to specify the Uri of the data to operate and set the binding relationship * between the ability using the Data template (data share for short) and the associated client process in @@ -72,8 +107,8 @@ DataShareHelper::~DataShareHelper() * * @return Returns the created DataShareHelper instance. */ -std::shared_ptr DataShareHelper::Creator( - const std::shared_ptr &context, const std::string &strUri) +std::shared_ptr DataShareHelper::Creator(const std::shared_ptr &context, + const std::string &strUri) { if (context == nullptr) { LOG_ERROR("DataShareHelper::Creator failed, context == nullptr"); @@ -100,7 +135,9 @@ std::shared_ptr DataShareHelper::Creator(const sptr DataShareHelper::Creator(const sptr(ptrDataShareHelper); } +std::shared_ptr DataShareHelper::Creator(const string &strUri, const CreateOptions &options) +{ + Uri uri(strUri); + if (!options.isProxy_ && options.token_ == nullptr) { + LOG_ERROR("token is nullptr"); + return nullptr; + } + if (uri.GetScheme() != SCHEME_DATASHARE_PROXY) { + LOG_ERROR("the Scheme is not datashareproxy, Scheme: %{public}s", uri.GetScheme().c_str()); + return nullptr; + } + std::shared_ptr connection = ConnectionFactory::GetInstance().GetConnection(uri, options); + if (connection == nullptr) { + LOG_ERROR("create dataShareConnection failed"); + return nullptr; + } + if (!connection->ConnectDataShare(uri, options.token_)) { + LOG_ERROR("connect failed"); + return nullptr; + } + DataShareHelper *ptrDataShareHelper = new (std::nothrow) DataShareHelper(options, uri, connection); + if (ptrDataShareHelper == nullptr) { + LOG_ERROR("create DataShareHelper failed"); + connection = nullptr; + return nullptr; + } + return std::shared_ptr(ptrDataShareHelper); +} + /** * @brief Releases the client resource of the data share. * You should call this method to releases client resource after the data operations are complete. @@ -133,7 +199,6 @@ std::shared_ptr DataShareHelper::Creator(const sptr obs(new (std::nothrow) ObserverImpl(dataObserver)); + sptr obs = ObserverImpl::GetObserver(uri, dataObserver); if (obs == nullptr) { LOG_ERROR("new ObserverImpl failed"); return; } ErrCode ret = obsMgrClient->RegisterObserverExt(uri, obs, isDescendants); if (ret != ERR_OK) { + ObserverImpl::DeleteObserver(uri, dataObserver); LOG_ERROR("RegisterObserverExt failed"); } return; @@ -563,7 +629,13 @@ void DataShareHelper::UnregisterObserverExt(const Uri &uri, std::shared_ptr obs(new (std::nothrow) ObserverImpl(dataObserver)); + + if (!ObserverImpl::FindObserver(uri, dataObserver)) { + LOG_ERROR("observer not exit!"); + return; + } + + sptr obs = ObserverImpl::GetObserver(uri, dataObserver); if (obs == nullptr) { LOG_ERROR("new ObserverImpl failed"); return; @@ -571,6 +643,8 @@ void DataShareHelper::UnregisterObserverExt(const Uri &uri, std::shared_ptrUnregisterObserverExt(uri, obs); if (ret != ERR_OK) { LOG_ERROR("UnregisterObserverExt failed"); + } else { + ObserverImpl::DeleteObserver(uri, dataObserver); } return; } @@ -701,23 +775,7 @@ void ObserverImpl::OnChangeExt(const ChangeInfo &info) DataShareObserver::ChangeInfo ObserverImpl::ConvertInfo(const AAFwk::ChangeInfo &info) { DataShareObserver::ChangeInfo changeInfo; - switch (info.changeType_) { - case AAFwk::ChangeInfo::INSERT: - changeInfo.changeType_ = DataShareObserver::INSERT; - break; - case AAFwk::ChangeInfo::DELETE: - changeInfo.changeType_ = DataShareObserver::DELETE; - break; - case AAFwk::ChangeInfo::UPDATE: - changeInfo.changeType_ = DataShareObserver::UPDATE; - break; - case AAFwk::ChangeInfo::OTHER: - changeInfo.changeType_ = DataShareObserver::OTHER; - break; - default: - changeInfo.changeType_ = DataShareObserver::INVAILD; - break; - } + changeInfo.changeType_ = static_cast(info.changeType_); changeInfo.uris_ = std::move(info.uris_); changeInfo.data_ = info.data_; changeInfo.size_ = info.size_; @@ -727,27 +785,350 @@ DataShareObserver::ChangeInfo ObserverImpl::ConvertInfo(const AAFwk::ChangeInfo AAFwk::ChangeInfo ObserverImpl::ConvertInfo(const DataShareObserver::ChangeInfo &info) { AAFwk::ChangeInfo changeInfo; - switch (info.changeType_) { - case DataShareObserver::INSERT: - changeInfo.changeType_ = AAFwk::ChangeInfo::INSERT; - break; - case DataShareObserver::DELETE: - changeInfo.changeType_ = AAFwk::ChangeInfo::DELETE; - break; - case DataShareObserver::UPDATE: - changeInfo.changeType_ = AAFwk::ChangeInfo::UPDATE; - break; - case DataShareObserver::OTHER: - changeInfo.changeType_ = AAFwk::ChangeInfo::OTHER; - break; - default: - changeInfo.changeType_ = AAFwk::ChangeInfo::INVAILD; - break; - } + changeInfo.changeType_ = static_cast(info.changeType_); changeInfo.uris_ = std::move(info.uris_); - changeInfo.data_ = info.data_; + changeInfo.data_ = const_cast(info.data_); changeInfo.size_ = info.size_; return changeInfo; } + +sptr ObserverImpl::GetObserver(const Uri& uri, const std::shared_ptr &observer) +{ + sptr result = nullptr; + observers_.Compute(observer.get(), [&result, &uri, &observer](const auto &key, auto &value) { + if (value.obs_ == nullptr) { + value.obs_ = new (std::nothrow) ObserverImpl(observer); + value.uris_.push_back(uri); + } else { + auto it = std::find(value.uris_.begin(), value.uris_.end(), uri); + if (it == value.uris_.end()) { + value.uris_.push_back(uri); + } + } + + result = value.obs_; + return result != nullptr; + }); + + return result; +} + +bool ObserverImpl::FindObserver(const Uri& uri, const std::shared_ptr &observer) +{ + auto result = observers_.Find(observer.get()); + if (result.first) { + auto it = std::find(result.second.uris_.begin(), result.second.uris_.end(), uri); + if (it == result.second.uris_.end()) { + return false; + } + } + return result.first; +} + +bool ObserverImpl::DeleteObserver(const Uri& uri, const std::shared_ptr &observer) +{ + return observers_.ComputeIfPresent(observer.get(), [&uri](auto &key, auto &value) { + value.uris_.remove_if([&uri](const auto &value) { + return uri == value; + }); + return !value.uris_.empty(); + }); +} + +int DataShareHelper::AddQueryTemplate(const std::string &uri, int64_t subscriberId, Template &tpl) +{ + int errNum = INVALID_VALUE; + auto connection = connection_; + if (connection == nullptr) { + LOG_ERROR("dataShareConnection_ is nullptr"); + return errNum; + } + if (!connection->ConnectDataShare(uri_, token_)) { + LOG_ERROR("dataShareProxy is nullptr"); + return errNum; + } + auto proxy = connection->GetDataShareProxy(); + if (proxy == nullptr) { + LOG_ERROR("GetDataShareProxy is nullptr"); + return errNum; + } + return proxy->AddQueryTemplate(uri, subscriberId, tpl); +} + +int DataShareHelper::DelQueryTemplate(const std::string &uri, int64_t subscriberId) +{ + int errNum = INVALID_VALUE; + auto connection = connection_; + if (connection == nullptr) { + LOG_ERROR("dataShareConnection_ is nullptr"); + return errNum; + } + if (!connection->ConnectDataShare(uri_, token_)) { + LOG_ERROR("dataShareProxy is nullptr"); + return errNum; + } + auto proxy = connection->GetDataShareProxy(); + if (proxy == nullptr) { + LOG_ERROR("GetDataShareProxy is nullptr"); + return errNum; + } + return proxy->DelQueryTemplate(uri, subscriberId); +} + +std::vector DataShareHelper::Publish(const Data &data, + const std::string &bundleName) +{ + std::vector results; + auto connection = connection_; + if (connection == nullptr) { + LOG_ERROR("dataShareConnection_ is nullptr"); + return results; + } + if (!connection->ConnectDataShare(uri_, token_)) { + LOG_ERROR("dataShareProxy is nullptr"); + return results; + } + auto proxy = connection->GetDataShareProxy(); + if (proxy == nullptr) { + LOG_ERROR("GetDataShareProxy is nullptr"); + return results; + } + return proxy->Publish(data, bundleName); +} + +Data DataShareHelper::GetPublishedData(const std::string &bundleName) +{ + Data results; + auto connection = connection_; + if (connection == nullptr) { + LOG_ERROR("dataShareConnection_ is nullptr"); + return results; + } + if (!connection->ConnectDataShare(uri_, token_)) { + LOG_ERROR("dataShareProxy is nullptr"); + return results; + } + auto proxy = connection->GetDataShareProxy(); + if (proxy == nullptr) { + LOG_ERROR("GetDataShareProxy is nullptr"); + return results; + } + return proxy->GetPublishedData(bundleName); +} + +std::vector DataShareHelper::SubscribeRdbData(const std::vector &uris, + const TemplateId &templateId, const std::function &callback) +{ + LOG_DEBUG("Start SubscribeRdbData"); + std::vector results; + auto connection = connection_; + if (connection == nullptr) { + LOG_ERROR("dataShareConnection_ is nullptr"); + return results; + } + if (!connection->ConnectDataShare(uri_, token_)) { + LOG_ERROR("dataShareProxy is nullptr"); + return results; + } + auto proxy = connection->GetDataShareProxy(); + if (proxy == nullptr) { + LOG_ERROR("dataShareProxy is nullptr"); + return results; + } + auto manager = rdbSubscriberManager_; + if (manager == nullptr) { + LOG_ERROR("rdbSubscriberManager_ is nullptr"); + return results; + } + return manager->AddObservers(proxy, uris, templateId, callback); +} + +std::vector DataShareHelper::UnsubscribeRdbData(const std::vector &uris, + const TemplateId &templateId) +{ + LOG_DEBUG("Start UnsubscribeRdbData"); + std::vector results; + auto connection = connection_; + if (connection == nullptr) { + LOG_ERROR("dataShareConnection_ is nullptr"); + return results; + } + if (!connection->ConnectDataShare(uri_, token_)) { + LOG_ERROR("dataShareProxy is nullptr"); + return results; + } + auto proxy = connection->GetDataShareProxy(); + if (proxy == nullptr) { + LOG_ERROR("dataShareProxy is nullptr"); + return results; + } + auto manager = rdbSubscriberManager_; + if (manager == nullptr) { + LOG_ERROR("rdbSubscriberManager_ is nullptr"); + return results; + } + return manager->DelObservers(proxy, uris, templateId); +} + +std::vector DataShareHelper::EnableRdbSubs(const std::vector &uris, + const TemplateId &templateId) +{ + LOG_DEBUG("Start EnableSubscribeRdbData"); + std::vector results; + auto connection = connection_; + if (connection == nullptr) { + LOG_ERROR("dataShareConnection_ is nullptr"); + return results; + } + if (!connection->ConnectDataShare(uri_, token_)) { + LOG_ERROR("dataShareProxy is nullptr"); + return results; + } + auto proxy = connection->GetDataShareProxy(); + if (proxy == nullptr) { + LOG_ERROR("dataShareProxy is nullptr"); + return results; + } + auto manager = rdbSubscriberManager_; + if (manager == nullptr) { + LOG_ERROR("rdbSubscriberManager_ is nullptr"); + return results; + } + return manager->EnableObservers(proxy, uris, templateId); +} + +std::vector DataShareHelper::DisableRdbSubs(const std::vector &uris, + const TemplateId &templateId) +{ + LOG_DEBUG("Start DisableSubscribeRdbData"); + std::vector results; + auto connection = connection_; + if (connection == nullptr) { + LOG_ERROR("dataShareConnection_ is nullptr"); + return results; + } + if (!connection->ConnectDataShare(uri_, token_)) { + LOG_ERROR("dataShareProxy is nullptr"); + return results; + } + auto proxy = connection->GetDataShareProxy(); + if (proxy == nullptr) { + LOG_ERROR("dataShareProxy is nullptr"); + return results; + } + auto manager = rdbSubscriberManager_; + if (manager == nullptr) { + LOG_ERROR("rdbSubscriberManager_ is nullptr"); + return results; + } + return manager->DisableObservers(proxy, uris, templateId); +} + +std::vector DataShareHelper::SubscribePublishedData(const std::vector &uris, + int64_t subscriberId, const std::function &callback) +{ + std::vector results; + auto connection = connection_; + if (connection == nullptr) { + LOG_ERROR("dataShareConnection_ is nullptr"); + return results; + } + if (!connection->ConnectDataShare(uri_, token_)) { + LOG_ERROR("dataShareProxy is nullptr"); + return results; + } + auto proxy = connection->GetDataShareProxy(); + if (proxy == nullptr) { + LOG_ERROR("dataShareProxy is nullptr"); + return results; + } + auto manager = publishedDataSubscriberManager_; + if (manager == nullptr) { + LOG_ERROR("rdbSubscriberManager_ is nullptr"); + return results; + } + return manager->AddObservers(proxy, uris, subscriberId, callback); +} + +std::vector DataShareHelper::UnsubscribePublishedData(const std::vector &uris, + int64_t subscriberId) +{ + LOG_DEBUG("Start UnSubscribePublishedData"); + std::vector results; + auto connection = connection_; + if (connection == nullptr) { + LOG_ERROR("dataShareConnection_ is nullptr"); + return results; + } + if (!connection->ConnectDataShare(uri_, token_)) { + LOG_ERROR("dataShareProxy is nullptr"); + return results; + } + auto proxy = connection->GetDataShareProxy(); + if (proxy == nullptr) { + LOG_ERROR("dataShareProxy is nullptr"); + return results; + } + auto manager = publishedDataSubscriberManager_; + if (manager == nullptr) { + LOG_ERROR("rdbSubscriberManager_ is nullptr"); + return results; + } + return manager->DelObservers(proxy, uris, subscriberId); +} + +std::vector DataShareHelper::EnablePubSubs(const std::vector &uris, + int64_t subscriberId) +{ + LOG_DEBUG("Start UnSubscribePublishedData"); + std::vector results; + auto connection = connection_; + if (connection == nullptr) { + LOG_ERROR("dataShareConnection_ is nullptr"); + return results; + } + if (!connection->ConnectDataShare(uri_, token_)) { + LOG_ERROR("dataShareProxy is nullptr"); + return results; + } + auto proxy = connection->GetDataShareProxy(); + if (proxy == nullptr) { + LOG_ERROR("dataShareProxy is nullptr"); + return results; + } + auto manager = publishedDataSubscriberManager_; + if (manager == nullptr) { + LOG_ERROR("rdbSubscriberManager_ is nullptr"); + return results; + } + return manager->EnableObservers(proxy, uris, subscriberId); +} + +std::vector DataShareHelper::DisablePubSubs(const std::vector &uris, + int64_t subscriberId) +{ + LOG_DEBUG("Start UnSubscribePublishedData"); + std::vector results; + auto connection = connection_; + if (connection == nullptr) { + LOG_ERROR("dataShareConnection_ is nullptr"); + return results; + } + if (!connection->ConnectDataShare(uri_, token_)) { + LOG_ERROR("dataShareProxy is nullptr"); + return results; + } + auto proxy = connection->GetDataShareProxy(); + if (proxy == nullptr) { + LOG_ERROR("dataShareProxy is nullptr"); + return results; + } + auto manager = publishedDataSubscriberManager_; + if (manager == nullptr) { + LOG_ERROR("rdbSubscriberManager_ is nullptr"); + return results; + } + return manager->DisableObservers(proxy, uris, subscriberId); +} } // namespace DataShare } // namespace OHOS \ No newline at end of file diff --git a/data_share/frameworks/native/consumer/src/datashare_proxy.cpp b/data_share/frameworks/native/consumer/src/datashare_proxy.cpp index fb79f89f5b2bb94f057377e76dce54021941360d..a9f48779a42607477039878f611ccd5c577043ad 100644 --- a/data_share/frameworks/native/consumer/src/datashare_proxy.cpp +++ b/data_share/frameworks/native/consumer/src/datashare_proxy.cpp @@ -17,13 +17,13 @@ #include -#include "datashare_result_set.h" #include "data_ability_observer_interface.h" +#include "datashare_itypes_utils.h" #include "datashare_log.h" +#include "datashare_result_set.h" #include "ipc_types.h" #include "ishared_result_set.h" #include "pac_map.h" -#include "itypes_utils.h" namespace OHOS { namespace DataShare { @@ -143,17 +143,10 @@ int DataShareProxy::Insert(const Uri &uri, const DataShareValuesBucket &value) LOG_ERROR("WriteInterfaceToken failed"); return index; } - - if (!data.WriteParcelable(&uri)) { - LOG_ERROR("fail to WriteParcelable uri"); - return index; - } - - if (!ITypesUtils::Marshalling(value, data)) { - LOG_ERROR("fail to WriteParcelable value"); + if (!ITypesUtil::Marshal(data, uri, value)) { + LOG_ERROR("fail to Marshal value"); return index; } - MessageParcel reply; MessageOption option; int32_t err = Remote()->SendRequest(CMD_INSERT, data, reply, option); @@ -161,9 +154,8 @@ int DataShareProxy::Insert(const Uri &uri, const DataShareValuesBucket &value) LOG_ERROR("Insert fail to SendRequest. err: %{public}d", err); return err == PERMISSION_ERR ? PERMISSION_ERR_CODE : index; } - - if (!reply.ReadInt32(index)) { - LOG_ERROR("fail to ReadInt32 index"); + if (!ITypesUtil::Unmarshal(reply, index)) { + LOG_ERROR("fail to Unmarshal index"); return index; } @@ -179,22 +171,10 @@ int DataShareProxy::Update(const Uri &uri, const DataSharePredicates &predicates LOG_ERROR("WriteInterfaceToken failed"); return index; } - - if (!data.WriteParcelable(&uri)) { - LOG_ERROR("fail to WriteParcelable uri"); - return index; - } - - if (!ITypesUtils::Marshalling(predicates, data)) { - LOG_ERROR("fail to Marshalling predicates"); + if (!ITypesUtil::Marshal(data, uri, predicates, value)) { + LOG_ERROR("fail to Marshal value"); return index; } - - if (!ITypesUtils::Marshalling(value, data)) { - LOG_ERROR("fail to Marshalling value"); - return index; - } - MessageParcel reply; MessageOption option; int32_t err = Remote()->SendRequest(CMD_UPDATE, data, reply, option); @@ -202,12 +182,10 @@ int DataShareProxy::Update(const Uri &uri, const DataSharePredicates &predicates LOG_ERROR("Update fail to SendRequest. err: %{public}d", err); return err == PERMISSION_ERR ? PERMISSION_ERR_CODE : index; } - - if (!reply.ReadInt32(index)) { - LOG_ERROR("fail to ReadInt32 index"); + if (!ITypesUtil::Unmarshal(reply, index)) { + LOG_ERROR("fail to Unmarshal index"); return index; } - return index; } @@ -219,13 +197,7 @@ int DataShareProxy::Delete(const Uri &uri, const DataSharePredicates &predicates LOG_ERROR("WriteInterfaceToken failed"); return index; } - - if (!data.WriteParcelable(&uri)) { - LOG_ERROR("fail to WriteParcelable uri"); - return index; - } - - if (!ITypesUtils::Marshalling(predicates, data)) { + if (!ITypesUtil::Marshal(data, uri, predicates)) { LOG_ERROR("fail to Marshalling predicates"); return index; } @@ -237,12 +209,10 @@ int DataShareProxy::Delete(const Uri &uri, const DataSharePredicates &predicates LOG_ERROR("Delete fail to SendRequest. err: %{public}d", err); return err == PERMISSION_ERR ? PERMISSION_ERR_CODE : index; } - - if (!reply.ReadInt32(index)) { - LOG_ERROR("fail to ReadInt32 index"); + if (!ITypesUtil::Unmarshal(reply, index)) { + LOG_ERROR("fail to Unmarshal index"); return index; } - return index; } @@ -254,22 +224,10 @@ std::shared_ptr DataShareProxy::Query(const Uri &uri, LOG_ERROR("WriteInterfaceToken failed"); return nullptr; } - - if (!data.WriteParcelable(&uri)) { - LOG_ERROR("fail to WriteParcelable uri"); - return nullptr; - } - - if (!ITypesUtils::Marshalling(predicates, data)) { - LOG_ERROR("fail to Marshalling predicates"); + if (!ITypesUtil::Marshal(data, uri, predicates, columns)) { + LOG_ERROR("fail to Marshalling"); return nullptr; } - - if (!data.WriteStringVector(columns)) { - LOG_ERROR("fail to WriteStringVector columns"); - return nullptr; - } - MessageParcel reply; MessageOption option; int32_t err = Remote()->SendRequest(CMD_QUERY, data, reply, option); @@ -292,8 +250,9 @@ std::string DataShareProxy::GetType(const Uri &uri) LOG_ERROR("WriteInterfaceToken failed"); return type; } - if (!data.WriteParcelable(&uri)) { - LOG_ERROR("fail to WriteParcelable uri"); + + if (!ITypesUtil::Marshal(data, uri)) { + LOG_ERROR("fail to Marshal value"); return type; } @@ -304,8 +263,10 @@ std::string DataShareProxy::GetType(const Uri &uri) LOG_ERROR("GetFileTypes fail to SendRequest. err: %{public}d", err); return type; } - - type = reply.ReadString(); + if (!ITypesUtil::Unmarshal(reply, type)) { + LOG_ERROR("fail to Unmarshal index"); + return type; + } if (type.empty()) { LOG_ERROR("fail to ReadString type"); return type; @@ -324,25 +285,11 @@ int DataShareProxy::BatchInsert(const Uri &uri, const std::vectorSendRequest(CMD_BATCH_INSERT, data, reply, option); @@ -350,12 +297,10 @@ int DataShareProxy::BatchInsert(const Uri &uri, const std::vectorAsObject())) { - LOG_ERROR("failed to WriteParcelable dataObserver "); + if (!ITypesUtil::Marshal(data, uri, dataObserver->AsObject())) { + LOG_ERROR("fail to Marshalling"); return false; } @@ -400,14 +340,8 @@ bool DataShareProxy::UnregisterObserver(const Uri &uri, const sptrAsObject())) { - LOG_ERROR("failed to WriteParcelable dataObserver "); + if (!ITypesUtil::Marshal(data, uri, dataObserver->AsObject())) { + LOG_ERROR("fail to Marshalling"); return false; } @@ -432,9 +366,8 @@ bool DataShareProxy::NotifyChange(const Uri &uri) LOG_ERROR("WriteInterfaceToken failed"); return false; } - - if (!data.WriteParcelable(&uri)) { - LOG_ERROR("failed to WriteParcelable uri "); + if (!ITypesUtil::Marshal(data, uri)) { + LOG_ERROR("fail to Marshalling"); return false; } @@ -454,16 +387,14 @@ bool DataShareProxy::NotifyChange(const Uri &uri) Uri DataShareProxy::NormalizeUri(const Uri &uri) { LOG_INFO("begin."); - Uri urivalue(""); MessageParcel data; if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { LOG_ERROR("WriteInterfaceToken failed"); - return urivalue; + return Uri(""); } - - if (!data.WriteParcelable(&uri)) { - LOG_ERROR("fail to WriteParcelable uri"); - return urivalue; + if (!ITypesUtil::Marshal(data, uri)) { + LOG_ERROR("fail to Marshalling"); + return Uri(""); } MessageParcel reply; @@ -471,31 +402,29 @@ Uri DataShareProxy::NormalizeUri(const Uri &uri) int32_t err = Remote()->SendRequest(CMD_NORMALIZE_URI, data, reply, option); if (err != DATA_SHARE_NO_ERROR) { LOG_ERROR("NormalizeUri fail to SendRequest. err: %{public}d", err); - return urivalue; + return Uri(""); } - - std::unique_ptr info(reply.ReadParcelable()); - if (!info) { - LOG_ERROR("ReadParcelable value is nullptr."); - return urivalue; + Uri info(""); + if (!ITypesUtil::Unmarshal(reply, info)) { + LOG_ERROR("fail to Unmarshal index"); + return Uri(""); } LOG_INFO("end successfully."); - return *info; + return info; } Uri DataShareProxy::DenormalizeUri(const Uri &uri) { LOG_INFO("begin."); - Uri urivalue(""); MessageParcel data; if (!data.WriteInterfaceToken(DataShareProxy::GetDescriptor())) { LOG_ERROR("WriteInterfaceToken failed"); - return urivalue; + return Uri(""); } - if (!data.WriteParcelable(&uri)) { - LOG_ERROR("fail to WriteParcelable uri"); - return urivalue; + if (!ITypesUtil::Marshal(data, uri)) { + LOG_ERROR("fail to Marshalling"); + return Uri(""); } MessageParcel reply; @@ -503,16 +432,84 @@ Uri DataShareProxy::DenormalizeUri(const Uri &uri) int32_t err = Remote()->SendRequest(CMD_DENORMALIZE_URI, data, reply, option); if (err != DATA_SHARE_NO_ERROR) { LOG_ERROR("DenormalizeUri fail to SendRequest. err: %{public}d", err); - return urivalue; + return Uri(""); } - std::unique_ptr info(reply.ReadParcelable()); - if (!info) { - LOG_ERROR("ReadParcelable value is nullptr."); - return urivalue; + Uri info(""); + if (!ITypesUtil::Unmarshal(reply, info)) { + LOG_ERROR("fail to Unmarshal index"); + return Uri(""); } LOG_INFO("end successfully."); - return *info; + return info; +} + +int DataShareProxy::AddQueryTemplate(const std::string &uri, int64_t subscriberId, Template &tpl) +{ + return -1; +} + +int DataShareProxy::DelQueryTemplate(const std::string &uri, int64_t subscriberId) +{ + return -1; +} + +std::vector DataShareProxy::Publish(const Data &data, const std::string &bundleName) +{ + return std::vector(); +} + +Data DataShareProxy::GetPublishedData(const std::string &bundleName) +{ + return Data(); +} + +std::vector DataShareProxy::SubscribeRdbData(const std::vector &uris, + const TemplateId &templateId, const sptr &observer) +{ + return std::vector(); +} + +std::vector DataShareProxy::UnSubscribeRdbData( + const std::vector &uris, const TemplateId &templateId) +{ + return {}; +} + +std::vector DataShareProxy::EnableSubscribeRdbData( + const std::vector &uris, const TemplateId &templateId) +{ + return {}; +} + +std::vector DataShareProxy::DisableSubscribeRdbData( + const std::vector &uris, const TemplateId &templateId) +{ + return {}; +} + +std::vector DataShareProxy::SubscribePublishedData( + const std::vector &uris, int64_t subscriberId, const sptr &observer) +{ + return {}; +} + +std::vector DataShareProxy::UnSubscribePublishedData( + const std::vector &uris, int64_t subscriberId) +{ + return {}; +} + +std::vector DataShareProxy::EnableSubscribePublishedData( + const std::vector &uris, int64_t subscriberId) +{ + return {}; +} + +std::vector DataShareProxy::DisableSubscribePublishedData( + const std::vector &uris, int64_t subscriberId) +{ + return {}; } } // namespace DataShare } // namespace OHOS \ No newline at end of file diff --git a/data_share/frameworks/native/provider/include/datashare_stub.h b/data_share/frameworks/native/provider/include/datashare_stub.h index 668e86d7e2eb4a1199506c4a53010f5526251be9..ddd7c23cdd472c6d177261a4910823ca11f7d6fb 100644 --- a/data_share/frameworks/native/provider/include/datashare_stub.h +++ b/data_share/frameworks/native/provider/include/datashare_stub.h @@ -19,8 +19,8 @@ #include #include -#include "idatashare.h" #include "datashare_business_error.h" +#include "idatashare.h" namespace OHOS { namespace DataShare { @@ -28,7 +28,8 @@ class DataShareStub : public IRemoteStub, public BaseProxy { public: DataShareStub(); ~DataShareStub(); - int OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option) override; + int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + private: ErrCode CmdGetFileTypes(MessageParcel &data, MessageParcel &reply); ErrCode CmdOpenFile(MessageParcel &data, MessageParcel &reply); @@ -45,6 +46,27 @@ private: ErrCode CmdNormalizeUri(MessageParcel &data, MessageParcel &reply); ErrCode CmdDenormalizeUri(MessageParcel &data, MessageParcel &reply); + int AddQueryTemplate(const std::string &uri, int64_t subscriberId, Template &tpl) override; + int DelQueryTemplate(const std::string &uri, int64_t subscriberId) override; + std::vector Publish(const Data &data, const std::string &bundleName) override; + Data GetPublishedData(const std::string &bundleName) override; + std::vector SubscribeRdbData(const std::vector &uris, const TemplateId &templateId, + const sptr &observer) override; + std::vector UnSubscribeRdbData( + const std::vector &uris, const TemplateId &templateId) override; + std::vector EnableSubscribeRdbData( + const std::vector &uris, const TemplateId &templateId) override; + std::vector DisableSubscribeRdbData( + const std::vector &uris, const TemplateId &templateId) override; + std::vector SubscribePublishedData(const std::vector &uris, int64_t subscriberId, + const sptr &observer) override; + std::vector UnSubscribePublishedData( + const std::vector &uris, int64_t subscriberId) override; + std::vector EnableSubscribePublishedData( + const std::vector &uris, int64_t subscriberId) override; + std::vector DisableSubscribePublishedData( + const std::vector &uris, int64_t subscriberId) override; + using RequestFuncType = int (DataShareStub::*)(MessageParcel &data, MessageParcel &reply); std::map stubFuncMap_; static constexpr int VALUEBUCKET_MAX_COUNT = 3000; diff --git a/data_share/frameworks/native/provider/include/datashare_stub_impl.h b/data_share/frameworks/native/provider/include/datashare_stub_impl.h index 620b1e2659f7c07931e00dde32e80ce61cf4ba49..6f5bc2d7d9be6529a3e4ea508bead01d46f57666 100644 --- a/data_share/frameworks/native/provider/include/datashare_stub_impl.h +++ b/data_share/frameworks/native/provider/include/datashare_stub_impl.h @@ -64,6 +64,26 @@ public: Uri NormalizeUri(const Uri &uri) override; Uri DenormalizeUri(const Uri &uri) override; + int AddQueryTemplate(const std::string &uri, int64_t subscriberId, Template &tpl) override; + int DelQueryTemplate(const std::string &uri, int64_t subscriberId) override; + std::vector Publish(const Data &data, const std::string &bundleName) override; + Data GetPublishedData(const std::string &bundleName) override; + std::vector SubscribeRdbData(const std::vector &uris, const TemplateId &templateId, + const sptr &observer) override; + std::vector UnSubscribeRdbData( + const std::vector &uris, const TemplateId &templateId) override; + std::vector EnableSubscribeRdbData( + const std::vector &uris, const TemplateId &templateId) override; + std::vector DisableSubscribeRdbData( + const std::vector &uris, const TemplateId &templateId) override; + std::vector SubscribePublishedData(const std::vector &uris, int64_t subscriberId, + const sptr &observer) override; + std::vector UnSubscribePublishedData( + const std::vector &uris, int64_t subscriberId) override; + std::vector EnableSubscribePublishedData( + const std::vector &uris, int64_t subscriberId) override; + std::vector DisableSubscribePublishedData( + const std::vector &uris, int64_t subscriberId) override; private: std::shared_ptr GetOwner(); diff --git a/data_share/frameworks/native/provider/src/datashare_stub.cpp b/data_share/frameworks/native/provider/src/datashare_stub.cpp index 459ee9ec977302635dab866e3c953d15d3022ac3..4d0ba05cbbf8c8a717dc5d0f3068bc9fc735ebbc 100644 --- a/data_share/frameworks/native/provider/src/datashare_stub.cpp +++ b/data_share/frameworks/native/provider/src/datashare_stub.cpp @@ -16,10 +16,10 @@ #include "datashare_stub.h" #include "data_ability_observer_interface.h" +#include "datashare_itypes_utils.h" #include "datashare_log.h" #include "ipc_types.h" #include "ishared_result_set.h" -#include "itypes_utils.h" #include "unistd.h" namespace OHOS { @@ -68,30 +68,21 @@ int DataShareStub::OnRemoteRequest(uint32_t code, MessageParcel& data, MessagePa return IPCObjectStub::OnRemoteRequest(code, data, reply, option); } -bool ReadUri(std::shared_ptr &uri, MessageParcel &data) -{ - uri = std::shared_ptr(data.ReadParcelable()); - if (uri == nullptr) { - LOG_ERROR("uri is nullptr"); - return false; - } - return true; -} - ErrCode DataShareStub::CmdGetFileTypes(MessageParcel &data, MessageParcel &reply) { - std::shared_ptr uri = nullptr; - if (!ReadUri(uri, data)) { + Uri uri(""); + std::string mimeTypeFilter; + if (!ITypesUtil::Unmarshal(data, uri, mimeTypeFilter)) { + LOG_ERROR("Unmarshalling value is nullptr"); return ERR_INVALID_VALUE; } - std::string mimeTypeFilter = data.ReadString(); if (mimeTypeFilter.empty()) { LOG_ERROR("mimeTypeFilter is nullptr"); return ERR_INVALID_VALUE; } - std::vector types = GetFileTypes(*uri, mimeTypeFilter); - if (!reply.WriteStringVector(types)) { - LOG_ERROR("fail to WriteStringVector types"); + std::vector types = GetFileTypes(uri, mimeTypeFilter); + if (!ITypesUtil::Marshal(reply, types)) { + LOG_ERROR("Marshal value is nullptr"); return ERR_INVALID_VALUE; } return DATA_SHARE_NO_ERROR; @@ -99,16 +90,17 @@ ErrCode DataShareStub::CmdGetFileTypes(MessageParcel &data, MessageParcel &reply ErrCode DataShareStub::CmdOpenFile(MessageParcel &data, MessageParcel &reply) { - std::shared_ptr uri = nullptr; - if (!ReadUri(uri, data)) { + Uri uri(""); + std::string mode; + if (!ITypesUtil::Unmarshal(data, uri, mode)) { + LOG_ERROR("Unmarshalling value is nullptr"); return ERR_INVALID_VALUE; } - std::string mode = data.ReadString(); if (mode.empty()) { LOG_ERROR("mode is nullptr"); return ERR_INVALID_VALUE; } - int fd = OpenFile(*uri, mode); + int fd = OpenFile(uri, mode); if (fd < 0) { LOG_ERROR("OpenFile fail, fd is %{pubilc}d", fd); return ERR_INVALID_VALUE; @@ -124,18 +116,15 @@ ErrCode DataShareStub::CmdOpenFile(MessageParcel &data, MessageParcel &reply) ErrCode DataShareStub::CmdOpenRawFile(MessageParcel &data, MessageParcel &reply) { - std::shared_ptr uri = nullptr; - if (!ReadUri(uri, data)) { - return ERR_INVALID_VALUE; - } - std::string mode = data.ReadString(); - if (mode.empty()) { - LOG_ERROR("mode is nullptr"); + Uri uri(""); + std::string mode; + if (!ITypesUtil::Unmarshal(data, uri, mode)) { + LOG_ERROR("Unmarshalling value is nullptr"); return ERR_INVALID_VALUE; } - int fd = OpenRawFile(*uri, mode); - if (!reply.WriteInt32(fd)) { - LOG_ERROR("fail to WriteInt32 fd"); + int fd = OpenRawFile(uri, mode); + if (!ITypesUtil::Marshal(reply, fd)) { + LOG_ERROR("Marshal value is nullptr"); return ERR_INVALID_VALUE; } return DATA_SHARE_NO_ERROR; @@ -143,17 +132,13 @@ ErrCode DataShareStub::CmdOpenRawFile(MessageParcel &data, MessageParcel &reply) ErrCode DataShareStub::CmdInsert(MessageParcel &data, MessageParcel &reply) { - std::shared_ptr uri(data.ReadParcelable()); - if (uri == nullptr) { - LOG_ERROR("DataShareStub uri is nullptr"); - return ERR_INVALID_VALUE; - } + Uri uri(""); DataShareValuesBucket value; - if (!ITypesUtils::Unmarshalling(data, value)) { + if (!ITypesUtil::Unmarshal(data, uri, value)) { LOG_ERROR("Unmarshalling value is nullptr"); return ERR_INVALID_VALUE; } - int index = Insert(*uri, value); + int index = Insert(uri, value); if (index == DEFAULT_NUMBER) { LOG_ERROR("Insert inner error"); return ERR_INVALID_VALUE; @@ -171,21 +156,14 @@ ErrCode DataShareStub::CmdInsert(MessageParcel &data, MessageParcel &reply) ErrCode DataShareStub::CmdUpdate(MessageParcel &data, MessageParcel &reply) { - std::shared_ptr uri = nullptr; - if (!ReadUri(uri, data)) { - return ERR_INVALID_VALUE; - } + Uri uri(""); DataSharePredicates predicates; - if (!ITypesUtils::Unmarshalling(data, predicates)) { - LOG_ERROR("Unmarshalling predicates is nullptr"); - return ERR_INVALID_VALUE; - } DataShareValuesBucket value; - if (!ITypesUtils::Unmarshalling(data, value)) { - LOG_ERROR("Unmarshalling value is nullptr"); + if (!ITypesUtil::Unmarshal(data, uri, predicates, value)) { + LOG_ERROR("Unmarshalling predicates is nullptr"); return ERR_INVALID_VALUE; } - int index = Update(*uri, predicates, value); + int index = Update(uri, predicates, value); if (index == DEFAULT_NUMBER) { LOG_ERROR("Update inner error"); return ERR_INVALID_VALUE; @@ -202,16 +180,13 @@ ErrCode DataShareStub::CmdUpdate(MessageParcel &data, MessageParcel &reply) ErrCode DataShareStub::CmdDelete(MessageParcel &data, MessageParcel &reply) { - std::shared_ptr uri = nullptr; - if (!ReadUri(uri, data)) { - return ERR_INVALID_VALUE; - } + Uri uri(""); DataSharePredicates predicates; - if (!ITypesUtils::Unmarshalling(data, predicates)) { + if (!ITypesUtil::Unmarshal(data, uri, predicates)) { LOG_ERROR("Unmarshalling predicates is nullptr"); return ERR_INVALID_VALUE; } - int index = Delete(*uri, predicates); + int index = Delete(uri, predicates); if (index == DEFAULT_NUMBER) { LOG_ERROR("Delete inner error"); return ERR_INVALID_VALUE; @@ -228,22 +203,15 @@ ErrCode DataShareStub::CmdDelete(MessageParcel &data, MessageParcel &reply) ErrCode DataShareStub::CmdQuery(MessageParcel &data, MessageParcel &reply) { - std::shared_ptr uri = nullptr; - if (!ReadUri(uri, data)) { - return ERR_INVALID_VALUE; - } + Uri uri(""); DataSharePredicates predicates; - if (!ITypesUtils::Unmarshalling(data, predicates)) { - LOG_ERROR("Unmarshalling predicates is nullptr"); - return ERR_INVALID_VALUE; - } std::vector columns; - if (!data.ReadStringVector(&columns)) { - LOG_ERROR("fail to ReadStringVector columns"); + if (!ITypesUtil::Unmarshal(data, uri, predicates, columns)) { + LOG_ERROR("Unmarshalling predicates is nullptr"); return ERR_INVALID_VALUE; } DatashareBusinessError businessError; - auto resultSet = Query(*uri, predicates, columns, businessError); + auto resultSet = Query(uri, predicates, columns, businessError); auto result = ISharedResultSet::WriteToParcel(std::move(resultSet), reply); reply.WriteInt32(businessError.GetCode()); reply.WriteString(businessError.GetMessage()); @@ -256,11 +224,12 @@ ErrCode DataShareStub::CmdQuery(MessageParcel &data, MessageParcel &reply) ErrCode DataShareStub::CmdGetType(MessageParcel &data, MessageParcel &reply) { - std::shared_ptr uri = nullptr; - if (!ReadUri(uri, data)) { + Uri uri(""); + if (!ITypesUtil::Unmarshal(data, uri)) { + LOG_ERROR("Unmarshalling predicates is nullptr"); return ERR_INVALID_VALUE; } - std::string type = GetType(*uri); + std::string type = GetType(uri); if (!reply.WriteString(type)) { LOG_ERROR("fail to WriteString type"); return ERR_INVALID_VALUE; @@ -270,32 +239,14 @@ ErrCode DataShareStub::CmdGetType(MessageParcel &data, MessageParcel &reply) ErrCode DataShareStub::CmdBatchInsert(MessageParcel &data, MessageParcel &reply) { - std::shared_ptr uri = nullptr; - if (!ReadUri(uri, data)) { - return ERR_INVALID_VALUE; - } - - int count = 0; - if (!data.ReadInt32(count)) { - LOG_ERROR("fail to ReadInt32 index"); - return ERR_INVALID_VALUE; - } - if (count > VALUEBUCKET_MAX_COUNT) { - return ERR_INVALID_VALUE; - } - + Uri uri(""); std::vector values; - values.reserve(static_cast(count)); - for (int i = 0; i < count; i++) { - DataShareValuesBucket value; - if (!ITypesUtils::Unmarshalling(data, value)) { - LOG_ERROR("Unmarshalling value is nullptr"); - return ERR_INVALID_VALUE; - } - values.emplace_back(value); + if (!ITypesUtil::Unmarshal(data, uri, values)) { + LOG_ERROR("Unmarshalling predicates is nullptr"); + return ERR_INVALID_VALUE; } - int ret = BatchInsert(*uri, values); + int ret = BatchInsert(uri, values); if (ret == DEFAULT_NUMBER) { LOG_ERROR("BatchInsert inner error"); return ERR_INVALID_VALUE; @@ -310,20 +261,21 @@ ErrCode DataShareStub::CmdBatchInsert(MessageParcel &data, MessageParcel &reply) return DATA_SHARE_NO_ERROR; } - ErrCode DataShareStub::CmdRegisterObserver(MessageParcel &data, MessageParcel &reply) { - std::shared_ptr uri = nullptr; - if (!ReadUri(uri, data)) { + Uri uri(""); + sptr observer; + if (!ITypesUtil::Unmarshal(data, uri, observer)) { + LOG_ERROR("Unmarshalling predicates is nullptr"); return ERR_INVALID_VALUE; } - auto obServer = iface_cast(data.ReadRemoteObject()); + auto obServer = iface_cast(observer); if (obServer == nullptr) { LOG_ERROR("obServer is nullptr"); return ERR_INVALID_VALUE; } - bool ret = RegisterObserver(*uri, obServer); + bool ret = RegisterObserver(uri, obServer); if (!reply.WriteInt32(ret)) { LOG_ERROR("fail to WriteInt32 ret"); return ERR_INVALID_VALUE; @@ -333,17 +285,19 @@ ErrCode DataShareStub::CmdRegisterObserver(MessageParcel &data, MessageParcel &r ErrCode DataShareStub::CmdUnregisterObserver(MessageParcel &data, MessageParcel &reply) { - std::shared_ptr uri = nullptr; - if (!ReadUri(uri, data)) { + Uri uri(""); + sptr observer; + if (!ITypesUtil::Unmarshal(data, uri, observer)) { + LOG_ERROR("Unmarshalling predicates is nullptr"); return ERR_INVALID_VALUE; } - auto obServer = iface_cast(data.ReadRemoteObject()); + auto obServer = iface_cast(observer); if (obServer == nullptr) { LOG_ERROR("obServer is nullptr"); return ERR_INVALID_VALUE; } - bool ret = UnregisterObserver(*uri, obServer); + bool ret = UnregisterObserver(uri, obServer); if (!reply.WriteInt32(ret)) { LOG_ERROR("fail to WriteInt32 ret"); return ERR_INVALID_VALUE; @@ -353,12 +307,13 @@ ErrCode DataShareStub::CmdUnregisterObserver(MessageParcel &data, MessageParcel ErrCode DataShareStub::CmdNotifyChange(MessageParcel &data, MessageParcel &reply) { - std::shared_ptr uri = nullptr; - if (!ReadUri(uri, data)) { + Uri uri(""); + if (!ITypesUtil::Unmarshal(data, uri)) { + LOG_ERROR("Unmarshalling predicates is nullptr"); return ERR_INVALID_VALUE; } - bool ret = NotifyChange(*uri); + bool ret = NotifyChange(uri); if (!reply.WriteInt32(ret)) { LOG_ERROR("fail to WriteInt32 ret"); return ERR_INVALID_VALUE; @@ -368,15 +323,14 @@ ErrCode DataShareStub::CmdNotifyChange(MessageParcel &data, MessageParcel &reply ErrCode DataShareStub::CmdNormalizeUri(MessageParcel &data, MessageParcel &reply) { - std::shared_ptr uri = nullptr; - if (!ReadUri(uri, data)) { + Uri uri(""); + if (!ITypesUtil::Unmarshal(data, uri)) { + LOG_ERROR("Unmarshalling predicates is nullptr"); return ERR_INVALID_VALUE; } - - Uri ret(""); - ret = NormalizeUri(*uri); - if (!reply.WriteParcelable(&ret)) { - LOG_ERROR("fail to WriteParcelable type"); + auto ret = NormalizeUri(uri); + if (!ITypesUtil::Marshal(reply, ret)) { + LOG_ERROR("Write to message parcel failed!"); return ERR_INVALID_VALUE; } return DATA_SHARE_NO_ERROR; @@ -384,18 +338,86 @@ ErrCode DataShareStub::CmdNormalizeUri(MessageParcel &data, MessageParcel &reply ErrCode DataShareStub::CmdDenormalizeUri(MessageParcel &data, MessageParcel &reply) { - std::shared_ptr uri = nullptr; - if (!ReadUri(uri, data)) { + Uri uri(""); + if (!ITypesUtil::Unmarshal(data, uri)) { + LOG_ERROR("Unmarshalling predicates is nullptr"); return ERR_INVALID_VALUE; } - Uri ret(""); - ret = DenormalizeUri(*uri); - if (!reply.WriteParcelable(&ret)) { - LOG_ERROR("fail to WriteParcelable type"); + auto ret = DenormalizeUri(uri); + if (!ITypesUtil::Marshal(reply, ret)) { + LOG_ERROR("Write to message parcel failed!"); return ERR_INVALID_VALUE; } return DATA_SHARE_NO_ERROR; } + +int DataShareStub::AddQueryTemplate(const std::string &uri, int64_t subscriberId, Template &tpl) +{ + return -1; +} + +int DataShareStub::DelQueryTemplate(const std::string &uri, int64_t subscriberId) +{ + return -1; +} + +std::vector DataShareStub::Publish(const Data &data, const std::string &bundleName) +{ + return {}; +} + +Data DataShareStub::GetPublishedData(const std::string &bundleName) +{ + return {}; +} + +std::vector DataShareStub::SubscribeRdbData(const std::vector &uris, + const TemplateId &templateId, const sptr &observer) +{ + return {}; +} + +std::vector DataShareStub::UnSubscribeRdbData( + const std::vector &uris, const TemplateId &templateId) +{ + return {}; +} + +std::vector DataShareStub::EnableSubscribeRdbData( + const std::vector &uris, const TemplateId &templateId) +{ + return {}; +} + +std::vector DataShareStub::DisableSubscribeRdbData( + const std::vector &uris, const TemplateId &templateId) +{ + return {}; +} + +std::vector DataShareStub::SubscribePublishedData(const std::vector &uris, + int64_t subscriberId, const sptr &observer) +{ + return {}; +} + +std::vector DataShareStub::UnSubscribePublishedData( + const std::vector &uris, int64_t subscriberId) +{ + return {}; +} + +std::vector DataShareStub::EnableSubscribePublishedData( + const std::vector &uris, int64_t subscriberId) +{ + return {}; +} + +std::vector DataShareStub::DisableSubscribePublishedData( + const std::vector &uris, int64_t subscriberId) +{ + return {}; +} } // namespace DataShare } // namespace OHOS \ No newline at end of file diff --git a/data_share/frameworks/native/provider/src/datashare_stub_impl.cpp b/data_share/frameworks/native/provider/src/datashare_stub_impl.cpp index 811ce0ba12f94c336e86aa7c1d88844759ca2e91..35da5630f68faa2c4f35fbdd2b9c3b98edb72361 100644 --- a/data_share/frameworks/native/provider/src/datashare_stub_impl.cpp +++ b/data_share/frameworks/native/provider/src/datashare_stub_impl.cpp @@ -384,5 +384,74 @@ void DataShareStubImpl::GetCallingInfo(CallingInfo& callingInfo) callingInfo.callingPid = GetCallingPid(); callingInfo.callingUid = GetCallingUid(); } + +int DataShareStubImpl::AddQueryTemplate(const std::string &uri, int64_t subscriberId, Template &tpl) +{ + return 0; +} + +int DataShareStubImpl::DelQueryTemplate(const std::string &uri, int64_t subscriberId) +{ + return 0; +} + +std::vector DataShareStubImpl::Publish( + const Data &data, const std::string &bundleName) +{ + return std::vector(); +} + +Data DataShareStubImpl::GetPublishedData(const std::string &bundleName) +{ + return Data(); +} + +std::vector DataShareStubImpl::SubscribeRdbData( + const std::vector &uris, const TemplateId &templateId, const sptr &observer) +{ + return std::vector(); +} + +std::vector DataShareStubImpl::UnSubscribeRdbData( + const std::vector &uris, const TemplateId &templateId) +{ + return std::vector(); +} + +std::vector DataShareStubImpl::EnableSubscribeRdbData( + const std::vector &uris, const TemplateId &templateId) +{ + return std::vector(); +} + +std::vector DataShareStubImpl::DisableSubscribeRdbData( + const std::vector &uris, const TemplateId &templateId) +{ + return std::vector(); +} + +std::vector DataShareStubImpl::SubscribePublishedData( + const std::vector &uris, int64_t subscriberId, const sptr &observer) +{ + return std::vector(); +} + +std::vector DataShareStubImpl::UnSubscribePublishedData( + const std::vector &uris, int64_t subscriberId) +{ + return std::vector(); +} + +std::vector DataShareStubImpl::EnableSubscribePublishedData( + const std::vector &uris, int64_t subscriberId) +{ + return std::vector(); +} + +std::vector DataShareStubImpl::DisableSubscribePublishedData( + const std::vector &uris, int64_t subscriberId) +{ + return std::vector(); +} } // namespace DataShare } // namespace OHOS \ No newline at end of file diff --git a/data_share/frameworks/native/provider/src/datashare_uv_queue.cpp b/data_share/frameworks/native/provider/src/datashare_uv_queue.cpp index 579620c65831f78bda1a95b1e93150da1fd96a8c..474cb50cf5ae34b73a9db23a21d0d5173cb7d93a 100644 --- a/data_share/frameworks/native/provider/src/datashare_uv_queue.cpp +++ b/data_share/frameworks/native/provider/src/datashare_uv_queue.cpp @@ -20,8 +20,8 @@ namespace OHOS { namespace DataShare { constexpr int WAIT_TIME = 3; -constexpr int SLEEP_TIME = 100; -constexpr int TRY_TIMES = 20; +constexpr int SLEEP_TIME = 1; +constexpr int TRY_TIMES = 2000; DataShareUvQueue::DataShareUvQueue(napi_env env) : env_(env) { diff --git a/data_share/frameworks/native/provider/src/js_datashare_ext_ability.cpp b/data_share/frameworks/native/provider/src/js_datashare_ext_ability.cpp index 2c6c5072e5955bc9d7c0a4a634f88a254f3bef92..dfbe00de78233a6e54d0e8a908db599000af4a26 100644 --- a/data_share/frameworks/native/provider/src/js_datashare_ext_ability.cpp +++ b/data_share/frameworks/native/provider/src/js_datashare_ext_ability.cpp @@ -51,7 +51,11 @@ JsDataShareExtAbility* JsDataShareExtAbility::Create(const std::unique_ptr &record, const std::shared_ptr &application, std::shared_ptr &handler, diff --git a/data_share/frameworks/native/proxy/include/data_proxy_observer.h b/data_share/frameworks/native/proxy/include/data_proxy_observer.h new file mode 100644 index 0000000000000000000000000000000000000000..8de56535c43a2ad35afb390de323baaae4ea644b --- /dev/null +++ b/data_share/frameworks/native/proxy/include/data_proxy_observer.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DATA_PROXY_OBSERVER_H +#define DATA_PROXY_OBSERVER_H + +#include + +namespace OHOS { +namespace DataShare { +class IDataProxyRdbObserver : public OHOS::IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DataShare.IDataProxyRdbObserver"); +}; + +class IDataProxyPublishedDataObserver : public OHOS::IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DataShare.IDataProxyPublishedDataObserver"); +}; +} // namespace DataShare +} // namespace OHOS +#endif // DATA_PROXY_OBSERVER_H diff --git a/data_share/frameworks/native/proxy/include/data_proxy_observer_stub.h b/data_share/frameworks/native/proxy/include/data_proxy_observer_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..490da4c1a8ab41a49a9255f4d8278618966f0cfb --- /dev/null +++ b/data_share/frameworks/native/proxy/include/data_proxy_observer_stub.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DATA_PROXY_OBSERVER_STUB_H +#define DATA_PROXY_OBSERVER_STUB_H + +#include "data_proxy_observer.h" +#include "datashare_template.h" +#include "iremote_stub.h" + +namespace OHOS { +namespace DataShare { +using RdbCallback = std::function; +class RdbObserverStub : public IRemoteStub { +public: + RdbObserverStub(RdbCallback callback); + virtual ~RdbObserverStub(); + int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + void OnChangeFromRdb(const RdbChangeNode &changeNode); + void ClearCallback(); +private: + std::mutex mutex_; + RdbCallback callback_; +}; + +using PublishedDataCallback = std::function; +class PublishedDataObserverStub : public IRemoteStub { +public: + virtual ~PublishedDataObserverStub(); + int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + explicit PublishedDataObserverStub(PublishedDataCallback callback) : callback_(callback){}; + void OnChangeFromPublishedData(PublishedDataChangeNode &changeNode); + void ClearCallback(); +private: + std::mutex mutex_; + PublishedDataCallback callback_; +}; +} // namespace DataShare +} // namespace OHOS +#endif //DATA_PROXY_OBSERVER_STUB_H diff --git a/data_share/frameworks/native/proxy/include/data_share_service_proxy.h b/data_share/frameworks/native/proxy/include/data_share_service_proxy.h index 2aae66a4bb17b4de247c2b3edf580ffaf6055ef8..6d03833da9f24fe10430d493fcb8a28b7e176f11 100644 --- a/data_share/frameworks/native/proxy/include/data_share_service_proxy.h +++ b/data_share/frameworks/native/proxy/include/data_share_service_proxy.h @@ -16,15 +16,15 @@ #ifndef DATASHARESERVICE_DATA_SHARE_SERVICE_PROXY_H #define DATASHARESERVICE_DATA_SHARE_SERVICE_PROXY_H -#include - #include +#include #include +#include "data_proxy_observer.h" +#include "datashare_business_error.h" #include "datashare_values_bucket.h" #include "idata_share_service.h" #include "uri.h" -#include "datashare_business_error.h" namespace OHOS::DataShare { class DataShareServiceProxy : public IRemoteProxy, public BaseProxy { @@ -32,10 +32,10 @@ public: explicit DataShareServiceProxy(const sptr &object); virtual int Insert(const Uri &uri, const DataShareValuesBucket &valuesBucket) override; - virtual int Update(const Uri &uri, const DataSharePredicates &predicate, - const DataShareValuesBucket &valuesBucket) override; + virtual int Update(const Uri &uri, const DataSharePredicates &predicate, + const DataShareValuesBucket &valuesBucket) override; - virtual int Delete(const Uri &uri, const DataSharePredicates &predicate) override; + virtual int Delete(const Uri &uri, const DataSharePredicates &predicate) override; virtual std::shared_ptr Query(const Uri &uri, const DataSharePredicates &predicates, std::vector &columns, DatashareBusinessError &businessError) override; @@ -60,6 +60,38 @@ public: virtual Uri DenormalizeUri(const Uri &uri) override; + int AddQueryTemplate(const std::string &uri, int64_t subscriberId, Template &tpl) override; + + int DelQueryTemplate(const std::string &uri, int64_t subscriberId) override; + + std::vector Publish(const Data &data, const std::string &bundleName) override; + + Data GetPublishedData(const std::string &bundleName) override; + + std::vector SubscribeRdbData(const std::vector &uris, const TemplateId &templateId, + const sptr &observer) override; + + std::vector UnSubscribeRdbData( + const std::vector &uris, const TemplateId &templateId) override; + + std::vector EnableSubscribeRdbData( + const std::vector &uris, const TemplateId &templateId) override; + + std::vector DisableSubscribeRdbData( + const std::vector &uris, const TemplateId &templateId) override; + + std::vector SubscribePublishedData(const std::vector &uris, int64_t subscriberId, + const sptr &observer) override; + + std::vector UnSubscribePublishedData( + const std::vector &uris, int64_t subscriberId) override; + + std::vector EnableSubscribePublishedData( + const std::vector &uris, int64_t subscriberId) override; + + std::vector DisableSubscribePublishedData( + const std::vector &uris, int64_t subscriberId) override; + private: static inline BrokerDelegator delegator_; }; diff --git a/data_share/frameworks/native/proxy/include/idata_share_service.h b/data_share/frameworks/native/proxy/include/idata_share_service.h index 5fd6a61deb6eb7935bdaf99e1fa856ef4dd7b617..568dd1a16a4381eb3ef94e12381374b984e6aa55 100644 --- a/data_share/frameworks/native/proxy/include/idata_share_service.h +++ b/data_share/frameworks/native/proxy/include/idata_share_service.h @@ -30,6 +30,19 @@ public: DATA_SHARE_SERVICE_CMD_DELETE, DATA_SHARE_SERVICE_CMD_UPDATE, DATA_SHARE_SERVICE_CMD_QUERY, + DATA_SHARE_SERVICE_CMD_ADD_TEMPLATE, + DATA_SHARE_SERVICE_CMD_DEL_TEMPLATE, + DATA_SHARE_SERVICE_CMD_PUBLISH, + DATA_SHARE_SERVICE_CMD_GET_DATA, + DATA_SHARE_SERVICE_CMD_SUBSCRIBE_RDB, + DATA_SHARE_SERVICE_CMD_UNSUBSCRIBE_RDB, + DATA_SHARE_SERVICE_CMD_ENABLE_SUBSCRIBE_RDB, + DATA_SHARE_SERVICE_CMD_DISABLE_SUBSCRIBE_RDB, + DATA_SHARE_SERVICE_CMD_SUBSCRIBE_PUBLISHED, + DATA_SHARE_SERVICE_CMD_UNSUBSCRIBE_PUBLISHED, + DATA_SHARE_SERVICE_CMD_ENABLE_SUBSCRIBE_PUBLISHED, + DATA_SHARE_SERVICE_CMD_DISABLE_SUBSCRIBE_PUBLISHED, + DATA_SHARE_SERVICE_CMD_QUERY_ASSERT, DATA_SHARE_SERVICE_CMD_MAX }; diff --git a/data_share/frameworks/native/proxy/include/published_data_subscriber_manager.h b/data_share/frameworks/native/proxy/include/published_data_subscriber_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..d9ff5a540565fff526c32d444ce1403d613d3e6b --- /dev/null +++ b/data_share/frameworks/native/proxy/include/published_data_subscriber_manager.h @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PUBLISHED_DATA_SUBSCRIBER_MANAGER_H +#define PUBLISHED_DATA_SUBSCRIBER_MANAGER_H +#include + +#include "callbacks_manager.h" +#include "data_proxy_observer.h" +#include "data_proxy_observer_stub.h" +#include "datashare_template.h" +#include "idatashare.h" +#include "iremote_stub.h" + +namespace OHOS { +namespace DataShare { +struct PublishedObserverMapKey { + std::string uri_; + int64_t subscriberId_; + PublishedObserverMapKey(const std::string &uri, int64_t subscriberId) + : uri_(uri), subscriberId_(subscriberId){}; + bool operator==(const PublishedObserverMapKey &node) const + { + return uri_ == node.uri_ && subscriberId_ == node.subscriberId_; + } + bool operator!=(const PublishedObserverMapKey &node) const + { + return !(node == *this); + } + bool operator<(const PublishedObserverMapKey &node) const + { + if (uri_ != node.uri_) { + return uri_ < node.uri_; + } + return subscriberId_ < node.subscriberId_; + } + operator std::string () const + { + return uri_; + } +}; + +class PublishedDataObserver { +public: + explicit PublishedDataObserver(const PublishedDataCallback &callback); + void OnChange(PublishedDataChangeNode &changeNode); + bool operator==(const PublishedDataObserver &rhs) const; + bool operator!=(const PublishedDataObserver &rhs) const; + +private: + PublishedDataCallback callback_; +}; + +class PublishedDataSubscriberManager : public CallbacksManager { +public: + using Key = PublishedObserverMapKey; + using Observer = PublishedDataObserver; + using BaseCallbacks = CallbacksManager; + PublishedDataSubscriberManager(); + std::vector AddObservers(std::shared_ptr proxy, + const std::vector &uris, int64_t subscriberId, const PublishedDataCallback &callback); + std::vector DelObservers(std::shared_ptr proxy, const std::vector &uris, + int64_t subscriberId); + std::vector EnableObservers(std::shared_ptr proxy, + const std::vector &uris, int64_t subscriberId); + std::vector DisableObservers(std::shared_ptr proxy, + const std::vector &uris, int64_t subscriberId); + void Emit(PublishedDataChangeNode &changeNode); + +private: + bool Init(); + void Destroy(); + sptr serviceCallback_; +}; +} // namespace DataShare +} // namespace OHOS +#endif //PUBLISHED_DATA_SUBSCRIBER_MANAGER_H diff --git a/data_share/frameworks/native/proxy/include/rdb_subscriber_manager.h b/data_share/frameworks/native/proxy/include/rdb_subscriber_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..21c6d76593eb2007562f2078f19db8c5d0b9a6de --- /dev/null +++ b/data_share/frameworks/native/proxy/include/rdb_subscriber_manager.h @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef RDB_SUBSCRIBER_MANAGER_H +#define RDB_SUBSCRIBER_MANAGER_H + +#include + +#include "callbacks_manager.h" +#include "data_proxy_observer.h" +#include "data_proxy_observer_stub.h" +#include "datashare_template.h" +#include "idatashare.h" +#include "iremote_stub.h" + +namespace OHOS { +namespace DataShare { +struct RdbObserverMapKey { + std::string uri_; + TemplateId templateId_; + RdbObserverMapKey(const std::string &uri, const TemplateId &templateId) : uri_(uri), templateId_(templateId){}; + bool operator==(const RdbObserverMapKey &node) const + { + return uri_ == node.uri_ && templateId_ == node.templateId_; + } + bool operator!=(const RdbObserverMapKey &node) const + { + return !(node == *this); + } + bool operator<(const RdbObserverMapKey &node) const + { + if (uri_ != node.uri_) { + return uri_ < node.uri_; + } + return templateId_ < node.templateId_; + } + operator std::string () const + { + return uri_; + } +}; + +class RdbObserver { +public: + RdbObserver(const RdbCallback &callback); + void OnChange(const RdbChangeNode &changeNode); + bool operator==(const RdbObserver &rhs) const; + bool operator!=(const RdbObserver &rhs) const; + +private: + RdbCallback callback_; +}; + +class RdbSubscriberManager : public CallbacksManager { +public: + using Key = RdbObserverMapKey; + using Observer = RdbObserver; + using BaseCallbacks = CallbacksManager; + RdbSubscriberManager(); + std::vector AddObservers(std::shared_ptr proxy, const std::vector &uris, + const TemplateId &templateId, const RdbCallback &callback); + std::vector DelObservers(std::shared_ptr proxy, const std::vector &uris, + const TemplateId &templateId); + std::vector EnableObservers(std::shared_ptr proxy, + const std::vector &uris, const TemplateId &templateId); + std::vector DisableObservers(std::shared_ptr proxy, + const std::vector &uris, const TemplateId &templateId); + void Emit(const RdbChangeNode &changeNode); + +private: + bool Init(); + void Destroy(); + sptr serviceCallback_; +}; +} // namespace DataShare +} // namespace OHOS +#endif // RDB_SUBSCRIBER_MANAGER_H diff --git a/data_share/frameworks/native/proxy/src/data_proxy_observer_stub.cpp b/data_share/frameworks/native/proxy/src/data_proxy_observer_stub.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f5d8ee1b684ea6e62e7c68aa60c00e91b365d343 --- /dev/null +++ b/data_share/frameworks/native/proxy/src/data_proxy_observer_stub.cpp @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "data_proxy_observer_stub.h" + +#include "datashare_itypes_utils.h" +#include "datashare_log.h" + +namespace OHOS { +namespace DataShare { +static constexpr int REQUEST_CODE = 0; +int RdbObserverStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + std::u16string descriptor = RdbObserverStub::GetDescriptor(); + std::u16string remoteDescriptor = data.ReadInterfaceToken(); + if (descriptor != remoteDescriptor) { + LOG_ERROR("local descriptor is not equal to remote"); + return ERR_INVALID_STATE; + } + if (code != REQUEST_CODE) { + LOG_ERROR("not support code:%u", code); + return ERR_INVALID_STATE; + } + RdbChangeNode changeNode; + if (!ITypesUtil::Unmarshal(data, changeNode)) { + LOG_ERROR("Unmarshalling is nullptr"); + return ERR_INVALID_VALUE; + } + OnChangeFromRdb(changeNode); + return ERR_OK; +} + +void RdbObserverStub::OnChangeFromRdb(const RdbChangeNode &changeNode) +{ + std::lock_guard lock(mutex_); + if (callback_) { + callback_(changeNode); + } +} + +RdbObserverStub::RdbObserverStub(RdbCallback callback) : callback_(callback) +{ +} + +RdbObserverStub::~RdbObserverStub() +{ + ClearCallback(); +} + +void RdbObserverStub::ClearCallback() +{ + std::lock_guard lock(mutex_); + callback_ = nullptr; +} + +int PublishedDataObserverStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, + MessageOption &option) +{ + std::u16string descriptor = PublishedDataObserverStub::GetDescriptor(); + std::u16string remoteDescriptor = data.ReadInterfaceToken(); + if (descriptor != remoteDescriptor) { + LOG_ERROR("local descriptor is not equal to remote"); + return ERR_INVALID_STATE; + } + if (code != REQUEST_CODE) { + LOG_ERROR("not support code:%u", code); + return ERR_INVALID_STATE; + } + PublishedDataChangeNode changeNode; + if (!ITypesUtil::Unmarshal(data, changeNode)) { + LOG_ERROR("Unmarshalling is nullptr"); + return ERR_INVALID_VALUE; + } + OnChangeFromPublishedData(changeNode); + return ERR_OK; +} + +void PublishedDataObserverStub::OnChangeFromPublishedData(PublishedDataChangeNode &changeNode) +{ + std::lock_guard lock(mutex_); + if (callback_) { + callback_(changeNode); + } +} + +void PublishedDataObserverStub::ClearCallback() +{ + std::lock_guard lock(mutex_); + callback_ = nullptr; +} + +PublishedDataObserverStub::~PublishedDataObserverStub() +{ + ClearCallback(); +} +} // namespace DataShare +} // namespace OHOS diff --git a/data_share/frameworks/native/proxy/src/data_share_service_proxy.cpp b/data_share/frameworks/native/proxy/src/data_share_service_proxy.cpp index 04f6591935ebb62111dcf4335ac1c6b088933467..f1334a1cb6f8603cf3a6a4fc2497a7f2e6b3c78e 100644 --- a/data_share/frameworks/native/proxy/src/data_share_service_proxy.cpp +++ b/data_share/frameworks/native/proxy/src/data_share_service_proxy.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2023 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -15,9 +15,9 @@ #include "data_share_service_proxy.h" +#include "datashare_itypes_utils.h" #include "datashare_log.h" #include "ishared_result_set.h" -#include "itypes_utils.h" namespace OHOS { namespace DataShare { @@ -35,7 +35,7 @@ int32_t DataShareServiceProxy::Insert(const Uri &uri, const DataShareValuesBucke LOG_ERROR("Write descriptor failed!"); return DATA_SHARE_ERROR; } - if (!ITypesUtils::Marshal(data, uriStr, value)) { + if (!ITypesUtil::Marshal(data, uriStr, value)) { LOG_ERROR("Write to message parcel failed!"); return DATA_SHARE_ERROR; } @@ -59,7 +59,7 @@ int32_t DataShareServiceProxy::Update(const Uri &uri, LOG_ERROR("Write descriptor failed!"); return DATA_SHARE_ERROR; } - if (!ITypesUtils::Marshal(data, uriStr, predicate, valuesBucket)) { + if (!ITypesUtil::Marshal(data, uriStr, predicate, valuesBucket)) { LOG_ERROR("Write to message parcel failed!"); return DATA_SHARE_ERROR; } @@ -82,7 +82,7 @@ int32_t DataShareServiceProxy::Delete(const Uri &uri, const DataSharePredicates LOG_ERROR("Write descriptor failed!"); return DATA_SHARE_ERROR; } - if (!ITypesUtils::Marshal(data, uriStr, predicate)) { + if (!ITypesUtil::Marshal(data, uriStr, predicate)) { LOG_ERROR("Write to message parcel failed!"); return DATA_SHARE_ERROR; } @@ -107,7 +107,7 @@ std::shared_ptr DataShareServiceProxy::Query(const Uri &uri, return nullptr; } - if (!ITypesUtils::Marshal(data, uriStr, predicates, columns)) { + if (!ITypesUtil::Marshal(data, uriStr, predicates, columns)) { LOG_ERROR("Write to message parcel failed!"); return nullptr; } @@ -125,7 +125,6 @@ std::shared_ptr DataShareServiceProxy::Query(const Uri &uri, return result; } - int DataShareServiceProxy::OpenFile(const Uri &uri, const std::string &mode) { return 0; @@ -175,5 +174,310 @@ Uri DataShareServiceProxy::DenormalizeUri(const Uri &uri) { return Uri(""); } + +int DataShareServiceProxy::AddQueryTemplate(const std::string &uri, int64_t subscriberId, Template &tpl) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(IDataShareService::GetDescriptor())) { + LOG_ERROR("Write descriptor failed!"); + return DATA_SHARE_ERROR; + } + if (!ITypesUtil::Marshal(data, uri, subscriberId, tpl.predicates_, tpl.scheduler_)) { + LOG_ERROR("Write to message parcel failed!"); + return DATA_SHARE_ERROR; + } + + MessageParcel reply; + MessageOption option; + int32_t err = Remote()->SendRequest(DATA_SHARE_SERVICE_CMD_ADD_TEMPLATE, data, reply, option); + if (err != NO_ERROR) { + LOG_ERROR("AddTemplate fail to SendRequest. uri: %{public}s, err: %{public}d", uri.c_str(), err); + return DATA_SHARE_ERROR; + } + return reply.ReadInt32(); +} + +int DataShareServiceProxy::DelQueryTemplate(const std::string &uri, int64_t subscriberId) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(IDataShareService::GetDescriptor())) { + LOG_ERROR("Write descriptor failed!"); + return DATA_SHARE_ERROR; + } + if (!ITypesUtil::Marshal(data, uri, subscriberId)) { + LOG_ERROR("Write to message parcel failed!"); + return DATA_SHARE_ERROR; + } + + MessageParcel reply; + MessageOption option; + int32_t err = Remote()->SendRequest(DATA_SHARE_SERVICE_CMD_DEL_TEMPLATE, data, reply, option); + if (err != NO_ERROR) { + LOG_ERROR("AddTemplate fail to SendRequest. uri: %{public}s, err: %{public}d", uri.c_str(), err); + return DATA_SHARE_ERROR; + } + return reply.ReadInt32(); +} + +std::vector DataShareServiceProxy::Publish(const Data &data, const std::string &bundleName) +{ + std::vector results; + MessageParcel parcel; + if (!parcel.WriteInterfaceToken(IDataShareService::GetDescriptor())) { + LOG_ERROR("Write descriptor failed!"); + return results; + } + if (!ITypesUtil::Marshal(parcel, data, bundleName)) { + LOG_ERROR("Marshalfailed!"); + return results; + } + + MessageParcel reply; + MessageOption option; + int32_t err = Remote()->SendRequest(DATA_SHARE_SERVICE_CMD_PUBLISH, parcel, reply, option); + if (err != NO_ERROR) { + LOG_ERROR("Publish fail to SendRequest. err: %{public}d", err); + return results; + } + + ITypesUtil::Unmarshal(reply, results); + return results; +} + +Data DataShareServiceProxy::GetPublishedData(const std::string &bundleName) +{ + Data results; + MessageParcel data; + if (!data.WriteInterfaceToken(IDataShareService::GetDescriptor())) { + LOG_ERROR("Write descriptor failed!"); + return results; + } + if (!ITypesUtil::Marshal(data, bundleName)) { + LOG_ERROR("Write to message parcel failed!"); + return results; + } + + MessageParcel reply; + MessageOption option; + int32_t err = Remote()->SendRequest(DATA_SHARE_SERVICE_CMD_GET_DATA, data, reply, option); + if (err != NO_ERROR) { + LOG_ERROR("AddTemplate fail to SendRequest, err: %{public}d", err); + return results; + } + ITypesUtil::Unmarshal(reply, results.datas_); + return results; } + +std::vector DataShareServiceProxy::SubscribeRdbData(const std::vector &uris, + const TemplateId &templateId, const sptr &observer) +{ + std::vector results; + MessageParcel data; + if (!data.WriteInterfaceToken(IDataShareService::GetDescriptor())) { + LOG_ERROR("Write descriptor failed!"); + return results; + } + + if (!ITypesUtil::Marshal(data, uris, templateId.subscriberId_, templateId.bundleName_)) { + LOG_ERROR("Write to message parcel failed!"); + return results; + } + if (!data.WriteRemoteObject(observer->AsObject())) { + LOG_ERROR("failed to WriteParcelable dataObserver "); + return results; + } + + MessageParcel reply; + MessageOption option; + int32_t err = Remote()->SendRequest(DATA_SHARE_SERVICE_CMD_SUBSCRIBE_RDB, data, reply, option); + if (err != NO_ERROR) { + LOG_ERROR("SubscribeRdbData fail to SendRequest. err: %{public}d", err); + return results; + } + ITypesUtil::Unmarshal(reply, results); + return results; +} + +std::vector DataShareServiceProxy::UnSubscribeRdbData( + const std::vector &uris, const TemplateId &templateId) +{ + std::vector results; + MessageParcel data; + if (!data.WriteInterfaceToken(IDataShareService::GetDescriptor())) { + LOG_ERROR("Write descriptor failed!"); + return results; + } + + if (!ITypesUtil::Marshal(data, uris, templateId.subscriberId_, templateId.bundleName_)) { + LOG_ERROR("Write to message parcel failed!"); + return results; + } + + MessageParcel reply; + MessageOption option; + int32_t err = Remote()->SendRequest(DATA_SHARE_SERVICE_CMD_UNSUBSCRIBE_RDB, data, reply, option); + if (err != NO_ERROR) { + LOG_ERROR("fail to SendRequest. err: %{public}d", err); + return results; + } + ITypesUtil::Unmarshal(reply, results); + return results; +} + +std::vector DataShareServiceProxy::EnableSubscribeRdbData( + const std::vector &uris, const TemplateId &templateId) +{ + std::vector results; + MessageParcel data; + if (!data.WriteInterfaceToken(IDataShareService::GetDescriptor())) { + LOG_ERROR("Write descriptor failed!"); + return results; + } + + if (!ITypesUtil::Marshal(data, uris, templateId.subscriberId_, templateId.bundleName_)) { + LOG_ERROR("Write to message parcel failed!"); + return results; + } + + MessageParcel reply; + MessageOption option; + int32_t err = Remote()->SendRequest(DATA_SHARE_SERVICE_CMD_ENABLE_SUBSCRIBE_RDB, data, reply, option); + if (err != NO_ERROR) { + LOG_ERROR("fail to SendRequest. err: %{public}d", err); + return results; + } + ITypesUtil::Unmarshal(reply, results); + return results; +} + +std::vector DataShareServiceProxy::DisableSubscribeRdbData( + const std::vector &uris, const TemplateId &templateId) +{ + std::vector results; + MessageParcel data; + if (!data.WriteInterfaceToken(IDataShareService::GetDescriptor())) { + LOG_ERROR("Write descriptor failed!"); + return results; + } + + if (!ITypesUtil::Marshal(data, uris, templateId.subscriberId_, templateId.bundleName_)) { + LOG_ERROR("Write to message parcel failed!"); + return results; + } + + MessageParcel reply; + MessageOption option; + int32_t err = Remote()->SendRequest(DATA_SHARE_SERVICE_CMD_DISABLE_SUBSCRIBE_RDB, data, reply, option); + if (err != NO_ERROR) { + LOG_ERROR("AddTemplate fail to SendRequest. err: %{public}d", err); + return results; + } + ITypesUtil::Unmarshal(reply, results); + return results; +} + +std::vector DataShareServiceProxy::SubscribePublishedData( + const std::vector &uris, int64_t subscriberId, const sptr &observer) +{ + std::vector results; + MessageParcel data; + if (!data.WriteInterfaceToken(IDataShareService::GetDescriptor())) { + LOG_ERROR("Write descriptor failed!"); + return results; + } + if (!ITypesUtil::Marshal(data, uris, subscriberId)) { + LOG_ERROR("Write to message parcel failed!"); + return results; + } + if (!data.WriteRemoteObject(observer->AsObject())) { + LOG_ERROR("failed to WriteRemoteObject dataObserver "); + return results; + } + + MessageParcel reply; + MessageOption option; + int32_t err = Remote()->SendRequest(DATA_SHARE_SERVICE_CMD_SUBSCRIBE_PUBLISHED, data, reply, option); + if (err != NO_ERROR) { + LOG_ERROR("AddTemplate fail to SendRequest. err: %{public}d", err); + return results; + } + ITypesUtil::Unmarshal(reply, results); + return results; +} + +std::vector DataShareServiceProxy::UnSubscribePublishedData( + const std::vector &uris, int64_t subscriberId) +{ + std::vector results; + MessageParcel data; + if (!data.WriteInterfaceToken(IDataShareService::GetDescriptor())) { + LOG_ERROR("Write descriptor failed!"); + return results; + } + if (!ITypesUtil::Marshal(data, uris, subscriberId)) { + LOG_ERROR("Write to message parcel failed!"); + return results; + } + + MessageParcel reply; + MessageOption option; + int32_t err = Remote()->SendRequest(DATA_SHARE_SERVICE_CMD_UNSUBSCRIBE_PUBLISHED, data, reply, option); + if (err != NO_ERROR) { + LOG_ERROR("AddTemplate fail to SendRequest. err: %{public}d", err); + return results; + } + ITypesUtil::Unmarshal(reply, results); + return results; +} + +std::vector DataShareServiceProxy::EnableSubscribePublishedData( + const std::vector &uris, int64_t subscriberId) +{ + std::vector results; + MessageParcel data; + if (!data.WriteInterfaceToken(IDataShareService::GetDescriptor())) { + LOG_ERROR("Write descriptor failed!"); + return results; + } + if (!ITypesUtil::Marshal(data, uris, subscriberId)) { + LOG_ERROR("Write to message parcel failed!"); + return results; + } + + MessageParcel reply; + MessageOption option; + int32_t err = Remote()->SendRequest(DATA_SHARE_SERVICE_CMD_ENABLE_SUBSCRIBE_PUBLISHED, data, reply, option); + if (err != NO_ERROR) { + LOG_ERROR("AddTemplate fail to SendRequest. err: %{public}d", err); + return results; + } + ITypesUtil::Unmarshal(reply, results); + return results; +} + +std::vector DataShareServiceProxy::DisableSubscribePublishedData( + const std::vector &uris, int64_t subscriberId) +{ + std::vector results; + MessageParcel data; + if (!data.WriteInterfaceToken(IDataShareService::GetDescriptor())) { + LOG_ERROR("Write descriptor failed!"); + return results; + } + if (!ITypesUtil::Marshal(data, uris, subscriberId)) { + LOG_ERROR("Write to message parcel failed!"); + return results; + } + + MessageParcel reply; + MessageOption option; + int32_t err = Remote()->SendRequest(DATA_SHARE_SERVICE_CMD_DISABLE_SUBSCRIBE_PUBLISHED, data, reply, option); + if (err != NO_ERROR) { + LOG_ERROR("AddTemplate fail to SendRequest. err: %{public}d", err); + return results; + } + ITypesUtil::Unmarshal(reply, results); + return results; } +} // namespace DataShare +} // namespace OHOS diff --git a/data_share/frameworks/native/proxy/src/published_data_subscriber_manager.cpp b/data_share/frameworks/native/proxy/src/published_data_subscriber_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..19f10b0842380f3ada7624eedde2db9083e3cdbc --- /dev/null +++ b/data_share/frameworks/native/proxy/src/published_data_subscriber_manager.cpp @@ -0,0 +1,228 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "published_data_subscriber_manager.h" + +#include "data_proxy_observer_stub.h" +#include "datashare_log.h" + +namespace OHOS { +namespace DataShare { +std::vector PublishedDataSubscriberManager::AddObservers(std::shared_ptr proxy, + const std::vector &uris, int64_t subscriberId, const PublishedDataCallback &callback) +{ + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return std::vector(); + } + std::vector keys; + std::for_each(uris.begin(), uris.end(), [&keys, &subscriberId](auto &uri) { + keys.emplace_back(uri, subscriberId); + }); + return BaseCallbacks::AddObservers(keys, std::make_shared(callback), + [&proxy, &subscriberId, this](const std::vector &firstAddKeys, const std::shared_ptr observer, + std::vector &opResult) { + std::vector firstAddUris; + std::for_each(firstAddKeys.begin(), firstAddKeys.end(), [&firstAddUris](auto &result) { + firstAddUris.emplace_back(result); + }); + if (firstAddUris.empty()) { + return; + } + + Init(); + auto subResults = proxy->SubscribePublishedData(firstAddUris, subscriberId, serviceCallback_); + std::vector failedKeys; + for (auto &subResult : subResults) { + opResult.emplace_back(subResult); + if (subResult.errCode_ != E_OK) { + failedKeys.emplace_back(subResult.key_, subscriberId); + LOG_WARN("registered failed, uri is %{public}s", subResult.key_.c_str()); + } + } + if (failedKeys.size() > 0) { + BaseCallbacks::DelObservers(failedKeys, observer); + } + Destroy(); + }); +} + +std::vector PublishedDataSubscriberManager::DelObservers(std::shared_ptr proxy, + const std::vector &uris, int64_t subscriberId) +{ + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return std::vector(); + } + std::vector keys; + std::for_each(uris.begin(), uris.end(), [&keys, &subscriberId](auto &uri) { + keys.emplace_back(uri, subscriberId); + }); + return BaseCallbacks::DelObservers(keys, nullptr, + [&proxy, &subscriberId, &uris, this](const std::vector &lastDelKeys, + const std::shared_ptr &observer, std::vector &opResult) { + // delete all obs + if (uris.empty()) { + for (const auto &key : lastDelKeys) { + proxy->UnSubscribePublishedData(std::vector(1, key.uri_), key.subscriberId_); + } + Destroy(); + return; + } + std::vector lastDelUris; + std::for_each(lastDelKeys.begin(), lastDelKeys.end(), [&lastDelUris](auto &result) { + lastDelUris.emplace_back(result); + }); + if (lastDelUris.empty()) { + return; + } + auto unsubResult = proxy->UnSubscribePublishedData(lastDelUris, subscriberId); + if (BaseCallbacks::GetEnabledSubscriberSize() == 0) { + LOG_INFO("no valid subscriber, delete callback"); + serviceCallback_ = nullptr; + } + opResult.insert(opResult.end(), unsubResult.begin(), unsubResult.end()); + Destroy(); + }); +} + +std::vector PublishedDataSubscriberManager::EnableObservers(std::shared_ptr proxy, + const std::vector &uris, int64_t subscriberId) +{ + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return std::vector(); + } + std::vector keys; + std::for_each(uris.begin(), uris.end(), [&keys, &subscriberId](auto &uri) { + keys.emplace_back(uri, subscriberId); + }); + return BaseCallbacks::EnableObservers(keys, + [&proxy, &subscriberId, this](const std::vector &firstAddKeys, std::vector &opResult) { + std::vector firstAddUris; + std::for_each(firstAddKeys.begin(), firstAddKeys.end(), [&firstAddUris](auto &result) { + firstAddUris.emplace_back(result); + }); + if (firstAddUris.empty()) { + return; + } + auto subResults = proxy->EnableSubscribePublishedData(firstAddUris, subscriberId); + std::vector failedKeys; + for (auto &subResult : subResults) { + opResult.emplace_back(subResult); + if (subResult.errCode_ != E_OK) { + failedKeys.emplace_back(subResult.key_, subscriberId); + LOG_WARN("registered failed, uri is %{public}s", subResult.key_.c_str()); + } + } + if (failedKeys.size() > 0) { + BaseCallbacks::DisableObservers(failedKeys); + } + }); +} + +std::vector PublishedDataSubscriberManager::DisableObservers(std::shared_ptr proxy, + const std::vector &uris, int64_t subscriberId) +{ + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return std::vector(); + } + std::vector keys; + std::for_each(uris.begin(), uris.end(), [&keys, &subscriberId](auto &uri) { + keys.emplace_back(uri, subscriberId); + }); + return BaseCallbacks::DisableObservers(keys, + [&proxy, &subscriberId, this](const std::vector &lastDisabledKeys, + std::vector &opResult) { + std::vector lastDisabledUris; + std::for_each(lastDisabledKeys.begin(), lastDisabledKeys.end(), [&lastDisabledUris](auto &result) { + lastDisabledUris.emplace_back(result); + }); + if (lastDisabledUris.empty()) { + return; + } + + auto results = proxy->DisableSubscribePublishedData(lastDisabledUris, subscriberId); + opResult.insert(opResult.end(), results.begin(), results.end()); + Destroy(); + }); +} + +void PublishedDataSubscriberManager::Emit(PublishedDataChangeNode &changeNode) +{ + std::map, PublishedDataChangeNode> results; + for (auto &data : changeNode.datas_) { + PublishedObserverMapKey key(data.key_, data.subscriberId_); + auto callbacks = BaseCallbacks::GetEnabledObservers(key); + if (callbacks.empty()) { + LOG_WARN("%{private}s nobody subscribe, but still notify", data.key_.c_str()); + continue; + } + for (auto const &obs : callbacks) { + results[obs].datas_.emplace_back(data.key_, data.subscriberId_, data.GetData()); + } + } + for (auto &[callback, node] : results) { + node.ownerBundleName_ = changeNode.ownerBundleName_; + callback->OnChange(node); + } +} + +bool PublishedDataSubscriberManager::Init() +{ + if (serviceCallback_ == nullptr) { + LOG_INFO("callback init"); + serviceCallback_ = new PublishedDataObserverStub([this](PublishedDataChangeNode &changeNode) { + Emit(changeNode); + }); + } + return true; +} + +void PublishedDataSubscriberManager::Destroy() +{ + if (BaseCallbacks::GetEnabledSubscriberSize() == 0) { + if (serviceCallback_ != nullptr) { + serviceCallback_->ClearCallback(); + } + LOG_INFO("no valid subscriber, delete callback"); + serviceCallback_ = nullptr; + } +} + +PublishedDataSubscriberManager::PublishedDataSubscriberManager() +{ + serviceCallback_ = nullptr; +} + +PublishedDataObserver::PublishedDataObserver(const PublishedDataCallback &callback) : callback_(callback) {} + +void PublishedDataObserver::OnChange(PublishedDataChangeNode &changeNode) +{ + callback_(changeNode); +} + +bool PublishedDataObserver::operator==(const PublishedDataObserver &rhs) const +{ + return false; +} + +bool PublishedDataObserver::operator!=(const PublishedDataObserver &rhs) const +{ + return !(rhs == *this); +} +} // namespace DataShare +} // namespace OHOS diff --git a/data_share/frameworks/native/proxy/src/rdb_subscriber_manager.cpp b/data_share/frameworks/native/proxy/src/rdb_subscriber_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d88fee9e9b7dc5365722aba4344b5f6db5acd81a --- /dev/null +++ b/data_share/frameworks/native/proxy/src/rdb_subscriber_manager.cpp @@ -0,0 +1,215 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "rdb_subscriber_manager.h" + +#include "data_proxy_observer_stub.h" +#include "datashare_log.h" + +namespace OHOS { +namespace DataShare { +RdbSubscriberManager::RdbSubscriberManager() +{ + serviceCallback_ = nullptr; +} + +std::vector RdbSubscriberManager::AddObservers(std::shared_ptr proxy, + const std::vector &uris, const TemplateId &templateId, const RdbCallback &callback) +{ + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return std::vector(); + } + std::vector keys; + std::for_each(uris.begin(), uris.end(), [&keys, &templateId](auto &uri) { + keys.emplace_back(uri, templateId); + }); + return BaseCallbacks::AddObservers(keys, std::make_shared(callback), + [&proxy, &templateId, this](const std::vector &firstAddKeys, + const std::shared_ptr observer, std::vector &opResult) { + std::vector firstAddUris; + std::for_each(firstAddKeys.begin(), firstAddKeys.end(), [&firstAddUris](auto &result) { + firstAddUris.emplace_back(result); + }); + if (firstAddUris.empty()) { + return; + } + + Init(); + auto subResults = proxy->SubscribeRdbData(firstAddUris, templateId, serviceCallback_); + std::vector failedKeys; + for (auto &subResult : subResults) { + opResult.emplace_back(subResult); + if (subResult.errCode_ != E_OK) { + failedKeys.emplace_back(subResult.key_, templateId); + LOG_WARN("registered failed, uri is %{public}s", subResult.key_.c_str()); + } + } + if (!failedKeys.empty()) { + BaseCallbacks::DelObservers(failedKeys, observer); + } + Destroy(); + }); +} + +std::vector RdbSubscriberManager::DelObservers(std::shared_ptr proxy, + const std::vector &uris, const TemplateId &templateId) +{ + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return std::vector(); + } + std::vector keys; + std::for_each(uris.begin(), uris.end(), [&keys, &templateId](auto &uri) { + keys.emplace_back(uri, templateId); + }); + return BaseCallbacks::DelObservers(keys, nullptr, + [&proxy, &templateId, &uris, this](const std::vector &lastDelKeys, + const std::shared_ptr &observer, std::vector &opResult) { + // delete all obs + if (uris.empty()) { + for (const auto& key : lastDelKeys) { + proxy->UnSubscribeRdbData(std::vector(1, key.uri_), key.templateId_); + } + Destroy(); + return; + } + std::vector lastDelUris; + std::for_each(lastDelKeys.begin(), lastDelKeys.end(), [&lastDelUris](auto &result) { + lastDelUris.emplace_back(result); + }); + if (lastDelUris.empty()) { + return; + } + auto unsubResult = proxy->UnSubscribeRdbData(lastDelUris, templateId); + if (BaseCallbacks::GetEnabledSubscriberSize() == 0) { + LOG_INFO("no valid subscriber, delete callback"); + serviceCallback_ = nullptr; + } + opResult.insert(opResult.end(), unsubResult.begin(), unsubResult.end()); + Destroy(); + }); +} + +std::vector RdbSubscriberManager::EnableObservers(std::shared_ptr proxy, + const std::vector &uris, const TemplateId &templateId) +{ + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return std::vector(); + } + std::vector keys; + std::for_each(uris.begin(), uris.end(), [&keys, &templateId](auto &uri) { + keys.emplace_back(uri, templateId); + }); + return BaseCallbacks::EnableObservers(keys, + [&proxy, &templateId, this](const std::vector &firstAddKeys, std::vector &opResult) { + std::vector firstAddUris; + std::for_each(firstAddKeys.begin(), firstAddKeys.end(), [&firstAddUris](auto &result) { + firstAddUris.emplace_back(result); + }); + if (firstAddUris.empty()) { + return; + } + auto subResults = proxy->EnableSubscribeRdbData(firstAddUris, templateId); + std::vector failedKeys; + for (auto &subResult : subResults) { + opResult.emplace_back(subResult); + if (subResult.errCode_ != E_OK) { + failedKeys.emplace_back(subResult.key_, templateId); + LOG_WARN("registered failed, uri is %{public}s", subResult.key_.c_str()); + } + } + if (!failedKeys.empty()) { + BaseCallbacks::DisableObservers(failedKeys); + } + }); +} + +std::vector RdbSubscriberManager::DisableObservers(std::shared_ptr proxy, + const std::vector &uris, const TemplateId &templateId) +{ + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return std::vector(); + } + std::vector keys; + std::for_each(uris.begin(), uris.end(), [&keys, &templateId](auto &uri) { + keys.emplace_back(uri, templateId); + }); + return BaseCallbacks::DisableObservers(keys, + [&proxy, &templateId, this](const std::vector &lastDisabledKeys, std::vector &opResult) { + std::vector lastDisabledUris; + std::for_each(lastDisabledKeys.begin(), lastDisabledKeys.end(), [&lastDisabledUris](auto &result) { + lastDisabledUris.emplace_back(result); + }); + if (lastDisabledUris.empty()) { + return; + } + + auto results = proxy->DisableSubscribeRdbData(lastDisabledUris, templateId); + opResult.insert(opResult.end(), results.begin(), results.end()); + Destroy(); + }); +} + +void RdbSubscriberManager::Emit(const RdbChangeNode &changeNode) +{ + RdbObserverMapKey key(changeNode.uri_, changeNode.templateId_); + auto callbacks = BaseCallbacks::GetEnabledObservers(key); + for (auto &obs : callbacks) { + if (obs != nullptr) { + obs->OnChange(changeNode); + } + } +} + +bool RdbSubscriberManager::Init() +{ + if (serviceCallback_ == nullptr) { + LOG_INFO("callback init"); + serviceCallback_ = new RdbObserverStub([this](const RdbChangeNode &changeNode) { Emit(changeNode); }); + } + return true; +} +void RdbSubscriberManager::Destroy() +{ + if (BaseCallbacks::GetEnabledSubscriberSize() == 0) { + if (serviceCallback_ != nullptr) { + serviceCallback_->ClearCallback(); + } + LOG_INFO("no valid subscriber, delete callback"); + serviceCallback_ = nullptr; + } +} + +RdbObserver::RdbObserver(const RdbCallback &callback) : callback_(callback) {} + +void RdbObserver::OnChange(const RdbChangeNode &changeNode) +{ + callback_(changeNode); +} + +bool RdbObserver::operator==(const RdbObserver &rhs) const +{ + return false; +} + +bool RdbObserver::operator!=(const RdbObserver &rhs) const +{ + return !(rhs == *this); +} +} // namespace DataShare +} // namespace OHOS diff --git a/data_share/interfaces/inner_api/BUILD.gn b/data_share/interfaces/inner_api/BUILD.gn index 464a8ae321e65ef527e5235403a5ad2bff315434..ca280e64c278c4800bfbb7b8b733d5cf45887573 100644 --- a/data_share/interfaces/inner_api/BUILD.gn +++ b/data_share/interfaces/inner_api/BUILD.gn @@ -49,24 +49,25 @@ config("datashare_public_config") { } ohos_shared_library("datashare_consumer") { - include_dirs = [] + include_dirs = + [ "//foundation/distributeddatamgr/kv_store/frameworks/common" ] sources = [ "${datashare_native_consumer_path}/src/connection_factory.cpp", "${datashare_native_consumer_path}/src/datashare_connection.cpp", "${datashare_native_consumer_path}/src/datashare_helper.cpp", "${datashare_native_consumer_path}/src/datashare_proxy.cpp", + "${datashare_native_proxy_path}/src/data_proxy_observer_stub.cpp", "${datashare_native_proxy_path}/src/data_share_manager_impl.cpp", "${datashare_native_proxy_path}/src/data_share_service_proxy.cpp", + "${datashare_native_proxy_path}/src/published_data_subscriber_manager.cpp", + "${datashare_native_proxy_path}/src/rdb_subscriber_manager.cpp", ] configs = [ ":ability_config" ] public_configs = [ ":datashare_public_config" ] version_script = "consumer/libdatashare_consumer.map" innerapi_tags = [ "platformsdk" ] - deps = [ - "${ability_runtime_path}/frameworks/native/ability/native:abilitykit_native", - "${datashare_innerapi_path}/common:datashare_common", - ] + deps = [ "${datashare_innerapi_path}/common:datashare_common" ] external_deps = [ "ability_base:want", @@ -89,7 +90,8 @@ ohos_shared_library("datashare_consumer") { } ohos_shared_library("datashare_provider") { - include_dirs = [] + include_dirs = + [ "//foundation/distributeddatamgr/kv_store/frameworks/common" ] sources = [ "${datashare_native_provider_path}/src/datashare_ext_ability.cpp", @@ -104,15 +106,13 @@ ohos_shared_library("datashare_provider") { public_configs = [ ":datashare_public_config" ] version_script = "provider/libdatashare_provider.map" innerapi_tags = [ "platformsdk" ] - deps = [ - "${ability_runtime_path}/frameworks/native/ability/native:abilitykit_native", - "${datashare_innerapi_path}/common:datashare_common", - ] + deps = [ "${datashare_innerapi_path}/common:datashare_common" ] external_deps = [ "ability_base:want", "ability_base:zuri", "ability_runtime:ability_context_native", + "ability_runtime:abilitykit_native", "ability_runtime:app_context", "ability_runtime:dataobs_manager", "ability_runtime:runtime", @@ -137,13 +137,11 @@ ohos_shared_library("datashare_ext_ability_module") { configs = [ ":ability_config" ] public_configs = [ ":datashare_public_config" ] - deps = [ - ":datashare_provider", - "${ability_runtime_path}/frameworks/native/ability/native:abilitykit_native", - ] + deps = [ ":datashare_provider" ] external_deps = [ "ability_base:want", + "ability_runtime:abilitykit_native", "ability_runtime:runtime", "c_utils:utils", "common_event_service:cesfwk_innerkits", diff --git a/data_share/interfaces/inner_api/common/BUILD.gn b/data_share/interfaces/inner_api/common/BUILD.gn index 9827a165d7d5be914cf205ca34c1f5a644488e8c..06abf4c76e5fe4aeceb4941b2c68b6662d0cc051 100644 --- a/data_share/interfaces/inner_api/common/BUILD.gn +++ b/data_share/interfaces/inner_api/common/BUILD.gn @@ -23,6 +23,13 @@ config("ability_config") { } } +config("datashare_public_config") { + visibility = [ ":*" ] + + include_dirs = + [ "${datashare_base_path}/interfaces/inner_api/common/include" ] +} + ohos_shared_library("datashare_common") { include_dirs = [ "${datashare_common_napi_path}/include", @@ -30,6 +37,8 @@ ohos_shared_library("datashare_common") { "${datashare_base_path}/interfaces/inner_api/common/include", "${datashare_base_path}/interfaces/inner_api/consumer/include", "${datashare_base_path}/interfaces/inner_api/provider/include", + "//foundation/communication/ipc/ipc/native/src/napi_common/include", + "//foundation/distributeddatamgr/kv_store/frameworks/common", ] sources = [ @@ -40,17 +49,20 @@ ohos_shared_library("datashare_common") { "${datashare_common_napi_path}/src/napi_datashare_values_bucket.cpp", "${datashare_common_native_path}/src/datashare_abs_result_set.cpp", "${datashare_common_native_path}/src/datashare_block_writer_impl.cpp", + "${datashare_common_native_path}/src/datashare_itypes_utils.cpp", "${datashare_common_native_path}/src/datashare_result_set.cpp", "${datashare_common_native_path}/src/ishared_result_set.cpp", "${datashare_common_native_path}/src/ishared_result_set_proxy.cpp", "${datashare_common_native_path}/src/ishared_result_set_stub.cpp", - "${datashare_common_native_path}/src/itypes_utils.cpp", "${datashare_common_native_path}/src/shared_block.cpp", ] + deps = [ "${ability_runtime_path}/frameworks/native/ability/native:abilitykit_native" ] + public_deps = [] configs = [ ":ability_config" ] + public_configs = [ ":datashare_public_config" ] version_script = "libdatashare_common.map" innerapi_tags = [ "platformsdk" ] @@ -61,6 +73,7 @@ ohos_shared_library("datashare_common") { "hitrace_native:hitrace_meter", "hitrace_native:libhitracechain", "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_napi_common", "ipc:ipc_single", "napi:ace_napi", ] diff --git a/data_share/interfaces/inner_api/common/include/datashare_errno.h b/data_share/interfaces/inner_api/common/include/datashare_errno.h index 9ac4f48e4a3018d34a778e0ae0081a6184466014..950d24f818b22bf989fb34ef33692bbafbd1ef79 100644 --- a/data_share/interfaces/inner_api/common/include/datashare_errno.h +++ b/data_share/interfaces/inner_api/common/include/datashare_errno.h @@ -35,29 +35,15 @@ constexpr int E_BASE = 1000; constexpr int E_ERROR = (E_BASE + 1); /** -* @brief The error code for readonly. +* @brief The error code for register exceptions. */ -constexpr int E_CANNOT_UPDATE_READONLY = (E_BASE + 2); +constexpr int E_REGISTERED_REPEATED = (E_BASE + 2); -/** -* @brief The error code for remove file. -*/ -constexpr int E_REMOVE_FILE = (E_BASE + 3); /** -* @brief The error code for empty file name. +* @brief The error code for register exceptions. */ -constexpr int E_EMPTY_FILE_NAME = (E_BASE + 4); - -/** -* @brief The error code for empty table name. -*/ -constexpr int E_EMPTY_TABLE_NAME = (E_BASE + 5); - -/** -* @brief The error code for empty valuesbucket. -*/ -constexpr int E_EMPTY_VALUES_BUCKET = (E_BASE + 6); +constexpr int E_UNREGISTERED_EMPTY = (E_BASE + 3); /** * @brief The error code for invalid statement. @@ -69,185 +55,35 @@ constexpr int E_INVALID_STATEMENT = (E_BASE + 7); */ constexpr int E_INVALID_COLUMN_INDEX = (E_BASE + 8); -/** -* @brief The error code for invalid column type. -*/ -constexpr int E_INVALID_COLUMN_TYPE = (E_BASE + 9); - -/** -* @brief The error code for invalid column name. -*/ -constexpr int E_INVALID_COLUMN_NAME = (E_BASE + 10); - -/** -* @brief The error code for query execute. -*/ -constexpr int E_QUERY_IN_EXECUTE = (E_BASE + 11); - -/** -* @brief The error code for transaction execute. -*/ -constexpr int E_TRANSACTION_IN_EXECUTE = (E_BASE + 12); - -/** -* @brief The error code for execute step query. -*/ -constexpr int E_EXECUTE_IN_STEP_QUERY = (E_BASE + 13); - -/** -* @brief The error code for execute write read connection. -*/ -constexpr int E_EXECUTE_WRITE_IN_READ_CONNECTION = (E_BASE + 14); - -/** -* @brief The error code for begin transaction read connection. -*/ -constexpr int E_BEGIN_TRANSACTION_IN_READ_CONNECTION = (E_BASE + 15); - -/** -* @brief The error code for no transaction read session. -*/ -constexpr int E_NO_TRANSACTION_IN_SESSION = (E_BASE + 16); - -/** -* @brief The error code for more step query one session. -*/ -constexpr int E_MORE_STEP_QUERY_IN_ONE_SESSION = (E_BASE + 17); - -/** -* @brief The error code for no row query. -*/ -constexpr int E_NO_ROW_IN_QUERY = (E_BASE + 18); - -/** -* @brief The error code for invalid bind args count. -*/ -constexpr int E_INVALID_BIND_ARGS_COUNT = (E_BASE + 19); - /** * @brief The error code for invalid object type. */ constexpr int E_INVALID_OBJECT_TYPE = (E_BASE + 20); /** -* @brief The error code for invalid conflict flag. -*/ -constexpr int E_INVALID_CONFLICT_FLAG = (E_BASE + 21); - -/** -* @brief The error code for having clause not in group. -*/ -constexpr int E_HAVING_CLAUSE_NOT_IN_GROUP_BY = (E_BASE + 22); - -/** -* @brief The error code for not supported step resultset. -*/ -constexpr int E_NOT_SUPPORTED_BY_STEP_RESULT_SET = (E_BASE + 23); - -/** -* @brief The error code for step resultset cross threads. -*/ -constexpr int E_STEP_RESULT_SET_CROSS_THREADS = (E_BASE + 24); - -/** -* @brief The error code for step result query not executed. -*/ -constexpr int E_STEP_RESULT_QUERY_NOT_EXECUTED = (E_BASE + 25); - -/** -* @brief The error code for step result is after last. -*/ -constexpr int E_STEP_RESULT_IS_AFTER_LAST = (E_BASE + 26); - -/** -* @brief The error code for step result query exceeded. -*/ -constexpr int E_STEP_RESULT_QUERY_EXCEEDED = (E_BASE + 27); - -/** -* @brief The error code for statement not prepared. -*/ -constexpr int E_STATEMENT_NOT_PREPARED = (E_BASE + 28); - -/** -* @brief The error code for execute result incorrect. -*/ -constexpr int E_EXECUTE_RESULT_INCORRECT = (E_BASE + 29); - -/** -* @brief The error code for step result closed. -*/ -constexpr int E_STEP_RESULT_CLOSED = (E_BASE + 30); - -/** -* @brief The error code for relative path. -*/ -constexpr int E_RELATIVE_PATH = (E_BASE + 31); - -/** -* @brief The error code for empty new encrypt key. -*/ -constexpr int E_EMPTY_NEW_ENCRYPT_KEY = (E_BASE + 32); - -/** -* @brief The error code for change unencrypted to encrypted. -*/ -constexpr int E_CHANGE_UNENCRYPTED_TO_ENCRYPTED = (E_BASE + 33); - -/** -* @brief The error code for change encrypt key in busy. -*/ -constexpr int E_CHANGE_ENCRYPT_KEY_IN_BUSY = (E_BASE + 34); - -/** -* @brief The error code for step statement not init. -*/ -constexpr int E_STEP_STATEMENT_NOT_INIT = (E_BASE + 35); - -/** -* @brief The error code for not supported attach in wal mode. -*/ -constexpr int E_NOT_SUPPORTED_ATTACH_IN_WAL_MODE = (E_BASE + 36); - -/** -* @brief The error code for create folder fail. -*/ -constexpr int E_CREATE_FOLDER_FAIL = (E_BASE + 37); - -/** -* @brief The error code for sqlite builder normalize fail. -*/ -constexpr int E_SQLITE_SQL_BUILDER_NORMALIZE_FAIL = (E_BASE + 38); - -/** -* @brief The error code for store session not give connection temporarily. -*/ -constexpr int E_STORE_SESSION_NOT_GIVE_CONNECTION_TEMPORARILY = (E_BASE + 39); - -/** -* @brief The error code for store session no current transaction. +* @brief The error code for invalid parcel. */ -constexpr int E_STORE_SESSION_NO_CURRENT_TRANSACTION = (E_BASE + 40); +constexpr int E_INVALID_PARCEL = (E_BASE + 42); /** -* @brief The error code for not support. +* @brief The version is smaller than exist. */ -constexpr int E_NOT_SUPPORT = (E_BASE + 41); +constexpr int E_VERSION_NOT_NEWER = (E_BASE + 45); /** -* @brief The error code for invalid parcel. +* @brief Cannot find the template */ -constexpr int E_INVALID_PARCEL = (E_BASE + 42); +constexpr int E_TEMPLATE_NOT_EXIST = (E_BASE + 46); /** -* @brief The error code for invalid file path. +* @brief Cannot find the subscriber */ -constexpr int E_INVALID_FILE_PATH = (E_BASE + 43); +constexpr int E_SUBSCRIBER_NOT_EXIST = (E_BASE + 47); /** -* @brief The error code for set persist wal. +* @brief Cannot find the uri */ -constexpr int E_SET_PERSIST_WAL = (E_BASE + 44); +constexpr int E_URI_NOT_EXIST = (E_BASE + 48); } // namespace DataShare } // namespace OHOS diff --git a/data_share/interfaces/inner_api/common/include/datashare_predicates.h b/data_share/interfaces/inner_api/common/include/datashare_predicates.h index df8b5edac58c0c9a9ef24139949eb52fc99eb5cc..8426bcfc673120346d6835a79a7ce7b65b2d031f 100644 --- a/data_share/interfaces/inner_api/common/include/datashare_predicates.h +++ b/data_share/interfaces/inner_api/common/include/datashare_predicates.h @@ -1,600 +1,600 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DATASHARE_PREDICATES_H -#define DATASHARE_PREDICATES_H - -#include - -#include "datashare_abs_predicates.h" -#include "datashare_errno.h" -#include "datashare_predicates_object.h" -#include "datashare_predicates_objects.h" - -namespace OHOS { -namespace DataShare { -class DataSharePredicates : public DataShareAbsPredicates { -public: - - /** - * @brief Constructor. - */ - DataSharePredicates() - { - } - - /** - * @brief Constructor. - * - * A parameterized constructor used to create an DataSharePredicates instance. - * - * @param OperationList Indicates the operation list of the database. - */ - explicit DataSharePredicates(std::vector operList) : operations_(std::move(operList)) - { - } - - /** - * @brief Destructor. - */ - ~DataSharePredicates() - { - } - - /** - * @brief The EqualTo of the predicate. - * - * @param field Indicates the target field. - * @param value Indicates the queried value. - */ - DataSharePredicates *EqualTo(const std::string &field, const SingleValue &value) - { - SetOperationList(EQUAL_TO, field, value); - return this; - } - - /** - * @brief The NotEqualTo of the predicate. - * - * @param field Indicates the target field. - * @param value Indicates the queried value. - */ - DataSharePredicates *NotEqualTo(const std::string &field, const SingleValue &value) - { - SetOperationList(NOT_EQUAL_TO, field, value); - return this; - } - - /** - * @brief The GreaterThan of the predicate. - * - * @param field Indicates the target field. - * @param value Indicates the queried value. - */ - DataSharePredicates *GreaterThan(const std::string &field, const SingleValue &value) - { - SetOperationList(GREATER_THAN, field, value); - return this; - } - - /** - * @brief The LessThan of the predicate. - * - * @param field Indicates the target field. - * @param value Indicates the queried value. - */ - DataSharePredicates *LessThan(const std::string &field, const SingleValue &value) - { - SetOperationList(LESS_THAN, field, value); - return this; - } - - /** - * @brief The GreaterThanOrEqualTo of the predicate. - * - * @param field Indicates the target field. - * @param value Indicates the queried value. - */ - DataSharePredicates *GreaterThanOrEqualTo(const std::string &field, const SingleValue &value) - { - SetOperationList(GREATER_THAN_OR_EQUAL_TO, field, value); - return this; - } - - /** - * @brief The LessThanOrEqualTo of the predicate. - * - * @param field Indicates the target field. - * @param value Indicates the queried value. - */ - DataSharePredicates *LessThanOrEqualTo(const std::string &field, const SingleValue &value) - { - SetOperationList(LESS_THAN_OR_EQUAL_TO, field, value); - return this; - } - - /** - * @brief The In of the predicate. - * - * @param field Indicates the target field. - * @param value Indicates the queried value. - */ - DataSharePredicates *In(const std::string &field, const MutliValue &values) - { - SetOperationList(SQL_IN, field, values); - return this; - } - - /** - * @brief The NotIn of the predicate. - * - * @param field Indicates the target field. - * @param value Indicates the queried value. - */ - DataSharePredicates *NotIn(const std::string &field, const MutliValue &values) - { - SetOperationList(NOT_IN, field, values); - return this; - } - - /** - * @brief BeginWrap. - */ - DataSharePredicates *BeginWrap() - { - SetOperationList(BEGIN_WARP); - return this; - } - - /** - * @brief EndWrap. - */ - DataSharePredicates *EndWrap() - { - SetOperationList(END_WARP); - return this; - } - - /** - * @brief Or. - */ - DataSharePredicates *Or() - { - SetOperationList(OR); - return this; - } - - /** - * @brief And. - */ - DataSharePredicates *And() - { - SetOperationList(AND); - return this; - } - - /** - * @brief The Contains of the predicate. - * - * @param field Indicates the target field. - * @param value Indicates the queried value. - */ - DataSharePredicates *Contains(const std::string &field, const std::string &value) - { - SetOperationList(CONTAINS, field, value); - return this; - } - - /** - * @brief The BeginsWith of the predicate. - * - * @param field Indicates the target field. - * @param value Indicates the queried value. - */ - DataSharePredicates *BeginsWith(const std::string &field, const std::string &value) - { - SetOperationList(BEGIN_WITH, field, value); - return this; - } - - /** - * @brief The EndsWith of the predicate. - * - * @param field Indicates the target field. - * @param value Indicates the queried value. - */ - DataSharePredicates *EndsWith(const std::string &field, const std::string &value) - { - SetOperationList(END_WITH, field, value); - return this; - } - - /** - * @brief The IsNull of the predicate. - * - * @param field Indicates the target field. - * @param value Indicates the queried value. - */ - DataSharePredicates *IsNull(const std::string &field) - { - SetOperationList(IS_NULL, field); - return this; - } - - /** - * @brief The IsNotNull of the predicate. - * - * @param field Indicates the target field. - * @param value Indicates the queried value. - */ - DataSharePredicates *IsNotNull(const std::string &field) - { - SetOperationList(IS_NOT_NULL, field); - return this; - } - - /** - * @brief The Like of the predicate. - * - * @param field Indicates the target field. - * @param value Indicates the queried value. - */ - DataSharePredicates *Like(const std::string &field, const std::string &value) - { - SetOperationList(LIKE, field, value); - return this; - } - - /** - * @brief The Unlike of the predicate. - * - * @param field Indicates the target field. - * @param value Indicates the queried value. - */ - DataSharePredicates *Unlike(const std::string &field, const std::string &value) - { - SetOperationList(UNLIKE, field, value); - return this; - } - - /** - * @brief The Glob of the predicate. - * - * @param field Indicates the target field. - * @param value Indicates the queried value. - */ - DataSharePredicates *Glob(const std::string &field, const std::string &value) - { - SetOperationList(GLOB, field, value); - return this; - } - - /** - * @brief The Between of the predicate. - * - * @param field Indicates the target field. - * @param value Indicates the queried value. - */ - DataSharePredicates *Between(const std::string &field, const std::string &low, const std::string &high) - { - SetOperationList(BETWEEN, field, low, high); - return this; - } - - /** - * @brief The NotBetween of the predicate. - * - * @param field Indicates the target field. - * @param value Indicates the queried value. - */ - DataSharePredicates *NotBetween(const std::string &field, const std::string &low, const std::string &high) - { - SetOperationList(NOTBETWEEN, field, low, high); - return this; - } - - /** - * @brief The OrderByAsc of the predicate. - * - * @param field Indicates the target field. - * @param value Indicates the queried value. - */ - DataSharePredicates *OrderByAsc(const std::string &field) - { - SetOperationList(ORDER_BY_ASC, field); - return this; - } - - /** - * @brief The OrderByDesc of the predicate. - * - * @param field Indicates the target field. - * @param value Indicates the queried value. - */ - DataSharePredicates *OrderByDesc(const std::string &field) - { - SetOperationList(ORDER_BY_DESC, field); - return this; - } - - /** - * @brief Distinct predicate condition. - */ - DataSharePredicates *Distinct() - { - SetOperationList(DISTINCT); - return this; - } - - /** - * @brief The Limit of the predicate. - * - * @param number Indicates the target number. - * @param offset Indicates the queried value. - */ - DataSharePredicates *Limit(const int number, const int offset) - { - SetOperationList(LIMIT, number, offset); - return this; - } - - /** - * @brief The GroupBy of the predicate. - * - * @param field Indicates the target field. - */ - DataSharePredicates *GroupBy(const std::vector &fields) - { - SetOperationList(GROUP_BY, fields); - return this; - } - - /** - * @brief The IndexedBy of the predicate. - * - * @param indexName indicates the query condition. - */ - DataSharePredicates *IndexedBy(const std::string &indexName) - { - SetOperationList(INDEXED_BY, indexName); - return this; - } - - /** - * @brief The KeyPrefix of the predicate. - * - * @param Search by prefix conditions. - */ - DataSharePredicates *KeyPrefix(const std::string &prefix) - { - SetOperationList(KEY_PREFIX, prefix); - return this; - } - - /** - * @brief The InKeys of the predicate. - * - * @param Query based on key conditions. - */ - DataSharePredicates *InKeys(const std::vector &keys) - { - SetOperationList(IN_KEY, keys); - return this; - } - - /** - * @brief The CrossJoin of the predicate. - * - * @param tableName indicates the query condition. - */ - DataSharePredicates *CrossJoin(const std::string &tableName) - { - SetOperationList(CROSSJOIN, tableName); - return this; - } - - /** - * @brief The InnerJoin of the predicate. - * - * @param tableName indicates the query condition. - */ - DataSharePredicates *InnerJoin(const std::string &tableName) - { - SetOperationList(INNERJOIN, tableName); - return this; - } - - /** - * @brief The LeftOuterJoin of the predicate. - * - * @param tableName indicates the query condition. - */ - DataSharePredicates *LeftOuterJoin(const std::string &tableName) - { - SetOperationList(LEFTOUTERJOIN, tableName); - return this; - } - - /** - * @brief The Using of the predicate. - * - * @param field Indicates the target field. - */ - DataSharePredicates *Using(const std::vector &fields) - { - SetOperationList(USING, fields); - return this; - } - - /** - * @brief The On of the predicate. - * - * @param field Indicates the target field. - */ - DataSharePredicates *On(const std::vector &fields) - { - SetOperationList(ON, fields); - return this; - } - - /** - * @brief The GetOperationList of the predicate. - */ - const std::vector &GetOperationList() const - { - return operations_; - } - - /** - * @brief The GetWhereClause of the predicate. - */ - std::string GetWhereClause() const - { - return whereClause_; - } - - /** - * @brief The SetWhereClause of the predicate. - * - * @param Query based on the whereClause. - */ - int SetWhereClause(const std::string &whereClause) - { - if ((settingMode_ != PREDICATES_METHOD) && (!whereClause.empty())) { - this->whereClause_ = whereClause; - settingMode_ = QUERY_LANGUAGE; - return E_OK; - } - return E_ERROR; - } - - /** - * @brief The GetWhereArgs of the predicate. - */ - std::vector GetWhereArgs() const - { - return whereArgs_; - } - - /** - * @brief The SetWhereArgs of the predicate. - * - * @param Query based on whereArgs conditions. - */ - int SetWhereArgs(const std::vector &whereArgs) - { - if ((settingMode_ != PREDICATES_METHOD) && (!whereArgs.empty())) { - if (!whereArgs.empty()) { - this->whereArgs_ = whereArgs; - settingMode_ = QUERY_LANGUAGE; - return E_OK; - } - } - return E_ERROR; - } - - /** - * @brief The GetOrder of the predicate. - */ - std::string GetOrder() const - { - return order_; - } - - /** - * @brief The SetOrder of the predicate. - * - * @param Query based on order conditions.. - */ - int SetOrder(const std::string &order) - { - if ((settingMode_ != PREDICATES_METHOD) && (!order.empty())) { - this->order_ = order; - settingMode_ = QUERY_LANGUAGE; - return E_OK; - } - return E_ERROR; - } - - /** - * @brief The GetSettingMode of the predicate. - */ - int16_t GetSettingMode() const - { - return settingMode_; - } - - /** - * @brief The SetSettingMode of the predicate. - */ - void SetSettingMode(int16_t settingMode) - { - settingMode_ = settingMode; - } - -private: - void SetOperationList(OperationType operationType, const MutliValue ¶m) - { - OperationItem operationItem {}; - operationItem.operation = operationType; - operationItem.multiParams.push_back(param.value); - operations_.push_back(operationItem); - if (settingMode_ != PREDICATES_METHOD) { - ClearQueryLanguage(); - settingMode_ = PREDICATES_METHOD; - } - } - void SetOperationList( - OperationType operationType, const SingleValue ¶m1, const MutliValue ¶m2) - { - OperationItem operationItem {}; - operationItem.operation = operationType; - operationItem.singleParams.push_back(param1.value); - operationItem.multiParams.push_back(param2.value); - operations_.push_back(operationItem); - if (settingMode_ != PREDICATES_METHOD) { - ClearQueryLanguage(); - settingMode_ = PREDICATES_METHOD; - } - } - void SetOperationList(OperationType operationType, const SingleValue ¶1 = {}, - const SingleValue ¶2 = {}, const SingleValue ¶3 = {}) - { - OperationItem operationItem {}; - operationItem.operation = operationType; - operationItem.singleParams.push_back(para1.value); - operationItem.singleParams.push_back(para2.value); - operationItem.singleParams.push_back(para3.value); - operations_.push_back(operationItem); - if (settingMode_ != PREDICATES_METHOD) { - ClearQueryLanguage(); - settingMode_ = PREDICATES_METHOD; - } - } - void ClearQueryLanguage() - { - whereClause_ = ""; - whereArgs_ = {}; - order_ = ""; - } - std::vector operations_; - std::string whereClause_; - std::vector whereArgs_; - std::string order_; - int16_t settingMode_ = {}; -}; -} // namespace DataShare -} // namespace OHOS +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DATASHARE_PREDICATES_H +#define DATASHARE_PREDICATES_H + +#include + +#include "datashare_abs_predicates.h" +#include "datashare_errno.h" +#include "datashare_predicates_object.h" +#include "datashare_predicates_objects.h" + +namespace OHOS { +namespace DataShare { +class DataSharePredicates : public DataShareAbsPredicates { +public: + + /** + * @brief Constructor. + */ + DataSharePredicates() + { + } + + /** + * @brief Constructor. + * + * A parameterized constructor used to create an DataSharePredicates instance. + * + * @param OperationList Indicates the operation list of the database. + */ + explicit DataSharePredicates(std::vector operList) : operations_(std::move(operList)) + { + } + + /** + * @brief Destructor. + */ + ~DataSharePredicates() + { + } + + /** + * @brief The EqualTo of the predicate. + * + * @param field Indicates the target field. + * @param value Indicates the queried value. + */ + DataSharePredicates *EqualTo(const std::string &field, const SingleValue &value) + { + SetOperationList(EQUAL_TO, field, value); + return this; + } + + /** + * @brief The NotEqualTo of the predicate. + * + * @param field Indicates the target field. + * @param value Indicates the queried value. + */ + DataSharePredicates *NotEqualTo(const std::string &field, const SingleValue &value) + { + SetOperationList(NOT_EQUAL_TO, field, value); + return this; + } + + /** + * @brief The GreaterThan of the predicate. + * + * @param field Indicates the target field. + * @param value Indicates the queried value. + */ + DataSharePredicates *GreaterThan(const std::string &field, const SingleValue &value) + { + SetOperationList(GREATER_THAN, field, value); + return this; + } + + /** + * @brief The LessThan of the predicate. + * + * @param field Indicates the target field. + * @param value Indicates the queried value. + */ + DataSharePredicates *LessThan(const std::string &field, const SingleValue &value) + { + SetOperationList(LESS_THAN, field, value); + return this; + } + + /** + * @brief The GreaterThanOrEqualTo of the predicate. + * + * @param field Indicates the target field. + * @param value Indicates the queried value. + */ + DataSharePredicates *GreaterThanOrEqualTo(const std::string &field, const SingleValue &value) + { + SetOperationList(GREATER_THAN_OR_EQUAL_TO, field, value); + return this; + } + + /** + * @brief The LessThanOrEqualTo of the predicate. + * + * @param field Indicates the target field. + * @param value Indicates the queried value. + */ + DataSharePredicates *LessThanOrEqualTo(const std::string &field, const SingleValue &value) + { + SetOperationList(LESS_THAN_OR_EQUAL_TO, field, value); + return this; + } + + /** + * @brief The In of the predicate. + * + * @param field Indicates the target field. + * @param value Indicates the queried value. + */ + DataSharePredicates *In(const std::string &field, const MutliValue &values) + { + SetOperationList(SQL_IN, field, values); + return this; + } + + /** + * @brief The NotIn of the predicate. + * + * @param field Indicates the target field. + * @param value Indicates the queried value. + */ + DataSharePredicates *NotIn(const std::string &field, const MutliValue &values) + { + SetOperationList(NOT_IN, field, values); + return this; + } + + /** + * @brief BeginWrap. + */ + DataSharePredicates *BeginWrap() + { + SetOperationList(BEGIN_WARP); + return this; + } + + /** + * @brief EndWrap. + */ + DataSharePredicates *EndWrap() + { + SetOperationList(END_WARP); + return this; + } + + /** + * @brief Or. + */ + DataSharePredicates *Or() + { + SetOperationList(OR); + return this; + } + + /** + * @brief And. + */ + DataSharePredicates *And() + { + SetOperationList(AND); + return this; + } + + /** + * @brief The Contains of the predicate. + * + * @param field Indicates the target field. + * @param value Indicates the queried value. + */ + DataSharePredicates *Contains(const std::string &field, const std::string &value) + { + SetOperationList(CONTAINS, field, value); + return this; + } + + /** + * @brief The BeginsWith of the predicate. + * + * @param field Indicates the target field. + * @param value Indicates the queried value. + */ + DataSharePredicates *BeginsWith(const std::string &field, const std::string &value) + { + SetOperationList(BEGIN_WITH, field, value); + return this; + } + + /** + * @brief The EndsWith of the predicate. + * + * @param field Indicates the target field. + * @param value Indicates the queried value. + */ + DataSharePredicates *EndsWith(const std::string &field, const std::string &value) + { + SetOperationList(END_WITH, field, value); + return this; + } + + /** + * @brief The IsNull of the predicate. + * + * @param field Indicates the target field. + * @param value Indicates the queried value. + */ + DataSharePredicates *IsNull(const std::string &field) + { + SetOperationList(IS_NULL, field); + return this; + } + + /** + * @brief The IsNotNull of the predicate. + * + * @param field Indicates the target field. + * @param value Indicates the queried value. + */ + DataSharePredicates *IsNotNull(const std::string &field) + { + SetOperationList(IS_NOT_NULL, field); + return this; + } + + /** + * @brief The Like of the predicate. + * + * @param field Indicates the target field. + * @param value Indicates the queried value. + */ + DataSharePredicates *Like(const std::string &field, const std::string &value) + { + SetOperationList(LIKE, field, value); + return this; + } + + /** + * @brief The Unlike of the predicate. + * + * @param field Indicates the target field. + * @param value Indicates the queried value. + */ + DataSharePredicates *Unlike(const std::string &field, const std::string &value) + { + SetOperationList(UNLIKE, field, value); + return this; + } + + /** + * @brief The Glob of the predicate. + * + * @param field Indicates the target field. + * @param value Indicates the queried value. + */ + DataSharePredicates *Glob(const std::string &field, const std::string &value) + { + SetOperationList(GLOB, field, value); + return this; + } + + /** + * @brief The Between of the predicate. + * + * @param field Indicates the target field. + * @param value Indicates the queried value. + */ + DataSharePredicates *Between(const std::string &field, const std::string &low, const std::string &high) + { + SetOperationList(BETWEEN, field, low, high); + return this; + } + + /** + * @brief The NotBetween of the predicate. + * + * @param field Indicates the target field. + * @param value Indicates the queried value. + */ + DataSharePredicates *NotBetween(const std::string &field, const std::string &low, const std::string &high) + { + SetOperationList(NOTBETWEEN, field, low, high); + return this; + } + + /** + * @brief The OrderByAsc of the predicate. + * + * @param field Indicates the target field. + * @param value Indicates the queried value. + */ + DataSharePredicates *OrderByAsc(const std::string &field) + { + SetOperationList(ORDER_BY_ASC, field); + return this; + } + + /** + * @brief The OrderByDesc of the predicate. + * + * @param field Indicates the target field. + * @param value Indicates the queried value. + */ + DataSharePredicates *OrderByDesc(const std::string &field) + { + SetOperationList(ORDER_BY_DESC, field); + return this; + } + + /** + * @brief Distinct predicate condition. + */ + DataSharePredicates *Distinct() + { + SetOperationList(DISTINCT); + return this; + } + + /** + * @brief The Limit of the predicate. + * + * @param number Indicates the target number. + * @param offset Indicates the queried value. + */ + DataSharePredicates *Limit(const int number, const int offset) + { + SetOperationList(LIMIT, number, offset); + return this; + } + + /** + * @brief The GroupBy of the predicate. + * + * @param field Indicates the target field. + */ + DataSharePredicates *GroupBy(const std::vector &fields) + { + SetOperationList(GROUP_BY, fields); + return this; + } + + /** + * @brief The IndexedBy of the predicate. + * + * @param indexName indicates the query condition. + */ + DataSharePredicates *IndexedBy(const std::string &indexName) + { + SetOperationList(INDEXED_BY, indexName); + return this; + } + + /** + * @brief The KeyPrefix of the predicate. + * + * @param Search by prefix conditions. + */ + DataSharePredicates *KeyPrefix(const std::string &prefix) + { + SetOperationList(KEY_PREFIX, prefix); + return this; + } + + /** + * @brief The InKeys of the predicate. + * + * @param Query based on key conditions. + */ + DataSharePredicates *InKeys(const std::vector &keys) + { + SetOperationList(IN_KEY, keys); + return this; + } + + /** + * @brief The CrossJoin of the predicate. + * + * @param tableName indicates the query condition. + */ + DataSharePredicates *CrossJoin(const std::string &tableName) + { + SetOperationList(CROSSJOIN, tableName); + return this; + } + + /** + * @brief The InnerJoin of the predicate. + * + * @param tableName indicates the query condition. + */ + DataSharePredicates *InnerJoin(const std::string &tableName) + { + SetOperationList(INNERJOIN, tableName); + return this; + } + + /** + * @brief The LeftOuterJoin of the predicate. + * + * @param tableName indicates the query condition. + */ + DataSharePredicates *LeftOuterJoin(const std::string &tableName) + { + SetOperationList(LEFTOUTERJOIN, tableName); + return this; + } + + /** + * @brief The Using of the predicate. + * + * @param field Indicates the target field. + */ + DataSharePredicates *Using(const std::vector &fields) + { + SetOperationList(USING, fields); + return this; + } + + /** + * @brief The On of the predicate. + * + * @param field Indicates the target field. + */ + DataSharePredicates *On(const std::vector &fields) + { + SetOperationList(ON, fields); + return this; + } + + /** + * @brief The GetOperationList of the predicate. + */ + const std::vector &GetOperationList() const + { + return operations_; + } + + /** + * @brief The GetWhereClause of the predicate. + */ + std::string GetWhereClause() const + { + return whereClause_; + } + + /** + * @brief The SetWhereClause of the predicate. + * + * @param Query based on the whereClause. + */ + int SetWhereClause(const std::string &whereClause) + { + if ((settingMode_ != PREDICATES_METHOD) && (!whereClause.empty())) { + this->whereClause_ = whereClause; + settingMode_ = QUERY_LANGUAGE; + return E_OK; + } + return E_ERROR; + } + + /** + * @brief The GetWhereArgs of the predicate. + */ + std::vector GetWhereArgs() const + { + return whereArgs_; + } + + /** + * @brief The SetWhereArgs of the predicate. + * + * @param Query based on whereArgs conditions. + */ + int SetWhereArgs(const std::vector &whereArgs) + { + if ((settingMode_ != PREDICATES_METHOD) && (!whereArgs.empty())) { + if (!whereArgs.empty()) { + this->whereArgs_ = whereArgs; + settingMode_ = QUERY_LANGUAGE; + return E_OK; + } + } + return E_ERROR; + } + + /** + * @brief The GetOrder of the predicate. + */ + std::string GetOrder() const + { + return order_; + } + + /** + * @brief The SetOrder of the predicate. + * + * @param Query based on order conditions.. + */ + int SetOrder(const std::string &order) + { + if ((settingMode_ != PREDICATES_METHOD) && (!order.empty())) { + this->order_ = order; + settingMode_ = QUERY_LANGUAGE; + return E_OK; + } + return E_ERROR; + } + + /** + * @brief The GetSettingMode of the predicate. + */ + int16_t GetSettingMode() const + { + return settingMode_; + } + + /** + * @brief The SetSettingMode of the predicate. + */ + void SetSettingMode(int16_t settingMode) + { + settingMode_ = settingMode; + } + +private: + void SetOperationList(OperationType operationType, const MutliValue ¶m) + { + OperationItem operationItem {}; + operationItem.operation = operationType; + operationItem.multiParams.push_back(param.value); + operations_.push_back(operationItem); + if (settingMode_ != PREDICATES_METHOD) { + ClearQueryLanguage(); + settingMode_ = PREDICATES_METHOD; + } + } + void SetOperationList( + OperationType operationType, const SingleValue ¶m1, const MutliValue ¶m2) + { + OperationItem operationItem {}; + operationItem.operation = operationType; + operationItem.singleParams.push_back(param1.value); + operationItem.multiParams.push_back(param2.value); + operations_.push_back(operationItem); + if (settingMode_ != PREDICATES_METHOD) { + ClearQueryLanguage(); + settingMode_ = PREDICATES_METHOD; + } + } + void SetOperationList(OperationType operationType, const SingleValue ¶1 = {}, + const SingleValue ¶2 = {}, const SingleValue ¶3 = {}) + { + OperationItem operationItem {}; + operationItem.operation = operationType; + operationItem.singleParams.push_back(para1.value); + operationItem.singleParams.push_back(para2.value); + operationItem.singleParams.push_back(para3.value); + operations_.push_back(operationItem); + if (settingMode_ != PREDICATES_METHOD) { + ClearQueryLanguage(); + settingMode_ = PREDICATES_METHOD; + } + } + void ClearQueryLanguage() + { + whereClause_ = ""; + whereArgs_ = {}; + order_ = ""; + } + std::vector operations_; + std::string whereClause_; + std::vector whereArgs_; + std::string order_; + int16_t settingMode_ = {}; +}; +} // namespace DataShare +} // namespace OHOS #endif \ No newline at end of file diff --git a/data_share/interfaces/inner_api/common/include/datashare_predicates_def.h b/data_share/interfaces/inner_api/common/include/datashare_predicates_def.h index 68ebf5a563faa90fce98fecee552abae9bf57af8..06fc04fdf1362deaffd37af42a15d260c2277eee 100644 --- a/data_share/interfaces/inner_api/common/include/datashare_predicates_def.h +++ b/data_share/interfaces/inner_api/common/include/datashare_predicates_def.h @@ -1,139 +1,139 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -#ifndef DATASHARE_PREDICATES_DEF_H -#define DATASHARE_PREDICATES_DEF_H - -#include -#include -#include "datashare_predicates_object.h" -#include "datashare_predicates_objects.h" -namespace OHOS { -namespace DataShare { -/** - * @brief SetOperationList parameters. - */ -typedef enum { - /** Indicates the parameters is INVALID_OPERATION.*/ - INVALID_OPERATION = 0x0, - /** Indicates the parameters is EQUAL_TO.*/ - EQUAL_TO, - /** Indicates the parameters is NOT_EQUAL_TO.*/ - NOT_EQUAL_TO, - /** Indicates the parameters is GREATER_THAN.*/ - GREATER_THAN, - /** Indicates the parameters is LESS_THAN.*/ - LESS_THAN, - /** Indicates the parameters is GREATER_THAN_OR_EQUAL_TO.*/ - GREATER_THAN_OR_EQUAL_TO, - /** Indicates the parameters is LESS_THAN_OR_EQUAL_TO.*/ - LESS_THAN_OR_EQUAL_TO, - /** Indicates the parameters is AND.*/ - AND, - /** Indicates the parameters is OR.*/ - OR, - /** Indicates the parameters is IS_NULL.*/ - IS_NULL, - /** Indicates the parameters is IS_NOT_NULL.*/ - IS_NOT_NULL, - /** Indicates the parameters is SQL_IN.*/ - SQL_IN, - /** Indicates the parameters is NOT_IN.*/ - NOT_IN, - /** Indicates the parameters is LIKE.*/ - LIKE, - /** Indicates the parameters is UNLIKE.*/ - UNLIKE, - /** Indicates the parameters is ORDER_BY_ASC.*/ - ORDER_BY_ASC, - /** Indicates the parameters is ORDER_BY_DESC.*/ - ORDER_BY_DESC, - /** Indicates the parameters is LIMIT.*/ - LIMIT, - /** Indicates the parameters is OFFSET.*/ - OFFSET, - /** Indicates the parameters is BEGIN_WARP.*/ - BEGIN_WARP, - /** Indicates the parameters is END_WARP.*/ - END_WARP, - /** Indicates the parameters is BEGIN_WITH.*/ - BEGIN_WITH, - /** Indicates the parameters is END_WITH.*/ - END_WITH, - /** Indicates the parameters is IN_KEY.*/ - IN_KEY, - /** Indicates the parameters is DISTINCT.*/ - DISTINCT, - /** Indicates the parameters is GROUP_BY.*/ - GROUP_BY, - /** Indicates the parameters is INDEXED_BY.*/ - INDEXED_BY, - /** Indicates the parameters is CONTAINS.*/ - CONTAINS, - /** Indicates the parameters is GLOB.*/ - GLOB, - /** Indicates the parameters is BETWEEN.*/ - BETWEEN, - /** Indicates the parameters is NOTBETWEEN.*/ - NOTBETWEEN, - /** Indicates the parameters is KEY_PREFIX.*/ - KEY_PREFIX, - /** Indicates the parameters is CROSSJOIN.*/ - CROSSJOIN, - /** Indicates the parameters is INNERJOIN.*/ - INNERJOIN, - /** Indicates the parameters is LEFTOUTERJOIN.*/ - LEFTOUTERJOIN, - /** Indicates the parameters is USING.*/ - USING, - /** Indicates the parameters is ON.*/ - ON, - /** Indicates the parameters is LAST_TYPE.*/ - LAST_TYPE -} OperationType; - -/** - * @brief OperationItem. - */ -struct OperationItem { - /** operation.*/ - int32_t operation; - /** The type of singleParams*/ - std::vector singleParams; - /** The type of multiParams*/ - std::vector multiParams; - /** SingleValue GetSingle.*/ - inline SingleValue GetSingle(int32_t index) const - { - return singleParams[index]; - } -}; - -/** - * @brief typedef. - */ -typedef enum : int16_t { - /** The type of INVALID_MODE*/ - INVALID_MODE, - /** The type of QUERY_LANGUAGE*/ - QUERY_LANGUAGE, - /** The type of PREDICATES_METHOD*/ - PREDICATES_METHOD -} SettingMode; -} // namespace DataShare -} // namespace OHOS - +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef DATASHARE_PREDICATES_DEF_H +#define DATASHARE_PREDICATES_DEF_H + +#include +#include +#include "datashare_predicates_object.h" +#include "datashare_predicates_objects.h" +namespace OHOS { +namespace DataShare { +/** + * @brief SetOperationList parameters. + */ +typedef enum { + /** Indicates the parameters is INVALID_OPERATION.*/ + INVALID_OPERATION = 0x0, + /** Indicates the parameters is EQUAL_TO.*/ + EQUAL_TO, + /** Indicates the parameters is NOT_EQUAL_TO.*/ + NOT_EQUAL_TO, + /** Indicates the parameters is GREATER_THAN.*/ + GREATER_THAN, + /** Indicates the parameters is LESS_THAN.*/ + LESS_THAN, + /** Indicates the parameters is GREATER_THAN_OR_EQUAL_TO.*/ + GREATER_THAN_OR_EQUAL_TO, + /** Indicates the parameters is LESS_THAN_OR_EQUAL_TO.*/ + LESS_THAN_OR_EQUAL_TO, + /** Indicates the parameters is AND.*/ + AND, + /** Indicates the parameters is OR.*/ + OR, + /** Indicates the parameters is IS_NULL.*/ + IS_NULL, + /** Indicates the parameters is IS_NOT_NULL.*/ + IS_NOT_NULL, + /** Indicates the parameters is SQL_IN.*/ + SQL_IN, + /** Indicates the parameters is NOT_IN.*/ + NOT_IN, + /** Indicates the parameters is LIKE.*/ + LIKE, + /** Indicates the parameters is UNLIKE.*/ + UNLIKE, + /** Indicates the parameters is ORDER_BY_ASC.*/ + ORDER_BY_ASC, + /** Indicates the parameters is ORDER_BY_DESC.*/ + ORDER_BY_DESC, + /** Indicates the parameters is LIMIT.*/ + LIMIT, + /** Indicates the parameters is OFFSET.*/ + OFFSET, + /** Indicates the parameters is BEGIN_WARP.*/ + BEGIN_WARP, + /** Indicates the parameters is END_WARP.*/ + END_WARP, + /** Indicates the parameters is BEGIN_WITH.*/ + BEGIN_WITH, + /** Indicates the parameters is END_WITH.*/ + END_WITH, + /** Indicates the parameters is IN_KEY.*/ + IN_KEY, + /** Indicates the parameters is DISTINCT.*/ + DISTINCT, + /** Indicates the parameters is GROUP_BY.*/ + GROUP_BY, + /** Indicates the parameters is INDEXED_BY.*/ + INDEXED_BY, + /** Indicates the parameters is CONTAINS.*/ + CONTAINS, + /** Indicates the parameters is GLOB.*/ + GLOB, + /** Indicates the parameters is BETWEEN.*/ + BETWEEN, + /** Indicates the parameters is NOTBETWEEN.*/ + NOTBETWEEN, + /** Indicates the parameters is KEY_PREFIX.*/ + KEY_PREFIX, + /** Indicates the parameters is CROSSJOIN.*/ + CROSSJOIN, + /** Indicates the parameters is INNERJOIN.*/ + INNERJOIN, + /** Indicates the parameters is LEFTOUTERJOIN.*/ + LEFTOUTERJOIN, + /** Indicates the parameters is USING.*/ + USING, + /** Indicates the parameters is ON.*/ + ON, + /** Indicates the parameters is LAST_TYPE.*/ + LAST_TYPE +} OperationType; + +/** + * @brief OperationItem. + */ +struct OperationItem { + /** operation.*/ + int32_t operation; + /** The type of singleParams*/ + std::vector singleParams; + /** The type of multiParams*/ + std::vector multiParams; + /** SingleValue GetSingle.*/ + inline SingleValue GetSingle(int32_t index) const + { + return singleParams[index]; + } +}; + +/** + * @brief typedef. + */ +typedef enum : int16_t { + /** The type of INVALID_MODE*/ + INVALID_MODE, + /** The type of QUERY_LANGUAGE*/ + QUERY_LANGUAGE, + /** The type of PREDICATES_METHOD*/ + PREDICATES_METHOD +} SettingMode; +} // namespace DataShare +} // namespace OHOS + #endif \ No newline at end of file diff --git a/data_share/interfaces/inner_api/common/include/datashare_template.h b/data_share/interfaces/inner_api/common/include/datashare_template.h new file mode 100644 index 0000000000000000000000000000000000000000..d2b9ddbf55d7107ae07b0ae29d4a456932a7090b --- /dev/null +++ b/data_share/interfaces/inner_api/common/include/datashare_template.h @@ -0,0 +1,260 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DATASHARE_TEMPLATE_H +#define DATASHARE_TEMPLATE_H + +#include +#include +#include +#include "hilog/log.h" +#include "iremote_object.h" + +namespace OHOS { +namespace DataShare { +/** + * Specifies the predicates structure of the template. + */ +struct PredicateTemplateNode { + PredicateTemplateNode() = default; + PredicateTemplateNode(const std::string &key, const std::string &selectSql) : key_(key), selectSql_(selectSql) {} + /** Specifies the key of the sql. */ + std::string key_; + /** Specifies the sql of the template. */ + std::string selectSql_; +}; + +/** + * Specifies the template structure in subscribe. + */ +struct Template { + Template() = default; + Template(const std::vector &predicates, + const std::string &scheduler) : predicates_(predicates), scheduler_(scheduler) {} + /** Specifies the predicates of the template. {@link #PredicateTemplateNode} */ + std::vector predicates_; + /** Specifies the scheduler sql of the template. */ + std::string scheduler_; +}; + +/** + * Specifies the {@link Template} id structure, template is marked by the template id. + */ +struct TemplateId { + /** Specifies the id of subscriber. */ + int64_t subscriberId_; + /** Specifies the bundleName of template owner. */ + std::string bundleName_; + bool operator==(const TemplateId &tplId) const + { + return subscriberId_ == tplId.subscriberId_ && bundleName_ == tplId.bundleName_; + } + bool operator!=(const TemplateId &tplId) const + { + return !(tplId == *this); + } + bool operator<(const TemplateId &tplId) const + { + if (subscriberId_ != tplId.subscriberId_) { + return subscriberId_ < tplId.subscriberId_; + } + return bundleName_ < tplId.bundleName_; + } +}; + +/** + * Manages create datashare helper options. + */ +struct CreateOptions { + /** Specifies whether the {@link DataShareHelper} in proxy mode. */ + bool isProxy_ = true; + /** Specifies the System token. */ + sptr token_; + /** Specifies whether use options to create DataShareHelper. */ + bool enabled_ = false; +}; + +struct AshmemNode { + sptr ashmem; + bool isManaged; +}; + +/** + * Specifies the published item structure. + */ +struct PublishedDataItem { + /** The key of the published data. */ + std::string key_; + /** The subscriber id */ + int64_t subscriberId_; + /** The published data. If the data is large, use Ashmem. Do not access, only for ipc */ + std::variant value_; + PublishedDataItem(){}; + PublishedDataItem(const PublishedDataItem &) = delete; + PublishedDataItem &operator=(const PublishedDataItem &) = delete; + virtual ~PublishedDataItem() + { + if (value_.index() == 0) { + AshmemNode &node = std::get(value_); + if (node.isManaged && node.ashmem != nullptr) { + node.ashmem->UnmapAshmem(); + node.ashmem->CloseAshmem(); + } + } + } + PublishedDataItem( + const std::string &key, int64_t subscriberId, std::variant, std::string> value) + : key_(key), subscriberId_(subscriberId) + { + if (value.index() == 0) { + std::vector &vecValue = std::get>(value); + sptr mem = Ashmem::CreateAshmem((key_ + std::to_string(subscriberId_)).c_str(), vecValue.size()); + if (mem == nullptr) { + return; + } + if (!mem->MapReadAndWriteAshmem()) { + mem->CloseAshmem(); + return; + } + if (!mem->WriteToAshmem(vecValue.data(), vecValue.size(), 0)) { + mem->UnmapAshmem(); + mem->CloseAshmem(); + return; + } + AshmemNode node = { mem, true }; + value_ = std::move(node); + } else { + value_ = std::move(std::get(value)); + } + } + + PublishedDataItem(PublishedDataItem &&item) + { + key_ = std::move(item.key_); + subscriberId_ = std::move(item.subscriberId_); + value_ = std::move(item.value_); + if (item.IsAshmem()) { + item.MoveOutAshmem(); + } + } + + PublishedDataItem &operator=(PublishedDataItem &&item) + { + key_ = std::move(item.key_); + subscriberId_ = std::move(item.subscriberId_); + value_ = std::move(item.value_); + if (item.IsAshmem()) { + item.MoveOutAshmem(); + } + return *this; + } + + inline bool IsAshmem() const + { + return value_.index() == 0; + } + + inline bool IsString() const + { + return value_.index() == 1; + } + + sptr MoveOutAshmem() + { + if (IsAshmem()) { + AshmemNode &node = std::get(value_); + if (!node.isManaged) { + return nullptr; + } + node.isManaged = false; + return std::move(node.ashmem); + } + return nullptr; + } + + void SetAshmem(sptr ashmem, bool isManaged = false) + { + AshmemNode node = { ashmem, isManaged }; + value_ = std::move(node); + } + + void Set(const std::string &value) + { + value_ = value; + } + + std::variant, std::string> GetData() const + { + if (IsAshmem()) { + const AshmemNode &node = std::get(value_); + if (node.ashmem != nullptr) { + node.ashmem->MapReadOnlyAshmem(); + uint8_t *data = (uint8_t *)node.ashmem->ReadFromAshmem(node.ashmem->GetAshmemSize(), 0); + if (data == nullptr) { + return std::vector(); + } + return std::vector(data, data + node.ashmem->GetAshmemSize()); + } + return std::vector(); + } else { + return std::get(value_); + } + } +}; + +/** Specifies the published data structure. */ +struct Data { + /** Indicates the published data. {@link PublishedDataItem} */ + std::vector datas_; + /** Indicates the version of data to publish, larger is newer. */ + int version_ = 0; +}; + +/** + * Specifies the change node structure of published data in callback. + */ +struct PublishedDataChangeNode { + /** Specifies the bundleName of the callback. */ + std::string ownerBundleName_; + /** Specifies the datas of the callback. */ + std::vector datas_; +}; + +/** + * Specifies the change node structure of rdb store data in callback. + */ +struct RdbChangeNode { + /** Specifies the uri of the callback. */ + std::string uri_; + /** Specifies the templateId of the callback. */ + TemplateId templateId_; + /** Specifies the datas of the callback. */ + std::vector data_; +}; + +/** + * Specifies the operation result structure. + */ +struct OperationResult { + OperationResult() = default; + OperationResult(const std::string &key, int errCode) : key_(key), errCode_(errCode) {} + /** Specifies the key of the operation result. */ + std::string key_; + /** Specifies the operation result error code. */ + int errCode_; +}; +} // namespace DataShare +} // namespace OHOS +#endif //DATASHARE_TEMPLATE_H diff --git a/data_share/interfaces/inner_api/common/libdatashare_common.map b/data_share/interfaces/inner_api/common/libdatashare_common.map index fc3862c64291f4bb3d301ec5db2e7f09b603cf6f..d0120308527894f4cba43739e9f4486ead40d9ad 100644 --- a/data_share/interfaces/inner_api/common/libdatashare_common.map +++ b/data_share/interfaces/inner_api/common/libdatashare_common.map @@ -1,27 +1,27 @@ -# Copyright (c) 2023 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -1.0 { - global: - *DataShareAbsPredicates*; - *DataShareJSUtils*; - *DataSharePredicates*; - *DataShareResultSet*; - *DataShareValueObject*; - *DataShareValuesBucket*; - *Error*; - *ISharedResultSet*; - *ITypesUtils*; - local: - *; +# Copyright (c) 2023 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +1.0 { + global: + *DataShareAbsPredicates*; + *DataShareJSUtils*; + *DataSharePredicates*; + *DataShareResultSet*; + *DataShareValueObject*; + *DataShareValuesBucket*; + *Error*; + *ISharedResultSet*; + *ITypesUtil*; + local: + *; }; \ No newline at end of file diff --git a/data_share/interfaces/inner_api/consumer/include/datashare_helper.h b/data_share/interfaces/inner_api/consumer/include/datashare_helper.h index 262195ae0c6b1401e829fc25ccb28571d0e80769..ff2bc8a8c510bc29dfb9f62031eae79953acdffb 100644 --- a/data_share/interfaces/inner_api/consumer/include/datashare_helper.h +++ b/data_share/interfaces/inner_api/consumer/include/datashare_helper.h @@ -16,15 +16,17 @@ #ifndef DATASHARE_HELPER_H #define DATASHARE_HELPER_H - #include #include #include +#include #include #include "base_connection.h" -#include "context.h" +#include "app/context.h" #include "datashare_business_error.h" +#include "datashare_template.h" +#include "rdb_subscriber_manager.h" #include "uri.h" using Uri = OHOS::Uri; @@ -33,7 +35,7 @@ namespace OHOS { namespace AppExecFwk { class PacMap; class IDataAbilityObserver; -} +} // namespace AppExecFwk namespace DataShare { using string = std::string; @@ -89,6 +91,16 @@ public: */ static std::shared_ptr Creator(const sptr &token, const std::string &strUri); + /** + * @brief Creates a DataShareHelper instance with the Uri and {@link #CreateOptions} . + * + * @param strUri Indicates the database table or disk file to operate. + * @param options Indicates the optional config. + * + * @return Returns the created DataShareHelper instance with a specified Uri. + */ + static std::shared_ptr Creator(const std::string &strUri, const CreateOptions &options); + /** * @brief Releases the client resource of the Data share. * You should call this method to releases client resource after the data operations are complete. @@ -273,17 +285,124 @@ public: */ Uri DenormalizeUri(Uri &uri); + /** + * @brief Adds a template of {@link #SubscribeRdbData}. + * @param uri, the uri to add. + * @param subscriberId, the subscribe id to add. + * @param tpl, the template to add. + * @return Returns the error code. + */ + int AddQueryTemplate(const std::string &uri, int64_t subscriberId, Template &tpl); + + /** + * @brief Deletes a template of {@link #SubscribeRdbData} + * @param uri, the uri to delete. + * @param subscriberId, the subscribe id to delete. + * @return Returns the error code. + */ + int DelQueryTemplate(const std::string &uri, int64_t subscriberId); + + /** + * @brief Update a single data into host data area. + * @param data, the data to publish. + * @param bundleName the bundleName of data to publish. + * @return Returns the error code. + */ + std::vector Publish(const Data &data, const std::string &bundleName); + + /** + * @brief Get published data by bundleName. + * @param bundleName, the bundleName of data. + * @return Data {@link #Data} + */ + Data GetPublishedData(const std::string &bundleName); + + /** + * @brief Registers observers to observe rdb data specified by the given uris and template. + * @param uris, the paths of the data to operate. + * @param templateId, the template of observers. + * @param callback, the callback function of observers. + * @return Returns the error code. + */ + std::vector SubscribeRdbData(const std::vector &uris, const TemplateId &templateId, + const std::function &callback); + + /** + * @brief Unregisters observers used for monitoring data specified by the given uris and template. + * @param uris, the paths of the data to operate, if uris is empty, Unregisters all observers. + * @param templateId, the template of observers. + * @return Returns the error code. + */ + std::vector UnsubscribeRdbData(const std::vector &uris = std::vector(), + const TemplateId &templateId = TemplateId()); + + /** + * @brief Enable observers by the given uris and template. + * @param uris, the paths of the data to operate. + * @param templateId, the template of observers. + * @return Returns the error code. + */ + std::vector EnableRdbSubs(const std::vector &uris, const TemplateId &templateId); + + /** + * @brief Disable observers by the given uris and template. + * @param uris, the paths of the data to operate. + * @param templateId, the template of observers. + * @return Returns the error code. + */ + std::vector DisableRdbSubs(const std::vector &uris, const TemplateId &templateId); + + /** + * @brief Registers observers to observe published data specified by the given uris and subscriberId. + * @param uris, the uris of the data to operate. + * @param subscriberId, the subscriberId of observers. + * @param callback, the callback function of observers. + * @return Returns the error code. + */ + std::vector SubscribePublishedData(const std::vector &uris, int64_t subscriberId, + const std::function &callback); + + /** + * @brief Unregisters observers used for monitoring data specified by the given uris and subscriberId. + * @param uris, the uris of the data to operate, if uris is empty, Unregisters all observers. + * @param subscriberId, the subscriberId of observers. + * @return Returns the error code. + */ + std::vector UnsubscribePublishedData( + const std::vector &uris = std::vector(), int64_t subscriberId = 0); + + /** + * @brief Enable observers by the given uris and subscriberId. + * @param uris, the paths of the data to operate. + * @param subscriberId, the subscriberId of observers. + * @return Returns the error code. + */ + std::vector EnablePubSubs(const std::vector &uris, int64_t subscriberId); + + /** + * @brief Disable observers by the given uris and template. + * @param uris, the paths of the data to operate. + * @param subscriberId, the subscriberId of observers. + * @return Returns the error code. + */ + std::vector DisablePubSubs(const std::vector &uris, int64_t subscriberId); + private: DataShareHelper(const sptr &token, const Uri &uri, - std::shared_ptr dataShareConnection); + std::shared_ptr dataShareConnection); DataShareHelper(const sptr &token, const Uri &uri); + DataShareHelper(const CreateOptions &options, const Uri &uri, std::shared_ptr dataShareConnection); bool isDataShareService_ = false; sptr token_ = {}; Uri uri_ = Uri(""); std::shared_ptr connection_ = nullptr; static bool RegObserver(const Uri &uri, const sptr &dataObserver); static bool UnregObserver(const Uri &uri, const sptr &dataObserver); + static std::string TransferUriPrefix(const std::string &originPrefix, const std::string &replacedPrefix, + const std::string &originUriStr); + std::shared_ptr rdbSubscriberManager_ = nullptr; + std::shared_ptr publishedDataSubscriberManager_ = nullptr; }; -} // namespace DataShare -} // namespace OHOS -#endif // DATASHARE_HELPER_H \ No newline at end of file +} // namespace DataShare +} // namespace OHOS +#endif // DATASHARE_HELPER_H \ No newline at end of file diff --git a/data_share/interfaces/inner_api/consumer/include/datashare_result_set.h b/data_share/interfaces/inner_api/consumer/include/datashare_result_set.h index 69a8adeb93a4aa7e71b957fcebc017a84c11eb37..860d15c38856a913f028d93a1adc7ff84e415fa0 100644 --- a/data_share/interfaces/inner_api/consumer/include/datashare_result_set.h +++ b/data_share/interfaces/inner_api/consumer/include/datashare_result_set.h @@ -1,189 +1,189 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef DATASHARE_RESULT_SET_H -#define DATASHARE_RESULT_SET_H - -#include -#include -#include -#include - -#include "datashare_abs_result_set.h" -#include "datashare_block_writer_impl.h" -#include "datashare_shared_result_set.h" -#include "message_parcel.h" -#include "parcel.h" -#include "result_set_bridge.h" -#include "shared_block.h" - -namespace OHOS { -namespace DataShare { - -/** - * This module provides data resultsets. - */ -class DataShareResultSet : public DataShareAbsResultSet, public DataShareSharedResultSet { -public: - DataShareResultSet(); - explicit DataShareResultSet(std::shared_ptr &bridge); - virtual ~DataShareResultSet(); - - /** - * @brief Get the data whose value type is blob from the database according to the columnIndex. - * - * @param columnIndex the zero-based index of the target column. - * @param glob Indicates the value of glob type data to put. - * - * @return Return the value of the requested column as a byte array. - */ - int GetBlob(int columnIndex, std::vector &blob) override; - - /** - * @brief Get the data whose value type is string from the database according to the columnIndex. - * - * @param columnIndex the zero-based index of the target column. - * @param value Indicates the value of columnIndex data to put or update. - * - * @return Return the value of the requested column as a String. - */ - int GetString(int columnIndex, std::string &value) override; - - /** - * @brief Get the data whose value type is int from the database according to the columnIndex. - * - * @param columnIndex the zero-based index of the target column. - * @param value Indicates the value of columnIndex data to put or update. - * - * @return Return the value of the requested column as a int. - */ - int GetInt(int columnIndex, int &value) override; - - /** - * @brief Get the data whose value type is long from the database according to the columnIndex. - * - * @param columnIndex the zero-based index of the target column. - * @param value Indicates the value of columnIndex data to put or update. - * - * @return Return the value of the requested column as a long. - */ - int GetLong(int columnIndex, int64_t &value) override; - - /** - * @brief Get the data whose value type is double from the database according to the columnIndex. - * - * @param columnIndex the zero-based index of the target column. - * @param value Indicates the value of columnIndex data to put or update. - * - * @return Return the value of the requested column as a double. - */ - int GetDouble(int columnIndex, double &value) override; - - /** - * @brief Get the data whose value type is isNull from the database according to the columnIndex. - * - * @param columnIndex the zero-based index of the target column. - * @param isNull Indicates the value of glob type data to put. - * - * @return Return whether the column value is null. - */ - int IsColumnNull(int columnIndex, bool &isNull) override; - - /** - * @brief data type of the given column's value. - * - * @param columnIndex the zero-based index of the target column. - * @param Place the obtained data type. - * - * @return Return column value type. - */ - int GetDataType(int columnIndex, DataType &dataType) override; - - /** - * @brief Go to row based on position. - * - * @param position the zero-based position to move to. - * - * @return Return whether the requested move succeeded. - */ - int GoToRow(int position) override; - - /** - * @brief Returns a string array holding the names of all of the columns in the result set. - * - * @return Return the names of the columns contains in this query result. - */ - int GetAllColumnNames(std::vector &columnNames) override; - - /** - * @return Return the numbers of rows in the result set. - */ - int GetRowCount(int &count) override; - - /** - * Obtains a block from the SharedResultSet. - */ - AppDataFwk::SharedBlock *GetBlock() const override; - - /** - * Called when the position of the result set changes. - */ - bool OnGo(int startRowIndex, int targetRowIndex, int *cachedIndex = nullptr) override; - - /** - * Adds the data of a SharedResultSet to a SharedBlock. - */ - void FillBlock(int startRowIndex, AppDataFwk::SharedBlock *block) override; - - /** - * SetBlock. - */ - virtual void SetBlock(AppDataFwk::SharedBlock *block); - - /** - * Closes the result set, releasing all of its resources and making it completely invalid. - */ - int Close() override; - - /** - * Checks whether an DataShareResultSet object contains shared blocks. - */ - bool HasBlock() const; - -protected: - int CheckState(int columnIndex); - void ClosedBlock(); - virtual void Finalize(); - - friend class ISharedResultSetStub; - friend class ISharedResultSetProxy; - bool Unmarshalling(MessageParcel &parcel); - bool Marshalling(MessageParcel &parcel); - -private: - static int blockId_; - // The actual position of the first row of data in the shareblock - int startRowPos_ = -1; - // The actual position of the last row of data in the shareblock - int endRowPos_ = -1; - // The SharedBlock owned by this DataShareResultSet - AppDataFwk::SharedBlock *sharedBlock_ = nullptr; - std::shared_ptr blockWriter_ = nullptr; - std::shared_ptr bridge_ = nullptr; -}; -} // namespace DataShare -} // namespace OHOS - +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DATASHARE_RESULT_SET_H +#define DATASHARE_RESULT_SET_H + +#include +#include +#include +#include + +#include "datashare_abs_result_set.h" +#include "datashare_block_writer_impl.h" +#include "datashare_shared_result_set.h" +#include "message_parcel.h" +#include "parcel.h" +#include "result_set_bridge.h" +#include "shared_block.h" + +namespace OHOS { +namespace DataShare { + +/** + * This module provides data resultsets. + */ +class DataShareResultSet : public DataShareAbsResultSet, public DataShareSharedResultSet { +public: + DataShareResultSet(); + explicit DataShareResultSet(std::shared_ptr &bridge); + virtual ~DataShareResultSet(); + + /** + * @brief Get the data whose value type is blob from the database according to the columnIndex. + * + * @param columnIndex the zero-based index of the target column. + * @param glob Indicates the value of glob type data to put. + * + * @return Return the value of the requested column as a byte array. + */ + int GetBlob(int columnIndex, std::vector &blob) override; + + /** + * @brief Get the data whose value type is string from the database according to the columnIndex. + * + * @param columnIndex the zero-based index of the target column. + * @param value Indicates the value of columnIndex data to put or update. + * + * @return Return the value of the requested column as a String. + */ + int GetString(int columnIndex, std::string &value) override; + + /** + * @brief Get the data whose value type is int from the database according to the columnIndex. + * + * @param columnIndex the zero-based index of the target column. + * @param value Indicates the value of columnIndex data to put or update. + * + * @return Return the value of the requested column as a int. + */ + int GetInt(int columnIndex, int &value) override; + + /** + * @brief Get the data whose value type is long from the database according to the columnIndex. + * + * @param columnIndex the zero-based index of the target column. + * @param value Indicates the value of columnIndex data to put or update. + * + * @return Return the value of the requested column as a long. + */ + int GetLong(int columnIndex, int64_t &value) override; + + /** + * @brief Get the data whose value type is double from the database according to the columnIndex. + * + * @param columnIndex the zero-based index of the target column. + * @param value Indicates the value of columnIndex data to put or update. + * + * @return Return the value of the requested column as a double. + */ + int GetDouble(int columnIndex, double &value) override; + + /** + * @brief Get the data whose value type is isNull from the database according to the columnIndex. + * + * @param columnIndex the zero-based index of the target column. + * @param isNull Indicates the value of glob type data to put. + * + * @return Return whether the column value is null. + */ + int IsColumnNull(int columnIndex, bool &isNull) override; + + /** + * @brief data type of the given column's value. + * + * @param columnIndex the zero-based index of the target column. + * @param Place the obtained data type. + * + * @return Return column value type. + */ + int GetDataType(int columnIndex, DataType &dataType) override; + + /** + * @brief Go to row based on position. + * + * @param position the zero-based position to move to. + * + * @return Return whether the requested move succeeded. + */ + int GoToRow(int position) override; + + /** + * @brief Returns a string array holding the names of all of the columns in the result set. + * + * @return Return the names of the columns contains in this query result. + */ + int GetAllColumnNames(std::vector &columnNames) override; + + /** + * @return Return the numbers of rows in the result set. + */ + int GetRowCount(int &count) override; + + /** + * Obtains a block from the SharedResultSet. + */ + AppDataFwk::SharedBlock *GetBlock() const override; + + /** + * Called when the position of the result set changes. + */ + bool OnGo(int startRowIndex, int targetRowIndex, int *cachedIndex = nullptr) override; + + /** + * Adds the data of a SharedResultSet to a SharedBlock. + */ + void FillBlock(int startRowIndex, AppDataFwk::SharedBlock *block) override; + + /** + * SetBlock. + */ + virtual void SetBlock(AppDataFwk::SharedBlock *block); + + /** + * Closes the result set, releasing all of its resources and making it completely invalid. + */ + int Close() override; + + /** + * Checks whether an DataShareResultSet object contains shared blocks. + */ + bool HasBlock() const; + +protected: + int CheckState(int columnIndex); + void ClosedBlock(); + virtual void Finalize(); + + friend class ISharedResultSetStub; + friend class ISharedResultSetProxy; + bool Unmarshalling(MessageParcel &parcel); + bool Marshalling(MessageParcel &parcel); + +private: + static int blockId_; + // The actual position of the first row of data in the shareblock + int startRowPos_ = -1; + // The actual position of the last row of data in the shareblock + int endRowPos_ = -1; + // The SharedBlock owned by this DataShareResultSet + AppDataFwk::SharedBlock *sharedBlock_ = nullptr; + std::shared_ptr blockWriter_ = nullptr; + std::shared_ptr bridge_ = nullptr; +}; +} // namespace DataShare +} // namespace OHOS + #endif // DATASHARE_RESULT_SET_H \ No newline at end of file diff --git a/data_share/test/native/BUILD.gn b/data_share/test/native/BUILD.gn index 8c5ee15a76ff78cfe30a6e0909fc5f1b10127024..58a614ed58e779cc26b54aab0964324f472cbf2d 100644 --- a/data_share/test/native/BUILD.gn +++ b/data_share/test/native/BUILD.gn @@ -22,8 +22,10 @@ group("unittest") { ":ErrorCodeTest", ":JoinTest", ":NativeDataShareTest", + ":ProxyDatasTest", ":SlientAccessTest", "resource/datashare_ext_bundle:datashare_ext", + "resource/datashareproxy_bundle/proxydatas_with_permission:proxydatas_with_permission", "resource/errorcode_ext_bundle:errorcode_ext", "resource/ohos_test:copy_ohos_test", ] @@ -33,22 +35,22 @@ ohos_unittest("NativeDataShareTest") { module_out_path = "data_share/native_datashare" include_dirs = [ + "//foundation/ability/ability_runtime/interfaces/inner_api/ability_manager/include", + "//foundation/ability/ability_runtime/interfaces/inner_api/app_manager/include/appmgr", + "//foundation/ability/ability_runtime/interfaces/kits/native/ability/native", "./unittest/mediadatashare_test/include", "//base/security/access_token/frameworks/common/include", "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", - "$MEDIA_LIB_BASE_DIR/interfaces/innerkits/native/include", + "${MEDIALIB_ROOT_PATH}/interfaces/innerkits/native/include", "//foundation/aafwk/standard/interfaces/innerkits/uri/include", - "${ABILITY_RUNTIME_INNER_API_PATH}/ability_manager/include", - "${ABILITY_RUNTIME_INNER_API_PATH}/app_manager/include/appmgr", - "${ABILITY_RUNTIME_PATH}/interfaces/kits/native/ability/native", - "$MEDIA_LIB_INNERKITS_DIR/media_library_helper/include", + "${MEDIALIB_INNERKITS_PATH}/media_library_helper/include", "//commonlibrary/c_utils/base/include", "//utils/system/safwk/native/include", "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", - "${MEDIA_LIB_SERVICES_DIR}/media_library/include", - "${MEDIA_LIB_BASE_DIR}/frameworks/innerkitsimpl/medialibrary_data_extension/include", - "${MEDIA_LIB_BASE_DIR}/interfaces/inner_api/media_library_helper/include", - "${MEDIA_LIB_COMMON_UTILS_DIR}/include", + "${MEDIALIB_SERVICES_PATH}/media_library/include", + "${MEDIALIB_ROOT_PATH}/frameworks/innerkitsimpl/medialibrary_data_extension/include", + "${MEDIALIB_ROOT_PATH}/interfaces/inner_api/media_library_helper/include", + "${MEDIALIB_UTILS_PATH}/include", "//third_party/json/include", ] @@ -57,25 +59,24 @@ ohos_unittest("NativeDataShareTest") { "./unittest/mediadatashare_test/src/mediadatashare_unit_test.cpp", ] - deps = [ - "${ABILITY_RUNTIME_INNER_API_PATH}/ability_manager:ability_manager", - "${ABILITY_RUNTIME_PATH}/frameworks/native/ability/native:abilitykit_native", - "//foundation/multimedia/media_library/frameworks/innerkitsimpl/media_library_helper:media_library_packages", - "//foundation/multimedia/media_library/frameworks/innerkitsimpl/media_library_manager:media_library_manager", - ] + deps = [] external_deps = [ "ability_base:want", "ability_base:zuri", + "ability_runtime:ability_manager", + "ability_runtime:abilitykit_native", "access_token:libaccesstoken_sdk", "access_token:libnativetoken", "access_token:libtoken_setproc", "c_utils:utils", + "common_event_service:cesfwk_innerkits", "data_share:datashare_common", "data_share:datashare_consumer", "hilog_native:libhilog", "hitrace_native:hitrace_meter", "ipc:ipc_single", + "media_library:media_library", "relational_store:native_rdb", "safwk:system_ability_fwk", "samgr:samgr_proxy", @@ -96,18 +97,18 @@ ohos_unittest("SlientAccessTest") { sources = [ "./unittest/mediadatashare_test/src/slientaccess_test.cpp" ] - deps = [ - "${ABILITY_RUNTIME_INNER_API_PATH}/ability_manager:ability_manager", - "${ABILITY_RUNTIME_PATH}/frameworks/native/ability/native:abilitykit_native", - "//base/security/access_token/interfaces/innerkits/token_setproc:libtoken_setproc", - ] + deps = [] external_deps = [ "ability_base:want", "ability_base:zuri", + "ability_runtime:ability_manager", + "ability_runtime:abilitykit_native", "access_token:libaccesstoken_sdk", "access_token:libnativetoken", + "access_token:libtoken_setproc", "c_utils:utils", + "common_event_service:cesfwk_innerkits", "data_share:datashare_common", "data_share:datashare_consumer", "hilog_native:libhilog", @@ -131,18 +132,18 @@ ohos_unittest("ErrorCodeTest") { sources = [ "./unittest/mediadatashare_test/src/errorcode_test.cpp" ] - deps = [ - "${ABILITY_RUNTIME_INNER_API_PATH}/ability_manager:ability_manager", - "${ABILITY_RUNTIME_PATH}/frameworks/native/ability/native:abilitykit_native", - "//base/security/access_token/interfaces/innerkits/token_setproc:libtoken_setproc", - ] + deps = [] external_deps = [ "ability_base:want", "ability_base:zuri", + "ability_runtime:ability_manager", + "ability_runtime:abilitykit_native", "access_token:libaccesstoken_sdk", "access_token:libnativetoken", + "access_token:libtoken_setproc", "c_utils:utils", + "common_event_service:cesfwk_innerkits", "data_share:datashare_common", "data_share:datashare_consumer", "hilog_native:libhilog", @@ -166,18 +167,54 @@ ohos_unittest("JoinTest") { sources = [ "./unittest/mediadatashare_test/src/join_test.cpp" ] - deps = [ - "${ABILITY_RUNTIME_INNER_API_PATH}/ability_manager:ability_manager", - "${ABILITY_RUNTIME_PATH}/frameworks/native/ability/native:abilitykit_native", - "//base/security/access_token/interfaces/innerkits/token_setproc:libtoken_setproc", + deps = [] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_manager", + "ability_runtime:abilitykit_native", + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "data_share:datashare_common", + "data_share:datashare_consumer", + "hilog_native:libhilog", + "ipc:ipc_single", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", ] +} + +ohos_unittest("ProxyDatasTest") { + module_out_path = "data_share/native_datashare" + + include_dirs = [ + "//base/security/access_token/frameworks/common/include", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + "//foundation/aafwk/standard/interfaces/innerkits/uri/include", + "//commonlibrary/c_utils/base/include", + "//utils/system/safwk/native/include", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + ] + + sources = + [ "./unittest/datashareproxy_test/proxydatas_with_permission_test.cpp" ] + + deps = [] external_deps = [ "ability_base:want", "ability_base:zuri", + "ability_runtime:ability_manager", + "ability_runtime:abilitykit_native", "access_token:libaccesstoken_sdk", "access_token:libnativetoken", + "access_token:libtoken_setproc", "c_utils:utils", + "common_event_service:cesfwk_innerkits", "data_share:datashare_common", "data_share:datashare_consumer", "hilog_native:libhilog", diff --git a/data_share/test/native/resource/datashare_ext_bundle/AppScope/app.json b/data_share/test/native/resource/datashare_ext_bundle/AppScope/app.json index 8ec8c76abea7eadca2f91c81cc1d3d7675e4ec0b..1a429e292b59f61bae66f822d2f677badd6a1093 100644 --- a/data_share/test/native/resource/datashare_ext_bundle/AppScope/app.json +++ b/data_share/test/native/resource/datashare_ext_bundle/AppScope/app.json @@ -1,13 +1,13 @@ -{ - "app": { - "bundleName": "com.acts.datasharetest", - "vendor": "example", - "versionCode": 1000000, - "versionName": "1.0.0", - "icon": "$media:app_icon", - "label": "$string:app_name", - "distributedNotificationEnabled": true, - "minAPIVersion": 9, - "targetAPIVersion": 9 - } -} +{ + "app": { + "bundleName": "com.acts.datasharetest", + "vendor": "example", + "versionCode": 1000000, + "versionName": "1.0.0", + "icon": "$media:app_icon", + "label": "$string:app_name", + "distributedNotificationEnabled": true, + "minAPIVersion": 9, + "targetAPIVersion": 9 + } +} diff --git a/data_share/test/native/resource/datashare_ext_bundle/AppScope/resources/base/element/string.json b/data_share/test/native/resource/datashare_ext_bundle/AppScope/resources/base/element/string.json index 740e505afa0f81910681f96281493a3cf118388e..616c648fb1daa54ca2376c77ea5ac703fa0b205f 100644 --- a/data_share/test/native/resource/datashare_ext_bundle/AppScope/resources/base/element/string.json +++ b/data_share/test/native/resource/datashare_ext_bundle/AppScope/resources/base/element/string.json @@ -1,8 +1,8 @@ -{ - "string": [ - { - "name": "app_name", - "value": "datasharetest" - } - ] -} +{ + "string": [ + { + "name": "app_name", + "value": "datasharetest" + } + ] +} diff --git a/data_share/test/native/resource/datashare_ext_bundle/entry/src/main/ets/DataShareExtAbility/DataShareExtAbility.ts b/data_share/test/native/resource/datashare_ext_bundle/entry/src/main/ets/DataShareExtAbility/DataShareExtAbility.ts index d0aca8c35c9fbc375d33bb25083e2973fa87c5bc..b16b4be81ed1b48914252718a21e7c10bbeb2aa2 100644 --- a/data_share/test/native/resource/datashare_ext_bundle/entry/src/main/ets/DataShareExtAbility/DataShareExtAbility.ts +++ b/data_share/test/native/resource/datashare_ext_bundle/entry/src/main/ets/DataShareExtAbility/DataShareExtAbility.ts @@ -1,197 +1,197 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import Extension from '@ohos.application.DataShareExtensionAbility' -import rdb from '@ohos.data.relationalStore'; -import rpc from '@ohos.rpc'; - -let DB_NAME = "DB00.db"; -let TBL_NAME = "TBL00"; -let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " -+ TBL_NAME -+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)"; -let DDL_TABLE_USER_SQL = "CREATE TABLE IF NOT EXISTS user (userId INTEGER PRIMARY KEY AUTOINCREMENT, firstName TEXT, lastName TEXT, age INTEGER , balance DOUBLE NOT NULL)"; -let DDL_TABLE_BOOK_SQL = "CREATE TABLE IF NOT EXISTS book (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, userId INTEGER, FOREIGN KEY (userId) REFERENCES user (userId) ON UPDATE NO ACTION ON DELETE CASCADE)"; - -let rdbStore; - -export default class -extends Extension { - async onCreate(want, callback) { - console.log('[ttt] [DataShareTest] <> DataShareExtAbility onCreate, want:' + want.abilityName); - console.log("[ttt] [DataShareTest] DataShareExtAbility onCreate this.context.databaseDir:" + this.context.databaseDir); - // @ts-ignore - rdbStore = await rdb.getRdbStore(this.context, { name: DB_NAME, securityLevel: rdb.SecurityLevel.S1 }); - console.log('[ttt] [DataShareTest] <> DataShareExtAbility getRdbStore done'); - await rdbStore.executeSql(DDL_TBL_CREATE, []); - await rdbStore.executeSql(DDL_TABLE_USER_SQL, []); - await rdbStore.executeSql(DDL_TABLE_BOOK_SQL, []); - console.log('[ttt] [DataShareTest] <> DataShareExtAbility executeSql multiple tables done'); - let err = {"code":0}; - callback(err); - console.log('[ttt] [DataShareTest] <> DataShareExtAbility onCreate end'); - } - - async getFileTypes(uri: string, mimeTypeFilter: string, callback) { - console.info('[ttt] [DataShareTest] <> [getFileTypes] enter'); - let ret = new Array("type01", "type00", "type03"); - console.info('[ttt] [DataShareTest] <> [getFileTypes] leave, ret:' + ret); - let err = {"code":0}; - await callback(err,ret); - return ret; - } - - async openFile(uri: string, mode: string, callback) { - console.info('[ttt] [DataShareTest] <> [openFile] enter'); - let ret = 12345; - let err = {"code":0}; - await callback(err,ret); - console.info('[ttt] [DataShareTest] <> [openFile] leave, ret:' + ret); - } - - async insert(uri, value, callback) { - console.info('[ttt] [DataShareTest] <> [insert] enter'); - if (value == null) { - console.info('[ttt] [DataShareTest] <> [insert] invalid valueBuckets'); - return; - } - - console.info('[ttt] [DataShareTest] <> [insert] getCallingTokenId:' + rpc.IPCSkeleton.getCallingTokenId()); - console.info('[ttt] [DataShareTest] <> [insert] value = ' + value); - console.info('[ttt] [DataShareTest] <> [insert] value = ' + JSON.stringify(value)); - await rdbStore.insert(TBL_NAME, value, function (err, ret) { - console.info('[ttt] [DataShareTest] <> [insert] callback ret:' + ret); - - if (callback != undefined) { - callback(err, ret); - } - }); - console.info('[ttt] [DataShareTest] <> [insert] leave'); - } - - async update(uri, predicates, value, callback) { - console.info('[ttt] [DataShareTest] <> [update] enter'); - if (predicates == null || predicates == undefined) { - console.info('[ttt] [DataShareTest] <> [update] invalid predicates'); - return; - } - console.info('[ttt] [DataShareTest] <> [update] values = ' + value); - console.info('[ttt] [DataShareTest] <> [update] values = ' + JSON.stringify(value)); - console.info('[ttt] [DataShareTest] <> [update] predicates = ' + predicates); - console.info('[ttt] [DataShareTest] <> [update] predicates = ' + JSON.stringify(predicates)); - try { - await rdbStore.update(TBL_NAME,value, predicates, function (err, ret) { - console.info('[ttt] [DataShareTest] <> [update] callback ret:' + ret); - console.info('[ttt] [DataShareTest] <> [update] callback err:' + err); - if (callback != undefined) { - callback(err, ret); - } - }); - } catch (err) { - console.error('[ttt] [DataShareTest] <> [update] error' + err); - } - console.info('[ttt] [DataShareTest] <> [update] leave'); - } - - async delete(uri, predicates, callback) { - console.info('[ttt] [DataShareTest] <> [delete] enter'); - if (predicates == null || predicates == undefined) { - console.info('[ttt] [DataShareTest] <> [delete] invalid predicates'); - return; - } - console.info('[ttt] [DataShareTest] <> [delete] predicates = ' + predicates); - console.info('[ttt] [DataShareTest] <> [delete] predicates = ' + JSON.stringify(predicates)); - try { - await rdbStore.delete(TBL_NAME,predicates, function (err, ret) { - console.info('[ttt] [DataShareTest] <> [delete] ret:' + ret); - if (callback != undefined) { - callback(err, ret); - } - }); - } catch (err) { - console.error('[ttt] [DataShareTest] <> [delete] error' + err); - } - console.info('[ttt] [DataShareTest] <> [delete] leave'); - } - - async query(uri, predicates, columns, callback) { - console.info('[ttt] [DataShareTest] <> [query] enter'); - if (predicates == null || predicates == undefined) { - console.info('[ttt] [DataShareTest] <> [query] invalid predicates'); - } - console.info('[ttt] [DataShareTest] <> [query] values = ' + columns); - console.info('[ttt] [DataShareTest] <> [query] values = ' + JSON.stringify(columns)); - console.info('[ttt] [DataShareTest] <> [query] predicates = ' + predicates); - console.info('[ttt] [DataShareTest] <> [query] predicates = ' + JSON.stringify(predicates)); - try { - await rdbStore.query(TBL_NAME, predicates, columns, function (err, resultSet) { - console.info('[ttt] [DataShareTest] <> [query] ret: ' + resultSet); - if (resultSet != undefined) { - console.info('[ttt] [DataShareTest] <> [query] resultSet.rowCount: ' + resultSet.rowCount); - } - if (callback != undefined) { - callback(err, resultSet); - } - }); - } catch (err) { - console.error(`[ttt] [DataShareTest] <> [query] error: code: ${err.code}, message: ${err.message} `); - callback(err, undefined); - } - console.info('[ttt] [DataShareTest] <> [query] leave'); - } - - async getType(uri: string, callback) { - console.info('[ttt] [DataShareTest] <> [getType] enter'); - let ret = "image"; - console.info('[ttt] [DataShareTest] <> [getType] leave, ret:' + ret); - let err = {"code":0}; - await callback(err,ret); - return ret; - } - - async batchInsert(uri: string, valueBuckets, callback) { - console.info('[ttt] [DataShareTest] <> [batchInsert] enter'); - if (valueBuckets == null || valueBuckets.length == undefined) { - console.info('[ttt] [DataShareTest] <> [batchInsert] invalid valueBuckets'); - return; - } - console.info('[ttt] [DataShareTest] <> [batchInsert] valueBuckets.length:' + valueBuckets.length); - let resultNum = valueBuckets.length - await rdbStore.batchinsert(TBL_NAME, valueBuckets, function (err, ret) { - console.info('[ttt] [DataShareTest] <> [batchInsert] callback ret:' + ret); - if (callback != undefined) { - callback(err, ret); - } - }); - - console.info('[ttt] [DataShareTest] <> [batchInsert] leave'); - } - - async normalizeUri(uri: string, callback) { - console.info('[ttt] [DataShareTest] <> [normalizeUri] enter'); - let ret = "normalize+" + uri; - let err = {"code":0}; - await callback(err, ret); - console.info('[ttt] [DataShareTest] <> [normalizeUri] leave, ret:' + ret); - } - - async denormalizeUri(uri: string, callback) { - console.info('[ttt] [DataShareTest] <> [denormalizeUri] enter'); - let ret = "denormalize+" + uri; - let err = {"code":0}; - await callback(err, ret); - console.info('[ttt] [DataShareTest] <> [denormalizeUri] leave, ret:' + ret); - } +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Extension from '@ohos.application.DataShareExtensionAbility' +import rdb from '@ohos.data.relationalStore'; +import rpc from '@ohos.rpc'; + +let DB_NAME = "DB00.db"; +let TBL_NAME = "TBL00"; +let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " ++ TBL_NAME ++ " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)"; +let DDL_TABLE_USER_SQL = "CREATE TABLE IF NOT EXISTS user (userId INTEGER PRIMARY KEY AUTOINCREMENT, firstName TEXT, lastName TEXT, age INTEGER , balance DOUBLE NOT NULL)"; +let DDL_TABLE_BOOK_SQL = "CREATE TABLE IF NOT EXISTS book (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, userId INTEGER, FOREIGN KEY (userId) REFERENCES user (userId) ON UPDATE NO ACTION ON DELETE CASCADE)"; + +let rdbStore; + +export default class +extends Extension { + async onCreate(want, callback) { + console.log('[ttt] [DataShareTest] <> DataShareExtAbility onCreate, want:' + want.abilityName); + console.log("[ttt] [DataShareTest] DataShareExtAbility onCreate this.context.databaseDir:" + this.context.databaseDir); + // @ts-ignore + rdbStore = await rdb.getRdbStore(this.context, { name: DB_NAME, securityLevel: rdb.SecurityLevel.S1 }); + console.log('[ttt] [DataShareTest] <> DataShareExtAbility getRdbStore done'); + await rdbStore.executeSql(DDL_TBL_CREATE, []); + await rdbStore.executeSql(DDL_TABLE_USER_SQL, []); + await rdbStore.executeSql(DDL_TABLE_BOOK_SQL, []); + console.log('[ttt] [DataShareTest] <> DataShareExtAbility executeSql multiple tables done'); + let err = {"code":0}; + callback(err); + console.log('[ttt] [DataShareTest] <> DataShareExtAbility onCreate end'); + } + + async getFileTypes(uri: string, mimeTypeFilter: string, callback) { + console.info('[ttt] [DataShareTest] <> [getFileTypes] enter'); + let ret = new Array("type01", "type00", "type03"); + console.info('[ttt] [DataShareTest] <> [getFileTypes] leave, ret:' + ret); + let err = {"code":0}; + await callback(err,ret); + return ret; + } + + async openFile(uri: string, mode: string, callback) { + console.info('[ttt] [DataShareTest] <> [openFile] enter'); + let ret = 12345; + let err = {"code":0}; + await callback(err,ret); + console.info('[ttt] [DataShareTest] <> [openFile] leave, ret:' + ret); + } + + async insert(uri, value, callback) { + console.info('[ttt] [DataShareTest] <> [insert] enter'); + if (value == null) { + console.info('[ttt] [DataShareTest] <> [insert] invalid valueBuckets'); + return; + } + + console.info('[ttt] [DataShareTest] <> [insert] getCallingTokenId:' + rpc.IPCSkeleton.getCallingTokenId()); + console.info('[ttt] [DataShareTest] <> [insert] value = ' + value); + console.info('[ttt] [DataShareTest] <> [insert] value = ' + JSON.stringify(value)); + await rdbStore.insert(TBL_NAME, value, function (err, ret) { + console.info('[ttt] [DataShareTest] <> [insert] callback ret:' + ret); + + if (callback != undefined) { + callback(err, ret); + } + }); + console.info('[ttt] [DataShareTest] <> [insert] leave'); + } + + async update(uri, predicates, value, callback) { + console.info('[ttt] [DataShareTest] <> [update] enter'); + if (predicates == null || predicates == undefined) { + console.info('[ttt] [DataShareTest] <> [update] invalid predicates'); + return; + } + console.info('[ttt] [DataShareTest] <> [update] values = ' + value); + console.info('[ttt] [DataShareTest] <> [update] values = ' + JSON.stringify(value)); + console.info('[ttt] [DataShareTest] <> [update] predicates = ' + predicates); + console.info('[ttt] [DataShareTest] <> [update] predicates = ' + JSON.stringify(predicates)); + try { + await rdbStore.update(TBL_NAME,value, predicates, function (err, ret) { + console.info('[ttt] [DataShareTest] <> [update] callback ret:' + ret); + console.info('[ttt] [DataShareTest] <> [update] callback err:' + err); + if (callback != undefined) { + callback(err, ret); + } + }); + } catch (err) { + console.error('[ttt] [DataShareTest] <> [update] error' + err); + } + console.info('[ttt] [DataShareTest] <> [update] leave'); + } + + async delete(uri, predicates, callback) { + console.info('[ttt] [DataShareTest] <> [delete] enter'); + if (predicates == null || predicates == undefined) { + console.info('[ttt] [DataShareTest] <> [delete] invalid predicates'); + return; + } + console.info('[ttt] [DataShareTest] <> [delete] predicates = ' + predicates); + console.info('[ttt] [DataShareTest] <> [delete] predicates = ' + JSON.stringify(predicates)); + try { + await rdbStore.delete(TBL_NAME,predicates, function (err, ret) { + console.info('[ttt] [DataShareTest] <> [delete] ret:' + ret); + if (callback != undefined) { + callback(err, ret); + } + }); + } catch (err) { + console.error('[ttt] [DataShareTest] <> [delete] error' + err); + } + console.info('[ttt] [DataShareTest] <> [delete] leave'); + } + + async query(uri, predicates, columns, callback) { + console.info('[ttt] [DataShareTest] <> [query] enter'); + if (predicates == null || predicates == undefined) { + console.info('[ttt] [DataShareTest] <> [query] invalid predicates'); + } + console.info('[ttt] [DataShareTest] <> [query] values = ' + columns); + console.info('[ttt] [DataShareTest] <> [query] values = ' + JSON.stringify(columns)); + console.info('[ttt] [DataShareTest] <> [query] predicates = ' + predicates); + console.info('[ttt] [DataShareTest] <> [query] predicates = ' + JSON.stringify(predicates)); + try { + await rdbStore.query(TBL_NAME, predicates, columns, function (err, resultSet) { + console.info('[ttt] [DataShareTest] <> [query] ret: ' + resultSet); + if (resultSet != undefined) { + console.info('[ttt] [DataShareTest] <> [query] resultSet.rowCount: ' + resultSet.rowCount); + } + if (callback != undefined) { + callback(err, resultSet); + } + }); + } catch (err) { + console.error(`[ttt] [DataShareTest] <> [query] error: code: ${err.code}, message: ${err.message} `); + callback(err, undefined); + } + console.info('[ttt] [DataShareTest] <> [query] leave'); + } + + async getType(uri: string, callback) { + console.info('[ttt] [DataShareTest] <> [getType] enter'); + let ret = "image"; + console.info('[ttt] [DataShareTest] <> [getType] leave, ret:' + ret); + let err = {"code":0}; + await callback(err,ret); + return ret; + } + + async batchInsert(uri: string, valueBuckets, callback) { + console.info('[ttt] [DataShareTest] <> [batchInsert] enter'); + if (valueBuckets == null || valueBuckets.length == undefined) { + console.info('[ttt] [DataShareTest] <> [batchInsert] invalid valueBuckets'); + return; + } + console.info('[ttt] [DataShareTest] <> [batchInsert] valueBuckets.length:' + valueBuckets.length); + let resultNum = valueBuckets.length + await rdbStore.batchinsert(TBL_NAME, valueBuckets, function (err, ret) { + console.info('[ttt] [DataShareTest] <> [batchInsert] callback ret:' + ret); + if (callback != undefined) { + callback(err, ret); + } + }); + + console.info('[ttt] [DataShareTest] <> [batchInsert] leave'); + } + + async normalizeUri(uri: string, callback) { + console.info('[ttt] [DataShareTest] <> [normalizeUri] enter'); + let ret = "normalize+" + uri; + let err = {"code":0}; + await callback(err, ret); + console.info('[ttt] [DataShareTest] <> [normalizeUri] leave, ret:' + ret); + } + + async denormalizeUri(uri: string, callback) { + console.info('[ttt] [DataShareTest] <> [denormalizeUri] enter'); + let ret = "denormalize+" + uri; + let err = {"code":0}; + await callback(err, ret); + console.info('[ttt] [DataShareTest] <> [denormalizeUri] leave, ret:' + ret); + } }; \ No newline at end of file diff --git a/data_share/test/native/resource/datashare_ext_bundle/entry/src/main/ets/MainAbility/MainAbility.ts b/data_share/test/native/resource/datashare_ext_bundle/entry/src/main/ets/MainAbility/MainAbility.ts index 57457c2ba26d771683fe7dc3d3888d12e7b8c5d2..4900721331a82a3692d5ee92ea375bff6b5669e9 100644 --- a/data_share/test/native/resource/datashare_ext_bundle/entry/src/main/ets/MainAbility/MainAbility.ts +++ b/data_share/test/native/resource/datashare_ext_bundle/entry/src/main/ets/MainAbility/MainAbility.ts @@ -1,252 +1,252 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import Ability from '@ohos.app.ability.UIAbility' -import dataShare from '@ohos.data.dataShare' -import dataSharePredicates from '@ohos.data.dataSharePredicates' - -let dseUri = ("datashare:///com.acts.datasharetest"); -let uri = ("datashare://com.acts.datasharetest/entry/DB00/TBL00?Proxy=true"); - -export function onCallback() { - console.info("[ttt] [DataShareTest] <> **** Observer on callback ****"); -} - -export function offCallback() { - console.info("[ttt] [DataShareTest] <> **** Observer off callback ****"); -} - -export default class MainAbility extends Ability { - onCreate(want, launchParam) { - // Ability is creating, initialize resources for this ability - console.log("[ttt] [DataShareTest] <> MainAbility onCreate") - globalThis.abilityWant = want; - } - - onDestroy() { - // Ability is destroying, release resources for this ability - console.log("[ttt] [DataShareTest] <> MainAbility onDestroy") - } - - onWindowStageCreate(windowStage) { - // Main window is created, set main page for this ability - console.log("[ttt] [DataShareTest] <> MainAbility onWindowStageCreate") - globalThis.abilityContext = this.context; - console.log("[ttt] [DataShareTest] <> MainAbility this.context.databaseDir:" + this.context.databaseDir); - globalThis.connectDataShareExtAbility = (async () => { - console.log("[ttt] [DataShareTest] <> connectDataShareExtAbility begin"); - globalThis.dsHelper = await dataShare.createDataShareHelper(this.context, dseUri); - console.log("[ttt] [DataShareTest] <> connectDataShareExtAbility end"); - }) - - globalThis.disconnectDataShareExtAbility = (async () => { - console.log("[ttt] [DataShareTest] <> disconnectDataShareExtAbility begin"); - globalThis.dsHelper = null; - console.log("[ttt] [DataShareTest] <> disconnectDataShareExtAbility end"); - }) - - globalThis.on = (async () => { - console.log("[ttt] [DataShareTest] <> on begin"); - if (globalThis.dsHelper == null) { - console.log("[ttt] [DataShareTest] <> on end, DSHelper is null"); - return; - } - await globalThis.dsHelper.on("dataChange", uri, onCallback); - console.log("[ttt] [DataShareTest] <> on end"); - }) - - globalThis.off = (async () => { - console.log("[ttt] [DataShareTest] <> off begin"); - if (globalThis.dsHelper == null) { - console.log("[ttt] [DataShareTest] <> off end, DSHelper is null"); - return; - } - await globalThis.dsHelper.off("dataChange", uri); - await globalThis.dsHelper.off("dataChange", uri, offCallback); - console.log("[ttt] [DataShareTest] <> off end"); - }) - - globalThis.openFile = (async () => { - console.log("[ttt] [DataShareTest] <> openFile begin"); - if (globalThis.dsHelper == null) { - console.log("[ttt] [DataShareTest] <> openFile end, DSHelper is null"); - return; - } - let result = await globalThis.dsHelper.openFile(dseUri, "rw"); - console.log("[ttt] [DataShareTest] <> openFile end, result:" + result); - return result; - }) - - globalThis.query = (async () => { - console.log("[ttt] [DataShareTest] <> query begin"); - let da = new dataSharePredicates.DataSharePredicates(); - if (da == null || da == undefined) { - console.log("[ttt] [DataShareTest] <> da is null or undefined"); - return; - } - let count = 0; - if (globalThis.dsHelper == null) { - console.log("[ttt] [DataShareTest] <> query end, DSHelper is null"); - return; - } - da.equalTo("name", "ZhangSan"); - let result = await globalThis.dsHelper.query(dseUri, da, ["*"]); - if (result != undefined) { - count = result.rowCount; - } - console.log("[ttt] [DataShareTest] <> query end, count:" + count); - return count; - }) - - globalThis.insert = (async () => { - console.log("[ttt] [DataShareTest] <> insert begin"); - if (globalThis.dsHelper == null) { - console.log("[ttt] [DataShareTest] <> insert end, DSHelper is null"); - return; - } - let vb = {"name":"ZhangSan", "age": 21} - - console.log("[ttt] [DataShareTest] <> insert vb:" + JSON.stringify(vb)); - let ret = await globalThis.dsHelper.insert(dseUri, vb); - await console.log("[ttt] [DataShareTest] <> insert end, ret:" + ret); - return ret; - }) - - globalThis.update = (async () => { - console.log("[ttt] [DataShareTest] <> update begin"); - if (globalThis.dsHelper == null) { - console.log("[ttt] [DataShareTest] <> update end, DSHelper is null"); - return; - } - console.log("[ttt] [DataShareTest] <> update begin RPF666"); - let da = new dataSharePredicates.DataSharePredicates(); - console.log("[ttt] [DataShareTest] <> update begin RPF777"); - if (da == null || da == undefined) { - console.log("[ttt] [DataShareTest] <> da is null or undefined"); - return; - } - da.equalTo("name", "ZhangSan"); - - let ret = await globalThis.dsHelper.update(dseUri, da, {"name":"ZhangSan", "age":31}); - console.log("[ttt] [DataShareTest] <> update end, result:" + ret); - return ret; - }) - - globalThis.delete = (async () => { - console.log("[ttt] [DataShareTest] <> delete begin"); - if (globalThis.dsHelper == null) { - console.log("[ttt] [DataShareTest] <> delete end, DSHelper is null"); - return; - } - let da = new dataSharePredicates.DataSharePredicates(); - if (da == null || da == undefined) { - console.log("[ttt] [DataShareTest] <> da is null or undefined"); - return; - } - da.equalTo("name", "ZhangSan"); - let ret = await globalThis.dsHelper.delete(dseUri, da); - console.log("[ttt] [DataShareTest] <> delete end, result:" + ret); - return ret; - }) - - globalThis.batchInsert = (async () => { - console.log("[ttt] [DataShareTest] <> batchInsert begin"); - if (globalThis.dsHelper == null) { - console.log("[ttt] [DataShareTest] <> batchInsert end, DSHelper is null"); - return; - } - let ar = new Uint8Array([1,2,3,4,5,6]); - let arr = new Uint8Array([4,5,6,7]); - let people = new Array( - {"name": "LiSi", "age": 41, "Binary": ar}, - {"name": "WangWu", "age": 21, "Binary": arr}, - {"name": "ZhaoLiu", "age": 61, "Binary": arr}); - let ret = await globalThis.dsHelper.batchInsert(dseUri, people); - console.log("[ttt] [DataShareTest] <> batchInsert end, result:" + ret); - return ret; - }) - - globalThis.notifyChange = (async () => { - console.log("[ttt] [DataShareTest] <> notifyChange begin"); - if (globalThis.dsHelper == null) { - console.log("[ttt] [DataShareTest] <> notifyChange end, DSHelper is null"); - return; - } - await globalThis.dsHelper.notifyChange(dseUri); - console.log("[ttt] [DataShareTest] <> notifyChange end"); - }) - - globalThis.getType = (async () => { - console.log("[ttt] [DataShareTest] <> getType begin"); - if (globalThis.dsHelper == null) { - console.log("[ttt] [DataShareTest] <> getType end, DSHelper is null"); - return; - } - let result = await globalThis.dsHelper.getType(dseUri); - console.log("[ttt] [DataShareTest] <> getType end, result:" + result); - return result; - }) - - globalThis.getFileTypes = (async () => { - console.log("[ttt] [DataShareTest] <> getFileTypes begin"); - if (globalThis.dsHelper == null) { - console.log("[ttt] [DataShareTest] <> getFileTypes end, DSHelper is null"); - return; - } - let result = await globalThis.dsHelper.getFileTypes(dseUri, "image/*"); - console.log("[ttt] [DataShareTest] <> getFileTypes end, result:" + result); - return result; - }) - - globalThis.normalizeUri = (async () => { - console.log("[ttt] [DataShareTest] <> normalizeUri begin"); - if (globalThis.dsHelper == null) { - console.log("[ttt] [DataShareTest] <> normalizeUri end, DSHelper is null"); - return; - } - let result = await globalThis.dsHelper.normalizeUri(dseUri); - console.log("[ttt] [DataShareTest] <> normalizeUri end, result:" + result); - return result; - }) - - globalThis.denormalizeUri = (async () => { - console.log("[ttt] [DataShareTest] <> denormalizeUri begin"); - if (globalThis.dsHelper == null) { - console.log("[ttt] [DataShareTest] <> denormalizeUri end, DSHelper is null"); - return; - } - let result = await globalThis.dsHelper.denormalizeUri(dseUri); - console.log("[ttt] [DataShareTest] <> denormalizeUri end, result:" + result); - return result; - }) - - windowStage.setUIContent(this.context, "pages/index", null) - } - - onWindowStageDestroy() { - // Main window is destroyed, release UI related resources - console.log("[ttt] [DataShareTest] <> MainAbility onWindowStageDestroy") - } - - onForeground() { - // Ability has brought to foreground - console.log("[ttt] [DataShareTest] <> MainAbility onForeground") - } - - onBackground() { - // Ability has back to background - console.log("[ttt] [DataShareTest] <> MainAbility onBackground") - } +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Ability from '@ohos.app.ability.UIAbility' +import dataShare from '@ohos.data.dataShare' +import dataSharePredicates from '@ohos.data.dataSharePredicates' + +let dseUri = ("datashare:///com.acts.datasharetest"); +let uri = ("datashare://com.acts.datasharetest/entry/DB00/TBL00?Proxy=true"); + +export function onCallback() { + console.info("[ttt] [DataShareTest] <> **** Observer on callback ****"); +} + +export function offCallback() { + console.info("[ttt] [DataShareTest] <> **** Observer off callback ****"); +} + +export default class MainAbility extends Ability { + onCreate(want, launchParam) { + // Ability is creating, initialize resources for this ability + console.log("[ttt] [DataShareTest] <> MainAbility onCreate") + globalThis.abilityWant = want; + } + + onDestroy() { + // Ability is destroying, release resources for this ability + console.log("[ttt] [DataShareTest] <> MainAbility onDestroy") + } + + onWindowStageCreate(windowStage) { + // Main window is created, set main page for this ability + console.log("[ttt] [DataShareTest] <> MainAbility onWindowStageCreate") + globalThis.abilityContext = this.context; + console.log("[ttt] [DataShareTest] <> MainAbility this.context.databaseDir:" + this.context.databaseDir); + globalThis.connectDataShareExtAbility = (async () => { + console.log("[ttt] [DataShareTest] <> connectDataShareExtAbility begin"); + globalThis.dsHelper = await dataShare.createDataShareHelper(this.context, dseUri); + console.log("[ttt] [DataShareTest] <> connectDataShareExtAbility end"); + }) + + globalThis.disconnectDataShareExtAbility = (async () => { + console.log("[ttt] [DataShareTest] <> disconnectDataShareExtAbility begin"); + globalThis.dsHelper = null; + console.log("[ttt] [DataShareTest] <> disconnectDataShareExtAbility end"); + }) + + globalThis.on = (async () => { + console.log("[ttt] [DataShareTest] <> on begin"); + if (globalThis.dsHelper == null) { + console.log("[ttt] [DataShareTest] <> on end, DSHelper is null"); + return; + } + await globalThis.dsHelper.on("dataChange", uri, onCallback); + console.log("[ttt] [DataShareTest] <> on end"); + }) + + globalThis.off = (async () => { + console.log("[ttt] [DataShareTest] <> off begin"); + if (globalThis.dsHelper == null) { + console.log("[ttt] [DataShareTest] <> off end, DSHelper is null"); + return; + } + await globalThis.dsHelper.off("dataChange", uri); + await globalThis.dsHelper.off("dataChange", uri, offCallback); + console.log("[ttt] [DataShareTest] <> off end"); + }) + + globalThis.openFile = (async () => { + console.log("[ttt] [DataShareTest] <> openFile begin"); + if (globalThis.dsHelper == null) { + console.log("[ttt] [DataShareTest] <> openFile end, DSHelper is null"); + return; + } + let result = await globalThis.dsHelper.openFile(dseUri, "rw"); + console.log("[ttt] [DataShareTest] <> openFile end, result:" + result); + return result; + }) + + globalThis.query = (async () => { + console.log("[ttt] [DataShareTest] <> query begin"); + let da = new dataSharePredicates.DataSharePredicates(); + if (da == null || da == undefined) { + console.log("[ttt] [DataShareTest] <> da is null or undefined"); + return; + } + let count = 0; + if (globalThis.dsHelper == null) { + console.log("[ttt] [DataShareTest] <> query end, DSHelper is null"); + return; + } + da.equalTo("name", "ZhangSan"); + let result = await globalThis.dsHelper.query(dseUri, da, ["*"]); + if (result != undefined) { + count = result.rowCount; + } + console.log("[ttt] [DataShareTest] <> query end, count:" + count); + return count; + }) + + globalThis.insert = (async () => { + console.log("[ttt] [DataShareTest] <> insert begin"); + if (globalThis.dsHelper == null) { + console.log("[ttt] [DataShareTest] <> insert end, DSHelper is null"); + return; + } + let vb = {"name":"ZhangSan", "age": 21} + + console.log("[ttt] [DataShareTest] <> insert vb:" + JSON.stringify(vb)); + let ret = await globalThis.dsHelper.insert(dseUri, vb); + await console.log("[ttt] [DataShareTest] <> insert end, ret:" + ret); + return ret; + }) + + globalThis.update = (async () => { + console.log("[ttt] [DataShareTest] <> update begin"); + if (globalThis.dsHelper == null) { + console.log("[ttt] [DataShareTest] <> update end, DSHelper is null"); + return; + } + console.log("[ttt] [DataShareTest] <> update begin RPF666"); + let da = new dataSharePredicates.DataSharePredicates(); + console.log("[ttt] [DataShareTest] <> update begin RPF777"); + if (da == null || da == undefined) { + console.log("[ttt] [DataShareTest] <> da is null or undefined"); + return; + } + da.equalTo("name", "ZhangSan"); + + let ret = await globalThis.dsHelper.update(dseUri, da, {"name":"ZhangSan", "age":31}); + console.log("[ttt] [DataShareTest] <> update end, result:" + ret); + return ret; + }) + + globalThis.delete = (async () => { + console.log("[ttt] [DataShareTest] <> delete begin"); + if (globalThis.dsHelper == null) { + console.log("[ttt] [DataShareTest] <> delete end, DSHelper is null"); + return; + } + let da = new dataSharePredicates.DataSharePredicates(); + if (da == null || da == undefined) { + console.log("[ttt] [DataShareTest] <> da is null or undefined"); + return; + } + da.equalTo("name", "ZhangSan"); + let ret = await globalThis.dsHelper.delete(dseUri, da); + console.log("[ttt] [DataShareTest] <> delete end, result:" + ret); + return ret; + }) + + globalThis.batchInsert = (async () => { + console.log("[ttt] [DataShareTest] <> batchInsert begin"); + if (globalThis.dsHelper == null) { + console.log("[ttt] [DataShareTest] <> batchInsert end, DSHelper is null"); + return; + } + let ar = new Uint8Array([1,2,3,4,5,6]); + let arr = new Uint8Array([4,5,6,7]); + let people = new Array( + {"name": "LiSi", "age": 41, "Binary": ar}, + {"name": "WangWu", "age": 21, "Binary": arr}, + {"name": "ZhaoLiu", "age": 61, "Binary": arr}); + let ret = await globalThis.dsHelper.batchInsert(dseUri, people); + console.log("[ttt] [DataShareTest] <> batchInsert end, result:" + ret); + return ret; + }) + + globalThis.notifyChange = (async () => { + console.log("[ttt] [DataShareTest] <> notifyChange begin"); + if (globalThis.dsHelper == null) { + console.log("[ttt] [DataShareTest] <> notifyChange end, DSHelper is null"); + return; + } + await globalThis.dsHelper.notifyChange(dseUri); + console.log("[ttt] [DataShareTest] <> notifyChange end"); + }) + + globalThis.getType = (async () => { + console.log("[ttt] [DataShareTest] <> getType begin"); + if (globalThis.dsHelper == null) { + console.log("[ttt] [DataShareTest] <> getType end, DSHelper is null"); + return; + } + let result = await globalThis.dsHelper.getType(dseUri); + console.log("[ttt] [DataShareTest] <> getType end, result:" + result); + return result; + }) + + globalThis.getFileTypes = (async () => { + console.log("[ttt] [DataShareTest] <> getFileTypes begin"); + if (globalThis.dsHelper == null) { + console.log("[ttt] [DataShareTest] <> getFileTypes end, DSHelper is null"); + return; + } + let result = await globalThis.dsHelper.getFileTypes(dseUri, "image/*"); + console.log("[ttt] [DataShareTest] <> getFileTypes end, result:" + result); + return result; + }) + + globalThis.normalizeUri = (async () => { + console.log("[ttt] [DataShareTest] <> normalizeUri begin"); + if (globalThis.dsHelper == null) { + console.log("[ttt] [DataShareTest] <> normalizeUri end, DSHelper is null"); + return; + } + let result = await globalThis.dsHelper.normalizeUri(dseUri); + console.log("[ttt] [DataShareTest] <> normalizeUri end, result:" + result); + return result; + }) + + globalThis.denormalizeUri = (async () => { + console.log("[ttt] [DataShareTest] <> denormalizeUri begin"); + if (globalThis.dsHelper == null) { + console.log("[ttt] [DataShareTest] <> denormalizeUri end, DSHelper is null"); + return; + } + let result = await globalThis.dsHelper.denormalizeUri(dseUri); + console.log("[ttt] [DataShareTest] <> denormalizeUri end, result:" + result); + return result; + }) + + windowStage.setUIContent(this.context, "pages/index", null) + } + + onWindowStageDestroy() { + // Main window is destroyed, release UI related resources + console.log("[ttt] [DataShareTest] <> MainAbility onWindowStageDestroy") + } + + onForeground() { + // Ability has brought to foreground + console.log("[ttt] [DataShareTest] <> MainAbility onForeground") + } + + onBackground() { + // Ability has back to background + console.log("[ttt] [DataShareTest] <> MainAbility onBackground") + } }; \ No newline at end of file diff --git a/data_share/test/native/resource/datashare_ext_bundle/entry/src/main/ets/pages/index.ets b/data_share/test/native/resource/datashare_ext_bundle/entry/src/main/ets/pages/index.ets index 6323faaf90672dce585c7aadbdda3675f13dd6ad..c50c4db9d4965395e0e92cf642342c2c201342b9 100644 --- a/data_share/test/native/resource/datashare_ext_bundle/entry/src/main/ets/pages/index.ets +++ b/data_share/test/native/resource/datashare_ext_bundle/entry/src/main/ets/pages/index.ets @@ -1,341 +1,341 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import dataShare from '@ohos.data.dataShare' -import dataSharePredicates from '@ohos.data.dataSharePredicates' - -@Entry -@Component -struct Index { - @State message: string = "Main thread message filed" - - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Text('DataShare Extension Ability Test') - .fontSize(25) - .fontWeight(FontWeight.Bold) - - Text(`${this.message}`) - .fontSize(30) - .height('15%') - .width('100%') - .textAlign(TextAlign.Center) - - Row() { - Button() { - Text('Connect') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('45%') - .height('8%') - .backgroundColor('#0ddffb') - .onClick(async () => { - console.info('[ttt] [DataShareTest] <> Connect onclick enter') - this.message = 'Connect onclick' - await globalThis.connectDataShareExtAbility() - console.info('[ttt] [DataShareTest] <> Connect onclick leave') - }) - - Button() { - Text('Disconnect') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('45%') - .height('8%') - .backgroundColor('#0ddffb') - .onClick(async () => { - console.info('[ttt] [DataShareTest] <> Disconnect onclick enter') - this.message = 'Disconnect onclick' - await globalThis.disconnectDataShareExtAbility() - console.info('[ttt] [DataShareTest] <> Disconnect onclick leave') - }) - } - - Row() { - Button() { - Text('On') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('25%') - .height('8%') - .backgroundColor('#0ddffb') - .onClick(async () => { - console.info('[ttt] [DataShareTest] <> On onclick enter') - this.message = '~ On onclick' - try { - await globalThis.on(); - } catch (err) { - console.error('[ttt] [DataAbilityTest] Observer on catch(err)====>:' + err); - } - console.info('[ttt] [DataShareTest] <> On onclick leave') - }) - - Button() { - Text('Off') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('25%') - .height('8%') - .backgroundColor('#0ddffb') - .onClick(async () => { - console.info('[ttt] [DataShareTest] <> Off onclick enter') - this.message = '~ Off onclick' - try { - await globalThis.off(); - } catch (err) { - console.error('[ttt] [DataAbilityTest] Observer Off catch(err)====>:' + err); - } - console.info('[ttt] [DataShareTest] <> Off onclick leave') - }) - - Button() { - Text('OpenFile') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('40%') - .height('8%') - .backgroundColor('#0ddffb') - .onClick(async () => { - console.info('[ttt] [DataShareTest] <> OpenFile onclick enter') - this.message = 'OpenFile onclick' - let ret = await globalThis.openFile() - this.message += "\n\n Test Result: " + ret; - console.info('[ttt] [DataShareTest] <> OpenFile onclick leave') - }) - } - - Row() { - Button() { - Text('Query') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('45%') - .height('8%') - .backgroundColor('#0ddffb') - .onClick(async () => { - console.info('[ttt] [DataShareTest] <> Query onclick enter') - this.message = 'Query onclick' - let ret = await globalThis.query() - this.message += "\n\n Test Result: " + ret; - console.info('[ttt] [DataShareTest] <> Query onclick leave') - }) - - Button() { - Text('Insert') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('45%') - .height('8%') - .backgroundColor('#0ddffb') - .onClick(async () => { - console.info('[ttt] [DataShareTest] <> Insert onclick enter') - this.message = 'Insert onclick' - let ret = await globalThis.insert() - this.message += "\n\n Test Result: " + ret; - console.info('[ttt] [DataShareTest] <> Insert onclick leave') - }) - } - - Row() { - Button() { - Text('Update') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('45%') - .height('8%') - .backgroundColor('#0ddffb') - .onClick(async () => { - console.info('[ttt] [DataShareTest] <> Update onclick enter') - this.message = 'Update onclick' - let ret = await globalThis.update() - this.message += "\n\n Test Result: " + ret; - console.info('[ttt] [DataShareTest] <> Update onclick leave') - }) - - Button() { - Text('Delete') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('45%') - .height('8%') - .backgroundColor('#0ddffb') - .onClick(async () => { - console.info('[ttt] [DataShareTest] <> Delete onclick enter') - this.message = 'Delete onclick' - let ret = await globalThis.delete() - this.message += "\n\n Test Result: " + ret; - console.info('[ttt] [DataShareTest] <> Delete onclick leave') - }) - } - - Row() { - Button() { - Text('BatchInsert') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('45%') - .height('8%') - .backgroundColor('#0ddffb') - .onClick(async () => { - console.info('[ttt] [DataShareTest] <> BatchInsert onclick enter') - this.message = 'BatchInsert onclick' - let ret = await globalThis.batchInsert() - this.message += "\n\n Test Result: " + ret; - console.info('[ttt] [DataShareTest] <> BatchInsert onclick leave') - }) - - Button() { - Text('NotifyChange') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('45%') - .height('8%') - .backgroundColor('#0ddffb') - .onClick(async () => { - console.info('[ttt] [DataShareTest] <> NotifyChange onclick enter') - this.message = 'NotifyChange onclick' - await globalThis.notifyChange() - console.info('[ttt] [DataShareTest] <> NotifyChange onclick leave') - }) - } - - Row() { - Button() { - Text('GetType') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('45%') - .height('8%') - .backgroundColor('#0ddffb') - .onClick(async () => { - console.info('[ttt] [DataShareTest] <> GetType onclick enter') - this.message = 'GetType onclick' - let ret = await globalThis.getType() - this.message += "\n\n Test Result: " + ret; - console.info('[ttt] [DataShareTest] <> GetType onclick leave') - }) - - Button() { - Text('GetFileTypes') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('45%') - .height('8%') - .backgroundColor('#0ddffb') - .onClick(async () => { - console.info('[ttt] [DataShareTest] <> GetFileTypes onclick enter') - this.message = 'GetFileTypes onclick' - let ret = await globalThis.getFileTypes() - this.message += "\n\n Test Result: " + ret; - console.info('[ttt] [DataShareTest] <> GetFileTypes onclick leave') - }) - } - - Row() { - Button() { - Text('NormalizeUri') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('45%') - .height('8%') - .backgroundColor('#0ddffb') - .onClick(async () => { - console.info('[ttt] [DataShareTest] <> NormalizeUri onclick enter') - this.message = 'NormalizeUri onclick' - let ret = await globalThis.normalizeUri() - this.message += "\n\n Test Result: " + ret; - console.info('[ttt] [DataShareTest] <> NormalizeUri onclick leave') - }) - - Button() { - Text('DenormalizeUri') - .fontSize(25) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 20 - }) - .width('45%') - .height('8%') - .backgroundColor('#0ddffb') - .onClick(async () => { - console.info('[ttt] [DataShareTest] <> DenormalizeUri onclick enter') - this.message = 'DenormalizeUri onclick' - let ret = await globalThis.denormalizeUri() - this.message += "\n\n Test Result: " + ret; - console.info('[ttt] [DataShareTest] <> DenormalizeUri onclick leave') - }) - } - } - .width('100%') - .height('100%') - } +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import dataShare from '@ohos.data.dataShare' +import dataSharePredicates from '@ohos.data.dataSharePredicates' + +@Entry +@Component +struct Index { + @State message: string = "Main thread message filed" + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Text('DataShare Extension Ability Test') + .fontSize(25) + .fontWeight(FontWeight.Bold) + + Text(`${this.message}`) + .fontSize(30) + .height('15%') + .width('100%') + .textAlign(TextAlign.Center) + + Row() { + Button() { + Text('Connect') + .fontSize(25) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top: 20 + }) + .width('45%') + .height('8%') + .backgroundColor('#0ddffb') + .onClick(async () => { + console.info('[ttt] [DataShareTest] <> Connect onclick enter') + this.message = 'Connect onclick' + await globalThis.connectDataShareExtAbility() + console.info('[ttt] [DataShareTest] <> Connect onclick leave') + }) + + Button() { + Text('Disconnect') + .fontSize(25) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top: 20 + }) + .width('45%') + .height('8%') + .backgroundColor('#0ddffb') + .onClick(async () => { + console.info('[ttt] [DataShareTest] <> Disconnect onclick enter') + this.message = 'Disconnect onclick' + await globalThis.disconnectDataShareExtAbility() + console.info('[ttt] [DataShareTest] <> Disconnect onclick leave') + }) + } + + Row() { + Button() { + Text('On') + .fontSize(25) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top: 20 + }) + .width('25%') + .height('8%') + .backgroundColor('#0ddffb') + .onClick(async () => { + console.info('[ttt] [DataShareTest] <> On onclick enter') + this.message = '~ On onclick' + try { + await globalThis.on(); + } catch (err) { + console.error('[ttt] [DataAbilityTest] Observer on catch(err)====>:' + err); + } + console.info('[ttt] [DataShareTest] <> On onclick leave') + }) + + Button() { + Text('Off') + .fontSize(25) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top: 20 + }) + .width('25%') + .height('8%') + .backgroundColor('#0ddffb') + .onClick(async () => { + console.info('[ttt] [DataShareTest] <> Off onclick enter') + this.message = '~ Off onclick' + try { + await globalThis.off(); + } catch (err) { + console.error('[ttt] [DataAbilityTest] Observer Off catch(err)====>:' + err); + } + console.info('[ttt] [DataShareTest] <> Off onclick leave') + }) + + Button() { + Text('OpenFile') + .fontSize(25) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top: 20 + }) + .width('40%') + .height('8%') + .backgroundColor('#0ddffb') + .onClick(async () => { + console.info('[ttt] [DataShareTest] <> OpenFile onclick enter') + this.message = 'OpenFile onclick' + let ret = await globalThis.openFile() + this.message += "\n\n Test Result: " + ret; + console.info('[ttt] [DataShareTest] <> OpenFile onclick leave') + }) + } + + Row() { + Button() { + Text('Query') + .fontSize(25) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top: 20 + }) + .width('45%') + .height('8%') + .backgroundColor('#0ddffb') + .onClick(async () => { + console.info('[ttt] [DataShareTest] <> Query onclick enter') + this.message = 'Query onclick' + let ret = await globalThis.query() + this.message += "\n\n Test Result: " + ret; + console.info('[ttt] [DataShareTest] <> Query onclick leave') + }) + + Button() { + Text('Insert') + .fontSize(25) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top: 20 + }) + .width('45%') + .height('8%') + .backgroundColor('#0ddffb') + .onClick(async () => { + console.info('[ttt] [DataShareTest] <> Insert onclick enter') + this.message = 'Insert onclick' + let ret = await globalThis.insert() + this.message += "\n\n Test Result: " + ret; + console.info('[ttt] [DataShareTest] <> Insert onclick leave') + }) + } + + Row() { + Button() { + Text('Update') + .fontSize(25) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top: 20 + }) + .width('45%') + .height('8%') + .backgroundColor('#0ddffb') + .onClick(async () => { + console.info('[ttt] [DataShareTest] <> Update onclick enter') + this.message = 'Update onclick' + let ret = await globalThis.update() + this.message += "\n\n Test Result: " + ret; + console.info('[ttt] [DataShareTest] <> Update onclick leave') + }) + + Button() { + Text('Delete') + .fontSize(25) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top: 20 + }) + .width('45%') + .height('8%') + .backgroundColor('#0ddffb') + .onClick(async () => { + console.info('[ttt] [DataShareTest] <> Delete onclick enter') + this.message = 'Delete onclick' + let ret = await globalThis.delete() + this.message += "\n\n Test Result: " + ret; + console.info('[ttt] [DataShareTest] <> Delete onclick leave') + }) + } + + Row() { + Button() { + Text('BatchInsert') + .fontSize(25) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top: 20 + }) + .width('45%') + .height('8%') + .backgroundColor('#0ddffb') + .onClick(async () => { + console.info('[ttt] [DataShareTest] <> BatchInsert onclick enter') + this.message = 'BatchInsert onclick' + let ret = await globalThis.batchInsert() + this.message += "\n\n Test Result: " + ret; + console.info('[ttt] [DataShareTest] <> BatchInsert onclick leave') + }) + + Button() { + Text('NotifyChange') + .fontSize(25) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top: 20 + }) + .width('45%') + .height('8%') + .backgroundColor('#0ddffb') + .onClick(async () => { + console.info('[ttt] [DataShareTest] <> NotifyChange onclick enter') + this.message = 'NotifyChange onclick' + await globalThis.notifyChange() + console.info('[ttt] [DataShareTest] <> NotifyChange onclick leave') + }) + } + + Row() { + Button() { + Text('GetType') + .fontSize(25) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top: 20 + }) + .width('45%') + .height('8%') + .backgroundColor('#0ddffb') + .onClick(async () => { + console.info('[ttt] [DataShareTest] <> GetType onclick enter') + this.message = 'GetType onclick' + let ret = await globalThis.getType() + this.message += "\n\n Test Result: " + ret; + console.info('[ttt] [DataShareTest] <> GetType onclick leave') + }) + + Button() { + Text('GetFileTypes') + .fontSize(25) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top: 20 + }) + .width('45%') + .height('8%') + .backgroundColor('#0ddffb') + .onClick(async () => { + console.info('[ttt] [DataShareTest] <> GetFileTypes onclick enter') + this.message = 'GetFileTypes onclick' + let ret = await globalThis.getFileTypes() + this.message += "\n\n Test Result: " + ret; + console.info('[ttt] [DataShareTest] <> GetFileTypes onclick leave') + }) + } + + Row() { + Button() { + Text('NormalizeUri') + .fontSize(25) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top: 20 + }) + .width('45%') + .height('8%') + .backgroundColor('#0ddffb') + .onClick(async () => { + console.info('[ttt] [DataShareTest] <> NormalizeUri onclick enter') + this.message = 'NormalizeUri onclick' + let ret = await globalThis.normalizeUri() + this.message += "\n\n Test Result: " + ret; + console.info('[ttt] [DataShareTest] <> NormalizeUri onclick leave') + }) + + Button() { + Text('DenormalizeUri') + .fontSize(25) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top: 20 + }) + .width('45%') + .height('8%') + .backgroundColor('#0ddffb') + .onClick(async () => { + console.info('[ttt] [DataShareTest] <> DenormalizeUri onclick enter') + this.message = 'DenormalizeUri onclick' + let ret = await globalThis.denormalizeUri() + this.message += "\n\n Test Result: " + ret; + console.info('[ttt] [DataShareTest] <> DenormalizeUri onclick leave') + }) + } + } + .width('100%') + .height('100%') + } } \ No newline at end of file diff --git a/data_share/test/native/resource/datashare_ext_bundle/entry/src/main/module.json b/data_share/test/native/resource/datashare_ext_bundle/entry/src/main/module.json index d510285dabdf3e59140c06dbf9bcf0d601853c4a..e90f1bde14651e1c5a4bb6c0a4077f891f9bce6a 100644 --- a/data_share/test/native/resource/datashare_ext_bundle/entry/src/main/module.json +++ b/data_share/test/native/resource/datashare_ext_bundle/entry/src/main/module.json @@ -1,50 +1,50 @@ -{ - "module": { - "name": "entry", - "type": "entry", - "srcEntrance": "./ets/Application/MyAbilityStage.ts", - "description": "$string:entry_desc", - "mainElement": "MainAbility", - "deviceTypes": [ - "default", - "tablet" - ], - "deliveryWithInstall": true, - "installationFree": false, - "pages": "$profile:main_pages", - "uiSyntax": "ets", - "abilities": [ - { - "name": "MainAbility", - "srcEntrance": "./ets/MainAbility/MainAbility.ts", - "description": "$string:MainAbility_desc", - "icon": "$media:icon", - "label": "$string:MainAbility_label", - "startWindowIcon": "$media:icon", - "startWindowBackground": "$color:white", - "visible": true, - "skills": [ - { - "entities": [ - "entity.system.home" - ], - "actions": [ - "action.system.home" - ] - } - ] - } - ], - "extensionAbilities": [ - { - "srcEntrance": "./ets/DataShareExtAbility/DataShareExtAbility.ts", - "name": "DataShareExtAbility", - "icon": "$media:icon", - "description": "$string:description_datashareextability", - "type": "dataShare", - "uri": "datashare://com.acts.datasharetest", - "visible": true - } - ] - } +{ + "module": { + "name": "entry", + "type": "entry", + "srcEntrance": "./ets/Application/MyAbilityStage.ts", + "description": "$string:entry_desc", + "mainElement": "MainAbility", + "deviceTypes": [ + "default", + "tablet" + ], + "deliveryWithInstall": true, + "installationFree": false, + "pages": "$profile:main_pages", + "uiSyntax": "ets", + "abilities": [ + { + "name": "MainAbility", + "srcEntrance": "./ets/MainAbility/MainAbility.ts", + "description": "$string:MainAbility_desc", + "icon": "$media:icon", + "label": "$string:MainAbility_label", + "startWindowIcon": "$media:icon", + "startWindowBackground": "$color:white", + "visible": true, + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ] + } + ], + "extensionAbilities": [ + { + "srcEntrance": "./ets/DataShareExtAbility/DataShareExtAbility.ts", + "name": "DataShareExtAbility", + "icon": "$media:icon", + "description": "$string:description_datashareextability", + "type": "dataShare", + "uri": "datashare://com.acts.datasharetest", + "visible": true + } + ] + } } \ No newline at end of file diff --git a/data_share/test/native/resource/datashare_ext_bundle/entry/src/main/resources/base/element/color.json b/data_share/test/native/resource/datashare_ext_bundle/entry/src/main/resources/base/element/color.json index 1bbc9aa9617e97c45440e1d3d66afc1154837012..62a137a61b90c14f109ed8c81d9d551ea0a5888a 100644 --- a/data_share/test/native/resource/datashare_ext_bundle/entry/src/main/resources/base/element/color.json +++ b/data_share/test/native/resource/datashare_ext_bundle/entry/src/main/resources/base/element/color.json @@ -1,8 +1,8 @@ -{ - "color": [ - { - "name": "white", - "value": "#FFFFFF" - } - ] +{ + "color": [ + { + "name": "white", + "value": "#FFFFFF" + } + ] } \ No newline at end of file diff --git a/data_share/test/native/resource/datashare_ext_bundle/entry/src/main/resources/base/element/string.json b/data_share/test/native/resource/datashare_ext_bundle/entry/src/main/resources/base/element/string.json index 222eb589c8710beebac1dc5937b21715d620a245..d0f0ca1516fe6cb55080ec9f2d66851dbc446d0d 100644 --- a/data_share/test/native/resource/datashare_ext_bundle/entry/src/main/resources/base/element/string.json +++ b/data_share/test/native/resource/datashare_ext_bundle/entry/src/main/resources/base/element/string.json @@ -1,28 +1,28 @@ -{ - "string": [ - { - "name": "entry_desc", - "value": "description" - }, - { - "name": "MainAbility_desc", - "value": "description" - }, - { - "name": "MainAbility_label", - "value": "DataShareTest" - }, - { - "name": "description_application", - "value": "DataShareTest" - }, - { - "name": "app_name", - "value": "DataShareTest" - }, - { - "name": "description_datashareextability", - "value": "description_datashareextability" - } - ] +{ + "string": [ + { + "name": "entry_desc", + "value": "description" + }, + { + "name": "MainAbility_desc", + "value": "description" + }, + { + "name": "MainAbility_label", + "value": "DataShareTest" + }, + { + "name": "description_application", + "value": "DataShareTest" + }, + { + "name": "app_name", + "value": "DataShareTest" + }, + { + "name": "description_datashareextability", + "value": "description_datashareextability" + } + ] } \ No newline at end of file diff --git a/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/AppScope/app.json b/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/AppScope/app.json new file mode 100644 index 0000000000000000000000000000000000000000..2a325a8c75ad87afedbb2da739a61279f24996d8 --- /dev/null +++ b/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/AppScope/app.json @@ -0,0 +1,13 @@ +{ + "app": { + "bundleName": "com.acts.ohos.data.datasharetest", + "vendor": "example", + "versionCode": 1000000, + "versionName": "1.0.0", + "icon": "$media:app_icon", + "label": "$string:app_name", + "distributedNotificationEnabled": true, + "minAPIVersion": 9, + "targetAPIVersion": 9 + } +} diff --git a/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/AppScope/resources/base/element/string.json b/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/AppScope/resources/base/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..740e505afa0f81910681f96281493a3cf118388e --- /dev/null +++ b/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/AppScope/resources/base/element/string.json @@ -0,0 +1,8 @@ +{ + "string": [ + { + "name": "app_name", + "value": "datasharetest" + } + ] +} diff --git a/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/AppScope/resources/base/media/app_icon.png b/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/AppScope/resources/base/media/app_icon.png new file mode 100644 index 0000000000000000000000000000000000000000..ce307a8827bd75456441ceb57d530e4c8d45d36c Binary files /dev/null and b/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/AppScope/resources/base/media/app_icon.png differ diff --git a/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/BUILD.gn b/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..0849c752f69616f6e248847c15dd02d0e760a4c4 --- /dev/null +++ b/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/BUILD.gn @@ -0,0 +1,45 @@ +# Copyright (c) 2022 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +ohos_hap("proxydatas_with_permission") { + hap_profile = "entry/src/main/module.json" + hap_name = "proxydatas_with_permission" + subsystem_name = "distributeddatamgr" + part_name = "data_share" + final_hap_path = "$root_out_dir/tests/unittest/data_share/resource/datashareproxy_bundle/${hap_name}.hap" + testonly = true + deps = [ + ":datashare_ext_ets_assets", + ":datashare_ext_ets_resources", + ] + certificate_profile = "signature/openharmony_sx.p7b" +} + +ohos_js_assets("datashare_ext_ets_assets") { + ets2abc = true + source_dir = "entry/src/main/ets" + hap_profile = "entry/src/main/module.json" +} + +ohos_app_scope("datashare_ext_app_profile") { + app_profile = "AppScope/app.json" + sources = [ "AppScope/resources" ] +} + +ohos_resources("datashare_ext_ets_resources") { + sources = [ "entry/src/main/resources" ] + deps = [ ":datashare_ext_app_profile" ] + hap_profile = "entry/src/main/module.json" +} diff --git a/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/entry/src/main/ets/Application/MyAbilityStage.ts b/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/entry/src/main/ets/Application/MyAbilityStage.ts new file mode 100644 index 0000000000000000000000000000000000000000..53ea040c8327e44abb58a3433ed4fece60681e1d --- /dev/null +++ b/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/entry/src/main/ets/Application/MyAbilityStage.ts @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import AbilityStage from "@ohos.app.ability.AbilityStage" + +export default class MyAbilityStage extends AbilityStage { + onCreate() { + console.log("[ttt] [datashareproxyTest] MyAbilityStage onCreate"); + } +} \ No newline at end of file diff --git a/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/entry/src/main/ets/MainAbility/MainAbility.ts b/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/entry/src/main/ets/MainAbility/MainAbility.ts new file mode 100644 index 0000000000000000000000000000000000000000..8fcc30deef1c036b86814c0ca28169954a986276 --- /dev/null +++ b/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/entry/src/main/ets/MainAbility/MainAbility.ts @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Ability from '@ohos.app.ability.UIAbility' +import dataShare from '@ohos.data.dataShare' +import dataSharePredicates from '@ohos.data.dataSharePredicates' +import rdb from '@ohos.data.rdb'; + +let cardUri = ("datashareproxy://com.acts.ohos.data.datasharetest/test"); +let dsProxyHelper:dataShare.DataShareHelper; +let dbHelper:dataShare.DataShareHelper; +let DB_NAME = "DB00.db"; +let TBL_NAME = "TBL00"; +let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " ++ TBL_NAME ++ " (id INTEGER PRIMARY KEY AUTOINCREMENT, name0 TEXT, name1 TEXT, name2 TEXT, name3 TEXT, name4 TEXT, name5 TEXT, name6 TEXT, " + +"name7 TEXT, name8 TEXT, name9 TEXT, time INTEGER, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN)"; +let rdbStore; + +export default class MainAbility extends Ability { + async onCreate(want, launchParam) { + // Ability is creating, initialize resources for this ability + console.log("[ttt] [datashareproxyTest] <> MainAbility onCreate") + globalThis.abilityWant = want; + globalThis.abilityContext = this.context; + console.log('[ttt] [DataShareTest] <> DataShareExtAbility onCreate, want:' + want.abilityName); + console.log("[ttt] [DataShareTest] DataShareExtAbility onCreate this.context.databaseDir:" + this.context.databaseDir); + + rdbStore = await rdb.getRdbStore(this.context, { name: DB_NAME }, 1); + console.log('[ttt] [DataShareTest] <> DataShareExtAbility getRdbStore done'); + await rdbStore.executeSql(DDL_TBL_CREATE, []); + console.log('[ttt] [DataShareTest] <> DataShareExtAbility executeSql done'); + } + + onDestroy() { + // Ability is destroying, release resources for this ability + console.log("[ttt] [datashareproxyTest] <> MainAbility onDestroy") + } + + onWindowStageCreate(windowStage) { + // Main window is created, set main page for this ability + console.log("[ttt] [datashareproxyTest] <> MainAbility onWindowStageCreate") + globalThis.abilityContext = this.context; + console.log("[ttt] [datashareproxyTest] <> MainAbility this.context.databaseDir:" + this.context.databaseDir); + globalThis.connectDataShareExtAbility = (async () => { + console.log("[ttt] [datashareproxyTest] <> connectDataShareExtAbility begin"); + // @ts-ignore + dsProxyHelper = await dataShare.createDataShareHelper(this.context, cardUri, {isProxy : true}); + }) + + globalThis.disconnectDataShareExtAbility = (async () => { + console.log("[ttt] [datashareproxyTest] <> disconnectDataShareExtAbility begin"); + dsProxyHelper = null; + console.log("[ttt] [datashareproxyTest] <> disconnectDataShareExtAbility end"); + }) + + globalThis.insert = (async () => { + console.log("[ttt] [datashareproxyTest] <> insert begin"); + if (dsProxyHelper == null) { + console.log("[ttt] [datashareproxyTest] <> insert end, DSHelper is null"); + return; + } + + let i = 0; + let ret; + for (i = 0; i < 2; i++) { + let vb = { + "name0": "name0" + i, + "name1": "name0", + "name2": "name0", + "name3": "name0", + "name4": "name0", + "name5": "name0", + "name6": "name0", + "name7": "name0", + "name8": "name0", + "name9": "name0", + "time": 50 + }; + ret = await dsProxyHelper.insert(cardUri, vb); + } + return ret; + }) + + windowStage.setUIContent(this.context, "pages/index", null) + } + + onWindowStageDestroy() { + // Main window is destroyed, release UI related resources + console.log("[ttt] [datashareproxyTest] <> MainAbility onWindowStageDestroy") + } + + onForeground() { + // Ability has brought to foreground + console.log("[ttt] [datashareproxyTest] <> MainAbility onForeground") + } + + onBackground() { + // Ability has back to background + console.log("[ttt] [datashareproxyTest] <> MainAbility onBackground") + } +}; \ No newline at end of file diff --git a/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/entry/src/main/ets/pages/index.ets b/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/entry/src/main/ets/pages/index.ets new file mode 100644 index 0000000000000000000000000000000000000000..b76fce0dcf8e81d0c0b652072674a211aea61055 --- /dev/null +++ b/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/entry/src/main/ets/pages/index.ets @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import dataShare from '@ohos.data.dataShare' +import dataSharePredicates from '@ohos.data.dataSharePredicates' + +@Entry +@Component +struct Index { + @State message: string = "datashareproxyTest Main thread message filed" + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Text('datashareproxyTest Ability Test') + .fontSize(25) + .fontWeight(FontWeight.Bold) + + Text(`${this.message}`) + .fontSize(35) + .height('20%') + .width('100%') + .textAlign(TextAlign.Center) + + Row() { + Button() { + Text('Connect') + .fontSize(20) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top: 25 + }) + .width('40%') + .height('8%') + .backgroundColor('#0ddffb') + .onClick(async () => { + console.info('[ttt] [datashareproxyTest] <> Connect onclick enter') + this.message = 'Connect onclick' + await globalThis.connectDataShareExtAbility() + console.info('[ttt] [datashareproxyTest] <> Connect onclick leave') + }) + + Button() { + Text('Disconnect') + .fontSize(20) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top: 25 + }) + .width('40%') + .height('8%') + .backgroundColor('#0ddffb') + .onClick(async () => { + console.info('[ttt] [datashareproxyTest] <> Disconnect onclick enter') + this.message = 'Disconnect onclick' + await globalThis.disconnectDataShareExtAbility() + console.info('[ttt] [datashareproxyTest] <> Disconnect onclick leave') + }) + } + + Row() { + Button() { + Text('Insert') + .fontSize(20) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top: 25 + }) + .width('40%') + .height('8%') + .backgroundColor('#0ddffb') + .onClick(async () => { + console.info('[ttt] [datashareproxyTest] <> Insert onclick enter') + this.message = 'Insert onclick' + let ret = await globalThis.insert() + this.message += "\n\n Test Result: " + ret; + console.info('[ttt] [datashareproxyTest] <> Insert onclick leave') + }) + } + } + .width('100%') + .height('100%') + } +} \ No newline at end of file diff --git a/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/entry/src/main/module.json b/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/entry/src/main/module.json new file mode 100644 index 0000000000000000000000000000000000000000..06919a470c69656f9c3f99256c6aa2e569e4a62e --- /dev/null +++ b/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/entry/src/main/module.json @@ -0,0 +1,55 @@ +{ + "module": { + "name": "entry", + "type": "entry", + "srcEntrance": "./ets/Application/MyAbilityStage.ts", + "description": "$string:entry_desc", + "mainElement": "MainAbility", + "deviceTypes": [ + "default", + "tablet" + ], + "deliveryWithInstall": true, + "installationFree": false, + "pages": "$profile:main_pages", + "uiSyntax": "ets", + "abilities": [ + { + "name": "MainAbility", + "srcEntrance": "./ets/MainAbility/MainAbility.ts", + "description": "$string:MainAbility_desc", + "icon": "$media:icon", + "label": "$string:MainAbility_label", + "startWindowIcon": "$media:icon", + "startWindowBackground": "$color:white", + "visible": true, + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ] + } + ], + "requestPermissions": [ + { + "name": "ohos.permission.GET_BUNDLE_INFO" + } + ], + "proxyDatas":[ + { + "uri": "datashareproxy://com.acts.ohos.data.datasharetest/test", + "requiredReadPermission":"ohos.permission.GET_BUNDLE_INFO", + "requiredWritePermission":"ohos.permission.GET_BUNDLE_INFO", + "metadata": { + "name": "dataProperties", + "resource": "$profile:test" + } + } + ] + } +} \ No newline at end of file diff --git a/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/entry/src/main/resources/base/element/color.json b/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/entry/src/main/resources/base/element/color.json new file mode 100644 index 0000000000000000000000000000000000000000..1bbc9aa9617e97c45440e1d3d66afc1154837012 --- /dev/null +++ b/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/entry/src/main/resources/base/element/color.json @@ -0,0 +1,8 @@ +{ + "color": [ + { + "name": "white", + "value": "#FFFFFF" + } + ] +} \ No newline at end of file diff --git a/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/entry/src/main/resources/base/element/string.json b/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/entry/src/main/resources/base/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..222eb589c8710beebac1dc5937b21715d620a245 --- /dev/null +++ b/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/entry/src/main/resources/base/element/string.json @@ -0,0 +1,28 @@ +{ + "string": [ + { + "name": "entry_desc", + "value": "description" + }, + { + "name": "MainAbility_desc", + "value": "description" + }, + { + "name": "MainAbility_label", + "value": "DataShareTest" + }, + { + "name": "description_application", + "value": "DataShareTest" + }, + { + "name": "app_name", + "value": "DataShareTest" + }, + { + "name": "description_datashareextability", + "value": "description_datashareextability" + } + ] +} \ No newline at end of file diff --git a/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/entry/src/main/resources/base/media/icon.png b/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/entry/src/main/resources/base/media/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..ce307a8827bd75456441ceb57d530e4c8d45d36c Binary files /dev/null and b/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/entry/src/main/resources/base/media/icon.png differ diff --git a/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/entry/src/main/resources/base/profile/main_pages.json b/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/entry/src/main/resources/base/profile/main_pages.json new file mode 100644 index 0000000000000000000000000000000000000000..feec276e105eeb8d621c20aaf838f318b0a94150 --- /dev/null +++ b/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/entry/src/main/resources/base/profile/main_pages.json @@ -0,0 +1,5 @@ +{ + "src": [ + "pages/index" + ] +} diff --git a/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/entry/src/main/resources/base/profile/test.json b/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/entry/src/main/resources/base/profile/test.json new file mode 100644 index 0000000000000000000000000000000000000000..0bafec750ac53e1ea59c7cdeef341cd3df07a4c9 --- /dev/null +++ b/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/entry/src/main/resources/base/profile/test.json @@ -0,0 +1,4 @@ +{ + "path": "DB00/TBL00", + "type": "rdb" +} \ No newline at end of file diff --git a/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/signature/openharmony_sx.p7b b/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/signature/openharmony_sx.p7b new file mode 100644 index 0000000000000000000000000000000000000000..4512fc0e7c36f20aa275736dce5631c304a80dc0 Binary files /dev/null and b/data_share/test/native/resource/datashareproxy_bundle/proxydatas_with_permission/signature/openharmony_sx.p7b differ diff --git a/data_share/test/native/resource/errorcode_ext_bundle/AppScope/app.json b/data_share/test/native/resource/errorcode_ext_bundle/AppScope/app.json index 40ca80306d451e9a07092bd9f35abac117ba3675..4489a6fdf14d0dd2977cbb506b49158c9312910f 100644 --- a/data_share/test/native/resource/errorcode_ext_bundle/AppScope/app.json +++ b/data_share/test/native/resource/errorcode_ext_bundle/AppScope/app.json @@ -1,13 +1,13 @@ -{ - "app": { - "bundleName": "com.acts.errorcodetest", - "vendor": "example", - "versionCode": 1000000, - "versionName": "1.0.0", - "icon": "$media:app_icon", - "label": "$string:app_name", - "distributedNotificationEnabled": true, - "minAPIVersion": 9, - "targetAPIVersion": 9 - } -} +{ + "app": { + "bundleName": "com.acts.errorcodetest", + "vendor": "example", + "versionCode": 1000000, + "versionName": "1.0.0", + "icon": "$media:app_icon", + "label": "$string:app_name", + "distributedNotificationEnabled": true, + "minAPIVersion": 9, + "targetAPIVersion": 9 + } +} diff --git a/data_share/test/native/resource/errorcode_ext_bundle/AppScope/resources/base/element/string.json b/data_share/test/native/resource/errorcode_ext_bundle/AppScope/resources/base/element/string.json index 740e505afa0f81910681f96281493a3cf118388e..616c648fb1daa54ca2376c77ea5ac703fa0b205f 100644 --- a/data_share/test/native/resource/errorcode_ext_bundle/AppScope/resources/base/element/string.json +++ b/data_share/test/native/resource/errorcode_ext_bundle/AppScope/resources/base/element/string.json @@ -1,8 +1,8 @@ -{ - "string": [ - { - "name": "app_name", - "value": "datasharetest" - } - ] -} +{ + "string": [ + { + "name": "app_name", + "value": "datasharetest" + } + ] +} diff --git a/data_share/test/native/resource/errorcode_ext_bundle/entry/src/main/ets/DataShareExtAbility/DataShareExtAbility.ts b/data_share/test/native/resource/errorcode_ext_bundle/entry/src/main/ets/DataShareExtAbility/DataShareExtAbility.ts index 7017c833ed0577f5585261a7741a4df404c178ca..c2ea2574fa0aacf23cbd1e1a987d2dd873f169b2 100644 --- a/data_share/test/native/resource/errorcode_ext_bundle/entry/src/main/ets/DataShareExtAbility/DataShareExtAbility.ts +++ b/data_share/test/native/resource/errorcode_ext_bundle/entry/src/main/ets/DataShareExtAbility/DataShareExtAbility.ts @@ -1,189 +1,189 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import Extension from '@ohos.application.DataShareExtensionAbility' -import rdb from '@ohos.data.relationalStore'; -import rpc from '@ohos.rpc'; - -let DB_NAME = "DB00.db"; -let TBL_NAME = "TBL00"; -let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " -+ TBL_NAME -+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)"; - -let rdbStore; - -export default class -extends Extension { - async onCreate(want, callback) { - console.log('[ttt] [DataShareTest] <> DataShareExtAbility onCreate, want:' + want.abilityName); - console.log("[ttt] [DataShareTest] DataShareExtAbility onCreate this.context.databaseDir:" + this.context.databaseDir); - // @ts-ignore - rdbStore = await rdb.getRdbStore(this.context, { name: DB_NAME, securityLevel: rdb.SecurityLevel.S1 }); - console.log('[ttt] [DataShareTest] <> DataShareExtAbility getRdbStore done'); - await rdbStore.executeSql(DDL_TBL_CREATE, []); - console.log('[ttt] [DataShareTest] <> DataShareExtAbility executeSql done'); - let err = {"code":0}; - callback(err); - console.log('[ttt] [DataShareTest] <> DataShareExtAbility onCreate end'); - } - - async getFileTypes(uri: string, mimeTypeFilter: string, callback) { - console.info('[ttt] [DataShareTest] <> [getFileTypes] enter'); - let ret = new Array("type01", "type00", "type03"); - console.info('[ttt] [DataShareTest] <> [getFileTypes] leave, ret:' + ret); - let err = {"code":0}; - await callback(err,ret); - return ret; - } - - async openFile(uri: string, mode: string, callback) { - console.info('[ttt] [DataShareTest] <> [openFile] enter'); - let ret = 12345; - let err = {"code":0}; - await callback(err,ret); - console.info('[ttt] [DataShareTest] <> [openFile] leave, ret:' + ret); - } - - async insert(uri, value, callback) { - console.info('[ttt] [DataShareTest] <> [insert] enter'); - if (value == null) { - console.info('[ttt] [DataShareTest] <> [insert] invalid valueBuckets'); - return; - } - - console.info('[ttt] [DataShareTest] <> [insert] getCallingTokenId:' + rpc.IPCSkeleton.getCallingTokenId()); - console.info('[ttt] [DataShareTest] <> [insert] value = ' + value); - console.info('[ttt] [DataShareTest] <> [insert] value = ' + JSON.stringify(value)); - await rdbStore.insert(TBL_NAME, value, function (err, ret) { - console.info('[ttt] [DataShareTest] <> [insert] callback ret:' + ret); - - if (callback != undefined) { - callback(err, ret); - } - }); - console.info('[ttt] [DataShareTest] <> [insert] leave'); - } - - async update(uri, predicates, value, callback) { - console.info('[ttt] [DataShareTest] <> [update] enter'); - if (predicates == null || predicates == undefined) { - console.info('[ttt] [DataShareTest] <> [update] invalid predicates'); - return; - } - console.info('[ttt] [DataShareTest] <> [update] values = ' + value); - console.info('[ttt] [DataShareTest] <> [update] values = ' + JSON.stringify(value)); - console.info('[ttt] [DataShareTest] <> [update] predicates = ' + predicates); - console.info('[ttt] [DataShareTest] <> [update] predicates = ' + JSON.stringify(predicates)); - try { - await rdbStore.update(TBL_NAME,value, predicates, function (err, ret) { - console.info('[ttt] [DataShareTest] <> [update] callback ret:' + ret); - console.info('[ttt] [DataShareTest] <> [update] callback err:' + err); - if (callback != undefined) { - callback(err, ret); - } - }); - } catch (err) { - console.error('[ttt] [DataShareTest] <> [update] error' + err); - } - console.info('[ttt] [DataShareTest] <> [update] leave'); - } - - async delete(uri, predicates, callback) { - console.info('[ttt] [DataShareTest] <> [delete] enter'); - if (predicates == null || predicates == undefined) { - console.info('[ttt] [DataShareTest] <> [delete] invalid predicates'); - return; - } - console.info('[ttt] [DataShareTest] <> [delete] predicates = ' + predicates); - console.info('[ttt] [DataShareTest] <> [delete] predicates = ' + JSON.stringify(predicates)); - try { - await rdbStore.delete(TBL_NAME,predicates, function (err, ret) { - console.info('[ttt] [DataShareTest] <> [delete] ret:' + ret); - if (callback != undefined) { - callback(err, ret); - } - }); - } catch (err) { - console.error('[ttt] [DataShareTest] <> [delete] error' + err); - } - console.info('[ttt] [DataShareTest] <> [delete] leave'); - } - - async query(uri, predicates, columns, callback) { - if (predicates == null || predicates == undefined) { - console.info('[ttt] [DataShareTest] <> [query] invalid predicates'); - } - try { - console.info('[ttt] [DataShareTest] <> [query] for errorcode test, sissing parameter: TBL_NAME '); - await rdbStore.query(columns, function (err, resultSet) { - console.info('[ttt] [DataShareTest] <> [query] ret: ' + resultSet); - if (resultSet != undefined) { - console.info('[ttt] [DataShareTest] <> [query] resultSet.rowCount: ' + resultSet.rowCount); - } - if (callback != undefined) { - callback(err, resultSet); - } - }); - } catch (err) { - console.error(`[ttt] [DataShareTest] <> [query] error: code: ${err.code}, message: ${err.message} `); - callback(err, undefined); - } - console.info('[ttt] [DataShareTest] <> [query] leave'); - } - - async getType(uri: string,callback) { - console.info('[ttt] [DataShareTest] <> [getType] enter'); - let ret = "image"; - console.info('[ttt] [DataShareTest] <> [getType] leave, ret:' + ret); - let err = {"code":0}; - await callback(err,ret); - return ret; - } - - async batchInsert(uri: string, valueBuckets, callback) { - console.info('[ttt] [DataShareTest] <> [batchInsert] enter'); - if (valueBuckets == null || valueBuckets.length == undefined) { - console.info('[ttt] [DataShareTest] <> [batchInsert] invalid valueBuckets'); - return; - } - console.info('[ttt] [DataShareTest] <> [batchInsert] valueBuckets.length:' + valueBuckets.length); - let resultNum = valueBuckets.length - await rdbStore.batchinsert(TBL_NAME, valueBuckets, function (err, ret) { - console.info('[ttt] [DataShareTest] <> [batchInsert] callback ret:' + ret); - if (callback != undefined) { - callback(err, ret); - } - }); - - console.info('[ttt] [DataShareTest] <> [batchInsert] leave'); - } - - async normalizeUri(uri: string, callback) { - console.info('[ttt] [DataShareTest] <> [normalizeUri] enter'); - let ret = "normalize+" + uri; - let err = {"code":0}; - await callback(err, ret); - console.info('[ttt] [DataShareTest] <> [normalizeUri] leave, ret:' + ret); - } - - async denormalizeUri(uri: string, callback) { - console.info('[ttt] [DataShareTest] <> [denormalizeUri] enter'); - let ret = "denormalize+" + uri; - let err = {"code":0}; - await callback(err, ret); - console.info('[ttt] [DataShareTest] <> [denormalizeUri] leave, ret:' + ret); - } +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Extension from '@ohos.application.DataShareExtensionAbility' +import rdb from '@ohos.data.relationalStore'; +import rpc from '@ohos.rpc'; + +let DB_NAME = "DB00.db"; +let TBL_NAME = "TBL00"; +let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " ++ TBL_NAME ++ " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)"; + +let rdbStore; + +export default class +extends Extension { + async onCreate(want, callback) { + console.log('[ttt] [DataShareTest] <> DataShareExtAbility onCreate, want:' + want.abilityName); + console.log("[ttt] [DataShareTest] DataShareExtAbility onCreate this.context.databaseDir:" + this.context.databaseDir); + // @ts-ignore + rdbStore = await rdb.getRdbStore(this.context, { name: DB_NAME, securityLevel: rdb.SecurityLevel.S1 }); + console.log('[ttt] [DataShareTest] <> DataShareExtAbility getRdbStore done'); + await rdbStore.executeSql(DDL_TBL_CREATE, []); + console.log('[ttt] [DataShareTest] <> DataShareExtAbility executeSql done'); + let err = {"code":0}; + callback(err); + console.log('[ttt] [DataShareTest] <> DataShareExtAbility onCreate end'); + } + + async getFileTypes(uri: string, mimeTypeFilter: string, callback) { + console.info('[ttt] [DataShareTest] <> [getFileTypes] enter'); + let ret = new Array("type01", "type00", "type03"); + console.info('[ttt] [DataShareTest] <> [getFileTypes] leave, ret:' + ret); + let err = {"code":0}; + await callback(err,ret); + return ret; + } + + async openFile(uri: string, mode: string, callback) { + console.info('[ttt] [DataShareTest] <> [openFile] enter'); + let ret = 12345; + let err = {"code":0}; + await callback(err,ret); + console.info('[ttt] [DataShareTest] <> [openFile] leave, ret:' + ret); + } + + async insert(uri, value, callback) { + console.info('[ttt] [DataShareTest] <> [insert] enter'); + if (value == null) { + console.info('[ttt] [DataShareTest] <> [insert] invalid valueBuckets'); + return; + } + + console.info('[ttt] [DataShareTest] <> [insert] getCallingTokenId:' + rpc.IPCSkeleton.getCallingTokenId()); + console.info('[ttt] [DataShareTest] <> [insert] value = ' + value); + console.info('[ttt] [DataShareTest] <> [insert] value = ' + JSON.stringify(value)); + await rdbStore.insert(TBL_NAME, value, function (err, ret) { + console.info('[ttt] [DataShareTest] <> [insert] callback ret:' + ret); + + if (callback != undefined) { + callback(err, ret); + } + }); + console.info('[ttt] [DataShareTest] <> [insert] leave'); + } + + async update(uri, predicates, value, callback) { + console.info('[ttt] [DataShareTest] <> [update] enter'); + if (predicates == null || predicates == undefined) { + console.info('[ttt] [DataShareTest] <> [update] invalid predicates'); + return; + } + console.info('[ttt] [DataShareTest] <> [update] values = ' + value); + console.info('[ttt] [DataShareTest] <> [update] values = ' + JSON.stringify(value)); + console.info('[ttt] [DataShareTest] <> [update] predicates = ' + predicates); + console.info('[ttt] [DataShareTest] <> [update] predicates = ' + JSON.stringify(predicates)); + try { + await rdbStore.update(TBL_NAME,value, predicates, function (err, ret) { + console.info('[ttt] [DataShareTest] <> [update] callback ret:' + ret); + console.info('[ttt] [DataShareTest] <> [update] callback err:' + err); + if (callback != undefined) { + callback(err, ret); + } + }); + } catch (err) { + console.error('[ttt] [DataShareTest] <> [update] error' + err); + } + console.info('[ttt] [DataShareTest] <> [update] leave'); + } + + async delete(uri, predicates, callback) { + console.info('[ttt] [DataShareTest] <> [delete] enter'); + if (predicates == null || predicates == undefined) { + console.info('[ttt] [DataShareTest] <> [delete] invalid predicates'); + return; + } + console.info('[ttt] [DataShareTest] <> [delete] predicates = ' + predicates); + console.info('[ttt] [DataShareTest] <> [delete] predicates = ' + JSON.stringify(predicates)); + try { + await rdbStore.delete(TBL_NAME,predicates, function (err, ret) { + console.info('[ttt] [DataShareTest] <> [delete] ret:' + ret); + if (callback != undefined) { + callback(err, ret); + } + }); + } catch (err) { + console.error('[ttt] [DataShareTest] <> [delete] error' + err); + } + console.info('[ttt] [DataShareTest] <> [delete] leave'); + } + + async query(uri, predicates, columns, callback) { + if (predicates == null || predicates == undefined) { + console.info('[ttt] [DataShareTest] <> [query] invalid predicates'); + } + try { + console.info('[ttt] [DataShareTest] <> [query] for errorcode test, sissing parameter: TBL_NAME '); + await rdbStore.query(columns, function (err, resultSet) { + console.info('[ttt] [DataShareTest] <> [query] ret: ' + resultSet); + if (resultSet != undefined) { + console.info('[ttt] [DataShareTest] <> [query] resultSet.rowCount: ' + resultSet.rowCount); + } + if (callback != undefined) { + callback(err, resultSet); + } + }); + } catch (err) { + console.error(`[ttt] [DataShareTest] <> [query] error: code: ${err.code}, message: ${err.message} `); + callback(err, undefined); + } + console.info('[ttt] [DataShareTest] <> [query] leave'); + } + + async getType(uri: string,callback) { + console.info('[ttt] [DataShareTest] <> [getType] enter'); + let ret = "image"; + console.info('[ttt] [DataShareTest] <> [getType] leave, ret:' + ret); + let err = {"code":0}; + await callback(err,ret); + return ret; + } + + async batchInsert(uri: string, valueBuckets, callback) { + console.info('[ttt] [DataShareTest] <> [batchInsert] enter'); + if (valueBuckets == null || valueBuckets.length == undefined) { + console.info('[ttt] [DataShareTest] <> [batchInsert] invalid valueBuckets'); + return; + } + console.info('[ttt] [DataShareTest] <> [batchInsert] valueBuckets.length:' + valueBuckets.length); + let resultNum = valueBuckets.length + await rdbStore.batchinsert(TBL_NAME, valueBuckets, function (err, ret) { + console.info('[ttt] [DataShareTest] <> [batchInsert] callback ret:' + ret); + if (callback != undefined) { + callback(err, ret); + } + }); + + console.info('[ttt] [DataShareTest] <> [batchInsert] leave'); + } + + async normalizeUri(uri: string, callback) { + console.info('[ttt] [DataShareTest] <> [normalizeUri] enter'); + let ret = "normalize+" + uri; + let err = {"code":0}; + await callback(err, ret); + console.info('[ttt] [DataShareTest] <> [normalizeUri] leave, ret:' + ret); + } + + async denormalizeUri(uri: string, callback) { + console.info('[ttt] [DataShareTest] <> [denormalizeUri] enter'); + let ret = "denormalize+" + uri; + let err = {"code":0}; + await callback(err, ret); + console.info('[ttt] [DataShareTest] <> [denormalizeUri] leave, ret:' + ret); + } }; \ No newline at end of file diff --git a/data_share/test/native/resource/errorcode_ext_bundle/entry/src/main/ets/MainAbility/MainAbility.ts b/data_share/test/native/resource/errorcode_ext_bundle/entry/src/main/ets/MainAbility/MainAbility.ts index 518b9eb982f99c2e01a9b9cef321f7a290c2937a..12d22516289c221a14bb9f4f0ea089990d0ef71f 100644 --- a/data_share/test/native/resource/errorcode_ext_bundle/entry/src/main/ets/MainAbility/MainAbility.ts +++ b/data_share/test/native/resource/errorcode_ext_bundle/entry/src/main/ets/MainAbility/MainAbility.ts @@ -1,55 +1,55 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import Ability from '@ohos.app.ability.UIAbility' -import dataShare from '@ohos.data.dataShare' -import dataSharePredicates from '@ohos.data.dataSharePredicates' - -let dseUri = ("datashare:///com.acts.errorcodetest"); -let uri = ("datashare://com.acts.errorcodetest/entry/DB00/TBL00?Proxy=true"); - -export default class MainAbility extends Ability { - onCreate(want, launchParam) { - console.log("[ttt] [DataShareTest] <> MainAbility onCreate") - globalThis.abilityWant = want; - } - - onDestroy() { - console.log("[ttt] [DataShareTest] <> MainAbility onDestroy") - } - - onWindowStageCreate(windowStage) { - globalThis.abilityContext = this.context; - console.log("[ttt] [DataShareTest] <> MainAbility this.context.databaseDir:" + this.context.databaseDir); - globalThis.connectDataShareExtAbility = (async () => { - console.log("[ttt] [DataShareTest] <> connectDataShareExtAbility begin"); - globalThis.dsHelper = await dataShare.createDataShareHelper(this.context, dseUri); - console.log("[ttt] [DataShareTest] <> connectDataShareExtAbility end"); - }) - windowStage.setUIContent(this.context, "pages/index", null) - } - - onWindowStageDestroy() { - console.log("[ttt] [DataShareTest] <> MainAbility onWindowStageDestroy") - } - - onForeground() { - console.log("[ttt] [DataShareTest] <> MainAbility onForeground") - } - - onBackground() { - console.log("[ttt] [DataShareTest] <> MainAbility onBackground") - } +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Ability from '@ohos.app.ability.UIAbility' +import dataShare from '@ohos.data.dataShare' +import dataSharePredicates from '@ohos.data.dataSharePredicates' + +let dseUri = ("datashare:///com.acts.errorcodetest"); +let uri = ("datashare://com.acts.errorcodetest/entry/DB00/TBL00?Proxy=true"); + +export default class MainAbility extends Ability { + onCreate(want, launchParam) { + console.log("[ttt] [DataShareTest] <> MainAbility onCreate") + globalThis.abilityWant = want; + } + + onDestroy() { + console.log("[ttt] [DataShareTest] <> MainAbility onDestroy") + } + + onWindowStageCreate(windowStage) { + globalThis.abilityContext = this.context; + console.log("[ttt] [DataShareTest] <> MainAbility this.context.databaseDir:" + this.context.databaseDir); + globalThis.connectDataShareExtAbility = (async () => { + console.log("[ttt] [DataShareTest] <> connectDataShareExtAbility begin"); + globalThis.dsHelper = await dataShare.createDataShareHelper(this.context, dseUri); + console.log("[ttt] [DataShareTest] <> connectDataShareExtAbility end"); + }) + windowStage.setUIContent(this.context, "pages/index", null) + } + + onWindowStageDestroy() { + console.log("[ttt] [DataShareTest] <> MainAbility onWindowStageDestroy") + } + + onForeground() { + console.log("[ttt] [DataShareTest] <> MainAbility onForeground") + } + + onBackground() { + console.log("[ttt] [DataShareTest] <> MainAbility onBackground") + } }; \ No newline at end of file diff --git a/data_share/test/native/resource/errorcode_ext_bundle/entry/src/main/ets/pages/index.ets b/data_share/test/native/resource/errorcode_ext_bundle/entry/src/main/ets/pages/index.ets index 51ac42aded1530b672b27ab4da2b1daaa7c3f010..24c9fb21cc01429847d3b3f45a928b3f852ce165 100644 --- a/data_share/test/native/resource/errorcode_ext_bundle/entry/src/main/ets/pages/index.ets +++ b/data_share/test/native/resource/errorcode_ext_bundle/entry/src/main/ets/pages/index.ets @@ -1,59 +1,59 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import dataShare from '@ohos.data.dataShare' -import dataSharePredicates from '@ohos.data.dataSharePredicates' - -@Entry -@Component -struct Index { - @State message: string = "Main thread message filed errorcode test" - - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Text('DataShare Extension Ability ErrorCode Test') - .fontSize(25) - .fontWeight(FontWeight.Bold) - - Text(`${this.message}`) - .fontSize(25) - .height('20%') - .width('100%') - .textAlign(TextAlign.Center) - - Row() { - Button() { - Text('Connect') - .fontSize(30) - .fontWeight(FontWeight.Bold) - }.type(ButtonType.Capsule) - .margin({ - top: 25 - }) - .width('50%') - .height('10%') - .backgroundColor('#0ddffb') - .onClick(async () => { - console.info('[ttt] [DataShareTest] <> ErrorCode Connect onclick enter') - this.message = 'Connect onclick' - await globalThis.connectDataShareExtAbility() - console.info('[ttt] [DataShareTest] <> ErrorCode Connect onclick leave') - }) - } - } - .width('100%') - .height('100%') - } +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import dataShare from '@ohos.data.dataShare' +import dataSharePredicates from '@ohos.data.dataSharePredicates' + +@Entry +@Component +struct Index { + @State message: string = "Main thread message filed errorcode test" + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Text('DataShare Extension Ability ErrorCode Test') + .fontSize(25) + .fontWeight(FontWeight.Bold) + + Text(`${this.message}`) + .fontSize(25) + .height('20%') + .width('100%') + .textAlign(TextAlign.Center) + + Row() { + Button() { + Text('Connect') + .fontSize(30) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top: 25 + }) + .width('50%') + .height('10%') + .backgroundColor('#0ddffb') + .onClick(async () => { + console.info('[ttt] [DataShareTest] <> ErrorCode Connect onclick enter') + this.message = 'Connect onclick' + await globalThis.connectDataShareExtAbility() + console.info('[ttt] [DataShareTest] <> ErrorCode Connect onclick leave') + }) + } + } + .width('100%') + .height('100%') + } } \ No newline at end of file diff --git a/data_share/test/native/resource/errorcode_ext_bundle/entry/src/main/module.json b/data_share/test/native/resource/errorcode_ext_bundle/entry/src/main/module.json index c7983cbb2ad156a869665f10ba92ab0bd202f3b9..3f44ca1fd4637b0a422ea6439c227e1f86019a5d 100644 --- a/data_share/test/native/resource/errorcode_ext_bundle/entry/src/main/module.json +++ b/data_share/test/native/resource/errorcode_ext_bundle/entry/src/main/module.json @@ -1,50 +1,50 @@ -{ - "module": { - "name": "entry", - "type": "entry", - "srcEntrance": "./ets/Application/MyAbilityStage.ts", - "description": "$string:entry_desc", - "mainElement": "MainAbility", - "deviceTypes": [ - "default", - "tablet" - ], - "deliveryWithInstall": true, - "installationFree": false, - "pages": "$profile:main_pages", - "uiSyntax": "ets", - "abilities": [ - { - "name": "MainAbility", - "srcEntrance": "./ets/MainAbility/MainAbility.ts", - "description": "$string:MainAbility_desc", - "icon": "$media:icon", - "label": "$string:MainAbility_label", - "startWindowIcon": "$media:icon", - "startWindowBackground": "$color:white", - "visible": true, - "skills": [ - { - "entities": [ - "entity.system.home" - ], - "actions": [ - "action.system.home" - ] - } - ] - } - ], - "extensionAbilities": [ - { - "srcEntrance": "./ets/DataShareExtAbility/DataShareExtAbility.ts", - "name": "DataShareExtAbility", - "icon": "$media:icon", - "description": "$string:description_datashareextability", - "type": "dataShare", - "uri": "datashare://com.acts.errorcodetest", - "visible": true - } - ] - } +{ + "module": { + "name": "entry", + "type": "entry", + "srcEntrance": "./ets/Application/MyAbilityStage.ts", + "description": "$string:entry_desc", + "mainElement": "MainAbility", + "deviceTypes": [ + "default", + "tablet" + ], + "deliveryWithInstall": true, + "installationFree": false, + "pages": "$profile:main_pages", + "uiSyntax": "ets", + "abilities": [ + { + "name": "MainAbility", + "srcEntrance": "./ets/MainAbility/MainAbility.ts", + "description": "$string:MainAbility_desc", + "icon": "$media:icon", + "label": "$string:MainAbility_label", + "startWindowIcon": "$media:icon", + "startWindowBackground": "$color:white", + "visible": true, + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ] + } + ], + "extensionAbilities": [ + { + "srcEntrance": "./ets/DataShareExtAbility/DataShareExtAbility.ts", + "name": "DataShareExtAbility", + "icon": "$media:icon", + "description": "$string:description_datashareextability", + "type": "dataShare", + "uri": "datashare://com.acts.errorcodetest", + "visible": true + } + ] + } } \ No newline at end of file diff --git a/data_share/test/native/resource/errorcode_ext_bundle/entry/src/main/resources/base/element/color.json b/data_share/test/native/resource/errorcode_ext_bundle/entry/src/main/resources/base/element/color.json index 1bbc9aa9617e97c45440e1d3d66afc1154837012..62a137a61b90c14f109ed8c81d9d551ea0a5888a 100644 --- a/data_share/test/native/resource/errorcode_ext_bundle/entry/src/main/resources/base/element/color.json +++ b/data_share/test/native/resource/errorcode_ext_bundle/entry/src/main/resources/base/element/color.json @@ -1,8 +1,8 @@ -{ - "color": [ - { - "name": "white", - "value": "#FFFFFF" - } - ] +{ + "color": [ + { + "name": "white", + "value": "#FFFFFF" + } + ] } \ No newline at end of file diff --git a/data_share/test/native/resource/errorcode_ext_bundle/entry/src/main/resources/base/element/string.json b/data_share/test/native/resource/errorcode_ext_bundle/entry/src/main/resources/base/element/string.json index 222eb589c8710beebac1dc5937b21715d620a245..d0f0ca1516fe6cb55080ec9f2d66851dbc446d0d 100644 --- a/data_share/test/native/resource/errorcode_ext_bundle/entry/src/main/resources/base/element/string.json +++ b/data_share/test/native/resource/errorcode_ext_bundle/entry/src/main/resources/base/element/string.json @@ -1,28 +1,28 @@ -{ - "string": [ - { - "name": "entry_desc", - "value": "description" - }, - { - "name": "MainAbility_desc", - "value": "description" - }, - { - "name": "MainAbility_label", - "value": "DataShareTest" - }, - { - "name": "description_application", - "value": "DataShareTest" - }, - { - "name": "app_name", - "value": "DataShareTest" - }, - { - "name": "description_datashareextability", - "value": "description_datashareextability" - } - ] +{ + "string": [ + { + "name": "entry_desc", + "value": "description" + }, + { + "name": "MainAbility_desc", + "value": "description" + }, + { + "name": "MainAbility_label", + "value": "DataShareTest" + }, + { + "name": "description_application", + "value": "DataShareTest" + }, + { + "name": "app_name", + "value": "DataShareTest" + }, + { + "name": "description_datashareextability", + "value": "description_datashareextability" + } + ] } \ No newline at end of file diff --git a/data_share/test/native/resource/ohos_test/ohos_test.xml b/data_share/test/native/resource/ohos_test/ohos_test.xml index ebd0874462a9ee44f51190d3a3bded4c9f593abb..95dc9f0d92c60f4846db6445a5c136dfead6b45f 100644 --- a/data_share/test/native/resource/ohos_test/ohos_test.xml +++ b/data_share/test/native/resource/ohos_test/ohos_test.xml @@ -14,6 +14,16 @@ limitations under the License. --> + + + + + +