From 7ef68df22210ac2d0108e05045e7d1050b1192fa Mon Sep 17 00:00:00 2001 From: Jihoon Chung Date: Thu, 3 Jan 2013 10:41:01 +0900 Subject: [PATCH] [Release] wrt-commons_0.2.89 Change-Id: I6e22548e13799c36c1cf830eec46ff34c3cb1d35 --- .gitignore | 1 + 3rdparty/CMakeLists.txt | 2 +- CMakeLists.txt | 9 +- build/CMakeLists.txt | 1 + build/core/CMakeLists.txt | 3 +- build/custom_handler_dao/CMakeLists.txt | 21 + .../wrt-commons-custom-handler-dao-ro.pc.in | 12 + .../wrt-commons-custom-handler-dao-rw.pc.in | 12 + build/db/CMakeLists.txt | 5 +- build/dbus/CMakeLists.txt | 5 +- build/encryption/CMakeLists.txt | 5 +- build/encryption/libs/libcal.a | Bin 0 -> 4734 bytes build/encryption/libs/libcal.arm.a | Bin 0 -> 5566 bytes build/encryption/libs/libcal.i586.a | Bin 0 -> 5496 bytes build/event/CMakeLists.txt | 5 +- build/log/CMakeLists.txt | 3 +- build/popup/CMakeLists.txt | 5 +- build/rpc/CMakeLists.txt | 4 +- build/socket/CMakeLists.txt | 3 +- build/test/CMakeLists.txt | 3 +- build/utils/CMakeLists.txt | 2 +- debian/changelog | 165 ++ debian/wrt-commons.postinst | 8 +- dir-struct.py | 14 + etc/wrt_commons_create_clean_db.sh | 2 +- etc/wrt_commons_reset_db.sh | 2 +- examples/fake_rpc/fake_rpc.cpp | 34 +- examples/metronome/metronome_client.cpp | 8 +- examples/rpc/rpc.cpp | 16 +- modules/CMakeLists.txt | 1 + modules/auto_save_dao/CMakeLists.txt | 11 +- modules/core/config.cmake | 1 - modules/core/include/dpl/named_input_pipe.h | 35 +- modules/core/include/dpl/thread.h | 8 +- modules/core/src/file_input.cpp | 3 +- modules/core/src/main.cpp | 55 - modules/core/src/named_input_pipe.cpp | 122 -- modules/core/src/string.cpp | 2 - modules/core/src/thread.cpp | 8 +- modules/core/src/zip_input.cpp | 8 +- modules/custom_handler_dao/CMakeLists.txt | 83 + .../dao/CustomHandlerDatabase.cpp | 47 + .../dao/custom_handler_dao.cpp | 300 +++ .../dao/custom_handler_dao_read_only.cpp | 264 +++ .../CustomHandlerDatabase.h | 66 + .../custom-handler-dao-ro/common_dao_types.h | 65 + .../custom_handler_dao_read_only.h | 98 + .../custom_handler_dao.h | 75 + .../custom_handler_dao/orm/custom_handler_db | 34 + .../orm/custom_handler_db_definitions | 6 + .../orm/custom_handler_db_sql_generator.h | 27 + modules/custom_handler_dao/orm/gen_db_md5.sh | 19 + .../orm/orm_generator_custom_handler.h | 24 + modules/custom_handler_dao/orm/version_db | 5 + modules/db/include/dpl/db/orm.h | 81 +- modules/db/include/dpl/db/sql_connection.h | 4 +- modules/db/src/sql_connection.cpp | 6 +- .../dpl/encryption/resource_decryption.h | 5 +- .../dpl/encryption/resource_encryption.h | 3 +- .../encryption/src/resource_decryption.cpp | 41 +- .../encryption/src/resource_encryption.cpp | 42 +- .../event/include/dpl/event/event_support.h | 6 +- .../dpl/event/inter_context_delegate.h | 35 +- .../dpl/localization/w3c_file_localization.h | 20 + .../localization/src/LanguageTagsProvider.cpp | 20 +- .../src/w3c_file_localization.cpp | 89 +- modules/popup/include/dpl/popup/evas_object.h | 6 +- modules/popup/include/dpl/popup/popup.h | 9 +- .../include/dpl/popup/popup_controller.h | 11 +- .../popup/include/dpl/popup/popup_manager.h | 2 +- .../popup/include/dpl/popup/popup_renderer.h | 18 +- modules/popup/src/popup_controller.cpp | 2 +- modules/popup/src/popup_manager.cpp | 4 +- modules/popup/src/popup_renderer.cpp | 52 +- .../include/dpl/rpc/generic_rpc_connection.h | 4 +- modules/security_origin_dao/CMakeLists.txt | 7 +- .../dao/security_origin_dao.cpp | 101 +- .../security-origin-dao/security_origin_dao.h | 9 +- .../security_origin_dao_types.h | 19 +- modules/socket/src/unix_socket.cpp | 6 +- .../include/dpl/test/test_results_collector.h | 4 +- modules/test/src/test_results_collector.cpp | 48 +- modules/test/src/test_runner.cpp | 4 +- modules/utils/src/wrt_global_settings.cpp | 2 +- modules/widget_dao/CMakeLists.txt | 13 +- modules/widget_dao/dao/bind_to_dao.h | 73 - modules/widget_dao/dao/config_parser_data.cpp | 51 + modules/widget_dao/dao/plugin_dao.cpp | 5 +- modules/widget_dao/dao/property_dao.cpp | 42 +- .../widget_dao/dao/property_dao_read_only.cpp | 89 +- modules/widget_dao/dao/widget_dao.cpp | 180 +- .../widget_dao/dao/widget_dao_read_only.cpp | 273 +-- .../include/dpl/wrt-dao-ro/common_dao_types.h | 18 +- .../dpl/wrt-dao-ro/config_parser_data.h | 55 + .../include/dpl/wrt-dao-ro/feature_model.h | 6 +- .../include/dpl/wrt-dao-ro/global_config.h | 61 +- .../dpl/wrt-dao-ro/plugin_dao_read_only.h | 4 +- .../dpl/wrt-dao-ro/property_dao_read_only.h | 31 +- .../include/dpl/wrt-dao-ro/vconf_config.h | 98 + .../include/dpl/wrt-dao-ro/widget_config.h | 2 +- .../dpl/wrt-dao-ro/widget_dao_read_only.h | 51 +- .../include/dpl/wrt-dao-rw/property_dao.h | 22 + .../include/dpl/wrt-dao-rw/widget_dao.h | 15 + modules/widget_dao/orm/wrt_db | 31 +- packaging/wrt-commons.spec | 35 +- tests/CMakeLists.txt | 18 + tests/CMakeUtils.txt | 178 ++ tests/common/include/loop_control.h | 42 + tests/common/src/loop_control.cpp | 75 + tests/dao/CMakeLists.txt | 37 + tests/dao/README | 11 + tests/dao/TestCases_CustomHandlerDAO.cpp | 120 ++ tests/dao/TestCases_FeatureDAO.cpp | 244 +++ tests/dao/TestCases_GlobalDAO.cpp | 111 ++ tests/dao/TestCases_PluginDAO.cpp | 441 +++++ tests/dao/TestCases_PropertyDAO.cpp | 163 ++ tests/dao/TestCases_WidgetDAO.cpp | 980 ++++++++++ tests/dao/tests_dao.cpp | 52 + tests/dao/wrt_dao_tests_prepare_db.sh | 129 ++ tests/dpl/CMakeLists.txt | 28 + tests/dpl/README | 13 + tests/dpl/core/.swp | Bin 0 -> 12288 bytes tests/dpl/core/CMakeLists.txt | 61 + tests/dpl/core/DESCRIPTION | 2 + tests/dpl/core/data/sample.zip | Bin 0 -> 174 bytes tests/dpl/core/main.cpp | 28 + tests/dpl/core/test_address.cpp | 50 + tests/dpl/core/test_binary_queue.cpp | 357 ++++ tests/dpl/core/test_fast_delegate.cpp | 248 +++ tests/dpl/core/test_foreach.cpp | 118 ++ .../dpl/core/test_log_unhandled_exception.cpp | 74 + tests/dpl/core/test_once.cpp | 103 + tests/dpl/core/test_scoped_array.cpp | 62 + tests/dpl/core/test_scoped_close.cpp | 27 + tests/dpl/core/test_scoped_fclose.cpp | 70 + tests/dpl/core/test_scoped_free.cpp | 53 + tests/dpl/core/test_scoped_ptr.cpp | 59 + tests/dpl/core/test_semaphore.cpp | 85 + tests/dpl/core/test_serialization.cpp | 259 +++ tests/dpl/core/test_shared_ptr.cpp | 85 + tests/dpl/core/test_string.cpp | 384 ++++ tests/dpl/core/test_thread.cpp | 100 + tests/dpl/core/test_type_list.cpp | 41 + tests/dpl/core/test_zip_input.cpp | 89 + tests/dpl/db/CMakeLists.txt | 49 + tests/dpl/db/main.cpp | 28 + tests/dpl/db/orm/CMakeLists.txt | 11 + tests/dpl/db/orm/dpl_orm_test_db | 88 + tests/dpl/db/orm/dpl_orm_test_db_definitions | 5 + .../db/orm/dpl_orm_test_db_sql_generator.h | 27 + .../orm/dpl_orm_test_db_sql_generator.h.gch | Bin 0 -> 6521 bytes tests/dpl/db/orm/generator_dpl_orm_test.h | 24 + tests/dpl/db/test_orm.cpp | 851 +++++++++ tests/dpl/db/test_sql_connection.cpp | 237 +++ tests/dpl/dbus/CMakeLists.txt | 63 + .../data/org.tizen.DBusTestService.service | 3 + tests/dpl/dbus/dbus_test.cpp | 117 ++ tests/dpl/dbus/dbus_test.h | 90 + tests/dpl/dbus/main.cpp | 35 + tests/dpl/dbus/test_cases.cpp | 190 ++ tests/dpl/dbus/test_service.cpp | 89 + tests/dpl/event/CMakeLists.txt | 42 + tests/dpl/event/main.cpp | 28 + tests/dpl/event/test_controller.cpp | 331 ++++ tests/dpl/event/test_event_support.cpp | 122 ++ tests/dpl/event/test_ic_delegate.cpp | 567 ++++++ tests/dpl/event/test_property.cpp | 111 ++ tests/dpl/localization/CMakeLists.txt | 51 + tests/dpl/localization/files/CMakeLists.txt | 19 + tests/dpl/localization/files/one | 0 tests/dpl/localization/files/two | 0 .../dpl/wrt-dao-ro/common_dao_types.h | 485 +++++ .../dpl/wrt-dao-rw/widget_dao.h | 231 +++ .../localization/mockup_src/widget_dao.cpp | 108 ++ tests/dpl/localization/test_localization.cpp | 28 + tests/dpl/localization/test_suite01.cpp | 112 ++ tests/dpl/unused/test_caller.cpp | 128 ++ tests/dpl/unused/test_crypto_hash.cpp | 90 + tests/dpl/unused/test_message_queue.cpp | 158 ++ tests/dpl/unused/test_shm.cpp | 1658 +++++++++++++++++ tests/dpl/unused/test_sql_connection.cpp | 44 + tests/dpl/unused/test_task.cpp | 93 + tests/dpl/utils/CMakeLists.txt | 33 + tests/dpl/utils/bash_utils.cpp | 38 + tests/dpl/utils/main.cpp | 28 + tests/dpl/utils/widget_version.cpp | 278 +++ tests/dpl/utils/wrt_utility.cpp | 163 ++ wrt-commons.manifest | 1 + 188 files changed, 14545 insertions(+), 838 deletions(-) create mode 100644 build/custom_handler_dao/CMakeLists.txt create mode 100644 build/custom_handler_dao/wrt-commons-custom-handler-dao-ro.pc.in create mode 100644 build/custom_handler_dao/wrt-commons-custom-handler-dao-rw.pc.in create mode 100755 build/encryption/libs/libcal.a create mode 100755 build/encryption/libs/libcal.arm.a create mode 100755 build/encryption/libs/libcal.i586.a delete mode 100644 modules/core/src/named_input_pipe.cpp create mode 100644 modules/custom_handler_dao/CMakeLists.txt create mode 100644 modules/custom_handler_dao/dao/CustomHandlerDatabase.cpp create mode 100644 modules/custom_handler_dao/dao/custom_handler_dao.cpp create mode 100644 modules/custom_handler_dao/dao/custom_handler_dao_read_only.cpp create mode 100644 modules/custom_handler_dao/include/wrt-commons/custom-handler-dao-ro/CustomHandlerDatabase.h create mode 100644 modules/custom_handler_dao/include/wrt-commons/custom-handler-dao-ro/common_dao_types.h create mode 100644 modules/custom_handler_dao/include/wrt-commons/custom-handler-dao-ro/custom_handler_dao_read_only.h create mode 100644 modules/custom_handler_dao/include/wrt-commons/custom-handler-dao-rw/custom_handler_dao.h create mode 100644 modules/custom_handler_dao/orm/custom_handler_db create mode 100644 modules/custom_handler_dao/orm/custom_handler_db_definitions create mode 100644 modules/custom_handler_dao/orm/custom_handler_db_sql_generator.h create mode 100755 modules/custom_handler_dao/orm/gen_db_md5.sh create mode 100644 modules/custom_handler_dao/orm/orm_generator_custom_handler.h create mode 100644 modules/custom_handler_dao/orm/version_db delete mode 100644 modules/widget_dao/dao/bind_to_dao.h mode change 100644 => 100755 modules/widget_dao/dao/config_parser_data.cpp mode change 100644 => 100755 modules/widget_dao/include/dpl/wrt-dao-ro/config_parser_data.h create mode 100644 modules/widget_dao/include/dpl/wrt-dao-ro/vconf_config.h create mode 100644 tests/CMakeLists.txt create mode 100644 tests/CMakeUtils.txt create mode 100644 tests/common/include/loop_control.h create mode 100644 tests/common/src/loop_control.cpp create mode 100644 tests/dao/CMakeLists.txt create mode 100644 tests/dao/README create mode 100644 tests/dao/TestCases_CustomHandlerDAO.cpp create mode 100644 tests/dao/TestCases_FeatureDAO.cpp create mode 100644 tests/dao/TestCases_GlobalDAO.cpp create mode 100644 tests/dao/TestCases_PluginDAO.cpp create mode 100644 tests/dao/TestCases_PropertyDAO.cpp create mode 100644 tests/dao/TestCases_WidgetDAO.cpp create mode 100644 tests/dao/tests_dao.cpp create mode 100755 tests/dao/wrt_dao_tests_prepare_db.sh create mode 100644 tests/dpl/CMakeLists.txt create mode 100644 tests/dpl/README create mode 100644 tests/dpl/core/.swp create mode 100644 tests/dpl/core/CMakeLists.txt create mode 100644 tests/dpl/core/DESCRIPTION create mode 100644 tests/dpl/core/data/sample.zip create mode 100644 tests/dpl/core/main.cpp create mode 100644 tests/dpl/core/test_address.cpp create mode 100644 tests/dpl/core/test_binary_queue.cpp create mode 100644 tests/dpl/core/test_fast_delegate.cpp create mode 100644 tests/dpl/core/test_foreach.cpp create mode 100644 tests/dpl/core/test_log_unhandled_exception.cpp create mode 100644 tests/dpl/core/test_once.cpp create mode 100644 tests/dpl/core/test_scoped_array.cpp create mode 100644 tests/dpl/core/test_scoped_close.cpp create mode 100644 tests/dpl/core/test_scoped_fclose.cpp create mode 100644 tests/dpl/core/test_scoped_free.cpp create mode 100644 tests/dpl/core/test_scoped_ptr.cpp create mode 100644 tests/dpl/core/test_semaphore.cpp create mode 100644 tests/dpl/core/test_serialization.cpp create mode 100644 tests/dpl/core/test_shared_ptr.cpp create mode 100644 tests/dpl/core/test_string.cpp create mode 100644 tests/dpl/core/test_thread.cpp create mode 100644 tests/dpl/core/test_type_list.cpp create mode 100644 tests/dpl/core/test_zip_input.cpp create mode 100644 tests/dpl/db/CMakeLists.txt create mode 100644 tests/dpl/db/main.cpp create mode 100644 tests/dpl/db/orm/CMakeLists.txt create mode 100644 tests/dpl/db/orm/dpl_orm_test_db create mode 100644 tests/dpl/db/orm/dpl_orm_test_db_definitions create mode 100644 tests/dpl/db/orm/dpl_orm_test_db_sql_generator.h create mode 100644 tests/dpl/db/orm/dpl_orm_test_db_sql_generator.h.gch create mode 100644 tests/dpl/db/orm/generator_dpl_orm_test.h create mode 100644 tests/dpl/db/test_orm.cpp create mode 100644 tests/dpl/db/test_sql_connection.cpp create mode 100644 tests/dpl/dbus/CMakeLists.txt create mode 100644 tests/dpl/dbus/data/org.tizen.DBusTestService.service create mode 100644 tests/dpl/dbus/dbus_test.cpp create mode 100644 tests/dpl/dbus/dbus_test.h create mode 100644 tests/dpl/dbus/main.cpp create mode 100644 tests/dpl/dbus/test_cases.cpp create mode 100644 tests/dpl/dbus/test_service.cpp create mode 100644 tests/dpl/event/CMakeLists.txt create mode 100644 tests/dpl/event/main.cpp create mode 100644 tests/dpl/event/test_controller.cpp create mode 100644 tests/dpl/event/test_event_support.cpp create mode 100644 tests/dpl/event/test_ic_delegate.cpp create mode 100644 tests/dpl/event/test_property.cpp create mode 100644 tests/dpl/localization/CMakeLists.txt create mode 100644 tests/dpl/localization/files/CMakeLists.txt create mode 100644 tests/dpl/localization/files/one create mode 100644 tests/dpl/localization/files/two create mode 100644 tests/dpl/localization/mockup_include/dpl/wrt-dao-ro/common_dao_types.h create mode 100644 tests/dpl/localization/mockup_include/dpl/wrt-dao-rw/widget_dao.h create mode 100644 tests/dpl/localization/mockup_src/widget_dao.cpp create mode 100644 tests/dpl/localization/test_localization.cpp create mode 100644 tests/dpl/localization/test_suite01.cpp create mode 100644 tests/dpl/unused/test_caller.cpp create mode 100644 tests/dpl/unused/test_crypto_hash.cpp create mode 100644 tests/dpl/unused/test_message_queue.cpp create mode 100644 tests/dpl/unused/test_shm.cpp create mode 100644 tests/dpl/unused/test_sql_connection.cpp create mode 100644 tests/dpl/unused/test_task.cpp create mode 100644 tests/dpl/utils/CMakeLists.txt create mode 100644 tests/dpl/utils/bash_utils.cpp create mode 100644 tests/dpl/utils/main.cpp create mode 100644 tests/dpl/utils/widget_version.cpp create mode 100644 tests/dpl/utils/wrt_utility.cpp diff --git a/.gitignore b/.gitignore index 9488fa3..fb11196 100755 --- a/.gitignore +++ b/.gitignore @@ -21,4 +21,5 @@ documentation.list modules/auto_save_dao/database_checksum_autosave.h modules/widget_dao/database_checksum.h modules/security_origin_dao/database_checksum_security_origin.h +modules/custom_handler_dao/database_checksum_custom_handler.h diff --git a/3rdparty/CMakeLists.txt b/3rdparty/CMakeLists.txt index 4783a46..e71fc4c 100644 --- a/3rdparty/CMakeLists.txt +++ b/3rdparty/CMakeLists.txt @@ -54,7 +54,7 @@ SET(TARGET_3RDPARTY "lib3rdparty") INCLUDE_DIRECTORIES(${DPL_3RDPARTY_INCLUDE_DIR}) # Add system include files -INCLUDE_DIRECTORIES(${SYS_3RDPARTY_INCLUDE_DIRS}) +INCLUDE_DIRECTORIES(SYSTEM ${SYS_3RDPARTY_INCLUDE_DIRS}) LINK_DIRECTORIES(${SYS_3RDPARTY_LIBRARY_DIRS}) # Build shared library diff --git a/CMakeLists.txt b/CMakeLists.txt index fc51d8e..084e4c2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -45,6 +45,8 @@ ELSE(DPL_LOG AND NOT CMAKE_BUILD_TYPE MATCHES "profiling") MESSAGE(STATUS "Logging disabled for DPL") ENDIF(DPL_LOG AND NOT CMAKE_BUILD_TYPE MATCHES "profiling") +OPTION(WITH_TESTS "Build tests" OFF) + # Compiler flags SET(CMAKE_C_FLAGS_PROFILING "-O2") SET(CMAKE_CXX_FLAGS_PROFILING "-O2 -std=c++0x") @@ -105,6 +107,7 @@ MESSAGE(STATUS "CMAKE_COMPILER_IS_GNUCC: " ${CMAKE_COMPILER_IS_GNUCC}) MESSAGE(STATUS "CMAKE_COMPILER_IS_GNUCXX : " ${CMAKE_COMPILER_IS_GNUCXX}) MESSAGE(STATUS "CMAKE_AR: " ${CMAKE_AR}) MESSAGE(STATUS "CMAKE_RANLIB: " ${CMAKE_RANLIB}) +MESSAGE(STATUS "WITH_TESTS: " ${WITH_TESTS}) MESSAGE(STATUS "========================================") # Build 3rd party libraries first @@ -170,7 +173,6 @@ ADD_DEFINITIONS("-std=c++0x") SET(DPL_3RDPARTY_INCLUDE_DIR ${PROJECT_SOURCE_DIR}/3rdparty) - # Set names of binaries being created SET(TARGET_DPL_EFL "lib${PROJECT_NAME}-efl") SET(TARGET_DPL_DBUS_EFL "lib${PROJECT_NAME}-dbus-efl") @@ -186,6 +188,8 @@ SET(TARGET_WRT_DAO_RO_LIB "dpl-wrt-dao-ro") SET(TARGET_AUTO_SAVE_DAO_LIB "wrt-commons-auto-save-dao") SET(TARGET_AUTO_SAVE_DAO_RW_LIB "wrt-commons-auto-save-dao-rw") SET(TARGET_AUTO_SAVE_DAO_RO_LIB "wrt-commons-auto-save-dao-ro") +SET(TARGET_CUSTOM_HANDLER_DAO_RW_LIB "wrt-commons-custom-handler-dao-rw") +SET(TARGET_CUSTOM_HANDLER_DAO_RO_LIB "wrt-commons-custom-handler-dao-ro") SET(TARGET_SECURITY_ORIGIN_DAO_LIB "wrt-commons-security-origin-dao") SET(TARGET_DPL_UTILS_EFL "lib${PROJECT_NAME}-utils-efl") SET(TARGET_DPL_ENCRYPTION "lib${PROJECT_NAME}-encryption") @@ -200,3 +204,6 @@ ADD_SUBDIRECTORY(modules) ADD_SUBDIRECTORY(build) ADD_SUBDIRECTORY(etc) +IF(WITH_TESTS) + ADD_SUBDIRECTORY(tests) +ENDIF(WITH_TESTS) diff --git a/build/CMakeLists.txt b/build/CMakeLists.txt index 2e40a76..e11b0e9 100644 --- a/build/CMakeLists.txt +++ b/build/CMakeLists.txt @@ -29,6 +29,7 @@ ADD_SUBDIRECTORY(test) ADD_SUBDIRECTORY(widget_dao) ADD_SUBDIRECTORY(auto_save_dao) ADD_SUBDIRECTORY(security_origin_dao) +ADD_SUBDIRECTORY(custom_handler_dao) ADD_SUBDIRECTORY(popup) ADD_SUBDIRECTORY(utils) ADD_SUBDIRECTORY(support) diff --git a/build/core/CMakeLists.txt b/build/core/CMakeLists.txt index a202bdc..080d65c 100644 --- a/build/core/CMakeLists.txt +++ b/build/core/CMakeLists.txt @@ -35,9 +35,10 @@ INCLUDE_DIRECTORIES( ${DPL_LOG_INCLUDE_DIR} ${DPL_CORE_INCLUDE_DIR} ${DPL_3RDPARTY_INCLUDE_DIR} - ${SYS_EFL_INCLUDE_DIRS} ) +INCLUDE_DIRECTORIES(SYSTEM ${SYS_EFL_INCLUDE_DIRS}) + LINK_DIRECTORIES(${SYS_EFL_LIBRARY_DIRS}) # Base EFL based DPL library diff --git a/build/custom_handler_dao/CMakeLists.txt b/build/custom_handler_dao/CMakeLists.txt new file mode 100644 index 0000000..26e701c --- /dev/null +++ b/build/custom_handler_dao/CMakeLists.txt @@ -0,0 +1,21 @@ +# Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# @file CMakeLists.txt +# @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) +# @brief +# + +configure_and_install_pkg(wrt-commons-custom-handler-dao-ro.pc) +configure_and_install_pkg(wrt-commons-custom-handler-dao-rw.pc) diff --git a/build/custom_handler_dao/wrt-commons-custom-handler-dao-ro.pc.in b/build/custom_handler_dao/wrt-commons-custom-handler-dao-ro.pc.in new file mode 100644 index 0000000..7cda187 --- /dev/null +++ b/build/custom_handler_dao/wrt-commons-custom-handler-dao-ro.pc.in @@ -0,0 +1,12 @@ +prefix=/usr +exec_prefix=${prefix} + +libdir=${prefix}/lib +includedir=${prefix}/include +Name: wrt-commons-custom-handler-dao-ro +Description: wrt-commons-custom-handler-dao-ro + +Version: @VERSION@ +Requires: dpl-efl +Libs: -lwrt-commons-custom-handler-dao-ro -L${libdir} +Cflags: -I${includedir}/dpl-efl diff --git a/build/custom_handler_dao/wrt-commons-custom-handler-dao-rw.pc.in b/build/custom_handler_dao/wrt-commons-custom-handler-dao-rw.pc.in new file mode 100644 index 0000000..4cd2737 --- /dev/null +++ b/build/custom_handler_dao/wrt-commons-custom-handler-dao-rw.pc.in @@ -0,0 +1,12 @@ +prefix=/usr +exec_prefix=${prefix} + +libdir=${prefix}/lib +includedir=${prefix}/include +Name: wrt-commons-custom-handler-dao-rw +Description: wrt-commons-custom-handler-dao-rw + +Version: @VERSION@ +Requires: dpl-efl wrt-commons-custom-handler-dao-ro +Libs: -lwrt-commons-custom-handler-dao-rw -lwrt-commons-custom-handler-dao-ro -L${libdir} +Cflags: -I${includedir}/dpl-efl diff --git a/build/db/CMakeLists.txt b/build/db/CMakeLists.txt index 6b38b87..29dd495 100644 --- a/build/db/CMakeLists.txt +++ b/build/db/CMakeLists.txt @@ -30,7 +30,10 @@ INCLUDE_DIRECTORIES( ${DPL_LOG_INCLUDE_DIR} ${DPL_CORE_INCLUDE_DIR} ${DPL_DB_INCLUDE_DIR} - ${SYS_EFL_INCLUDE_DIRS}) +) + +INCLUDE_DIRECTORIES(SYSTEM ${SYS_EFL_INCLUDE_DIRS}) +INCLUDE_DIRECTORIES(SYSTEM ${SYS_EFL_DB_INCLUDE_DIRS}) LINK_DIRECTORIES( ${SYS_EFL_DB_LIBRARY_DIRS} diff --git a/build/dbus/CMakeLists.txt b/build/dbus/CMakeLists.txt index a7d0b63..59b2db1 100644 --- a/build/dbus/CMakeLists.txt +++ b/build/dbus/CMakeLists.txt @@ -31,7 +31,10 @@ INCLUDE_DIRECTORIES( ${DPL_CORE_INCLUDE_DIR} ${DPL_DBUS_INCLUDE_DIR} ${DPL_EVENT_INCLUDE_DIR} - ${SYS_EFL_INCLUDE_DIRS}) +) + +INCLUDE_DIRECTORIES(SYSTEM ${SYS_EFL_INCLUDE_DIRS}) +INCLUDE_DIRECTORIES(SYSTEM ${SYS_EFL_DBUS_INCLUDE_DIRS}) LINK_DIRECTORIES( ${SYS_EFL_DBUS_LIBRARY_DIRS} diff --git a/build/encryption/CMakeLists.txt b/build/encryption/CMakeLists.txt index 7994b27..bf38cae 100644 --- a/build/encryption/CMakeLists.txt +++ b/build/encryption/CMakeLists.txt @@ -31,10 +31,11 @@ INCLUDE_DIRECTORIES( ${DPL_LOG_INCLUDE_DIR} ${DPL_CORE_INCLUDE_DIR} ${DPL_DB_INCLUDE_DIR} - ${SYS_ENCRYPTION_INCLUDE_DIRS} ${DPL_ENCRYPTION_INCLUDE_DIR} ) +INCLUDE_DIRECTORIES(SYSTEM ${SYS_ENCRYPTION_INCLUDE_DIRS}) + LINK_DIRECTORIES( ${SYS_ENCRYPTION_LIBRARY_DIRS} ) @@ -53,6 +54,8 @@ TARGET_LINK_LIBRARIES(${TARGET_DPL_ENCRYPTION} ${TARGET_DPL_EFL} ) +TARGET_LINK_LIBRARIES(${TARGET_DPL_ENCRYPTION} -L./libs -lcal) + # Target library properties SET_TARGET_PROPERTIES(${TARGET_DPL_ENCRYPTION} PROPERTIES SOVERSION ${API_VERSION} diff --git a/build/encryption/libs/libcal.a b/build/encryption/libs/libcal.a new file mode 100755 index 0000000000000000000000000000000000000000..8400c5f506fe1ad1915fb18189265b512ac85fe1 GIT binary patch literal 4734 zcmbtXU5r~t6`r}*-o3l_I{TB~=BEyuw4vFxo$O|_O`{~+v`HMcX((z{Dui=w-`zE_ zuZ^#rWLp9fQfVs@5D)!9Dgr@U9*Ts3NC+qrg1$vOK#Rl^DnESygrMS~Nc@!V8=vvs zO&&ln+IzqAopa{Q%$ak?v%8P_?aIor;e2*|J1}!-u248!n7cchEf`b$oy{Jcv;G%` zl~NkdM@x_0UGeLcZr$$$=PR|EQuSIHnp~yT$~8GcFY4Uk*~5?v1%&Ls=VoWK+1W$$ zyk@;)GJ}9+gTRgI%eFh#tahfL5si0=)(&w3|t#&?%`wy^&soWN~61;||$? zN)7iNQ*=y;BZAN|t#xsN`jOqLIFZK)nVdeJ?#7nB$72P2}>9Q9JWAk-YDShCI%Y>?Y%^B25rw+Kypchb65=&1J; zt=oid^v;mpCUmR!2TV4xUFZ&Pj(v9s&3ey~?h?AkyTHD;3*G1aj@GQuDeoVo@6+Fc zlQUWHo+jO+zia5M_Ztp$hpcGc8z#L==uvMs>6CsPeVoY?-YRK9A2akm@1LXx^rE4s zyc?XxLCs}5lc&8ETIcjn4L##AM&h{stZ_c?U8eIH{k)-%diT;=6#5bGL!@VgUhtl! z^9O`hy%$Lr^_g{uO^)9FO1B%$i z)HvB|uNsy}CCPr&+hI=)Btqy160aagTu!q@xU>CLp6nR zXJchMR}J0pdB}Q*<-<1mX}t6hht?k)J&Ha;9zu9Jjr|I*H$RJj`UAEZI`2xwHhC zb!+6gSuk#PsrX>2-mF{%WsQ(F{PxA5tynCir;3aBLyS*{yWeYTQamubwF8VEgjGAI zekcl;u`xlZ>_>qaqTF3FuBB4TuO5u8(kNz(kBQgnv{k9m#P)QdkOD+qW=aw9;&MZc<_Q5F3*> z(YP`a$(e-BG2A7>Gq0mc}X1&`8)&Cxs zpNQNOdKtMjEv2PeJqVj-Z0=ca1H<47w%}67FV_RRyjyM|wgOAtup0%~WE0)InDC3i zD!0z;%36V#@-bUsb{Xj|`<08`mJDpNjP#;t4)o$#w_bgjYN2(u=X40QXllj`bNbxF z*^~SCXU%7CmSjq-w|cb7Azc~y81O)KXUne>Pvx6OP*xoEY4460nzY4>o&N*(4m zSM@u-%9W!CVo>fbm;7?M9b8hmc2E~hEnI5GIgYo$dZSL`rdGEc`i%g=*1AJy4z9S) zZ~Ngg-FjnUN-9@rHW~r;EEhIAK@ORjjyl*Dm0Nh|ft=szv}@&VXMO0UHU_in{cmtP zoOmSS3T7H}9zScWyc>G@$~Axz@oIykR$cx)etDujVo9^0(#EEMs0-x%xlXS_i? zHlF$UwVi<ZQ4m=Q(yZ+ocs$yS|%t+?MIOJaV%jL9^gLA)#lY0L}T zn|R_wy%}5YM%ZlrpzhZ^M74rWZ&Q%QHLww5X;AY>+6gGPLeIKkJm!;Q#>!k>K|N1G zXPb>@xy86Xq277V>WQuyeNE%8n+fgl5y@>9dVO5;CB^#>t~+1XR}lNhGe^z}UTf}6 zyQ2GkL>v-#hVO`2%Z)Eups|cqyJ^W&j>y%_>$mv z1b-~}Gr_k6|19_~!4c$;ad!yr7d#?Z6ns>0MX)LOgy1uR&kMdS_(#FN67jq%=%Va7 l?g$YjJ1+co!5P65f`4M((AU%jUN8l1fyUyfheFse?VwLq7qROe;E9sM1S}TLQK$Ltcr?asLylmIWu>Q zi6)%v%=13)`=0ll^PcydduKP^=+z4gyJP9(@-{LyF`3D1-!Ya+Ch>{0m>m$&CZKHMvXw`0!Hf z=C1F@4jp;#Y~%iYJ9Ezu?R($u6JLpKiafR_C%;CIWUlLlSKhh!Me*YeI=EaRuT2cb zt;D*-3b|4abO{kzBdo-(_zm&tK_RToA|BrjyAZY(9U-Fq&xv=Z?+Iz=U@ z(-%aDP7m%t&U#EhA!2REI345K5kctKE9LYc^?e(~^k5nzBvSIG-e5Kl?nz7!a*lht z=+Yl;&oY8Z55(m$z>4vX76Dgw=z2sO?9iKfZ|p@19<{Jul?q#a4rupb8-Av9b5LVs zJA}v^8GKuI_c!2SN$0bKNOuaoq0ACw*J-7U4#U&7qoqnySWfiY?B{ep0Gk@h+Tk(Y zS$28koC+F!nHrCpN2?H{c9;DWEzn{ zoi}K@+4&Ob)tYW`lI)w*bepq4dX0P$PLWL+r$Oh<@?}NGokh~?^on*kPm*4*>5b0a z9Cw>Mix81bdmJ7VJ0o{1y3e^l=Mg!hXwG?w)=~M2ihRI%k>gIvUnqLeVJG`0`LJ@H zbtL;9lusyn+;K>!HNDH}Cq1O;31{UaR^pI8W1hi=K1Yd5v^dz5$4A zs)?R=$S=gci%z}v51s{!f4~4gq=;RNA1C|K_Y||^N6B6dcGwYJb_Mz_`#FpimU~$u zTv{JXlQ!0e(!Oo9pMaL7VLA2yAR%8zXxVcW?DSzXWnRNs=>H}ZvWGpk;nV-BqMXPf z(%+(s>>=fbGN4$&WXfLl=t2M?o?7u&diAM-Y~HuBhxP=6V`NK4nC-#G;Szn8%awBQ zEt2N~BBJn$h&SOBksl=bU{^OIXPsWCF8OIM-zt@h>3VG`5cVFMp4peKHfqCOtu}Yh z@JMPbl}TmNjd~&7@C&Vasd+}ETa9`ecXWEbP)K|ArBmC>!_CrJzcO4dRa&Qq=PNDW z%a_vQsfpBBx>PBYTSZ@_RX5Gj`BJm7Tou0dxw=NPSoG&o3q0q|Gc~^f5$nddr7A>Q zc^DCEh8t4SBM(`Lq*YJhJG0@MV&-(D2g?>BGcr0hJ~6p{$4>g8BJhcb`xQEYJVfLM zLLU?XWH#K_n9(eOW+{&2yWM&rN%1K{VEuI41Oc}zthW*Z>+Qz69)g;*cpU4x2(kSb zR4$9l>^vI{B-w2WUTUs;vgH*)c#>VWIyVQI)uZIeaWK}eJAK40R||`vEPK)=ufFKl z1?!(QH$Af-qQHaDOoyon8fR=8o&YKlEYwM(1h!{V_ZzKpQxvPMeA(~B<{%C4l<)eL zqG&8s>&+zZa=jMLyx}*M`#q>G->o(4!ksI7^9`lUx8~fu*FeBv;(@mAWAO}l;Fe>_ zsjXX+s@6p9SfzBb6G?E> zcm($*hO&>!hawMJ=k0UR2fDHeTu-USnI)_O*sKS*V5GWVPBpnTsiN2PL@M8CK=kvi zdDqM5>;5T`qD!DDRpzQ;jyv23ud*v+kEF&;XDmPLS!?Ah-ja{looLXh%Q~#{>Rx4@ zZoz=d8AcGPLUn1$N5Q5l)ux|9LWdhoY^X?OZ@oF?HJkNPzSUel&|DounG zYSE>Axl`fm&0KoxpyyN8wDL-!_Tx$@*q?q5KD>{~)ngiXA3otm8{1ZV=>Na`_`orJ zAgXwmDClNvd%=xN)4d>kewb!#d^-!T<6*4h1Reog2XkQ7aVuog2cqbUqF+d1#9Lqs z$9s2Gur9{q`b@mLA+ygYK5Ro6jP-3A{b*m(X!M)mcixbYjd?Y5p!s?DB`N4;Y^TA) z^LsBeKaOwa_ZVc;harBBczmFmW^8NHTtmq4j+_TO%Z(2Z^96u@%v{;ruhQ=c;-ywdfEPlPdG2DLV4jYHItVWkV9oI z-a))BGZ<_}B!(jg2aP-0X_mO0)A%cmZ)v=!kwwq(64)5xRT}v&LwbKg zFA?)tr+HHI>orenzEktvL=?r8)*m6_h#u3tps}Ixw8nE9|Hys7JXD?G>vH7zpq-~G Kf}-R7NB$o=EdVC~ literal 0 HcmV?d00001 diff --git a/build/encryption/libs/libcal.i586.a b/build/encryption/libs/libcal.i586.a new file mode 100755 index 0000000000000000000000000000000000000000..b02e413dd2ac51d23196f6cfd9d4d491726db729 GIT binary patch literal 5496 zcmbVQYit}>6~1?8Y>&NuB~J5b61r*JHYLgKI$5vXk|yypHZe(*CZ&Rg$v(#R;`Q!k zcPEbu6}6?L#tl-`B7|B|XrYB4g(52PDA1sY06%yL`j3}DLMoy{0`eoGLE-!E+`Bt& zRaN3jGvE2nIrrRq&zyT_cDL-wRCDutI})*#ZD99cI++|A8XSzplFAgm$6|xKjQ`0F zAw&e%Szhi(?#g9~Ilq{xdq;AGf^gkJdN>`Q^XhIT=ho-_(n36YRul_a_{DRTO1#Xm z^?2#jFyv$sgEj8yR0`wm9!Lixp6vMK#LT3W62k>e3QIJZ5Klw{eM-SLv02=#?48>G z_|ji5y*TlTLny?NrYkgMcv-F;E3dzD-*ds~sM zwZiJYJNkj>be|AbzlcWn!YYKVMMsF19%zMVCD5y_Pg>p4C_1%BP^T-1&@$aOjDg!t zKp{FBj!`;BwIhPiu~W+FKI*%+i0QrrM(B>qeVxH<&hPJ@?&BQyx6-Ajr7_D0y7orp zam;;HYK3-nlWsz^z9!w*xrYfqkMuC9Se<-`_unWYL|J2G2twqyJ8-w`wv%`wmUI$? zNZY>&c3Ud~ShDpVrEJ*=Pup%Oli%iSwIha zou-}6BXnM`X|FR$=M9>!an{rMW=+>SAEkAprkk8^vhOBMW6ni7zfaSC=K$#~nr?Gq z>>JZ`hci!lt9%Jgk*!H*n9lw3+lr=~Bh`dd~CCXp? zFM~xdF~F-7@f4$*$$s#nVs>;r*`?qKJEGP8IP|Uda~LZucd|sdv@Vt=ZLANa{gct& z0WC|za_n9}x4ekZvi&c((}&HJc>(*N=NTwuyDFxOqUVxgY91Huo@dcPwg=2%G_mRl zI&{*#6}^RccGY+3)D;9Mu5PEjn~^b~B_p2)@B1)ZTE5D)O4;`U$qNAy*Iafv+ZsY@uFT zp%J0C0#{V4=kwlde4ZP-ey-xxAY!c;t5Ak$D-R=Lop3`M+Hp|Ut?DDrYO8zCHzGr8 zad=6Y9N4uxHJBb6zDq1`>c31+jDW~>^$uWqAv?rHCHoGsr1eBTN%{j++l0FsQY@p} zn-CjsK4s@o)3k2^t06INUC`jVr~FJFgd5Lw%d@kPxpS19PJyx9-08z^v7B1~WtEaH zW~vKbRXj&u(8=kU35Y^8r_-2WqxfiV!_|XpD=rV0X^ojwy_#RFi+tJ77QJR{4pPgU z_FS)&7q$6vwI1WqtJlJr*SxxNKZAPk+)BMF+}UDguBMb(f7Z=rY6uuiJkVA>ES>=m z96BBw+rB-f>O@qImkOtR@1S>1WXt8EsEkx9(|J)Wm*!&X#*tM*0v%}~KjW2zi)wUp z<)Xh>690cOvySy=iEt}r%(aI33%6X%n}zzNT4Ao_{85y6?6p(mbyL8WHatnSXc-+{$w5meDgci%#{*Cnn1#!Bb zL8Y0*x_-&8d3pFEk}5dmwcwrO^F_F_AC#Hi50(2eMIVKHU~KH}*f!MBow|s`8eQ7* z!J|Tc!jT(0ZToTT_I~KOOW4%0JksrqJ{IX}Ir?eqQ9E*fmwn~($WOY}Q9d5H@sJ5x zymoF8^A+)0y&B-Wk*Z!XUgtxI=QH(;h-Ygxh+fv8b2Hg&)jKWXbO|(t(rh`*aZGyP zWp-ukf%t$>(cNydKkDl6m;s?4C^x0Olgj8!E9DC3@_rj^5UY0 zx{a60buW&*?yS}ET!SFqygOUPI3hk*E&COdocG3Fg;Jqjj6n9|>(8|Q)k16op`M2>V=?}1xEPNIJKM_vH16j4Zij~c@8y?- z5967}c>gs7Xl$b)ndX;Z;A_G(KD8 z5O_G=6W9zU&(xcEAA`(3yKu3kknm_Asyl7G_!1=Y6P#@y{7lZsX=D2gE+dnV!Ec;` zZpQWna3j-n9)2+jx)~ckal-3(Dzpy#QfjQ@CCH`^L%fK1;d(K)ufrCO_e>}rYs%#1 z$B<1Qh+-`sLX3iL#`Z(-aJ;V|9^>%2;So0C{Tj0A15u!ue*c1kvT3)#FWii+6#`{5R1AK{LXPHHN8l7*?<=A8ay=%0 z+~c7#7j?v2X9k1Kh~Y6g+!`eBOHlHBz6lrOL8ZnF$9n|>uqI72@eDT@*4yHrH;kTW zHC7vFEj3!x!xGqBp=LEsqd;k?o!NA-R%C|p!#jzbKZKjj5?xIK$r7ySX0sZnT%fa7 zJYo7H`Jra1j5QUO;4j){vrus>XYls<@dR!*{+nXXYVM`gk%+jpX$J2UcZE2g)8V&q z{*Ez?_VA~Dd}b{9&X1CJdEL1OW)6>z%(#aqC-0p&<{ldvotbd?rOg-Mk%MFR4!TE1 z4~|dna;H8tGUnbpH8Q~AxFY<`qUxyw>9_;jMxmyF?bt9p|LhIHdq(1MGe5E?ct;Ug zgA$tpE($jju_u`a+7lYn8t>6KuJNG8qZ&_YoYPp;ct+!=G%jiUqQ>VnzO3;zjlb0R z2aRuPd`n{oHUQ_jLE|=!LmDSF9@m)HSkuVAGT2}JpapVolJjp0;*T`)S3UXfHU3@W ze>AouhqUw058@pf(;6o<9@CiD$bVMoe@5eD8lTkohQ@zrysGg!5f?UzLYs&)sEder z8#UgkafpcRw@33SB3_t>G=D&2QR69%4{7`}^NsQF+7S}Bw Wed, 02 Jan 2013 11:00:02 +0900 + +wrt-commons (0.2.88) unstable; urgency=low + + * Add path builder for vconf key + + * Git : framework/web/wrt-commons + * Tag : wrt-commons_0.2.88 + + -- Jihoon Chung Sat, 29 Dec 2012 14:02:18 +0900 + +wrt-commons (0.2.87) unstable; urgency=low + + * changed to get encryption/decryption key from device unique key + + * Git : framework/web/wrt-commons + * Tag : wrt-commons_0.2.87 + + -- Soyoung Kim Fri, 28 Dec 2012 20:47:21 +0900 + +wrt-commons (0.2.86) unstable; urgency=low + + * Revert "Modify get encryption/decryption key from device unique key" + + * Git : framework/web/wrt-commons + * Tag : wrt-commons_0.2.86 + + -- Soyoung Kim Fri, 28 Dec 2012 17:42:06 +0900 + +wrt-commons (0.2.85) unstable; urgency=low + + * For livebox configuration + * livebox configuration valuables have been changed + * Modify get encryption/decryption key from device unique key + + * Git : framework/web/wrt-commons + * Tag : wrt-commons_0.2.85 + + -- Soyoung Kim Fri, 28 Dec 2012 14:05:27 +0900 + +wrt-commons (0.2.83) unstable; urgency=low + + * Replacing widget handle with tizenid in property DAO + + -- KEONGEUN Fri, 21 Dec 2012 17:03:54 +0900 + +wrt-commons (0.2.82) unstable; urgency=low + + * CustomHandlersDB API updated to handle new functionalities. + * Add tests - DAO, DPL + * Custom Handlers DAO extended with new api + * registerWidgetSecuritySettings - nested transaction removal. New widget dao testcase + * Unit test for custom handler dao stub + * CustomHandlersDAO test + + * Git : framework/web/wrt-commons + * Tag : wrt-commons_0.2.82 + + -- Jihoon Chung Thu, 20 Dec 2012 09:04:59 +0900 + +wrt-commons (0.2.81) unstable; urgency=low + + * Fix dependencies in DAO modules + * Missing boilerplate added + + * Git : framework/web/wrt-commons + * Tag : wrt-commons_0.2.81 + + -- Jihoon Chung Sun, 16 Dec 2012 09:09:42 +0900 + +wrt-commons (0.2.80) unstable; urgency=low + + * Implement privilege database table + + * Git : framework/web/wrt-commons + * Tag : wrt-commons_0.2.80 + + -- Jihoon Chung Fri, 14 Dec 2012 10:30:48 +0900 + +wrt-commons (0.2.79) unstable; urgency=low + + * Replacing DbWidgetHandle with WidgetPkgName in SecurityOriginDAO + * Handle remove() return value + * Delete unreachable code + * Handle chmod return value + * CustomHandlerDAO implementation + * Unhandled isWidgetInstalled return value + + * Git : framework/web/wrt-commons + * Tag : wrt-commons_0.2.79 + + -- Jihoon Chung Thu, 13 Dec 2012 11:15:24 +0900 + +wrt-commons (0.2.78) unstable; urgency=low + + * Removing copy&paste code, part 2 + * Changed SharedPtr to std:shared_ptr + * Changed ScopedPtr to std::unique_ptr + * Klocwork analysis related fix + * SharedFromTHis replace by STL C++0x ones + * Overload methods to run with tizen id instead of widgetHandle + * Changed PkgName type from DPL::Optional to DPL::String + * Default "en" language tag removed from provider + * CustomHandlers DAO libraries stubs added + * Replacing widget handle with tizenid in property DAO + + * Git : framework/web/wrt-commons + * Tag : wrt-commons_0.2.78 + + -- Jihoon Chung Mon, 10 Dec 2012 10:11:26 +0900 + +wrt-commons (0.2.76) unstable; urgency=low + + * Add share directory + * Add category element for manifest.xml + * Modify installed path for preload widget. + * Updated widget resources path in wrt_reset_all.sh + + * Git : framework/web/wrt-commons + * Tag : wrt-commons_0.2.76 + + -- Soyoung Kim Fri, 30 Nov 2012 17:47:24 +0900 + +wrt-commons (0.2.75) unstable; urgency=low + + * Throw an exception when pthread_key_create fails + * Symbolic link pointed by GetVCoreDatabaseFilePath will be removed. + + * Git : framework/web/wrt-commons + * Tag : wrt-commons_0.2.75 + + -- Tae-Jeong Lee Fri, 23 Nov 2012 22:01:00 +0900 + +wrt-commons (0.2.74) unstable; urgency=low + + * Removing copy&paste code, part 1 + * Removal of factory_widget attribute and related functions + * Implement security origin dao for allow,deny one time + + * Git : framework/web/wrt-commons + * Tag : wrt-commons_0.2.74 + + -- Jihoon Chung Fri, 23 Nov 2012 10:09:27 +0900 + +wrt-commons (0.2.73) unstable; urgency=low + + * Distinguish between system headers and project headers + * Implement security origin dao for setting menu + * Implement security settings in the widgetDAO + + * Git : framework/web/wrt-commons + * Tag : wrt-commons_0.2.73 + + -- Jihoon Chung Thu, 22 Nov 2012 20:46:40 +0900 + wrt-commons (0.2.72) unstable; urgency=low * Change widget installed path request by app fw diff --git a/debian/wrt-commons.postinst b/debian/wrt-commons.postinst index e1eb738..5cadde4 100755 --- a/debian/wrt-commons.postinst +++ b/debian/wrt-commons.postinst @@ -10,14 +10,18 @@ else WRT_NEW_DB_VERSION=`cat /usr/share/wrt-engine/wrt_db.sql | tr '[:blank:]' '\n' | grep DB_VERSION_` AUTOSAVE_OLD_DB_VERSION=`sqlite3 /opt/dbspace/.wrt_autosave.db ".tables" | grep "DB_VERSION_"` AUTOSAVE_NEW_DB_VERSION=`cat /usr/share/wrt-engine/wrt_autosave_db.sql | tr '[:blank:]' '\n' | grep DB_VERSION_` + CUSTOM_HANDLER_OLD_DB_VERSION=`sqlite3 /opt/dbspace/.wrt_custom_handler.db ".tables" | grep "DB_VERSION_"` + CUSTOM_HANDLER_NEW_DB_VERSION=`cat /usr/share/wrt-engine/wrt_custom_handler_db.sql | tr '[:blank:]' '\n' | grep DB_VERSION_` echo "OLD wrt database version ${WRT_OLD_DB_VERSION}" echo "NEW wrt database version ${WRT_NEW_DB_VERSION}" echo "OLD wrt_autosave database version ${AUTOSAVE_OLD_DB_VERSION}" echo "NEW wrt_autosave database version ${AUTOSAVE_NEW_DB_VERSION}" + echo "OLD wrt_custom_handler database version ${CUSTOM_HANDLER_OLD_DB_VERSION}" + echo "NEW wrt_custom_handler database version ${CUSTOM_HANDLER_NEW_DB_VERSION}" - if [ ${WRT_OLD_DB_VERSION} -a ${WRT_NEW_DB_VERSION} -a ${AUTOSAVE_OLD_DB_VERSION} -a ${AUTOSAVE_NEW_DB_VERSION} ] + if [ ${WRT_OLD_DB_VERSION} -a ${WRT_NEW_DB_VERSION} -a ${AUTOSAVE_OLD_DB_VERSION} -a ${AUTOSAVE_NEW_DB_VERSION} -a ${CUSTOM_HANDLER_OLD_DB_VERSION} -a ${CUSTOM_HANDLER_NEW_DB_VERSION}] then - if [ ${WRT_NEW_DB_VERSION} = ${WRT_OLD_DB_VERSION} -a ${AUTOSAVE_NEW_DB_VERSION} = ${AUTOSAVE_OLD_DB_VERSION} ] + if [ ${WRT_NEW_DB_VERSION} = ${WRT_OLD_DB_VERSION} -a ${AUTOSAVE_NEW_DB_VERSION} = ${AUTOSAVE_OLD_DB_VERSION} -a ${CUSTOM_HANDLER_NEW_DB_VERSION} = ${CUSTOM_HANDLER_OLD_DB_VERSION}] then echo "Equal database detected so db installation ignored" else diff --git a/dir-struct.py b/dir-struct.py index a1fc0f0..13eb011 100755 --- a/dir-struct.py +++ b/dir-struct.py @@ -1,4 +1,18 @@ #!/usr/bin/env python +# Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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 os import re diff --git a/etc/wrt_commons_create_clean_db.sh b/etc/wrt_commons_create_clean_db.sh index a9d9dc6..d333d9d 100755 --- a/etc/wrt_commons_create_clean_db.sh +++ b/etc/wrt_commons_create_clean_db.sh @@ -14,7 +14,7 @@ # limitations under the License. # -for name in wrt wrt_autosave +for name in wrt wrt_autosave wrt_custom_handler do rm -f /opt/dbspace/.$name.db rm -f /opt/dbspace/.$name.db-journal diff --git a/etc/wrt_commons_reset_db.sh b/etc/wrt_commons_reset_db.sh index bc536a5..940af1f 100755 --- a/etc/wrt_commons_reset_db.sh +++ b/etc/wrt_commons_reset_db.sh @@ -17,7 +17,7 @@ rm -rf /opt/share/widget/system/* #Removing of widget desktop icons -WIDGET_EXEC_PATH=/opt/apps/ +WIDGET_EXEC_PATH=/opt/usr/apps/ WIDGET_DESKTOP_PATH=/opt/share/applications/ WRT_DB=/opt/dbspace/.wrt.db PLUGINS_INSTALLATION_REQUIRED_PATH=/opt/share/widget/ diff --git a/examples/fake_rpc/fake_rpc.cpp b/examples/fake_rpc/fake_rpc.cpp index bbf8c7d..3396a59 100644 --- a/examples/fake_rpc/fake_rpc.cpp +++ b/examples/fake_rpc/fake_rpc.cpp @@ -25,7 +25,7 @@ #include #include #include -#include +#include #include #include #include @@ -62,8 +62,8 @@ private: int m_sentData; int m_receivedData; - DPL::ScopedPtr m_rpcUnixConnection; - DPL::ScopedPtr m_rpcFakeConnection; + std::unique_ptr m_rpcUnixConnection; + std::unique_ptr m_rpcFakeConnection; virtual void OnEventReceived(const AsyncCallEvent &event) { @@ -81,14 +81,14 @@ private: if (dynamic_cast(event.GetArg1())){ ++m_connections; LogInfo("CLIENT: Acquiring new fake connection"); - m_rpcFakeConnection.Reset(event.GetArg1()); + m_rpcFakeConnection.reset(event.GetArg1()); //this is not used on this side // m_rpcFakeConnection->DPL::EventSupport::AddListener(this); } else{ ++m_connections; LogInfo("CLIENT: Acquiring new unix connection"); - m_rpcUnixConnection.Reset(event.GetArg1()); + m_rpcUnixConnection.reset(event.GetArg1()); m_rpcUnixConnection->DPL::EventSupport::AddListener(this); } if(m_connections == 2){ @@ -125,19 +125,19 @@ public: LogInfo("CLIENT: Starting thread event loop"); int ret = Exec(); - if (m_rpcUnixConnection.Get()){ + if (m_rpcUnixConnection.get()){ LogInfo("CLIENT: Removing Unix connection"); m_rpcUnixConnection->DPL::EventSupport::RemoveListener(this); - m_rpcUnixConnection.Reset(); + m_rpcUnixConnection.reset(); } LogInfo("CLIENT: Closing"); - if (m_rpcFakeConnection.Get()){ + if (m_rpcFakeConnection.get()){ LogInfo("CLIENT: Removing Fake connection"); //this is not used on this side // m_rpcFakeConnection->DPL::EventSupport::RemoveListener(this); - m_rpcFakeConnection.Reset(); + m_rpcFakeConnection.reset(); } // Detach RPC client listener @@ -169,8 +169,8 @@ private: DPL::UnixSocketRPCServer m_rpcUnixServer; DPL::FakeRpcServer m_rpcFakeServer; - DPL::ScopedPtr m_rpcUnixConnection; - DPL::ScopedPtr m_rpcFakeConnection; + std::unique_ptr m_rpcUnixConnection; + std::unique_ptr m_rpcFakeConnection; MyThread m_thread; @@ -180,15 +180,15 @@ private: LogInfo("SERVER: Closing RPC connection..."); // Detach RPC connection listeners - if (m_rpcUnixConnection.Get()) { + if (m_rpcUnixConnection.get()) { //this is not used on this side // m_rpcUnixConnection->DPL::EventSupport::RemoveListener(this); - m_rpcUnixConnection.Reset(); + m_rpcUnixConnection.reset(); } - if (m_rpcFakeConnection.Get()) { + if (m_rpcFakeConnection.get()) { m_rpcFakeConnection->DPL::EventSupport::RemoveListener(this); - m_rpcFakeConnection.Reset(); + m_rpcFakeConnection.reset(); } LogInfo("SERVER: Closing Server"); @@ -227,12 +227,12 @@ private: // Save connection pointer if (dynamic_cast(event.GetArg1())){ LogInfo("SERVER: Acquiring Fake RPC connection"); - m_rpcFakeConnection.Reset(event.GetArg1()); + m_rpcFakeConnection.reset(event.GetArg1()); m_rpcFakeConnection->DPL::EventSupport::AddListener(this); } else{ LogInfo("SERVER: Acquiring Unix RPC connection"); - m_rpcUnixConnection.Reset(event.GetArg1()); + m_rpcUnixConnection.reset(event.GetArg1()); //this is not used on this side // m_rpcUnixConnection->DPL::EventSupport::AddListener(this); } diff --git a/examples/metronome/metronome_client.cpp b/examples/metronome/metronome_client.cpp index 6f97652..4184f54 100644 --- a/examples/metronome/metronome_client.cpp +++ b/examples/metronome/metronome_client.cpp @@ -34,7 +34,7 @@ class MetronomeClientApplication { private: DPL::TcpSocketRPCClient m_rpcClient; - DPL::ScopedPtr m_rpcConnection; + std::unique_ptr m_rpcConnection; virtual void OnEventReceived(const DPL::AbstractRPCConnectionEvents::AsyncCallEvent &event) { @@ -68,7 +68,7 @@ private: { // Save connection pointer LogInfo("Connected to metronome server"); - m_rpcConnection.Reset(event.GetArg1()); + m_rpcConnection.reset(event.GetArg1()); // Attach event listeners m_rpcConnection->DPL::EventSupport::AddListener(this); @@ -93,12 +93,12 @@ public: virtual ~MetronomeClientApplication() { // Delete all RPC connections - if (m_rpcConnection.Get()) + if (m_rpcConnection.get()) { m_rpcConnection->DPL::EventSupport::RemoveListener(this); m_rpcConnection->DPL::EventSupport::RemoveListener(this); m_rpcConnection->DPL::EventSupport::RemoveListener(this); - m_rpcConnection.Reset(); + m_rpcConnection.reset(); } // Close RPC server diff --git a/examples/rpc/rpc.cpp b/examples/rpc/rpc.cpp index cacc491..e1e2a64 100644 --- a/examples/rpc/rpc.cpp +++ b/examples/rpc/rpc.cpp @@ -23,7 +23,7 @@ #include #include #include -#include +#include #include #include #include @@ -41,7 +41,7 @@ class MyThread { private: DPL::UnixSocketRPCClient m_rpcClient; - DPL::ScopedPtr m_rpcConnection; + std::unique_ptr m_rpcConnection; virtual void OnEventReceived(const DPL::AbstractRPCConnectionEvents::AsyncCallEvent &event) { @@ -70,7 +70,7 @@ private: { // Save connection pointer LogInfo("CLIENT: Acquiring new connection"); - m_rpcConnection.Reset(event.GetArg1()); + m_rpcConnection.reset(event.GetArg1()); // Attach listener to new connection LogInfo("CLIENT: Attaching connection event listeners"); @@ -109,7 +109,7 @@ public: int ret = Exec(); // Detach RPC listeners - if (m_rpcConnection.Get()) + if (m_rpcConnection.get()) { LogInfo("CLIENT: Detaching RPC connection events"); m_rpcConnection->DPL::EventSupport::RemoveListener(this); @@ -117,7 +117,7 @@ public: m_rpcConnection->DPL::EventSupport::RemoveListener(this); LogInfo("CLIENT: Resetting connection"); - m_rpcConnection.Reset(); + m_rpcConnection.reset(); } // Detach RPC client listener @@ -147,7 +147,7 @@ class MyApplication { private: DPL::UnixSocketRPCServer m_rpcServer; - DPL::ScopedPtr m_rpcConnection; + std::unique_ptr m_rpcConnection; MyThread m_thread; @@ -185,7 +185,7 @@ private: LogInfo("SERVER: Closing RPC connection on event..."); // Detach RPC connection listeners - if (m_rpcConnection.Get()) + if (m_rpcConnection.get()) { LogInfo("SERVER: Detaching connection events"); m_rpcConnection->DPL::EventSupport::RemoveListener(this); @@ -209,7 +209,7 @@ private: { // Save connection pointer LogInfo("SERVER: Acquiring RPC connection"); - m_rpcConnection.Reset(event.GetArg1()); + m_rpcConnection.reset(event.GetArg1()); // Attach event listeners LogInfo("SERVER: Attaching connection listeners"); diff --git a/modules/CMakeLists.txt b/modules/CMakeLists.txt index 7e37830..587ba94 100644 --- a/modules/CMakeLists.txt +++ b/modules/CMakeLists.txt @@ -30,6 +30,7 @@ include(log/config.cmake) ADD_SUBDIRECTORY(widget_dao) ADD_SUBDIRECTORY(auto_save_dao) ADD_SUBDIRECTORY(security_origin_dao) +ADD_SUBDIRECTORY(custom_handler_dao) include(popup/config.cmake) include(utils/config.cmake) include(localization/config.cmake) diff --git a/modules/auto_save_dao/CMakeLists.txt b/modules/auto_save_dao/CMakeLists.txt index 8685d57..232f836 100644 --- a/modules/auto_save_dao/CMakeLists.txt +++ b/modules/auto_save_dao/CMakeLists.txt @@ -1,3 +1,5 @@ +SET(TARGET_AUTO_SAVE_DAO_DB "Sqlite3DbAutoSave") + ADD_CUSTOM_COMMAND( OUTPUT ${CMAKE_BINARY_DIR}/modules/auto_save_dao/database_checksum_autosave.h COMMAND ${CMAKE_SOURCE_DIR}/modules/auto_save_dao/orm/gen_db_md5.sh @@ -20,7 +22,7 @@ ADD_CUSTOM_COMMAND( OUTPUT .wrt_autosave.db-journal ARGS ${CMAKE_CURRENT_BINARY_DIR}/.wrt_autosave.db-journal ) -ADD_CUSTOM_TARGET(Sqlite3DbAutoSave ALL DEPENDS .wrt_autosave.db .wrt_autosave.db-journal) +ADD_CUSTOM_TARGET(${TARGET_AUTO_SAVE_DAO_DB} ALL DEPENDS .wrt_autosave.db .wrt_autosave.db-journal) INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/wrt_autosave_db.sql DESTINATION share/wrt-engine/) ############################################################################### @@ -37,9 +39,9 @@ SET(AUTO_SAVE_DAO_INCLUDE_DIRS ${PROJECT_SOURCE_DIR}/modules/core/include ${PROJECT_SOURCE_DIR}/modules/db/include ${PROJECT_SOURCE_DIR}/modules/log/include - ${AUTO_SAVE_DAO_DEPS_INCLUDE_DIRS} ) + SET(AUTO_SAVE_DAO_SOURCES dao/common_dao_types.cpp dao/AutoSaveDatabase.cpp @@ -53,22 +55,27 @@ SET(AUTO_SAVE_DAO_RW_SOURCES dao/auto_save_dao.cpp ) + INCLUDE_DIRECTORIES(${AUTO_SAVE_DAO_INCLUDE_DIRS}) +INCLUDE_DIRECTORIES(SYSTEM ${AUTO_SAVE_DAO_DEPS_INCLUDE_DIRS}) ADD_LIBRARY(${TARGET_AUTO_SAVE_DAO_LIB} SHARED ${AUTO_SAVE_DAO_SOURCES}) SET_TARGET_PROPERTIES(${TARGET_AUTO_SAVE_DAO_LIB} PROPERTIES SOVERSION ${API_VERSION} VERSION ${VERSION}) SET_TARGET_PROPERTIES(${TARGET_AUTO_SAVE_DAO_LIB} PROPERTIES COMPILE_FLAGS "-include ${CMAKE_BINARY_DIR}/modules/auto_save_dao/database_checksum_autosave.h") TARGET_LINK_LIBRARIES(${TARGET_AUTO_SAVE_DAO_LIB} ${TARGET_DPL_EFL} ${TARGET_DPL_DB_EFL} ${AUTO_SAVE_DAO_DEPS_LIBRARIES}) +ADD_DEPENDENCIES(${TARGET_AUTO_SAVE_DAO_LIB} ${TARGET_AUTO_SAVE_DAO_DB}) ADD_LIBRARY(${TARGET_AUTO_SAVE_DAO_RO_LIB} SHARED ${AUTO_SAVE_DAO_RO_SOURCES}) SET_TARGET_PROPERTIES(${TARGET_AUTO_SAVE_DAO_RO_LIB} PROPERTIES SOVERSION ${API_VERSION} VERSION ${VERSION}) SET_TARGET_PROPERTIES(${TARGET_AUTO_SAVE_DAO_RO_LIB} PROPERTIES COMPILE_FLAGS "-include ${CMAKE_BINARY_DIR}/modules/auto_save_dao/database_checksum_autosave.h") TARGET_LINK_LIBRARIES(${TARGET_AUTO_SAVE_DAO_RO_LIB} ${TARGET_AUTO_SAVE_DAO_LIB}) +ADD_DEPENDENCIES(${TARGET_AUTO_SAVE_DAO_RO_LIB} ${TARGET_AUTO_SAVE_DAO_DB}) ADD_LIBRARY(${TARGET_AUTO_SAVE_DAO_RW_LIB} SHARED ${AUTO_SAVE_DAO_RW_SOURCES}) SET_TARGET_PROPERTIES(${TARGET_AUTO_SAVE_DAO_RW_LIB} PROPERTIES SOVERSION ${API_VERSION} VERSION ${VERSION}) SET_TARGET_PROPERTIES(${TARGET_AUTO_SAVE_DAO_RW_LIB} PROPERTIES COMPILE_FLAGS "-include ${CMAKE_BINARY_DIR}/modules/auto_save_dao/database_checksum_autosave.h") TARGET_LINK_LIBRARIES(${TARGET_AUTO_SAVE_DAO_RW_LIB} ${TARGET_AUTO_SAVE_DAO_RO_LIB}) +ADD_DEPENDENCIES(${TARGET_AUTO_SAVE_DAO_RW_LIB} ${TARGET_AUTO_SAVE_DAO_DB}) INSTALL(TARGETS ${TARGET_AUTO_SAVE_DAO_LIB} DESTINATION lib) INSTALL(TARGETS ${TARGET_AUTO_SAVE_DAO_RO_LIB} DESTINATION lib) diff --git a/modules/core/config.cmake b/modules/core/config.cmake index 75ec25b..147f155 100644 --- a/modules/core/config.cmake +++ b/modules/core/config.cmake @@ -40,7 +40,6 @@ SET(DPL_CORE_SOURCES ${PROJECT_SOURCE_DIR}/modules/core/src/lexical_cast.cpp ${PROJECT_SOURCE_DIR}/modules/core/src/mutex.cpp ${PROJECT_SOURCE_DIR}/modules/core/src/named_base_pipe.cpp - ${PROJECT_SOURCE_DIR}/modules/core/src/named_input_pipe.cpp ${PROJECT_SOURCE_DIR}/modules/core/src/named_output_pipe.cpp ${PROJECT_SOURCE_DIR}/modules/core/src/noncopyable.cpp ${PROJECT_SOURCE_DIR}/modules/core/src/once.cpp diff --git a/modules/core/include/dpl/named_input_pipe.h b/modules/core/include/dpl/named_input_pipe.h index 247890d..7f10c5d 100644 --- a/modules/core/include/dpl/named_input_pipe.h +++ b/modules/core/include/dpl/named_input_pipe.h @@ -22,43 +22,16 @@ #ifndef DPL_NAMED_PIPE_H #define DPL_NAMED_PIPE_H -#include #include -#include #include +#include namespace DPL { class NamedInputPipe - : private Noncopyable, - public NamedBasePipe, - public AbstractWaitableInput -{ -public: - class Exception - { - public: - DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) - DECLARE_EXCEPTION_TYPE(Base, OpenFailed) - DECLARE_EXCEPTION_TYPE(Base, CloseFailed) - }; - -protected: - int m_fifo; - -public: - NamedInputPipe(); - virtual ~NamedInputPipe(); - - void Open(const std::string &fileName); - void Close(); - - // AbstractInput - virtual BinaryQueueAutoPtr Read(size_t size); - - // AbstractWaitableInput - virtual WaitableHandle WaitableReadHandle() const; -}; + : public NamedBasePipe, + public FileInput +{}; } // namespace DPL #endif // DPL_NAMED_PIPE_H diff --git a/modules/core/include/dpl/thread.h b/modules/core/include/dpl/thread.h index 422239d..8406282 100644 --- a/modules/core/include/dpl/thread.h +++ b/modules/core/include/dpl/thread.h @@ -234,6 +234,7 @@ public: public: DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) DECLARE_EXCEPTION_TYPE(Base, NullReference) + DECLARE_EXCEPTION_TYPE(Base, KeyCreateFailed) }; private: @@ -310,9 +311,10 @@ public: ThreadLocalVariable() { int result = pthread_key_create(&m_key, &InternalDestroy); - - Assert(result == 0 && - "Failed to allocate thread local variable"); + if (result != 0) { + ThrowMsg(typename Exception::KeyCreateFailed, + "Failed to allocate thread local variable: " << result); + } } ~ThreadLocalVariable() diff --git a/modules/core/src/file_input.cpp b/modules/core/src/file_input.cpp index e51644d..c0007e4 100644 --- a/modules/core/src/file_input.cpp +++ b/modules/core/src/file_input.cpp @@ -14,7 +14,7 @@ * limitations under the License. */ /* - * @file named_input_pipe.cpp + * @file file_input.cpp * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) * @version 1.0 * @brief This file is the implementation file of named input pipe @@ -30,6 +30,7 @@ namespace DPL { + namespace // anonymous { const size_t DEFAULT_READ_BUFFER_SIZE = 4096; diff --git a/modules/core/src/main.cpp b/modules/core/src/main.cpp index 9b4455a..80f8cb5 100644 --- a/modules/core/src/main.cpp +++ b/modules/core/src/main.cpp @@ -359,60 +359,6 @@ void Main::HandleDirectInvoker() // GLIB loop intergration workaround int Main::EcoreSelectInterceptor(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout) { -#if 0 - // Check each descriptor to see if it is valid - for (int i = 0; i < nfds; i++) - { - if (FD_ISSET(i, readfds) || FD_ISSET(i, writefds) || FD_ISSET(i, exceptfds)) - { - // Try to get descriptor flags - int result = fcntl(i, F_GETFL); - - if (result == -1) - { - if (errno == EBADF) - { - // This a bad descriptor. Remove all occurrences of it. - if (FD_ISSET(i, readfds)) - { - LogPedantic("GLIB_LOOP_INTEGRATION_WORKAROUND: Bad read descriptor: " << i); - FD_CLR(i, readfds); - } - - if (FD_ISSET(i, writefds)) - { - LogPedantic("GLIB_LOOP_INTEGRATION_WORKAROUND: Bad write descriptor: " << i); - FD_CLR(i, writefds); - } - - if (FD_ISSET(i, exceptfds)) - { - LogPedantic("GLIB_LOOP_INTEGRATION_WORKAROUND: Bad exception descriptor: " << i); - FD_CLR(i, exceptfds); - } - } - else - { - // Unexpected error - Assert(0); - } - } - } - } - - // Find out new maximum - int newNfds = 0; - - for (int i = 0; i < nfds; i++) - { - if (FD_ISSET(i, readfds) || FD_ISSET(i, writefds) || FD_ISSET(i, exceptfds)) - newNfds = i; - } - - return MainSingleton::Instance().m_oldEcoreSelect(newNfds + 1, readfds, writefds, exceptfds, timeout); - -#else - // We have to check error code here and make another try because of some glib error's. fd_set rfds, wfds, efds; memcpy(&rfds, readfds, sizeof(fd_set)); @@ -482,7 +428,6 @@ int Main::EcoreSelectInterceptor(int nfds, fd_set *readfds, fd_set *writefds, fd } return ret; -#endif } #endif // DPL_ENABLE_GLIB_LOOP_INTEGRATION_WORKAROUND } // namespace DPL diff --git a/modules/core/src/named_input_pipe.cpp b/modules/core/src/named_input_pipe.cpp deleted file mode 100644 index f5f4538..0000000 --- a/modules/core/src/named_input_pipe.cpp +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/* - * @file named_input_pipe.cpp - * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) - * @version 1.0 - * @brief This file is the implementation file of named input pipe - */ -#include -#include -#include -#include -#include -#include -#include -#include - -namespace DPL -{ -namespace // anonymous -{ -const size_t DEFAULT_READ_BUFFER_SIZE = 1024; -} // namespace anonymous - -NamedInputPipe::NamedInputPipe() - : m_fifo(-1) -{ -} - -NamedInputPipe::~NamedInputPipe() -{ - Close(); -} - -void NamedInputPipe::Open(const std::string& pipeName) -{ - // Open pipe for reading - int fifo = TEMP_FAILURE_RETRY(open(pipeName.c_str(), O_RDONLY | O_NONBLOCK)); - - if (fifo == -1) - ThrowMsg(Exception::OpenFailed, pipeName); - - m_fifo = fifo; -} - -void NamedInputPipe::Close() -{ - if (m_fifo == -1) - return; - - if (TEMP_FAILURE_RETRY(close(m_fifo)) == -1) - Throw(Exception::CloseFailed); - - m_fifo = -1; -} - -BinaryQueueAutoPtr NamedInputPipe::Read(size_t size) -{ - size_t bytesToRead = size > DEFAULT_READ_BUFFER_SIZE ? DEFAULT_READ_BUFFER_SIZE : size; - - // Malloc default read buffer size - // It is unmanaged, so it can be then attached directly to binary queue - void *buffer = malloc(bytesToRead); - - if (buffer == NULL) - throw std::bad_alloc(); - - ssize_t result = TEMP_FAILURE_RETRY(read(m_fifo, buffer, bytesToRead)); - - if (result > 0) - { - // Succedded to read socket data - BinaryQueueAutoPtr binaryQueue(new BinaryQueue()); - - // Append unmanaged memory - binaryQueue->AppendUnmanaged(buffer, result, &BinaryQueue::BufferDeleterFree, NULL); - - // Return buffer - return binaryQueue; - } - else if (result == 0) - { - // Socket was gracefuly closed - free(buffer); - - // Return empty buffer - return BinaryQueueAutoPtr(new BinaryQueue()); - } - else - { - // Must first save errno value, because it may be altered - int lastErrno = errno; - - // Free buffer - free(buffer); - - // Interpret error result - (void)lastErrno; - - // FIXME: Handle specific errno - Throw(AbstractInput::Exception::ReadFailed); - } -} - -int NamedInputPipe::WaitableReadHandle() const -{ - return m_fifo; -} -} // namespace DPL diff --git a/modules/core/src/string.cpp b/modules/core/src/string.cpp index efb68c7..f03ccec 100644 --- a/modules/core/src/string.cpp +++ b/modules/core/src/string.cpp @@ -115,7 +115,6 @@ String FromUTF8String(const std::string& aIn) ThrowMsg(StringException::IconvConvertErrorUTF8ToUTF32, "iconv failed for " << "UTF-32 <- UTF-8" << "error: " << GetErrnoString()); - return String(); } // Ignore BOM in front of UTF-32 @@ -158,7 +157,6 @@ std::string ToUTF8String(const DPL::String& aIn) ThrowMsg(StringException::IconvConvertErrorUTF32ToUTF8, "iconv failed for " << "UTF-8 <- UTF-32" << "error: " << GetErrnoString()); - return std::string(); } return &output[0]; diff --git a/modules/core/src/thread.cpp b/modules/core/src/thread.cpp index 8dacad6..3974406 100644 --- a/modules/core/src/thread.cpp +++ b/modules/core/src/thread.cpp @@ -27,6 +27,7 @@ #include #include #include +#include namespace // anonymous { @@ -118,7 +119,12 @@ void *Thread::StaticThreadEntry(void *param) Assert(This != NULL); // Set thread specific - pthread_setspecific(g_threadSpecific.threadSpecific, This); + int result = pthread_setspecific(g_threadSpecific.threadSpecific, This); + + if (result!=0) + { + LogError("Failed to set threadSpecific. Error: " << strerror(result)); + } // Enter thread proc // Do not allow exceptions to hit pthread core diff --git a/modules/core/src/zip_input.cpp b/modules/core/src/zip_input.cpp index 8ce1201..691a2ec 100644 --- a/modules/core/src/zip_input.cpp +++ b/modules/core/src/zip_input.cpp @@ -29,7 +29,7 @@ #include #include #include -#include +#include #include #include #include @@ -304,7 +304,7 @@ ZipInput::ZipInput(const std::string &fileName) // Create master device LogPedantic("Creating master device"); - ScopedPtr device(new Device(fileName)); + std::unique_ptr device(new Device(fileName)); // Open master file zlib_filefunc64_def interface; @@ -315,7 +315,7 @@ ZipInput::ZipInput(const std::string &fileName) interface.zseek64_file = &Device::seek64_file; interface.zclose_file = &Device::close_file; interface.zerror_file = &Device::testerror_file; - interface.opaque = device.Get(); + interface.opaque = device.get(); LogPedantic("Opening zip file"); unzFile file = unzOpen2_64(NULL, &interface); @@ -339,7 +339,7 @@ ZipInput::ZipInput(const std::string &fileName) // Release scoped unz close m_masterFile = scopedUnzClose.Release(); - m_device = device.Release(); + m_device = device.release(); LogPedantic("Zip file opened"); } diff --git a/modules/custom_handler_dao/CMakeLists.txt b/modules/custom_handler_dao/CMakeLists.txt new file mode 100644 index 0000000..1afddd5 --- /dev/null +++ b/modules/custom_handler_dao/CMakeLists.txt @@ -0,0 +1,83 @@ +SET(TARGET_CUSTOM_HANDLER_DAO_DB "Sqlite3DbCustomHandler") + +ADD_CUSTOM_COMMAND( + OUTPUT ${CMAKE_BINARY_DIR}/modules/custom_handler_dao/database_checksum_custom_handler.h + COMMAND ${CMAKE_SOURCE_DIR}/modules/custom_handler_dao/orm/gen_db_md5.sh + ARGS ${CMAKE_BINARY_DIR}/modules/custom_handler_dao/database_checksum_custom_handler.h + ${CMAKE_SOURCE_DIR}/modules/custom_handler_dao/orm/custom_handler_db + DEPENDS ${CMAKE_SOURCE_DIR}/modules/custom_handler_dao/orm/custom_handler_db + ${CMAKE_SOURCE_DIR}/modules/custom_handler_dao/orm/gen_db_md5.sh + COMMENT "Generating WRT custom handlers database checksum" + ) + +ADD_CUSTOM_COMMAND( OUTPUT .wrt_custom_handler.db + COMMAND rm -f ${CMAKE_CURRENT_BINARY_DIR}/.wrt_custom_handler.db + COMMAND gcc -Wall -include ${CMAKE_BINARY_DIR}/modules/custom_handler_dao/database_checksum_custom_handler.h -I${PROJECT_SOURCE_DIR}/modules/db/include -I${PROJECT_SOURCE_DIR}/modules/custom_handler_dao/orm -E ${PROJECT_SOURCE_DIR}/modules/custom_handler_dao/orm/custom_handler_db_sql_generator.h | grep --invert-match "^#" > ${CMAKE_CURRENT_BINARY_DIR}/wrt_custom_handler_db.sql + COMMAND sqlite3 ${CMAKE_CURRENT_BINARY_DIR}/.wrt_custom_handler.db ".read ${CMAKE_CURRENT_BINARY_DIR}/wrt_custom_handler_db.sql" || rm -f ${CMAKE_CURRENT_BINARY_DIR}/.wrt_custom_handler.db + DEPENDS ${CMAKE_BINARY_DIR}/modules/custom_handler_dao/database_checksum_custom_handler.h ${PROJECT_SOURCE_DIR}/modules/custom_handler_dao/orm/custom_handler_db_sql_generator.h ${PROJECT_SOURCE_DIR}/modules/custom_handler_dao/orm/custom_handler_db + ) + +ADD_CUSTOM_COMMAND( OUTPUT .wrt_custom_handler.db-journal + COMMAND touch + ARGS ${CMAKE_CURRENT_BINARY_DIR}/.wrt_custom_handler.db-journal + ) + +ADD_CUSTOM_TARGET(${TARGET_CUSTOM_HANDLER_DAO_DB} ALL DEPENDS .wrt_custom_handler.db .wrt_custom_handler.db-journal) +INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/wrt_custom_handler_db.sql DESTINATION share/wrt-engine/) + +############################################################################### + +INCLUDE(FindPkgConfig) + +PKG_CHECK_MODULES(CUSTOM_HANDLER_DAO_DEPS + glib-2.0 + REQUIRED) + +SET(CUSTOM_HANDLER_DAO_INCLUDE_DIRS + ${PROJECT_SOURCE_DIR}/modules/custom_handler_dao/include + ${PROJECT_SOURCE_DIR}/modules/custom_handler_dao/orm + ${PROJECT_SOURCE_DIR}/modules/core/include + ${PROJECT_SOURCE_DIR}/modules/db/include + ${PROJECT_SOURCE_DIR}/modules/log/include +) + + +SET(CUSTOM_HANDLER_DAO_RO_SOURCES + dao/CustomHandlerDatabase.cpp + dao/custom_handler_dao_read_only.cpp +) + +SET(CUSTOM_HANDLER_DAO_RW_SOURCES + dao/custom_handler_dao.cpp +) + + +INCLUDE_DIRECTORIES(${CUSTOM_HANDLER_DAO_INCLUDE_DIRS}) +INCLUDE_DIRECTORIES(SYSTEM ${CUSTOM_HANDLER_DAO_DEPS_INCLUDE_DIRS}) + +ADD_LIBRARY(${TARGET_CUSTOM_HANDLER_DAO_RO_LIB} SHARED ${CUSTOM_HANDLER_DAO_RO_SOURCES}) +SET_TARGET_PROPERTIES(${TARGET_CUSTOM_HANDLER_DAO_RO_LIB} PROPERTIES SOVERSION ${API_VERSION} VERSION ${VERSION}) +SET_TARGET_PROPERTIES(${TARGET_CUSTOM_HANDLER_DAO_RO_LIB} PROPERTIES COMPILE_FLAGS "-include ${CMAKE_BINARY_DIR}/modules/custom_handler_dao/database_checksum_custom_handler.h") +TARGET_LINK_LIBRARIES(${TARGET_CUSTOM_HANDLER_DAO_RO_LIB} ${TARGET_CUSTOM_HANDLER_DAO_LIB}) +ADD_DEPENDENCIES(${TARGET_CUSTOM_HANDLER_DAO_RO_LIB} ${TARGET_CUSTOM_HANDLER_DAO_DB}) + +ADD_LIBRARY(${TARGET_CUSTOM_HANDLER_DAO_RW_LIB} SHARED ${CUSTOM_HANDLER_DAO_RW_SOURCES}) +SET_TARGET_PROPERTIES(${TARGET_CUSTOM_HANDLER_DAO_RW_LIB} PROPERTIES SOVERSION ${API_VERSION} VERSION ${VERSION}) +SET_TARGET_PROPERTIES(${TARGET_CUSTOM_HANDLER_DAO_RW_LIB} PROPERTIES COMPILE_FLAGS "-include ${CMAKE_BINARY_DIR}/modules/custom_handler_dao/database_checksum_custom_handler.h") +TARGET_LINK_LIBRARIES(${TARGET_CUSTOM_HANDLER_DAO_RW_LIB} ${TARGET_CUSTOM_HANDLER_DAO_RO_LIB}) +ADD_DEPENDENCIES(${TARGET_CUSTOM_HANDLER_DAO_RW_LIB} ${TARGET_CUSTOM_HANDLER_DAO_DB}) + +INSTALL(TARGETS ${TARGET_CUSTOM_HANDLER_DAO_RO_LIB} DESTINATION lib) +INSTALL(TARGETS ${TARGET_CUSTOM_HANDLER_DAO_RW_LIB} DESTINATION lib) + +INSTALL(FILES + include/wrt-commons/custom-handler-dao-ro/common_dao_types.h + include/wrt-commons/custom-handler-dao-ro/CustomHandlerDatabase.h + include/wrt-commons/custom-handler-dao-ro/custom_handler_dao_read_only.h + DESTINATION include/dpl-efl/wrt-commons/custom-handler-dao-ro +) + +INSTALL(FILES + include/wrt-commons/custom-handler-dao-rw/custom_handler_dao.h + DESTINATION include/dpl-efl/wrt-commons/custom-handler-dao-rw +) diff --git a/modules/custom_handler_dao/dao/CustomHandlerDatabase.cpp b/modules/custom_handler_dao/dao/CustomHandlerDatabase.cpp new file mode 100644 index 0000000..d0b26c5 --- /dev/null +++ b/modules/custom_handler_dao/dao/CustomHandlerDatabase.cpp @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 + +namespace CustomHandlerDB { +namespace Interface { + +namespace { +const char* CustomHandler_DB_DATABASE = "/opt/dbspace/.wrt_custom_handler.db"; +DPL::DB::SqlConnection::Flag::Type CustomHandler_DB_FLAGS = + DPL::DB::SqlConnection::Flag::UseLucene; +} + +DPL::Mutex g_dbQueriesMutex; +DPL::DB::ThreadDatabaseSupport g_dbInterface(CustomHandler_DB_DATABASE, + CustomHandler_DB_FLAGS); + +void attachDatabaseRO() +{ + g_dbInterface.AttachToThread(DPL::DB::SqlConnection::Flag::RO); +} + +void attachDatabaseRW() +{ + g_dbInterface.AttachToThread(DPL::DB::SqlConnection::Flag::RW); +} + +void detachDatabase() +{ + g_dbInterface.DetachFromThread(); +} + +} //namespace Interface +} //namespace CustomHandlerDB diff --git a/modules/custom_handler_dao/dao/custom_handler_dao.cpp b/modules/custom_handler_dao/dao/custom_handler_dao.cpp new file mode 100644 index 0000000..555655e --- /dev/null +++ b/modules/custom_handler_dao/dao/custom_handler_dao.cpp @@ -0,0 +1,300 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file custom_handler_dao.cpp + * @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) + * @version 1.0 + * @brief This file contains the definition of custom handler dao class. + */ + +#include +#include +#include +#include + +using namespace DPL::DB::ORM; +using namespace DPL::DB::ORM::custom_handler; + +namespace CustomHandlerDB { + +namespace { + +template +void fillRow(T& row, const CustomHandler& handler, const DPL::String& pkgName) +{ + row.Set_app_id(pkgName); + row.Set_target(handler.target); + row.Set_base_url(handler.base_url); + row.Set_url(handler.url); + row.Set_title(handler.title); + row.Set_user_allowed(handler.user_decision); +} + +} // namespace + +CustomHandlerDAO::CustomHandlerDAO(const DPL::String& pkgName) : + CustomHandlerDAOReadOnly(pkgName) +{ +} + +CustomHandlerDAO::~CustomHandlerDAO() +{ +} + +void CustomHandlerDAO::registerContentHandler(const CustomHandler& handler) +{ + LogDebug("Registering content handler " << handler.target << " " << + handler.base_url); + Try { + if (handler.user_decision & Agreed) { + //need to disable all previous, agreed entries + CUSTOM_HANDLER_DB_SELECT(select, ContentHandlers); + select->Where(And(Equals(handler.target), + Or(Equals(Agreed), + Equals(AgreedPermanently)) + )); + ContentHandlers::Select::RowList rows = select->GetRowList(); + if (rows.size() > 1) { + //more than one activ content handler - not good. Remove all. + //this should never happen + LogError("Database data incoherent."); + CUSTOM_HANDLER_DB_DELETE(deleteContent, ContentHandlers); + deleteContent->Where(And(Equals(handler.target), + Or(Equals(Agreed), + Equals(AgreedPermanently)))); + deleteContent->Execute(); + //all content handlers removed. New one can be inserted + } else if (!rows.empty()) { + //one active handler. Can be updaed + LogDebug("Activ content handler exist. Update"); + CUSTOM_HANDLER_DB_UPDATE(update, ContentHandlers); + update->Where(And(Equals(handler.target), + Or(Equals(Agreed), + Equals(AgreedPermanently)) + )); + ContentHandlers::Row rowToUpdate = rows.front(); + + if (handler.user_decision & DecisionSaved) { + //do not ask about previous one + rowToUpdate.Set_user_allowed(DeclinedPermanently); + } else { + //ask for next time + rowToUpdate.Set_user_allowed(Declined); + } + update->Values(rowToUpdate); + update->Execute(); + } + } + LogDebug("Inserting new content handler"); + ContentHandlers::Row row; + fillRow(row, handler, m_pkgName); + if (getContentHandler(handler.target, handler.url, handler.base_url)) { + LogDebug("Content handler exist. Update its state"); + CUSTOM_HANDLER_DB_UPDATE(updateRow, ContentHandlers); + updateRow->Where(And(Equals(m_pkgName), + And(Equals(handler.target), + And(Equals(handler.url), + Equals(handler.base_url))))); + updateRow->Values(row); + updateRow->Execute(); + LogDebug("updated"); + return; + } + CUSTOM_HANDLER_DB_INSERT(insert, ContentHandlers); + insert->Values(row); + insert->Execute(); + LogDebug("insterted"); + } + Catch(DPL::DB::SqlConnection::Exception::Base){ + ReThrowMsg(CustomHandlerDAO::Exception::DatabaseError, + "Failed to register custom handler"); + } +} + +void CustomHandlerDAO::registerProtocolHandler(const CustomHandler& handler) +{ + LogDebug("Registering protocol handler " << handler.target << " " << + handler.base_url); + Try { + + if (handler.user_decision & Agreed) { + //need to disable all previous, agreed entries + CUSTOM_HANDLER_DB_SELECT(select, ProtocolHandlers); + select->Where(And(Equals(handler.target), + Or(Equals(Agreed), + Equals(AgreedPermanently)) + )); + ProtocolHandlers::Select::RowList rows = select->GetRowList(); + if (rows.size() > 1) { + //more than one activ protocol handler - not good. Remove all. + //this should never happen + LogError("Database data incoherent."); + CUSTOM_HANDLER_DB_DELETE(deleteProtocol, ProtocolHandlers); + deleteProtocol->Where(And(Equals(handler.target), + Or(Equals(Agreed), + Equals(AgreedPermanently)))); + deleteProtocol->Execute(); + //all protocol handlers removed. New one can be inserted + } else if (!rows.empty()) { + //one active handler. Can be updaed + CUSTOM_HANDLER_DB_UPDATE(update, ProtocolHandlers); + update->Where(And(Equals(handler.target), + Or(Equals(Agreed), + Equals(AgreedPermanently)) + )); + ProtocolHandlers::Row rowToUpdate = rows.front(); + + if (handler.user_decision & DecisionSaved) { + //do not ask about previous one + rowToUpdate.Set_user_allowed(DeclinedPermanently); + } else { + //ask for next time + rowToUpdate.Set_user_allowed(Declined); + } + update->Values(rowToUpdate); + update->Execute(); + } + } + LogDebug("Inserting new protocol handler"); + ProtocolHandlers::Row row; + fillRow(row, handler, m_pkgName); + if (getProtocolHandler(handler.target, handler.url, handler.base_url)) { + LogDebug("Protocol handler exist. Update its state"); + CUSTOM_HANDLER_DB_UPDATE(updateRow, ProtocolHandlers); + updateRow->Where(And(Equals(m_pkgName), + And(Equals(handler.target), + And(Equals(handler.url), + Equals(handler.base_url))))); + updateRow->Values(row); + updateRow->Execute(); + LogDebug("updated"); + return; + } + CUSTOM_HANDLER_DB_INSERT(insert, ProtocolHandlers); + insert->Values(row); + insert->Execute(); + LogDebug("insterted"); + } + Catch(DPL::DB::SqlConnection::Exception::Base){ + ReThrowMsg(CustomHandlerDAO::Exception::DatabaseError, + "Failed to register custom handler"); + } +} + +void CustomHandlerDAO::unregisterContentHandler(const DPL::String& target, + const DPL::String& url) +{ + LogDebug("Removing content handler " << target << " " << url); + Try { + CUSTOM_HANDLER_DB_DELETE(deleteFrom, ContentHandlers); + deleteFrom->Where(And(Equals(m_pkgName), + And(Equals(target), + Equals(url)))); + deleteFrom->Execute(); + } + Catch(DPL::DB::SqlConnection::Exception::Base) { + ReThrowMsg(CustomHandlerDAO::Exception::DatabaseError, + "Failed to remove content handler"); + } +} + +void CustomHandlerDAO::unregisterProtocolHandler(const DPL::String& target, + const DPL::String& url) +{ + LogDebug("Removing protocol handler " << target << " " << url); + Try { + CUSTOM_HANDLER_DB_DELETE(deleteFrom, ProtocolHandlers); + deleteFrom->Where(And(Equals(m_pkgName), + And(Equals(target), + Equals(url)))); + deleteFrom->Execute(); + } + Catch(DPL::DB::SqlConnection::Exception::Base) { + ReThrowMsg(CustomHandlerDAO::Exception::DatabaseError, + "Failed to remove content handler"); + } + +} + +void CustomHandlerDAO::unregisterContentHandler(const DPL::String& target, + const DPL::String& url, + const DPL::String& baseURL) +{ + LogDebug("Removing content handler " << target << " " << url); + Try { + CUSTOM_HANDLER_DB_DELETE(deleteFrom, ContentHandlers); + deleteFrom->Where(And(Equals(m_pkgName), + And(Equals(target), + And(Equals(url), + Equals(baseURL))))); + deleteFrom->Execute(); + } + Catch(DPL::DB::SqlConnection::Exception::Base) { + ReThrowMsg(CustomHandlerDAO::Exception::DatabaseError, + "Failed to remove content handler"); + } +} + +void CustomHandlerDAO::unregisterProtocolHandler(const DPL::String& target, + const DPL::String& url, + const DPL::String& baseURL) +{ + LogDebug("Removing protocol handler " << target << " " << url); + Try { + CUSTOM_HANDLER_DB_DELETE(deleteFrom, ProtocolHandlers); + deleteFrom->Where(And(Equals(m_pkgName), + And(Equals(target), + And(Equals(url), + Equals(baseURL))))); + deleteFrom->Execute(); + } + Catch(DPL::DB::SqlConnection::Exception::Base) { + ReThrowMsg(CustomHandlerDAO::Exception::DatabaseError, + "Failed to remove content handler"); + } + +} + +void CustomHandlerDAO::removeWidgetProtocolHandlers() +{ + LogDebug("ente"); + Try { + CUSTOM_HANDLER_DB_DELETE(deleteProtocol, ProtocolHandlers); + deleteProtocol->Where(Equals(m_pkgName)); + deleteProtocol->Execute(); + + } Catch(DPL::DB::SqlConnection::Exception::Base) { + ReThrowMsg(CustomHandlerDAO::Exception::DatabaseError, + "Failed to remove widget protoc"); + } +} + +void CustomHandlerDAO::removeWidgetContentHandlers() +{ + LogDebug("ente"); + Try { + CUSTOM_HANDLER_DB_DELETE(deleteContent, ContentHandlers); + deleteContent->Where(Equals(m_pkgName)); + deleteContent->Execute(); + + } Catch(DPL::DB::SqlConnection::Exception::Base) { + ReThrowMsg(CustomHandlerDAO::Exception::DatabaseError, + "Failed to remove widget entries"); + } +} + + +} // namespace CustomHandlerDB diff --git a/modules/custom_handler_dao/dao/custom_handler_dao_read_only.cpp b/modules/custom_handler_dao/dao/custom_handler_dao_read_only.cpp new file mode 100644 index 0000000..a7159fa --- /dev/null +++ b/modules/custom_handler_dao/dao/custom_handler_dao_read_only.cpp @@ -0,0 +1,264 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This file contains the declaration of custom handler dao class. + * + * @file custom_handler_dao_read_only.cpp + * @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) + * @version 1.0 + * @brief This file contains the declaration of custom handler dao + */ + +#include +#include + +#include + +using namespace DPL::DB::ORM; +using namespace DPL::DB::ORM::custom_handler; + +namespace CustomHandlerDB { + +namespace { + +template +CustomHandlerPtr getSingleHandler(std::list row) +{ + CustomHandlerPtr handler; + if (!row.empty()) { + // There should be only one + if (row.size() > 1) { + ThrowMsg(CustomHandlerDAOReadOnly::Exception::DatabaseError, + "More than one handler registered"); + } + + handler.reset(new CustomHandler()); + handler->target = row.front().Get_target(); + handler->base_url = row.front().Get_base_url(); + handler->url = row.front().Get_url(); + handler->title = row.front().Get_title(); + handler->user_allowed = static_cast(row.front().Get_user_allowed()); + handler->user_decision = + static_cast(row.front().Get_user_allowed()); + } + return handler; +} + +} // namespace + +CustomHandlerDAOReadOnly::CustomHandlerDAOReadOnly(const DPL::String& pkgName) : + m_pkgName(pkgName) +{ +} + +CustomHandlerDAOReadOnly::~CustomHandlerDAOReadOnly() +{ +} + +CustomHandlerPtr CustomHandlerDAOReadOnly::getProtocolHandler( + const DPL::String& protocol, + const DPL::String& url) +{ + LogDebug("Getting protocol handler"); + Try{ + CUSTOM_HANDLER_DB_SELECT(select, ProtocolHandlers); + + select->Where(And(Equals(m_pkgName), + And(Equals(protocol), + Equals(url)))); + + std::list list = select->GetRowList(); + return getSingleHandler(list); + } Catch(DPL::DB::SqlConnection::Exception::Base) { + ReThrowMsg(CustomHandlerDAOReadOnly::Exception::DatabaseError, + "Failed to get protocol handler"); + } +} + +CustomHandlerPtr CustomHandlerDAOReadOnly::getContentHandler( + const DPL::String& content, + const DPL::String& url) +{ + LogDebug("Getting content handler"); + Try{ + CUSTOM_HANDLER_DB_SELECT(select, ContentHandlers); + + select->Where(And(Equals(m_pkgName), + And(Equals(content), + Equals(url)))); + + std::list list = select->GetRowList(); + return getSingleHandler(list); + } Catch(DPL::DB::SqlConnection::Exception::Base) { + ReThrowMsg(CustomHandlerDAOReadOnly::Exception::DatabaseError, + "Failed to get content handler"); + } +} + +CustomHandlerPtr CustomHandlerDAOReadOnly::getActivProtocolHandler( + const DPL::String& protocol) +{ + LogDebug("Getting active protocol handler"); + Try{ + CUSTOM_HANDLER_DB_SELECT(select, ProtocolHandlers); + + select->Where(And(Equals(m_pkgName), + Equals(protocol))); + + std::list list = select->GetRowList(); + CustomHandlerPtr handler; + + FOREACH(it, list) { + if (it->Get_user_allowed() & Agreed) { + handler.reset(new CustomHandler()); + handler->base_url = it->Get_base_url(); + handler->target = it->Get_target(); + handler->title = it->Get_title(); + handler->url = it->Get_url(); + handler->user_allowed = + static_cast(it->Get_user_allowed()); + handler->user_decision = + static_cast(it->Get_user_allowed()); + } + } + return handler; + } Catch(DPL::DB::SqlConnection::Exception::Base) { + ReThrowMsg(CustomHandlerDAOReadOnly::Exception::DatabaseError, + "Failed to get protocol handler"); + } +} + +CustomHandlerPtr CustomHandlerDAOReadOnly::getProtocolHandler( + const DPL::String& protocol, + const DPL::String& url, + const DPL::String& baseURL) +{ + LogDebug("Check if protocol is registered"); + Try{ + CUSTOM_HANDLER_DB_SELECT(select, ProtocolHandlers); + + select->Where(And(Equals(m_pkgName), + And(Equals(protocol), + And(Equals(url), + Equals(baseURL) + ) + ) + ) + ); + + std::list list = select->GetRowList(); + return getSingleHandler(list); + } Catch(DPL::DB::SqlConnection::Exception::Base) { + ReThrowMsg(CustomHandlerDAOReadOnly::Exception::DatabaseError, + "Failed to get content handler"); + } +} + + +CustomHandlerPtr CustomHandlerDAOReadOnly::getActivContentHandler( + const DPL::String& content) +{ + LogDebug("Getting active content handler"); + Try{ + CUSTOM_HANDLER_DB_SELECT(select, ContentHandlers); + + select->Where(And(Equals(m_pkgName), + Equals(content))); + + std::list list = select->GetRowList(); + CustomHandlerPtr handler; + + FOREACH(it, list) { + if (it->Get_user_allowed() & Agreed) { + handler.reset(new CustomHandler()); + handler->base_url = it->Get_base_url(); + handler->target = it->Get_target(); + handler->title = it->Get_title(); + handler->url = it->Get_url(); + handler->user_allowed = + static_cast(it->Get_user_allowed()); + handler->user_decision = + static_cast(it->Get_user_allowed()); + } + } + return handler; + } Catch(DPL::DB::SqlConnection::Exception::Base) { + ReThrowMsg(CustomHandlerDAOReadOnly::Exception::DatabaseError, + "Failed to get protocol handler"); + } +} + +CustomHandlerPtr CustomHandlerDAOReadOnly::getContentHandler( + const DPL::String& content, + const DPL::String& url, + const DPL::String& baseURL) +{ + LogDebug("Check if content is registered"); + Try{ + CUSTOM_HANDLER_DB_SELECT(select, ContentHandlers); + + select->Where(And(Equals(m_pkgName), + And(Equals(content), + And(Equals(url), + Equals(baseURL))))); + + std::list list = select->GetRowList(); + return getSingleHandler(list); + } Catch(DPL::DB::SqlConnection::Exception::Base) { + ReThrowMsg(CustomHandlerDAOReadOnly::Exception::DatabaseError, + "Failed to get content handler"); + } +} + +CustomHandlerPtr CustomHandlerDAOReadOnly::getAllowedProtocolHandler( + const DPL::String& protocol) +{ + LogDebug("Getting allowed protocol handler"); + Try{ + CUSTOM_HANDLER_DB_SELECT(select, ProtocolHandlers); + + select->Where(And(Equals(m_pkgName), + And(Equals(protocol), + Equals(true)))); + + std::list list = select->GetRowList(); + return getSingleHandler(list); + } Catch(DPL::DB::SqlConnection::Exception::Base) { + ReThrowMsg(CustomHandlerDAOReadOnly::Exception::DatabaseError, + "Failed to get content handler"); + } +} + +CustomHandlerPtr CustomHandlerDAOReadOnly::getAllowedContentHandler( + const DPL::String& protocol) +{ + LogDebug("Getting allowed content handler"); + Try{ + CUSTOM_HANDLER_DB_SELECT(select, ContentHandlers) + + select->Where(And(Equals(m_pkgName), + And(Equals(protocol), + Equals(true)))); + + std::list list = select->GetRowList(); + return getSingleHandler(list); + } Catch(DPL::DB::SqlConnection::Exception::Base) { + ReThrowMsg(CustomHandlerDAOReadOnly::Exception::DatabaseError, + "Failed to get content handler"); + } +} + +} // namespace CustomHandlerDB diff --git a/modules/custom_handler_dao/include/wrt-commons/custom-handler-dao-ro/CustomHandlerDatabase.h b/modules/custom_handler_dao/include/wrt-commons/custom-handler-dao-ro/CustomHandlerDatabase.h new file mode 100644 index 0000000..fea6309 --- /dev/null +++ b/modules/custom_handler_dao/include/wrt-commons/custom-handler-dao-ro/CustomHandlerDatabase.h @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 _CUSTOM_HANDLER_DATABASE_H_ +#define _CUSTOM_HANDLER_DATABASE_H_ + +#include +#include +#include + +namespace CustomHandlerDB { +namespace Interface { + +void attachDatabaseRO(); +void attachDatabaseRW(); +void detachDatabase(); + +extern DPL::Mutex g_dbQueriesMutex; +extern DPL::DB::ThreadDatabaseSupport g_dbInterface; + +} // namespace Interface +} // namespace CustomHandlerDB + +#define CUSTOM_HANDLER_DB_INTERNAL(tlsCommand, InternalType) \ + static DPL::ThreadLocalVariable *tlsCommand ## Ptr = NULL; \ + { \ + DPL::Mutex::ScopedLock lock( \ + &CustomHandlerDB::Interface::g_dbQueriesMutex); \ + if (!tlsCommand ## Ptr) { \ + static DPL::ThreadLocalVariable tmp; \ + tlsCommand ## Ptr = &tmp; \ + } \ + } \ + DPL::ThreadLocalVariable &tlsCommand = *tlsCommand ## Ptr; \ + if (tlsCommand.IsNull()) \ + { \ + tlsCommand = InternalType(&CustomHandlerDB::Interface::g_dbInterface); \ + } + +#define CUSTOM_HANDLER_DB_SELECT(name, type) \ + CUSTOM_HANDLER_DB_INTERNAL(name, type::Select) + +#define CUSTOM_HANDLER_DB_INSERT(name, type) \ + CUSTOM_HANDLER_DB_INTERNAL(name, type::Insert) + +#define CUSTOM_HANDLER_DB_UPDATE(name, type) \ + CUSTOM_HANDLER_DB_INTERNAL(name, type::Update) + +#define CUSTOM_HANDLER_DB_DELETE(name, type) \ + CUSTOM_HANDLER_DB_INTERNAL(name, type::Delete) + +#endif /* _CUSTOM_HANDLER_DATABASE_H_ */ + diff --git a/modules/custom_handler_dao/include/wrt-commons/custom-handler-dao-ro/common_dao_types.h b/modules/custom_handler_dao/include/wrt-commons/custom-handler-dao-ro/common_dao_types.h new file mode 100644 index 0000000..b08142a --- /dev/null +++ b/modules/custom_handler_dao/include/wrt-commons/custom-handler-dao-ro/common_dao_types.h @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file common_dao_types.h + * @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) + * @version 1.0 + * @brief This file contains the declaration of + * common data types for custom handler database. + */ +#ifndef SRC_MODULES_CUSTOM_HANDLERS_DAO_COMMON_DAO_TYPES_H_ +#define SRC_MODULES_CUSTOM_HANDLERS_DAO_COMMON_DAO_TYPES_H_ + +#include +#include +#include + +namespace CustomHandlerDB { + +/** + * @brief Custom Handler struct + * + * Describes custom handler for protocol and content. + */ +enum HandlerState { + Agreed = 0x01, //user agreed to use protocol only, + //but want to ask in next occurence + Declined = 0x02, //user declined to use protocol, + //but want to ask in next occurence + //in fact it is used when user wants to cover saved agreed + //decision by agreeing to another one without save. + DecisionSaved = 0x04, //user dont want to ask again + AgreedPermanently = Agreed | DecisionSaved, + DeclinedPermanently = Declined | DecisionSaved +}; + +struct CustomHandler +{ + DPL::String target; // protocol/content ("mailto"/"application/x-soup") + DPL::String base_url; // base url of registered page + DPL::String url; // url used for protocol/content handling + DPL::String title; // user friendly handler name + bool user_allowed; // true if user has allowed the handler + HandlerState user_decision; +}; + +typedef std::shared_ptr CustomHandlerPtr; +typedef std::list CustomHandlersList; + +} // namespace CustomHandlerDB + +#endif /* SRC_MODULES_CUSTOM_HANDLERS_DAO_COMMON_DAO_TYPES_H_ */ diff --git a/modules/custom_handler_dao/include/wrt-commons/custom-handler-dao-ro/custom_handler_dao_read_only.h b/modules/custom_handler_dao/include/wrt-commons/custom-handler-dao-ro/custom_handler_dao_read_only.h new file mode 100644 index 0000000..88c720d --- /dev/null +++ b/modules/custom_handler_dao/include/wrt-commons/custom-handler-dao-ro/custom_handler_dao_read_only.h @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This file contains the declaration of custom handler dao class. + * + * @file custom_handler_dao_read_only.h + * @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) + * @version 1.0 + * @brief This file contains the declaration of custom handler dao + */ + +#ifndef _CUSTOM_HANDLER_DAO_READ_ONLY_H_ +#define _CUSTOM_HANDLER_DAO_READ_ONLY_H_ + +#include +#include +#include "common_dao_types.h" + +namespace CustomHandlerDB { + +class CustomHandlerDAOReadOnly +{ + public: + /** + * CustomHandlerDAOReadOnly Exception classes + */ + class Exception + { + public: + DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) + DECLARE_EXCEPTION_TYPE(Base, DatabaseError) + }; + + public: + explicit CustomHandlerDAOReadOnly(const DPL::String& pkgName); + virtual ~CustomHandlerDAOReadOnly(); + + /** + * Returns protocol handler + */ + CustomHandlerPtr getProtocolHandler(const DPL::String& protocol, + const DPL::String& url); + CustomHandlerPtr getProtocolHandler(const DPL::String& protocol, + const DPL::String& url, + const DPL::String& baseURL); + + /** + * Returns protocol handler that is agreed or agreed and saved and match tizenID + */ + CustomHandlerPtr getActivProtocolHandler(const DPL::String& protocol); + + + + /** + * Returns content handler + */ + CustomHandlerPtr getContentHandler(const DPL::String& content, + const DPL::String& url); + CustomHandlerPtr getContentHandler(const DPL::String& protocol, + const DPL::String& url, + const DPL::String& baseURL); + + /** + * Returns content handler that is agreed or agreed and saved and match tizenID + */ + CustomHandlerPtr getActivContentHandler(const DPL::String& content); + + /** + * Returns allowed handler for given protocol + */ + CustomHandlerPtr getAllowedProtocolHandler(const DPL::String& protocol); + + /** + * Returns allowed handler for given content + */ + CustomHandlerPtr getAllowedContentHandler(const DPL::String& protocol); + + protected: + DPL::String m_pkgName; +}; + +} // namespace CustomHandlerDB + +#endif // _CUSTOM_HANDLER_DAO_READ_ONLY_H_ + diff --git a/modules/custom_handler_dao/include/wrt-commons/custom-handler-dao-rw/custom_handler_dao.h b/modules/custom_handler_dao/include/wrt-commons/custom-handler-dao-rw/custom_handler_dao.h new file mode 100644 index 0000000..1ce61cf --- /dev/null +++ b/modules/custom_handler_dao/include/wrt-commons/custom-handler-dao-rw/custom_handler_dao.h @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This file contains the declaration of custom handler dao class. + * + * @file custom_handler_dao.h + * @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) + * @version 1.0 + * @brief This file contains the declaration of custom handler dao + */ +#ifndef _CUSTOM_HANDLER_DAO_H_ +#define _CUSTOM_HANDLER_DAO_H_ + +#include + +namespace CustomHandlerDB { + +class CustomHandlerDAO : public CustomHandlerDAOReadOnly +{ + public: + explicit CustomHandlerDAO(const DPL::String& pkgName); + virtual ~CustomHandlerDAO(); + + /** + * Registers custom content handler + */ + void registerContentHandler(const CustomHandler& handler); + + /** + * Registers custom protocol handler + */ + void registerProtocolHandler(const CustomHandler& handler); + + /** + * Unregisters custom content handler + */ + void unregisterContentHandler(const DPL::String& target, + const DPL::String& burl); + /** + * Unregisters custom protocol handler + */ + void unregisterProtocolHandler(const DPL::String& target, + const DPL::String& url); + + void unregisterContentHandler(const DPL::String& target, + const DPL::String& url, + const DPL::String& baseURL); + + void unregisterProtocolHandler(const DPL::String& target, + const DPL::String& url, + const DPL::String& baseURL); + + /** + * Removes all widget entries connected to given ID + */ + void removeWidgetProtocolHandlers(); + void removeWidgetContentHandlers(); +}; + +} // namespace CustomHandlerDB + +#endif // _CUSTOM_HANDLER_DAO_H_ diff --git a/modules/custom_handler_dao/orm/custom_handler_db b/modules/custom_handler_dao/orm/custom_handler_db new file mode 100644 index 0000000..848c84a --- /dev/null +++ b/modules/custom_handler_dao/orm/custom_handler_db @@ -0,0 +1,34 @@ +SQL( + BEGIN TRANSACTION; +) + +CREATE_TABLE(ProtocolHandlers) + COLUMN_NOT_NULL(app_id, TEXT,) + COLUMN_NOT_NULL(target, TEXT,) + COLUMN_NOT_NULL(base_url, TEXT,) + COLUMN_NOT_NULL(url, TEXT,) + COLUMN_NOT_NULL(title, TEXT,) + COLUMN_NOT_NULL(user_allowed, INT,) + + TABLE_CONSTRAINTS( + PRIMARY KEY (app_id, target, base_url, url) + ) +CREATE_TABLE_END() + +CREATE_TABLE(ContentHandlers) + COLUMN_NOT_NULL(app_id, TEXT,) + COLUMN_NOT_NULL(target, TEXT,) + COLUMN_NOT_NULL(base_url, TEXT,) + COLUMN_NOT_NULL(url, TEXT,) + COLUMN_NOT_NULL(title, TEXT,) + COLUMN_NOT_NULL(user_allowed, INT,) + + TABLE_CONSTRAINTS( + PRIMARY KEY (app_id, target, base_url, url) + ) +CREATE_TABLE_END() + +SQL( + COMMIT; +) + diff --git a/modules/custom_handler_dao/orm/custom_handler_db_definitions b/modules/custom_handler_dao/orm/custom_handler_db_definitions new file mode 100644 index 0000000..1bc2bcd --- /dev/null +++ b/modules/custom_handler_dao/orm/custom_handler_db_definitions @@ -0,0 +1,6 @@ +DATABASE_START(custom_handler) + +#include "custom_handler_db" +#include "version_db" + +DATABASE_END() diff --git a/modules/custom_handler_dao/orm/custom_handler_db_sql_generator.h b/modules/custom_handler_dao/orm/custom_handler_db_sql_generator.h new file mode 100644 index 0000000..9b007de --- /dev/null +++ b/modules/custom_handler_dao/orm/custom_handler_db_sql_generator.h @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file custom_handler_db_sql_generator.h + * @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) + * @version 1.0 + * @brief Macro definitions for generating the SQL + * input file from database definition. + */ + +//Do not include this file directly! It is used only for SQL code generation. +#include + +#include "custom_handler_db_definitions" diff --git a/modules/custom_handler_dao/orm/gen_db_md5.sh b/modules/custom_handler_dao/orm/gen_db_md5.sh new file mode 100755 index 0000000..22c2530 --- /dev/null +++ b/modules/custom_handler_dao/orm/gen_db_md5.sh @@ -0,0 +1,19 @@ +#!/bin/sh +# Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +CHECKSUM=`cat ${2} ${3} 2>/dev/null | md5sum 2>/dev/null | cut -d\ -f1 2>/dev/null` +echo "#define DB_CHECKSUM DB_VERSION_${CHECKSUM}" > ${1} +echo "#define DB_CHECKSUM_STR \"DB_VERSION_${CHECKSUM}\"" >> ${1} + diff --git a/modules/custom_handler_dao/orm/orm_generator_custom_handler.h b/modules/custom_handler_dao/orm/orm_generator_custom_handler.h new file mode 100644 index 0000000..35c43a2 --- /dev/null +++ b/modules/custom_handler_dao/orm/orm_generator_custom_handler.h @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 _ORM_GENERATOR_CUSTOM_HANDLER_H_ +#define _ORM_GENERATOR_CUSTOM_HANDLER_H_ + +#define ORM_GENERATOR_DATABASE_NAME custom_handler_db_definitions +#include +#undef ORM_GENERATOR_DATABASE_NAME + +#endif // _ORM_GENERATOR_CUSTOM_HANDLER_H_ diff --git a/modules/custom_handler_dao/orm/version_db b/modules/custom_handler_dao/orm/version_db new file mode 100644 index 0000000..7e20d8d --- /dev/null +++ b/modules/custom_handler_dao/orm/version_db @@ -0,0 +1,5 @@ +SQL( + BEGIN TRANSACTION; + CREATE TABLE DB_CHECKSUM (version INT); + COMMIT; +) diff --git a/modules/db/include/dpl/db/orm.h b/modules/db/include/dpl/db/orm.h index 64c0705..c404fba 100644 --- a/modules/db/include/dpl/db/orm.h +++ b/modules/db/include/dpl/db/orm.h @@ -26,12 +26,12 @@ #include #include #include +#include #include #include #include #include -#include #include #include #include @@ -84,7 +84,7 @@ public: virtual ArgumentIndex BindTo(DataCommand *command, ArgumentIndex index) = 0; }; -typedef DPL::SharedPtr ExpressionPtr; +typedef std::shared_ptr ExpressionPtr; template class __attribute__ ((visibility("hidden"))) BinaryExpression : public Expression { @@ -128,6 +128,14 @@ BinaryExpression (leftExpression, rightExpression); } +template +BinaryExpression + Or(const LeftExpression& leftExpression, const RightExpression& rightExpression) +{ + return BinaryExpression + (leftExpression, rightExpression); +} + template class __attribute__ ((visibility("hidden"))) ExpressionWithArgument : public Expression { protected: @@ -586,7 +594,7 @@ public: str.str()); } //TODO maybe don't make a copy here but just generate the string part of the query. - m_whereExpression.Reset(new Expression(expression)); + m_whereExpression.reset(new Expression(expression)); } }; @@ -632,6 +640,29 @@ public: } }; +namespace { +class BindVisitor { +private: + DataCommand *m_command; +public: + ArgumentIndex m_bindArgumentIndex; + + BindVisitor(DataCommand *command) : + m_command(command), + m_bindArgumentIndex(1) + {} + + template + void Visit(const char*, const ColumnType& value, bool isSet) + { + if ( isSet ) + { + DataCommandUtils::BindArgument(m_command, m_bindArgumentIndex, value); + m_bindArgumentIndex++; + } + } +}; +} //anonymous namespace template class __attribute__ ((visibility("hidden"))) Insert : public Query { @@ -689,27 +720,6 @@ protected: } } - class BindVisitor { - private: - DataCommand *m_command; - ArgumentIndex m_bindArgumentIndex; - public: - BindVisitor(DataCommand *command) : - m_command(command), - m_bindArgumentIndex(1) - {} - - template - void Visit(const char*, const ColumnType& value, bool isSet) - { - if ( isSet ) - { - DataCommandUtils::BindArgument(m_command, m_bindArgumentIndex, value); - m_bindArgumentIndex++; - } - } - }; - void Bind() { BindVisitor visitor(this->m_command); @@ -999,29 +1009,6 @@ protected: } } - class BindVisitor { - private: - DataCommand *m_command; - - public: - ArgumentIndex m_bindArgumentIndex; - - BindVisitor(DataCommand *command) : - m_command(command), - m_bindArgumentIndex(1) - {} - - template - void Visit(const char*, const ColumnType& value, bool isSet) - { - if ( isSet ) - { - DataCommandUtils::BindArgument(m_command, m_bindArgumentIndex, value); - m_bindArgumentIndex++; - } - } - }; - void Bind() { BindVisitor visitor(this->m_command); diff --git a/modules/db/include/dpl/db/sql_connection.h b/modules/db/include/dpl/db/sql_connection.h index f973772..f1b3b62 100644 --- a/modules/db/include/dpl/db/sql_connection.h +++ b/modules/db/include/dpl/db/sql_connection.h @@ -25,7 +25,7 @@ #include #include #include -#include +#include #include #include #include @@ -423,7 +423,7 @@ protected: int m_dataCommandsCount; // Synchronization object - ScopedPtr m_synchronizationObject; + std::unique_ptr m_synchronizationObject; virtual void Connect(const std::string &address, Flag::Type = Flag::None, Flag::Option = Flag::RO); diff --git a/modules/db/src/sql_connection.cpp b/modules/db/src/sql_connection.cpp index 26fb815..d1b44dd 100644 --- a/modules/db/src/sql_connection.cpp +++ b/modules/db/src/sql_connection.cpp @@ -69,7 +69,7 @@ SqlConnection::DataCommand::DataCommand(SqlConnection *connection, Assert(connection != NULL); // Notify all after potentially synchronized database connection access - ScopedNotifyAll notifyAll(connection->m_synchronizationObject.Get()); + ScopedNotifyAll notifyAll(connection->m_synchronizationObject.get()); for (;;) { @@ -324,7 +324,7 @@ bool SqlConnection::DataCommand::Step() { // Notify all after potentially synchronized database connection access ScopedNotifyAll notifyAll( - m_masterConnection->m_synchronizationObject.Get()); + m_masterConnection->m_synchronizationObject.get()); for (;;) { @@ -765,7 +765,7 @@ void SqlConnection::ExecCommand(const char *format, ...) LogPedantic("Executing SQL command: " << buffer.Get()); // Notify all after potentially synchronized database connection access - ScopedNotifyAll notifyAll(m_synchronizationObject.Get()); + ScopedNotifyAll notifyAll(m_synchronizationObject.get()); for (;;) { diff --git a/modules/encryption/include/dpl/encryption/resource_decryption.h b/modules/encryption/include/dpl/encryption/resource_decryption.h index c22b1d2..2a39eb1 100644 --- a/modules/encryption/include/dpl/encryption/resource_decryption.h +++ b/modules/encryption/include/dpl/encryption/resource_decryption.h @@ -28,8 +28,9 @@ #include #include -namespace WRTDecryptor{ +extern char** calculate(char*pappId, int idLen, int keyLen); +namespace WRTDecryptor{ class ResourceDecryptor { public: @@ -50,7 +51,7 @@ class ResourceDecryptor private: AES_KEY* GetDecryptionKey(); - AES_KEY *m_decKey; + AES_KEY m_decKey; }; } //namespace WRTDecryptor diff --git a/modules/encryption/include/dpl/encryption/resource_encryption.h b/modules/encryption/include/dpl/encryption/resource_encryption.h index ffc82c2..6f57a93 100644 --- a/modules/encryption/include/dpl/encryption/resource_encryption.h +++ b/modules/encryption/include/dpl/encryption/resource_encryption.h @@ -28,8 +28,9 @@ #include #include -namespace WRTEncryptor{ +extern char** calculate(char*pappId, int idLen, int keyLen); +namespace WRTEncryptor{ class ResourceEncryptor { public: diff --git a/modules/encryption/src/resource_decryption.cpp b/modules/encryption/src/resource_decryption.cpp index db45f81..9e8b39f 100644 --- a/modules/encryption/src/resource_decryption.cpp +++ b/modules/encryption/src/resource_decryption.cpp @@ -28,19 +28,16 @@ #include namespace { -inline std::string GetDefaultEncryptKeyPath() { - return "/opt/share/widget/data/"; -} +#define BITS_SIZE 128 +#define KEY_SIZE 16 } namespace WRTDecryptor{ -ResourceDecryptor::ResourceDecryptor() : - m_decKey(NULL) +ResourceDecryptor::ResourceDecryptor() { LogDebug("Started Decryption"); } -ResourceDecryptor::ResourceDecryptor(std::string userKey) : - m_decKey(NULL) +ResourceDecryptor::ResourceDecryptor(std::string userKey) { LogDebug("Finished Decryption"); SetDecryptionKey(userKey); @@ -48,47 +45,39 @@ ResourceDecryptor::ResourceDecryptor(std::string userKey) : ResourceDecryptor::~ResourceDecryptor() { - delete m_decKey; } void ResourceDecryptor::SetDecryptionKey(std::string userKey) { - /* TODO : get key from secure storage */ - std::string keyPath = GetDefaultEncryptKeyPath() + userKey + "_dec"; - LogDebug("Description Key path : " << keyPath); - - FILE* fp = fopen(keyPath.c_str(), "rb"); - if (fp == NULL) { - ThrowMsg(ResourceDecryptor::Exception::GetDecKeyFailed, - "Failed to get decryption key"); + if (userKey.empty()) { + return; } - m_decKey = new AES_KEY; - size_t resultSize =fread(m_decKey, 1, sizeof(AES_KEY),fp); - if (resultSize!= sizeof(AES_KEY)) - ThrowMsg(ResourceDecryptor::Exception::GetDecKeyFailed, - "Failed to get AES key"); + char **duk = calculate(const_cast(userKey.c_str()), userKey.size(), KEY_SIZE); + unsigned char *key = reinterpret_cast(*duk); - fclose(fp); + if ( 0 > AES_set_decrypt_key(key, BITS_SIZE, &m_decKey)) { + ThrowMsg(ResourceDecryptor::Exception::GetDecKeyFailed, + "Failed to create decryption key"); + } } AES_KEY* ResourceDecryptor::GetDecryptionKey() { - return m_decKey; + return &m_decKey; } void ResourceDecryptor::GetDecryptedChunk(unsigned char* inBuf, unsigned char* decBuf, size_t inBufSize) { Assert(decBuf); - Assert(m_decKey); - if (decBuf == NULL || m_decKey == NULL) { + if (decBuf == NULL) { ThrowMsg(ResourceDecryptor::Exception::EncryptionFailed, "Failed to Get Decryption Chunk"); } unsigned char ivec[16] = {0, }; - AES_cbc_encrypt(inBuf, decBuf, inBufSize, m_decKey, ivec, AES_DECRYPT); + AES_cbc_encrypt(inBuf, decBuf, inBufSize, &m_decKey, ivec, AES_DECRYPT); LogDebug("Success decryption"); } diff --git a/modules/encryption/src/resource_encryption.cpp b/modules/encryption/src/resource_encryption.cpp index e89940e..a238705 100644 --- a/modules/encryption/src/resource_encryption.cpp +++ b/modules/encryption/src/resource_encryption.cpp @@ -27,12 +27,7 @@ namespace { #define BITS_SIZE 128 -const char* ENCRYPTION_FILE = "_enc"; -const char* DECRYPTION_FILE = "_dec"; - -inline std::string GetDefaultEncryptKeyPath() { - return "/opt/share/widget/data"; -} +#define KEY_SIZE 16 } namespace WRTEncryptor{ ResourceEncryptor::ResourceEncryptor() @@ -59,44 +54,13 @@ void ResourceEncryptor::CreateEncryptionKey(std::string userKey) return; } - AES_KEY decKey; - const unsigned char* key = reinterpret_cast( - const_cast(userKey.c_str())); + char **duk = calculate(const_cast(userKey.c_str()), userKey.size(), KEY_SIZE); + unsigned char *key = reinterpret_cast(*duk); if ( 0 > AES_set_encrypt_key(key, BITS_SIZE, &m_encKey)) { ThrowMsg(ResourceEncryptor::Exception::CreateEncKeyFailed, "Failed to create encryption key"); } - if ( 0 > AES_set_decrypt_key(key, BITS_SIZE, &decKey)) { - ThrowMsg(ResourceEncryptor::Exception::CreateDecKeyFailed, - "Failed to create decryption key"); - } - - std::string encPath, decPath; - - encPath = GetDefaultEncryptKeyPath() + "/" + userKey + ENCRYPTION_FILE; - decPath = GetDefaultEncryptKeyPath() + "/" + userKey + DECRYPTION_FILE; - - /* TODO : save keys to secure storage */ - LogDebug("Encryption Key path " << encPath); - LogDebug("Decryption Key path " << decPath); - - FILE* encFp = fopen(encPath.c_str(), "wb"); - if (encFp == NULL) { - ThrowMsg(ResourceEncryptor::Exception::CreateEncKeyFileFailed, - "Failed to save encryption key"); - } - fwrite(&m_encKey, 1, sizeof(m_encKey), encFp); - fclose(encFp); - - FILE* decFp = fopen(decPath.c_str(), "wb"); - if (decFp == NULL) { - ThrowMsg(ResourceEncryptor::Exception::CreateDecKeyFileFailed, - "Failed to save decryption key"); - } - - fwrite(&decKey, 1, sizeof(decKey), decFp); - fclose(decFp); LogDebug("Success to create ecryption and decryption key"); } diff --git a/modules/event/include/dpl/event/event_support.h b/modules/event/include/dpl/event/event_support.h index 3aaab81..2e8cfb2 100644 --- a/modules/event/include/dpl/event/event_support.h +++ b/modules/event/include/dpl/event/event_support.h @@ -29,7 +29,7 @@ #include #include #include -#include +#include #include #include #include @@ -364,7 +364,7 @@ protected: double dueTime = 0.0) { // Emit event, and retrieve later in current context to dispatch - ScopedPtr lock( + std::unique_ptr lock( new Mutex::ScopedLock(&m_listenerDelegateMutex)); // Show some info @@ -583,7 +583,7 @@ protected: if (!synchronizationBarrier.empty()) { LogPedantic("Leaving lock due to existing barrier"); - lock.Reset(); + lock.reset(); } LogPedantic("Size of barrier: " << synchronizationBarrier.size()); diff --git a/modules/event/include/dpl/event/inter_context_delegate.h b/modules/event/include/dpl/event/inter_context_delegate.h index 55af651..78efd5f 100644 --- a/modules/event/include/dpl/event/inter_context_delegate.h +++ b/modules/event/include/dpl/event/inter_context_delegate.h @@ -31,8 +31,6 @@ #include #include #include -#include -#include #include #include #include @@ -43,6 +41,7 @@ #include #include #include +#include /* * - Created ICDelegate can be passed freely to other threads. @@ -88,7 +87,7 @@ namespace ICDPrivate { class ICDSharedDataBase { public: - typedef DPL::SharedPtr ICDSharedDataBasePtr; + typedef std::shared_ptr ICDSharedDataBasePtr; typedef std::list ICDSharedDataBaseList; class ScopedLock : DPL::Noncopyable @@ -146,7 +145,7 @@ class DeleteICDSharedDataBaseEventCall : public DPL::Event::AbstractEventCall } virtual void Call() { - m_helperBase.Reset(); + m_helperBase.reset(); } private: @@ -194,7 +193,7 @@ class ICDelegate ICD::Reuse reuse) { ICDSharedData* hlp = new ICDSharedData(base, outerDelegate, reuse); - m_helper.Reset(hlp); + m_helper.reset(hlp); } // Calling operator will pass all args passed to it to correct context and @@ -203,7 +202,7 @@ class ICDelegate { Assert(m_helper); ICDPrivate::ICDSharedDataBase::ScopedLock lock( - DPL::StaticPointerCast(m_helper)); + std::static_pointer_cast(m_helper)); m_helper->CallDelegate(args ...); } @@ -212,7 +211,7 @@ class ICDelegate { Assert(m_helper); ICDPrivate::ICDSharedDataBase::ScopedLock lock( - DPL::StaticPointerCast(m_helper)); + std::static_pointer_cast(m_helper)); m_helper->disable(); } @@ -220,14 +219,14 @@ class ICDelegate ICDPrivate::ICDSharedDataBase::ICDSharedDataBasePtr getRelatedICDSharedData() const { - return DPL::StaticPointerCast(m_helper); + return std::static_pointer_cast(m_helper); } private: template friend class ICDelegateSupport; class ICDSharedData; - typedef DPL::SharedPtr ICDSharedDataPtr; + typedef std::shared_ptr ICDSharedDataPtr; struct PrivateEvent { @@ -245,7 +244,7 @@ class ICDelegate typedef DPL::FastDelegate ICDSharedDataDelegateType; class ICDSharedData : private DPL::Event::EventSupport, - private DPL::EnableSharedFromThis, + public std::enable_shared_from_this, public ICDPrivate::ICDSharedDataBase { public: @@ -268,10 +267,10 @@ class ICDelegate void CallDelegate(ArgTypesList ... args) { ICDPrivate::ICDSharedDataBase::ScopedLock lock( - DPL::StaticPointerCast( - this->SharedFromThis())); + std::static_pointer_cast( + this->shared_from_this())); if (!isDisabled()) { - EmitEvent(PrivateEvent(this->SharedFromThis(), + EmitEvent(PrivateEvent(this->shared_from_this(), args ...)); } } @@ -279,8 +278,8 @@ class ICDelegate virtual void disable() { ICDPrivate::ICDSharedDataBase::ICDSharedDataBasePtr ptr( - DPL::StaticPointerCast( - this->SharedFromThis())); + std::static_pointer_cast( + this->shared_from_this())); ICDPrivate::ICDSharedDataBase::ScopedLock lock(ptr); if (!isDisabled()) { ICDPrivate::ICDSharedDataBase::disable(); @@ -290,7 +289,7 @@ class ICDelegate } private: - friend class DPL::SharedPtr; + friend class std::shared_ptr; ICDSharedDataDelegateType m_subDelegate; ICDPrivate::ICDelegateSupportInterface* m_base; DPL::FastDelegate m_outerDelegate; @@ -299,7 +298,7 @@ class ICDelegate void delegateForwarder(const PrivateEvent& event) { ICDPrivate::ICDSharedDataBase::ICDSharedDataBasePtr ptr( - DPL::StaticPointerCast(event.helper)); + std::static_pointer_cast(event.helper)); ICDPrivate::ICDSharedDataBase::ScopedLock lock(ptr); Assert(!m_outerDelegate.empty()); @@ -364,7 +363,7 @@ class ICDelegateSupport : public ICDPrivate::ICDelegateSupportInterface m_ICDSharedDatas; FOREACH(helper, list) { ICDPrivate::ICDSharedDataBase::ScopedLock lock( - DPL::StaticPointerCast(*helper)); + std::static_pointer_cast(*helper)); (*helper)->disable(); } m_ICDSharedDatas.clear(); diff --git a/modules/localization/include/dpl/localization/w3c_file_localization.h b/modules/localization/include/dpl/localization/w3c_file_localization.h index 1e155ad..e0e5737 100644 --- a/modules/localization/include/dpl/localization/w3c_file_localization.h +++ b/modules/localization/include/dpl/localization/w3c_file_localization.h @@ -38,10 +38,22 @@ typedef std::list WidgetIconList; DPL::Optional getFilePathInWidgetPackageFromUrl( WrtDB::DbWidgetHandle widgetHandle, const DPL::String &url); +DPL::Optional getFilePathInWidgetPackageFromUrl( + const WrtDB::WidgetPkgName &pkgname, + const DPL::String &url); +DPL::Optional getFilePathInWidgetPackageFromUrl( + WrtDB::WidgetDAOReadOnlyPtr dao, + const DPL::String &url); DPL::Optional getFilePathInWidgetPackage( WrtDB::DbWidgetHandle widgetHandle, const DPL::String& file); +DPL::Optional getFilePathInWidgetPackage( + const WrtDB::WidgetPkgName &pkgname, + const DPL::String& file); +DPL::Optional getFilePathInWidgetPackage( + WrtDB::WidgetDAOReadOnlyPtr dao, + const DPL::String& file); DPL::OptionalString getStartFile(WrtDB::DbWidgetHandle handle); DPL::OptionalString getStartFile(const WrtDB::WidgetPkgName & pkgname); @@ -53,9 +65,17 @@ OptionalWidgetIcon getIcon(WrtDB::WidgetDAOReadOnlyPtr dao); WidgetIconList getValidIconsList( WrtDB::DbWidgetHandle widgetHandle); +WidgetIconList getValidIconsList( + const WrtDB::WidgetPkgName &pkgname); +WidgetIconList getValidIconsList( + WrtDB::WidgetDAOReadOnlyPtr dao); OptionalWidgetStartFileInfo getStartFileInfo( WrtDB::DbWidgetHandle widgetHandle); +OptionalWidgetStartFileInfo getStartFileInfo( + const WrtDB::WidgetPkgName &pkgname); +OptionalWidgetStartFileInfo getStartFileInfo( + WrtDB::WidgetDAOReadOnlyPtr dao); WrtDB::WidgetLocalizedInfo getLocalizedInfo(WrtDB::DbWidgetHandle widgetHandle); WrtDB::WidgetLocalizedInfo getLocalizedInfo(const WrtDB::WidgetPkgName & pkgname); diff --git a/modules/localization/src/LanguageTagsProvider.cpp b/modules/localization/src/LanguageTagsProvider.cpp index b75de8b..576d06a 100644 --- a/modules/localization/src/LanguageTagsProvider.cpp +++ b/modules/localization/src/LanguageTagsProvider.cpp @@ -38,16 +38,11 @@ const LanguageTags LanguageTagsProvider::getLanguageTags() const void LanguageTagsProvider::setLanguageTags(const LanguageTags& taglist) { m_languageTagsList = taglist; - /* If given list does not contain default values ("en" and empty string) - * than append them to the list. - * In case of empty list given as parameter only two default values + /* If given list does not contain default value (empty string) + * than append it to the list. + * In case of empty list given as parameter only default value * will exist on m_languageTagsList. */ - DPL::String tofind = L"en"; - if(std::find(m_languageTagsList.begin(), m_languageTagsList.end(), - tofind) == m_languageTagsList.end()) { - m_languageTagsList.push_back(L"en"); - } - tofind = L""; + DPL::String tofind = L""; if(std::find(m_languageTagsList.begin(), m_languageTagsList.end(), tofind) == m_languageTagsList.end()) { m_languageTagsList.push_back(L""); @@ -133,7 +128,6 @@ void LanguageTagsProvider::createTagsFromLocales(const char* language) LogDebug("Setting default language tags"); /* If NULL language given than set default language tags * and return. */ - m_languageTagsList.push_back(L"en"); m_languageTagsList.push_back(L""); return; } @@ -159,12 +153,6 @@ void LanguageTagsProvider::createTagsFromLocales(const char* language) langdescr = langdescr.substr(0, position); } } - /* If current content of langdescr (thus last added added tag) - * is not "en" then add english as default locales. - * "en" and empty tag are added even when langdescr is not valid. */ - if (langdescr.compare(L"en") != 0){ - m_languageTagsList.push_back(L"en"); - } /* Add empty tag for non-localized content */ m_languageTagsList.push_back(L""); } diff --git a/modules/localization/src/w3c_file_localization.cpp b/modules/localization/src/w3c_file_localization.cpp index 60ea79d..4a6cfe1 100644 --- a/modules/localization/src/w3c_file_localization.cpp +++ b/modules/localization/src/w3c_file_localization.cpp @@ -105,19 +105,37 @@ DPL::Optional GetFilePathInWidgetPackageInternal( } namespace W3CFileLocalization { + DPL::Optional getFilePathInWidgetPackageFromUrl( DbWidgetHandle widgetHandle, const DPL::String &url) +{ + return getFilePathInWidgetPackageFromUrl( + WidgetDAOReadOnlyPtr(new WidgetDAOReadOnly(widgetHandle)), + url); +} + +DPL::Optional getFilePathInWidgetPackageFromUrl( + const WrtDB::WidgetPkgName &pkgname, + const DPL::String &url) +{ + return getFilePathInWidgetPackageFromUrl( + WidgetDAOReadOnlyPtr(new WidgetDAOReadOnly(pkgname)), + url); +} + +DPL::Optional getFilePathInWidgetPackageFromUrl( + WrtDB::WidgetDAOReadOnlyPtr dao, + const DPL::String &url) { DPL::String req = url; - WidgetDAOReadOnly dao(widgetHandle); if (req.find(WIDGET_URI_BEGIN) == 0) { req.erase(0, WIDGET_URI_BEGIN.length()); } else if (req.find(FILE_URI_BEGIN) == 0) { req.erase(0, FILE_URI_BEGIN.length()); - if (req.find(dao.getPath()) == 0) { - req.erase(0, dao.getPath().length()); + if (req.find(dao->getPath()) == 0) { + req.erase(0, dao->getPath().length()); } if (req.find(LOCALE_PREFIX) == 0) { req.erase(0, LOCALE_PREFIX.length()); @@ -133,7 +151,7 @@ DPL::Optional getFilePathInWidgetPackageFromUrl( return DPL::Optional::Null; } - auto widgetPath = dao.getPath(); + auto widgetPath = dao->getPath(); DPL::Optional found = GetFilePathInWidgetPackageInternal(widgetPath, req); @@ -152,8 +170,25 @@ DPL::Optional getFilePathInWidgetPackage( WrtDB::DbWidgetHandle widgetHandle, const DPL::String& file) { - WidgetDAOReadOnly dao(widgetHandle); - return GetFilePathInWidgetPackageInternal(dao.getPath(), file); + return getFilePathInWidgetPackage( + WidgetDAOReadOnlyPtr(new WidgetDAOReadOnly(widgetHandle)), + file); +} + +DPL::Optional getFilePathInWidgetPackage( + const WrtDB::WidgetPkgName &pkgname, + const DPL::String& file) +{ + return getFilePathInWidgetPackage( + WidgetDAOReadOnlyPtr(new WidgetDAOReadOnly(pkgname)), + file); +} + +DPL::Optional getFilePathInWidgetPackage( + WrtDB::WidgetDAOReadOnlyPtr dao, + const DPL::String& file) +{ + return GetFilePathInWidgetPackageInternal(dao->getPath(), file); } DPL::OptionalString getStartFile(const WrtDB::WidgetPkgName & pkgname) @@ -238,18 +273,28 @@ OptionalWidgetIcon getIcon(WrtDB::WidgetDAOReadOnlyPtr dao) return OptionalWidgetIcon::Null; } -WidgetIconList getValidIconsList( - WrtDB::DbWidgetHandle widgetHandle) +WidgetIconList getValidIconsList(WrtDB::DbWidgetHandle widgetHandle) +{ + return getValidIconsList( + WidgetDAOReadOnlyPtr(new WidgetDAOReadOnly(widgetHandle))); +} + +WidgetIconList getValidIconsList(const WrtDB::WidgetPkgName &pkgname) { - WidgetDAOReadOnly dao(widgetHandle); - WidgetDAOReadOnly::WidgetIconList list = dao.getIconList(); + return getValidIconsList( + WidgetDAOReadOnlyPtr(new WidgetDAOReadOnly(pkgname))); +} + +WidgetIconList getValidIconsList(WrtDB::WidgetDAOReadOnlyPtr dao) +{ + WidgetDAOReadOnly::WidgetIconList list = dao->getIconList(); WidgetIconList outlist; FOREACH(it, list) { LogDebug(":" << it->iconSrc); - if (!!getFilePathInWidgetPackage(widgetHandle, + if (!!getFilePathInWidgetPackage(dao->getHandle(), it->iconSrc)) { WidgetIcon ret; @@ -262,15 +307,27 @@ WidgetIconList getValidIconsList( return outlist; } -OptionalWidgetStartFileInfo getStartFileInfo( - WrtDB::DbWidgetHandle widgetHandle) +OptionalWidgetStartFileInfo getStartFileInfo(WrtDB::DbWidgetHandle widgetHandle) +{ + return getStartFileInfo( + WidgetDAOReadOnlyPtr(new WidgetDAOReadOnly(widgetHandle))); +} + +OptionalWidgetStartFileInfo getStartFileInfo(const WrtDB::WidgetPkgName &pkgname) +{ + return getStartFileInfo( + WidgetDAOReadOnlyPtr(new WidgetDAOReadOnly(pkgname))); + +} + + +OptionalWidgetStartFileInfo getStartFileInfo(WrtDB::WidgetDAOReadOnlyPtr dao) { WidgetStartFileInfo info; - WidgetDAOReadOnly dao(widgetHandle); WidgetDAOReadOnly::LocalizedStartFileList locList = - dao.getLocalizedStartFileList(); - WidgetDAOReadOnly::WidgetStartFileList list = dao.getStartFileList(); + dao->getLocalizedStartFileList(); + WidgetDAOReadOnly::WidgetStartFileList list = dao->getStartFileList(); const LanguageTags tagsList = LanguageTagsProviderSingleton::Instance().getLanguageTags(); FOREACH(tag, tagsList) diff --git a/modules/popup/include/dpl/popup/evas_object.h b/modules/popup/include/dpl/popup/evas_object.h index ba4ad9b..25d7a66 100644 --- a/modules/popup/include/dpl/popup/evas_object.h +++ b/modules/popup/include/dpl/popup/evas_object.h @@ -22,23 +22,23 @@ #ifndef WRT_SRC_DOMAIN_EFL_EVAS_OBJECT_H #define WRT_SRC_DOMAIN_EFL_EVAS_OBJECT_H +#include #include #include -#include #include #include #include #include #include #include - +#include namespace DPL { namespace Popup { class EvasObject { class EvasObjectShared; - typedef DPL::SharedPtr EvasObjectSharedPtr; + typedef std::shared_ptr EvasObjectSharedPtr; public: class IConnection diff --git a/modules/popup/include/dpl/popup/popup.h b/modules/popup/include/dpl/popup/popup.h index e5c926c..84c2c4e 100644 --- a/modules/popup/include/dpl/popup/popup.h +++ b/modules/popup/include/dpl/popup/popup.h @@ -23,8 +23,7 @@ #ifndef WRT_SRC_POPUP_POPUP_H_ #define WRT_SRC_POPUP_POPUP_H_ -#include -#include +#include #include #include #include @@ -43,9 +42,9 @@ struct AnswerCallbackData class PopupManager; class IPopup; -typedef DPL::SharedPtr IPopupPtr; +typedef std::shared_ptr IPopupPtr; -class IPopup : protected DPL::EnableSharedFromThis +class IPopup : public std::enable_shared_from_this { public: virtual void SetTitle(const std::string &title) = 0; @@ -63,7 +62,7 @@ class IPopup : protected DPL::EnableSharedFromThis private: friend class PopupManager; - friend class DPL::SharedPtr; + friend class std::shared_ptr; }; } // namespace Popup diff --git a/modules/popup/include/dpl/popup/popup_controller.h b/modules/popup/include/dpl/popup/popup_controller.h index 0b49201..5f2938a 100644 --- a/modules/popup/include/dpl/popup/popup_controller.h +++ b/modules/popup/include/dpl/popup/popup_controller.h @@ -65,14 +65,13 @@ #ifndef WRT_SRC_POPUP_CONTROLLER_POPUP_CONTROLLER_H_ #define WRT_SRC_POPUP_CONTROLLER_POPUP_CONTROLLER_H_ +#include #include #include #include #include #include #include -#include -#include #include #include #include @@ -99,7 +98,7 @@ struct PopupAnswerCallback class PopupController; class CtrlPopup; -typedef DPL::SharedPtr CtrlPopupPtr; +typedef std::shared_ptr CtrlPopupPtr; DECLARE_GENERIC_EVENT_3(PopupAnswerEvent, CtrlPopupPtr, @@ -111,18 +110,18 @@ DECLARE_GENERIC_EVENT_2(ShowPopupEventShort, PopupAnswerCallback) class CtrlPopup : public DPL::Event::EventSupport, - protected DPL::EnableSharedFromThis + public std::enable_shared_from_this { public: void SetTitle(const std::string &title); void Append(PopupObject::IPopupObject *object); + ~CtrlPopup(); private: friend class PopupController; - friend class DPL::SharedPtr; + friend class std::shared_ptr; explicit CtrlPopup(IPopupPtr popup); - ~CtrlPopup(); void EmitAnswer(const AnswerCallbackData& answer); IPopupPtr m_popup; diff --git a/modules/popup/include/dpl/popup/popup_manager.h b/modules/popup/include/dpl/popup/popup_manager.h index 267cd14..42a4de5 100644 --- a/modules/popup/include/dpl/popup/popup_manager.h +++ b/modules/popup/include/dpl/popup/popup_manager.h @@ -23,8 +23,8 @@ #ifndef WRT_SRC_POPUP_POPUP_MANAGER_H_ #define WRT_SRC_POPUP_POPUP_MANAGER_H_ +#include #include -#include #include #include #include diff --git a/modules/popup/include/dpl/popup/popup_renderer.h b/modules/popup/include/dpl/popup/popup_renderer.h index 593c231..18d2aab 100644 --- a/modules/popup/include/dpl/popup/popup_renderer.h +++ b/modules/popup/include/dpl/popup/popup_renderer.h @@ -25,20 +25,18 @@ #include #include +#include -#include #include #include #include -#include #include - #include namespace DPL { namespace Popup { -class PopupRenderer : public DPL::EnableSharedFromThis +class PopupRenderer : public std::enable_shared_from_this { public: PopupRenderer(); @@ -49,7 +47,7 @@ class PopupRenderer : public DPL::EnableSharedFromThis virtual void setExternalCanvas(void* externalCanvas); protected: class Popup; - typedef DPL::SharedPtr PopupPtr; + typedef std::shared_ptr PopupPtr; class Popup : public IPopup { @@ -73,7 +71,7 @@ class PopupRenderer : public DPL::EnableSharedFromThis Assert(callback); m_data = data; m_callback = callback; - m_renderer->Render(DPL::StaticPointerCast(SharedFromThis())); + m_renderer->Render(std::static_pointer_cast(shared_from_this())); } const std::string& GetTitle() const @@ -95,10 +93,10 @@ class PopupRenderer : public DPL::EnableSharedFromThis private: friend class PopupRenderer; - friend class DPL::SharedPtr; + friend class std::shared_ptr; friend class PopupObjectTheme; - Popup(DPL::SharedPtr renderer) : m_renderer(renderer) + Popup(std::shared_ptr renderer) : m_renderer(renderer) { } @@ -111,7 +109,7 @@ class PopupRenderer : public DPL::EnableSharedFromThis void* m_data; IPopup::PopupCallbackType m_callback; PopupObject::PopupObjects m_popupObjectList; - DPL::SharedPtr m_renderer; + std::shared_ptr m_renderer; }; private: @@ -121,7 +119,7 @@ class PopupRenderer : public DPL::EnableSharedFromThis Impl* m_impl; }; -typedef DPL::SharedPtr PopupRendererPtr; +typedef std::shared_ptr PopupRendererPtr; } // namespace Popup } // namespace DPL diff --git a/modules/popup/src/popup_controller.cpp b/modules/popup/src/popup_controller.cpp index f67dc16..5bd1cf1 100644 --- a/modules/popup/src/popup_controller.cpp +++ b/modules/popup/src/popup_controller.cpp @@ -56,7 +56,7 @@ CtrlPopup::~CtrlPopup() void CtrlPopup::EmitAnswer(const AnswerCallbackData & answer) { AnswerCallbackData l_answer = answer; - PopupAnswerEvent event(SharedFromThis(), m_callback, l_answer); + PopupAnswerEvent event(shared_from_this(), m_callback, l_answer); DPL::Event::EventSupport::EmitEvent(event); } diff --git a/modules/popup/src/popup_manager.cpp b/modules/popup/src/popup_manager.cpp index be1b680..a6fa465 100644 --- a/modules/popup/src/popup_manager.cpp +++ b/modules/popup/src/popup_manager.cpp @@ -22,9 +22,7 @@ #include #include #include - #include -#include #include #include @@ -45,7 +43,7 @@ void PopupManager::Deinitialize() { m_popupRenderer->Deinitialize(); Assert(m_initialized); - m_popupRenderer.Reset(); + m_popupRenderer.reset(); m_initialized = false; } diff --git a/modules/popup/src/popup_renderer.cpp b/modules/popup/src/popup_renderer.cpp index b702faa..411c709 100644 --- a/modules/popup/src/popup_renderer.cpp +++ b/modules/popup/src/popup_renderer.cpp @@ -24,7 +24,6 @@ #include #include #include -#include #include #include #include @@ -93,7 +92,7 @@ class PopupRenderer::Impl void Deinitialize() { Assert(m_initialized); - m_current.Reset(NULL); + m_current.reset(); while (!m_popupsToRender.empty()) { m_popupsToRender.pop(); } @@ -112,7 +111,7 @@ class PopupRenderer::Impl answerData.chackState = m_checkState; answerData.password = m_password; m_current->ForwardAnswer(answerData); - m_current.Reset(); + m_current.reset(); FOREACH(it, m_createdObjects) { @@ -192,35 +191,28 @@ class PopupRenderer::Impl elm_object_text_set(btn, object.getLabel().c_str()); elm_object_part_content_set(parent, POPUP_PART_BUTTON1, btn); - btn.ConnectMemberSmartCallback(BUTTON_CLICKED_CALLBACK_NAME, + btn.ConnectMemberSmartCallback(BUTTON_CLICKED_CALLBACK_NAME, &Impl::ButtonCallback, this, reinterpret_cast(object.getLabelId())); - m_createdObjects.push_back(btn); + m_createdObjects.push_back(btn); } void DoRender(const PopupObject::Button& object1, const PopupObject::Button& object2, EvasObject &parent) { - EvasObject btn1(elm_button_add(parent)); - EvasObject btn2(elm_button_add(parent)); + DoRender(object1, parent); - elm_object_text_set(btn1, object1.getLabel().c_str()); - elm_object_part_content_set(parent, POPUP_PART_BUTTON1, btn1); - btn1.ConnectMemberSmartCallback(BUTTON_CLICKED_CALLBACK_NAME, - &Impl::ButtonCallback, - this, - reinterpret_cast(object1.getLabelId())); + EvasObject btn2(elm_button_add(parent)); elm_object_text_set(btn2, object2.getLabel().c_str()); elm_object_part_content_set(parent, POPUP_PART_BUTTON2, btn2); - btn2.ConnectMemberSmartCallback(BUTTON_CLICKED_CALLBACK_NAME, + btn2.ConnectMemberSmartCallback(BUTTON_CLICKED_CALLBACK_NAME, &Impl::ButtonCallback, this, reinterpret_cast(object2.getLabelId())); - m_createdObjects.push_back(btn1); - m_createdObjects.push_back(btn2); + m_createdObjects.push_back(btn2); } void DoRender(const PopupObject::Button& object1, @@ -228,33 +220,17 @@ class PopupRenderer::Impl const PopupObject::Button& object3, EvasObject &parent) { - EvasObject btn1(elm_button_add(parent)); - EvasObject btn2(elm_button_add(parent)); - EvasObject btn3(elm_button_add(parent)); + DoRender(object1, object2, parent); - elm_object_text_set(btn1, object1.getLabel().c_str()); - elm_object_part_content_set(parent, POPUP_PART_BUTTON1, btn1); - btn1.ConnectMemberSmartCallback(BUTTON_CLICKED_CALLBACK_NAME, - &Impl::ButtonCallback, - this, - reinterpret_cast(object1.getLabelId())); - - elm_object_text_set(btn2, object2.getLabel().c_str()); - elm_object_part_content_set(parent, POPUP_PART_BUTTON2, btn2); - btn2.ConnectMemberSmartCallback(BUTTON_CLICKED_CALLBACK_NAME, - &Impl::ButtonCallback, - this, - reinterpret_cast(object2.getLabelId())); + EvasObject btn3(elm_button_add(parent)); elm_object_text_set(btn3, object3.getLabel().c_str()); elm_object_part_content_set(parent, POPUP_PART_BUTTON3, btn3); - btn3.ConnectMemberSmartCallback(BUTTON_CLICKED_CALLBACK_NAME, + btn3.ConnectMemberSmartCallback(BUTTON_CLICKED_CALLBACK_NAME, &Impl::ButtonCallback, this, reinterpret_cast(object3.getLabelId())); - m_createdObjects.push_back(btn1); - m_createdObjects.push_back(btn2); - m_createdObjects.push_back(btn3); + m_createdObjects.push_back(btn3); } EvasObject getBaseObject() @@ -421,8 +397,8 @@ void PopupRenderer::Deinitialize() IPopupPtr PopupRenderer::CreatePopup() { - return DPL::StaticPointerCast(IPopupPtr - (new Popup(SharedFromThis()))); + return std::static_pointer_cast(IPopupPtr + (new Popup(shared_from_this()))); } void PopupRenderer::Render(PopupPtr popup) diff --git a/modules/rpc/include/dpl/rpc/generic_rpc_connection.h b/modules/rpc/include/dpl/rpc/generic_rpc_connection.h index 1342859..353dd3a 100644 --- a/modules/rpc/include/dpl/rpc/generic_rpc_connection.h +++ b/modules/rpc/include/dpl/rpc/generic_rpc_connection.h @@ -25,7 +25,7 @@ #include #include #include -#include +#include namespace DPL { @@ -42,7 +42,7 @@ private: virtual void OnInputStreamClosed(); virtual void OnInputStreamBroken(); - ScopedPtr m_inputOutput; + std::unique_ptr m_inputOutput; public: /** diff --git a/modules/security_origin_dao/CMakeLists.txt b/modules/security_origin_dao/CMakeLists.txt index f2a37da..4e74cc3 100644 --- a/modules/security_origin_dao/CMakeLists.txt +++ b/modules/security_origin_dao/CMakeLists.txt @@ -1,3 +1,5 @@ +SET(TARGET_SECURITY_ORIGIN_DAO_DB "Sqlite3DbSecurityOrigin") + ADD_CUSTOM_COMMAND( OUTPUT .security_origin.db COMMAND rm -f ${CMAKE_CURRENT_BINARY_DIR}/.security_origin.db COMMAND gcc -Wall -I${PROJECT_SOURCE_DIR}/modules/db/include -I${PROJECT_SOURCE_DIR}/modules/security_origin_dao/orm -E ${PROJECT_SOURCE_DIR}/modules/security_origin_dao/orm/security_origin_db_sql_generator.h | grep --invert-match "^#" > ${CMAKE_CURRENT_BINARY_DIR}/security_origin_db.sql @@ -10,7 +12,7 @@ ADD_CUSTOM_COMMAND( OUTPUT .security_origin.db-journal ARGS ${CMAKE_CURRENT_BINARY_DIR}/.security_origin.db-journal ) -ADD_CUSTOM_TARGET(Sqlite3DbSecurityOrigin ALL DEPENDS .security_origin.db .security_origin.db-journal) +ADD_CUSTOM_TARGET(${TARGET_SECURITY_ORIGIN_DAO_DB} ALL DEPENDS .security_origin.db .security_origin.db-journal) INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/security_origin_db.sql DESTINATION share/wrt-engine/) ############################################################################### @@ -28,7 +30,6 @@ SET(SECURITY_ORIGIN_DAO_INCLUDE_DIRS ${PROJECT_SOURCE_DIR}/modules/db/include ${PROJECT_SOURCE_DIR}/modules/log/include ${PROJECT_SOURCE_DIR}/modules/widget_dao/include - ${SECURITY_ORIGIN_DAO_DEPS_INCLUDE_DIRS} ) SET(SECURITY_ORIGIN_DAO_SOURCES @@ -37,11 +38,13 @@ SET(SECURITY_ORIGIN_DAO_SOURCES dao/security_origin_dao.cpp ) +INCLUDE_DIRECTORIES(SYSTEM ${SECURITY_ORIGIN_DAO_DEPS_INCLUDE_DIRS} ) INCLUDE_DIRECTORIES(${SECURITY_ORIGIN_DAO_INCLUDE_DIRS}) ADD_LIBRARY(${TARGET_SECURITY_ORIGIN_DAO_LIB} SHARED ${SECURITY_ORIGIN_DAO_SOURCES}) SET_TARGET_PROPERTIES(${TARGET_SECURITY_ORIGIN_DAO_LIB} PROPERTIES SOVERSION ${API_VERSION} VERSION ${VERSION}) TARGET_LINK_LIBRARIES(${TARGET_SECURITY_ORIGIN_DAO_LIB} ${TARGET_DPL_EFL} ${TARGET_DPL_DB_EFL} ${TARGET_WRT_DAP_RO_LIB} ${SECURITY_ORIGIN_DAO_DEPS_LIBRARIES}) +ADD_DEPENDENCIES(${TARGET_SECURITY_ORIGIN_DAO_LIB} ${TARGET_SECURITY_ORIGIN_DAO_DB}) INSTALL(TARGETS ${TARGET_SECURITY_ORIGIN_DAO_LIB} DESTINATION lib) diff --git a/modules/security_origin_dao/dao/security_origin_dao.cpp b/modules/security_origin_dao/dao/security_origin_dao.cpp index 34ed369..377358c 100644 --- a/modules/security_origin_dao/dao/security_origin_dao.cpp +++ b/modules/security_origin_dao/dao/security_origin_dao.cpp @@ -29,6 +29,7 @@ #include #include #include +#include #include #include @@ -55,25 +56,32 @@ const char* const SECURITY_ORIGIN_DB_NAME = ".security_origin.db"; const char* const SECURITY_ORIGIN_DB_SQL_PATH = "/usr/share/wrt-engine/security_origin_db.sql"; +std::string createDatabasePath(const WrtDB::WidgetPkgName &pkgName) +{ + std::stringstream filename; + + filename << WrtDB::WidgetConfig::GetWidgetPersistentStoragePath(pkgName) + << "/" + << SECURITY_ORIGIN_DB_NAME; + return filename.str(); +} + std::string createDatabasePath(int widgetHandle) { using namespace DPL::DB::ORM; using namespace WrtDB::WidgetConfig; using namespace WrtDB::GlobalConfig; - SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN - { - std::stringstream filename; - WrtDB::WidgetDAOReadOnly widgetDAO(widgetHandle); - DPL::Optional pkgname = widgetDAO.getPkgname(); + WrtDB::WidgetPkgName pkgname; - filename << GetWidgetPersistentStoragePath(*pkgname) - << "/" - << SECURITY_ORIGIN_DB_NAME; - return filename.str(); + Try + { + pkgname = WrtDB::WidgetDAOReadOnly::getPkgName(widgetHandle); } - SQL_CONNECTION_EXCEPTION_HANDLER_END("Fail to get database Path") - + Catch(DPL::DB::SqlConnection::Exception::Base) { + LogError("Failed to get database Path"); + } + return createDatabasePath(pkgname); } void checkDatabase(std::string databasePath) @@ -121,11 +129,40 @@ SecurityOriginDAO::SecurityOriginDAO(int handle) : m_securityOriginDBInterface.AttachToThread(SECURITY_ORIGIN_DB_OPTION); } +SecurityOriginDAO::SecurityOriginDAO(const WrtDB::WidgetPkgName &pkgName) : + m_securityOriginDBPath(createDatabasePath(pkgName)), + m_securityOriginDBInterface(m_securityOriginDBPath, SECURITY_ORIGIN_DB_TYPE) +{ + checkDatabase(m_securityOriginDBPath); + m_securityOriginDBInterface.AttachToThread(SECURITY_ORIGIN_DB_OPTION); +} + SecurityOriginDAO::~SecurityOriginDAO() { m_securityOriginDBInterface.DetachFromThread(); } +SecurityOriginDataList SecurityOriginDAO::getSecurityOriginDataList(void) +{ + SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN + { + SecurityOriginDataList list; + SECURITY_ORIGIN_DB_SELECT(select, SecurityOriginInfo, &m_securityOriginDBInterface); + typedef std::list RowList; + RowList rowList = select->GetRowList(); + + FOREACH(it, rowList) { + Origin origin(it->Get_scheme(), it->Get_host(), it->Get_port()); + list.push_back( + SecurityOriginDataPtr( + new SecurityOriginData( + static_cast(it->Get_feature()), origin))); + } + return list; + } + SQL_CONNECTION_EXCEPTION_HANDLER_END("Failed to get data list") +} + Result SecurityOriginDAO::getResult(const SecurityOriginData &securityOriginData) { SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN @@ -179,22 +216,44 @@ void SecurityOriginDAO::setSecurityOriginData(const SecurityOriginData &security SQL_CONNECTION_EXCEPTION_HANDLER_END("Fail to set security origin data") } -bool SecurityOriginDAO::hasResult(const SecurityOriginData &securityOriginData) +void SecurityOriginDAO::removeSecurityOriginData( + const SecurityOriginData &securityOriginData) { SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { - SECURITY_ORIGIN_DB_SELECT(select, SecurityOriginInfo, &m_securityOriginDBInterface); - select->Where( - And(And(And(Equals(securityOriginData.feature), - Equals(securityOriginData.origin.scheme)), - Equals(securityOriginData.origin.host)), - Equals(securityOriginData.origin.port))); + ScopedTransaction transaction(&m_securityOriginDBInterface); - SecurityOriginInfo::Select::RowList rows = select->GetRowList(); + if (true == hasResult(securityOriginData)) { + SECURITY_ORIGIN_DB_DELETE(del, SecurityOriginInfo, &m_securityOriginDBInterface) + del->Where( + And(And(And(Equals(securityOriginData.feature), + Equals(securityOriginData.origin.scheme)), + Equals(securityOriginData.origin.host)), + Equals(securityOriginData.origin.port))); + del->Execute(); + transaction.Commit(); + } + } + SQL_CONNECTION_EXCEPTION_HANDLER_END("Fail to set security origin data") +} - return !rows.empty(); +void SecurityOriginDAO::removeSecurityOriginData(const Result result) +{ + SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN + { + ScopedTransaction transaction(&m_securityOriginDBInterface); + SECURITY_ORIGIN_DB_DELETE(del, SecurityOriginInfo, &m_securityOriginDBInterface) + del->Where(Equals(result)); + del->Execute(); + transaction.Commit(); } - SQL_CONNECTION_EXCEPTION_HANDLER_END("Failed to get result for security origin") + SQL_CONNECTION_EXCEPTION_HANDLER_END("Fail to remove data by result") +} + +bool SecurityOriginDAO::hasResult(const SecurityOriginData &securityOriginData) +{ + Result res=getResult(securityOriginData); + return (res != RESULT_UNKNOWN); } #undef SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN diff --git a/modules/security_origin_dao/include/wrt-commons/security-origin-dao/security_origin_dao.h b/modules/security_origin_dao/include/wrt-commons/security-origin-dao/security_origin_dao.h index a1e649e..9dc7d9c 100644 --- a/modules/security_origin_dao/include/wrt-commons/security-origin-dao/security_origin_dao.h +++ b/modules/security_origin_dao/include/wrt-commons/security-origin-dao/security_origin_dao.h @@ -24,6 +24,7 @@ #include #include +#include namespace SecurityOriginDB { @@ -38,17 +39,23 @@ class SecurityOriginDAO DECLARE_EXCEPTION_TYPE(Base, DataNotExist) }; - explicit SecurityOriginDAO(int handle); + explicit SecurityOriginDAO(int handle) __attribute__((deprecated)); + explicit SecurityOriginDAO(const WrtDB::WidgetPkgName &pkgName); virtual ~SecurityOriginDAO(); + SecurityOriginDataList getSecurityOriginDataList(); Result getResult(const SecurityOriginData &securityOriginData); void setSecurityOriginData(const SecurityOriginData &securityOriginData, const Result result); + void removeSecurityOriginData(const SecurityOriginData &securityOriginData); + void removeSecurityOriginData(const Result result); private: std::string m_securityOriginDBPath; DPL::DB::ThreadDatabaseSupport m_securityOriginDBInterface; bool hasResult(const SecurityOriginData &securityOriginData); }; +typedef std::shared_ptr SecurityOriginDAOPtr; + } // namespace SecurityOriginDB #endif // _SECURITY_ORIGIN_DAO_H_ diff --git a/modules/security_origin_dao/include/wrt-commons/security-origin-dao/security_origin_dao_types.h b/modules/security_origin_dao/include/wrt-commons/security-origin-dao/security_origin_dao_types.h index 90e355b..35081ca 100644 --- a/modules/security_origin_dao/include/wrt-commons/security-origin-dao/security_origin_dao_types.h +++ b/modules/security_origin_dao/include/wrt-commons/security-origin-dao/security_origin_dao_types.h @@ -25,24 +25,28 @@ #define _SECURITY_ORIGIN_DAO_TYPES_H_ #include +#include #include namespace SecurityOriginDB { enum Feature { + FEATURE_START = 0, FEATURE_GEOLOCATION = 0, - FEATURE_FILESYSTEM, - FEATURE_WEB_NOTIFICATION + FEATURE_WEB_NOTIFICATION, + FEATURE_WEB_DATABASE, + FEATURE_FILE_SYSTEM_ACCESS, + FEATURE_END = FEATURE_FILE_SYSTEM_ACCESS }; enum Result { RESULT_UNKNOWN = 0, - RESULT_USER_ALLOWED, - RESULT_USER_DENIED, - RESULT_EXCEPTION_ALLOWED, - RESULT_EXCEPTION_DENIED + RESULT_ALLOW_ONCE, + RESULT_DENY_ONCE, + RESULT_ALLOW_ALWAYS, + RESULT_DENY_ALWAYS }; struct Origin @@ -96,6 +100,9 @@ struct SecurityOriginData } }; +typedef std::shared_ptr SecurityOriginDataPtr; +typedef std::list SecurityOriginDataList; + } // namespace SecurityOriginDB #endif // _SECURITY_ORIGIN_DAO_TYPES_H_ diff --git a/modules/socket/src/unix_socket.cpp b/modules/socket/src/unix_socket.cpp index 29fae2b..3dd905c 100644 --- a/modules/socket/src/unix_socket.cpp +++ b/modules/socket/src/unix_socket.cpp @@ -30,6 +30,7 @@ #include #include #include +#include namespace DPL { @@ -102,8 +103,9 @@ void UnixSocket::Bind(const Address &address) GenericSocket::Bind(address); // Always set proper permissions to the socket file - chmod(address.GetAddress().c_str(), 0777); + if(chmod(address.GetAddress().c_str(), 0777)<0){ + LogError("Error setting permissions to the socket file. Errno " << strerror(errno)); + } } - } } // namespace DPL diff --git a/modules/test/include/dpl/test/test_results_collector.h b/modules/test/include/dpl/test/test_results_collector.h index cf8fa4e..d3f44bb 100644 --- a/modules/test/include/dpl/test/test_results_collector.h +++ b/modules/test/include/dpl/test/test_results_collector.h @@ -23,12 +23,12 @@ #ifndef DPL_TEST_RESULTS_COLLECTOR_H #define DPL_TEST_RESULTS_COLLECTOR_H -#include #include #include #include #include #include +#include namespace DPL { @@ -36,7 +36,7 @@ namespace Test { class TestResultsCollectorBase; -typedef DPL::SharedPtr +typedef std::shared_ptr TestResultsCollectorBasePtr; class TestResultsCollectorBase diff --git a/modules/test/src/test_results_collector.cpp b/modules/test/src/test_results_collector.cpp index 029393d..d481aa5 100644 --- a/modules/test/src/test_results_collector.cpp +++ b/modules/test/src/test_results_collector.cpp @@ -27,11 +27,14 @@ #include #include +#include #include #include #include #include +#define GREEN_RESULT_OK "[%s%s%s]\n", BOLD_GREEN_BEGIN, " OK ", BOLD_GREEN_END + namespace DPL { namespace Test @@ -43,6 +46,16 @@ const char *DEFAULT_HTML_FILE_NAME = "index.html"; const char *DEFAULT_TAP_FILE_NAME = "results.tap"; const char *DEFAULT_XML_FILE_NAME = "results.xml"; +bool ParseCollectorFileArg(const std::string &arg, std::string &filename) +{ + const std::string argname = "--file="; + if (0 == arg.find(argname)) { + filename = arg.substr(argname.size()); + return true; + } + return false; +} + class Statistic { public: @@ -125,7 +138,7 @@ class ConsoleCollector printf("Running test case %-60s", tmp.c_str()); switch(status) { case TestResultsCollectorBase::FailStatus::NONE: - printf("[%s%s%s]\n", BOLD_GREEN_BEGIN, " OK ", BOLD_GREEN_END); break; + printf(GREEN_RESULT_OK); break; case TestResultsCollectorBase::FailStatus::FAILED: PrintfErrorMessage( " FAILED ", reason, true); break; case TestResultsCollectorBase::FailStatus::IGNORED: @@ -265,13 +278,7 @@ class HtmlCollector virtual bool ParseCollectorSpecificArg(const std::string& arg) { - const std::string argname = "--file="; - if (0 == arg.find(argname)) { - m_filename = arg.substr(argname.size()); - return true; - } else { - return false; - } + return ParseCollectorFileArg(arg, m_filename); } virtual void CollectResult(const std::string& id, @@ -285,7 +292,7 @@ class HtmlCollector fprintf(m_fp.Get(), "Running test case %-100s", tmp.c_str()); switch(status) { case TestResultsCollectorBase::FailStatus::NONE: - fprintf(m_fp.Get(), "[%s%s%s]\n", BOLD_GREEN_BEGIN, " OK ", BOLD_GREEN_END); break; + fprintf(m_fp.Get(), GREEN_RESULT_OK); break; case TestResultsCollectorBase::FailStatus::FAILED: PrintfErrorMessage( " FAILED ", reason, true); break; case TestResultsCollectorBase::FailStatus::IGNORED: @@ -432,8 +439,10 @@ class XmlCollector m_outputBuffer.erase(posBegin - 3, posEnd - posBegin + sizeof("") + 2); } + if(remove(m_filename.c_str())!=0){ + LogError("Can't remove file. Error: " << strerror(errno)); + } - remove(m_filename.c_str()); m_fp.Reset(fopen (m_filename.c_str(), "w")); Assert(!!m_fp && "File handle must not be null"); fseek(m_fp.Get(), 0L, SEEK_SET); @@ -443,13 +452,7 @@ class XmlCollector virtual bool ParseCollectorSpecificArg(const std::string& arg) { - const std::string argname = "--file="; - if (0 == arg.find(argname)) { - m_filename = arg.substr(argname.size()); - return true; - } else { - return false; - } + return ParseCollectorFileArg(arg, m_filename); } virtual void CollectResult(const std::string& id, @@ -698,17 +701,9 @@ class TAPCollector virtual bool ParseCollectorSpecificArg(const std::string& arg) { - const std::string argname = "--file="; - if (0 == arg.find(argname)) { - m_filename = arg.substr(argname.size()); - return true; - } else { - return false; - } + return ParseCollectorFileArg(arg, m_filename); } - - virtual void CollectResult(const std::string& id, const std::string& description, const FailStatus::Type status = FailStatus::NONE, @@ -832,3 +827,4 @@ int RegisterCollectorConstructors() } } +#undef GREEN_RESULT_OK diff --git a/modules/test/src/test_runner.cpp b/modules/test/src/test_runner.cpp index 8ad093a..506dd10 100644 --- a/modules/test/src/test_runner.cpp +++ b/modules/test/src/test_runner.cpp @@ -417,7 +417,7 @@ int TestRunner::ExecTestRunner(const ArgsList& value) Usage(); return -1; } - currentCollector.Reset(TestResultsCollectorBase::Create(arg)); + currentCollector.reset(TestResultsCollectorBase::Create(arg)); if (!currentCollector) { InvalidArgs("Unsupported output type!"); Usage(); @@ -469,7 +469,7 @@ int TestRunner::ExecTestRunner(const ArgsList& value) } } - currentCollector.Reset(); + currentCollector.reset(); // Show help if (showHelp) diff --git a/modules/utils/src/wrt_global_settings.cpp b/modules/utils/src/wrt_global_settings.cpp index 9cc9c56..9428fb3 100644 --- a/modules/utils/src/wrt_global_settings.cpp +++ b/modules/utils/src/wrt_global_settings.cpp @@ -67,7 +67,7 @@ MachineType getMachineType() // get current machine name struct utsname u; if (0 == uname(&u)) { - if ((!u.machine) || (0 == strlen(u.machine))) { + if (0 == strlen(u.machine)) { return MACHINE_TYPE_UNKNOWN; } else { // If current machine is emul, diff --git a/modules/widget_dao/CMakeLists.txt b/modules/widget_dao/CMakeLists.txt index c6f7057..cf1034f 100644 --- a/modules/widget_dao/CMakeLists.txt +++ b/modules/widget_dao/CMakeLists.txt @@ -1,3 +1,5 @@ +SET(TARGET_WRT_DAO_DB "Sqlite3DbWRT") + ADD_CUSTOM_COMMAND( OUTPUT ${CMAKE_BINARY_DIR}/modules/widget_dao/database_checksum.h COMMAND ${CMAKE_SOURCE_DIR}/modules/widget_dao/orm/gen_db_md5.sh @@ -22,7 +24,7 @@ ADD_CUSTOM_COMMAND( OUTPUT .wrt.db-journal ARGS ${CMAKE_CURRENT_BINARY_DIR}/.wrt.db-journal ) -ADD_CUSTOM_TARGET(Sqlite3DbWRT ALL DEPENDS .wrt.db .wrt.db-journal) +ADD_CUSTOM_TARGET(${TARGET_WRT_DAO_DB} ALL DEPENDS .wrt.db .wrt.db-journal) INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/wrt_db.sql DESTINATION share/wrt-engine/ @@ -68,10 +70,10 @@ SET(WRT_DAO_INCLUDE_DIRS ${PROJECT_SOURCE_DIR}/modules/db/include ${PROJECT_SOURCE_DIR}/modules/log/include ${PROJECT_SOURCE_DIR}/modules/localization/include - ${WRT_DAO_DEPS_INCLUDE_DIRS} - ) +) INCLUDE_DIRECTORIES(${WRT_DAO_INCLUDE_DIRS}) +INCLUDE_DIRECTORIES(SYSTEM ${WRT_DAO_DEPS_INCLUDE_DIRS}) ADD_LIBRARY(${TARGET_WRT_DAO_RO_LIB} SHARED ${WRT_DAO_RO_SOURCES} @@ -90,6 +92,7 @@ target_link_libraries(${TARGET_WRT_DAO_RO_LIB} ${TARGET_DPL_EFL} ${TARGET_DPL_DB_EFL} ${WRT_DAO_DEPS_LIBRARIES}) +ADD_DEPENDENCIES(${TARGET_WRT_DAO_RO_LIB} ${TARGET_WRT_DAO_DB}) ADD_LIBRARY(${TARGET_WRT_DAO_RW_LIB} SHARED ${WRT_DAO_RW_SOURCES}) @@ -104,6 +107,7 @@ SET_TARGET_PROPERTIES(${TARGET_WRT_DAO_RW_LIB} PROPERTIES target_link_libraries(${TARGET_WRT_DAO_RW_LIB} ${TARGET_WRT_DAO_RO_LIB}) +ADD_DEPENDENCIES(${TARGET_WRT_DAO_RW_LIB} ${TARGET_WRT_DAO_DB}) INSTALL(TARGETS ${TARGET_WRT_DAO_RO_LIB} DESTINATION lib) @@ -122,11 +126,12 @@ INSTALL(FILES include/dpl/wrt-dao-ro/plugin_dao_read_only.h include/dpl/wrt-dao-ro/property_dao_read_only.h include/dpl/wrt-dao-ro/widget_config.h + include/dpl/wrt-dao-ro/vconf_config.h include/dpl/wrt-dao-ro/widget_dao_read_only.h include/dpl/wrt-dao-ro/wrt_db_types.h include/dpl/wrt-dao-ro/WrtDatabase.h DESTINATION include/dpl-efl/dpl/wrt-dao-ro - ) + ) INSTALL(FILES include/dpl/wrt-dao-rw/feature_dao.h diff --git a/modules/widget_dao/dao/bind_to_dao.h b/modules/widget_dao/dao/bind_to_dao.h deleted file mode 100644 index 9b9c2d3..0000000 --- a/modules/widget_dao/dao/bind_to_dao.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @file bind_to_dao.h - * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) - * @version 1.0 - * @brief - */ - -#ifndef WRT_SRC_CONFIGURATION_BIND_TO_DAO_H_ -#define WRT_SRC_CONFIGURATION_BIND_TO_DAO_H_ - -namespace WrtDB { - -/** - * @param ObjectType type of object used as delegate argument - * @param RetType Type returned from the external function - * @param ExtArg Type of argument required by external fun - * @param getterFun Object Type method which returns value of type ExtArg - * used as argument for external function - * */ -//STATIC FUNCTION -template < - typename ObjectType, - typename ValueType, - typename ExtArg, - ExtArg(ObjectType::*argGetter) () const, - ValueType(*externalGetter) (ExtArg) - > -struct BindToDAO_Static -{ - static ValueType Get(DPL::Model* obj) - { - ObjectType* instance = static_cast(obj); - - return externalGetter((instance->*argGetter)()); - } -}; - -template < - typename ObjectType, - typename ValueType, - typename ExtArg, - typename ExtObject, - ExtArg(ObjectType::*argGetter) () const, - ValueType(ExtObject::*externalGetter) () const - > -struct BindToDAO -{ - static ValueType Get(DPL::Model* obj) - { - ObjectType* instance = static_cast(obj); - ExtObject extObject((instance->*argGetter)()); - return (extObject.*externalGetter)(); - } -}; - -} // namespace WrtDB - -#endif diff --git a/modules/widget_dao/dao/config_parser_data.cpp b/modules/widget_dao/dao/config_parser_data.cpp old mode 100644 new mode 100755 index 4d0968b..2fbd0f6 --- a/modules/widget_dao/dao/config_parser_data.cpp +++ b/modules/widget_dao/dao/config_parser_data.cpp @@ -299,6 +299,36 @@ bool ConfigParserData::Feature::operator<=(const Feature& other) const return paramsList <= other.paramsList; } +bool ConfigParserData::Privilege::operator==(const Privilege& other) const +{ + return name == other.name; +} + +bool ConfigParserData::Privilege::operator!=(const Privilege& other) const +{ + return name != other.name; +} + +bool ConfigParserData::Privilege::operator >(const Privilege& other) const +{ + return name > other.name; +} + +bool ConfigParserData::Privilege::operator>=(const Privilege& other) const +{ + return name >= other.name; +} + +bool ConfigParserData::Privilege::operator <(const Privilege& other) const +{ + return name < other.name; +} + +bool ConfigParserData::Privilege::operator<=(const Privilege& other) const +{ + return name < other.name; +} + bool ConfigParserData::Icon::operator==(const Icon& other) const { return src == other.src; @@ -427,4 +457,25 @@ bool ConfigParserData::ServiceInfo::operator!= (const ServiceInfo& info) const m_scheme != info.m_scheme && m_mime != info.m_mime; } + +bool ConfigParserData::LiveboxInfo::operator==(const LiveboxInfo& other) const +{ + return m_liveboxId == other.m_liveboxId && + m_autoLaunch == other.m_autoLaunch && + m_updatePeriod == other.m_updatePeriod && + m_primary == other.m_primary && + m_label == other.m_label && + m_icon == other.m_icon; +} + +bool ConfigParserData::LiveboxInfo::operator!=(const LiveboxInfo& other) const +{ + return m_liveboxId != other.m_liveboxId && + m_autoLaunch != other.m_autoLaunch && + m_updatePeriod != other.m_updatePeriod && + m_primary != other.m_primary && + m_label != other.m_label && + m_icon != other.m_icon; +} + } // namespace WrtDB diff --git a/modules/widget_dao/dao/plugin_dao.cpp b/modules/widget_dao/dao/plugin_dao.cpp index edfa08c..804c739 100644 --- a/modules/widget_dao/dao/plugin_dao.cpp +++ b/modules/widget_dao/dao/plugin_dao.cpp @@ -216,10 +216,9 @@ void PluginDAO::unregisterPlugin(DbPluginHandle pluginHandle) Try { DPL::DB::ORM::wrt::ScopedTransaction transaction( &WrtDatabase::interface()); - DbPluginHandle handle; if (!isPluginInstalled(pluginHandle)) { - LogInfo("PluginHandle is invalid. Handle: " << handle); + LogInfo("PluginHandle is invalid. Handle: " << pluginHandle); return; } else { @@ -232,7 +231,7 @@ void PluginDAO::unregisterPlugin(DbPluginHandle pluginHandle) del->Execute(); transaction.Commit(); - LogDebug(" >> Plugin Unregistered. Handle: " << handle); + LogDebug(" >> Plugin Unregistered. Handle: " << pluginHandle); } } Catch(DPL::DB::SqlConnection::Exception::Base) diff --git a/modules/widget_dao/dao/property_dao.cpp b/modules/widget_dao/dao/property_dao.cpp index 9193b46..b509118 100644 --- a/modules/widget_dao/dao/property_dao.cpp +++ b/modules/widget_dao/dao/property_dao.cpp @@ -30,20 +30,26 @@ namespace WrtDB { namespace PropertyDAO { - +//deprecated void RemoveProperty(DbWidgetHandle widgetHandle, const PropertyDAOReadOnly::WidgetPropertyKey &key) +{ + RemoveProperty(WidgetDAOReadOnly::getPkgName(widgetHandle),key); +} + +void RemoveProperty(WidgetPkgName pkgName, + const PropertyDAOReadOnly::WidgetPropertyKey &key) { //TODO below there are two queries. // First query asks if given property can be removed, // Second removes it. Maybe it should be combined two one. - LogDebug("Removing Property. Handle: " << widgetHandle << ", key: " << key); + LogDebug("Removing Property. pkgName: " << pkgName << ", key: " << key); Try { DPL::DB::ORM::wrt::ScopedTransaction transaction(&WrtDatabase::interface()); DPL::OptionalInt readonly = PropertyDAOReadOnly::CheckPropertyReadFlag( - widgetHandle, + pkgName, key); if (!readonly.IsNull() && *readonly == 1) { LogError("'" << key << @@ -58,7 +64,7 @@ void RemoveProperty(DbWidgetHandle widgetHandle, using namespace DPL::DB::ORM::wrt; WRT_DB_DELETE(del, WidgetPreference, &WrtDatabase::interface()) del->Where(And( - Equals(widgetHandle), + Equals(pkgName), Equals(key))); del->Execute(); @@ -70,12 +76,21 @@ void RemoveProperty(DbWidgetHandle widgetHandle, } } +//deprecated void SetProperty(DbWidgetHandle widgetHandle, const PropertyDAOReadOnly::WidgetPropertyKey &key, const PropertyDAOReadOnly::WidgetPropertyValue &value, bool readOnly) { - LogDebug("Setting/updating Property. Handle: " << widgetHandle << + SetProperty(WidgetDAOReadOnly::getPkgName(widgetHandle),key,value,readOnly); +} + +void SetProperty(WidgetPkgName pkgName, + const PropertyDAOReadOnly::WidgetPropertyKey &key, + const PropertyDAOReadOnly::WidgetPropertyValue &value, + bool readOnly) +{ + LogDebug("Setting/updating Property. pkgName: " << pkgName << ", key: " << key); Try { using namespace DPL::DB::ORM; @@ -83,7 +98,7 @@ void SetProperty(DbWidgetHandle widgetHandle, DPL::DB::ORM::wrt::ScopedTransaction transaction(&WrtDatabase::interface()); DPL::OptionalInt readonly = PropertyDAOReadOnly::CheckPropertyReadFlag( - widgetHandle, + pkgName, key); if (!readonly.IsNull() && *readonly == 1) { LogError("'" << key << @@ -94,7 +109,7 @@ void SetProperty(DbWidgetHandle widgetHandle, if (readonly.IsNull()) { WidgetPreference::Row row; - row.Set_app_id(widgetHandle); + row.Set_pkgname(pkgName); row.Set_key_name(key); row.Set_key_value(value); row.Set_readonly(readOnly ? 1 : 0); @@ -108,7 +123,7 @@ void SetProperty(DbWidgetHandle widgetHandle, WRT_DB_UPDATE(update, WidgetPreference, &WrtDatabase::interface()) update->Where(And( - Equals(widgetHandle), + Equals(pkgName), Equals(key))); update->Values(row); @@ -122,10 +137,17 @@ void SetProperty(DbWidgetHandle widgetHandle, } } +//deprecated void RegisterProperties(DbWidgetHandle widgetHandle, const WidgetRegisterInfo ®Info) { - LogDebug("Registering proferences for widget. Handle: " << widgetHandle); + RegisterProperties(WidgetDAOReadOnly::getPkgName(widgetHandle),regInfo); +} + +void RegisterProperties(WidgetPkgName pkgName, + const WidgetRegisterInfo ®Info) +{ + LogDebug("Registering proferences for widget. pkgName: " << pkgName); // Try-Catch in WidgetDAO @@ -137,7 +159,7 @@ void RegisterProperties(DbWidgetHandle widgetHandle, { { // Insert into table Widget Preferences WidgetPreference::Row row; - row.Set_app_id(widgetHandle); + row.Set_pkgname(pkgName); row.Set_key_name(it->name); row.Set_key_value(it->value); int readonly = true == it->readonly ? 1 : 0; diff --git a/modules/widget_dao/dao/property_dao_read_only.cpp b/modules/widget_dao/dao/property_dao_read_only.cpp index 2e6c121..1bc172c 100644 --- a/modules/widget_dao/dao/property_dao_read_only.cpp +++ b/modules/widget_dao/dao/property_dao_read_only.cpp @@ -21,6 +21,7 @@ */ #include #include +#include #include #include #include @@ -58,7 +59,7 @@ void convertWidgetPreferenceRow(const ORMWidgetPreferenceList& ormWidgetPrefRow, FOREACH(it, ormWidgetPrefRow) { WidgetPreferenceRow row; - row.app_id = it->Get_app_id(); + row.pkgname = it->Get_pkgname(); row.key_name = it->Get_key_name(); row.key_value = it->Get_key_value(); row.readonly = it->Get_readonly(); @@ -78,15 +79,50 @@ void convertWidgetPropertyKeyList(const ORMWidgetPropertyKeyList& propKeyList, } +//deprecated +DPL::OptionalInt CheckPropertyReadFlag(DbWidgetHandle widgetHandle, + const WidgetPropertyKey &key) +{ + return CheckPropertyReadFlag(WidgetDAOReadOnly::getPkgName(widgetHandle), + key); +} + +DPL::OptionalInt CheckPropertyReadFlag(WidgetPkgName pkgName, + const WidgetPropertyKey &key) +{ + LogDebug("Checking Property flag. pkgName: " << pkgName << + ", key: " << key); + + Try { + using namespace DPL::DB::ORM; + using namespace DPL::DB::ORM::wrt; + WRT_DB_SELECT(select, WidgetPreference, &WrtDatabase::interface()) + select->Where(And(Equals(pkgName), + Equals(key))); + + return select->GetSingleValue(); + } + Catch(DPL::DB::SqlConnection::Exception::Base){ + ReThrowMsg(Exception::DatabaseError, + "Failure during checking readonly flag for property"); + } +} + +//deprecated WidgetPropertyKeyList GetPropertyKeyList(DbWidgetHandle widgetHandle) { - LogDebug("Get PropertyKey list. Handle: " << widgetHandle); + return GetPropertyKeyList(WidgetDAOReadOnly::getPkgName(widgetHandle)); +} + +WidgetPropertyKeyList GetPropertyKeyList(WidgetPkgName pkgName) +{ + LogDebug("Get PropertyKey list. pkgName: " << pkgName); Try { using namespace DPL::DB::ORM; using namespace DPL::DB::ORM::wrt; ORMWidgetPropertyKeyList keyList; WRT_DB_SELECT(select, WidgetPreference, &WrtDatabase::interface()) - select->Where(Equals(widgetHandle)); + select->Where(Equals(pkgName)); keyList = select->GetValueList(); WidgetPropertyKeyList retKeyList; @@ -100,14 +136,26 @@ WidgetPropertyKeyList GetPropertyKeyList(DbWidgetHandle widgetHandle) } } +//deprecated WidgetPreferenceList GetPropertyList(DbWidgetHandle widgetHandle) { - LogDebug("Get Property list. Handle: " << widgetHandle); + Try{ + WidgetPkgName pkgName=WidgetDAOReadOnly::getPkgName(widgetHandle); + return GetPropertyList(pkgName); + }Catch(WidgetDAOReadOnly::Exception::WidgetNotExist){ + WidgetPreferenceList empty; + return empty; + } +} + +WidgetPreferenceList GetPropertyList(WidgetPkgName pkgName) +{ + LogDebug("Get Property list. pkgName: " << pkgName); Try { using namespace DPL::DB::ORM; using namespace DPL::DB::ORM::wrt; WRT_DB_SELECT(select, WidgetPreference, &WrtDatabase::interface()) - select->Where(Equals(widgetHandle)); + select->Where(Equals(pkgName)); ORMWidgetPreferenceList ormPrefList = select->GetRowList(); WidgetPreferenceList prefList; @@ -121,16 +169,23 @@ WidgetPreferenceList GetPropertyList(DbWidgetHandle widgetHandle) } } +//deprecated WidgetPropertyValue GetPropertyValue(DbWidgetHandle widgetHandle, const WidgetPropertyKey &key) { - LogDebug("Get Property value. Handle: " << widgetHandle << + return GetPropertyValue(WidgetDAOReadOnly::getPkgName(widgetHandle),key); +} + +WidgetPropertyValue GetPropertyValue(WidgetPkgName pkgName, + const WidgetPropertyKey &key) +{ + LogDebug("Get Property value. pkgName: " << pkgName << ", key: " << key); Try { using namespace DPL::DB::ORM; using namespace DPL::DB::ORM::wrt; WRT_DB_SELECT(select, WidgetPreference, &WrtDatabase::interface()) - select->Where(And(Equals(widgetHandle), + select->Where(And(Equals(pkgName), Equals(key))); ORMWidgetPropertyValue ormPropValue = @@ -148,25 +203,5 @@ WidgetPropertyValue GetPropertyValue(DbWidgetHandle widgetHandle, } } -DPL::OptionalInt CheckPropertyReadFlag(DbWidgetHandle widgetHandle, - const WidgetPropertyKey &key) -{ - LogDebug("Checking Property flag. Handle: " << widgetHandle << - ", key: " << key); - Try { - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::wrt; - WRT_DB_SELECT(select, WidgetPreference, &WrtDatabase::interface()) - select->Where(And(Equals(widgetHandle), - Equals(key))); - - return select->GetSingleValue(); - } - Catch(DPL::DB::SqlConnection::Exception::Base){ - ReThrowMsg(Exception::DatabaseError, - "Failure during checking readonly flag for property"); - } -} - } // namespace PropertyDAOReadOnly } // namespace WrtDB diff --git a/modules/widget_dao/dao/widget_dao.cpp b/modules/widget_dao/dao/widget_dao.cpp index deb55d2..e078797 100644 --- a/modules/widget_dao/dao/widget_dao.cpp +++ b/modules/widget_dao/dao/widget_dao.cpp @@ -97,13 +97,24 @@ void WidgetDAO::setProperty( } void WidgetDAO::setPkgName(const DPL::OptionalString& pkgName) +{ + + // if(!!pkgName) + setPkgName_TEMPORARY_API(*pkgName); +} + + +void WidgetDAO::setPkgName_TEMPORARY_API(const WidgetPkgName& pkgName) { SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { using namespace DPL::DB::ORM; wrt::ScopedTransaction transaction(&WrtDatabase::interface()); - isWidgetInstalled(getHandle()); + if (!isWidgetInstalled(getHandle())) { + ThrowMsg(WidgetDAOReadOnly::Exception::WidgetNotExist, + "Cannot find widget. Handle: " << getHandle()); + } wrt::WidgetInfo::Row row; row.Set_pkgname(pkgName); @@ -119,6 +130,136 @@ void WidgetDAO::setPkgName(const DPL::OptionalString& pkgName) SQL_CONNECTION_EXCEPTION_HANDLER_END("Failed to register widget") } +void WidgetDAO::setSecurityPopupUsage(const SettingsType value) +{ + SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN + { + using namespace DPL::DB::ORM; + using namespace DPL::DB::ORM::wrt; + + ScopedTransaction transaction(&WrtDatabase::interface()); + if (!isWidgetInstalled(getHandle())) { + ThrowMsg(WidgetDAOReadOnly::Exception::WidgetNotExist, + "Cannot find widget. Handle: " << getHandle()); + } + + WidgetSecuritySettings::Row row; + row.Set_security_popup_usage(value); + + WRT_DB_UPDATE(update, WidgetSecuritySettings, &WrtDatabase::interface()) + update->Where(Equals(getHandle())); + update->Values(row); + update->Execute(); + + transaction.Commit(); + } + SQL_CONNECTION_EXCEPTION_HANDLER_END("Failed to set security popup usage") +} + +void WidgetDAO::setGeolocationUsage(const SettingsType value) +{ + SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN + { + using namespace DPL::DB::ORM; + using namespace DPL::DB::ORM::wrt; + + ScopedTransaction transaction(&WrtDatabase::interface()); + if (!isWidgetInstalled(getHandle())) { + ThrowMsg(WidgetDAOReadOnly::Exception::WidgetNotExist, + "Cannot find widget. Handle: " << getHandle()); + } + + WidgetSecuritySettings::Row row; + row.Set_geolocation_usage(value); + + WRT_DB_UPDATE(update, WidgetSecuritySettings, &WrtDatabase::interface()) + update->Where(Equals(getHandle())); + update->Values(row); + update->Execute(); + + transaction.Commit(); + } + SQL_CONNECTION_EXCEPTION_HANDLER_END("Failed to set geolocation usage") +} + +void WidgetDAO::setWebNotificationUsage(const SettingsType value) +{ + SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN + { + using namespace DPL::DB::ORM; + using namespace DPL::DB::ORM::wrt; + + ScopedTransaction transaction(&WrtDatabase::interface()); + if (!isWidgetInstalled(getHandle())) { + ThrowMsg(WidgetDAOReadOnly::Exception::WidgetNotExist, + "Cannot find widget. Handle: " << getHandle()); + } + + WidgetSecuritySettings::Row row; + row.Set_web_notification_usage(value); + + WRT_DB_UPDATE(update, WidgetSecuritySettings, &WrtDatabase::interface()) + update->Where(Equals(getHandle())); + update->Values(row); + update->Execute(); + + transaction.Commit(); + } + SQL_CONNECTION_EXCEPTION_HANDLER_END("Failed to set web notification usage") +} + +void WidgetDAO::setWebDatabaseUsage(const SettingsType value) +{ + SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN + { + using namespace DPL::DB::ORM; + using namespace DPL::DB::ORM::wrt; + + ScopedTransaction transaction(&WrtDatabase::interface()); + if (!isWidgetInstalled(getHandle())) { + ThrowMsg(WidgetDAOReadOnly::Exception::WidgetNotExist, + "Cannot find widget. Handle: " << getHandle()); + } + + WidgetSecuritySettings::Row row; + row.Set_web_database_usage(value); + + WRT_DB_UPDATE(update, WidgetSecuritySettings, &WrtDatabase::interface()) + update->Where(Equals(getHandle())); + update->Values(row); + update->Execute(); + + transaction.Commit(); + } + SQL_CONNECTION_EXCEPTION_HANDLER_END("Failed to set web database usage") +} + +void WidgetDAO::setFileSystemUsage(const SettingsType value) +{ + SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN + { + using namespace DPL::DB::ORM; + using namespace DPL::DB::ORM::wrt; + + ScopedTransaction transaction(&WrtDatabase::interface()); + if (!isWidgetInstalled(getHandle())) { + ThrowMsg(WidgetDAOReadOnly::Exception::WidgetNotExist, + "Cannot find widget. Handle: " << getHandle()); + } + + WidgetSecuritySettings::Row row; + row.Set_file_system_usage(value); + + WRT_DB_UPDATE(update, WidgetSecuritySettings, &WrtDatabase::interface()) + update->Where(Equals(getHandle())); + update->Values(row); + update->Execute(); + + transaction.Commit(); + } + SQL_CONNECTION_EXCEPTION_HANDLER_END("Failed to set filesystem usage") +} + void WidgetDAO::registerWidget( const WidgetPkgName & widgetPkgname, const WidgetRegisterInfo &widgetRegInfo, @@ -197,6 +338,8 @@ void WidgetDAO::registerWidgetInternal( registerWidgetFeatures(widgetHandle, widgetRegInfo); + registerWidgetPrivilege(widgetHandle, widgetRegInfo); + registerWidgetWindowModes(widgetHandle, widgetRegInfo); registerWidgetWarpInfo(widgetHandle, widgetRegInfo); @@ -218,6 +361,8 @@ void WidgetDAO::registerWidgetInternal( registerEncryptedResouceInfo(widgetHandle, widgetRegInfo); registerExternalLocations(widgetHandle, widgetRegInfo.externalLocations); + + registerWidgetSecuritySettings(widgetHandle); } void WidgetDAO::registerOrUpdateWidget( @@ -260,7 +405,7 @@ void WidgetDAO::registerWidgetExtendedInfo(DbWidgetHandle widgetHandle, row.Set_install_time(regInfo.installedTime); row.Set_splash_img_src(regInfo.configInfo.splashImgSrc); row.Set_background_page(regInfo.configInfo.backgroundPage); - + row.Set_installed_path(regInfo.widgetInstalledPath); DO_INSERT(row, WidgetExtendedInfo) } @@ -486,6 +631,22 @@ void WidgetDAO::registerWidgetFeatures(DbWidgetHandle widgetHandle, } } +void WidgetDAO::registerWidgetPrivilege(DbWidgetHandle widgetHandle, + const WidgetRegisterInfo ®Info) +{ + using namespace DPL::DB::ORM; + const ConfigParserData& widgetConfigurationInfo = regInfo.configInfo; + + FOREACH(it, widgetConfigurationInfo.privilegeList) + { + wrt::WidgetPrivilege::Row widgetPrivilege; + widgetPrivilege.Set_app_id(widgetHandle); + widgetPrivilege.Set_name(it->name); + + DO_INSERT(widgetPrivilege, wrt::WidgetPrivilege) + } +} + void WidgetDAO::updateFeatureRejectStatus(const DbWidgetFeature &widgetFeature){ // This function could be merged with registerWidgetFeature but it requires desing change: // 1. Check "ace step" in installer must be done before "update database step" @@ -664,6 +825,21 @@ void WidgetDAO::registerExternalLocations(DbWidgetHandle widgetHandle, SQL_CONNECTION_EXCEPTION_HANDLER_END("Failed to register external files"); } +void WidgetDAO::registerWidgetSecuritySettings(DbWidgetHandle widgetHandle) +{ + using namespace DPL::DB::ORM; + using namespace DPL::DB::ORM::wrt; + WidgetSecuritySettings::Row row; + row.Set_app_id(widgetHandle); + row.Set_security_popup_usage(SETTINGS_TYPE_ON); + row.Set_geolocation_usage(SETTINGS_TYPE_ON); + row.Set_web_notification_usage(SETTINGS_TYPE_ON); + row.Set_web_database_usage(SETTINGS_TYPE_ON); + row.Set_file_system_usage(SETTINGS_TYPE_ON); + + DO_INSERT(row, WidgetSecuritySettings) +} + void WidgetDAO::unregisterAllExternalLocations() { using namespace DPL::DB::ORM; diff --git a/modules/widget_dao/dao/widget_dao_read_only.cpp b/modules/widget_dao/dao/widget_dao_read_only.cpp index aa54c6b..58a8c27 100644 --- a/modules/widget_dao/dao/widget_dao_read_only.cpp +++ b/modules/widget_dao/dao/widget_dao_read_only.cpp @@ -64,17 +64,20 @@ namespace WrtDB { typedef DPL::DB::ORM::wrt::WidgetInfo::Row WidgetInfoRow; typedef DPL::DB::ORM::wrt::WidgetFeature::widget_feature_id::ColumnType - WidgetFeatureId; + WidgetFeatureId; +typedef DPL::DB::ORM::wrt::WidgetSecuritySettings::Row + WidgetSecuritySettingsRow; namespace { +using namespace DPL::DB::ORM; +using namespace DPL::DB::ORM::wrt; + WidgetInfoRow getWidgetInfoRow(int widgetHandle) { LogDebug("Getting WidgetInfo row. Handle: " << widgetHandle); SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::wrt; WRT_DB_SELECT(select, WidgetInfo, &WrtDatabase::interface()) select->Where(Equals(widgetHandle)); @@ -88,8 +91,49 @@ WidgetInfoRow getWidgetInfoRow(int widgetHandle) SQL_CONNECTION_EXCEPTION_HANDLER_END("Failed in GetWidgetInfoRow") } +WidgetSecuritySettingsRow getWidgetSecuritySettingsRow(int widgetHandle) +{ + LogDebug("Getting WidgetSecuritySettings row. Handle: " << widgetHandle); + SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN + { + using namespace DPL::DB::ORM; + using namespace DPL::DB::ORM::wrt; + WRT_DB_SELECT(select, WidgetSecuritySettings, &WrtDatabase::interface()) + select->Where(Equals(widgetHandle)); + + WidgetSecuritySettings::Select::RowList rows = select->GetRowList(); + if (rows.empty()) { + ThrowMsg(WidgetDAOReadOnly::Exception::WidgetNotExist, + "Cannot find widget. Handle: " << widgetHandle); + } + return rows.front(); + } + SQL_CONNECTION_EXCEPTION_HANDLER_END("Failed in getWidgetSecuritySettingsRow") +} + const int MAX_TIZENID_LENGTH = 10; +WidgetPkgName getPkgNameByHandle(const DbWidgetHandle handle) +{ + LogDebug("Getting WidgetPkgName by DbWidgetHandle: " << handle); + + SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN + { + WRT_DB_SELECT(select, WidgetInfo, &WrtDatabase::interface()) + select->Where(Equals(handle)); + WidgetInfo::Select::RowList rowList = select->GetRowList(); + + if (rowList.empty()) { + ThrowMsg(WidgetDAOReadOnly::Exception::WidgetNotExist, + "Failed to get widget by handle"); + } + WidgetPkgName pkgname = rowList.front().Get_pkgname(); + + return pkgname; + + } + SQL_CONNECTION_EXCEPTION_HANDLER_END("Failed in getHandle") +} } // namespace @@ -128,8 +172,6 @@ DbWidgetHandle WidgetDAOReadOnly::getHandle(const WidgetGUID GUID) SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::wrt; WRT_DB_SELECT(select, WidgetInfo, &WrtDatabase::interface()) select->Where(Equals(GUID)); WidgetInfo::Select::RowList rowList = select->GetRowList(); @@ -141,9 +183,6 @@ DbWidgetHandle WidgetDAOReadOnly::getHandle(const WidgetGUID GUID) return rowList.front().Get_app_id(); } SQL_CONNECTION_EXCEPTION_HANDLER_END("Failed in getHandle") - - ThrowMsg(WidgetDAOReadOnly::Exception::WidgetNotExist, - "Failed to get widget by guid"); } DbWidgetHandle WidgetDAOReadOnly::getHandle(const DPL::String pkgName) @@ -152,8 +191,6 @@ DbWidgetHandle WidgetDAOReadOnly::getHandle(const DPL::String pkgName) SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::wrt; WRT_DB_SELECT(select, WidgetInfo, &WrtDatabase::interface()) select->Where(Equals(pkgName)); WidgetInfo::Select::RowList rowList = select->GetRowList(); @@ -165,45 +202,52 @@ DbWidgetHandle WidgetDAOReadOnly::getHandle(const DPL::String pkgName) return rowList.front().Get_app_id(); } SQL_CONNECTION_EXCEPTION_HANDLER_END("Failed in getHandle") +} - ThrowMsg(WidgetDAOReadOnly::Exception::WidgetNotExist, - "Failed to get widget by package name"); +WidgetPkgName WidgetDAOReadOnly::getPkgName() const +{ + return getPkgNameByHandle(m_widgetHandle); +} + +WidgetPkgName WidgetDAOReadOnly::getPkgName(const WidgetGUID GUID) +{ + return getPkgNameByHandle(getHandle(GUID)); +} + +WidgetPkgName WidgetDAOReadOnly::getPkgName(const DbWidgetHandle handle) +{ + return getPkgNameByHandle(handle); } PropertyDAOReadOnly::WidgetPropertyKeyList WidgetDAOReadOnly::getPropertyKeyList() const { - return PropertyDAOReadOnly::GetPropertyKeyList(m_widgetHandle); + return PropertyDAOReadOnly::GetPropertyKeyList(getPkgName()); } PropertyDAOReadOnly::WidgetPreferenceList WidgetDAOReadOnly::getPropertyList() const { - return PropertyDAOReadOnly::GetPropertyList(m_widgetHandle); + return PropertyDAOReadOnly::GetPropertyList(getPkgName()); } PropertyDAOReadOnly::WidgetPropertyValue WidgetDAOReadOnly::getPropertyValue( const PropertyDAOReadOnly::WidgetPropertyKey &key) const { - return PropertyDAOReadOnly::GetPropertyValue(m_widgetHandle, key); + return PropertyDAOReadOnly::GetPropertyValue(getPkgName(), key); } DPL::OptionalInt WidgetDAOReadOnly::checkPropertyReadFlag( const PropertyDAOReadOnly::WidgetPropertyKey &key) const { - return PropertyDAOReadOnly::CheckPropertyReadFlag(m_widgetHandle, key); + return PropertyDAOReadOnly::CheckPropertyReadFlag(getPkgName(), key); } DPL::String WidgetDAOReadOnly::getPath() const { - DPL::String path = DPL::FromUTF8String( - GlobalConfig::GetUserInstalledWidgetPath()); + DPL::String path = *getWidgetInstalledPath(); DPL::String srcPath = DPL::FromUTF8String(GlobalConfig::GetWidgetSrcPath()); - DPL::OStringStream strAppId; - strAppId << m_widgetHandle; - DPL::OptionalString pkgname = getPkgname(); - path += L"/" + *pkgname; path += srcPath + L"/"; return path; @@ -221,11 +265,9 @@ WidgetLocalizedInfo LogDebug("Getting Localized Info. Handle: " << m_widgetHandle); SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { - DPL::DB::ORM::wrt::ScopedTransaction transaction(&WrtDatabase::interface()); + ScopedTransaction transaction(&WrtDatabase::interface()); CHECK_WIDGET_EXISTENCE(transaction, m_widgetHandle) - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::wrt; WRT_DB_SELECT(select, LocalizedWidgetInfo, &WrtDatabase::interface()) select->Where( And(Equals(m_widgetHandle), @@ -250,16 +292,14 @@ DbWidgetFeatureSet WidgetDAOReadOnly::getFeaturesList() const LogDebug("Getting FeaturesList. Handle: " << m_widgetHandle); SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { - DPL::DB::ORM::wrt::ScopedTransaction transaction(&WrtDatabase::interface()); + ScopedTransaction transaction(&WrtDatabase::interface()); CHECK_WIDGET_EXISTENCE(transaction, m_widgetHandle) - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::wrt; - WRT_DB_SELECT(select, DPL::DB::ORM::wrt::WidgetFeature, &WrtDatabase::interface()) - select->Where(Equals(m_widgetHandle)); + WRT_DB_SELECT(select, WidgetFeature, &WrtDatabase::interface()) + select->Where(Equals(m_widgetHandle)); DbWidgetFeatureSet resultSet; - typedef std::list RowList; + typedef std::list RowList; RowList list = select->GetRowList(); for (RowList::iterator i = list.begin(); i != list.end(); ++i) { @@ -284,14 +324,12 @@ WidgetParamMap WidgetDAOReadOnly::getFeatureParams(int id) LogDebug("Getting feature Params. featureId: " << widgetFeatureId); SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::wrt; - WRT_DB_SELECT(select, DPL::DB::ORM::wrt::FeatureParam, &WrtDatabase::interface()) - select->Where(Equals( + WRT_DB_SELECT(select, FeatureParam, &WrtDatabase::interface()) + select->Where(Equals( widgetFeatureId)); WidgetParamMap resultMap; - typedef std::list RowList; + typedef std::list RowList; RowList list = select->GetRowList(); FOREACH(i, list) @@ -309,11 +347,9 @@ bool WidgetDAOReadOnly::hasFeature(const std::string& featureName) const m_widgetHandle); SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { - DPL::DB::ORM::wrt::ScopedTransaction transaction(&WrtDatabase::interface()); + ScopedTransaction transaction(&WrtDatabase::interface()); CHECK_WIDGET_EXISTENCE(transaction, m_widgetHandle) - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::wrt; WRT_DB_SELECT(select, wrt::WidgetFeature, &WrtDatabase::interface()) select->Where(And(Equals(m_widgetHandle), Equals( @@ -331,11 +367,9 @@ HostList WidgetDAOReadOnly::getAccessHostList() const LogDebug("Getting AccessHostList. Handle: " << m_widgetHandle); SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { - DPL::DB::ORM::wrt::ScopedTransaction transaction(&WrtDatabase::interface()); + ScopedTransaction transaction(&WrtDatabase::interface()); CHECK_WIDGET_EXISTENCE(transaction, m_widgetHandle) - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::wrt; WRT_DB_SELECT(select, WidgetAccessHost, &WrtDatabase::interface()) select->Where(Equals(m_widgetHandle)); std::list values = @@ -362,8 +396,6 @@ DbWidgetHandleList WidgetDAOReadOnly::getHandleList() LogDebug("Getting DbWidgetHandle List"); SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::wrt; WRT_DB_SELECT(select, WidgetInfo, &WrtDatabase::interface()) return select->GetValueList(); } @@ -373,10 +405,19 @@ DbWidgetHandleList WidgetDAOReadOnly::getHandleList() WidgetPkgNameList WidgetDAOReadOnly::getPkgnameList() { LogDebug("Getting Pkgname List"); + WidgetPkgNameList_TEMPORARY_API pkgnameList_TEMPORARY_API = getPkgnameList_TEMPORARY_API(); + WidgetPkgNameList pkgnameList; + FOREACH(it,pkgnameList_TEMPORARY_API ){ + pkgnameList.push_back(DPL::Optional(*it)); + } + return pkgnameList; +} + +WidgetPkgNameList_TEMPORARY_API WidgetDAOReadOnly::getPkgnameList_TEMPORARY_API() +{ + LogDebug("Getting Pkgname List "); SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::wrt; WRT_DB_SELECT(select, WidgetInfo, &WrtDatabase::interface()) return select->GetValueList(); } @@ -398,8 +439,6 @@ bool WidgetDAOReadOnly::isWidgetInstalled(DbWidgetHandle handle) LogDebug("Checking if widget exist. Handle: " << handle); SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::wrt; WRT_DB_SELECT(select, WidgetInfo, &WrtDatabase::interface()) select->Where(Equals(handle)); @@ -415,8 +454,6 @@ bool WidgetDAOReadOnly::isWidgetInstalled(const WidgetPkgName & pkgName) LogDebug("Checking if widget exist. package name " << pkgName); SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::wrt; WRT_DB_SELECT(select, WidgetInfo, &WrtDatabase::interface()) select->Where(Equals(pkgName)); @@ -433,8 +470,6 @@ ExternalLocationList WidgetDAOReadOnly::getWidgetExternalLocations() const ExternalLocationList result; SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::wrt; WRT_DB_SELECT(select, WidgetExternalLocations, &WrtDatabase::interface()); select->Where(Equals(m_widgetHandle)); WidgetExternalLocations::Select::RowList rows = select->GetRowList(); @@ -450,15 +485,13 @@ ExternalLocationList WidgetDAOReadOnly::getWidgetExternalLocations() const CertificateChainList WidgetDAOReadOnly::getWidgetCertificate( CertificateSource source) const { - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::wrt; WRT_DB_SELECT(select, WidgetCertificate, &WrtDatabase::interface()) select->Where( And( Equals(m_widgetHandle), Equals(source))); - std::list chainList = select->GetRowList(); + std::list chainList = select->GetRowList(); CertificateChainList result; @@ -497,8 +530,7 @@ WidgetGUID WidgetDAOReadOnly::getGUID() const DPL::OptionalString WidgetDAOReadOnly::getPkgname() const { - WidgetInfoRow row = getWidgetInfoRow(m_widgetHandle); - return row.Get_pkgname(); + return DPL::OptionalString(getPkgName()); } DPL::OptionalString WidgetDAOReadOnly::getDefaultlocale() const @@ -541,8 +573,6 @@ std::string WidgetDAOReadOnly::getShareHref() const { SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::wrt; WRT_DB_SELECT(select, WidgetExtendedInfo, &WrtDatabase::interface()) select->Where(Equals(m_widgetHandle)); WidgetExtendedInfo::Select::RowList rows = select->GetRowList(); @@ -608,8 +638,6 @@ bool WidgetDAOReadOnly::isTrusted() const bool WidgetDAOReadOnly::isTestWidget() const { Try { - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::wrt; WRT_DB_SELECT(select, WidgetExtendedInfo, &WrtDatabase::interface()) select->Where(Equals(m_widgetHandle)); @@ -639,8 +667,6 @@ time_t WidgetDAOReadOnly::getInstallTime() const { SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::wrt; WRT_DB_SELECT(select, WidgetExtendedInfo, &WrtDatabase::interface()) select->Where(Equals(m_widgetHandle)); @@ -659,8 +685,6 @@ DPL::OptionalString WidgetDAOReadOnly::getSplashImgSrc() const { SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::wrt; WRT_DB_SELECT(select, WidgetExtendedInfo, &WrtDatabase::interface()) select->Where(Equals(m_widgetHandle)); @@ -685,12 +709,10 @@ WidgetDAOReadOnly::WidgetLocalizedIconList WidgetDAOReadOnly::getLocalizedIconLi //TODO check widget existance?? SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::wrt; WRT_DB_SELECT(select, WidgetLocalizedIcon, &WrtDatabase::interface()) select->Where(Equals(m_widgetHandle)); - std::list list = + std::list list = select->GetRowList(); WidgetLocalizedIconList ret; FOREACH(it,list) @@ -710,12 +732,10 @@ WidgetDAOReadOnly::WidgetIconList WidgetDAOReadOnly::getIconList() const //TODO check widget existance SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::wrt; WRT_DB_SELECT(select, wrt::WidgetIcon, &WrtDatabase::interface()) select->Where(Equals(m_widgetHandle)); - std::list list = + std::list list = select->GetRowList(); WidgetIconList ret; FOREACH(it,list) @@ -737,14 +757,12 @@ WidgetDAOReadOnly::LocalizedStartFileList WidgetDAOReadOnly::getLocalizedStartFi //TODO check widget existance SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::wrt; WRT_DB_SELECT(select, WidgetLocalizedStartFile, &WrtDatabase::interface()) select->Where(Equals( m_widgetHandle)); select->OrderBy("start_file_id ASC"); - std::list list = + std::list list = select->GetRowList(); LocalizedStartFileList ret; FOREACH(it,list) @@ -766,13 +784,11 @@ WidgetDAOReadOnly::WidgetStartFileList WidgetDAOReadOnly::getStartFileList() con //TODO check widget existance SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::wrt; WRT_DB_SELECT(select, WidgetStartFile, &WrtDatabase::interface()) select->Where(Equals(m_widgetHandle)); select->OrderBy("start_file_id ASC"); - std::list list = + std::list list = select->GetRowList(); WidgetStartFileList ret; FOREACH(it,list) @@ -792,8 +808,6 @@ WindowModeList WidgetDAOReadOnly::getWindowModes() const //TODO check widget existance SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::wrt; WRT_DB_SELECT(select, WidgetWindowModes, &WrtDatabase::interface()) select->Where(Equals(m_widgetHandle)); @@ -823,8 +837,6 @@ WidgetCertificateDataList WidgetDAOReadOnly::getCertificateDataList() const //TODO check widget existance SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::wrt; WRT_DB_SELECT(select, WidgetCertificateFingerprint, &WrtDatabase::interface()) select->Where(Equals( m_widgetHandle)); @@ -866,8 +878,6 @@ FingerPrintList WidgetDAOReadOnly::getKeyFingerprints( //TODO check widget existance SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::wrt; WRT_DB_SELECT(select, WidgetCertificateFingerprint, &WrtDatabase::interface()) select->Where(And(And( Equals(m_widgetHandle), @@ -901,8 +911,6 @@ WidgetCertificateCNList WidgetDAOReadOnly::getKeyCommonNameList( //TODO check widget existance SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::wrt; WRT_DB_SELECT(select, WidgetCertificateFingerprint, &WrtDatabase::interface()) select->Where(And(And( Equals(m_widgetHandle), @@ -926,14 +934,12 @@ WidgetCertificateCNList WidgetDAOReadOnly::getKeyCommonNameList( ResourceAttributeList WidgetDAOReadOnly::getResourceAttribute( const std::string &resourceId) const { - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::wrt; - WRT_DB_SELECT(select, DPL::DB::ORM::wrt::WidgetFeature, &WrtDatabase::interface()) - select->Where(And(Equals(m_widgetHandle), - Equals( + WRT_DB_SELECT(select, WidgetFeature, &WrtDatabase::interface()) + select->Where(And(Equals(m_widgetHandle), + Equals( DPL::FromUTF8String(resourceId)))); - std::list list = select->GetRowList(); + std::list list = select->GetRowList(); ResourceAttributeList result; if (!list.empty()) { int widgetFeatureId = list.begin()->Get_widget_feature_id(); @@ -951,8 +957,6 @@ void WidgetDAOReadOnly::getWidgetAccessInfo( //TODO check widget existance SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::wrt; WRT_DB_SELECT(select, WidgetWARPInfo, &WrtDatabase::interface()) select->Where(Equals(m_widgetHandle)); @@ -981,8 +985,6 @@ LanguageTags WidgetDAOReadOnly::getLanguageTags() const //TODO check widget existance SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::wrt; WRT_DB_SELECT(select, LocalizedWidgetInfo, &WrtDatabase::interface()) select->Where(Equals(m_widgetHandle)); return select->GetValueList(); @@ -993,8 +995,6 @@ LanguageTags WidgetDAOReadOnly::getLanguageTags() const LanguageTags WidgetDAOReadOnly::getIconLanguageTags() const { //TODO check widget existance - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::wrt; WRT_DB_SELECT(select, WidgetLocalizedIcon, &WrtDatabase::interface()) select->Where(Equals(m_widgetHandle)); select->Distinct(); @@ -1006,9 +1006,9 @@ std::string WidgetDAOReadOnly::getCookieDatabasePath() const using namespace WrtDB::WidgetConfig; std::ostringstream path; - DPL::OptionalString pkgname = getPkgname(); + WidgetPkgName pkgname = getPkgName(); - path << GetWidgetPersistentStoragePath(*pkgname); + path << GetWidgetPersistentStoragePath(pkgname); path << "/"; path << GlobalConfig::GetCookieDatabaseFile(); @@ -1018,8 +1018,8 @@ std::string WidgetDAOReadOnly::getCookieDatabasePath() const std::string WidgetDAOReadOnly::getPrivateLocalStoragePath() const { std::ostringstream path; - DPL::OptionalString pkgname = getPkgname(); - path << WidgetConfig::GetWidgetWebLocalStoragePath(*pkgname); + WidgetPkgName pkgname = getPkgName(); + path << WidgetConfig::GetWidgetWebLocalStoragePath(pkgname); path << "/"; return path.str(); @@ -1031,8 +1031,6 @@ void WidgetDAOReadOnly::getWidgetSettings( //TODO check widget existance SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::wrt; WRT_DB_SELECT(select, SettingsList, &WrtDatabase::interface()) select->Where(Equals(m_widgetHandle)); @@ -1056,11 +1054,9 @@ void WidgetDAOReadOnly::getAppServiceList( LogDebug("Getting getAppServiceList. Handle: " << m_widgetHandle); SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { - DPL::DB::ORM::wrt::ScopedTransaction transaction(&WrtDatabase::interface()); + ScopedTransaction transaction(&WrtDatabase::interface()); CHECK_WIDGET_EXISTENCE(transaction, m_widgetHandle) - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::wrt; WRT_DB_SELECT(select, ApplicationServiceInfo, &WrtDatabase::interface()) select->Where(Equals(m_widgetHandle)); @@ -1095,12 +1091,10 @@ PackagingType WidgetDAOReadOnly::getPackagingType() const void WidgetDAOReadOnly::getEncryptedFileList(EncryptedFileList& filesList) const { //TODO check widget existance - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::wrt; WRT_DB_SELECT(select, EncryptedResourceList, &WrtDatabase::interface()) select->Where(Equals(m_widgetHandle)); - typedef std::list RowList; + typedef std::list RowList; RowList list = select->GetRowList(); FOREACH(it, list) { @@ -1115,8 +1109,6 @@ DPL::OptionalString WidgetDAOReadOnly::getBackgroundPage() const { SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { - using namespace DPL::DB::ORM; - using namespace DPL::DB::ORM::wrt; WRT_DB_SELECT(select, WidgetExtendedInfo, &WrtDatabase::interface()) select->Where(Equals(m_widgetHandle)); @@ -1145,6 +1137,65 @@ WidgetPkgName WidgetDAOReadOnly::generateTizenId() { return tizenId; } +SettingsType WidgetDAOReadOnly::getSecurityPopupUsage(void) const +{ + WidgetSecuritySettingsRow row = + getWidgetSecuritySettingsRow(m_widgetHandle); + DPL::OptionalInt result = row.Get_security_popup_usage(); + return static_cast(*result); +} + +SettingsType WidgetDAOReadOnly::getGeolocationUsage(void) const +{ + WidgetSecuritySettingsRow row = + getWidgetSecuritySettingsRow(m_widgetHandle); + DPL::OptionalInt result = row.Get_geolocation_usage(); + return static_cast(*result); +} + +SettingsType WidgetDAOReadOnly::getWebNotificationUsage(void) const +{ + WidgetSecuritySettingsRow row = + getWidgetSecuritySettingsRow(m_widgetHandle); + DPL::OptionalInt result = row.Get_web_notification_usage(); + return static_cast(*result); +} + +SettingsType WidgetDAOReadOnly::getWebDatabaseUsage(void) const +{ + WidgetSecuritySettingsRow row = + getWidgetSecuritySettingsRow(m_widgetHandle); + DPL::OptionalInt result = row.Get_web_database_usage(); + return static_cast(*result); +} + +SettingsType WidgetDAOReadOnly::getFileSystemUsage(void) const +{ + WidgetSecuritySettingsRow row = + getWidgetSecuritySettingsRow(m_widgetHandle); + DPL::OptionalInt result = row.Get_file_system_usage(); + return static_cast(*result); +} + +DPL::OptionalString WidgetDAOReadOnly::getWidgetInstalledPath() const +{ + SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN + { + using namespace DPL::DB::ORM; + using namespace DPL::DB::ORM::wrt; + WRT_DB_SELECT(select, WidgetExtendedInfo, &WrtDatabase::interface()) + select->Where(Equals(m_widgetHandle)); + + WidgetExtendedInfo::Select::RowList rows = select->GetRowList(); + if (rows.empty()) { + ThrowMsg(WidgetDAOReadOnly::Exception::WidgetNotExist, + "Cannot find widget. Handle: " << m_widgetHandle); + } + + return rows.front().Get_installed_path(); + } + SQL_CONNECTION_EXCEPTION_HANDLER_END("Failed to get widdget installed path") +} #undef SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN #undef SQL_CONNECTION_EXCEPTION_HANDLER_END #undef CHECK_WIDGET_EXISTENCE diff --git a/modules/widget_dao/include/dpl/wrt-dao-ro/common_dao_types.h b/modules/widget_dao/include/dpl/wrt-dao-ro/common_dao_types.h index 36ee037..17ebf57 100644 --- a/modules/widget_dao/include/dpl/wrt-dao-ro/common_dao_types.h +++ b/modules/widget_dao/include/dpl/wrt-dao-ro/common_dao_types.h @@ -29,9 +29,9 @@ #include #include #include -#include -#include #include +#include + namespace WrtDB { class PluginMetafileData @@ -63,7 +63,7 @@ class PluginObjectsDAO { public: typedef std::set Objects; - typedef DPL::SharedPtr ObjectsPtr; + typedef std::shared_ptr ObjectsPtr; public: explicit PluginObjectsDAO() {} @@ -237,6 +237,7 @@ typedef std::multiset DbWidgetFeatureSet; typedef std::list DbWidgetHandleList; typedef std::list > WidgetPkgNameList; //TODO: this cannot be null -> appropriate changes in db schema needed +typedef std::list WidgetPkgNameList_TEMPORARY_API; //TODO: this cannot be null -> appropriate changes in db schema needed class WidgetDAOReadOnly; //forward declaration typedef std::shared_ptr WidgetDAOReadOnlyPtr; @@ -301,8 +302,9 @@ enum PkgType { PKG_TYPE_UNKNOWN = 0, // unknown PKG_TYPE_NOMAL_WEB_APP, + PKG_TYPE_DIRECTORY_WEB_APP, PKG_TYPE_HOSTED_WEB_APP, // request from browser - PKG_TYPE_HYBRID_WEB_APP, // Tizen webapp with C++ service app + PKG_TYPE_HYBRID_WEB_APP // Tizen webapp with C++ service app }; class PackagingType @@ -330,6 +332,7 @@ class PackagingType #define X(x) case x: return #x; X(PKG_TYPE_UNKNOWN) X(PKG_TYPE_NOMAL_WEB_APP) + X(PKG_TYPE_DIRECTORY_WEB_APP) X(PKG_TYPE_HOSTED_WEB_APP) X(PKG_TYPE_HYBRID_WEB_APP) #undef X @@ -341,6 +344,13 @@ class PackagingType PkgType pkgType; }; +enum SettingsType +{ + SETTINGS_TYPE_UNKNOWN = 0, + SETTINGS_TYPE_ON, + SETTINGS_TYPE_ALWAYS_ASK, + SETTINGS_TYPE_OFF +}; } // namespace WrtDB struct WidgetSetting diff --git a/modules/widget_dao/include/dpl/wrt-dao-ro/config_parser_data.h b/modules/widget_dao/include/dpl/wrt-dao-ro/config_parser_data.h old mode 100644 new mode 100755 index 7ec8a25..2520bd4 --- a/modules/widget_dao/include/dpl/wrt-dao-ro/config_parser_data.h +++ b/modules/widget_dao/include/dpl/wrt-dao-ro/config_parser_data.h @@ -77,6 +77,22 @@ class ConfigParserData }; typedef std::set FeaturesList; + struct Privilege + { + Privilege(const DPL::String& _name) : name(_name) + { + } + DPL::String name; + + bool operator==(const Privilege&) const; + bool operator!=(const Privilege&) const; + bool operator >(const Privilege&) const; + bool operator>=(const Privilege&) const; + bool operator <(const Privilege&) const; + bool operator<=(const Privilege&) const; + }; + typedef std::set PrivilegeList; + struct Icon { Icon(const DPL::String& _src) : src(_src) @@ -189,8 +205,44 @@ class ConfigParserData bool operator!=(const ServiceInfo&) const; }; typedef std::list ServiceInfoList; + + typedef std::list> BoxSizeList; + + struct LiveboxInfo + { + LiveboxInfo() { } + + struct BoxContent + { + DPL::String m_boxSrc; + BoxSizeList m_boxSize ; + DPL::String m_pdSrc; + DPL::String m_pdWidth; + DPL::String m_pdHeight; + }; typedef BoxContent BoxContentInfo; + + DPL::String m_label; + DPL::String m_icon; + DPL::String m_liveboxId; + DPL::String m_primary; + DPL::String m_autoLaunch; + DPL::String m_updatePeriod; + BoxContentInfo m_boxInfo; + + bool operator==(const LiveboxInfo&) const; + bool operator!=(const LiveboxInfo&) const; + bool operator >(const LiveboxInfo&) const; + bool operator>=(const LiveboxInfo&) const; + bool operator <(const LiveboxInfo&) const; + bool operator<=(const LiveboxInfo&) const; + }; + typedef std::list> LiveboxList; + LiveboxList m_livebox; + typedef std::list DependsPkgList; + typedef std::set CategoryList; + StringsList nameSpaces; LocalizedDataSet localizedDataSet; @@ -200,6 +252,7 @@ class ConfigParserData DPL::OptionalString authorEmail; FeaturesList featuresList; + PrivilegeList privilegeList; SettingsList settingsList; @@ -242,6 +295,8 @@ class ConfigParserData DPL::OptionalString splashImgSrc; // Background page filename DPL::OptionalString backgroundPage; + // For category + CategoryList categoryList; ConfigParserData() : flashNeeded(false), diff --git a/modules/widget_dao/include/dpl/wrt-dao-ro/feature_model.h b/modules/widget_dao/include/dpl/wrt-dao-ro/feature_model.h index d9440da..fc9754d 100644 --- a/modules/widget_dao/include/dpl/wrt-dao-ro/feature_model.h +++ b/modules/widget_dao/include/dpl/wrt-dao-ro/feature_model.h @@ -24,7 +24,7 @@ #include #include -#include +#include #include #include #include @@ -34,7 +34,7 @@ namespace WrtDB { typedef int FeatureHandle; typedef std::list FeatureHandleList; -typedef DPL::SharedPtr FeatureHandleListPtr; +typedef std::shared_ptr FeatureHandleListPtr; typedef int FeatureSetHandle; typedef std::list FeatureSetHandleList; @@ -69,7 +69,7 @@ class FeatureModel : public DPL::Event::Model } }; -typedef DPL::SharedPtr FeatureModelPtr; +typedef std::shared_ptr FeatureModelPtr; } // namespace WrtDB diff --git a/modules/widget_dao/include/dpl/wrt-dao-ro/global_config.h b/modules/widget_dao/include/dpl/wrt-dao-ro/global_config.h index 4a8739c..5558dbd 100644 --- a/modules/widget_dao/include/dpl/wrt-dao-ro/global_config.h +++ b/modules/widget_dao/include/dpl/wrt-dao-ro/global_config.h @@ -53,17 +53,25 @@ inline const char* GetDevicePluginPath() } /** - * WRT factory widgets that are loaded by default + * WRT widgets that are downloaded and installed by user */ -inline const char* GetFactoryInstalledWidgetPath() +inline const char* GetUserInstalledWidgetPath() { - return "/opt/share/widget/system"; + return "/opt/usr/apps"; +} + +/** + * WRT widgets that are preloaded + */ +inline const char* GetUserPreloadedWidgetPath() +{ + return "/usr/apps"; } /** * WRT widgets that are downloaded and installed by user */ -inline const char* GetUserInstalledWidgetPath() +inline const char* GetWidgetUserDataPath() { return "/opt/usr/apps"; } @@ -116,6 +124,13 @@ inline const char* GetWidgetPrivateStoragePath() return "data"; } +/** + * widgets share directory path + */ +inline const char* GetWidgetSharePath() +{ + return "share"; +} /** * widgets desktop files path @@ -226,7 +241,7 @@ inline const char* GetFingerprintListSchema() inline const char* GetVCoreDatabaseFilePath() { - return "/opt/dbspace/.vcore.db"; + return "/opt/dbspace/.cert_svc_vcore.db"; } /** @@ -269,6 +284,42 @@ inline const char* GetTempInstallInfoPath() { return "/opt/share/widget/temp_info"; } + +inline const char* GetVconfKeyPrefixPath() +{ + return "file/private"; +} + +inline const char* GetVconfKeyPopupUsagePath() +{ + return "/popup_usage"; +} + +inline const char* GetVconfKeyGeolocationUsagePath() +{ + return "/geolocation_usage"; +} + +inline const char* GetVconfKeyWebNotificationUsagePath() +{ + return "/web_notification_usage"; +} + +inline const char* GetVconfKeyWebDatabaseUsagePath() +{ + return "/web_database_usage"; +} + +inline const char* GetVconfKeyFilesystemUsagePath() +{ + return "/filesystem_usage"; +} + +inline const char* GetVconfKeyMemorySavingModePath() +{ + return "/memory_saving_mode"; +} + } // namespace GlobalConfig } // namespace WrtDB diff --git a/modules/widget_dao/include/dpl/wrt-dao-ro/plugin_dao_read_only.h b/modules/widget_dao/include/dpl/wrt-dao-ro/plugin_dao_read_only.h index 33c83b1..044d3d0 100644 --- a/modules/widget_dao/include/dpl/wrt-dao-ro/plugin_dao_read_only.h +++ b/modules/widget_dao/include/dpl/wrt-dao-ro/plugin_dao_read_only.h @@ -26,8 +26,8 @@ #include #include +#include #include -#include #include namespace WrtDB { @@ -35,7 +35,7 @@ namespace WrtDB { typedef std::list PluginHandleList; typedef std::set PluginHandleSet; typedef std::list ImplementedObjectsList; -typedef DPL::SharedPtr PluginHandleSetPtr; +typedef std::shared_ptr PluginHandleSetPtr; //TODO make it friend to FeatureDAO or inherit class PluginDAOReadOnly diff --git a/modules/widget_dao/include/dpl/wrt-dao-ro/property_dao_read_only.h b/modules/widget_dao/include/dpl/wrt-dao-ro/property_dao_read_only.h index 50b3dab..4c5a283 100644 --- a/modules/widget_dao/include/dpl/wrt-dao-ro/property_dao_read_only.h +++ b/modules/widget_dao/include/dpl/wrt-dao-ro/property_dao_read_only.h @@ -38,7 +38,7 @@ typedef DPL::OptionalString WidgetPropertyValue; typedef std::list WidgetPropertyKeyList; struct WidgetPreferenceRow { - int app_id; + WidgetPkgName pkgname; WidgetPropertyKey key_name; WidgetPropertyValue key_value; DPL::OptionalInt readonly; @@ -57,24 +57,49 @@ class Exception DECLARE_EXCEPTION_TYPE(Base, ReadOnlyProperty) }; +//deprecated /* This method checks read only flag for given property */ DPL::OptionalInt CheckPropertyReadFlag(DbWidgetHandle widgetHandle, + const WidgetPropertyKey &key) + __attribute__((deprecated)); + +/* This method checks read only flag for given property + */ +DPL::OptionalInt CheckPropertyReadFlag(WidgetPkgName pkgName, const WidgetPropertyKey &key); +//deprecated /* This method gets widget property key list */ -WidgetPropertyKeyList GetPropertyKeyList(DbWidgetHandle widgetHandle); +WidgetPropertyKeyList GetPropertyKeyList(DbWidgetHandle widgetHandle) + __attribute__((deprecated)); +/* This method gets widget property key list + */ +WidgetPropertyKeyList GetPropertyKeyList(WidgetPkgName pkgName); + +//deprecated /* This method gets widget property list */ -WidgetPreferenceList GetPropertyList(DbWidgetHandle widgetHandle); +WidgetPreferenceList GetPropertyList(DbWidgetHandle widgetHandle) + __attribute__((deprecated)); +/* This method gets widget property list + */ +WidgetPreferenceList GetPropertyList(WidgetPkgName pkgName); + +//deprecated /* This method get widget property value */ WidgetPropertyValue GetPropertyValue(DbWidgetHandle widgetHandle, const WidgetPropertyKey &key); +/* This method get widget property value + */ +WidgetPropertyValue GetPropertyValue(WidgetPkgName pkgName, + const WidgetPropertyKey &key); + } // PropertyDAOReadOnly } // namespace WrtDB diff --git a/modules/widget_dao/include/dpl/wrt-dao-ro/vconf_config.h b/modules/widget_dao/include/dpl/wrt-dao-ro/vconf_config.h new file mode 100644 index 0000000..a30a84d --- /dev/null +++ b/modules/widget_dao/include/dpl/wrt-dao-ro/vconf_config.h @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file vconf_config.h + * @author Jihoon Chung (jihoon.chung@samsung.com) + * @version 1.0 + * @brief Implementation file for vconf key config. + */ +#ifndef SRC_DOMAIN_VCONF_CONFIG_H +#define SRC_DOMAIN_VCONF_CONFIG_H + +#include +#include + +#include +#include + +namespace WrtDB { +namespace VconfConfig { +inline std::string GetVconfKeyRootPath(DPL::String pkgName) +{ + return PathBuilder() + .Append(GlobalConfig::GetVconfKeyPrefixPath()) + .Append(DPL::ToUTF8String(pkgName)) + .GetFullPath(); +} + +inline std::string GetVconfKeyPopupUsage(DPL::String pkgName) +{ + return PathBuilder() + .Append(GlobalConfig::GetVconfKeyPrefixPath()) + .Append(DPL::ToUTF8String(pkgName)) + .Concat(GlobalConfig::GetVconfKeyPopupUsagePath()) + .GetFullPath(); +} + +inline std::string GetVconfKeyGeolocationUsage(DPL::String pkgName) +{ + return PathBuilder() + .Append(GlobalConfig::GetVconfKeyPrefixPath()) + .Append(DPL::ToUTF8String(pkgName)) + .Concat(GlobalConfig::GetVconfKeyGeolocationUsagePath()) + .GetFullPath(); +} + +inline std::string GetVconfKeyWebNotificationUsage(DPL::String pkgName) +{ + return PathBuilder() + .Append(GlobalConfig::GetVconfKeyPrefixPath()) + .Append(DPL::ToUTF8String(pkgName)) + .Concat(GlobalConfig::GetVconfKeyWebNotificationUsagePath()) + .GetFullPath(); +} + +inline std::string GetVconfKeyWebDatabaseUsage(DPL::String pkgName) +{ + return PathBuilder() + .Append(GlobalConfig::GetVconfKeyPrefixPath()) + .Append(DPL::ToUTF8String(pkgName)) + .Concat(GlobalConfig::GetVconfKeyWebDatabaseUsagePath()) + .GetFullPath(); +} + +inline std::string GetVconfKeyFilesystemUsage(DPL::String pkgName) +{ + return PathBuilder() + .Append(GlobalConfig::GetVconfKeyPrefixPath()) + .Append(DPL::ToUTF8String(pkgName)) + .Concat(GlobalConfig::GetVconfKeyFilesystemUsagePath()) + .GetFullPath(); +} + +inline std::string GetVconfKeyMemorySavingMode(DPL::String pkgName) +{ + return PathBuilder() + .Append(GlobalConfig::GetVconfKeyPrefixPath()) + .Append(DPL::ToUTF8String(pkgName)) + .Concat(GlobalConfig::GetVconfKeyMemorySavingModePath()) + .GetFullPath(); +} + +} // namespace VconfConfig +} // namespace WrtDB + +#endif diff --git a/modules/widget_dao/include/dpl/wrt-dao-ro/widget_config.h b/modules/widget_dao/include/dpl/wrt-dao-ro/widget_config.h index bd1ee00..7669701 100644 --- a/modules/widget_dao/include/dpl/wrt-dao-ro/widget_config.h +++ b/modules/widget_dao/include/dpl/wrt-dao-ro/widget_config.h @@ -35,7 +35,7 @@ namespace WidgetConfig { inline std::string GetWidgetBasePath(DPL::String pkgName) { return PathBuilder() - .Append(GlobalConfig::GetUserInstalledWidgetPath()) + .Append(GlobalConfig::GetWidgetUserDataPath()) .Append(DPL::ToUTF8String(pkgName)) .GetFullPath(); } diff --git a/modules/widget_dao/include/dpl/wrt-dao-ro/widget_dao_read_only.h b/modules/widget_dao/include/dpl/wrt-dao-ro/widget_dao_read_only.h index 5b66498..f454637 100644 --- a/modules/widget_dao/include/dpl/wrt-dao-ro/widget_dao_read_only.h +++ b/modules/widget_dao/include/dpl/wrt-dao-ro/widget_dao_read_only.h @@ -175,11 +175,15 @@ struct WidgetRegisterInfo int isTestWidget; ConfigParserData configInfo; LocalizationData localizationData; + DPL::OptionalString pkgname; + WidgetPkgName pkgName; + time_t installedTime; PackagingType packagingType; EncryptedFileList encryptedFiles; ExternalLocationList externalLocations; + DPL::OptionalString widgetInstalledPath; }; typedef std::list CertificateChainList; @@ -312,6 +316,17 @@ class WidgetDAOReadOnly static DbWidgetHandle getHandle(const WidgetGUID GUID); static DbWidgetHandle getHandle(const DPL::String pkgName); + /** + * Returns pkgname for the specified widget + * + * @return pkgname + * @exception WRT_CONF_ERR_EMDB_FAILURE - Fail to query DB table. + * @exception WRT_CONF_ERR_EMDB_NO_RECORD - Can not find matching records in DB table. + */ + WidgetPkgName getPkgName() const; + static WidgetPkgName getPkgName(const WidgetGUID GUID); + static WidgetPkgName getPkgName(const DbWidgetHandle handle); + /** * This method returns the root directory of widget resource. * @@ -356,13 +371,14 @@ class WidgetDAOReadOnly */ WidgetGUID getGUID() const; + /** - * This method returns the Package name of the widget. - * - * @return pkgname - * @exception WRT_CONF_ERR_EMDB_FAILURE - Fail to query DB table. - * @exception WRT_CONF_ERR_EMDB_NO_RECORD - Can not find matching records in DB table. - */ + * This method returns the Package name of the widget. + * + * @return pkgname + * @exception WRT_CONF_ERR_EMDB_FAILURE - Fail to query DB table. + * @exception WRT_CONF_ERR_EMDB_NO_RECORD - Can not find matching records in DB table. + */ DPL::OptionalString getPkgname() const; /** @@ -558,6 +574,7 @@ class WidgetDAOReadOnly * @return list of pkgname of installed packages */ static WidgetPkgNameList getPkgnameList(); + static WidgetPkgNameList_TEMPORARY_API getPkgnameList_TEMPORARY_API(); /** * This method returns a list of all the installed widgets. @@ -750,6 +767,28 @@ class WidgetDAOReadOnly * @return new tizen id */ static WidgetPkgName generateTizenId(); + + /** + * @brief This method return each value for security setting + * + * @return SettingsType + * SETTINGS_TYPE_UNKNOWN : unknow value + * SETTINGS_TYPE_ON : enable + * SETTINGS_TYPE_ALWAYS_ASK : ask by popup + * SETTINGS_TYPE_OFF : disable + */ + SettingsType getSecurityPopupUsage() const; + SettingsType getGeolocationUsage() const; + SettingsType getWebNotificationUsage() const; + SettingsType getWebDatabaseUsage() const; + SettingsType getFileSystemUsage() const; + + /** + * This method returns widget's installed path + * + * @return path of widget installed + */ + DPL::OptionalString getWidgetInstalledPath() const; }; } // namespace WrtDB diff --git a/modules/widget_dao/include/dpl/wrt-dao-rw/property_dao.h b/modules/widget_dao/include/dpl/wrt-dao-rw/property_dao.h index d75dc59..7046042 100644 --- a/modules/widget_dao/include/dpl/wrt-dao-rw/property_dao.h +++ b/modules/widget_dao/include/dpl/wrt-dao-rw/property_dao.h @@ -31,20 +31,42 @@ struct WidgetRegisterInfo; //forward declaration namespace PropertyDAO { +//deprecated void RemoveProperty(DbWidgetHandle widgetHandle, + const PropertyDAOReadOnly::WidgetPropertyKey &key) + __attribute__((deprecated)); + +void RemoveProperty(WidgetPkgName pkgName, const PropertyDAOReadOnly::WidgetPropertyKey &key); +//deprecated /* This method sets widget property */ void SetProperty(DbWidgetHandle widgetHandle, + const PropertyDAOReadOnly::WidgetPropertyKey &key, + const PropertyDAOReadOnly::WidgetPropertyValue &value, + bool readOnly = false) + __attribute__((deprecated)); + +/* This method sets widget property + */ +void SetProperty(WidgetPkgName pkgName, const PropertyDAOReadOnly::WidgetPropertyKey &key, const PropertyDAOReadOnly::WidgetPropertyValue &value, bool readOnly = false); +//deprecated /* This method registers properties for widget. * Properties unregistering is done via "delete cascade" mechanism in SQL */ void RegisterProperties(DbWidgetHandle widgetHandle, + const WidgetRegisterInfo ®Info) + __attribute__((deprecated)); + +/* This method registers properties for widget. + * Properties unregistering is done via "delete cascade" mechanism in SQL + */ +void RegisterProperties(WidgetPkgName pkgName, const WidgetRegisterInfo ®Info); } // namespace PropertyDAO diff --git a/modules/widget_dao/include/dpl/wrt-dao-rw/widget_dao.h b/modules/widget_dao/include/dpl/wrt-dao-rw/widget_dao.h index 94aba6b..3f7b819 100644 --- a/modules/widget_dao/include/dpl/wrt-dao-rw/widget_dao.h +++ b/modules/widget_dao/include/dpl/wrt-dao-rw/widget_dao.h @@ -133,6 +133,7 @@ class WidgetDAO : public WidgetDAOReadOnly /* set PkgName */ void setPkgName(const DPL::OptionalString& pkgName); + void setPkgName_TEMPORARY_API(const WidgetPkgName& pkgName); /* This function will update of api-feature status. * If status is true (feature rejected) plugin connected with this @@ -140,6 +141,15 @@ class WidgetDAO : public WidgetDAOReadOnly */ void updateFeatureRejectStatus(const DbWidgetFeature &widgetFeature); + /* + * This method change security settings value + */ + void setSecurityPopupUsage(const SettingsType value); + void setGeolocationUsage(const SettingsType value); + void setWebNotificationUsage(const SettingsType value); + void setWebDatabaseUsage(const SettingsType value); + void setFileSystemUsage(const SettingsType value); + private: //Methods used during widget registering static DbWidgetHandle registerWidgetInfo( @@ -165,6 +175,9 @@ class WidgetDAO : public WidgetDAOReadOnly static void registerWidgetFeatures( DbWidgetHandle widgetHandle, const WidgetRegisterInfo ®Info); + static void registerWidgetPrivilege( + DbWidgetHandle widgetHandle, + const WidgetRegisterInfo ®Info); static void registerWidgetWindowModes( DbWidgetHandle widgetHandle, const WidgetRegisterInfo ®Info); @@ -193,6 +206,8 @@ class WidgetDAO : public WidgetDAOReadOnly */ static void registerExternalLocations(DbWidgetHandle widgetHandle, const ExternalLocationList & externals); + static void registerWidgetSecuritySettings(DbWidgetHandle widgetHandle); + static void registerWidgetInternal( const WidgetPkgName & widgetName, diff --git a/modules/widget_dao/orm/wrt_db b/modules/widget_dao/orm/wrt_db index 0dfedb4..06c12bc 100644 --- a/modules/widget_dao/orm/wrt_db +++ b/modules/widget_dao/orm/wrt_db @@ -38,7 +38,7 @@ CREATE_TABLE(WidgetInfo) COLUMN_NOT_NULL(back_supported, TINYINT, DEFAULT 0) COLUMN(access_network, TINYINT, DEFAULT 0) COLUMN(defaultlocale, VARCHAR(256), DEFAULT 0) - COLUMN(pkgname, VARCHAR(256), DEFAULT 0 UNIQUE) + COLUMN_NOT_NULL(pkgname, VARCHAR(256), DEFAULT 0 UNIQUE) COLUMN(pkg_type, INT, DEFAULT 0) CREATE_TABLE_END() @@ -91,20 +91,21 @@ CREATE_TABLE(WidgetExtendedInfo) COLUMN_NOT_NULL(test_widget, INT, CHECK(test_widget between 0 and 1) DEFAULT 0) COLUMN(splash_img_src, VARCHAR(256), DEFAULT '') COLUMN(background_page, VARCHAR(256), DEFAULT '') + COLUMN(installed_path, VARCHAR(512), DEFAULT '') TABLE_CONSTRAINTS( FOREIGN KEY(app_id) REFERENCES WidgetInfo (app_id) ON DELETE CASCADE ) CREATE_TABLE_END() CREATE_TABLE(WidgetPreference) - COLUMN_NOT_NULL(app_id, INT,) + COLUMN_NOT_NULL(pkgname, VARCHAR(256), DEFAULT 0) COLUMN_NOT_NULL(key_name, VARCHAR(256),) COLUMN(key_value, VARCHAR(8000), DEFAULT '') COLUMN(readonly, INT, DEFAULT 0) TABLE_CONSTRAINTS( - PRIMARY KEY(app_id, key_name), - FOREIGN KEY(app_id) REFERENCES WidgetInfo (app_id) ON DELETE CASCADE + PRIMARY KEY(pkgname, key_name), + FOREIGN KEY(pkgname) REFERENCES WidgetInfo (pkgname) ON DELETE CASCADE ) CREATE_TABLE_END() @@ -123,12 +124,20 @@ CREATE_TABLE(FeatureParam) COLUMN_NOT_NULL(widget_feature_id, INTEGER,) COLUMN_NOT_NULL(name, TEXT,) COLUMN_NOT_NULL(value, TEXT,) - TABLE_CONSTRAINTS( FOREIGN KEY (widget_feature_id) REFERENCES WidgetFeature (widget_feature_id) ON DELETE CASCADE ) CREATE_TABLE_END() +CREATE_TABLE(WidgetPrivilege) + COLUMN_NOT_NULL(widget_privilege_id, INTEGER, primary key autoincrement) + COLUMN_NOT_NULL(app_id, INT,) + COLUMN_NOT_NULL(name, VARCHAR(256),) + TABLE_CONSTRAINTS( + FOREIGN KEY (app_id) REFERENCES WidgetInfo (app_id) ON DELETE CASCADE + ) +CREATE_TABLE_END() + CREATE_TABLE(WidgetIcon) COLUMN_NOT_NULL(icon_id, INTEGER, primary key autoincrement) COLUMN_NOT_NULL(app_id, INT,) @@ -215,6 +224,18 @@ CREATE_TABLE(WidgetWARPInfo) ) CREATE_TABLE_END() +CREATE_TABLE(WidgetSecuritySettings) + COLUMN_NOT_NULL(app_id, INT,) + COLUMN_NOT_NULL(security_popup_usage, INT, DEFAULT 1) + COLUMN_NOT_NULL(geolocation_usage, INT, DEFAULT 1) + COLUMN_NOT_NULL(web_notification_usage, INT, DEFAULT 1) + COLUMN_NOT_NULL(web_database_usage, INT, DEFAULT 1) + COLUMN_NOT_NULL(file_system_usage, INT, DEFAULT 1) + TABLE_CONSTRAINTS( + FOREIGN KEY (app_id) REFERENCES WidgetInfo (app_id) ON DELETE CASCADE + ) +CREATE_TABLE_END() + CREATE_TABLE(FeaturesList) COLUMN_NOT_NULL(FeatureUUID, INTEGER, primary key autoincrement) COLUMN_NOT_NULL(FeatureName, TEXT, unique) diff --git a/packaging/wrt-commons.spec b/packaging/wrt-commons.spec index c7cdda9..41357df 100644 --- a/packaging/wrt-commons.spec +++ b/packaging/wrt-commons.spec @@ -1,7 +1,7 @@ -#git:framework/web/wrt-commons wrt-commons 0.2.72 +#git:framework/web/wrt-commons wrt-commons 0.2.89 Name: wrt-commons Summary: Wrt common library -Version: 0.2.72 +Version: 0.2.89 Release: 1 Group: Development/Libraries License: Apache License, Version 2.0 @@ -38,13 +38,26 @@ Wrt common library development headers %prep %setup -q +%define with_tests 0 +%if "%{WITH_TESTS}" == "ON" || "%{WITH_TESTS}" == "Y" || "%{WITH_TESTS}" == "YES" || "%{WITH_TESTS}" == "TRUE" || "%{WITH_TESTS}" == "1" + %define with_tests 1 +%endif + %build + +%ifarch %{ix86} +cp build/encryption/libs/libcal.i586.a build/encryption/libs/libcal.a +%else +cp build/encryption/libs/libcal.arm.a build/encryption/libs/libcal.a +%endif + export LDFLAGS+="-Wl,--rpath=%{_libdir} -Wl,--hash-style=both -Wl,--as-needed" cmake . -DVERSION=%{version} \ -DDPL_LOG="OFF" \ -DCMAKE_INSTALL_PREFIX=%{_prefix} \ - -DCMAKE_BUILD_TYPE=%{?build_type:%build_type} + -DCMAKE_BUILD_TYPE=%{?build_type:%build_type} \ + %{?WITH_TESTS:-DWITH_TESTS=%WITH_TESTS} make %{?jobs:-j%jobs} %install @@ -115,6 +128,8 @@ chsmack -a 'wrt-commons::db_wrt' /opt/dbspace/.wrt.db chsmack -a 'wrt-commons::db_wrt' /opt/dbspace/.wrt.db-journal chsmack -a 'wrt-commons::db_wrt_autosave' /opt/dbspace/.wrt_autosave.db chsmack -a 'wrt-commons::db_wrt_autosave' /opt/dbspace/.wrt_autosave.db-journal +chsmack -a 'wrt-commons::db_wrt_custom_handler' /opt/dbspace/.wrt_custom_handler.db +chsmack -a 'wrt-commons::db_wrt_custom_handler' /opt/dbspace/.wrt_custom_handler.db-journal echo "[WRT] wrt-commons postinst done ..." @@ -122,10 +137,18 @@ echo "[WRT] wrt-commons postinst done ..." %manifest wrt-commons.manifest %{_libdir}/*.so %{_libdir}/*.so.* -/usr/share/wrt-engine/* -%attr(775,root,root) %{_bindir}/wrt_commons_reset_db.sh -%attr(775,root,root) %{_bindir}/wrt_commons_create_clean_db.sh +%{_datadir}/wrt-engine/* %{_datadir}/license/%{name} +%attr(755,root,root) %{_bindir}/wrt_commons_create_clean_db.sh +%attr(755,root,root) %{_bindir}/wrt_commons_reset_db.sh +%if %{with_tests} + %attr(755,root,root) %{_bindir}/dpl-tests-* + %attr(755,root,root) %{_bindir}/dpl-dbus-test-service + %attr(755,root,root) %{_bindir}/wrt-tests-* + %attr(755,root,root) %{_bindir}/wrt_dao_tests_prepare_db.sh + %{_datadir}/dbus-1/services/org.tizen.DBusTestService.service + /opt/share/wrt/wrt-commons/tests/* +%endif %files devel %{_includedir}/dpl-efl/* diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt new file mode 100644 index 0000000..40112fe --- /dev/null +++ b/tests/CMakeLists.txt @@ -0,0 +1,18 @@ +# Suppress all warnings; TODO: inhibit only specific warnings per target (TURNED OFF) +#SET(CMAKE_CXX_FLAGS_BACKUP ${CMAKE_CXX_FLAGS}) +#SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -w") + +INCLUDE(CMakeUtils.txt) + +SET(TESTS_DIR ${CMAKE_CURRENT_SOURCE_DIR}) +SET(TESTS_COMMON_DIR "${TESTS_DIR}/common") + +WRT_ADD_INTERNAL_DEPENDENCIES( + ${TARGET_DPL_TEST_ENGINE_EFL} +) + +ADD_SUBDIRECTORY(dao) +ADD_SUBDIRECTORY(dpl) + +# Rollback CXX flags +#SET(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS_BACKUP}) \ No newline at end of file diff --git a/tests/CMakeUtils.txt b/tests/CMakeUtils.txt new file mode 100644 index 0000000..ea9cfb3 --- /dev/null +++ b/tests/CMakeUtils.txt @@ -0,0 +1,178 @@ +# @file CMakeUtils.txt +# @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) +# @author Pawel Sikorski (p.sikorski@samsung.com) +# @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) +# @version 1.0 +# @brief +# + +# +# Discovers target's INCLUDE_DIRECTORIES and LINK_DIRECTORIES. +# This is done by retrieving the directory target was built in and +# fetching appropriate properties of that directory. +FUNCTION(WRT_INTROSPECT_TARGET PREFIX TARGET_NAME) + GET_TARGET_PROPERTY(LOCATION ${TARGET_NAME} LOCATION) + IF(${LOCATION} STREQUAL "LOCATION-NOTFOUND") + MESSAGE(FATAL_ERROR "Target '${TARGET_NAME}' introspection failed") + ELSE(${LOCATION} STREQUAL "LOCATION-NOTFOUND") + STRING(FIND ${LOCATION} "/" LAST_SLASH_POSITION REVERSE) + STRING(SUBSTRING ${LOCATION} 0 ${LAST_SLASH_POSITION} LOCATION) + + GET_DIRECTORY_PROPERTY(INCLUDE_DIRS DIRECTORY ${LOCATION} INCLUDE_DIRECTORIES) + SET("${PREFIX}_INCLUDE_DIRS" ${INCLUDE_DIRS} PARENT_SCOPE) + + GET_DIRECTORY_PROPERTY(LIBRARY_DIRS DIRECTORY ${LOCATION} LINK_DIRECTORIES) + SET("${PREFIX}_LIBRARY_DIRS" ${LIBRARY_DIRS} PARENT_SCOPE) + ENDIF(${LOCATION} STREQUAL "LOCATION-NOTFOUND") +ENDFUNCTION(WRT_INTROSPECT_TARGET) + +# +# Replacement functions for standard (w/o "WRT_" prefix) CMake functions. +# They store supplied arguments in global properties to assign them to tests. +# Anything added with this functions is used by all targets that are built with +# WRT_TEST_BUILD function. + +# +# Appends directories to global property TESTS_INCLUDE_DIRS which is +# then read by WRT_TEST_BUILD and its content is forwarded to +# command INCLUDE_DIRECTORIES() (for all targets). +FUNCTION(WRT_INCLUDE_DIRECTORIES) + SET_PROPERTY(GLOBAL APPEND PROPERTY TESTS_INCLUDE_DIRS ${ARGV}) +ENDFUNCTION(WRT_INCLUDE_DIRECTORIES) + +# +# Appends directories to global property TESTS_LIBRARY_DIRS which is +# then read by WRT_TEST_BUILD and its content is forwarded to +# command LINK_DIRECTORIES() (for all targets). +FUNCTION(WRT_LINK_DIRECTORIES) + SET_PROPERTY(GLOBAL APPEND PROPERTY TESTS_LIBRARY_DIRS ${ARGV}) +ENDFUNCTION(WRT_LINK_DIRECTORIES) + +# +# Appends directories to global property TESTS_LIBRARIES which is +# then read by WRT_TEST_BUILD and its content is forwarded to +# command TARGET_LINK_LIBRARIES() (for all targets). +FUNCTION(WRT_TARGET_LINK_LIBRARIES) + SET_PROPERTY(GLOBAL APPEND PROPERTY TESTS_LIBRARIES ${ARGV}) +ENDFUNCTION(WRT_TARGET_LINK_LIBRARIES) + +# +# Convenience method that fills TESTS_INCLUDE_DIRS, TESTS_LIBRARY_DIRS +# and TESTS_LIBRARIES with values discovered from introspecting supplied +# targets. +# Function takes arbitrary number of targets. +FUNCTION(WRT_ADD_INTERNAL_DEPENDENCIES) + FOREACH(DEPENDENCY ${ARGV}) + WRT_INTROSPECT_TARGET(prefix ${DEPENDENCY}) + WRT_INCLUDE_DIRECTORIES(${prefix_INCLUDE_DIRS}) + WRT_LINK_DIRECTORIES(${prefix_LIBRARY_DIRS}) + WRT_TARGET_LINK_LIBRARIES(${DEPENDENCY}) + ENDFOREACH(DEPENDENCY) +ENDFUNCTION(WRT_ADD_INTERNAL_DEPENDENCIES) + + +# +# Replacement functions for standard (w/o "WRT_" prefix) CMake functions. +# They store supplied arguments in global properties to assign them to specific +# tests. Properties names are based on the test target name. +# Anything added with this functions is used only by the specified target that +# is built with WRT_TEST_BUILD function. + +# +# Appends directories to global property ${TARGET_NAME}_INCLUDE_DIRS +# which is then read by WRT_TEST_BUILD and its content is forwarded to +# command INCLUDE_DIRECTORIES() (for specified target). +FUNCTION(WRT_TEST_INCLUDE_DIRECTORIES TARGET_NAME) + SET_PROPERTY(GLOBAL APPEND PROPERTY ${TARGET_NAME}_INCLUDE_DIRS ${ARGN}) +ENDFUNCTION(WRT_TEST_INCLUDE_DIRECTORIES) + +# +# Appends directories to global property ${TARGET_NAME}_LIBRARY_DIRS +# which is then read by WRT_TEST_BUILD and its content is forwarded to +# command LINK_DIRECTORIES() (for specified target). +FUNCTION(WRT_TEST_LINK_DIRECTORIES TARGET_NAME) + SET_PROPERTY(GLOBAL APPEND PROPERTY ${TARGET_NAME}_LIBRARY_DIRS ${ARGN}) +ENDFUNCTION(WRT_TEST_LINK_DIRECTORIES) + +# +# Appends directories to global property ${TARGET_NAME}_LIBRARIES +# which is then read by WRT_TEST_BUILD and its content is forwarded to +# command TARGET_LINK_LIBRARIES() (for specified target). +FUNCTION(WRT_TEST_TARGET_LINK_LIBRARIES TARGET_NAME) + SET_PROPERTY(GLOBAL APPEND PROPERTY ${TARGET_NAME}_LIBRARIES ${ARGN}) +ENDFUNCTION(WRT_TEST_TARGET_LINK_LIBRARIES) + +# +# Convenience method that fills ${TARGET_NAME}_INCLUDE_DIRS, +# ${TARGET_NAME}_LIBRARY_DIRS and ${TARGET_NAME}_LIBRARIES with +# values discovered from introspecting supplied targets. +# Function takes arbitrary number of targets. +FUNCTION(WRT_TEST_ADD_INTERNAL_DEPENDENCIES TARGET_NAME) + FOREACH(DEPENDENCY ${ARGN}) + WRT_INTROSPECT_TARGET(prefix ${DEPENDENCY}) + WRT_TEST_INCLUDE_DIRECTORIES(${TARGET_NAME} ${prefix_INCLUDE_DIRS}) + WRT_TEST_LINK_DIRECTORIES(${TARGET_NAME} ${prefix_LIBRARY_DIRS}) + WRT_TEST_TARGET_LINK_LIBRARIES(${TARGET_NAME} ${DEPENDENCY}) + ENDFOREACH(DEPENDENCY) +ENDFUNCTION(WRT_TEST_ADD_INTERNAL_DEPENDENCIES) + +# Functions used to build test targets (proper sources, includes, libs are +# added automatically) +FUNCTION(WRT_TEST_BUILD TARGET_NAME) + SET(SOURCES "${ARGN}") + ADD_EXECUTABLE("${TARGET_NAME}" ${SOURCES}) + + # get include dirs global property + GET_PROPERTY(INCLUDE_DIRS GLOBAL PROPERTY TESTS_INCLUDE_DIRS) + GET_PROPERTY(TEST_INCLUDE_DIRS GLOBAL PROPERTY ${TARGET_NAME}_INCLUDE_DIRS) + INCLUDE_DIRECTORIES( + ${INCLUDE_DIRS} + ${TEST_INCLUDE_DIRS} + ) + + # get library dirs global property + GET_PROPERTY(LIBRARY_DIRS GLOBAL PROPERTY TESTS_LIBRARY_DIRS) + GET_PROPERTY(TEST_LIBRARY_DIRS GLOBAL PROPERTY ${TARGET_NAME}_LIBRARY_DIRS) + LINK_DIRECTORIES( + ${LIBRARY_DIRS} + ${TEST_LIBRARY_DIRS} + ) + + # get link libraries global property + GET_PROPERTY(LINK_LIBRARIES GLOBAL PROPERTY TESTS_LIBRARIES) + GET_PROPERTY(TEST_LIBRARIES GLOBAL PROPERTY ${TARGET_NAME}_LIBRARIES) + TARGET_LINK_LIBRARIES("${TARGET_NAME}" + ${LINK_LIBRARIES} + ${TEST_LIBRARIES} + ) +ENDFUNCTION(WRT_TEST_BUILD) + +FUNCTION(WRT_TEST_INSTALL) + SET_TARGET_PROPERTIES(${ARGV} PROPERTIES + BUILD_WITH_INSTALL_RPATH ON + INSTALL_RPATH_USE_LINK_PATH ON + ) + INSTALL(TARGETS ${ARGV} + DESTINATION bin + PERMISSIONS OWNER_READ + OWNER_WRITE + OWNER_EXECUTE + GROUP_READ + GROUP_EXECUTE + WORLD_READ + WORLD_EXECUTE + ) +ENDFUNCTION(WRT_TEST_INSTALL) + +# Takes arbitrary number of arguments and concatenates them using ':' character. +# Rationale: +# CMake list when converted to a string is joined with ';' character. However, +# GCC takes strings with multiple elements separated with ':' (e.g. list of +# paths). Used typically when generating DB schemas with ORM mechanism. +FUNCTION(WRT_CONVERT_TO_GCC_LIST OUTPUT_VARIABLE) + FOREACH(ITEM ${ARGN}) + LIST(APPEND ITEMS ${ITEM}) + ENDFOREACH(ITEM) + STRING(REPLACE ";" ":" OUTPUT "${ITEMS}") + SET("${OUTPUT_VARIABLE}" "${OUTPUT}" PARENT_SCOPE) +ENDFUNCTION(WRT_CONVERT_TO_GCC_LIST) diff --git a/tests/common/include/loop_control.h b/tests/common/include/loop_control.h new file mode 100644 index 0000000..30aa6e8 --- /dev/null +++ b/tests/common/include/loop_control.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file loop_control.cpp + * @author Jaroslaw Osmanski (j.osmanski@samsung.com) + * @version 1.0 + * @brief This file is the definitions of loop controlling utilities + */ + + +#ifndef LOOP_CONTROL_H_ +#define LOOP_CONTROL_H_ + +namespace LoopControl +{ + +void init_loop(int argc, char *argv[]); +void wait_for_wrt_init(); +void finish_wait_for_wrt_init(); +void quit_loop(); + +void wrt_start_loop(); +void wrt_end_loop(); + +void *abstract_window(); + +} + +#endif /* LOOP_CONTROL_H_ */ diff --git a/tests/common/src/loop_control.cpp b/tests/common/src/loop_control.cpp new file mode 100644 index 0000000..eed375c --- /dev/null +++ b/tests/common/src/loop_control.cpp @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file loop_control.cpp + * @author Jaroslaw Osmanski (j.osmanski@samsung.com) + * @version 1.0 + * @brief This is implementation of EFL version of loop control + */ + +#include +#include + +#include + +#include +#include + + +namespace LoopControl +{ +void init_loop(int argc, char *argv[]) +{ + (void)argc; + (void)argv; + g_type_init(); + g_thread_init(NULL); + + LogInfo("Starting"); + elm_init(argc, argv); +} + +void wait_for_wrt_init() +{ + ecore_main_loop_begin(); +} + +void finish_wait_for_wrt_init() +{ + ecore_main_loop_quit(); +} + +void quit_loop() +{ + elm_shutdown(); +} + +void wrt_start_loop() +{ + ecore_main_loop_begin(); +} + +void wrt_end_loop() +{ + ecore_main_loop_quit(); +} + +void *abstract_window() +{ + return elm_win_add(NULL, "hello", ELM_WIN_BASIC); +} + +}//end of LoopControl namespace diff --git a/tests/dao/CMakeLists.txt b/tests/dao/CMakeLists.txt new file mode 100644 index 0000000..75ff334 --- /dev/null +++ b/tests/dao/CMakeLists.txt @@ -0,0 +1,37 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# @file CMakeLists.txt +# @author Pawel Sikorski (p.sikorski@samsung.com) +# @version 1.0 +# @brief +# + +# common part +FILE(GLOB DAO_TESTS_SOURCES "${PROJECT_SOURCE_DIR}/tests/dao/*DAO.cpp") +MESSAGE(STATUS "DAO_TESTS_SOURCES: ${DAO_TESTS_SOURCES}") + +# target wrt-tests-dao +SET(TARGET_DAO_TEST "wrt-tests-dao") +WRT_TEST_INCLUDE_DIRECTORIES(${TARGET_DAO_TEST} ${PROJECT_SOURCE_DIR}/modules/support/) +WRT_TEST_ADD_INTERNAL_DEPENDENCIES(${TARGET_DAO_TEST} ${TARGET_WRT_DAO_RW_LIB} ${TARGET_CUSTOM_HANDLER_DAO_RW_LIB}) +WRT_TEST_BUILD(${TARGET_DAO_TEST} ${DAO_TESTS_SOURCES} tests_dao.cpp) +WRT_TEST_INSTALL(${TARGET_DAO_TEST}) + + +# common installed files +INSTALL(PROGRAMS + ${PROJECT_SOURCE_DIR}/tests/dao/wrt_dao_tests_prepare_db.sh + DESTINATION bin + ) diff --git a/tests/dao/README b/tests/dao/README new file mode 100644 index 0000000..6c60a17 --- /dev/null +++ b/tests/dao/README @@ -0,0 +1,11 @@ +Wrt DAO +System tests. Tests database access layer: widgets information database, global configuration, plugins. +Binary file: wrt-tests-dao. Uses our test framework. Allows to use different types of output. Text output shows results on console - green passed. +To run: +1. Install wrt-extra on target +2. Run wrt-tests-dao --output=text + +Automatic: YES +Included in Daily Build: YES (http://build01.sprc.samsung.pl/browse/LINUXNGWAP-INT) +Included in Gerrit Builds: YES (http://build01.sprc.samsung.pl/browse/LINUXNGWAP-GERRIT) +Number of test cases: 45 \ No newline at end of file diff --git a/tests/dao/TestCases_CustomHandlerDAO.cpp b/tests/dao/TestCases_CustomHandlerDAO.cpp new file mode 100644 index 0000000..fb1a465 --- /dev/null +++ b/tests/dao/TestCases_CustomHandlerDAO.cpp @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file TestCases_CustomHandlerDAO.cpp + * @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) + * @version 1.0 + * @brief This file contains tests for custom handler dao class. + */ + +#include +#include +#include +#include + +using namespace CustomHandlerDB; + +RUNNER_TEST_GROUP_INIT(DAO) + +namespace +{ +const DPL::String P_TARGET(L"p_target"); +const DPL::String P_BASE_URL(L"p_base_url"); +const DPL::String P_URL(L"p_url"); +const DPL::String P_TITLE(L"p_title"); + +const DPL::String C_TARGET(L"c_target"); +const DPL::String C_BASE_URL(L"c_base_url"); +const DPL::String C_URL(L"c_url"); +const DPL::String C_TITLE(L"c_title"); + +void checkHandlersExistence(CustomHandlerDAOReadOnly& dao, bool protocol, bool content) +{ + CustomHandlerDB::CustomHandlerPtr handler; + handler = dao.getProtocolHandler(P_TARGET, P_URL); + RUNNER_ASSERT_MSG((!!handler) == protocol, "Protocol handler check"); + handler = dao.getContentHandler(C_TARGET, C_URL); + RUNNER_ASSERT_MSG((!!handler) == content, "Content handler check"); +} + +} // namespace + +RUNNER_TEST(custom_handler_empty_db_read) +{ + CustomHandlerDAOReadOnly dao(DPL::String(L"test")); +} + + +RUNNER_TEST(custom_handlers) +{ + CustomHandlerDAOReadOnly dao_ro(L"test"); + CustomHandlerDAO dao_rw(L"test"); + + CustomHandlerDB::CustomHandlerPtr handler; + CustomHandlerDB::CustomHandler p_handler; + p_handler.target = P_TARGET; + p_handler.base_url = P_BASE_URL; + p_handler.url = P_URL; + p_handler.title = P_TITLE; + p_handler.user_decision = Agreed; + + // initial check + checkHandlersExistence(dao_ro,false,false); + + // Protocol handler registration + dao_rw.registerProtocolHandler(p_handler); + checkHandlersExistence(dao_ro,true,false); + + handler = dao_ro.getProtocolHandler(P_TARGET, P_URL); + RUNNER_ASSERT(handler); + RUNNER_ASSERT(handler->target == P_TARGET); + RUNNER_ASSERT(handler->base_url == P_BASE_URL); + RUNNER_ASSERT(handler->url == P_URL); + RUNNER_ASSERT(handler->title == P_TITLE); + RUNNER_ASSERT(handler->user_decision == Agreed); + + + // Content handler registration + CustomHandlerDB::CustomHandler c_handler; + c_handler.target = C_TARGET; + c_handler.base_url = C_BASE_URL; + c_handler.url = C_URL; + c_handler.title = C_TITLE; + c_handler.user_decision = DeclinedPermanently; + + dao_rw.registerContentHandler(c_handler); + checkHandlersExistence(dao_ro,true,true); + handler = dao_ro.getContentHandler(C_TARGET, C_URL); + + RUNNER_ASSERT(handler); + RUNNER_ASSERT(handler->target == C_TARGET); + RUNNER_ASSERT(handler->base_url == C_BASE_URL); + RUNNER_ASSERT(handler->url == C_URL); + RUNNER_ASSERT(handler->title == C_TITLE); + RUNNER_ASSERT(handler->user_decision == DeclinedPermanently); + + // Handler unregistration + dao_rw.unregisterProtocolHandler(P_TARGET, P_URL); + checkHandlersExistence(dao_ro,false,true); + + // Nonexistent unregistration + dao_rw.unregisterContentHandler(L"blah", L"blah"); + checkHandlersExistence(dao_ro,false,true); + + // Cleanup + dao_rw.unregisterContentHandler(C_TARGET, C_URL); + checkHandlersExistence(dao_ro,false,false); +} diff --git a/tests/dao/TestCases_FeatureDAO.cpp b/tests/dao/TestCases_FeatureDAO.cpp new file mode 100644 index 0000000..26ea2bd --- /dev/null +++ b/tests/dao/TestCases_FeatureDAO.cpp @@ -0,0 +1,244 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file TestCases_FeatureDAO.cpp + * @author Pawel Sikorski (p.sikorski@samsung.com) + * @version 1.0 + * @brief This file contains tests for feature dao class. + */ + +#include +#include +#include +#include +#include + +using namespace WrtDB; + +#define RUNNER_ASSERT_WHAT_EQUALS(in, test) \ + {std::string tmp(in); \ + RUNNER_ASSERT_MSG(tmp == test, "Equals: [" + tmp + "]");} + +RUNNER_TEST_GROUP_INIT(DAO) + +/* +Name: feature_dao_test_register_features +Description: Checks if plugin registeration performs features registration +Expected: registrartion should succeed +*/ +RUNNER_TEST(feature_dao_test_register_features) +{ + PluginHandle plHandle; + { + std::string libraryPath("nfp1 lib_path"); + std::string libraryName("nfp1"); + + PluginMetafileData pluginData; + pluginData.m_libraryName = libraryName; + + plHandle = PluginDAO::registerPlugin(pluginData, libraryPath); + RUNNER_ASSERT(PluginDAO::isPluginInstalled(libraryName) == true); + + FeatureHandleList old = FeatureDAOReadOnly::GetHandleList(); + PluginMetafileData::Feature f; + f.m_name = std::string("new_f1"); + + FeatureHandle handle = FeatureDAO::RegisterFeature(f,plHandle); + RUNNER_ASSERT_MSG(handle != -1, "Already registered"); + RUNNER_ASSERT_MSG(old.size() < FeatureDAOReadOnly::GetHandleList().size(), + "New feature should be saved"); + + FeatureDAOReadOnly dao(handle); + + RUNNER_ASSERT_WHAT_EQUALS(dao.GetName(),"new_f1"); + plHandle = dao.GetPluginHandle(); + } + + { + FeatureHandleList old = FeatureDAOReadOnly::GetHandleList(); + + PluginMetafileData::Feature f; + f.m_name = std::string("new_f2"); + + FeatureHandle handle = FeatureDAO::RegisterFeature(f,plHandle); + RUNNER_ASSERT_MSG(handle != -1, "Already registered"); + RUNNER_ASSERT_MSG(old.size() < FeatureDAOReadOnly::GetHandleList().size(), + "New feature should be saved"); + + FeatureDAOReadOnly dao(handle); + + RUNNER_ASSERT_MSG(plHandle == dao.GetPluginHandle(), + "New plugin registered (should be old used)"); + } +} + +/* +Name: feature_dao_test_get_feature_properties +Description: Checks properties of inserted features +Expected: properties of features should match values inserted to database directly +*/ +RUNNER_TEST(feature_dao_test_get_feature_properties) +{ + { + FeatureDAOReadOnly dao("feature1"); + RUNNER_ASSERT_WHAT_EQUALS(dao.GetName(), "feature1"); + RUNNER_ASSERT_WHAT_EQUALS(dao.GetLibraryName(), "plugin1"); + RUNNER_ASSERT_WHAT_EQUALS(dao.GetLibraryPath(), ""); + } + + { + FeatureDAOReadOnly dao("feature2"); + RUNNER_ASSERT_WHAT_EQUALS(dao.GetName(), "feature2"); + RUNNER_ASSERT_WHAT_EQUALS(dao.GetLibraryName(), "p4"); + RUNNER_ASSERT_WHAT_EQUALS(dao.GetLibraryPath(), "path_to_p4"); + } + + { + FeatureDAOReadOnly dao("feature3"); + RUNNER_ASSERT_WHAT_EQUALS(dao.GetName(), "feature3"); + RUNNER_ASSERT_WHAT_EQUALS(dao.GetLibraryName(), "p4"); + RUNNER_ASSERT_WHAT_EQUALS(dao.GetLibraryPath(), "path_to_p4"); + } +} + +/* +Name: feature_dao_test_feature_constructor_name +Description: - +Expected: - + +TODO: test +*/ +RUNNER_TEST(feature_dao_test_feature_constructor_name) +{ + std::list preinstalled; + preinstalled.push_back("feature1"); + preinstalled.push_back("feature2"); + preinstalled.push_back("feature3"); + preinstalled.push_back("feature4"); + + FOREACH(it, preinstalled) + { + FeatureDAOReadOnly dao(*it); + RUNNER_ASSERT_WHAT_EQUALS(dao.GetName(), *it); + } + + //TODO check exception that may occur (feature does not exist) +} + +/* +Name: feature_dao_test_feature_handle_list +Description: Checks if list of installed features is returend correctly +Expected: list size should be at last equal number of preinserted features +*/ +RUNNER_TEST(feature_dao_test_feature_handle_list) +{ + FeatureHandleList handles = FeatureDAOReadOnly::GetHandleList(); + RUNNER_ASSERT(handles.size() >= 4); +} + +/* +Name: feature_dao_test_is_feature_installed +Description: Checks if installed features are showed correctly. +Expected: correct installed features should be present +*/ +RUNNER_TEST(feature_dao_test_is_feature_installed) +{ + //installed + { + std::list preinstalled; + preinstalled.push_back("feature1"); + preinstalled.push_back("feature2"); + preinstalled.push_back("feature3"); + preinstalled.push_back("feature4"); + + FOREACH(it, preinstalled) + RUNNER_ASSERT(FeatureDAOReadOnly::isFeatureInstalled(*it)); + } + + //not installed + { + RUNNER_ASSERT(FeatureDAOReadOnly::isFeatureInstalled("not_installed1")==false); + RUNNER_ASSERT(FeatureDAOReadOnly::isFeatureInstalled("plugin1") == false); + RUNNER_ASSERT(FeatureDAOReadOnly::isFeatureInstalled("") == false); + RUNNER_ASSERT(FeatureDAOReadOnly::isFeatureInstalled("ff") == false); + } +} + +/* +Name: feature_dao_test_get_device_capab +Description: - +Expected: - + +TODO: fix test +*/ +RUNNER_TEST(feature_dao_test_get_device_capab) +{ +#if 0 + //TODO do more tests + + {//check deviceCaps + Feature f; + f.setName("new_dev_f4"); + f.setLibraryName("new_dev_f4 lib_name"); + + FeatureDAOReadOnly::DeviceCapabilitiesList devList; + devList.insert("new_dev_f4 devcap1"); + devList.insert("new_dev_f4 devcap2"); + + FOREACH(it, devList) + f.addDeviceCapability(*it); + + FeatureHandle handle = FeatureDAO::RegisterFeature(f,"new_dev_f4 path"); + + FeatureDAOReadOnly dao(handle); + + FeatureDAOReadOnly::DeviceCapabilitiesList gotList = + dao.GetDeviceCapabilities(); + RUNNER_ASSERT_MSG(gotList.size() == devList.size(), + "deviceCaps wrong"); + } +#endif +} + +/* +Name: feature_dao_test_is_device_capab_installed +Description: Checks if FeatureDAOReadOnly::isDeviceCapabilityInstalled works correctly. +Expected: correct capabilities should be present +*/ +RUNNER_TEST(feature_dao_test_is_device_capab_installed) +{ + //installed + std::list preinstalled; + preinstalled.push_back("devicecap1"); + preinstalled.push_back("devicecap2"); + preinstalled.push_back("devicecap3"); + preinstalled.push_back("devicecap4"); + + FOREACH(it, preinstalled) + RUNNER_ASSERT(FeatureDAOReadOnly::isDeviceCapabilityInstalled(*it)); + + //not installed + std::list notinstalled; + notinstalled.push_back("notinstalled1"); + notinstalled.push_back("plugin1"); + notinstalled.push_back(""); + notinstalled.push_back("ff"); + + FOREACH(it, notinstalled) + RUNNER_ASSERT(!FeatureDAOReadOnly::isDeviceCapabilityInstalled(*it)); +} + +#undef RUNNER_ASSERT_WHAT_EQUALS diff --git a/tests/dao/TestCases_GlobalDAO.cpp b/tests/dao/TestCases_GlobalDAO.cpp new file mode 100644 index 0000000..0098eee --- /dev/null +++ b/tests/dao/TestCases_GlobalDAO.cpp @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file TestCases_GlobalDAO.cpp + * @author Pawel Sikorski (p.sikorski@samsung.com) + * @version 1.0 + * @brief This file contains tests for global dao class. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace WrtDB; + + +namespace +{ +const DPL::String widgetPackage5(L"widgetpackage5"); +} // namespace + +RUNNER_TEST_GROUP_INIT(DAO) + +/* +Name: global_dao_developer_mode +Description: tests if developer mode is correctly set and get +Expected: received developer shoudl match the one was set +*/ +RUNNER_TEST(global_dao_developer_mode) +{ + bool prev_mode = GlobalDAO::GetDeveloperMode(); + GlobalDAO::SetDeveloperMode(false); + RUNNER_ASSERT_MSG(!GlobalDAO::GetDeveloperMode(), "set false failed"); + + GlobalDAO::SetDeveloperMode(true); + RUNNER_ASSERT_MSG(GlobalDAO::GetDeveloperMode(), "set true failed"); + GlobalDAO::SetDeveloperMode(prev_mode); +} + +/* +Name: home_network_data_usage +Description: tests if HomeNetworkDataUsage is correctly set and get +Expected: received developer shoudl match the one was set +*/ +RUNNER_TEST(home_network_data_usage) +{ + GlobalDAO::NetworkAccessMode original = + GlobalDAO::GetHomeNetworkDataUsage(); + + GlobalDAO::SetHomeNetworkDataUsage(GlobalDAO::CONNECT_AUTOMATICALLY); + RUNNER_ASSERT_MSG(GlobalDAO::CONNECT_AUTOMATICALLY == + GlobalDAO::GetHomeNetworkDataUsage(), "Value not updated"); + + GlobalDAO::SetHomeNetworkDataUsage(GlobalDAO::ALWAYS_ASK); + RUNNER_ASSERT_MSG(GlobalDAO::ALWAYS_ASK == + GlobalDAO::GetHomeNetworkDataUsage(), "Value not updated"); + + GlobalDAO::SetHomeNetworkDataUsage(GlobalDAO::NEVER_CONNECT); + RUNNER_ASSERT_MSG(GlobalDAO::NEVER_CONNECT == + GlobalDAO::GetHomeNetworkDataUsage(), "Value not updated"); + + GlobalDAO::SetHomeNetworkDataUsage(original); + RUNNER_ASSERT_MSG(original == GlobalDAO::GetHomeNetworkDataUsage(), + "Value not updated"); +} + +/* +Name: roaming_data_usage +Description: tests if RoamingDataUsage is correctly set and get +Expected: received developer shoudl match the one was set +*/ +RUNNER_TEST(roaming_data_usage) +{ + GlobalDAO::NetworkAccessMode original = + GlobalDAO::GetRoamingDataUsage(); + + GlobalDAO::SetRoamingDataUsage(GlobalDAO::CONNECT_AUTOMATICALLY); + RUNNER_ASSERT_MSG(GlobalDAO::CONNECT_AUTOMATICALLY == + GlobalDAO::GetRoamingDataUsage(), "Value not updated"); + + GlobalDAO::SetRoamingDataUsage(GlobalDAO::ALWAYS_ASK); + RUNNER_ASSERT_MSG(GlobalDAO::ALWAYS_ASK == + GlobalDAO::GetRoamingDataUsage(), "Value not updated"); + + GlobalDAO::SetRoamingDataUsage(GlobalDAO::NEVER_CONNECT); + RUNNER_ASSERT_MSG(GlobalDAO::NEVER_CONNECT == + GlobalDAO::GetRoamingDataUsage(), "Value not updated"); + + GlobalDAO::SetRoamingDataUsage(original); + RUNNER_ASSERT_MSG(original == GlobalDAO::GetRoamingDataUsage(), + "Value not updated"); +} diff --git a/tests/dao/TestCases_PluginDAO.cpp b/tests/dao/TestCases_PluginDAO.cpp new file mode 100644 index 0000000..d737752 --- /dev/null +++ b/tests/dao/TestCases_PluginDAO.cpp @@ -0,0 +1,441 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file TestCases_PluginDAO.cpp + * @author Pawel Sikorski (p.sikorski@samsung.com) + * @version 1.0 + * @brief This file contains tests for feature dao class. + */ + +#include +#include +#include +#include +#include +//#include +#include +#include + +using namespace WrtDB; + +#define RUNNER_ASSERT_WHAT_EQUALS(in, test) \ + {std::string tmp(in); \ + RUNNER_ASSERT_MSG(tmp == test, "Equals: [" + tmp + "]");} + +RUNNER_TEST_GROUP_INIT(DAO) + +/* +Name: plugin_dao_test_register_plugins +Description: registers new plugin and check if it was correctly registered +Expected: plugin should be correctly registered +*/ +RUNNER_TEST(plugin_dao_test_register_plugins) +{ + { + std::string libraryPath("np1 lib_path"); + std::string libraryName("np1"); + + PluginMetafileData pluginData; + pluginData.m_libraryName = libraryName; + + PluginHandle handle = PluginDAO::registerPlugin(pluginData, libraryPath); + PluginDAO::setPluginInstallationStatus(handle,PluginDAO::INSTALLATION_COMPLETED); + RUNNER_ASSERT(PluginDAO::isPluginInstalled(libraryName) == true); + + PluginDAO dao(handle); + std::string tmp; + tmp = dao.getLibraryPath(); //do for each + RUNNER_ASSERT_MSG(tmp == libraryPath, "Equals: " + tmp); + } + + { + std::string libraryName("np2"); + + PluginMetafileData pluginData; + pluginData.m_libraryName = libraryName; + + PluginHandle handle = PluginDAO::registerPlugin(pluginData, ""); + PluginDAO::setPluginInstallationStatus(handle,PluginDAO::INSTALLATION_COMPLETED); + RUNNER_ASSERT(PluginDAO::isPluginInstalled(libraryName) == true); + + PluginDAO dao(handle); + RUNNER_ASSERT(dao.getLibraryPath() == ""); + } +} + +/* +Name: plugin_dao_test_register_plugin_implemented_object +Description: registers new PluginImplementedObject + and check if it was correctly registered +Expected: plugin dao shoudld be upodated with PluginImplementedObject +*/ +RUNNER_TEST(plugin_dao_test_register_plugin_implemented_object) +{ + { + std::string libraryPath("np3 lib_path"); + std::string libraryName("np3"); + + PluginMetafileData pluginData; + pluginData.m_libraryName = libraryName; + + PluginHandle handle = + PluginDAO::registerPlugin(pluginData, libraryPath); + RUNNER_ASSERT(PluginDAO::isPluginInstalled(libraryName) == true); + + std::string object1("object1"); + std::string object2("object2"); + PluginDAO::registerPluginImplementedObject(object1, handle); + PluginDAO::registerPluginImplementedObject(object2, handle); + + PluginHandle retHandle1 = + PluginDAO::getPluginHandleForImplementedObject(object1); + PluginHandle retHandle2 = + PluginDAO::getPluginHandleForImplementedObject(object1); + RUNNER_ASSERT(retHandle1 == handle); + RUNNER_ASSERT(retHandle2 == handle); + } +} + +/* +Name: plugin_dao_test_register_plugin_implemented_object +Description: registers dependecies for plugins and checks if they were saved +Expected: registered dependecies should be returned from database +*/ +RUNNER_TEST(plugin_dao_test_register_library_dependencies) +{ + { + std::string libraryPath("np4 lib_path"); + std::string libraryName("np4"); + + PluginMetafileData pluginData; + pluginData.m_libraryName = libraryName; + + PluginHandle handle = + PluginDAO::registerPlugin(pluginData, libraryPath); + PluginDAO::setPluginInstallationStatus(handle,PluginDAO::INSTALLATION_COMPLETED); + RUNNER_ASSERT(PluginDAO::isPluginInstalled(libraryName) == true); + + PluginHandle depHandles[] = {117, 119}; + + PluginHandleSetPtr dependencies(new PluginHandleSet); + dependencies->insert(depHandles[1]); + dependencies->insert(depHandles[2]); + + PluginDAO::registerPluginLibrariesDependencies(handle, dependencies); + + PluginDAO dao(handle); + PluginHandleSetPtr retDependencies; + retDependencies = dao.getLibraryDependencies(); + + RUNNER_ASSERT( + retDependencies->size()==sizeof(depHandles)/sizeof(depHandles[0])); + RUNNER_ASSERT( + retDependencies->find(depHandles[1]) != retDependencies->end()); + RUNNER_ASSERT( + retDependencies->find(depHandles[2]) != retDependencies->end()); + } +} + +/* +Name: plugin_dao_test_register_required_object +Description: registers required plugin objects for plugins and checks if they were saved +Expected: registered required plugin objects should be returned from database +*/ +RUNNER_TEST(plugin_dao_test_register_required_object) +{ + { + std::string libraryPath("np5 lib_path"); + std::string libraryName("np5"); + + PluginMetafileData pluginData; + pluginData.m_libraryName = libraryName; + + PluginHandle handle = + PluginDAO::registerPlugin(pluginData, libraryPath); + PluginDAO::setPluginInstallationStatus(handle,PluginDAO::INSTALLATION_COMPLETED); + RUNNER_ASSERT(PluginDAO::isPluginInstalled(libraryName) == true); + + const size_t numObjects =2; + std::string objectReq [numObjects]; + objectReq[0] = std::string("object1.req"); + objectReq[1] = std::string("object2.req"); + PluginDAO::registerPluginRequiredObject(objectReq[0], handle); + PluginDAO::registerPluginRequiredObject(objectReq[1], handle); + + WrtDB::PluginObjectsDAO::ObjectsPtr objects = + PluginDAO::getRequiredObjectsForPluginHandle(handle); + + RUNNER_ASSERT(objects->size() == numObjects + && objects->find(objectReq[0]) != objects->end() + && objects->find(objectReq[1]) != objects->end()); + } +} + +/* +Name: plugin_dao_test_is_library_installed +Description: tests if plugin isntallation/registrartion works +Expected: only registered plugins should be reported as installed +*/ +RUNNER_TEST(plugin_dao_test_is_library_installed) +{ + { + //exist + std::list preinstalled; + preinstalled.push_back("plugin1"); + preinstalled.push_back("plugin2"); + preinstalled.push_back("plugin3"); + preinstalled.push_back("p4"); + preinstalled.push_back("p5"); + + FOREACH(it, preinstalled) + RUNNER_ASSERT_MSG(PluginDAO::isPluginInstalled(*it), + std::string("Not found: ") + *it); + } + + { + //does not exist + RUNNER_ASSERT_MSG( + PluginDAO::isPluginInstalled("not_installed1") == false, + "Found not_installed1"); + RUNNER_ASSERT_MSG(PluginDAO::isPluginInstalled("p 4") == false, + "Found p 4"); + RUNNER_ASSERT_MSG(PluginDAO::isPluginInstalled("") == false, + "Found "); + RUNNER_ASSERT_MSG(PluginDAO::isPluginInstalled("p33") == false, + "Found p33"); + RUNNER_ASSERT_MSG(PluginDAO::isPluginInstalled("feature1") == false, + "Found feature1"); + } +} + +/* +Name: plugin_dao_test_get_plugin_handle_list +Description: test of returning plugin handle list +Expected: returned list should be no less than number of registered plugins +*/ +RUNNER_TEST(plugin_dao_test_get_plugin_handle_list) +{ + PluginHandleList handles = PluginDAO::getPluginHandleList(); + RUNNER_ASSERT(handles.size() >= 5); +} + +/* +Name: plugin_dao_test_constructor_name +Description: tests construction of plugin dao based on plugin name +Expected: Instance of dao should be constructed only + if there is given plugin in database +*/ +RUNNER_TEST(plugin_dao_test_constructor_name) +{ + { + //exist + std::list preinstalled; + preinstalled.push_back("plugin1"); + preinstalled.push_back("plugin2"); + preinstalled.push_back("plugin3"); + preinstalled.push_back("p4"); + preinstalled.push_back("p5"); + + FOREACH(it, preinstalled) + { + PluginDAO dao(*it); + RUNNER_ASSERT_WHAT_EQUALS(dao.getLibraryName(), *it); + } + } + + { + //does not exist + std::list not_installed; + not_installed.push_back("plugin 1"); + not_installed.push_back(""); + not_installed.push_back("p 3"); + + FOREACH(it, not_installed) + { + Try { + //Plugin not exist + PluginDAO dao(*it); + RUNNER_ASSERT_MSG(false, "should not be found"); + } + Catch (PluginDAO::Exception::PluginNotExist) { + continue; + } + } + } + +} + +/* +Name: plugin_dao_test_get_plugin_properties +Description: tests reading plugin properties from database +Expected: Data, inserted into database, should be accessible via dao +*/ +RUNNER_TEST(plugin_dao_test_get_plugin_properties) +{ + { + PluginDAO dao("p4"); + RUNNER_ASSERT(dao.getPluginHandle() == 4); + RUNNER_ASSERT_WHAT_EQUALS(dao.getLibraryName(), "p4"); + RUNNER_ASSERT_WHAT_EQUALS(dao.getLibraryPath(), "path_to_p4"); + } + + { + PluginDAO dao(5); + RUNNER_ASSERT(dao.getPluginHandle() == 5); + RUNNER_ASSERT_WHAT_EQUALS(dao.getLibraryName(), "p5"); + RUNNER_ASSERT_WHAT_EQUALS(dao.getLibraryPath(), "path_to_p5"); + } + + { + PluginDAO dao(2); + RUNNER_ASSERT(dao.getPluginHandle() == 2); + RUNNER_ASSERT_WHAT_EQUALS(dao.getLibraryName(), "plugin2"); + RUNNER_ASSERT_WHAT_EQUALS(dao.getLibraryPath(), "path_to_plugin2"); + } + + { + PluginDAO dao(1); + RUNNER_ASSERT(dao.getPluginHandle() == 1); + RUNNER_ASSERT_WHAT_EQUALS(dao.getLibraryName(), "plugin1"); + RUNNER_ASSERT_WHAT_EQUALS(dao.getLibraryPath(), ""); + } +} + +/* +Name: plugin_dao_test_get_implemented_objects_for_plugin_handle_1 +Description: tests receiving from dao Implemented Objects +Expected: returned object is size 0 +*/ +RUNNER_TEST(plugin_dao_test_get_implemented_objects_for_plugin_handle_1) +{ + { + const int handle = 1; + PluginDAOReadOnly dao(handle); + auto dbHandle = dao.getPluginHandle(); + RUNNER_ASSERT(dbHandle == handle); + auto objects = dao.getImplementedObjectsForPluginHandle(dbHandle); + + RUNNER_ASSERT(objects.size() == 0); + } +} + +/* +Name: plugin_dao_test_get_implemented_objects_for_plugin_handle_2 +Description: tests receiving from dao Implemented Objects +Expected: returned object is size as it was inserted +*/ +RUNNER_TEST(plugin_dao_test_get_implemented_objects_for_plugin_handle_2) +{ + { + std::set< std::string > preinstalled = + { + "" + }; + + PluginDAOReadOnly dao(2); + auto dbHandle = dao.getPluginHandle(); + auto objects = dao.getImplementedObjectsForPluginHandle(dbHandle); + + //LogError("\n" << objects.size() << " " << preinstalled.size() << "\n"); + + RUNNER_ASSERT(objects.size() == preinstalled.size()); + + FOREACH(dbObject, objects) + { + RUNNER_ASSERT(preinstalled.find(*dbObject) != preinstalled.end()); + } + } +} + +/* +Name: plugin_dao_test_get_implemented_objects_for_plugin_handle_3 +Description: tests receiving from dao Implemented Objects +Expected: returned objects list has preinserted object +*/ +RUNNER_TEST(plugin_dao_test_get_implemented_objects_for_plugin_handle_3) +{ + { + std::set< std::string > preinstalled = + { + "Plugin_3_Object_A" + }; + + PluginDAOReadOnly dao(3); + auto dbHandle = dao.getPluginHandle(); + auto objects = dao.getImplementedObjectsForPluginHandle(dbHandle); + RUNNER_ASSERT(objects.size() == preinstalled.size()); + + FOREACH(dbObject, objects) + { + RUNNER_ASSERT(preinstalled.find(*dbObject) != preinstalled.end()); + } + } +} + +/* +Name: plugin_dao_test_get_implemented_objects_for_plugin_handle_4 +Description: tests receiving from dao Implemented Objects +Expected: returned objects list has all preinserted objects +*/ +RUNNER_TEST(plugin_dao_test_get_implemented_objects_for_plugin_handle_4) +{ + { + std::set< std::string > preinstalled = + { + "Plugin_4_Object_A", + "Plugin_4_Object_B", + "Plugin_4_Object_C", + }; + + PluginDAOReadOnly dao(4); + auto dbHandle = dao.getPluginHandle(); + auto objects = dao.getImplementedObjectsForPluginHandle(dbHandle); + RUNNER_ASSERT(objects.size() == preinstalled.size()); + + FOREACH(dbObject, objects) + { + RUNNER_ASSERT(preinstalled.find(*dbObject) != preinstalled.end()); + } + } +} + +/* +Name: plugin_dao_test_get_implemented_objects_for_plugin_handle_5 +Description: tests receiving from dao Implemented Objects +Expected: returned objects list do not have object that was not inserted +*/ +RUNNER_TEST(plugin_dao_test_get_implemented_objects_for_plugin_handle_5) +{ + { + std::set< std::string > preinstalled = + { + "Plugin_5_Object_B", + }; + + PluginDAOReadOnly dao(5); + auto dbHandle = dao.getPluginHandle(); + auto objects = dao.getImplementedObjectsForPluginHandle(dbHandle); + RUNNER_ASSERT(objects.size() == preinstalled.size()); + + FOREACH(dbObject, objects) + { + RUNNER_ASSERT(preinstalled.find(*dbObject) == preinstalled.end()); + } + } +} + + +#undef RUNNER_ASSERT_WHAT_EQUALS diff --git a/tests/dao/TestCases_PropertyDAO.cpp b/tests/dao/TestCases_PropertyDAO.cpp new file mode 100644 index 0000000..e72b01b --- /dev/null +++ b/tests/dao/TestCases_PropertyDAO.cpp @@ -0,0 +1,163 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file TestCases_PropertyDAO.cpp + * @author Pawel Sikorski (p.sikorski@samsung.com) + * @version 1.0 + * @brief This file contains tests for property dao class. + */ + +#include +#include +#include +#include +#include +#include +#include + +using namespace WrtDB; +using namespace WrtDB::PropertyDAOReadOnly; + +// Widgets used 2000, 2001, 2002, 2003(saved by wrt_dao_tests_prepare_db.sh) + +#define RUNNER_ASSERT_WHAT_EQUALS(in, test) \ + {std::string tmp(in); \ + RUNNER_ASSERT_MSG(tmp == test, "Equals: [" + tmp + "]");} + +#define RUNNER_ASSERT_WHAT_EQUALS_OPTIONAL(in, test) \ + { \ + if(in.IsNull()) RUNNER_ASSERT_MSG(false, "NULL"); \ + else RUNNER_ASSERT_WHAT_EQUALS(DPL::ToUTF8String(*in),test);\ + } + +RUNNER_TEST_GROUP_INIT(DAO) + +/* +Name: property_dao_get_lists +Description: tests returning list of properties for given id +Expected: data received should match those, which were inserted in prepare script +*/ +RUNNER_TEST(property_dao_get_lists) +{ + {//property list + std::map prefsMap; + prefsMap.insert(std::pair(2000, 2)); + prefsMap.insert(std::pair(2001, 1)); + prefsMap.insert(std::pair(2002, 2)); + prefsMap.insert(std::pair(1, 0)); //no widget + + FOREACH(it, prefsMap) { + PropertyDAOReadOnly::WidgetPreferenceList prefs = + PropertyDAOReadOnly::GetPropertyList(it->first); + RUNNER_ASSERT(prefs.size() == it->second); + } + } + + {//property key list + WidgetPropertyKeyList orig_2000; + orig_2000.push_back(DPL::FromUTF8String("key1_for_2000")); + orig_2000.push_back(DPL::FromUTF8String("key2_for_2000")); + + WidgetPropertyKeyList orig_2001; + orig_2001.push_back(DPL::FromUTF8String("key1_for_2001")); + + WidgetPropertyKeyList orig_2002; + orig_2002.push_back(DPL::FromUTF8String("key1_for_2002")); + orig_2002.push_back(DPL::FromUTF8String("key2_for_2002")); + + std::map prefsKeyMap; + prefsKeyMap.insert(std::pair( + 2000, &orig_2000)); + prefsKeyMap.insert(std::pair( + 2001, &orig_2001)); + prefsKeyMap.insert(std::pair( + 2002, &orig_2002)); + + FOREACH(it_out, prefsKeyMap) { + WidgetPropertyKeyList got = PropertyDAOReadOnly::GetPropertyKeyList( + it_out->first); + RUNNER_ASSERT(got.size() == it_out->second->size()); + //TODO + // FOREACH(it_in, got) + // { + // RUNNER_ASSERT(it_out->second. + // } + } + } +} + +/* +Name: property_dao_set_update_remove +Description: tests set new property for widget, updating property and removing it +Expected: given operation should works +*/ +RUNNER_TEST(property_dao_set_update_remove) +{ + WidgetPropertyKeyList keys = PropertyDAOReadOnly::GetPropertyKeyList(2000); + + //ADD + PropertyDAO::SetProperty(2000, + DPL::FromUTF8String("new_key"), + DPL::FromUTF8String("new_value1")); + + RUNNER_ASSERT_MSG( + keys.size() + 1 == PropertyDAOReadOnly::GetPropertyKeyList(2000).size(), + "new property not added"); + RUNNER_ASSERT_WHAT_EQUALS_OPTIONAL( + PropertyDAOReadOnly::GetPropertyValue(2000, + DPL::FromUTF8String("new_key")), + "new_value1"); + + //UPDATE + PropertyDAO::SetProperty(2000, + DPL::FromUTF8String("new_key"), + DPL::FromUTF8String("new_value2")); + RUNNER_ASSERT_MSG( + keys.size() + 1 == PropertyDAOReadOnly::GetPropertyKeyList(2000).size(), + "new property not added"); + RUNNER_ASSERT_WHAT_EQUALS_OPTIONAL( + PropertyDAOReadOnly::GetPropertyValue(2000, + DPL::FromUTF8String("new_key")), + "new_value2"); + + //REMOVE + PropertyDAO::RemoveProperty(2000, DPL::FromUTF8String("new_key")); + + RUNNER_ASSERT_MSG( + keys.size() == PropertyDAOReadOnly::GetPropertyKeyList(2000).size(), + "property not removed"); + +} + +/* +Name: property_dao_get_value +Description: tests if properties can be received from database +Expected: value, which were inserted before test, should be present +*/ +RUNNER_TEST(property_dao_get_value) +{ + RUNNER_ASSERT_WHAT_EQUALS_OPTIONAL( + PropertyDAOReadOnly::GetPropertyValue( + 2000, DPL::FromUTF8String("key1_for_2000")), + "value_for_key1_2000"); + + RUNNER_ASSERT_WHAT_EQUALS_OPTIONAL( + PropertyDAOReadOnly::GetPropertyValue( + 2000, DPL::FromUTF8String("key2_for_2000")), + "value_for_key2_2000"); +} + +#undef RUNNER_ASSERT_WHAT_EQUALS diff --git a/tests/dao/TestCases_WidgetDAO.cpp b/tests/dao/TestCases_WidgetDAO.cpp new file mode 100644 index 0000000..92e1995 --- /dev/null +++ b/tests/dao/TestCases_WidgetDAO.cpp @@ -0,0 +1,980 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file TestCases_WidgetDAO.cpp + * @author Pawel Sikorski (p.sikorski@samsung.com) + * @version 1.0 + * @brief This file contains tests for widget dao class. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace WrtDB; + +namespace { + +class WacSecurityMock : public WrtDB::IWacSecurity +{ +public: + WacSecurityMock() : + mRecognized(false), + mDistributorSigned(false), + mWacSigned(false) + { + } + + virtual const WidgetCertificateDataList& getCertificateList() const + { + return mList; + } + + virtual bool isRecognized() const { return mRecognized; } + virtual bool isDistributorSigned() const { return mDistributorSigned; } + virtual bool isWacSigned() const { return mWacSigned; } + virtual void getCertificateChainList(CertificateChainList& /*lst*/) const {} + virtual void getCertificateChainList(CertificateChainList& /*lst*/, + CertificateSource source) const {} + + WrtDB::WidgetCertificateDataList& getCertificateListRef() + { + return mList; + } + + void setRecognized(bool recognized) { mRecognized = recognized; } + void setDistributorSigned(bool distributorSigned) + { + mDistributorSigned = distributorSigned; + } + void setWacSigned(bool wacSigned) { mWacSigned = wacSigned; } + +private: + WrtDB::WidgetCertificateDataList mList; + // author signature verified + bool mRecognized; + // known distribuor + bool mDistributorSigned; + // distributor is wac + bool mWacSigned; + +}; + +WidgetPkgName _registerWidget(const WidgetRegisterInfo& regInfo, + const IWacSecurity& sec, + int line) +{ + WidgetPkgName pkgname; + Try { + auto previous = WidgetDAO::getPkgnameList_TEMPORARY_API(); + + // register widget + pkgname = WidgetDAO::registerWidgetGenerateTizenId(regInfo, sec); + + RUNNER_ASSERT_MSG(!pkgname.empty(), + "(called from line " << line << ")"); + + auto current = WidgetDAO::getPkgnameList_TEMPORARY_API(); + RUNNER_ASSERT_MSG(previous.size()+1 == current.size(), + "(called from line " << line << ")"); + + RUNNER_ASSERT_MSG(WidgetDAO::isWidgetInstalled(pkgname), + "(called from line " << line << " pkgname: " << pkgname << ")"); + } + Catch (WidgetDAO::Exception::AlreadyRegistered) { + RUNNER_ASSERT_MSG( + false, + "Unexpected exception (called from line " << line << ")"); + } + return pkgname; +} + +#define REGISTER_WIDGET(regInfo, sec) _registerWidget((regInfo),(sec), __LINE__) + +} // namespace + +// Widgets used <2300,2500), 2000, 2001, 2002, 2003 + +#define RUNNER_ASSERT_WHAT_EQUALS(in, test) \ + {std::string tmp(in); \ + RUNNER_ASSERT_MSG(tmp == test, "Equals: [" + tmp + "]");} + +#define RUNNER_ASSERT_WHAT_EQUALS_OPTIONAL(in, test) \ + { \ + if(in.IsNull()) RUNNER_ASSERT_MSG(false, "NULL"); \ + else RUNNER_ASSERT_WHAT_EQUALS(DPL::ToUTF8String(*in),test);\ + } + +#define RUNNER_ASSERT_WHAT_EQUALS_OPTIONALINT(in, test) \ + { \ + if(in.IsNull()) RUNNER_ASSERT_MSG(false, "NULL"); \ + else RUNNER_ASSERT_MSG(*in == test, "Equals: [" + *in + "]"); \ + } + +RUNNER_TEST_GROUP_INIT(DAO) + +//2300 +/* +Name: widget_dao_test_register_widget_empty_strings +Description: Tests registeration of new widget with empty values +Expected: widget should be registered in database +*/ +RUNNER_TEST(widget_dao_test_register_widget_empty_strings) +{ + WidgetRegisterInfo regInfo; + + //ext info + regInfo.shareHref = ""; + + //info + regInfo.configInfo.widget_id = DPL::FromUTF8String(""); + regInfo.configInfo.version = DPL::FromUTF8String(""); + regInfo.configInfo.width = 10; + regInfo.configInfo.height = 10; + regInfo.configInfo.authorName = DPL::FromUTF8String(""); + regInfo.configInfo.authorEmail = DPL::FromUTF8String(""); + regInfo.configInfo.authorHref = DPL::FromUTF8String(""); + regInfo.baseFolder = ""; + //TODO authenticated, etc... + regInfo.configInfo.flashNeeded = false; + regInfo.configInfo.minVersionRequired = DPL::FromUTF8String("1.0"); + regInfo.configInfo.backSupported = true; + + //loc info + ConfigParserData::LocalizedData locData; + locData.name = DPL::FromUTF8String(""); + locData.shortName = DPL::FromUTF8String(""); + locData.description = DPL::FromUTF8String(""); + locData.license = DPL::FromUTF8String(""); + locData.licenseFile = DPL::FromUTF8String(""); + locData.licenseHref = DPL::FromUTF8String(""); + regInfo.configInfo.localizedDataSet.insert( + std::make_pair(DPL::FromUTF8String("en"),locData)); + + //userAgentLoc + + //icons + ConfigParserData::Icon icon(DPL::FromUTF8String("")); + icon.width = 10; + icon.height = 10; + LocaleSet locs; + locs.insert(DPL::FromUTF8String("en")); + WidgetRegisterInfo::LocalizedIcon locIcon(icon,locs); + regInfo.localizationData.icons.push_back(locIcon); + + //start file + WidgetRegisterInfo::StartFileProperties prop; + prop.encoding = DPL::FromUTF8String(""); + prop.type = DPL::FromUTF8String(""); + WidgetRegisterInfo::LocalizedStartFile file; + file.path = DPL::FromUTF8String(""); + file.propertiesForLocales.insert( + std::make_pair(DPL::FromUTF8String("en"), prop)); + regInfo.localizationData.startFiles.push_back(file); + + //widget pref + ConfigParserData::Preference pref(DPL::FromUTF8String(""),false); + pref.value = DPL::FromUTF8String(""); + regInfo.configInfo.preferencesList.insert(pref); + + //widget feature + ConfigParserData::Feature feat(DPL::FromUTF8String(""),false); + ConfigParserData::Param par(DPL::FromUTF8String((""))); + par.value = DPL::FromUTF8String(""); + feat.paramsList.insert(par); + regInfo.configInfo.featuresList.insert(feat); + + //win modes + regInfo.configInfo.windowModes.insert(DPL::FromUTF8String("")); + + //WARP info + ConfigParserData::AccessInfo access(DPL::FromUTF8String(""),true); + regInfo.configInfo.accessInfoSet.insert(access); + + //certificates + WidgetCertificateData cert; + cert.owner = WidgetCertificateData::AUTHOR; + cert.type = WidgetCertificateData::ROOT; + cert.chainId = 1; + cert.strMD5Fingerprint = ""; + cert.strSHA1Fingerprint = ""; + cert.strCommonName = DPL::FromUTF8String(""); + + WacSecurityMock security; + security.getCertificateListRef().push_back(cert); + + REGISTER_WIDGET(regInfo,security); +} + +/* +Name: widget_dao_test_register_widget_empty_strings +Description: Tests possiblity of registering twice same content (different tizenId) +Expected: it should be possible +*/ +RUNNER_TEST(widget_dao_test_twice_install_same_widget) +{ + WacSecurityMock sec; + { + WidgetRegisterInfo regInfo; + REGISTER_WIDGET(regInfo, sec); + } + { + WidgetRegisterInfo regInfo; + REGISTER_WIDGET(regInfo, sec); + } + +} + +/* +Name: widget_dao_test_register_widget_minimum_info +Description: Tests simplest registeration of new widget +Expected: widget should be registered in database +*/ +RUNNER_TEST(widget_dao_test_register_widget_minimum_info) +{ + WacSecurityMock sec; + const std::size_t NUMBER_OF_WIDGETS = 5; + + WidgetPkgName lastPkgname; + + for (std::size_t number = 0; number < NUMBER_OF_WIDGETS; ++number) + { + WidgetRegisterInfo regInfo; + WidgetPkgName pkgname = REGISTER_WIDGET(regInfo, sec); + + lastPkgname = pkgname; + + WidgetDAO dao(pkgname); + //TODO check nulls + } +} + +/* +Name: widget_dao_test_register_widget_info +Description: Tests registeration of many widgets +Expected: all widgets should be registered in database +*/ +RUNNER_TEST(widget_dao_test_register_widget_info) +{ + WacSecurityMock sec; + const std::size_t NUMBER_OF_WIDGETS = 5; + + for (std::size_t number = 0; number < NUMBER_OF_WIDGETS; ++number) + { + std::ostringstream str; + str << "register_info_test_" << number; + + WidgetRegisterInfo regInfo; + regInfo.configInfo.widget_id = DPL::FromUTF8String(str.str()); + regInfo.configInfo.version = DPL::FromUTF8String(str.str()); + regInfo.configInfo.width = 10; + regInfo.configInfo.height = 10; + regInfo.configInfo.authorName = DPL::FromUTF8String(str.str()); + regInfo.configInfo.authorEmail = DPL::FromUTF8String(str.str()); + regInfo.configInfo.authorHref = DPL::FromUTF8String(str.str()); + regInfo.baseFolder = str.str(); //base folder at the end has / + regInfo.configInfo.flashNeeded = false; + //TODO authenticated, etc... + //in wrt-installer: TaskWidgetConfig::fillWidgetConfig: + //regInfo.minVersion = regInfo.configInfo.minVersionRequired + regInfo.minVersion = DPL::FromUTF8String("1.0"); + regInfo.configInfo.backSupported = true; + + WidgetPkgName pkgname = REGISTER_WIDGET(regInfo, sec); + + WidgetDAO dao(pkgname); + RUNNER_ASSERT_WHAT_EQUALS_OPTIONAL(dao.getGUID(), str.str()); + RUNNER_ASSERT_WHAT_EQUALS_OPTIONAL(dao.getVersion(), str.str()); + RUNNER_ASSERT_WHAT_EQUALS_OPTIONAL(dao.getAuthorName(), str.str()); + RUNNER_ASSERT_WHAT_EQUALS_OPTIONAL(dao.getAuthorEmail(), str.str()); + RUNNER_ASSERT_WHAT_EQUALS_OPTIONAL(dao.getAuthorHref(), str.str()); + RUNNER_ASSERT_WHAT_EQUALS(dao.getBaseFolder(), str.str() + "/"); + RUNNER_ASSERT(dao.getWebkitPluginsRequired() == false); +// RUNNER_ASSERT( +// dao.GetWidgetSecurityDomain() == WacSecurity::Trusted); + RUNNER_ASSERT_WHAT_EQUALS_OPTIONAL(dao.getMinimumWacVersion(), "1.0"); + } + +} + +/* +Name: widget_dao_test_register_widget_extended_info +Description: Tests registeration of widget_extended_info +Expected: registeration of extended inforamtion is checked + via existence of backgroudn page value +*/ +RUNNER_TEST(widget_dao_test_register_widget_extended_info) +{ + WacSecurityMock sec; + const std::size_t NUMBER_OF_WIDGETS = 5; + + for (std::size_t number = 0; number < NUMBER_OF_WIDGETS; ++number) + { + std::ostringstream str; + str << "register_ext_info_test_" << number; + + WidgetRegisterInfo regInfo; + +// regInfo.shareHref = str.str(); + regInfo.configInfo.backgroundPage = L"background.html"; + + WidgetPkgName pkgname = REGISTER_WIDGET(regInfo, sec); + + WidgetDAO dao(pkgname); +// RUNNER_ASSERT_WHAT_EQUALS(dao.GetShareHref(), str.str()); + + RUNNER_ASSERT_WHAT_EQUALS_OPTIONAL(dao.getBackgroundPage(), + "background.html"); + } +} + +/* +Name: widget_dao_test_register_widget_localized_info +Description: Tests registeration of localized widgets information +Expected: values received by dao should match those which were registered +*/ +RUNNER_TEST(widget_dao_test_register_widget_localized_info) +{ + WacSecurityMock sec; + const std::size_t NUMBER_OF_WIDGETS = 5; + + for (std::size_t number = 0; number < NUMBER_OF_WIDGETS; ++number) + { + WidgetRegisterInfo regInfo; + std::ostringstream str_en; + std::ostringstream str_pl; + str_en << "register_loc_info_test_en_" << number; + str_pl<< "register_loc_info_test_pl_" << number; + {//EN + ConfigParserData::LocalizedData locDataEn; + locDataEn.name = DPL::FromUTF8String(str_en.str()); + locDataEn.shortName = DPL::FromUTF8String(str_en.str()); + locDataEn.description = DPL::FromUTF8String(str_en.str()); + locDataEn.license = DPL::FromUTF8String(str_en.str()); + locDataEn.licenseFile = DPL::FromUTF8String(str_en.str()); + locDataEn.licenseHref = DPL::FromUTF8String(str_en.str()); + regInfo.configInfo.localizedDataSet.insert( + std::make_pair(DPL::FromUTF8String("en"),locDataEn)); + } + + {//PL + ConfigParserData::LocalizedData locDataPl; + locDataPl.name = DPL::FromUTF8String(str_pl.str()); + locDataPl.shortName = DPL::FromUTF8String(str_pl.str()); + locDataPl.description = DPL::FromUTF8String(str_pl.str()); + locDataPl.license = DPL::FromUTF8String(str_pl.str()); + locDataPl.licenseFile = DPL::FromUTF8String(str_pl.str()); + locDataPl.licenseHref = DPL::FromUTF8String(str_pl.str()); + regInfo.configInfo.localizedDataSet.insert( + std::make_pair(DPL::FromUTF8String("pl"),locDataPl)); + } + + WidgetPkgName pkgname = REGISTER_WIDGET(regInfo, sec); + + WidgetDAO dao(pkgname); + RUNNER_ASSERT_MSG(dao.getLanguageTags().size() == 2, + "language tags list invalid"); + + {//EN + WidgetLocalizedInfo locInfo = + dao.getLocalizedInfo(DPL::FromUTF8String("en")); + + RUNNER_ASSERT_WHAT_EQUALS_OPTIONAL(locInfo.name, + str_en.str()); + RUNNER_ASSERT_WHAT_EQUALS_OPTIONAL(locInfo.shortName, + str_en.str()); + RUNNER_ASSERT_WHAT_EQUALS_OPTIONAL(locInfo.description, + str_en.str()); + RUNNER_ASSERT_WHAT_EQUALS_OPTIONAL(locInfo.license, + str_en.str()); + RUNNER_ASSERT_WHAT_EQUALS_OPTIONAL(locInfo.licenseHref, + str_en.str()); + } + + {//PL + WidgetLocalizedInfo locInfo = + dao.getLocalizedInfo(DPL::FromUTF8String("pl")); + + RUNNER_ASSERT_WHAT_EQUALS_OPTIONAL(locInfo.name, + str_pl.str()); + RUNNER_ASSERT_WHAT_EQUALS_OPTIONAL(locInfo.shortName, + str_pl.str()); + RUNNER_ASSERT_WHAT_EQUALS_OPTIONAL(locInfo.description, + str_pl.str()); + RUNNER_ASSERT_WHAT_EQUALS_OPTIONAL(locInfo.license, + str_pl.str()); + RUNNER_ASSERT_WHAT_EQUALS_OPTIONAL(locInfo.licenseHref, + str_pl.str()); + } + } +} + +/* +Name: widget_dao_test_register_widget_icons +Description: Tests registeration of localized icons information +Expected: values received by dao should match those which were registered + for icon +*/ +RUNNER_TEST(widget_dao_test_register_widget_icons) +{ + WacSecurityMock sec; + WidgetRegisterInfo regInfo; + + ConfigParserData::Icon icon(L"icon1"); + icon.width = 10; + icon.height = 10; + LocaleSet locs; + locs.insert(DPL::FromUTF8String("en")); + WidgetRegisterInfo::LocalizedIcon locIcon(icon,locs); + regInfo.localizationData.icons.push_back(locIcon); + + WidgetPkgName pkgname = REGISTER_WIDGET(regInfo, sec); + + WidgetDAO dao(pkgname); + WidgetDAOReadOnly::WidgetIconList list = dao.getIconList(); + + RUNNER_ASSERT(list.size() == regInfo.localizationData.icons.size()); + WidgetDAOReadOnly::WidgetIconList::const_iterator it1 = list.begin(); + WidgetRegisterInfo::LocalizedIconList::const_iterator it2 = + regInfo.localizationData.icons.begin(); + for(;it1!=list.end() && it2!=regInfo.localizationData.icons.end(); + ++it1,++it2) + { + RUNNER_ASSERT(it2->height == it1->iconHeight); + RUNNER_ASSERT(it2->width == it1->iconWidth); + RUNNER_ASSERT(it2->src == it1->iconSrc); + RUNNER_ASSERT(it2->availableLocales == locs); + } +} + +/* +Name: widget_dao_test_register_widget_start_files +Description: Tests registeration of localized start files +Expected: no expectations as it should be removed +*/ +RUNNER_TEST(widget_dao_test_register_widget_start_files) +{ + WacSecurityMock sec; + + WidgetRegisterInfo::LocalizedStartFileList files; + WidgetRegisterInfo::StartFilePropertiesForLocalesMap map1; + WidgetRegisterInfo::StartFileProperties prop1; + prop1.encoding = DPL::FromUTF8String("enc1"); + prop1.type = DPL::FromUTF8String("type1"); + + map1.insert(std::make_pair(DPL::FromUTF8String("en"),prop1)); + map1.insert(std::make_pair(DPL::FromUTF8String("pl"),prop1)); + + WidgetRegisterInfo::LocalizedStartFile file1; + WidgetRegisterInfo::LocalizedStartFile file2; + file1.path = DPL::FromUTF8String("path1"); + file1.propertiesForLocales = map1; + file2.path = DPL::FromUTF8String("path2"); + file2.propertiesForLocales = map1; + + files.push_back(file1); + files.push_back(file1); + + WidgetRegisterInfo regInfo; + regInfo.localizationData.startFiles = files; + + REGISTER_WIDGET(regInfo, sec); + + //TODO no getter in WidgetDAO (getter in LocalizedWidgetDAO, + // but it will be removed +} + +/* +Name: widget_dao_test_register_widget_features +Description: Tests registeration of features of widget +Expected: number of features should match (for given widget reginfo) +*/ +RUNNER_TEST(widget_dao_test_register_widget_features) +{ + WacSecurityMock sec; + ConfigParserData::FeaturesList features; + features.insert(ConfigParserData::Feature(DPL::FromUTF8String("f1"),true)); + features.insert(ConfigParserData::Feature(DPL::FromUTF8String("f2"))); + features.insert(ConfigParserData::Feature(DPL::FromUTF8String("f3"), + false)); + + WidgetRegisterInfo regInfo; + FOREACH(it, features) + regInfo.configInfo.featuresList.insert(*it); + + WidgetPkgName pkgname = REGISTER_WIDGET(regInfo, sec); + + WidgetDAO dao(pkgname); + WidgetFeatureSet out = dao.getFeaturesList(); + RUNNER_ASSERT_MSG(out.size() == features.size(), + "wrong number of features"); +// FOREACH(it, out) +// RUNNER_ASSERT(features.find(*it) != features.end()); +} + +/* +Name: widget_dao_test_register_widget_security_settings +Description: Tests registeration of dafault values of security settings +Expected: widget should be registered in database. + Returned values should match dafault. +*/ +RUNNER_TEST(widget_dao_test_register_widget_security_settings) +{ + WacSecurityMock sec; + WidgetRegisterInfo regInfo; + WidgetPkgName pkgname = REGISTER_WIDGET(regInfo, sec); + + WidgetDAO dao(pkgname); + RUNNER_ASSERT_MSG(dao.getSecurityPopupUsage() == WrtDB::SETTINGS_TYPE_ON, "SecurityPopupUsage is not deafult on"); + RUNNER_ASSERT_MSG(dao.getGeolocationUsage() == WrtDB::SETTINGS_TYPE_ON, "GeolocationUsage is not deafult on"); + RUNNER_ASSERT_MSG(dao.getWebNotificationUsage() == WrtDB::SETTINGS_TYPE_ON, "WebNotificationUsage is not deafult on"); + RUNNER_ASSERT_MSG(dao.getWebDatabaseUsage() == WrtDB::SETTINGS_TYPE_ON, "WebDatabaseUsage is not deafult on"); + RUNNER_ASSERT_MSG(dao.getFileSystemUsage() == WrtDB::SETTINGS_TYPE_ON, "FileSystemUsage is not deafult on"); + + dao.setSecurityPopupUsage(WrtDB::SETTINGS_TYPE_OFF); + RUNNER_ASSERT_MSG(dao.getSecurityPopupUsage() == WrtDB::SETTINGS_TYPE_OFF, "SecurityPopupUsage - wrong value"); + RUNNER_ASSERT_MSG(dao.getGeolocationUsage() == WrtDB::SETTINGS_TYPE_ON, "GeolocationUsage - wrong value"); + RUNNER_ASSERT_MSG(dao.getWebNotificationUsage() == WrtDB::SETTINGS_TYPE_ON, "WebNotificationUsage - wrong value"); + RUNNER_ASSERT_MSG(dao.getWebDatabaseUsage() == WrtDB::SETTINGS_TYPE_ON, "WebDatabaseUsage - wrong value"); + RUNNER_ASSERT_MSG(dao.getFileSystemUsage() == WrtDB::SETTINGS_TYPE_ON, "FileSystemUsage - wrong value"); + + dao.setGeolocationUsage(WrtDB::SETTINGS_TYPE_ALWAYS_ASK); + RUNNER_ASSERT_MSG(dao.getSecurityPopupUsage() == WrtDB::SETTINGS_TYPE_OFF, "SecurityPopupUsage - wrong value"); + RUNNER_ASSERT_MSG(dao.getGeolocationUsage() == WrtDB::SETTINGS_TYPE_ALWAYS_ASK, "GeolocationUsage - wrong value"); + RUNNER_ASSERT_MSG(dao.getWebNotificationUsage() == WrtDB::SETTINGS_TYPE_ON, "WebNotificationUsage - wrong value"); + RUNNER_ASSERT_MSG(dao.getWebDatabaseUsage() == WrtDB::SETTINGS_TYPE_ON, "WebDatabaseUsage - wrong value"); + RUNNER_ASSERT_MSG(dao.getFileSystemUsage() == WrtDB::SETTINGS_TYPE_ON, "FileSystemUsage - wrong value"); + + dao.setWebNotificationUsage(WrtDB::SETTINGS_TYPE_OFF); + RUNNER_ASSERT_MSG(dao.getSecurityPopupUsage() == WrtDB::SETTINGS_TYPE_OFF, "SecurityPopupUsage - wrong value"); + RUNNER_ASSERT_MSG(dao.getGeolocationUsage() == WrtDB::SETTINGS_TYPE_ALWAYS_ASK, "GeolocationUsage - wrong value"); + RUNNER_ASSERT_MSG(dao.getWebNotificationUsage() == WrtDB::SETTINGS_TYPE_OFF, "WebNotificationUsage - wrong value"); + RUNNER_ASSERT_MSG(dao.getWebDatabaseUsage() == WrtDB::SETTINGS_TYPE_ON, "WebDatabaseUsage - wrong value"); + RUNNER_ASSERT_MSG(dao.getFileSystemUsage() == WrtDB::SETTINGS_TYPE_ON, "FileSystemUsage - wrong value"); + + dao.setWebDatabaseUsage(WrtDB::SETTINGS_TYPE_ALWAYS_ASK); + RUNNER_ASSERT_MSG(dao.getSecurityPopupUsage() == WrtDB::SETTINGS_TYPE_OFF, "SecurityPopupUsage - wrong value"); + RUNNER_ASSERT_MSG(dao.getGeolocationUsage() == WrtDB::SETTINGS_TYPE_ALWAYS_ASK, "GeolocationUsage - wrong value"); + RUNNER_ASSERT_MSG(dao.getWebNotificationUsage() == WrtDB::SETTINGS_TYPE_OFF, "WebNotificationUsage - wrong value"); + RUNNER_ASSERT_MSG(dao.getWebDatabaseUsage() == WrtDB::SETTINGS_TYPE_ALWAYS_ASK, "WebDatabaseUsage - wrong value"); + RUNNER_ASSERT_MSG(dao.getFileSystemUsage() == WrtDB::SETTINGS_TYPE_ON, "FileSystemUsage - wrong value"); + + dao.setFileSystemUsage(WrtDB::SETTINGS_TYPE_OFF); + RUNNER_ASSERT_MSG(dao.getSecurityPopupUsage() == WrtDB::SETTINGS_TYPE_OFF, "SecurityPopupUsage - wrong value"); + RUNNER_ASSERT_MSG(dao.getGeolocationUsage() == WrtDB::SETTINGS_TYPE_ALWAYS_ASK, "GeolocationUsage - wrong value"); + RUNNER_ASSERT_MSG(dao.getWebNotificationUsage() == WrtDB::SETTINGS_TYPE_OFF, "WebNotificationUsage - wrong value"); + RUNNER_ASSERT_MSG(dao.getWebDatabaseUsage() == WrtDB::SETTINGS_TYPE_ALWAYS_ASK, "WebDatabaseUsage - wrong value"); + RUNNER_ASSERT_MSG(dao.getFileSystemUsage() == WrtDB::SETTINGS_TYPE_OFF, "FileSystemUsage - wrong value"); + + dao.setFileSystemUsage(WrtDB::SETTINGS_TYPE_ON); + RUNNER_ASSERT_MSG(dao.getSecurityPopupUsage() == WrtDB::SETTINGS_TYPE_OFF, "SecurityPopupUsage - wrong value"); + RUNNER_ASSERT_MSG(dao.getGeolocationUsage() == WrtDB::SETTINGS_TYPE_ALWAYS_ASK, "GeolocationUsage - wrong value"); + RUNNER_ASSERT_MSG(dao.getWebNotificationUsage() == WrtDB::SETTINGS_TYPE_OFF, "WebNotificationUsage - wrong value"); + RUNNER_ASSERT_MSG(dao.getWebDatabaseUsage() == WrtDB::SETTINGS_TYPE_ALWAYS_ASK, "WebDatabaseUsage - wrong value"); + RUNNER_ASSERT_MSG(dao.getFileSystemUsage() == WrtDB::SETTINGS_TYPE_ON, "FileSystemUsage - wrong value"); +} + +/* +Name: widget_dao_test_register_widget_win_modes +Description: Tests registeration of window modes +Expected: all modes should be returned from dao +*/ +RUNNER_TEST(widget_dao_test_register_widget_win_modes) +{ + WacSecurityMock sec; + std::set modes; + modes.insert(DPL::FromUTF8String("full")); + modes.insert(DPL::FromUTF8String("window")); + + WidgetRegisterInfo regInfo; + + FOREACH(it, modes) + regInfo.configInfo.windowModes.insert(*it); + + WidgetPkgName pkgname = REGISTER_WIDGET(regInfo, sec); + + WidgetDAO dao(pkgname); + std::list wins = dao.getWindowModes(); + RUNNER_ASSERT_MSG(modes.size() == wins.size(), + "wrong number of window modes"); + FOREACH(it, wins) + RUNNER_ASSERT(modes.find(*it) != modes.end()); +} + +/* +Name: widget_dao_test_register_widget_warp_info +Description: Tests registeration of access info iris +Expected: all access info iris should be returned from dao +*/ +RUNNER_TEST(widget_dao_test_register_widget_warp_info) +{ + WacSecurityMock sec; + ConfigParserData::AccessInfoSet orig; + orig.insert(ConfigParserData::AccessInfo(DPL::FromUTF8String("iri1"), + true)); + orig.insert(ConfigParserData::AccessInfo(DPL::FromUTF8String("iri2"), + false)); + orig.insert(ConfigParserData::AccessInfo(DPL::FromUTF8String("iri3"), + true)); + + WidgetRegisterInfo regInfo; + FOREACH(it, orig) + regInfo.configInfo.accessInfoSet.insert(*it); + + WidgetPkgName pkgname = REGISTER_WIDGET(regInfo, sec); + + WidgetDAO dao(pkgname); + + WidgetAccessInfoList out; + dao.getWidgetAccessInfo(out); + RUNNER_ASSERT_MSG(out.size() == orig.size(), + "wrong number of access info elem"); + FOREACH(it, out){ + ConfigParserData::AccessInfo tmp(it->strIRI,it->bSubDomains); + RUNNER_ASSERT(orig.find(tmp) != orig.end()); + } +} + +/* +Name: widget_dao_test_register_widget_certificates +Description: Tests registeration of widget certificates +Expected: all certificates should be returned from dao + and should contain inserted data +*/ +RUNNER_TEST(widget_dao_test_register_widget_certificates) +{ + WacSecurityMock sec; + WidgetRegisterInfo regInfo; + + WidgetCertificateData cert; + cert.owner = WidgetCertificateData::AUTHOR; + cert.type = WidgetCertificateData::ROOT; + cert.chainId = 1; + cert.strMD5Fingerprint = "md5"; + cert.strSHA1Fingerprint = "sha1"; + cert.strCommonName = DPL::FromUTF8String("common name"); + + WidgetCertificateDataList& certListRef = sec.getCertificateListRef(); + certListRef.push_back(cert); + + // register widget + WidgetPkgName pkgname = REGISTER_WIDGET(regInfo, sec); + + WidgetDAO dao(pkgname); + + // certificates + WidgetCertificateDataList recList = dao.getCertificateDataList(); + RUNNER_ASSERT(recList.size() == certListRef.size()); + + auto recListIt = recList.begin(); + auto certListIt = certListRef.begin(); + for(;recListIt != recList.end() && certListIt != certListRef.end(); + ++recListIt,++certListIt) + { + RUNNER_ASSERT(recListIt->chainId == certListIt->chainId); + RUNNER_ASSERT(recListIt->owner == certListIt->owner); + RUNNER_ASSERT(recListIt->strCommonName == certListIt->strCommonName); + RUNNER_ASSERT(recListIt->strMD5Fingerprint == + certListIt->strMD5Fingerprint); + RUNNER_ASSERT(recListIt->strSHA1Fingerprint == + certListIt->strSHA1Fingerprint); + RUNNER_ASSERT(recListIt->type == certListIt->type); + } + + // fingerprints + RUNNER_ASSERT(dao.getKeyFingerprints(WidgetCertificateData::DISTRIBUTOR, + WidgetCertificateData::ENDENTITY).empty()); + RUNNER_ASSERT(dao.getKeyFingerprints(WidgetCertificateData::AUTHOR, + WidgetCertificateData::ENDENTITY).empty()); + RUNNER_ASSERT(dao.getKeyFingerprints(WidgetCertificateData::DISTRIBUTOR, + WidgetCertificateData::ROOT).empty()); + + FingerPrintList fingerprints = dao.getKeyFingerprints( + WidgetCertificateData::AUTHOR, + WidgetCertificateData::ROOT); + + RUNNER_ASSERT(fingerprints.size() == certListRef.size()*2); + FOREACH(it, certListRef) + { + auto md5 = std::find(fingerprints.begin(), + fingerprints.end(), + it->strMD5Fingerprint); + RUNNER_ASSERT(md5 != fingerprints.end()); + + auto sha = std::find(fingerprints.begin(), + fingerprints.end(), + it->strSHA1Fingerprint); + RUNNER_ASSERT(sha != fingerprints.end()); + } + + // common names + RUNNER_ASSERT(dao.getKeyCommonNameList(WidgetCertificateData::DISTRIBUTOR, + WidgetCertificateData::ENDENTITY).empty()); + RUNNER_ASSERT(dao.getKeyCommonNameList(WidgetCertificateData::AUTHOR, + WidgetCertificateData::ENDENTITY).empty()); + RUNNER_ASSERT(dao.getKeyCommonNameList(WidgetCertificateData::DISTRIBUTOR, + WidgetCertificateData::ROOT).empty()); + + FingerPrintList commonNames = dao.getKeyCommonNameList( + WidgetCertificateData::AUTHOR, + WidgetCertificateData::ROOT); + + RUNNER_ASSERT(commonNames.size() == certListRef.size()); + FOREACH(it, certListRef) + { + auto cn = std::find(commonNames.begin(), + commonNames.end(), + DPL::ToUTF8String(it->strCommonName)); + RUNNER_ASSERT(cn != commonNames.end()); + } +} + +/* +Name: widget_dao_test_is_widget_installed +Description: Tests checking if widgets are installed +Expected: installed widgets should be stated as installed +*/ +RUNNER_TEST(widget_dao_test_is_widget_installed) +{ + RUNNER_ASSERT(WidgetDAO::isWidgetInstalled(L"tizenid201")); + + WacSecurityMock sec; + WidgetRegisterInfo regInfo; + + WidgetPkgName pkgname = REGISTER_WIDGET(regInfo, sec); + + RUNNER_ASSERT(WidgetDAO::isWidgetInstalled(pkgname)); +} + +/* +Name: widget_dao_test_unregister_widget +Description: Tests unregistering widgets +Expected: widget register informations should be successfully removed +*/ +RUNNER_TEST(widget_dao_test_unregister_widget) +{ + WacSecurityMock sec; + WidgetHandleList handles = WidgetDAO::getHandleList(); + + WidgetRegisterInfo regInfo; + + WidgetPkgName pkgname = REGISTER_WIDGET(regInfo, sec); + + WidgetDAO::unregisterWidget(pkgname); + + RUNNER_ASSERT_MSG(handles.size() == WidgetDAO::getHandleList().size(), + "Widget unregister failed"); +} + +/* +Name: widget_dao_test_register_or_update_widget +Description: Tests reregistering widgets +Expected: widget should be successfully replaced +*/ +RUNNER_TEST(widget_dao_test_register_or_update_widget) +{ + WacSecurityMock sec; + + WidgetRegisterInfo regInfo; + regInfo.configInfo.version = L"1.0"; + regInfo.configInfo.authorName = L"AAA"; + + WidgetRegisterInfo regInfo2; + regInfo2.configInfo.version = L"1.1"; + regInfo2.configInfo.authorName = L"BBB"; + + WrtDB::WidgetPkgName pkgname(L"abcdefghij"); + + //first installation + WidgetDAO::registerWidget(pkgname, regInfo, sec); + RUNNER_ASSERT_MSG(WidgetDAO::isWidgetInstalled(pkgname), "Widget is not registered"); + + //success full update + WidgetDAO::registerOrUpdateWidget(pkgname, regInfo2, sec); + RUNNER_ASSERT_MSG(WidgetDAO::isWidgetInstalled(pkgname), "Widget is not reregistered"); + WidgetDAO dao(pkgname); + RUNNER_ASSERT_MSG(*dao.getVersion() == L"1.1", "Data widget was not updated"); + RUNNER_ASSERT_MSG(*dao.getAuthorName() == L"BBB", "Data widget was not updated"); + + WidgetDAO::unregisterWidget(pkgname); +} + +/* +Name: widget_dao_test_get_widget_pkgname_list +Description: Tests getPkgnameList API for backendlib +Expected: For all position in database should be returned one item in list +*/ +RUNNER_TEST(widget_dao_test_get_widget_pkgname_list) +{ + WidgetPkgNameList_TEMPORARY_API pkgnames = WidgetDAO::getPkgnameList_TEMPORARY_API(); + RUNNER_ASSERT(pkgnames.size() >= 3); +} + +/* +Name: widget_dao_test_get_widget_list +Description: Tests getPkgnameList API for backendlib +Expected: For all position in database should be returned one item in list + Those item should contain valid pkgname +*/ +RUNNER_TEST(widget_dao_test_get_widget_list) +{ + WidgetDAOReadOnlyList list = WidgetDAOReadOnly::getWidgetList(); + RUNNER_ASSERT(list.size() >= 3); + RUNNER_ASSERT_MSG(!!list.front(), "widget dao exists"); + WidgetDAOReadOnlyPtr dao = list.front(); +} + +/* +Name: widget_dao_test_get_widget_attributes +Description: Tests returning basic widget attributes by dao +Expected: Attributes should match values inserted into database +*/ +RUNNER_TEST(widget_dao_test_get_widget_attributes) +{ + { + WidgetPkgName pkgname = L"tizenid201"; + WidgetDAO dao(pkgname); + + RUNNER_ASSERT_WHAT_EQUALS_OPTIONAL(dao.getGUID(), "w_id_2000"); + RUNNER_ASSERT_WHAT_EQUALS_OPTIONAL(dao.getVersion(), "1.0.0"); + RUNNER_ASSERT_WHAT_EQUALS_OPTIONAL(dao.getAuthorName(), "a_name_2000"); + RUNNER_ASSERT_WHAT_EQUALS_OPTIONAL(dao.getAuthorEmail(), + "a_email_2000"); + RUNNER_ASSERT_WHAT_EQUALS_OPTIONAL(dao.getAuthorHref(), "a_href_2000"); + RUNNER_ASSERT_WHAT_EQUALS(dao.getBaseFolder(), "basef_2000/"); + RUNNER_ASSERT(dao.getWebkitPluginsRequired() == true); + RUNNER_ASSERT_WHAT_EQUALS_OPTIONAL(dao.getMinimumWacVersion(), "1.0"); + } +} + +/* +Name: widget_dao_test_localization +Description: Tests inserting and returning localization info +Expected: Values inserted into database should match values received from database +*/ +RUNNER_TEST(widget_dao_test_localization) +{ + WacSecurityMock sec; + + // icon + WidgetRegisterInfo regInfo; + ConfigParserData::Icon icon(L"icon1"); + icon.width = 10; + icon.height = 10; + LocaleSet locs; + locs.insert(DPL::FromUTF8String("en")); + locs.insert(DPL::FromUTF8String("pl")); + WidgetRegisterInfo::LocalizedIcon locIcon(icon,locs); + regInfo.localizationData.icons.push_back(locIcon); + + //start file + WidgetRegisterInfo::StartFileProperties prop_en; + prop_en.encoding = DPL::FromUTF8String("encoding_en"); + prop_en.type = DPL::FromUTF8String("type_en"); + + WidgetRegisterInfo::StartFileProperties prop_pl; + prop_pl.encoding = DPL::FromUTF8String("encoding_pl"); + prop_pl.type = DPL::FromUTF8String("type_pl"); + + WidgetRegisterInfo::LocalizedStartFile file; + file.path = DPL::FromUTF8String("path"); + file.propertiesForLocales.insert( + std::make_pair(DPL::FromUTF8String("en"), prop_en)); + file.propertiesForLocales.insert( + std::make_pair(DPL::FromUTF8String("pl"), prop_pl)); + regInfo.localizationData.startFiles.push_back(file); + + // register widget + WidgetPkgName pkgname = REGISTER_WIDGET(regInfo, sec); + + WidgetDAO dao(pkgname); + + // check localized icons + WidgetDAO::WidgetLocalizedIconList locList = dao.getLocalizedIconList(); + RUNNER_ASSERT(locList.size() == locs.size()); + + // non-localized icon + WidgetDAO::WidgetIconList list = dao.getIconList(); + int iconId = list.front().iconId; + + // compare every icon with the origin + auto locsIt = locs.begin(); + auto iconIt = locList.begin(); + for(;locsIt!=locs.end() && iconIt!=locList.end();++locsIt,++iconIt) { + RUNNER_ASSERT(iconIt->appId == dao.getHandle()); + RUNNER_ASSERT(iconIt->iconId == iconId); + RUNNER_ASSERT(iconIt->widgetLocale == *locsIt); + } + + // localized start file list + WidgetDAO::LocalizedStartFileList fList = dao.getLocalizedStartFileList(); + RUNNER_ASSERT(fList.size() == file.propertiesForLocales.size()); + + int startFileId = dao.getStartFileList().front().startFileId; + + FOREACH(it,fList) + { + RUNNER_ASSERT(it->appId == dao.getHandle()); + auto propIt = file.propertiesForLocales.find(it->widgetLocale); + RUNNER_ASSERT(propIt != file.propertiesForLocales.end()); + RUNNER_ASSERT(it->encoding == propIt->second.encoding); + RUNNER_ASSERT(it->type == propIt->second.type); + RUNNER_ASSERT(it->startFileId == startFileId); + } +} + +/* +Name: widget_dao_test_wac_security +Description: Tests inserting and returning wac security information +Expected: Values inserted into database should match values received from database +*/ +RUNNER_TEST(widget_dao_test_wac_security) +{ + WacSecurityMock sec; + WidgetRegisterInfo regInfo; + { + // register widget + WidgetPkgName pkgname = REGISTER_WIDGET(regInfo, sec); + WidgetDAO dao(pkgname); + + RUNNER_ASSERT(!dao.isDistributorSigned()); + RUNNER_ASSERT(!dao.isRecognized()); + RUNNER_ASSERT(!dao.isWacSigned()); + } + sec.setDistributorSigned(true); + sec.setRecognized(true); + sec.setWacSigned(true); + { + // register widget + WidgetPkgName pkgname = REGISTER_WIDGET(regInfo, sec); + WidgetDAO dao(pkgname); + + RUNNER_ASSERT(dao.isDistributorSigned()); + RUNNER_ASSERT(dao.isRecognized()); + RUNNER_ASSERT(dao.isWacSigned()); + } +} + +#undef RUNNER_ASSERT_WHAT_EQUALS diff --git a/tests/dao/tests_dao.cpp b/tests/dao/tests_dao.cpp new file mode 100644 index 0000000..5d0422f --- /dev/null +++ b/tests/dao/tests_dao.cpp @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file tests_plugin_dao.cpp + * @author Pawel Sikorski (p.sikorski@samsung.com) + * @version 1.0 + * @brief This file contains tests for plugin dao class. + */ + +#include +#include +#include +#include + +int main (int argc, char *argv[]) +{ + int ret = system("/usr/bin/wrt_dao_tests_prepare_db.sh start"); + if (ret != 0) { + LogError("Preparation script has return error: " << ret + << ". Quitting"); + return -1; + } + + WrtDB::WrtDatabase::attachToThreadRW(); + CustomHandlerDB::Interface::attachDatabaseRW(); + + LogInfo("Starting tests"); + int status = DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, argv); + + CustomHandlerDB::Interface::detachDatabase(); + WrtDB::WrtDatabase::detachFromThread(); + + ret = system("/usr/bin/wrt_dao_tests_prepare_db.sh stop"); + if (ret != 0) { + LogError("Finalization script has return error: " << ret); + return -1; + } + return status; +} diff --git a/tests/dao/wrt_dao_tests_prepare_db.sh b/tests/dao/wrt_dao_tests_prepare_db.sh new file mode 100755 index 0000000..4f989f0 --- /dev/null +++ b/tests/dao/wrt_dao_tests_prepare_db.sh @@ -0,0 +1,129 @@ +#!/bin/sh +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +WRT_DB=/opt/dbspace/.wrt.db +WRT_DB_BCK=/tmp/wrt.db_backup + +if [ "x$1" == "xstart" ]; then + echo start; + cp $WRT_DB $WRT_DB_BCK + wrt_commons_create_clean_db.sh; + + #simple plugins + INS_MIN_PLUGINPROP="insert into PluginProperties(PluginPropertiesId, InstallationState, PluginLibraryName" + INS_ALL_PLUGINPROP="insert into PluginProperties(PluginPropertiesId, InstallationState, PluginLibraryName, PluginLibraryPath)" + INS_PLUGIN_OBJECTS="insert into PluginImplementedObjects(PluginObject, PluginPropertiesId)" + + sqlite3 $WRT_DB "${INS_MIN_PLUGINPROP}) VALUES(1, 1, 'plugin1')"; + sqlite3 $WRT_DB "${INS_MIN_PLUGINPROP}, PluginLibraryPath) VALUES(2, 1, 'plugin2', 'path_to_plugin2')"; + sqlite3 $WRT_DB "${INS_MIN_PLUGINPROP}) VALUES(3, 1, 'plugin3')"; + sqlite3 $WRT_DB "${INS_ALL_PLUGINPROP} VALUES(4, 1, 'p4', 'path_to_p4')"; + sqlite3 $WRT_DB "${INS_ALL_PLUGINPROP} VALUES(5, 1, 'p5', 'path_to_p5')"; + + #plugin dependendencies + #sqlite3 $WRT_DB "${INS_PLUGIN_OBJECTS} VALUES(1, )"; + sqlite3 $WRT_DB "${INS_PLUGIN_OBJECTS} VALUES('', 2)"; + sqlite3 $WRT_DB "${INS_PLUGIN_OBJECTS} VALUES('Plugin_3_Object_A', 3)"; + sqlite3 $WRT_DB "${INS_PLUGIN_OBJECTS} VALUES('Plugin_4_Object_A', 4)"; + sqlite3 $WRT_DB "${INS_PLUGIN_OBJECTS} VALUES('Plugin_4_Object_B', 4)"; + sqlite3 $WRT_DB "${INS_PLUGIN_OBJECTS} VALUES('Plugin_4_Object_C', 4)"; + sqlite3 $WRT_DB "${INS_PLUGIN_OBJECTS} VALUES('Plugin_5_Object_A', 5)"; + + + #simple features + INS_ALL_FEATURESLIST="insert into FeaturesList(FeatureUUID, FeatureName, PluginPropertiesId)" + sqlite3 $WRT_DB "${INS_ALL_FEATURESLIST} VALUES(1, 'feature1', 1)"; + sqlite3 $WRT_DB "${INS_ALL_FEATURESLIST} VALUES(2, 'feature2', 4)"; + sqlite3 $WRT_DB "${INS_ALL_FEATURESLIST} VALUES(3, 'feature3', 4)"; + sqlite3 $WRT_DB "${INS_ALL_FEATURESLIST} VALUES(4, 'feature4', 4)"; + + #device capabilities + INS_ALL_DEVICECAPS="insert into DeviceCapabilities(DeviceCapID, DeviceCapName, DeviceCapDefaultValue)" + sqlite3 $WRT_DB "${INS_ALL_DEVICECAPS} VALUES(1, 'devicecap1', 1)"; + sqlite3 $WRT_DB "${INS_ALL_DEVICECAPS} VALUES(2, 'devicecap2', 2)"; + sqlite3 $WRT_DB "${INS_ALL_DEVICECAPS} VALUES(3, 'devicecap3', 3)"; + sqlite3 $WRT_DB "${INS_ALL_DEVICECAPS} VALUES(4, 'devicecap4', 4)"; + + #Widgets + INS_ALL_WIDGETEXT="insert into WidgetExtendedInfo(app_id, share_href, signature_type)" + INS_ALL_WIDGET="insert into WidgetInfo(app_id, widget_id, widget_version, widget_width, widget_height, author_name, author_email, author_href, base_folder, webkit_plugins_required, recognized, wac_signed, distributor_signed, min_version, pkgname)" + INS_ALL_WIDGET_LOC="insert into LocalizedWidgetInfo(app_id, widget_locale, widget_name, widget_shortname, widget_description, widget_license, widget_license_file, widget_license_href)" + INS_ALL_WIDGET_ICONS="insert into WidgetIcon(app_id, icon_src, icon_width, icon_height)" + INS_ALL_WIDGET_LOC_ICONS="insert into WidgetLocalizedIcon(app_id, icon_id, widget_locale)" + INS_ALL_WIDGET_STARTFILE="insert into WidgetStartFile(app_id, src)" + INS_ALL_WIDGET_LOC_STARTFILE="insert into WidgetLocalizedStartFile(app_id, start_file_id, widget_locale, type, encoding)" + INS_ALL_WIDGET_DEFPREF="insert into WidgetDefaultPreference(app_id, key_name, key_value, readonly)" + INS_ALL_WIDGET_PREF="insert into WidgetPreference(pkgname, key_name, key_value, readonly)" + INS_ALL_WIDGET_FEATURE="insert into WidgetFeature(app_id, name, required)" + INS_ALL_WIDGET_FEATURE_PARAM="insert into FeatureParam(widget_feature_id, name, value)" + INS_ALL_WIDGET_WINMODES="insert into WidgetWindowModes(app_id, window_mode)" + INS_ALL_WIDGET_WARP="insert into WidgetWARPInfo(app_id, iri, subdomain_access)" + INS_ALL_WIDGET_CERT="insert into WidgetCertificateFingerprint(app_id, owner, chainid, type, md5_fingerprint, sha1_fingerprint, common_name)" + INS_ALL_WIDGET_POWDERLEV="insert into PowderLevels(app_id, category, level)" + INS_ALL_WIDGET_POWDERLEV_CONT="insert into PowderLevelContexts(levelid, context)" + + + sqlite3 $WRT_DB "${INS_ALL_WIDGET} VALUES(2000, 'w_id_2000', '1.0.0', 100, 200, 'a_name_2000', 'a_email_2000', 'a_href_2000', 'basef_2000', 1, 1, 1, 1, '1.0', 'tizenid201')"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET} VALUES(2001, 'w_id_2001', '2.0.0', 100, 200, 'a_name_2001', 'a_email_2001', 'a_href_2001', 'basef_2001', 1, 1, 1, 1, '0.5', 'tizenid202')"; + sqlite3 $WRT_DB "insert into WidgetInfo(app_id, back_supported, pkgname) VALUES(2002, 0, 'tizenid203')"; + sqlite3 $WRT_DB "insert into WidgetInfo(app_id, back_supported, pkgname) VALUES(2003, 0, 'tizenid204')"; # for properties tests + + sqlite3 $WRT_DB "${INS_ALL_WIDGETEXT} VALUES(2000, 'share_href_2000', 0)"; + sqlite3 $WRT_DB "${INS_ALL_WIDGETEXT} VALUES(2001, 'share_href_2001', 0)"; + sqlite3 $WRT_DB "insert into WidgetExtendedInfo(app_id) VALUES(2002)"; + sqlite3 $WRT_DB "insert into WidgetExtendedInfo(app_id) VALUES(2003)"; + + sqlite3 $WRT_DB "${INS_ALL_WIDGET_LOC} VALUES(2000, 'en', 'w_name_2000_en', 'w_shortname_2000_en', 'w_desc_2000_en', 'w_lic_2000_en', 'w_licf_2000_en', 'w_lic_href_2000_en')"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_LOC} VALUES(2000, 'pl', 'w_name_2000_pl', 'w_shortname_2000_pl', 'w_desc_2000_pl', 'w_lic_2000_pl', 'w_licf_2000_pl', 'w_lic_href_2000_pl')"; + sqlite3 $WRT_DB "insert into LocalizedWidgetInfo(app_id, widget_locale) VALUES(2002, 'en')"; + sqlite3 $WRT_DB "insert into LocalizedWidgetInfo(app_id, widget_locale) VALUES(2003, 'en')"; + + sqlite3 $WRT_DB "${INS_ALL_WIDGET_ICONS} VALUES(2000, 'icon_src_2000', 50, 50)"; + sqlite3 $WRT_DB "insert into WidgetIcon(app_id, icon_src) VALUES(2002, 'icon_src_2002')"; + + sqlite3 $WRT_DB "${INS_ALL_WIDGET_LOC_ICONS} VALUES(2000, 1, 'en')"; + + sqlite3 $WRT_DB "${INS_ALL_WIDGET_STARTFILE} VALUES(2000, 'start_file_2000')"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_STARTFILE} VALUES(2001, 'start_file_2001')"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_STARTFILE} VALUES(2002, 'start_file_2002')"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_STARTFILE} VALUES(2003, 'start_file_2003')"; + + sqlite3 $WRT_DB "${INS_ALL_WIDGET_LOC_STARTFILE} VALUES(2000, 1, 'en', '', '')"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_LOC_STARTFILE} VALUES(2001, 2, 'en', '', '')"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_LOC_STARTFILE} VALUES(2002, 3, 'en', '', '')"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_LOC_STARTFILE} VALUES(2003, 4, 'en', '', '')"; + + #widget properties + sqlite3 $WRT_DB "${INS_ALL_WIDGET_PREF} VALUES('tizenid201', 'key1_for_2000', 'value_for_key1_2000', 0)"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_PREF} VALUES('tizenid201', 'key2_for_2000', 'value_for_key2_2000', 0)"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_PREF} VALUES('tizenid202', 'key1_for_2001', 'value1_for_key_2001', 1)"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_PREF} VALUES('tizenid203', 'key1_for_2002', 'value1_for_key_2002', 0)"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_PREF} VALUES('tizenid203', 'key2_for_2002', 'value2_for_key_2002', 1)"; + + #create if not exists and fix autoincrement value + sqlite3 $WRT_DB "INSERT INTO WidgetInfo(pkgname) VALUES('temp')"; + sqlite3 $WRT_DB "DELETE FROM WidgetInfo WHERE pkgname = 'temp'"; + sqlite3 $WRT_DB "UPDATE sqlite_sequence SET seq = 2004 WHERE name = 'WidgetInfo'"; + + exit $? + +elif [ "x$1" == "xstop" ]; then + echo stop; + cp $WRT_DB_BCK $WRT_DB + exit $? +else + exit 1 +fi diff --git a/tests/dpl/CMakeLists.txt b/tests/dpl/CMakeLists.txt new file mode 100644 index 0000000..b2348aa --- /dev/null +++ b/tests/dpl/CMakeLists.txt @@ -0,0 +1,28 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# @file CMakeLists.txt +# @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) +# @version 1.0 +# @brief +# + +SET(TESTS_DPL_DIR "${TESTS_DIR}/dpl") + +ADD_SUBDIRECTORY(core) +ADD_SUBDIRECTORY(db) +ADD_SUBDIRECTORY(dbus) +ADD_SUBDIRECTORY(event) +#ADD_SUBDIRECTORY(localization) TODO localization mockups need to be fixed +ADD_SUBDIRECTORY(utils) diff --git a/tests/dpl/README b/tests/dpl/README new file mode 100644 index 0000000..6641953 --- /dev/null +++ b/tests/dpl/README @@ -0,0 +1,13 @@ +Unit tests for dpl library functionality. +There are 6 binaries: dpl-dbus-test-service, dpl-tests-core, dpl-tests-db, +dpl-tests-dbus, dpl-tests-event, dpl-tests-utils. +All binaries are using our test framework - it allows to use different types of +output. Text output shows results on console - green passed. +To run: +1. Install wrt-extra on target +2. Run for f in /usr/bin/dpl-tests-*; do $f --output=text; done + +Automatic: YES +Included in Daily Build: YES (http://build01.sprc.samsung.pl/browse/LINUXNGWAP-INT) +Included in Gerrit Builds: YES (http://build01.sprc.samsung.pl/browse/LINUXNGWAP-GERRIT) +Number of test cases: 151 \ No newline at end of file diff --git a/tests/dpl/core/.swp b/tests/dpl/core/.swp new file mode 100644 index 0000000000000000000000000000000000000000..e25a05b48227470164a5b546ec0bb135d5e190aa GIT binary patch literal 12288 zcmeI%ze>YE90%~Ln~N6p0qP%cEBzygqv+yLaH;EY&0U&<^m1MGIE2;hgAC*2+v2bf#IC7bX!#rnCWd7AgCEw=r#0 kM9HK-7KA2Ms=C4l59(+mT%Vs7stBq=N~iLC)IBEn07(a^&j0`b literal 0 HcmV?d00001 diff --git a/tests/dpl/core/CMakeLists.txt b/tests/dpl/core/CMakeLists.txt new file mode 100644 index 0000000..48d2c93 --- /dev/null +++ b/tests/dpl/core/CMakeLists.txt @@ -0,0 +1,61 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# @file CMakeLists.txt +# @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) +# @version 1.0 +# @brief +# + +# +# Test files +# +# Define all DPL tests sources. +# Runner is responsible for runnint it all and +# generating proper output files +# + +SET(TARGET_NAME "dpl-tests-core") + +# Set DPL tests sources +SET(DPL_TESTS_CORE_SOURCES + ${TESTS_DPL_DIR}/core/main.cpp + ${TESTS_DPL_DIR}/core/test_address.cpp + ${TESTS_DPL_DIR}/core/test_binary_queue.cpp + ${TESTS_DPL_DIR}/core/test_foreach.cpp + ${TESTS_DPL_DIR}/core/test_fast_delegate.cpp + ${TESTS_DPL_DIR}/core/test_log_unhandled_exception.cpp + ${TESTS_DPL_DIR}/core/test_once.cpp + ${TESTS_DPL_DIR}/core/test_serialization.cpp + ${TESTS_DPL_DIR}/core/test_scoped_array.cpp + ${TESTS_DPL_DIR}/core/test_scoped_close.cpp + ${TESTS_DPL_DIR}/core/test_scoped_fclose.cpp + ${TESTS_DPL_DIR}/core/test_scoped_free.cpp + ${TESTS_DPL_DIR}/core/test_scoped_ptr.cpp + ${TESTS_DPL_DIR}/core/test_semaphore.cpp + ${TESTS_DPL_DIR}/core/test_shared_ptr.cpp + ${TESTS_DPL_DIR}/core/test_string.cpp + ${TESTS_DPL_DIR}/core/test_thread.cpp + ${TESTS_DPL_DIR}/core/test_type_list.cpp + ${TESTS_DPL_DIR}/core/test_zip_input.cpp +) + +WRT_TEST_ADD_INTERNAL_DEPENDENCIES(${TARGET_NAME} ${TARGET_DPL_EFL}) +WRT_TEST_BUILD(${TARGET_NAME} ${DPL_TESTS_CORE_SOURCES}) +WRT_TEST_INSTALL(${TARGET_NAME}) + +INSTALL(FILES + ${TESTS_DPL_DIR}/core/data/sample.zip + DESTINATION /opt/share/wrt/wrt-commons/tests/core + ) diff --git a/tests/dpl/core/DESCRIPTION b/tests/dpl/core/DESCRIPTION new file mode 100644 index 0000000..48e5394 --- /dev/null +++ b/tests/dpl/core/DESCRIPTION @@ -0,0 +1,2 @@ +!!!options!!! stop +Test code diff --git a/tests/dpl/core/data/sample.zip b/tests/dpl/core/data/sample.zip new file mode 100644 index 0000000000000000000000000000000000000000..02417d89316a2de5eb658decfa83dc60e366c8c7 GIT binary patch literal 174 zcmWIWW@h1H0D-h9e>XlTKgobc3Fe?N{`GRn11vdjD z%L`_pLJ(1sT3iy~&B!FjjLRemkOd5kK)j?8#6mWg6=E)$nE~FcY#^14Ko|g|JwO}= E0Bw;T(f|Me literal 0 HcmV?d00001 diff --git a/tests/dpl/core/main.cpp b/tests/dpl/core/main.cpp new file mode 100644 index 0000000..42ffe3a --- /dev/null +++ b/tests/dpl/core/main.cpp @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file main.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of main + */ +#include + +int main(int argc, char *argv[]) +{ + return DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, argv); +} + diff --git a/tests/dpl/core/test_address.cpp b/tests/dpl/core/test_address.cpp new file mode 100644 index 0000000..7aff2df --- /dev/null +++ b/tests/dpl/core/test_address.cpp @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file test_address.cpp + * @author Tomasz Swierczek (t.swierczek@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of test address + */ +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL) + +RUNNER_TEST(Address_InitialEmpty) +{ + DPL::Address address; + RUNNER_ASSERT(address.ToString() == ":0"); +} + +RUNNER_TEST(Address_InitialAddress) +{ + DPL::Address address("www.sample.com"); + RUNNER_ASSERT(address.ToString() == "www.sample.com:0"); +} + +RUNNER_TEST(Address_InitialAddressPort) +{ + DPL::Address address("www.somewhere.com", 8080); + RUNNER_ASSERT(address.ToString() == "www.somewhere.com:8080"); +} + +RUNNER_TEST(Address_Getters) +{ + DPL::Address address("www.somewhere.com", 8080); + RUNNER_ASSERT(address.GetAddress() == "www.somewhere.com"); + RUNNER_ASSERT(address.GetPort() == 8080); +} diff --git a/tests/dpl/core/test_binary_queue.cpp b/tests/dpl/core/test_binary_queue.cpp new file mode 100644 index 0000000..d955aab --- /dev/null +++ b/tests/dpl/core/test_binary_queue.cpp @@ -0,0 +1,357 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file test_binary_queue.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of test binary queue + */ +#include +#include +RUNNER_TEST_GROUP_INIT(DPL) + +inline std::string BinaryQueueToString(const DPL::BinaryQueue &queue) +{ + char *buffer = new char[queue.Size()]; + queue.Flatten(buffer, queue.Size()); + std::string result = std::string(buffer, buffer + queue.Size()); + delete [] buffer; + return result; +} + +RUNNER_TEST(BinaryQueue_InitialEmpty) +{ + DPL::BinaryQueue queue; + RUNNER_ASSERT(queue.Empty() == true); +} + +RUNNER_TEST(BinaryQueue_InitialSize) +{ + DPL::BinaryQueue queue; + RUNNER_ASSERT(queue.Size() == 0); +} + +RUNNER_TEST(BinaryQueue_InitialCopy) +{ + DPL::BinaryQueue queue; + DPL::BinaryQueue copy = queue; + + RUNNER_ASSERT(copy.Size() == 0); +} + +RUNNER_TEST(BinaryQueue_InitialConsumeZero) +{ + DPL::BinaryQueue queue; + queue.Consume(0); +} + +RUNNER_TEST(BinaryQueue_InitialFlattenConsumeZero) +{ + DPL::BinaryQueue queue; + queue.FlattenConsume(NULL, 0); +} + +RUNNER_TEST(BinaryQueue_InitialFlattenZero) +{ + DPL::BinaryQueue queue; + queue.Flatten(NULL, 0); +} + +RUNNER_TEST(BinaryQueue_InitialConsumeOne) +{ + DPL::BinaryQueue queue; + + Try + { + queue.Consume(1); + } + Catch (DPL::BinaryQueue::Exception::OutOfData) + { + return; + } + + RUNNER_FAIL; +} + +RUNNER_TEST(BinaryQueue_InitialFlattenConsumeOne) +{ + DPL::BinaryQueue queue; + + Try + { + char data; + queue.FlattenConsume(&data, 1); + } + Catch (DPL::BinaryQueue::Exception::OutOfData) + { + return; + } + + RUNNER_FAIL; +} + +RUNNER_TEST(BinaryQueue_InitialFlattenOne) +{ + DPL::BinaryQueue queue; + + Try + { + char data; + queue.Flatten(&data, 1); + } + Catch (DPL::BinaryQueue::Exception::OutOfData) + { + return; + } + + RUNNER_FAIL; +} + +RUNNER_TEST(BinaryQueue_ZeroCopyFrom) +{ + DPL::BinaryQueue queue; + DPL::BinaryQueue copy; + + copy.AppendCopyFrom(queue); + RUNNER_ASSERT(queue.Empty()); +} + +RUNNER_TEST(BinaryQueue_ZeroMoveFrom) +{ + DPL::BinaryQueue queue; + DPL::BinaryQueue copy; + + copy.AppendMoveFrom(queue); + RUNNER_ASSERT(queue.Empty()); +} + +RUNNER_TEST(BinaryQueue_ZeroCopyTo) +{ + DPL::BinaryQueue queue; + DPL::BinaryQueue copy; + + queue.AppendCopyTo(copy); + RUNNER_ASSERT(queue.Empty()); +} + +RUNNER_TEST(BinaryQueue_InsertSingleCharacters) +{ + DPL::BinaryQueue queue; + + queue.AppendCopy("a", 1); + queue.AppendCopy("b", 1); + queue.AppendCopy("c", 1); + queue.AppendCopy("d", 1); + + RUNNER_ASSERT(queue.Size() == 4); + RUNNER_ASSERT(BinaryQueueToString(queue) == "abcd"); +} + +RUNNER_TEST(BinaryQueue_Consume) +{ + DPL::BinaryQueue queue; + + queue.AppendCopy("abcd", 4); + queue.AppendCopy("ef", 2); + + RUNNER_ASSERT(queue.Size() == 6); + + queue.Consume(1); + RUNNER_ASSERT(queue.Size() == 5); + RUNNER_ASSERT(BinaryQueueToString(queue) == "bcdef"); + + queue.Consume(2); + RUNNER_ASSERT(queue.Size() == 3); + RUNNER_ASSERT(BinaryQueueToString(queue) == "def"); + + queue.Consume(1); + RUNNER_ASSERT(queue.Size() == 2); + RUNNER_ASSERT(BinaryQueueToString(queue) == "ef"); + + queue.Consume(2); + RUNNER_ASSERT(queue.Size() == 0); + RUNNER_ASSERT(BinaryQueueToString(queue) == ""); +} + +RUNNER_TEST(BinaryQueue_Flatten) +{ + DPL::BinaryQueue queue; + + queue.AppendCopy("abcd", 4); + queue.AppendCopy("ef", 2); + queue.AppendCopy("g", 1); + + RUNNER_ASSERT(queue.Size() == 7); + + RUNNER_ASSERT(BinaryQueueToString(queue) == "abcdefg"); +} + +RUNNER_TEST(BinaryQueue_FlattenConsume) +{ + DPL::BinaryQueue queue; + + queue.AppendCopy("abcd", 4); + queue.AppendCopy("ef", 2); + + RUNNER_ASSERT(queue.Size() == 6); + + char buffer[7] = { '\0' }; + queue.FlattenConsume(buffer, 3); + + RUNNER_ASSERT(queue.Size() == 3); + RUNNER_ASSERT(BinaryQueueToString(queue) == "def"); +} + +RUNNER_TEST(BinaryQueue_AppendCopyFrom) +{ + DPL::BinaryQueue queue; + DPL::BinaryQueue copy; + + queue.AppendCopy("abcd", 4); + queue.AppendCopy("ef", 2); + + copy.AppendCopyFrom(queue); + + RUNNER_ASSERT(queue.Size() == 6); + RUNNER_ASSERT(copy.Size() == 6); + RUNNER_ASSERT(BinaryQueueToString(queue) == "abcdef"); + RUNNER_ASSERT(BinaryQueueToString(copy) == "abcdef"); +} + +RUNNER_TEST(BinaryQueue_AppendCopyTo) +{ + DPL::BinaryQueue queue; + DPL::BinaryQueue copy; + + queue.AppendCopy("abcd", 4); + queue.AppendCopy("ef", 2); + + queue.AppendCopyTo(copy); + + RUNNER_ASSERT(queue.Size() == 6); + RUNNER_ASSERT(copy.Size() == 6); + RUNNER_ASSERT(BinaryQueueToString(queue) == "abcdef"); + RUNNER_ASSERT(BinaryQueueToString(copy) == "abcdef"); +} + +RUNNER_TEST(BinaryQueue_AppendMoveFrom) +{ + DPL::BinaryQueue queue; + DPL::BinaryQueue copy; + + queue.AppendCopy("abcd", 4); + queue.AppendCopy("ef", 2); + + copy.AppendMoveFrom(queue); + + RUNNER_ASSERT(queue.Size() == 0); + RUNNER_ASSERT(copy.Size() == 6); + RUNNER_ASSERT(BinaryQueueToString(queue) == ""); + RUNNER_ASSERT(BinaryQueueToString(copy) == "abcdef"); +} + +RUNNER_TEST(BinaryQueue_AppendMoveTo) +{ + DPL::BinaryQueue queue; + DPL::BinaryQueue copy; + + queue.AppendCopy("abcd", 4); + queue.AppendCopy("ef", 2); + + queue.AppendMoveTo(copy); + + RUNNER_ASSERT(queue.Size() == 0); + RUNNER_ASSERT(copy.Size() == 6); + RUNNER_ASSERT(BinaryQueueToString(queue) == ""); + RUNNER_ASSERT(BinaryQueueToString(copy) == "abcdef"); +} + +class Visitor + : public DPL::BinaryQueue::BucketVisitor +{ +private: + int m_index; + +public: + Visitor() + : m_index(0) + { + } + + virtual void OnVisitBucket(const void *buffer, size_t bufferSize) + { + const char *str = static_cast(buffer); + + if (m_index == 0) + { + RUNNER_ASSERT(bufferSize == 4); + RUNNER_ASSERT(str[0] == 'a'); + RUNNER_ASSERT(str[1] == 'b'); + RUNNER_ASSERT(str[2] == 'c'); + RUNNER_ASSERT(str[3] == 'd'); + } + else if (m_index == 1) + { + RUNNER_ASSERT(bufferSize == 2); + RUNNER_ASSERT(str[0] == 'e'); + RUNNER_ASSERT(str[1] == 'f'); + } + else + { + RUNNER_FAIL; + } + + ++m_index; + } +}; + +RUNNER_TEST(BinaryQueue_Visitor) +{ + DPL::BinaryQueue queue; + + queue.AppendCopy("abcd", 4); + queue.AppendCopy("ef", 2); + + Visitor visitor; + queue.VisitBuckets(&visitor); +} + +RUNNER_TEST(BinaryQueue_AbstracInputRead) +{ + DPL::BinaryQueue queue; + + queue.AppendCopy("abcd", 4); + + queue.Read(0); + + RUNNER_ASSERT(BinaryQueueToString(*queue.Read(1).get()) == "a"); + RUNNER_ASSERT(BinaryQueueToString(*queue.Read(2).get()) == "bc"); + RUNNER_ASSERT(BinaryQueueToString(*queue.Read(1).get()) == "d"); + + RUNNER_ASSERT(queue.Size() == 0); +} + +RUNNER_TEST(BinaryQueue_AbstracOutputWrite) +{ + DPL::BinaryQueue queue; + queue.AppendCopy("abcd", 4); + + DPL::BinaryQueue stream; + + stream.Write(queue, 4); + + RUNNER_ASSERT(BinaryQueueToString(*queue.Read(4).get()) == "abcd"); +} diff --git a/tests/dpl/core/test_fast_delegate.cpp b/tests/dpl/core/test_fast_delegate.cpp new file mode 100644 index 0000000..947cbe5 --- /dev/null +++ b/tests/dpl/core/test_fast_delegate.cpp @@ -0,0 +1,248 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file test_fast_delegate.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of fast delegate tests. + */ +#include +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL) + +// Sample copied and adopted from +// http://www.codeproject.com/KB/cpp/FastDelegate.aspx +// +// Demonstrate the syntax for FastDelegates. +// -Don Clugston, May 2004. +// It's a really boring example, but it shows the most important cases. +// Declare some functions of varying complexity... +void SimpleStaticFunction(int num, const char *str); +void SimpleStaticFunction(int num, const char *str) +{ + LogDebug("In SimpleStaticFunction. Num=" << num << ", str =" << str); +} + +void SimpleVoidFunction(); +void SimpleVoidFunction() +{ + LogDebug("In SimpleVoidFunction with no parameters."); +} + +class CBaseClass +{ +protected: + const char *m_name; + +public: + CBaseClass(const char *name) + : m_name(name) + { + } + + virtual ~CBaseClass() + { + } + + void SimpleMemberFunction(int num, const char *str) + { + LogDebug("In SimpleMemberFunction in " << m_name << ". Num=" + << num << ", str = " << str); + } + + int SimpleMemberFunctionReturnsInt(int num, const char *str) + { + LogDebug("In SimpleMemberFunctionReturnsInt in " << m_name << ". Num=" + << num << ", str = " << str); + return -1; + } + + void ConstMemberFunction(int num, const char *str) const + { + LogDebug("In ConstMemberFunction in " << m_name << ". Num=" + << num << ", str = " << str); + } + + virtual void SimpleVirtualFunction(int num, const char *str) + { + LogDebug("In SimpleVirtualFunction in " << m_name << ". Num=" + << num << ", str = " << str); + } + + static void StaticMemberFunction(int num, const char *str) + { + LogDebug("In StaticMemberFunction Num=" + << num << ", str = " << str); + } +}; + +class COtherClass +{ + double rubbish; // to ensure this class has non-zero size. + +public: + virtual ~COtherClass() + { + } + + virtual void UnusedVirtualFunction(void) + { + } + virtual void TrickyVirtualFunction(int num, const char *str) = 0; +}; + +class VeryBigClass +{ + int letsMakeThingsComplicated[400]; +}; + +// This declaration ensures that we get a convoluted class heirarchy. +class CDerivedClass + : public VeryBigClass, + virtual public COtherClass, + virtual public CBaseClass +{ + double m_somemember[8]; + +public: + CDerivedClass() + : CBaseClass("Base of Derived") + { + m_somemember[0] = 1.2345; + } + + void SimpleDerivedFunction(int num, const char *str) + { + LogDebug("In SimpleDerivedFunction Num=" + << num << ", str = " << str); + } + + virtual void AnotherUnusedVirtualFunction(int num, const char *str) + { + LogDebug("In AnotherUnusedVirtualFunction in " << m_name << ". Num=" + << num << ", str = " << str); + } + + virtual void TrickyVirtualFunction(int num, const char *str) + { + LogDebug("In TrickyVirtualFunction in " << m_name << ". Num=" + << num << ", str = " << str); + } +}; + +RUNNER_TEST(FastDelegate_Test) +{ + // Delegates with up to 8 parameters are supported. + // Here's the case for a void function. + // We declare a delegate and attach it to SimpleVoidFunction() + DPL::FastDelegate0<> noparameterdelegate(&SimpleVoidFunction); + + // invoke the delegate - this calls SimpleVoidFunction() + noparameterdelegate(); + + LogDebug("-- Examples using two-parameter delegates (int, char *) --"); + + // By default, the return value is void. + typedef DPL::FastDelegate2 MyDelegate; + + // If you want to have a non-void return value, put it at the end. + typedef DPL::FastDelegate2 IntMyDelegate; + + + MyDelegate funclist[12]; // delegates are initialized to empty + CBaseClass a("Base A"); + CBaseClass b("Base B"); + CDerivedClass d; + CDerivedClass c; + + IntMyDelegate newdeleg; + newdeleg = DPL::MakeDelegate(&a, + &CBaseClass::SimpleMemberFunctionReturnsInt); + + // Binding a simple member function + funclist[0].bind(&a, &CBaseClass::SimpleMemberFunction); + + // You can also bind static (free) functions + funclist[1].bind(&SimpleStaticFunction); + + // and static member functions + funclist[2].bind(&CBaseClass::StaticMemberFunction); + + // and const member functions (these only need a const class pointer). + funclist[3].bind((const CBaseClass *) &a, + &CBaseClass::ConstMemberFunction); + + funclist[4].bind(&a, &CBaseClass::ConstMemberFunction); + + // and virtual member functions + funclist[5].bind(&b, &CBaseClass::SimpleVirtualFunction); + + // You can also use the = operator. For static functions, a fastdelegate + // looks identical to a simple function pointer. + funclist[6] = &CBaseClass::StaticMemberFunction; + + // The weird rule about the class of derived member function pointers + // is avoided. For MSVC, you can use &CDerivedClass::SimpleVirtualFunction + // here, but DMC will complain. Note that as well as .bind(), you can also + // use the MakeDelegate() global function. + funclist[7] = DPL::MakeDelegate(&d, &CBaseClass::SimpleVirtualFunction); + + // The worst case is an abstract virtual function of a virtually-derived + // class with at least one non-virtual base class. This is a VERY obscure + // situation, which you're unlikely to encounter in the real world. + // FastDelegate versions prior to 1.3 had problems with this case on VC6. + // Now, it works without problems on all compilers. + funclist[8].bind(&c, &CDerivedClass::TrickyVirtualFunction); + + // BUT... in such cases you should be using the base class as an + // interface, anyway. + funclist[9].bind(&c, &COtherClass::TrickyVirtualFunction); + + // Calling a function that was first declared in the derived class is + // straightforward + funclist[10] = DPL::MakeDelegate(&c, &CDerivedClass::SimpleDerivedFunction); + + // You can also bind directly using the constructor + MyDelegate dg(&b, &CBaseClass::SimpleVirtualFunction); + + const char *msg = "Looking for equal delegate"; + + for (int i = 0; i < 12; i++) + { + LogDebug(i << ":"); + + // The == and != operators are provided + // Note that they work even for inline functions. + if (funclist[i] == dg) + { + msg = "Found equal delegate"; + } + + // operator ! can be used to test for an empty delegate + // You can also use the .empty() member function. + if (!funclist[i]) + { + LogDebug("Delegate is empty"); + } + else + { + // Invocation generates optimal assembly code. + funclist[i](i, msg); + } + } +} diff --git a/tests/dpl/core/test_foreach.cpp b/tests/dpl/core/test_foreach.cpp new file mode 100644 index 0000000..f698081 --- /dev/null +++ b/tests/dpl/core/test_foreach.cpp @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file test_foreach.cpp + * @author Bartosz Janiak (b.janiak@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of foreach tests. + */ + +#include +#include +#include +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL) + +static const size_t testContainerSize = 1024; + +template +void VerifyForeach(Container& container) +{ + size_t i = 0; + FOREACH(it, container) + { + RUNNER_ASSERT(*it == i); + i++; + } + RUNNER_ASSERT(i == container.size()); +} + +#define VERIFY_FOREACH(container) \ + { \ + size_t i = 0; \ + FOREACH(it, container) \ + { \ + RUNNER_ASSERT(*it == i); \ + i++; \ + } \ + } + +static size_t numberOfCallsToTemporaryList = 0; +std::list temporaryList(); +std::list temporaryList() +{ + ++numberOfCallsToTemporaryList; + std::list list; + for (size_t i = 0 ; i < testContainerSize ; i++) + { + list.push_back(i); + } + return list; +} + +static size_t numberOfCallsToTemporaryVector = 0; +std::vector temporaryVector(); +std::vector temporaryVector() +{ + ++numberOfCallsToTemporaryVector; + std::vector vector; + for (size_t i = 0 ; i < testContainerSize ; i++) + { + vector.push_back(i); + } + return vector; +} + +static size_t numberOfCallsToTemporarySet = 0; +std::set temporarySet(); +std::set temporarySet() +{ + ++numberOfCallsToTemporarySet; + std::set set; + for (size_t i = 0 ; i < testContainerSize ; i++) + { + set.insert(i); + } + return set; +} + +RUNNER_TEST(Foreach_std_containers) +{ + std::vector vector; + std::list list; + std::set set; + + for (size_t i = 0 ; i < testContainerSize ; i++) + { + vector.push_back(i); + list.push_back(i); + set.insert(i); + } + + VerifyForeach(vector); + VerifyForeach(list); + VerifyForeach(set); + + VERIFY_FOREACH(temporaryList()); + VERIFY_FOREACH(temporaryVector()); + VERIFY_FOREACH(temporarySet()); + + RUNNER_ASSERT(numberOfCallsToTemporaryList == 1); + RUNNER_ASSERT(numberOfCallsToTemporaryVector == 1); + RUNNER_ASSERT(numberOfCallsToTemporarySet == 1); +} diff --git a/tests/dpl/core/test_log_unhandled_exception.cpp b/tests/dpl/core/test_log_unhandled_exception.cpp new file mode 100644 index 0000000..0403c28 --- /dev/null +++ b/tests/dpl/core/test_log_unhandled_exception.cpp @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file test_log_unhandled_exception.cpp + * @author Pawel Sikorski (p.marcinkiew@samsung.com) + * @version 1.0 + * @brief + */ +#include +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL) + +class MyException +{ +}; + +class MyDPLException +{ +public: + DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) + DECLARE_EXCEPTION_TYPE(Base, MyException) +}; + +class MySTDException + : public std::exception +{ +public: + virtual const char* what()const throw() { return "my std exception occurred";} +}; + +RUNNER_TEST(Log_Unknown_Exception) +{ + UNHANDLED_EXCEPTION_HANDLER_BEGIN + { +// throw MyException(); + } + UNHANDLED_EXCEPTION_HANDLER_END + RUNNER_ASSERT(true); +} + +RUNNER_TEST(Log_DPL_Exception) +{ + UNHANDLED_EXCEPTION_HANDLER_BEGIN + { +// Throw(MyDPLException::MyException); + } + UNHANDLED_EXCEPTION_HANDLER_END + RUNNER_ASSERT(true); +} + +RUNNER_TEST(Log_STD_Exception) +{ + UNHANDLED_EXCEPTION_HANDLER_BEGIN + { +// throw MySTDException(); + } + UNHANDLED_EXCEPTION_HANDLER_END + RUNNER_ASSERT(true); +} diff --git a/tests/dpl/core/test_once.cpp b/tests/dpl/core/test_once.cpp new file mode 100644 index 0000000..b278f83 --- /dev/null +++ b/tests/dpl/core/test_once.cpp @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file test_once.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of once tests + */ +#include +#include +#include +#include +#include +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL) + +namespace // anonymous +{ +gint g_counter; + +void Delegate() +{ + ++g_counter; +} +} // namespace anonymous + +RUNNER_TEST(Once_DoubleCall) +{ + g_counter = 0; + + DPL::Once once; + + once.Call(&Delegate); + once.Call(&Delegate); + + RUNNER_ASSERT_MSG(g_counter == 1, "Counter value is: " << g_counter); +} + +class MyThread + : public DPL::Thread +{ +protected: + virtual int ThreadEntry() + { + DPL::WaitForSingleHandle(m_event->GetHandle()); + m_once->Call(DPL::Once::Delegate(this, &MyThread::Call)); + return 0; + } + + void Call() + { + ++*m_atom; + } + +public: + MyThread(DPL::WaitableEvent *event, DPL::Once *once, DPL::Atomic *atom) + : m_event(event), m_once(once), m_atom(atom) + { + } + +private: + DPL::WaitableEvent *m_event; + DPL::Once *m_once; + DPL::Atomic *m_atom; +}; + +RUNNER_TEST(Once_MultiThreadCall) +{ + const size_t NUM_THREADS = 20; + typedef std::shared_ptr ThreadPtr; + + ThreadPtr threads[NUM_THREADS]; + DPL::WaitableEvent event; + DPL::Once once; + DPL::Atomic atom; + + for (size_t i = 0; i< NUM_THREADS; ++i) + { + (threads[i] = ThreadPtr(new MyThread(&event, &once, &atom)))->Run(); + } + + event.Signal(); + + for (size_t i = 0; i< NUM_THREADS; ++i) + threads[i]->Quit(); + + RUNNER_ASSERT_MSG(atom == 1, "Atom value is: " << atom); +} diff --git a/tests/dpl/core/test_scoped_array.cpp b/tests/dpl/core/test_scoped_array.cpp new file mode 100644 index 0000000..58b0603 --- /dev/null +++ b/tests/dpl/core/test_scoped_array.cpp @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file test_scoped_array.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of test scoped array + */ +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL) + +RUNNER_TEST(ScopedArray_Zero) +{ + DPL::ScopedArray array; + + RUNNER_ASSERT(!array); + RUNNER_ASSERT(!!!array); +} + +RUNNER_TEST(ScopedArray_NonZero) +{ + DPL::ScopedArray array(new char[7]); + + RUNNER_ASSERT(array); + RUNNER_ASSERT(!!array); +} + +RUNNER_TEST(ScopedArray_Reset) +{ + DPL::ScopedArray array(new char[7]); + array.Reset(); + + RUNNER_ASSERT(!array); + + array.Reset(new char); + RUNNER_ASSERT(array); +} + +RUNNER_TEST(ScopedArray_ArrayOperator) +{ + DPL::ScopedArray array(new char[7]); + + array[1] = array[2] = 3; + + RUNNER_ASSERT(array[1] == 3); + RUNNER_ASSERT(array[2] == 3); +} diff --git a/tests/dpl/core/test_scoped_close.cpp b/tests/dpl/core/test_scoped_close.cpp new file mode 100644 index 0000000..3549fed --- /dev/null +++ b/tests/dpl/core/test_scoped_close.cpp @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file test_scoped_close.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of test scoped close + */ +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL) + +// DUNNO diff --git a/tests/dpl/core/test_scoped_fclose.cpp b/tests/dpl/core/test_scoped_fclose.cpp new file mode 100644 index 0000000..dbdff95 --- /dev/null +++ b/tests/dpl/core/test_scoped_fclose.cpp @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/*! + * @file test_scoped_fclose.cpp + * @author Piotr Marcinkiewicz (p.marcinkiew@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of test scoped fclose + */ + +#include +#include + +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL) + +namespace +{ +FILE* MakeTmp() +{ + FILE* result = NULL; + do + { + result = tmpfile(); + } while (NULL != result && EINTR == errno); + return result; +} +}//anonymous namespace + +RUNNER_TEST(ScopedFClose_Zero) +{ + DPL::ScopedFClose file; + + RUNNER_ASSERT(!file); + RUNNER_ASSERT(!!!file); +} + +RUNNER_TEST(ScopedFClose_NonZero) +{ + DPL::ScopedFClose file(MakeTmp()); + + RUNNER_ASSERT(file); + RUNNER_ASSERT(!!file); +} + +RUNNER_TEST(ScopedFClose_Reset) +{ + DPL::ScopedFClose file(MakeTmp()); + file.Reset(); + + RUNNER_ASSERT(!file); + + file.Reset(MakeTmp()); + RUNNER_ASSERT(file); +} + diff --git a/tests/dpl/core/test_scoped_free.cpp b/tests/dpl/core/test_scoped_free.cpp new file mode 100644 index 0000000..bc41a5a --- /dev/null +++ b/tests/dpl/core/test_scoped_free.cpp @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file test_scoped_free.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of test scoped free + */ +#include +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL) + +RUNNER_TEST(ScopedFree_Zero) +{ + DPL::ScopedFree free; + + RUNNER_ASSERT(!free); + RUNNER_ASSERT(!!!free); +} + +RUNNER_TEST(ScopedFree_NonZero) +{ + DPL::ScopedFree free(malloc(7)); + + RUNNER_ASSERT(free); + RUNNER_ASSERT(!!free); +} + +RUNNER_TEST(ScopedFree_Reset) +{ + DPL::ScopedFree free(malloc(7)); + free.Reset(); + + RUNNER_ASSERT(!free); + + free.Reset(malloc(8)); + RUNNER_ASSERT(free); +} diff --git a/tests/dpl/core/test_scoped_ptr.cpp b/tests/dpl/core/test_scoped_ptr.cpp new file mode 100644 index 0000000..f3a7237 --- /dev/null +++ b/tests/dpl/core/test_scoped_ptr.cpp @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file test_scoped_ptr.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of test scoped ptr + */ +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL) + +RUNNER_TEST(ScopedPtr_Zero) +{ + DPL::ScopedPtr ptr; + + RUNNER_ASSERT(!ptr); + RUNNER_ASSERT(!!!ptr); +} + +RUNNER_TEST(ScopedPtr_NonZero) +{ + DPL::ScopedPtr ptr(new char(7)); + + RUNNER_ASSERT(ptr); + RUNNER_ASSERT(!!ptr); +} + +RUNNER_TEST(ScopedPtr_Reset) +{ + DPL::ScopedPtr ptr(new char(7)); + ptr.Reset(); + + RUNNER_ASSERT(!ptr); + + ptr.Reset(new char); + RUNNER_ASSERT(ptr); +} + +RUNNER_TEST(ScopedPtr_Operators) +{ + DPL::ScopedPtr ptr(new char(7)); + + RUNNER_ASSERT(*ptr == *ptr.Get()); +} diff --git a/tests/dpl/core/test_semaphore.cpp b/tests/dpl/core/test_semaphore.cpp new file mode 100644 index 0000000..854978e --- /dev/null +++ b/tests/dpl/core/test_semaphore.cpp @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file test_semaphore.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of semaphore tests + */ +#include +#include +#include +#include +#include +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL) + +class SemaphoreThread + : public DPL::Thread +{ + int m_delta; + int m_times; + int *m_value; + std::string m_semaphoreName; + +public: + SemaphoreThread(int delta, + int times, + int *value, + const std::string &semaphoreName) + : m_delta(delta), + m_times(times), + m_value(value), + m_semaphoreName(semaphoreName) + { + } + +protected: + virtual int ThreadEntry() + { + DPL::Semaphore semaphore(m_semaphoreName); + + for (int i = 0; i < m_times; ++i) + { + // Take scoped semaphore lock + DPL::Semaphore::ScopedLock lock(&semaphore); + *m_value += m_delta; + } + + return 0; + } +}; + +RUNNER_TEST(Semaphore_NamedIncrementDecrement) +{ + std::string semaphoreName = + "dpl_test_semaphore_" + + DPL::lexical_cast(std::time(NULL)); + + int value = 0; + SemaphoreThread threadA(-1, 10000, &value, semaphoreName); + SemaphoreThread threadB(+1, 10000, &value, semaphoreName); + + threadA.Run(); + threadB.Run(); + + threadA.Quit(); + threadB.Quit(); + + RUNNER_ASSERT_MSG(value == 0, "Final value is: " << value); +} diff --git a/tests/dpl/core/test_serialization.cpp b/tests/dpl/core/test_serialization.cpp new file mode 100644 index 0000000..8776fc8 --- /dev/null +++ b/tests/dpl/core/test_serialization.cpp @@ -0,0 +1,259 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file test_address.cpp + * @author Tomasz Swierczek (t.swierczek@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of serialization tests + */ + +#include +#include +#include +#include + +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL) + +// test stream class +class BinaryStream : public DPL::IStream { + public: + virtual void Read(size_t num, void * bytes) + { + for (unsigned i = 0; i < num; ++i) { + ((unsigned char*)bytes)[i] = data[i + readPosition]; + } + readPosition += num; + } + virtual void Write(size_t num, const void * bytes) + { + for (unsigned i = 0; i < num; ++i) { + data.push_back(((unsigned char*)bytes)[i]); + } + } + BinaryStream() + { + readPosition = 0; + } + virtual ~BinaryStream(){}; + + private: + std::vector data; + unsigned readPosition; +}; + +//test ISerializable class +class TestClass : public DPL::ISerializable { + public: + TestClass(int val, std::string str1, std::string str2) + { + a = val; + b = str1; + c.push_back(str1); + c.push_back(str2); + c.push_back(str1 + str2); + }; + TestClass(DPL::IStream& stream) + { + DPL::Deserialization::Deserialize(stream,a); + DPL::Deserialization::Deserialize(stream,b); + DPL::Deserialization::Deserialize(stream,c); + }; + virtual void Serialize(DPL::IStream& stream) const + { + DPL::Serialization::Serialize(stream,a); + DPL::Serialization::Serialize(stream,b); + DPL::Serialization::Serialize(stream,c); + } + virtual ~TestClass(){} + virtual bool operator==(const TestClass& other) + { + return (a == other.a && + b == other.b && + c.size() == other.c.size() && + c[0] == other.c[0] && + c[1] == other.c[1] && + c[2] == other.c[2]); + } + private: + int a; + std::string b; + std::vector c; +}; + +RUNNER_TEST(Serialize_primitives) +{ + int a = 1; + bool b = true; + unsigned c = 23; + BinaryStream stream; + DPL::Serialization::Serialize(stream,a); + DPL::Serialization::Serialize(stream,b); + DPL::Serialization::Serialize(stream,c); + int test_int; + DPL::Deserialization::Deserialize(stream,test_int); + RUNNER_ASSERT(test_int == a); + bool test_bool; + DPL::Deserialization::Deserialize(stream,test_bool); + RUNNER_ASSERT(test_bool == b); + unsigned test_unsigned; + DPL::Deserialization::Deserialize(stream,test_unsigned); + RUNNER_ASSERT(test_unsigned == c); +} + +RUNNER_TEST(Serialize_primitive_pointers) +{ + int a = 1; + bool b = true; + unsigned c = 23; + BinaryStream stream; + DPL::Serialization::Serialize(stream,&a); + DPL::Serialization::Serialize(stream,&b); + DPL::Serialization::Serialize(stream,&c); + int* test_int; + DPL::Deserialization::Deserialize(stream,test_int); + RUNNER_ASSERT(test_int != NULL && *test_int == a); + bool* test_bool; + DPL::Deserialization::Deserialize(stream,test_bool); + RUNNER_ASSERT(test_bool != NULL && *test_bool == b); + unsigned* test_unsigned; + DPL::Deserialization::Deserialize(stream,test_unsigned); + RUNNER_ASSERT(test_unsigned != NULL && *test_unsigned == c); + delete test_int; + delete test_bool; + delete test_unsigned; +} + +RUNNER_TEST(Serialize_strings) +{ + std::string str1 = "ALA MA KOTA"; + std::string str2 = "MULTILINE\nTEST"; + BinaryStream stream; + DPL::Serialization::Serialize(stream,str1); + DPL::Serialization::Serialize(stream,str2); + std::string test_str1; + DPL::Deserialization::Deserialize(stream,test_str1); + RUNNER_ASSERT(test_str1 == str1); + std::string test_str2; + DPL::Deserialization::Deserialize(stream,test_str2); + RUNNER_ASSERT(test_str2 == str2); +} + +RUNNER_TEST(Serialize_string_pointers) +{ + std::string str1 = "ALA MA KOTA"; + std::string str2 = "MULTILINE\nTEST"; + BinaryStream stream; + DPL::Serialization::Serialize(stream,&str1); + DPL::Serialization::Serialize(stream,&str2); + std::string* test_str1; + DPL::Deserialization::Deserialize(stream,test_str1); + RUNNER_ASSERT(test_str1 != NULL && *test_str1 == str1); + std::string* test_str2; + DPL::Deserialization::Deserialize(stream,test_str2); + RUNNER_ASSERT(test_str2 != NULL && *test_str2 == str2); + delete test_str1; + delete test_str2; +} + +RUNNER_TEST(Serialize_containers) +{ + std::vector vec; + vec.push_back(134); + vec.push_back(265); + std::list list; + list.push_back(true); + list.push_back(false); + std::pair pair; + pair.first = -23; + pair.second = 1234; + std::map map; + map.insert(std::pair(45, "ALA MA CZARNEGO KOTA")); + map.insert(std::pair(-78, "...A MOZE\nMA\nWIELE LINIJEK")); + BinaryStream stream; + DPL::Serialization::Serialize(stream,vec); + DPL::Serialization::Serialize(stream,list); + DPL::Serialization::Serialize(stream,pair); + DPL::Serialization::Serialize(stream,map); + std::vector test_vec; + DPL::Deserialization::Deserialize(stream,test_vec); + RUNNER_ASSERT(test_vec.size() == vec.size() && + test_vec[0] == vec[0] && test_vec[1] == vec[1]); + std::list test_list; + DPL::Deserialization::Deserialize(stream,test_list); + RUNNER_ASSERT(test_list.size() == list.size() && + test_list.front() == list.front() && + test_list.back() == test_list.back()); + std::pair test_pair; + DPL::Deserialization::Deserialize(stream,test_pair); + RUNNER_ASSERT(test_pair.first == pair.first && + test_pair.second == pair.second); + std::map test_map; + DPL::Deserialization::Deserialize(stream,test_map); + RUNNER_ASSERT(test_map.size() == map.size() && + test_map.at(45) == map.at(45) && + test_map.at(-78) == map.at(-78)); +} + +RUNNER_TEST(Serialize_objects) +{ + TestClass a(123,"ASDGHUADB\n\n5679b^^()*","TEST_STRING"), + b(679,"HUSPIDNSAHDPA","\nASDSADASD\naDSADASD8"); + BinaryStream stream; + DPL::Serialization::Serialize(stream,a); + DPL::Serialization::Serialize(stream,b); + TestClass test_a(0,"",""), test_b(0,"",""); + DPL::Deserialization::Deserialize(stream, test_a); + RUNNER_ASSERT(test_a == a); + DPL::Deserialization::Deserialize(stream, test_b); + RUNNER_ASSERT(test_b == b); +} + +RUNNER_TEST(Serialize_all) +{ + std::map > map; + std::vector vec; + vec.push_back(new TestClass(123,"ASDGHUADB\n\n5679b^^()*","TEST_STRING")); + vec.push_back(new TestClass(679,"HUSPIDNSAHDPA","\nASDSADASD\naDSADASD8")); + map.insert(std::pair >("KEY1",vec)); + map.insert(std::pair >("KEY2",vec)); + BinaryStream stream; + + DPL::Serialization::Serialize(stream, map); + + std::map > test_map; + DPL::Deserialization::Deserialize(stream,test_map); + RUNNER_ASSERT(map.size() == test_map.size()); + std::vector test_vec1,test_vec2; + test_vec1 = map.at("KEY1"); + test_vec2 = test_map.at("KEY1"); + RUNNER_ASSERT(test_vec1.size() == test_vec2.size()); + unsigned i; + for (i = 0; i < test_vec1.size(); ++i) + { + RUNNER_ASSERT((*test_vec1[i]) == (*test_vec2[i])); + } + test_vec1 = map.at("KEY2"); + test_vec2 = test_map.at("KEY2"); + RUNNER_ASSERT(test_vec1.size() == test_vec2.size()); + for (i = 0; i < test_vec1.size(); ++i) + { + RUNNER_ASSERT((*test_vec1[i]) == (*test_vec2[i])); + } +} + diff --git a/tests/dpl/core/test_shared_ptr.cpp b/tests/dpl/core/test_shared_ptr.cpp new file mode 100644 index 0000000..541a333 --- /dev/null +++ b/tests/dpl/core/test_shared_ptr.cpp @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file test_shared_ptr.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of test shared ptr + */ +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL) + +RUNNER_TEST(SharedPtr_Zero) +{ + DPL::SharedPtr ptr; + + RUNNER_ASSERT(!ptr); + RUNNER_ASSERT(!!!ptr); + RUNNER_ASSERT(ptr == DPL::SharedPtr()); +} + +RUNNER_TEST(SharedPtr_NonZero) +{ + DPL::SharedPtr ptr(new char(7)); + + RUNNER_ASSERT(ptr); + RUNNER_ASSERT(!!ptr); + RUNNER_ASSERT(ptr != DPL::SharedPtr()); +} + +RUNNER_TEST(SharedPtr_Copy) +{ + DPL::SharedPtr ptr1(new char(7)); + DPL::SharedPtr ptr2(new char(7)); + + RUNNER_ASSERT(ptr1 != ptr2); + + ptr2 = ptr1; + + RUNNER_ASSERT(ptr1 == ptr2); +} + +RUNNER_TEST(SharedPtr_Reset) +{ + DPL::SharedPtr ptr(new char(7)); + ptr.Reset(); + + RUNNER_ASSERT(!ptr); + + ptr.Reset(new char); + RUNNER_ASSERT(ptr); +} + +RUNNER_TEST(SharedPtr_RefCounting) +{ + DPL::SharedPtr ptr1(new char(7)); + DPL::SharedPtr ptr2; + + ptr2 = ptr1; + + RUNNER_ASSERT(ptr1 == ptr2); + RUNNER_ASSERT(ptr1.GetUseCount() == ptr2.GetUseCount()); + RUNNER_ASSERT(ptr1.GetUseCount() == 2); +} + +RUNNER_TEST(SharedPtr_Operators) +{ + DPL::SharedPtr ptr(new char(7)); + + RUNNER_ASSERT(*ptr == *ptr.Get()); +} diff --git a/tests/dpl/core/test_string.cpp b/tests/dpl/core/test_string.cpp new file mode 100644 index 0000000..dea0a22 --- /dev/null +++ b/tests/dpl/core/test_string.cpp @@ -0,0 +1,384 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file test_string.cpp + * @author Piotr Marcinkiewicz (p.marcinkiew@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of string tests + */ +#include +#include +#include +#include +#include +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL) + +unsigned char GetBaseCode(int index); +unsigned char GetBaseCode(int index) +{ + /* aaaack but it's fast and const should make it shared text page. */ + static const unsigned char pr2six[256] = + { + /* ASCII table */ + 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 62, 64, 64, 64, 63, + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 64, 64, 64, 64, 64, + 64, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 64, 64, 64, 64, 64, + 64, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, + 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64 + }; + return pr2six[index]; +} + + +/* Function adapted from APR library (http://apr.apache.org/) */ +int wbxml_base64_decode(const char *buffer, char **result); +int wbxml_base64_decode(const char *buffer, char **result) +{ + int nbytesdecoded = 0, nprbytes = 0; + const char *bufin = NULL; + char *bufout = NULL; + + if ((buffer == NULL) || (result == NULL)) + return 0; + + /* Initialize output buffer */ + *result = NULL; + + bufin = buffer; + while (GetBaseCode(*(bufin++)) <= 63) {} + + nprbytes = (bufin - buffer) - 1; + nbytesdecoded = ((nprbytes + 3) / 4) * 3; + + /* Malloc result buffer */ + if ((*result = (char*) malloc(nbytesdecoded + 1)) == NULL) + return 0; + memset(*result, nbytesdecoded + 1, 0); + + bufout = *result; + bufin = buffer; + + while (nprbytes > 4) + { + *(bufout++) = (char)(GetBaseCode(*bufin) << 2 | GetBaseCode(bufin[1]) >> 4); + *(bufout++) = (char)(GetBaseCode(bufin[1]) << 4 | GetBaseCode(bufin[2]) >> 2); + *(bufout++) = (char)(GetBaseCode(bufin[2]) << 6 | GetBaseCode(bufin[3])); + bufin += 4; + nprbytes -= 4; + } + + /* Note: (nprbytes == 1) would be an error, so just ingore that case */ + if (nprbytes > 1) + { + *(bufout++) = (char)(GetBaseCode(*bufin) << 2 | GetBaseCode(bufin[1]) >> 4); + } + if (nprbytes > 2) + { + *(bufout++) = (char)(GetBaseCode(bufin[1]) << 4 | GetBaseCode(bufin[2]) >> 2); + } + if (nprbytes > 3) + { + *(bufout++) = (char)(GetBaseCode(bufin[2]) << 6 | GetBaseCode(bufin[3])); + } + + nbytesdecoded -= (4 - nprbytes) & 3; + + return nbytesdecoded; +} + +//#define TEST_CONVERSION(in_string, out_string, buffer_type, function + +const char utf32Encoded[] = +"RDAAAI0wAABvMAAAazAAAHswAAB4MAAAaDAAAAAwAABhMAAAijAAAGwwAACLMAAAkjAAAAAwAACP\ +MAAASzAAAIgwAABfMAAAjDAAAF0wAAAAMAAAZDAAAG0wAABqMAAAiTAAAIAwAAAAMAAARjAAAJAw\ +AABuMAAASjAAAE8wAACEMAAAfjAAAAAwAABRMAAAdTAAAFMwAABIMAAAZjAAAAAwAABCMAAAVTAA\ +AE0wAACGMAAAgTAAAH8wAABXMAAAADAAAJEwAAByMAAAgjAAAFswAABZMAAACgAAANsFAADaBQAA\ +IAAAANQFAADqBQAA6AUAAOEFAADnBQAAIAAAAOAFAADkBQAA5QUAACAAAADiBQAA3AUAACAAAADS\ +BQAA1QUAANYFAADcBQAAIAAAAOcFAADYBQAA3wUAACwAAAAgAAAA6QUAANMFAADXBQAA4wUAACAA\ +AADQBQAA6gUAACAAAADmBQAA0QUAANkFAAAgAAAA3AUAAN4FAADZBQAA3QUAAAoAAACk0AAApMIA\ +AFjHAAAgAAAA4KwAACDHAABwyAAAdKwAAEDHAAAgAAAAhccAACDCAAB8sAAArLkAACAAAADMuQAA\ +mLAAAHzFAAAgAAAAWNUAAOCsAAAgAAAAudIAAMS8AABc1QAAIAAAADCuAAAgwgAAQMcAACAAAABE\ +1QAAlMYAAFjOAAAgAAAASsUAAOSyAAAKAAAAUAAAAGMAAABoAAAAbgAAAAUBAAAHAQAAIAAAAHcA\ +AAAgAAAAdAAAABkBAAAgAAAAQgEAAPMAAABkAAAAegEAACAAAABqAAAAZQAAAHwBAABhAAAAIAAA\ +AGwAAAB1AAAAYgAAACAAAABvAAAAWwEAAG0AAAAgAAAAcwAAAGsAAAByAAAAegAAAHkAAABEAQAA\ +IAAAAGYAAABpAAAAZwAAAC4AAAAKAAAAQgAAAGwAAABvAAAAdwAAAHoAAAB5AAAAIAAAAG4AAABp\ +AAAAZwAAAGgAAAB0AAAALQAAAGYAAAByAAAAdQAAAG0AAABwAAAAcwAAACAAAAB2AAAAZQAAAHgA\ +AAAnAAAAZAAAACAAAABKAAAAYQAAAGMAAABrAAAAIAAAAFEAAAAuAAAACgAAAEYGAAA1BgAAIAAA\ +AC0GAABDBgAASgYAAEUGAAAgAAAARAYAAEcGAAAgAAAAMwYAADEGAAAgAAAAQgYAACcGAAA3BgAA\ +OQYAACAAAABIBgAAMAYAAEgGAAAgAAAANAYAACMGAABGBgAAIAAAADkGAAA4BgAASgYAAEUGAAAg\ +AAAARQYAAEMGAAAqBgAASAYAACgGAAAgAAAAOQYAAEQGAABJBgAAIAAAACsGAABIBgAAKAYAACAA\ +AAAjBgAALgYAADYGAAAxBgAAIAAAAEgGAABFBgAAOgYAAEQGAABBBgAAIAAAACgGAAAsBgAARAYA\ +AC8GAAAgAAAAIwYAADIGAAAxBgAAQgYAACAAAAAKAAAAEgQAACAAAABHBAAAMAQAAEkEAAAwBAAA\ +RQQAACAAAABOBAAAMwQAADAEAAAgAAAANgQAADgEAAA7BAAAIAAAADEEAABLBAAAIAAAAEYEAAA4\ +BAAAQgQAAEAEAABDBAAAQQQAAD8AAAAgAAAAFAQAADAEAAAsAAAAIAAAAD0EAAA+BAAAIAAAAEQE\ +AAAwBAAAOwQAAEwEAABIBAAAOAQAADIEAABLBAAAOQQAACAAAABNBAAAOgQAADcEAAA1BAAAPAQA\ +AD8EAAA7BAAATwQAAEAEAAAhAAAACgAAAKQDAACsAwAAxwMAALkDAADDAwAAxAMAALcDAAAgAAAA\ +sQMAALsDAADOAwAAwAMAALcDAAC+AwAAIAAAALIDAACxAwAAxgMAAK4DAADCAwAAIAAAAMgDAAC3\ +AwAAvAMAAK0DAAC9AwAAtwMAACAAAACzAwAAtwMAACwAAAAgAAAAtAMAAMEDAACxAwAAwwMAALoD\ +AAC1AwAAuwMAAK8DAAC2AwAAtQMAALkDAAAgAAAAxQMAAMADAACtAwAAwQMAACAAAAC9AwAAyQMA\ +ALgDAADBAwAAvwMAAM0DAAAgAAAAugMAAMUDAAC9AwAAzAMAAMIDAAAKAAAAVgAAAGkAAABjAAAA\ +dAAAAG8AAAByAAAAIAAAAGoAAABhAAAAZwAAAHQAAAAgAAAAegAAAHcAAAD2AAAAbAAAAGYAAAAg\ +AAAAQgAAAG8AAAB4AAAAawAAAOQAAABtAAAAcAAAAGYAAABlAAAAcgAAACAAAABxAAAAdQAAAGUA\ +AAByAAAAIAAAAPwAAABiAAAAZQAAAHIAAAAgAAAAZAAAAGUAAABuAAAAIAAAAGcAAAByAAAAbwAA\ +AN8AAABlAAAAbgAAACAAAABTAAAAeQAAAGwAAAB0AAAAZQAAAHIAAAAgAAAARAAAAGUAAABpAAAA\ +YwAAAGgAAAAKAAAAlokAAM6RAAAhcQAAUJYAAONeAAAM/wAAl3oAABZZAAAJZwAAzYUAAClZAAAK\ +AAAACgAAAAAAAAA="; + +const char utf8Encoded[] = +"44GE44KN44Gv44Gr44G744G444Go44CA44Gh44KK44Gs44KL44KS44CA44KP44GL44KI44Gf44KM\ +44Gd44CA44Gk44Gt44Gq44KJ44KA44CA44GG44KQ44Gu44GK44GP44KE44G+44CA44GR44G144GT\ +44GI44Gm44CA44GC44GV44GN44KG44KB44G/44GX44CA44KR44Gy44KC44Gb44GZCteb15og15TX\ +qteo16HXpyDXoNek16Ug16LXnCDXkteV15bXnCDXp9eY158sINep15PXl9ejINeQ16og16bXkdeZ\ +INec157XmdedCu2CpOyKpOydmCDqs6DsnKDsobDqsbTsnYAg7J6F7Iig64G866asIOunjOuCmOyV\ +vCDtlZjqs6Ag7Yq567OE7ZWcIOq4sOyIoOydgCDtlYTsmpTsuZgg7JWK64ukClBjaG7EhcSHIHcg\ +dMSZIMWCw7NkxbogamXFvGEgbHViIG/Fm20gc2tyennFhCBmaWcuCkJsb3d6eSBuaWdodC1mcnVt\ +cHMgdmV4J2QgSmFjayBRLgrZhti1INit2YPZitmFINmE2Ycg2LPYsSDZgtin2LfYuSDZiNiw2Ygg\ +2LTYo9mGINi52LjZitmFINmF2YPYqtmI2Kgg2LnZhNmJINir2YjYqCDYo9iu2LbYsSDZiNmF2LrZ\ +hNmBINio2KzZhNivINij2LLYsdmCIArQkiDRh9Cw0YnQsNGFINGO0LPQsCDQttC40Lsg0LHRiyDR\ +htC40YLRgNGD0YE/INCU0LAsINC90L4g0YTQsNC70YzRiNC40LLRi9C5INGN0LrQt9C10LzQv9C7\ +0Y/RgCEKzqTOrM+HzrnPg8+EzrcgzrHOu8+Oz4DOt86+IM6yzrHPhs6uz4Igz4jOt868zq3Ovc63\ +IM6zzrcsIM60z4HOsc+DzrrOtc67zq/Ots61zrkgz4XPgM6tz4Egzr3Pic64z4HOv8+NIM66z4XO\ +vc+Mz4IKVmljdG9yIGphZ3QgenfDtmxmIEJveGvDpG1wZmVyIHF1ZXIgw7xiZXIgZGVuIGdyb8Of\ +ZW4gU3lsdGVyIERlaWNoCuimlumHjueEoemZkOW7o++8jOeql+WkluacieiXjeWkqQoKAA=="; + + + + +const char asciiEncodedIso1[] = +"ISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZ\ +WltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fgA="; + +const char asciiEncodedUtf32[] = +"IQAAACIAAAAjAAAAJAAAACUAAAAmAAAAJwAAACgAAAApAAAAKgAAACsAAAAsAAAALQAAAC4AAAAv\ +AAAAMAAAADEAAAAyAAAAMwAAADQAAAA1AAAANgAAADcAAAA4AAAAOQAAADoAAAA7AAAAPAAAAD0A\ +AAA+AAAAPwAAAEAAAABBAAAAQgAAAEMAAABEAAAARQAAAEYAAABHAAAASAAAAEkAAABKAAAASwAA\ +AEwAAABNAAAATgAAAE8AAABQAAAAUQAAAFIAAABTAAAAVAAAAFUAAABWAAAAVwAAAFgAAABZAAAA\ +WgAAAFsAAABcAAAAXQAAAF4AAABfAAAAYAAAAGEAAABiAAAAYwAAAGQAAABlAAAAZgAAAGcAAABo\ +AAAAaQAAAGoAAABrAAAAbAAAAG0AAABuAAAAbwAAAHAAAABxAAAAcgAAAHMAAAB0AAAAdQAAAHYA\ +AAB3AAAAeAAAAHkAAAB6AAAAewAAAHwAAAB9AAAAfgAAAAAAAAA="; + + +RUNNER_TEST(String_ConverterFromASCII) +{ + char* inStr = NULL; + int inSize = wbxml_base64_decode(asciiEncodedIso1, &inStr); + RUNNER_ASSERT(inSize > 0); + RUNNER_ASSERT(NULL != inStr); + inStr[inSize] = '\0'; + { + DPL::String asciiString = DPL::FromASCIIString(inStr); + + std::string result = DPL::ToUTF8String(asciiString); + + RUNNER_ASSERT(strlen(inStr) == result.size()); + + RUNNER_ASSERT(0 == memcmp(inStr, result.c_str(), result.size())); + } + + free(inStr); +} + +RUNNER_TEST(String_ConverterFromUTF8) +{ + char* inStr = NULL; + int inSize = wbxml_base64_decode(asciiEncodedIso1, &inStr); + RUNNER_ASSERT(inSize > 0); + RUNNER_ASSERT(NULL != inStr); + { + DPL::String asciiString = DPL::FromUTF8String(inStr); + + std::string result = DPL::ToUTF8String(asciiString); + + RUNNER_ASSERT(strlen(inStr) == result.size()); + + RUNNER_ASSERT(0 == memcmp(inStr, result.c_str(), result.size())); + } + + free(inStr); +} + +RUNNER_TEST(String_ConverterFromUTF32) +{ + wchar_t* inStr = NULL; + int inSize = wbxml_base64_decode(utf32Encoded, reinterpret_cast(&inStr)); + RUNNER_ASSERT(inSize > 0); + RUNNER_ASSERT(NULL != inStr); + char* outStr = NULL; + int outSize = wbxml_base64_decode(utf8Encoded, &outStr); + RUNNER_ASSERT(outSize > 0); + RUNNER_ASSERT(NULL != outStr); + outStr[outSize] = '\0'; + { + DPL::String utfString = DPL::FromUTF32String(inStr); + std::string result = DPL::ToUTF8String(utfString); + + RUNNER_ASSERT(strlen(outStr) == result.size()); + RUNNER_ASSERT(0 == memcmp(outStr, result.c_str(), result.size())); + + + RUNNER_ASSERT(inSize / sizeof(wchar_t) - 1 == utfString.size()); + RUNNER_ASSERT(0 == memcmp(inStr, &(utfString[0]), utfString.size() * sizeof(wchar_t))); + + } + + free(inStr); +} + +template +void String_TokenizeReal(const DelimiterType& delimiter) +{ + DPL::String str(L".##..abc.#."); + std::vector tokens; + DPL::Tokenize(str, delimiter, std::back_inserter(tokens)); + + std::vector expectedTokens; + for ( int i = 0 ; i < 5 ; i++ ) + expectedTokens.push_back(L""); + expectedTokens.push_back(L"abc"); + for ( int i = 0 ; i < 3 ; i++ ) + expectedTokens.push_back(L""); + + RUNNER_ASSERT(expectedTokens == tokens); + tokens.clear(); + expectedTokens.clear(); + + DPL::Tokenize(str, delimiter, std::back_inserter(tokens), true); + expectedTokens.push_back(L"abc"); + RUNNER_ASSERT(expectedTokens == tokens); +} + +RUNNER_TEST(String_Tokenize) +{ + String_TokenizeReal(L"#."); + String_TokenizeReal(L".#"); + String_TokenizeReal(L".....####.###.."); + String_TokenizeReal(DPL::String(L".#")); + + std::vector tokens; + DPL::Tokenize(std::string("abc.def"), '.', std::back_inserter(tokens)); + std::vector expectedTokens; + expectedTokens.push_back("abc"); + expectedTokens.push_back("def"); + + RUNNER_ASSERT(tokens == expectedTokens); +} + +template +void TestInStreams( + std::basic_string argumentInString, + std::basic_string argumentResultString) +{ + typedef std::basic_string + String; + std::basic_istringstream + istream(argumentInString); + int intValue = 0; + double doubleValue = 0.0; + float floatValue = 0.0; + String stringValue; + + istream >> intValue; + RUNNER_ASSERT(!istream.fail()); + istream >> doubleValue; + RUNNER_ASSERT(!istream.fail()); + istream >> floatValue; + RUNNER_ASSERT(!istream.fail()); + istream >> stringValue; + RUNNER_ASSERT(!istream.fail()); + + RUNNER_ASSERT(1 == intValue); + RUNNER_ASSERT(fabs(1.1f - doubleValue) < 0.00001); + RUNNER_ASSERT(fabs(1.1f - floatValue) < 0.00001); + RUNNER_ASSERT(argumentResultString == stringValue); +} + +template +void TestOutStreams( + std::basic_string argumentInString, + std::basic_string argumentResultString) +{ + typedef std::basic_string + String; + + std::basic_ostringstream + ostream; + + int intValue = 1; + double doubleValue = 1.1; + float floatValue = 1.1f; + String stringValue = argumentInString; + + ostream << intValue; + RUNNER_ASSERT(!ostream.fail()); + ostream << doubleValue; + RUNNER_ASSERT(!ostream.fail()); + ostream << floatValue; + RUNNER_ASSERT(!ostream.fail()); + ostream << stringValue; + RUNNER_ASSERT(!ostream.fail()); + + RUNNER_ASSERT(ostream.str() == argumentResultString); +} + +RUNNER_TEST(String_Streams) +{ + TestInStreams >("1 1.1 1.1 test", "test"); + TestInStreams >(L"1 1.1 1.1 test", L"test"); + TestInStreams(L"1 1.1 1.1 test", L"test"); + TestOutStreams >("test", "11.11.1test"); + TestOutStreams >(L"test", L"11.11.1test"); + TestOutStreams(L"test", L"11.11.1test"); +} + +RUNNER_TEST(String_CompareCaseSensitive) +{ + RUNNER_ASSERT( + DPL::StringCompare( + DPL::FromUTF32String(L"Ala Makota ma żołądkówkę"), + DPL::FromUTF32String(L"Ala Makota ma żołądkówkę")) == 0); +} + +RUNNER_TEST(String_CompareCaseInsensitive) +{ + RUNNER_ASSERT( + DPL::StringCompare( + DPL::FromUTF32String(L"Ala Makota ma żołądkówkę"), + DPL::FromUTF32String(L"AlA MakOTA ma Å»oŁąDKÓwkę"), + true) == 0); +} + diff --git a/tests/dpl/core/test_thread.cpp b/tests/dpl/core/test_thread.cpp new file mode 100644 index 0000000..202d468 --- /dev/null +++ b/tests/dpl/core/test_thread.cpp @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file test_thread.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of thread tests + */ +#include +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL) + +bool g_wasFooDeleted; + +class Foo +{ +public: + int id; + Foo(int i=0): id(i) + { + LogInfo("Foo: ctor: " << id); + } + + ~Foo() + { + LogInfo("Foo: dtor: " << id); + g_wasFooDeleted = true; + } + + void Bar() + { + LogInfo("Foo: bar"); + } +}; + +typedef DPL::ThreadLocalVariable TlsFoo; +TlsFoo g_foo; + +class FooThread + : public DPL::Thread +{ +protected: + virtual int ThreadEntry() + { + LogInfo("In thread"); + + RUNNER_ASSERT(!g_foo); + RUNNER_ASSERT(g_foo.IsNull()); + + g_foo = Foo(); + g_foo->Bar(); + + return 0; + } +}; + +RUNNER_TEST(Thread_ThreadLocalVariable_FooDeletion) +{ + static TlsFoo staticFooForMain; + staticFooForMain = Foo(1); + + TlsFoo fooForMain; + fooForMain = Foo(2); + + RUNNER_ASSERT(!g_foo); + RUNNER_ASSERT(g_foo.IsNull()); + + g_wasFooDeleted = false; + + FooThread thread1; + thread1.Run(); + thread1.Quit(); + + RUNNER_ASSERT(!g_foo); + RUNNER_ASSERT(g_foo.IsNull()); + + RUNNER_ASSERT(g_wasFooDeleted == true); + + FooThread thread2; + thread2.Run(); + thread2.Quit(); + + RUNNER_ASSERT(!g_foo); + RUNNER_ASSERT(g_foo.IsNull()); +} diff --git a/tests/dpl/core/test_type_list.cpp b/tests/dpl/core/test_type_list.cpp new file mode 100644 index 0000000..98167f3 --- /dev/null +++ b/tests/dpl/core/test_type_list.cpp @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file test_type_list.cpp + * @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) + * @version 0.1 + * @brief + */ + +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL) + +RUNNER_TEST(TypeList_TypeCount) +{ + typedef DPL::TypeListDecl::Type TestTypeList1; + typedef DPL::TypeListDecl::Type TestTypeList2; + typedef DPL::TypeListDecl<>::Type TestTypeList3; + typedef DPL::TypeList TestTypeList4; + + RUNNER_ASSERT(TestTypeList1::Size == 3); + RUNNER_ASSERT(TestTypeList2::Size == 1); + RUNNER_ASSERT(TestTypeList3::Size == 0); + RUNNER_ASSERT(TestTypeList4::Size == 4); + + RUNNER_ASSERT(TestTypeList4::Tail::Tail::Size == 2); +} diff --git a/tests/dpl/core/test_zip_input.cpp b/tests/dpl/core/test_zip_input.cpp new file mode 100644 index 0000000..5e5b9b4 --- /dev/null +++ b/tests/dpl/core/test_zip_input.cpp @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file test_zip_input.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of zip input tests + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +const char* PATH_NO_FILE = "/opt/share/wrt/wrt-commons/tests/core/no_such_file"; +const char* PATH_ARCHIVE = "/opt/share/wrt/wrt-commons/tests/core/sample.zip"; +const char* ARCHIVED_FILE = "sample.txt"; +} + +RUNNER_TEST_GROUP_INIT(DPL) + +RUNNER_TEST(ZipInput_OpenFailed) +{ + bool opened = true; + + Try + { + DPL::ZipInput zip(PATH_NO_FILE); + (void)zip; + } + Catch(DPL::ZipInput::Exception::OpenFailed) + { + opened = false; + } + + RUNNER_ASSERT(opened == false); +} + +RUNNER_TEST(ZipInput_OpenFile) +{ + DPL::ZipInput zip(PATH_ARCHIVE); + + FOREACH(iter, zip) + { + LogDebug("---------"); + LogDebug("FileInfo: "); +#define FIELD(X) LogDebug(#X ": " << iter->X) + FIELD(name); + FIELD(comment); + FIELD(compressedSize); + FIELD(uncompressedSize); +#undef FIELD + } +} + +RUNNER_TEST(ZipInput_UnzipSingleFile) +{ + DPL::ZipInput zip(PATH_ARCHIVE); + DPL::ZipInput::File *file = zip.OpenFile(ARCHIVED_FILE); + DPL::AbstractWaitableInputAdapter fileAdapter(file); + DPL::BinaryQueue buffer; + DPL::AbstractWaitableOutputAdapter bufferAdapter(&buffer); + + DPL::Copy(&fileAdapter, &bufferAdapter); + + DPL::ScopedArray data(new char[buffer.Size() + 1]); + buffer.Flatten(data.Get(), buffer.Size()); + data[buffer.Size()] = '\0'; + + RUNNER_ASSERT(std::string(data.Get()) == "test"); +} diff --git a/tests/dpl/db/CMakeLists.txt b/tests/dpl/db/CMakeLists.txt new file mode 100644 index 0000000..f4b5c22 --- /dev/null +++ b/tests/dpl/db/CMakeLists.txt @@ -0,0 +1,49 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# @file CMakeLists.txt +# @author Lukasz Marek (l.marek@samsung.com) +# @version 1.0 +# @brief +# + +# +# Test files +# +# Define all DPL tests sources. +# Runner is responsible for runnint it all and +# generating proper output files +# + +SET(TARGET_NAME "dpl-tests-db") + +# Set DPL tests sources +SET(DPL_TESTS_DB_SOURCES + ${TESTS_DPL_DIR}/db/main.cpp + ${TESTS_DPL_DIR}/db/test_orm.cpp + ${TESTS_DPL_DIR}/db/test_sql_connection.cpp +) + +ADD_SUBDIRECTORY(orm) + +#include subdirectory +WRT_INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/orm) +WRT_TEST_ADD_INTERNAL_DEPENDENCIES(${TARGET_NAME} ${TARGET_DPL_DB_EFL}) +WRT_TEST_BUILD(${TARGET_NAME} ${DPL_TESTS_DB_SOURCES}) +WRT_TEST_INSTALL(${TARGET_NAME}) + +INSTALL(FILES + ${TESTS_DPL_DIR}/db/orm/dpl_orm_test.db + DESTINATION /opt/share/wrt/wrt-commons/tests/db +) diff --git a/tests/dpl/db/main.cpp b/tests/dpl/db/main.cpp new file mode 100644 index 0000000..4ed6191 --- /dev/null +++ b/tests/dpl/db/main.cpp @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file main.cpp + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of main. + */ + +#include + +int main(int argc, char *argv[]) +{ + return DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, argv); +} diff --git a/tests/dpl/db/orm/CMakeLists.txt b/tests/dpl/db/orm/CMakeLists.txt new file mode 100644 index 0000000..b7ebafb --- /dev/null +++ b/tests/dpl/db/orm/CMakeLists.txt @@ -0,0 +1,11 @@ +WRT_INTROSPECT_TARGET(db ${TARGET_DPL_DB_EFL}) +WRT_CONVERT_TO_GCC_LIST(db_INCLUDE_DIRS_GCC ${db_INCLUDE_DIRS}) + +ADD_CUSTOM_COMMAND( OUTPUT dpl_orm_test_db.sql + COMMAND rm -f ${CMAKE_CURRENT_SOURCE_DIR}/dpl_orm_test.db + COMMAND C_INCLUDE_PATH=${db_INCLUDE_DIRS_GCC} gcc -Wall -E ${CMAKE_CURRENT_SOURCE_DIR}/dpl_orm_test_db_sql_generator.h | grep --invert-match "^#" > ${CMAKE_CURRENT_SOURCE_DIR}/dpl_orm_test_db.sql + COMMAND sqlite3 ${CMAKE_CURRENT_SOURCE_DIR}/dpl_orm_test.db ".read ${CMAKE_CURRENT_SOURCE_DIR}/dpl_orm_test_db.sql" || rm -f ${CMAKE_CURRENT_SOURCE_DIR}/dpl_orm_test.db + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/dpl_orm_test_db_sql_generator.h ${CMAKE_CURRENT_SOURCE_DIR}/dpl_orm_test_db +) + +ADD_CUSTOM_TARGET( Sqlite3Db ALL DEPENDS dpl_orm_test_db.sql ) diff --git a/tests/dpl/db/orm/dpl_orm_test_db b/tests/dpl/db/orm/dpl_orm_test_db new file mode 100644 index 0000000..8191624 --- /dev/null +++ b/tests/dpl/db/orm/dpl_orm_test_db @@ -0,0 +1,88 @@ + +CREATE_TABLE(TestTableInsert) + COLUMN(ColumnOptInt, INT,) + COLUMN(ColumnOptText, TEXT,) + COLUMN_NOT_NULL(ColumnInt, INT, DEFAULT 99) + COLUMN_NOT_NULL(ColumnInt2, INT,) + COLUMN_NOT_NULL(ColumnText, TEXT,) +CREATE_TABLE_END() + +CREATE_TABLE(TestTableDelete) + COLUMN(ColumnOptInt, INT,) + COLUMN(ColumnOptText, TEXT,) + COLUMN_NOT_NULL(ColumnInt, INT, DEFAULT 99) + COLUMN_NOT_NULL(ColumnInt2, INT,) + COLUMN_NOT_NULL(ColumnText, TEXT,) +CREATE_TABLE_END() + +SQL( + INSERT INTO TestTableDelete VALUES(1, "two", 3, 4, "five"); + INSERT INTO TestTableDelete VALUES(6, "seven", 8, 9, "ten"); + INSERT INTO TestTableDelete (ColumnInt2, ColumnText) VALUES(11, "twelve"); + INSERT INTO TestTableDelete (ColumnInt2, ColumnText) VALUES(13, "fourteen"); +) + +CREATE_TABLE(TestTable) + COLUMN(ColumnOptInt, INT,) + COLUMN(ColumnOptText, TEXT,) + COLUMN_NOT_NULL(ColumnInt, INT, DEFAULT 99) + COLUMN_NOT_NULL(ColumnInt2, INT,) + COLUMN_NOT_NULL(ColumnText, TEXT,) +CREATE_TABLE_END() + +SQL( + INSERT INTO TestTable VALUES(1, "two", 3, 4, "five"); + INSERT INTO TestTable VALUES(6, "seven", 8, 9, "ten"); + INSERT INTO TestTable (ColumnInt2, ColumnText) VALUES(11, "twelve"); + INSERT INTO TestTable (ColumnInt2, ColumnText) VALUES(13, "fourteen"); +) + +CREATE_TABLE(TestTableJoin1) + COLUMN_NOT_NULL(TestID, INT) + COLUMN_NOT_NULL(TestText, TEXT) + COLUMN(TestNumber, INT) + TABLE_CONSTRAINTS( + PRIMARY KEY(TestID) + ) +CREATE_TABLE_END() + +CREATE_TABLE(TestTableJoin2) + COLUMN_NOT_NULL(TestID, INT) + COLUMN_NOT_NULL(TestText1, TEXT) + COLUMN_NOT_NULL(TestText2, TEXT) + TABLE_CONSTRAINTS( + PRIMARY KEY(TestID) + ) +CREATE_TABLE_END() + +CREATE_TABLE(TestTableJoin3) + COLUMN_NOT_NULL(TestID, INT) + COLUMN(Value3, INT) + COLUMN(TestText33, TEXT) + TABLE_CONSTRAINTS( + PRIMARY KEY(TestID) + ) +CREATE_TABLE_END() + +SQL( + INSERT INTO TestTableJoin1 VALUES(1, "text val 1", 111); + INSERT INTO TestTableJoin1 VALUES(2, "text val 2", 222); + INSERT INTO TestTableJoin1 VALUES(3, "text val 3", 333); + INSERT INTO TestTableJoin1 VALUES(4, "text val 4", 444); + INSERT INTO TestTableJoin1 VALUES(5, "text val 5", 555); + INSERT INTO TestTableJoin1 VALUES(6, "text val 6", 666); + + INSERT INTO TestTableJoin2 VALUES(1, "01", "text2 1"); + INSERT INTO TestTableJoin2 VALUES(2, "02", "text2 2"); + INSERT INTO TestTableJoin2 VALUES(3, "03", "text2 3"); + INSERT INTO TestTableJoin2 VALUES(4, " 4 ", "text2 4"); + INSERT INTO TestTableJoin2 VALUES(5, "*5*", "text2 5"); + INSERT INTO TestTableJoin2 VALUES(10, "6", "text2 6"); + + INSERT INTO TestTableJoin3 VALUES(1, 111, "test 1"); + INSERT INTO TestTableJoin3 VALUES(2, 111, "test 2"); + INSERT INTO TestTableJoin3 VALUES(3, 222, "test 3"); + INSERT INTO TestTableJoin3 VALUES(6, 222, "test 4"); + INSERT INTO TestTableJoin3 (TestID, TestText33) VALUES(7, "test 5"); + INSERT INTO TestTableJoin3 (TestID, TestText33) VALUES(10, "test 6"); +) \ No newline at end of file diff --git a/tests/dpl/db/orm/dpl_orm_test_db_definitions b/tests/dpl/db/orm/dpl_orm_test_db_definitions new file mode 100644 index 0000000..da79427 --- /dev/null +++ b/tests/dpl/db/orm/dpl_orm_test_db_definitions @@ -0,0 +1,5 @@ +DATABASE_START(dpl_orm_test) + +#include "dpl_orm_test_db" + +DATABASE_END() diff --git a/tests/dpl/db/orm/dpl_orm_test_db_sql_generator.h b/tests/dpl/db/orm/dpl_orm_test_db_sql_generator.h new file mode 100644 index 0000000..d045a39 --- /dev/null +++ b/tests/dpl/db/orm/dpl_orm_test_db_sql_generator.h @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file dpl_orm_test_db_sql_generator.h + * @author Lukasz Marek (l.marek@samsung.com) + * @version 1.0 + * @brief Macro definitions for generating the SQL input file from database definition. + */ + +//Do not include this file directly! It is used only for SQL code generation. + +#include + +#include "dpl_orm_test_db_definitions" diff --git a/tests/dpl/db/orm/dpl_orm_test_db_sql_generator.h.gch b/tests/dpl/db/orm/dpl_orm_test_db_sql_generator.h.gch new file mode 100644 index 0000000000000000000000000000000000000000..5bd675d819280b19af780a02d2739acb3bf9f0f0 GIT binary patch literal 6521 zcmai3$&w^T5pB#62(gMqh`pEr)WxXEa$kdUS4}|M}bBs}uV9_n+T>bBTX+KTltN`guNhdh(U-i<4I`KEC<*Gyc!d>2F@Z zhweBzxp?vN=JNI6Y0*9PWBSK;>DQR?S!-s^+|-Yk#`I1HVGxD=pVHC~d3oE+H>Rzt z^(M^Bta?m)vNVm;`?UH^-Z5!6Y{2xwVVI{$nZ#*OL{U`a>E$3UCijjQE6nD}vL<7< z*RQUgU0;6GyZGek%OBCsx7aA1io-^y7yaHv@BaN>+kS@@zQv29X|*zE&4wN?-llK9 z&ELY)!nzox>AP-l0e zvxzu8{piK*AD>_LlVOdm{Q*CW^wke5Dnh-PF2)p7@W3r{ z_9vA5EU_MjMUrHBk_3622W6UuS(t9y7WEW+>*m~4o5iddbt%5OzCkeRE6N=PuHtc! z_urunQt(MLZ#KxsW@;Am_6Zz9p}#@D##F0W-O^W~25>&#j?A*!jHYea4)UtFZ9<(s_78h)L9OYU5Tes3O_!-pU zFfa40jKer7vM3JI{PIB@6kcML30^Ecvh_>)HRk;BV@`N8pDaxM;kIg<%@fni+h$(( zg7;|8_jn)7081AC&tF_W>+y$U0@Vx2{yJ}eesz8Ox)%biE@yFM>gBp=7jsmi9%SPQ zYA@>y*6o~NFt3585L^a#jKR_L>;aNd5OK~WMCw6WkU%9QkHRCu4k2QzkYEpSkWz8& zF(!<1*cOgjDp?ySslbXHqk8&m$1~zJ=((6sCc*av(1O1d&AMKhwmKuoEm!rVfi%Gd zk+t<^JTlY8dLu~yKjbkEaayg(AVVDh-%T%&K5Nd;>-EME5zptdn&DFn$+Q+ynBdgA8e-E*%{DYuO2N{AD~14u86zKpeCf}j#Ytj-g*5_J46=) zmDGw5DNaddgm2_u7VuA_l-;M&t@wmkfd3w27jho5D3Y{Jf5tbS-X!t`QP)1Q46Vu|XNRvEI ziy&`X)l>^L9u!!G4whIOoj}PU=m^zWV;~-@N zH?3dOlBU;=1P48Y3b}`H&aXrGUCPo|%Gp?#3x*(sKq=J$dxyW^_bzg}ni4RmE-)>g zuj=!L1bL-;jWv1JYK)YFCrovzJ61ve^PT6850ffK^M&ohyJR9D?M+@0{FF|}<*5kC zqHa-wB~cDrPcn8d8K%Sd9*U|;xzosKG(&u@%Mm3+Mlq2&J)lQ+;2fso@d4odo&oa;I>B~I$4I68t54`kpwl-2=WDe8tMrS;AX9@tQBc1(t0@DX$d&@em^bT<c&0gcc> zQc{nlaWA|agc*-{Qe6NMk?1f&HPi;+jn@*d$_u6>fx*Mc($F6YLYqRzE2~Yc6$nvg zD;9R!NO`V6ad|+dny$BJxLn|lz|;zc0e-A%{)%=AzqkSHbSF>$-=}T+aG;_cNQgg% zD)YNWyu*B$(>{%KxLZYBKo)Fl7%29W)sAT$dpJlmoI9fAP>+9L^ks?BEO&nT!yV=w zfZG^>Hl$P#Vv$_{zS!(K2S8~YhKvPdD#;!T33NzfzT^muqkM%gco4bRKfr1#NGEY1A z!=rVDp|f<1=19ELJv$&s3oLU4C2KGNAa`R3T_TVYksDg14u60s+?U>3tNcH%!2p3Vs@cFoJHM^U_ZT#`s^d@C|w)H*f)gbyDS6@nKutj%4|;13n~Dxh~m_ z{ucNp@@8da(k?2N6g(^*;26!5rv%VO39QS^7h?oa5^V&#M5M9@^yMCjjseGa8Y~q% zICsAk+R|zDm?^>-C?UbY6IieVVpL#BGJU4Gz7< z8BI-I;V~T|ECYNI4~oz|hqP)N-I*wl^i#eu%hUrL7Pg%tDnSh(&|MOgBv_LmEUqmB z$kRk`+pu^HA%12tCTKcDOFG8s3rC!%lN;5@>-xW;H77X0njrS*RpIyUG^U9EE-)M> zK^T=qk|p%!uLyG*IFfXN+Dd!m^oVVexg*W#ICQ`lsVMr*@jZJlX<4RX@+T^yILR`4 z!4MTiMlZUG33BD4Rcn@XqRO@=df7%fCCSW3qKO*-P6u($_h#{tf<%b60{YU6>;r*f z#JhP4uc^DINR&9nuLp<-ixt5k#br)x0}fiBJ6@0~vgj0w&r^sTe77Fhd#4M7Ub~0JS7O%F*QHdF+AO z+vojF0c~>QB=P3U1}z$^Sm+RhKopu$<0@+>T1kg1mm59e1h*D1S&%K4OM=ACn`R3q qy^GW98=WE$5YGUvZF?;Y>MF-DDConx;ptV`*>IDH%M1Q@!~X$0f4^1$ literal 0 HcmV?d00001 diff --git a/tests/dpl/db/orm/generator_dpl_orm_test.h b/tests/dpl/db/orm/generator_dpl_orm_test.h new file mode 100644 index 0000000..39bb1b7 --- /dev/null +++ b/tests/dpl/db/orm/generator_dpl_orm_test.h @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 ORM_GENERATOR_DPL_ORM_TEST_H +#define ORM_GENERATOR_DPL_ORM_TEST_H + +#define ORM_GENERATOR_DATABASE_NAME dpl_orm_test_db_definitions +#include +#undef ORM_GENERATOR_DATABASE_NAME + +#endif diff --git a/tests/dpl/db/test_orm.cpp b/tests/dpl/db/test_orm.cpp new file mode 100644 index 0000000..9295ed2 --- /dev/null +++ b/tests/dpl/db/test_orm.cpp @@ -0,0 +1,851 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 + +const char* PATH_DB = "/opt/share/wrt/wrt-commons/tests/db/dpl_orm_test.db"; + +//utils + +#define TEST_REPETITION 16 + +class SmartAttach +{ +public: + + SmartAttach(bool autoattach = true) : + m_interface(PATH_DB, + DPL::DB::SqlConnection::Flag::UseLucene), + m_autoattach(autoattach) + { + if (m_autoattach) { + m_interface.AttachToThread(DPL::DB::SqlConnection::Flag::RW); + } + } + + ~SmartAttach() + { + if (m_autoattach) { + m_interface.DetachFromThread(); + } + } + + DPL::DB::ThreadDatabaseSupport* get() + { + return &m_interface; + } +private: + DPL::DB::ThreadDatabaseSupport m_interface; + bool m_autoattach; +}; + +template +bool ContainerContentsEqual(const ContainerType1& container1, const ContainerType2& container2) +{ + using namespace DPL::DB::ORM::dpl_orm_test::TestTableInsert; + typedef std::set Set1; + typedef std::set Set2; + Set1 set1(container1.begin(), container1.end()); + Set2 set2(container2.begin(), container2.end()); + + for (typename Set1::iterator it = set1.begin(); + it != set1.end(); + it++) + { + LogDebug("Set1 element: " << *it); + } + + for (typename Set2::iterator it = set2.begin(); it != set2.end(); it++) + { + LogDebug("Set2 element: " << *it); + } + + return set1 == set2; +} + +template +std::list makeList(const T& a, const T& b) +{ + std::list list; + list.push_back(a); + list.push_back(b); + return list; +} + +//tests + +RUNNER_TEST_GROUP_INIT(DPL) + +RUNNER_TEST(ORM_SelectSingleValue) +{ + SmartAttach interface; + using namespace DPL::DB::ORM; + using namespace DPL::DB::ORM::dpl_orm_test; + //Getting each column + { + TestTable::Select select(interface.get()); + select.Where(Equals(8)); + int result; + RUNNER_ASSERT_MSG((result = *select.GetSingleValue()) == 6, "Got " << result); + } + { + TestTable::Select select(interface.get()); + select.Where(Equals(8)); + DPL::String result; + RUNNER_ASSERT_MSG((result = *select.GetSingleValue()) == L"seven", "Got " << result); + } + { + TestTable::Select select(interface.get()); + select.Where(Equals(8)); + int result; + RUNNER_ASSERT_MSG((result = select.GetSingleValue()) == 8, "Got " << result); + } + { + TestTable::Select select(interface.get()); + select.Where(Equals(8)); + int result; + RUNNER_ASSERT_MSG((result = select.GetSingleValue()) == 9, "Got " << result); + } + { + TestTable::Select select(interface.get()); + select.Where(Equals(8)); + DPL::String result; + RUNNER_ASSERT_MSG((result = select.GetSingleValue()) == L"ten", "Got " << result); + } + + //Where on each column + { + TestTable::Select select(interface.get()); + select.Where(Equals(6)); + int result; + RUNNER_ASSERT_MSG((result = *select.GetSingleValue()) == 6, "Got " << result); + } + { + TestTable::Select select(interface.get()); + select.Where(Equals(DPL::String(L"seven"))); + DPL::String result; + RUNNER_ASSERT_MSG((result = *select.GetSingleValue()) == L"seven", "Got " << result); + } + { + TestTable::Select select(interface.get()); + select.Where(Equals(8)); + int result; + RUNNER_ASSERT_MSG((result = select.GetSingleValue()) == 8, "Got " << result); + } + { + TestTable::Select select(interface.get()); + select.Where(Equals(9)); + int result; + RUNNER_ASSERT_MSG((result = select.GetSingleValue()) == 9, "Got " << result); + } + { + TestTable::Select select(interface.get()); + select.Where(Equals(L"ten")); + DPL::String result; + RUNNER_ASSERT_MSG((result = select.GetSingleValue()) == L"ten", "Got " << result); + } +} + +RUNNER_TEST(ORM_SelectSingleRow) +{ + SmartAttach interface; + using namespace DPL::DB::ORM; + using namespace DPL::DB::ORM::dpl_orm_test; + { + TestTable::Select select(interface.get()); + select.Where(Equals(3)); + TestTable::Row result = select.GetSingleRow(); + TestTable::Row expected; + expected.Set_ColumnOptInt(1); + expected.Set_ColumnOptText(DPL::String(L"two")); + expected.Set_ColumnInt(3); + expected.Set_ColumnInt2(4); + expected.Set_ColumnText(L"five"); + RUNNER_ASSERT_MSG(result == expected, "Got " << result); + } + + { + TestTable::Select select(interface.get()); + select.Where(Equals(DPL::String(L"seven"))); + TestTable::Row result = select.GetSingleRow(); + TestTable::Row expected; + expected.Set_ColumnOptInt(6); + expected.Set_ColumnOptText(DPL::String(L"seven")); + expected.Set_ColumnInt(8); + expected.Set_ColumnInt2(9); + expected.Set_ColumnText(L"ten"); + RUNNER_ASSERT_MSG(result == expected, "Got " << result); + } +} + +RUNNER_TEST(ORM_SelectRowList) +{ + SmartAttach interface; + using namespace DPL::DB::ORM; + using namespace DPL::DB::ORM::dpl_orm_test; + { + TestTable::Select select(interface.get()); + select.Where(Equals(3)); + std::list result = select.GetRowList(); + RUNNER_ASSERT_MSG(result.size() == 1, "Got " << result.size()); + + TestTable::Row expected; + expected.Set_ColumnOptInt(1); + expected.Set_ColumnOptText(DPL::String(L"two")); + expected.Set_ColumnInt(3); + expected.Set_ColumnInt2(4); + expected.Set_ColumnText(L"five"); + RUNNER_ASSERT_MSG(*(result.begin()) == expected, "Got " << *(result.begin()) ); + } + + { + TestTable::Select select(interface.get()); + select.Where(Equals(DPL::String(L"seven"))); + std::list result = select.GetRowList(); + RUNNER_ASSERT_MSG(result.size() == 1, "Got " << result.size()); + + TestTable::Row expected; + expected.Set_ColumnOptInt(6); + expected.Set_ColumnOptText(DPL::String(L"seven")); + expected.Set_ColumnInt(8); + expected.Set_ColumnInt2(9); + expected.Set_ColumnText(L"ten"); + RUNNER_ASSERT_MSG(*(result.begin()) == expected, "Got " << *(result.begin()) ); + } + + { + TestTable::Select select(interface.get()); + select.Where(Equals(99)); + std::list result = select.GetRowList(); + + TestTable::Row expected1; + expected1.Set_ColumnInt(99); + expected1.Set_ColumnInt2(11); + expected1.Set_ColumnText(L"twelve"); + + TestTable::Row expected2; + expected2.Set_ColumnInt(99); + expected2.Set_ColumnInt2(13); + expected2.Set_ColumnText(L"fourteen"); + + RUNNER_ASSERT(ContainerContentsEqual(makeList(expected1, expected2), result)); + } +} + +RUNNER_TEST(ORM_SelectValueList) +{ + SmartAttach interface; + using namespace DPL::DB::ORM; + using namespace DPL::DB::ORM::dpl_orm_test; + //Getting each column + { + TestTable::Select select(interface.get()); + select.Where(Is(DPL::Optional::Null)); + RUNNER_ASSERT(ContainerContentsEqual(select.GetValueList(), + makeList(99, 99))); + } + { + TestTable::Select select(interface.get()); + select.Where(Is(DPL::Optional::Null)); + RUNNER_ASSERT(ContainerContentsEqual(select.GetValueList(), + makeList(11, 13))); + } + { + TestTable::Select select(interface.get()); + select.Where(Is(DPL::Optional::Null)); + RUNNER_ASSERT(ContainerContentsEqual(select.GetValueList(), + makeList(DPL::String(L"twelve"), DPL::String(L"fourteen")))); + } + { + TestTable::Select select(interface.get()); + select.Where(Is(DPL::Optional::Null)); + RUNNER_ASSERT(ContainerContentsEqual(select.GetValueList(), + makeList(DPL::Optional::Null,DPL::Optional::Null))); + } + + //Where on each column + { + TestTable::Select select(interface.get()); + select.Where(Is(DPL::Optional::Null)); + RUNNER_ASSERT(ContainerContentsEqual(select.GetValueList(), + makeList(11, 13))); + } + { + TestTable::Select select(interface.get()); + select.Where(Is(DPL::Optional::Null)); + RUNNER_ASSERT(ContainerContentsEqual(select.GetValueList(), + makeList(11, 13))); + } + { + TestTable::Select select(interface.get()); + select.Where(Is(99)); + RUNNER_ASSERT(ContainerContentsEqual(select.GetValueList(), + makeList(11, 13))); + } +} + +RUNNER_TEST(ORM_MultipleCalls) +{ + for (int j = 0 ; j < TEST_REPETITION ; j++ ) + { + for (int i = 0 ; i < TEST_REPETITION ; i++ ) + ORM_SelectSingleValue(); + + for (int i = 0 ; i < TEST_REPETITION ; i++ ) + ORM_SelectSingleRow(); + + for (int i = 0 ; i < TEST_REPETITION ; i++ ) + ORM_SelectRowList(); + + for (int i = 0 ; i < TEST_REPETITION ; i++ ) + ORM_SelectValueList(); + } +} + +RUNNER_TEST(ORM_Insert) +{ + SmartAttach interface; + using namespace DPL::DB::ORM; + using namespace DPL::DB::ORM::dpl_orm_test; + + TestTableInsert::Select select1(interface.get()); + std::list resultList = select1.GetValueList(); + RUNNER_ASSERT_MSG(resultList.size() == 0, "Returned list has wrong size: " << resultList.size()); + std::list list; + + TestTableInsert::Insert insert(interface.get()); + TestTableInsert::Row row; + row.Set_ColumnOptInt(1); + row.Set_ColumnInt2(2); + row.Set_ColumnText(L"three"); + insert.Values(row); + insert.Execute(); + + row.Set_ColumnInt(99); + list.push_back(row); + { + TestTableInsert::Select select2(interface.get()); + RUNNER_ASSERT_MSG(ContainerContentsEqual(select2.GetRowList(), list), "Returned list doesn't match."); + } + + TestTableInsert::Insert insert2(interface.get()); + TestTableInsert::Row row2; + row2.Set_ColumnInt(4); + row2.Set_ColumnInt2(5); + row2.Set_ColumnText(L"six"); + insert2.Values(row2); + insert2.Execute(); + + list.push_back(row2); + { + TestTableInsert::Select select(interface.get()); + RUNNER_ASSERT_MSG(ContainerContentsEqual(select.GetRowList(), list), "Returned list doesn't match."); + } + + TestTableInsert::Insert insert3(interface.get()); + TestTableInsert::Row row3; + row3.Set_ColumnOptInt(1); + row3.Set_ColumnInt2(7); + row3.Set_ColumnText(L"eight"); + insert3.Values(row3); + insert3.Execute(); + + row3.Set_ColumnInt(99); + list.push_back(row3); + { + TestTableInsert::Select select3(interface.get()); + RUNNER_ASSERT_MSG(ContainerContentsEqual(select3.GetRowList(), list), "Returned list doesn't match."); + } + + TestTableInsert::Insert insert4(interface.get()); + TestTableInsert::Row row4; + row4.Set_ColumnOptInt(9); + row4.Set_ColumnInt2(10); + row4.Set_ColumnText(L"eleven"); + insert4.Values(row4); + insert4.Execute(); + + row4.Set_ColumnInt(99); + list.push_back(row4); + { + TestTableInsert::Select select4(interface.get()); + RUNNER_ASSERT_MSG(ContainerContentsEqual(select4.GetRowList(), list), "Returned list doesn't match."); + } + + // restore original table state + { + TestTableInsert::Delete del(interface.get()); + del.Execute(); + + TestTableInsert::Select select(interface.get()); + RUNNER_ASSERT(select.GetRowList().size() == 0); + } +} + +RUNNER_TEST(ORM_MultipleBindInsert) +{ + for ( int i = 0 ; i < TEST_REPETITION ; i++ ) + { + ORM_Insert(); + } +} + +RUNNER_TEST(ORM_Delete) +{ + SmartAttach interface; + using namespace DPL::DB::ORM; + using namespace DPL::DB::ORM::dpl_orm_test; + TestTableDelete::Select selectStart(interface.get()); + selectStart.OrderBy("ColumnInt2 ASC"); + std::list list = selectStart.GetRowList(); + std::list originalList = list; + + std::vector vector(list.begin(), list.end()); + RUNNER_ASSERT_MSG(list.size() == 4, "Returned list has wrong size: " << list.size()); + + typedef DPL::String S; + + //no-act deletes + { + TestTableDelete::Delete del(interface.get()); + del.Where(And(Equals(1), Equals(S(L"seven")))); + del.Execute(); + + TestTableDelete::Select select(interface.get()); + RUNNER_ASSERT_MSG(ContainerContentsEqual(select.GetRowList(), list), "Returned list doesn't match."); + } + + { + TestTableDelete::Delete del(interface.get()); + del.Where(And(Equals(6), Equals(S(L"two")))); + del.Execute(); + + TestTableDelete::Select select(interface.get()); + RUNNER_ASSERT_MSG(ContainerContentsEqual(select.GetRowList(), list), "Returned list doesn't match."); + } + + { + TestTableDelete::Delete del(interface.get()); + del.Where(Equals(10)); + del.Execute(); + + TestTableDelete::Select select(interface.get()); + RUNNER_ASSERT_MSG(ContainerContentsEqual(select.GetRowList(), list), "Returned list doesn't match."); + } + + //act deletes + { + list.remove(vector[1]); + + TestTableDelete::Delete del(interface.get()); + del.Where(And(Equals(6), Equals(L"ten"))); + del.Execute(); + + TestTableDelete::Select select(interface.get()); + RUNNER_ASSERT_MSG(ContainerContentsEqual(select.GetRowList(), list), "Returned list doesn't match."); + } + + { + list.remove(vector[2]); + list.remove(vector[3]); + + TestTableDelete::Delete del(interface.get()); + del.Where(Is(DPL::Optional::Null)); + del.Execute(); + + TestTableDelete::Select select(interface.get()); + RUNNER_ASSERT_MSG(ContainerContentsEqual(select.GetRowList(), list), "Returned list doesn't match."); + } + + { + TestTableDelete::Delete del(interface.get()); + del.Execute(); + + TestTableDelete::Select select(interface.get()); + RUNNER_ASSERT_MSG(select.GetRowList().size() == 0, "Returned list is not empty"); + } + + // Restore original table state + // This also tests if multiple different binds for Insert are working properly + for (std::list::iterator i = originalList.begin(); i != originalList.end(); i++) + { + TestTableDelete::Insert insert(interface.get()); + insert.Values(*i); + insert.Execute(); + } + + { + TestTableDelete::Select select(interface.get()); + RUNNER_ASSERT_MSG(ContainerContentsEqual(select.GetRowList(), originalList), "Returned list doesn't match."); + } + +} + +RUNNER_TEST(ORM_MultipleBindDelete) +{ + for ( int i = 0 ; i < TEST_REPETITION ; i++ ) + { + ORM_Delete(); + } +} + +RUNNER_TEST(ORM_MultipleBindWhere) +{ + SmartAttach interface; + using namespace DPL::DB::ORM; + using namespace DPL::DB::ORM::dpl_orm_test; + { + TestTable::Select select(interface.get()); + int result; + select.Where(Equals(8)); + RUNNER_ASSERT_MSG((result = *select.GetSingleValue()) == 6, "Got " << result); + + select.Where(Equals(3)); + RUNNER_ASSERT_MSG((result = *select.GetSingleValue()) == 1, "Got " << result); + + select.Where(Equals(8)); + RUNNER_ASSERT_MSG((result = *select.GetSingleValue()) == 6, "Got " << result); + + select.Where(Equals(3)); + RUNNER_ASSERT_MSG((result = *select.GetSingleValue()) == 1, "Got " << result); + } + + { + TestTable::Select select(interface.get()); + int result; + select.Where(And(Equals(99), + Equals(L"fourteen"))); + RUNNER_ASSERT_MSG((result = select.GetSingleValue()) == 13, "Got " << result); + + select.Where(And(Equals(99), + Equals(L"twelve"))); + RUNNER_ASSERT_MSG((result = select.GetSingleValue()) == 11, "Got " << result); + + select.Where(And(Equals(99), + Equals(L"fourteen"))); + RUNNER_ASSERT_MSG((result = select.GetSingleValue()) == 13, "Got " << result); + + select.Where(And(Equals(99), + Equals(L"twelve"))); + RUNNER_ASSERT_MSG((result = select.GetSingleValue()) == 11, "Got " << result); + } + + { + TestTable::Select select(interface.get()); + int result; + select.Where(And(Equals(L"fourteen"), + Equals(99))); + RUNNER_ASSERT_MSG((result = select.GetSingleValue()) == 13, "Got " << result); + + select.Where(And(Equals(L"twelve"), + Equals(99))); + RUNNER_ASSERT_MSG((result = select.GetSingleValue()) == 11, "Got " << result); + + select.Where(And(Equals(L"fourteen"), + Equals(99))); + RUNNER_ASSERT_MSG((result = select.GetSingleValue()) == 13, "Got " << result); + + select.Where(And(Equals(L"twelve"), + Equals(99))); + RUNNER_ASSERT_MSG((result = select.GetSingleValue()) == 11, "Got " << result); + + } + +} + +RUNNER_TEST(ORM_Update) +{ + SmartAttach interface; + using namespace DPL::DB::ORM; + using namespace DPL::DB::ORM::dpl_orm_test; + + std::list list; + + TestTableInsert::Delete del(interface.get()); + del.Execute(); + + // INSERT + { + TestTableInsert::Insert insert(interface.get()); + TestTableInsert::Row row; + row.Set_ColumnOptInt(5); + row.Set_ColumnInt2(2); + row.Set_ColumnText(L"two"); + insert.Values(row); + insert.Execute(); + + row.Set_ColumnInt(99); + list.push_back(row); + } + { + TestTableInsert::Insert insert(interface.get()); + TestTableInsert::Row row; + row.Set_ColumnOptInt(1); + row.Set_ColumnInt2(2); + row.Set_ColumnText(L"three"); + insert.Values(row); + insert.Execute(); + + row.Set_ColumnInt(99); + list.push_back(row); + } + { + TestTableInsert::Insert insert(interface.get()); + TestTableInsert::Row row; + row.Set_ColumnOptInt(2); + row.Set_ColumnInt2(3); + row.Set_ColumnText(L"three"); + insert.Values(row); + insert.Execute(); + + row.Set_ColumnInt(99); + list.push_back(row); + + // CHECK + TestTableInsert::Select select(interface.get()); + RUNNER_ASSERT_MSG(ContainerContentsEqual(select.GetRowList(), list), "Returned list doesn't match."); + } + { + // UPDATE - no rows + TestTableInsert::Update update(interface.get()); + TestTableInsert::Row row; + row.Set_ColumnInt2(4); + row.Set_ColumnText(L"four"); + update.Values(row); + update.Where(Equals(12)); + update.Execute(); + + // CHECK + TestTableInsert::Select select(interface.get()); + RUNNER_ASSERT_MSG(ContainerContentsEqual(select.GetRowList(), list), "Returned list doesn't match."); + } + { + // UPDATE - one row + TestTableInsert::Update update(interface.get()); + TestTableInsert::Row row; + row.Set_ColumnInt2(2); + row.Set_ColumnText(L"four"); + update.Values(row); + update.Where(Equals(3)); + update.Execute(); + + list.back().Set_ColumnInt2(2); + list.back().Set_ColumnText(L"four"); + + // CHECK + TestTableInsert::Select select(interface.get()); + RUNNER_ASSERT_MSG(ContainerContentsEqual(select.GetRowList(), list), "Returned list doesn't match."); + } + + { + // UPDATE - multiple rows + TestTableInsert::Update update(interface.get()); + TestTableInsert::Row row; + row.Set_ColumnText(L"dup"); + update.Values(row); + update.Where(Equals(2)); + update.Execute(); + + FOREACH(it, list) + { + it->Set_ColumnText(L"dup"); + } + + // CHECK + TestTableInsert::Select select(interface.get()); + RUNNER_ASSERT_MSG(ContainerContentsEqual(select.GetRowList(), list), "Returned list doesn't match."); + } + + // restore original table state + { + TestTableInsert::Delete del2(interface.get()); + del2.Execute(); + + TestTableInsert::Select select(interface.get()); + RUNNER_ASSERT(select.GetRowList().size() == 0); + } +} + +RUNNER_TEST(ORM_MultipleBindUpdate) +{ + for ( int i = 0 ; i < TEST_REPETITION ; i++ ) + { + ORM_Update(); + } +} + +RUNNER_TEST(ORM_transactions) +{ + SmartAttach interface; + DPL::DB::ORM::dpl_orm_test::ScopedTransaction transaction(interface.get()); +} + +RUNNER_TEST(ORM_MultiAttach) +{ + SmartAttach interface(false); + RUNNER_ASSERT_MSG(!interface.get()->IsAttached(), "Is attached, but shouldn't be."); + interface.get()->AttachToThread(); + RUNNER_ASSERT_MSG(interface.get()->IsAttached(), "Isn't attached, but should be."); + interface.get()->AttachToThread(); + RUNNER_ASSERT_MSG(interface.get()->IsAttached(), "Isn't attached, but should be."); + interface.get()->DetachFromThread(); + RUNNER_ASSERT_MSG(interface.get()->IsAttached(), "Isn't attached, but should be."); + interface.get()->DetachFromThread(); + RUNNER_ASSERT_MSG(!interface.get()->IsAttached(), "Is attached, but shouldn't be."); +} + +RUNNER_TEST(ORM_Join) +{ + SmartAttach interface; + using namespace DPL::DB::ORM; + using namespace DPL::DB::ORM::dpl_orm_test; + + typedef DPL::TypeListDecl::Type JoinColumns; + + /* Test for correct join: + * 5 ids from first table matches 5 ids from second table thus join result + * contains 5 rows */ + TestTableJoin1::Select select(interface.get()); + select.Join(Equal()); + std::list> rowlist = + select.GetCustomRowList>(); + + RUNNER_ASSERT_MSG(rowlist.size() == 5, "Invalid number of rows fetched: " << rowlist.size()); + + std::string text; + std::ostringstream oss; + int cnt = 0; + FOREACH(rowit, rowlist) + { + cnt++; + + text = DPL::ToUTF8String((*rowit).GetColumnData()); + oss << "text val " << cnt; + RUNNER_ASSERT_MSG(text.compare(oss.str()) == 0, "Invalid value from first column: " + << text << " expected: " << oss.str()); + oss.str(std::string()); + + text = DPL::ToUTF8String((*rowit).GetColumnData()); + oss << "text2 " << cnt; + RUNNER_ASSERT_MSG(text.compare(oss.str()) == 0, "Invalid value from second column: " + << text << " expected: " << oss.str()); + oss.str(std::string()); + } + /* Test for empty join: + * None of number values from first table matches ids from second table + * - join result should be empty */ + TestTableJoin1::Select select2(interface.get()); + select2.Join(Equal()); + rowlist = select2.GetCustomRowList>(); + + RUNNER_ASSERT_MSG(rowlist.empty(), "Result should be empty but it is not!"); + + /* Test for "converted" join: + * - join made with int column and text column as keys + * - expected 5 matching rows (one row of 6 should not be matched)*/ + TestTableJoin1::Select select3(interface.get()); + select3.Join(Equal()); + rowlist = select3.GetCustomRowList>(); + RUNNER_ASSERT_MSG(rowlist.size() == 5, "Expected 5 rows while received: " << rowlist.size()); + cnt = 0; + FOREACH(rowit, rowlist) + { + cnt++; + // look at last two insertions into TestTableJoin2 + // for this skip understanding + if(cnt == 5) { + cnt = 6; + } + text = DPL::ToUTF8String((*rowit).GetColumnData()); + oss << "text val " << cnt; + RUNNER_ASSERT_MSG(text.compare(oss.str()) == 0, "Invalid value from first column: " + << text << " expected: " << oss.str() << " iteration: " <()); + oss << "text2 " << cnt; + RUNNER_ASSERT_MSG(text.compare(oss.str()) == 0, "Invalid value from second column: " + << text << " expected: " << oss.str() << " iteration: " <::Type JoinTables2; + TestTableJoin1::Select select4(interface.get()); + select4.Join(Equal()); + std::list> rowlist2 = select4.GetCustomRowList>(); + RUNNER_ASSERT_MSG(rowlist2.size() == 4, "Expected 4 rows while received: " << rowlist.size()); + cnt = 0; + DPL::Optional optext; + FOREACH(rowit, rowlist2) + { + cnt++; + + text = DPL::ToUTF8String((*rowit).GetColumnData()); + // values expected in subsequent (1,2,3,4) iterations: 1 1 2 2 + oss << "text val " << (1+(int)(cnt/3)); + RUNNER_ASSERT_MSG(text.compare(oss.str()) == 0, "Invalid value from first column: " + << text << " expected: " << oss.str() << " iteration: " <(); + text = DPL::ToUTF8String(*optext); + oss << "test " << cnt; + RUNNER_ASSERT_MSG(text.compare(oss.str()) == 0, "Invalid value from second column: " + << text << " expected: " << oss.str() << " iteration: " <::Type Join3Tables; + TestTableJoin1::Select select5(interface.get()); + select5.Join(Equal()); + select5.Join(Equal()); + std::list> rowlist3tab = select5.GetCustomRowList>(); + RUNNER_ASSERT_MSG(rowlist3tab.size() == 3, "Expected 3 rows while received: " << rowlist3tab.size()); + cnt = 0; + FOREACH(rowit, rowlist3tab) + { + cnt++; + + text = DPL::ToUTF8String((*rowit).GetColumnData()); + oss << "text val " << cnt; + RUNNER_ASSERT_MSG(text.compare(oss.str()) == 0, "Invalid value from first column: " + << text << " expected: " << oss.str() << " iteration: " <()); + oss << "text2 " << cnt; + RUNNER_ASSERT_MSG(text.compare(oss.str()) == 0, "Invalid value from first column: " + << text << " expected: " << oss.str() << " iteration: " <(); + text = DPL::ToUTF8String(*optext); + oss << "test " << cnt; + RUNNER_ASSERT_MSG(text.compare(oss.str()) == 0, "Invalid value from second column: " + << text << " expected: " << oss.str() << " iteration: " < +#include +#include +#include +#include +#include +#include +#include +#include + +extern const char* PATH_DB; + +RUNNER_TEST_GROUP_INIT(DPL) + +class AbstractSynchronizationObjectGenerator +{ +public: + virtual ~AbstractSynchronizationObjectGenerator() {} + + virtual DPL::DB::SqlConnection::SynchronizationObject *Create() = 0; +}; + +class NaiveSynchronizationObjectGenerator + : public AbstractSynchronizationObjectGenerator +{ +public: + virtual DPL::DB::SqlConnection::SynchronizationObject *Create() + { + return new DPL::DB::NaiveSynchronizationObject(); + } +}; + +void MassiveReadWriteTest(AbstractSynchronizationObjectGenerator *generator); + +class StressGenerator + : public DPL::Thread +{ +private: + size_t m_prefix; + std::string m_dbFileName; + AbstractSynchronizationObjectGenerator *m_generator; + +protected: + virtual int ThreadEntry() + { + DPL::DB::SqlConnection connection( + m_dbFileName, + DPL::DB::SqlConnection::Flag::None, + DPL::DB::SqlConnection::Flag::RW, + m_generator->Create()); + + DPL::DB::SqlConnection::DataCommandAutoPtr countCommand = + connection.PrepareDataCommand( + "SELECT COUNT(*) FROM test WHERE value=?"); + + for (size_t i = 0; i < 10; ++i) + { + std::ostringstream valueStream; + + valueStream << "value_"; + valueStream << static_cast(m_prefix); + valueStream << "_"; + valueStream << static_cast(i); + + std::string value = valueStream.str(); + + connection.ExecCommand( + "INSERT INTO test VALUES ('%s');", + value.c_str()); + + countCommand->BindString(1, value.c_str()); + + RUNNER_ASSERT(countCommand->Step()); + + RUNNER_ASSERT(countCommand->GetColumnString(0) == "1"); + + countCommand->Reset(); + } + + countCommand.reset(); + + return 0; + } + +public: + StressGenerator(size_t prefix, + const std::string &dbFileName, + AbstractSynchronizationObjectGenerator *generator) + : m_prefix(prefix), + m_dbFileName(dbFileName), + m_generator(generator) + { + } +}; + +typedef std::shared_ptr ThreadPtr; + +void MassiveReadWriteTest(AbstractSynchronizationObjectGenerator *generator) +{ + DPL::DB::SqlConnection connection(PATH_DB, + DPL::DB::SqlConnection::Flag::UseLucene, + DPL::DB::SqlConnection::Flag::RW); + + connection.ExecCommand("CREATE TABLE test(value TEXT);"); + + const size_t STRESS_GENERATOR_COUNT = 5; + ThreadPtr stressGenerators[STRESS_GENERATOR_COUNT]; + + for (size_t i = 0; i < STRESS_GENERATOR_COUNT; ++i) + { + stressGenerators[i].reset( + new StressGenerator(i, PATH_DB, generator)); + + stressGenerators[i]->Run(); + } + + for (size_t i = 0; i < STRESS_GENERATOR_COUNT; ++i) + stressGenerators[i]->Quit(); + + connection.ExecCommand("DROP TABLE test;"); +} + +RUNNER_TEST(SqlConnection_MassiveReadWrite_NaiveSynchronization) +{ + srand(time(NULL)); + + NaiveSynchronizationObjectGenerator m_generator; + MassiveReadWriteTest(&m_generator); +} + + + + + + +RUNNER_TEST(SqlConnection_Not_Connected_Lucene) +{ + Try { + DPL::DB::SqlConnection connection("/notexisitingdirectiory/foo", + DPL::DB::SqlConnection::Flag::UseLucene, + DPL::DB::SqlConnection::Flag::RW); + RUNNER_ASSERT_MSG(false, + "connection should throw on accessing " + "nonexistent file as a database"); + } + Catch (DPL::DB::SqlConnection::Exception::ConnectionBroken) + { + RUNNER_ASSERT(true); + } + catch (DPL::Exception) + { + RUNNER_ASSERT_MSG(false, "Wrong exception found"); + } +} + +RUNNER_TEST(SqlConnection_Not_Connected) +{ + Try { + DPL::DB::SqlConnection connection("/notexisitingdirectiory/foo", + DPL::DB::SqlConnection::Flag::None, + DPL::DB::SqlConnection::Flag::RW); + RUNNER_ASSERT_MSG(false, + "connection should throw on accessing " + "nonexistent file as a database"); + } + Catch (DPL::DB::SqlConnection::Exception::ConnectionBroken) + { + RUNNER_ASSERT(true); + } + catch (DPL::Exception) + { + RUNNER_ASSERT_MSG(false, "Wrong exception found"); + } +} + +RUNNER_TEST(SqlConnection_Null_Query) +{ + DPL::DB::SqlConnection connection(PATH_DB, + DPL::DB::SqlConnection::Flag::UseLucene, + DPL::DB::SqlConnection::Flag::RW); + Try + { + connection.ExecCommand(NULL); + RUNNER_ASSERT_MSG(false, + "Null pointer should not be accepted"); + } + Catch (DPL::DB::SqlConnection::Exception::SyntaxError) + { + RUNNER_ASSERT(true); + } + catch (DPL::Exception) + { + RUNNER_ASSERT_MSG(false, "Wrong exception found"); + } + +} + +RUNNER_TEST(SqlConnection_Bad_Query) +{ + DPL::DB::SqlConnection connection(PATH_DB, + DPL::DB::SqlConnection::Flag::UseLucene, + DPL::DB::SqlConnection::Flag::RW); + Try + { + connection.ExecCommand("Some stupid string"); + RUNNER_ASSERT_MSG(false, "This string should not be accepted"); + } + Catch (DPL::DB::SqlConnection::Exception::SyntaxError) + { + RUNNER_ASSERT(true); + } + catch (DPL::Exception) + { + RUNNER_ASSERT_MSG(false, "Wrong exception found"); + } +} diff --git a/tests/dpl/dbus/CMakeLists.txt b/tests/dpl/dbus/CMakeLists.txt new file mode 100644 index 0000000..066ad79 --- /dev/null +++ b/tests/dpl/dbus/CMakeLists.txt @@ -0,0 +1,63 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# @file CMakeLists.txt +# @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) +# @version 1.0 +# @brief +# + +INCLUDE(FindPkgConfig) + +PKG_CHECK_MODULES(DEPENDENCIES gthread-2.0 REQUIRED) + +SET(TARGET_DBUS_TESTS "dpl-tests-dbus") +SET(TARGET_DBUS_TEST_SERVICE "dpl-dbus-test-service") + +SET(DBUS_TESTS_SRCS + ${TESTS_DPL_DIR}/dbus/main.cpp + ${TESTS_DPL_DIR}/dbus/test_cases.cpp + ${TESTS_DPL_DIR}/dbus/dbus_test.cpp + ${TESTS_COMMON_DIR}/src/loop_control.cpp +) + +SET(DBUS_TEST_SERVICE_SRCS + ${TESTS_DPL_DIR}/dbus/test_service.cpp + ${TESTS_COMMON_DIR}/src/loop_control.cpp +) + +WRT_TEST_ADD_INTERNAL_DEPENDENCIES(${TARGET_DBUS_TESTS} ${TARGET_DPL_DBUS_EFL}) +WRT_TEST_INCLUDE_DIRECTORIES(${TARGET_DBUS_TESTS} + ${TESTS_COMMON_DIR}/include + ${DEPENDENCIES_INCLUDE_DIRS} +) +WRT_TEST_LINK_DIRECTORIES(${TARGET_DBUS_TESTS} ${DEPENDENCIES_LIBRARY_DIRS}) +WRT_TEST_TARGET_LINK_LIBRARIES(${TARGET_DBUS_TESTS} ${DEPENDENCIES_LIBRARIES}) +WRT_TEST_BUILD(${TARGET_DBUS_TESTS} ${DBUS_TESTS_SRCS}) +WRT_TEST_INSTALL(${TARGET_DBUS_TESTS}) + +WRT_TEST_ADD_INTERNAL_DEPENDENCIES(${TARGET_DBUS_TEST_SERVICE} ${TARGET_DPL_DBUS_EFL}) +WRT_TEST_INCLUDE_DIRECTORIES(${TARGET_DBUS_TEST_SERVICE} + ${TESTS_COMMON_DIR}/include + ${DEPENDENCIES_INCLUDE_DIRS} +) +WRT_TEST_LINK_DIRECTORIES(${TARGET_DBUS_TEST_SERVICE} ${DEPENDENCIES_LIBRARY_DIRS}) +WRT_TEST_TARGET_LINK_LIBRARIES(${TARGET_DBUS_TEST_SERVICE} ${DEPENDENCIES_LIBRARIES}) +WRT_TEST_BUILD(${TARGET_DBUS_TEST_SERVICE} ${DBUS_TEST_SERVICE_SRCS}) +WRT_TEST_INSTALL(${TARGET_DBUS_TEST_SERVICE}) + +INSTALL(FILES + ${TESTS_DPL_DIR}/dbus/data/org.tizen.DBusTestService.service + DESTINATION /usr/share/dbus-1/services +) diff --git a/tests/dpl/dbus/data/org.tizen.DBusTestService.service b/tests/dpl/dbus/data/org.tizen.DBusTestService.service new file mode 100644 index 0000000..f024543 --- /dev/null +++ b/tests/dpl/dbus/data/org.tizen.DBusTestService.service @@ -0,0 +1,3 @@ +[D-BUS Service] +Name=org.tizen.DBusTestService +Exec=/usr/bin/dpl-dbus-test-service diff --git a/tests/dpl/dbus/dbus_test.cpp b/tests/dpl/dbus/dbus_test.cpp new file mode 100644 index 0000000..6071f9f --- /dev/null +++ b/tests/dpl/dbus/dbus_test.cpp @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file dbus_test.cpp + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + * @brief Implementation file for DBusTest and DBusTestManager. + */ + +#include +#include "loop_control.h" +#include "dbus_test.h" + +DBusTest::DBusTest(const std::string& name) + : m_name(name), + m_status(Status::NONE) +{ +} + +void DBusTest::run(unsigned int timeout) +{ + DPL::Event::ControllerEventHandler::Touch(); + DPL::Event::ControllerEventHandler::Touch(); + + DPL::Event::ControllerEventHandler::PostTimedEvent( + TimeoutEvent(), timeout); + + LoopControl::wrt_start_loop(); + + switch (m_status) + { + case Status::FAILED: + throw DPL::Test::TestRunner::TestFailed(m_name.c_str(), + __FILE__, + __LINE__, + m_message); + + default: + break; + } +} + +void DBusTest::quit() +{ + DPL::Event::ControllerEventHandler::PostEvent(QuitEvent()); +} + +void DBusTest::setStatus(Status status) +{ + m_status = status; +} + +void DBusTest::setMessage(const std::string& message) +{ + m_message = message; +} + +void DBusTest::success() +{ + m_status = Status::SUCCESS; +} + +void DBusTest::fail(const std::string& message) +{ + m_status = Status::FAILED; + m_message = message; +} + +void DBusTest::OnEventReceived(const TimeoutEvent& /*event*/) +{ + fail("Test timed out."); + + // Saving one event dispatch since Quit and Timeout work on the same thread. + LoopControl::wrt_end_loop(); +} + +void DBusTest::OnEventReceived(const QuitEvent& /*event*/) +{ + LoopControl::wrt_end_loop(); +} + +DBusTestManager& DBusTestManager::getInstance() +{ + static DBusTestManager instance; + return instance; +} + +DBusTestManager::DBusTestManager() : m_test(NULL) { } + +DBusTest& DBusTestManager::getCurrentTest() const +{ + Assert(NULL != m_test && "Test not set."); + + return *m_test; +} + +void DBusTestManager::setCurrentTest(DBusTest& test) +{ + m_test = &test; +} + +void DBusTestManager::clear() +{ + m_test = NULL; +} diff --git a/tests/dpl/dbus/dbus_test.h b/tests/dpl/dbus/dbus_test.h new file mode 100644 index 0000000..9b5061e --- /dev/null +++ b/tests/dpl/dbus/dbus_test.h @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file dbus_test.h + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + * @brief Header file for DBusTest and DBusTestManager. + */ + +#ifndef WRT_TESTS_DBUS_TESTS_DBUS_TEST_H +#define WRT_TESTS_DBUS_TESTS_DBUS_TEST_H + +#include +#include +#include + +DECLARE_GENERIC_EVENT_0(QuitEvent) +DECLARE_GENERIC_EVENT_0(TimeoutEvent) + +class DBusTest : + private DPL::Event::Controller::Type> +{ +public: + enum class Status + { + NONE, + SUCCESS, + FAILED + }; + + explicit DBusTest(const std::string& name); + + void run(unsigned int timeout); + void quit(); + + void setStatus(Status status); + void setMessage(const std::string& message); + + void success(); + void fail(const std::string& message = std::string()); + +private: + void OnEventReceived(const TimeoutEvent& event); + void OnEventReceived(const QuitEvent& event); + + std::string m_name; + Status m_status; + std::string m_message; +}; + +class DBusTestManager : private DPL::Noncopyable +{ +public: + static DBusTestManager& getInstance(); + + DBusTest& getCurrentTest() const; + void setCurrentTest(DBusTest& test); + + void clear(); + +private: + DBusTestManager(); + + DBusTest* m_test; +}; + +#define DBUS_TEST(TestProc) \ + void DBus##TestProc(); \ + RUNNER_TEST(TestProc) \ + { \ + DBusTest test(#TestProc); \ + DBusTestManager::getInstance().setCurrentTest(test); \ + DBus##TestProc(); \ + DBusTestManager::getInstance().clear(); \ + } \ + void DBus##TestProc() + +#endif diff --git a/tests/dpl/dbus/main.cpp b/tests/dpl/dbus/main.cpp new file mode 100644 index 0000000..55a8950 --- /dev/null +++ b/tests/dpl/dbus/main.cpp @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file main.cpp + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of main. + */ + +#include "loop_control.h" +#include +#include + +int main(int argc, char *argv[]) +{ + LoopControl::init_loop(argc, argv); + + LogInfo("Running tests"); + int status = DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, argv); + + return status; +} diff --git a/tests/dpl/dbus/test_cases.cpp b/tests/dpl/dbus/test_cases.cpp new file mode 100644 index 0000000..dfb3c7e --- /dev/null +++ b/tests/dpl/dbus/test_cases.cpp @@ -0,0 +1,190 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file TestCases.cpp + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + * @version 1.0 + * @brief Implementation file for test cases for DBus internal tests. + */ + +#include +#include +#include +#include +#include +#include +#include "dbus_test.h" + +namespace { +const std::string dbusServiceName = "org.freedesktop.DBus"; +const std::string dbusObjectPath = "/"; +const std::string dbusInterfaceName = "org.freedesktop.DBus"; +const std::string dbusMethodGetId = "GetId"; + +const std::string serviceName = "org.tizen.DBusTestService"; +const std::string objectPath = "/org/tizen/DBusTestService"; +const std::string interfaceName = "org.tizen.DBusTestService"; +const std::string methodNameEcho = "echo"; +const std::string methodNameQuit = "quit"; +const std::string nodeInfo = + "" + "" + " " + " " + " " + " " + " " + " " + " " + " " + ""; + +const std::string challenge = "Hello world!"; + +const int DEFAULT_TIMEOUT = 2; // in seconds +} + +RUNNER_TEST_GROUP_INIT(DPL) + +RUNNER_TEST(AcquireSessionBus) +{ + try + { + DPL::DBus::Connection::sessionBus(); + } + catch (const DPL::DBus::Exception& ex) + { + RUNNER_ASSERT_MSG(false, ex.DumpToString()); + } +} + +RUNNER_TEST(AcquireSystemBus) +{ + try + { + DPL::DBus::Connection::systemBus(); + } + catch (const DPL::DBus::Exception& ex) + { + RUNNER_ASSERT_MSG(false, ex.DumpToString()); + } +} + +RUNNER_TEST(ParseNodeInfo) +{ + try + { + auto ifaces = DPL::DBus::Interface::fromXMLString(nodeInfo); + RUNNER_ASSERT(!ifaces.empty()); + + auto iface = ifaces.at(0); + RUNNER_ASSERT(NULL != iface->getVTable()); + RUNNER_ASSERT(NULL != iface->getInfo()); + } + catch (const DPL::DBus::Exception& ex) + { + RUNNER_ASSERT_MSG(false, ex.DumpToString()); + } +} + +RUNNER_TEST(InvokeRemoteMethod) +{ + try + { + auto connection = DPL::DBus::Connection::systemBus(); + auto freedesktop = connection->createObjectProxy(dbusServiceName, + dbusObjectPath); + auto getId = freedesktop->createMethodProxy + (dbusInterfaceName, dbusMethodGetId); + RUNNER_ASSERT(!getId().empty()); + } + catch (const DPL::DBus::Exception& ex) + { + RUNNER_ASSERT_MSG(false, ex.DumpToString()); + } +} + +class RegisterServiceListener : + public DPL::Event::EventListener +{ +public: + void OnEventReceived( + const DPL::DBus::ConnectionEvents::ServiceNameAcquiredEvent& event) + { + DBusTest& test = DBusTestManager::getInstance().getCurrentTest(); + + auto name = event.GetArg0(); + if (serviceName == name) + { + test.success(); + } + else + { + test.fail("Acquired service name: " + name); + } + test.quit(); + } +}; + +DBUS_TEST(RegisterService) +{ + try + { + RegisterServiceListener listener; + + auto connection = DPL::DBus::Connection::sessionBus(); + connection->DPL::Event::EventSupport::AddListener(&listener); + connection->registerService(serviceName); + + DBusTestManager::getInstance().getCurrentTest().run(DEFAULT_TIMEOUT); + } + catch (const DPL::DBus::Exception& ex) + { + RUNNER_ASSERT_MSG(false, ex.DumpToString()); + } +} + +/** + * This test checks: + * - object registration (done on the wrt-dbus-test-service side) + * - service registration (done on the wrt-dbus-test-service side) + * - dispatching method calls (done on the wrt-dbus-test-service side) + * - launching dbus service on demand + * - invoking remote method(s) + */ +DBUS_TEST(InvokeTestService) +{ + try + { + auto connection = DPL::DBus::Connection::sessionBus(); + auto testService = connection->createObjectProxy(serviceName, + objectPath); + auto echo = testService->createMethodProxy + (interfaceName, methodNameEcho); + auto response = echo(challenge); + + testService->createMethodProxy(interfaceName, methodNameQuit)(); + + RUNNER_ASSERT_MSG(response == challenge, + "[challenge = " << challenge << + ", response = " << response << "]"); + } + catch (const DPL::DBus::Exception& ex) + { + RUNNER_ASSERT_MSG(false, ex.DumpToString()); + } +} diff --git a/tests/dpl/dbus/test_service.cpp b/tests/dpl/dbus/test_service.cpp new file mode 100644 index 0000000..bc2e3f8 --- /dev/null +++ b/tests/dpl/dbus/test_service.cpp @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file test_service.cpp + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + * @brief Implementation file for wrt-dbus-test-service. + */ + +#include +#include +#include +#include +#include +#include + +namespace { +const std::string serviceName = "org.tizen.DBusTestService"; +const std::string objectPath = "/org/tizen/DBusTestService"; +const std::string interfaceName = "org.tizen.DBusTestService"; +const std::string methodNameEcho = "echo"; +const std::string methodNameQuit = "quit"; +const std::string nodeInfo = + "" + "" + " " + " " + " " + " " + " " + " " + " " + " " + ""; +} + +class TestServiceDispatcher : public DPL::DBus::Dispatcher +{ +private: + void onMethodCall(GDBusConnection* /*connection*/, + const gchar* /*sender*/, + const gchar* /*objectPath*/, + const gchar* /*interfaceName*/, + const gchar* methodName, + GVariant* parameters, + GDBusMethodInvocation* invocation) + { + if (methodNameEcho == methodName) + { + LogDebug("Echo"); + g_dbus_method_invocation_return_value(invocation, + parameters); + } + else if (methodNameQuit == methodName) + { + LogDebug("Quit"); + g_dbus_method_invocation_return_value(invocation, NULL); + LoopControl::wrt_end_loop(); + } + } +}; + +int main(int argc, char* argv[]) +{ + LoopControl::init_loop(argc, argv); + TestServiceDispatcher dispatcher; + + auto iface = DPL::DBus::Interface::fromXMLString(nodeInfo).at(0); + iface->setDispatcher(&dispatcher); + auto object = DPL::DBus::Object::create(objectPath, iface); + auto connection = DPL::DBus::Connection::sessionBus(); + connection->registerObject(object); + connection->registerService(serviceName); + LoopControl::wrt_start_loop(); + + return 0; +} diff --git a/tests/dpl/event/CMakeLists.txt b/tests/dpl/event/CMakeLists.txt new file mode 100644 index 0000000..de3db4a --- /dev/null +++ b/tests/dpl/event/CMakeLists.txt @@ -0,0 +1,42 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# @file CMakeLists.txt +# @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) +# @version 1.0 +# @brief +# + +# +# Test files +# +# Define all DPL tests sources. +# Runner is responsible for runnint it all and +# generating proper output files +# + +SET(TARGET_NAME "dpl-tests-event") + +# Set DPL tests sources +SET(DPL_TESTS_EVENT_SOURCES + ${TESTS_DPL_DIR}/event/main.cpp + ${TESTS_DPL_DIR}/event/test_controller.cpp + ${TESTS_DPL_DIR}/event/test_event_support.cpp + ${TESTS_DPL_DIR}/event/test_ic_delegate.cpp + ${TESTS_DPL_DIR}/event/test_property.cpp +) + +WRT_TEST_ADD_INTERNAL_DEPENDENCIES(${TARGET_NAME} ${TARGET_DPL_EVENT_EFL}) +WRT_TEST_BUILD(${TARGET_NAME} ${DPL_TESTS_EVENT_SOURCES}) +WRT_TEST_INSTALL(${TARGET_NAME}) \ No newline at end of file diff --git a/tests/dpl/event/main.cpp b/tests/dpl/event/main.cpp new file mode 100644 index 0000000..4ed6191 --- /dev/null +++ b/tests/dpl/event/main.cpp @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file main.cpp + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of main. + */ + +#include + +int main(int argc, char *argv[]) +{ + return DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, argv); +} diff --git a/tests/dpl/event/test_controller.cpp b/tests/dpl/event/test_controller.cpp new file mode 100644 index 0000000..fe2a700 --- /dev/null +++ b/tests/dpl/event/test_controller.cpp @@ -0,0 +1,331 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file test_controller.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of test controller + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL) + +class IntController + : public DPL::Event::Controller::Type> +{ +private: + int m_value; + +protected: + virtual void OnEventReceived(const int &event) + { + m_value = event; + } + +public: + IntController() + : m_value(-1) + { + } + + int Value() const + { + return m_value; + } +}; + +DECLARE_GENERIC_EVENT_1(DoneSignalEvent, DPL::WaitableEvent *) + +class ThreadController + : public DPL::Event::Controller::Type> +{ +private: + DPL::Thread *m_value; + +protected: + virtual void OnEventReceived(const DoneSignalEvent &event) + { + m_value = DPL::Thread::GetCurrentThread(); + event.GetArg0()->Signal(); + } + +public: + ThreadController() + : m_value(NULL) + { + } + + DPL::Thread *Value() const + { + return m_value; + } +}; + +struct StrangeStruct +{ + int a; + float b; + double c; +}; + +class StrangeController + : public DPL::Event::Controller::Type> +{ +protected: + virtual void OnEventReceived(const char &event) { (void)event; } + virtual void OnEventReceived(const short &event) { (void)event; } + virtual void OnEventReceived(const int &event) { (void)event; } + virtual void OnEventReceived(const long &event) { (void)event; } + virtual void OnEventReceived(const unsigned char &event) { (void)event; } + virtual void OnEventReceived(const unsigned short &event) { (void)event; } + virtual void OnEventReceived(const unsigned int &event) { (void)event; } + virtual void OnEventReceived(const unsigned long &event) { (void)event; } + virtual void OnEventReceived(const float &event) { (void)event; } + virtual void OnEventReceived(const double &event) { (void)event; } + virtual void OnEventReceived(const StrangeStruct &event) { (void)event; } +}; + +RUNNER_TEST(Controller_InitSimple) +{ + IntController controller; + controller.Touch(); + RUNNER_ASSERT(controller.Value() == -1); +} + +RUNNER_TEST(Controller_InitStrange) +{ + StrangeController controller; + controller.Touch(); +} + +RUNNER_TEST(Controller_PostEventToThread) +{ + ThreadController controller; + controller.Touch(); + + DPL::Thread thread; + thread.Run(); + + controller.SwitchToThread(&thread); + + DPL::WaitableEvent waitHandle; + + controller.PostEvent(DoneSignalEvent(&waitHandle)); + + DPL::WaitForSingleHandle(waitHandle.GetHandle()); + + controller.SwitchToThread(NULL); + + RUNNER_ASSERT(controller.Value() == &thread); +} + +RUNNER_TEST(Controller_PostTimedEventToThread) +{ + ThreadController controller; + controller.Touch(); + + DPL::Thread thread; + thread.Run(); + + controller.SwitchToThread(&thread); + + DPL::WaitableEvent waitHandle; + + controller.PostTimedEvent(DoneSignalEvent(&waitHandle), 0.5); + + DPL::WaitForSingleHandle(waitHandle.GetHandle()); + + controller.SwitchToThread(NULL); + + RUNNER_ASSERT(controller.Value() == &thread); +} + +DECLARE_GENERIC_EVENT_2(TouchInThread, DPL::WaitableEvent *, DPL::Thread **) +DECLARE_GENERIC_EVENT_2(TouchedControllerSignal, DPL::WaitableEvent *, DPL::Thread **) + +class TouchInThreadController + : public DPL::Event::Controller::Type>, + private DPL::Event::Controller::Type> +{ +public: + typedef DPL::Event::Controller::Type> PublicController; + typedef DPL::Event::Controller::Type> PrivateController; + + virtual void OnEventReceived(const TouchInThread &event) + { + // Touch controller in thread + PrivateController::Touch(); + + // Post signal + PrivateController::PostEvent(TouchedControllerSignal(event.GetArg0(), event.GetArg1())); + } + + virtual void OnEventReceived(const TouchedControllerSignal &event) + { + // Return touched thread + *event.GetArg1() = DPL::Thread::GetCurrentThread(); + + // Signal waitable event + event.GetArg0()->Signal(); + } +}; + +RUNNER_TEST(Controller_TouchInThread) +{ + TouchInThreadController controller; + controller.PublicController::Touch(); + + DPL::Thread thread; + thread.Run(); + + controller.PublicController::SwitchToThread(&thread); + + DPL::WaitableEvent waitHandle; + DPL::Thread *touchedThread = NULL; + + controller.PublicController::PostEvent(TouchInThread(&waitHandle, &touchedThread)); + + DPL::WaitForSingleHandle(waitHandle.GetHandle()); + + controller.PublicController::SwitchToThread(NULL); + + RUNNER_ASSERT(touchedThread == &thread); +} + +RUNNER_TEST(Controller_SynchronizedEvent) +{ + IntController controller; + controller.Touch(); + + DPL::Thread thread; + thread.Run(); + + controller.SwitchToThread(&thread); + controller.PostSyncEvent(12345); + controller.SwitchToThread(NULL); + + RUNNER_ASSERT(controller.Value() == 12345); +} + +const int ControllersNumber = 5; +const int MaxEventsPerController = 1; +const int MaxEvents = ControllersNumber * MaxEventsPerController; +const int ControllersPerThread = 1; + +class TestController; //Forward Declaration + +typedef std::shared_ptr ControllerPtr; +typedef std::shared_ptr ThreadPtr; +typedef std::vector ControllerList; +typedef std::list ThreadList; + +DECLARE_GENERIC_EVENT_0(QuitEvent) +class QuitController + : public DPL::Event::Controller::Type>, + public DPL::ApplicationExt +{ +public: + explicit QuitController( ) : DPL::ApplicationExt(1, NULL, "test-app") { Touch(); } +protected: + virtual void OnEventReceived(const QuitEvent &) { Quit(); } +}; + +struct TestContext +{ + ControllerList controllers; + ThreadList threads; + QuitController quitter; + DPL::Atomic g_ReceivedCounter; + DPL::Atomic g_SentCounter; +}; +typedef std::unique_ptr TestContextPtr; +TestContextPtr testContextPtr; + +DECLARE_GENERIC_EVENT_0(StartSendEvent) +DECLARE_GENERIC_EVENT_0(RandomEvent) +class TestController + : public DPL::Event::Controller::Type> +{ +public: + explicit TestController() { Touch(); } +protected: + virtual void OnEventReceived(const RandomEvent &) + { + ++testContextPtr->g_ReceivedCounter; + if(testContextPtr->g_ReceivedCounter == MaxEvents) + { + testContextPtr->quitter.DPL::Event::ControllerEventHandler::PostEvent(QuitEvent()); + return; + } + } + virtual void OnEventReceived(const StartSendEvent &) + { + for (int i=0 ; ig_SentCounter > MaxEvents) + { + return; + } + ++testContextPtr->g_SentCounter; + int id = rand() % static_cast(testContextPtr->controllers.size()); + testContextPtr->controllers.at(id)->DPL::Event::ControllerEventHandler::PostEvent(RandomEvent()); + } + } +}; + +RUNNER_TEST(Controllers_MultipleEvents) +{ + srand ( time(NULL) ); + + testContextPtr.reset(new TestContext()); + testContextPtr->controllers.reserve(ControllersNumber); + + for (int i = 0; i < ControllersNumber ; ++i) + { + if(testContextPtr->controllers.size() % ControllersPerThread ==0) + { + ThreadPtr thread = ThreadPtr(new DPL::Thread()); + testContextPtr->threads.push_back(thread); + thread->Run(); + } + + ControllerPtr controller = ControllerPtr(new TestController()); + testContextPtr->controllers.push_back(controller); + if(testContextPtr->controllers.size() % 2 == 0) + { + //This controller is being switched to thread (otherwise it is touched to main thread) + ThreadPtr thread = testContextPtr->threads.back(); + controller->SwitchToThread(thread.get()); + } + controller->DPL::Event::ControllerEventHandler::PostEvent(StartSendEvent()); + } + testContextPtr->quitter.Exec(); + RUNNER_ASSERT(testContextPtr->g_SentCounter == testContextPtr->g_ReceivedCounter); + testContextPtr.reset(); +} diff --git a/tests/dpl/event/test_event_support.cpp b/tests/dpl/event/test_event_support.cpp new file mode 100644 index 0000000..af303f0 --- /dev/null +++ b/tests/dpl/event/test_event_support.cpp @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file test_event_support.cpp + * @author Piotr Marcinkiewicz (p.marcinkiew@samsung.com) + * @author Pawel Sikorski (p.sikorski@samsung.com) + * @version 1.0 + * @brief This file contains test for event support + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +DECLARE_GENERIC_EVENT_0(TestEvent) + +class TestListener: public DPL::Event::EventListener +{ +public: + explicit TestListener() : m_dummyVar(0) { } + void OnEventReceived(const TestEvent &) { m_dummyVar = 1; } + int GetDummyVar() const { return m_dummyVar; } + void ZeroDummyVar() { m_dummyVar = 0; } + +private: + int m_dummyVar; +}; + +class TestEventSupport + : public DPL::Event::EventSupport +{ +public: + void TestEmitEvent() { EmitEvent(TestEvent()); } +}; + +DECLARE_GENERIC_EVENT_0(QuitEvent) + +class QuitController + : public DPL::Event::Controller::Type>, + public DPL::ApplicationExt +{ +public: + QuitController() : DPL::ApplicationExt(1, NULL, "test-app") { Touch(); } + +protected: + virtual void OnEventReceived(const QuitEvent &) { Quit(); } +}; + +RUNNER_TEST(EventSupport_DestroyBeforeProcessing) +{ + QuitController quitter; + quitter.PostTimedEvent(QuitEvent(), 1.0); + + TestListener eventListener; + { + TestEventSupport eventSupport; + eventSupport.AddListener(&eventListener); + eventSupport.TestEmitEvent(); + eventSupport.RemoveListener(&eventListener); + } + eventListener.ZeroDummyVar(); + + quitter.Exec(); + RUNNER_ASSERT(eventListener.GetDummyVar() == 0); +} + +int g_delegateTest; + +void OnDelegateTest(const int &k); + +void OnDelegateTest(const int &k) +{ + LogInfo("Got delegate call"); + g_delegateTest = k; +} + +class DelegateTestSupport + : public DPL::Event::EventSupport +{ +public: + void Test() + { + EmitEvent(7); + } +}; + +RUNNER_TEST(EventSupport_BindDelegate) +{ + g_delegateTest = 0; + + DelegateTestSupport support; + support.AddListener(&OnDelegateTest); + + QuitController quitter; + quitter.PostTimedEvent(QuitEvent(), 1.0); + + support.Test(); + + quitter.Exec(); + + support.RemoveListener(&OnDelegateTest); + + RUNNER_ASSERT(g_delegateTest == 7); +} diff --git a/tests/dpl/event/test_ic_delegate.cpp b/tests/dpl/event/test_ic_delegate.cpp new file mode 100644 index 0000000..34aea50 --- /dev/null +++ b/tests/dpl/event/test_ic_delegate.cpp @@ -0,0 +1,567 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file test_ic_delegate.cpp + * @author Pawel Sikorski (p.sikorski@samsung.com) + * @author Lukasz Wrzosek (l.wrzosek@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of fast delegate tests. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +RUNNER_TEST_GROUP_INIT(DPL) + +const int IntVal = 123; +const std::string StringVal = "someString"; + +typedef DPL::Event::ICDelegate<> GetNothingDlpType; +typedef DPL::Event::ICDelegate GetIntDlgType; +typedef DPL::Event::ICDelegate GetIntAndStringDlgType; +DECLARE_GENERIC_EVENT_1(GetNothingEvent, GetNothingDlpType) +DECLARE_GENERIC_EVENT_1(GetIntEvent, GetIntDlgType) +DECLARE_GENERIC_EVENT_1(GetIntAndStringEvent, GetIntAndStringDlgType) + +class ICTestController +: public DPL::Event::Controller::Type> +{ + public: + ICTestController() { } + + protected: + virtual void OnEventReceived(const GetNothingEvent& event) + { + event.GetArg0()(); //calling intercontext delegate + } + virtual void OnEventReceived(const GetIntEvent& event) + { + event.GetArg0()(IntVal); //calling intercontext delegate + } + + virtual void OnEventReceived(const GetIntAndStringEvent& event) + { + event.GetArg0()(IntVal, StringVal); //calling intercontext delegate + } +}; + +struct TestResult +{ + TestResult() : + m_correctThread0(false), + m_correctThread1(false), + m_correctThread2(false), + m_int(-1), + m_int2(-1), + m_string("") + { + } + + void TestEventsPassed() + { + RUNNER_ASSERT(m_correctThread0); + RUNNER_ASSERT(m_correctThread1); + RUNNER_ASSERT(m_int == IntVal); + RUNNER_ASSERT(m_correctThread2); + RUNNER_ASSERT(m_int2 == IntVal); + RUNNER_ASSERT(m_string == StringVal); + } + + void TestEventsDidNotPass() + { + RUNNER_ASSERT(!m_correctThread0); + RUNNER_ASSERT(!m_correctThread1); + RUNNER_ASSERT(m_int == -1); + RUNNER_ASSERT(!m_correctThread2); + RUNNER_ASSERT(m_int2 == -1); + RUNNER_ASSERT(m_string == ""); + } + + bool m_correctThread0; + bool m_correctThread1; + bool m_correctThread2; + int m_int; + int m_int2; + std::string m_string; +}; + +class TestContextFreeClass : + protected DPL::Thread, + public DPL::Event::ICDelegateSupport +{ + public: + TestContextFreeClass(ICTestController* controller, TestResult* result) : + Thread(), + m_testResult(result), + m_controller(controller) + { + LogDebug("Context thread id = " << this); + } + + void Run() + { + LogDebug("Running Context Free thread"); + Thread::Run(); + } + + void Quit() + { + LogDebug("Exiting Context Free thread"); + Thread::Quit(); + } + + + void Wait() + { + LogDebug("Waiting for thread"); + DPL::WaitForSingleHandle(m_waitable.GetHandle()); + } + + protected: + void OnNothing() + { + LogDebug("Received nothing in thread = " << GetCurrentThread()); + m_testResult->m_correctThread0 = (GetCurrentThread() == this); + } + + void OnIntReceive(int val) + { + LogDebug("Received int in thread = " << GetCurrentThread()); + m_testResult->m_correctThread1 = (GetCurrentThread() == this); + m_testResult->m_int = val; + } + + void OnIntAndStringReceive(int val, std::string stringval) + { + LogDebug("Received int and string in thread = " << GetCurrentThread()); + m_testResult->m_correctThread2 = (GetCurrentThread() == this); + m_testResult->m_int2 = val; + m_testResult->m_string = stringval; + m_waitable.Signal(); + } + + virtual int ThreadEntry() + { + GetNothingEvent getNothingEvent( + makeICDelegate( + &TestContextFreeClass::OnNothing)); + m_controller->DPL::Event::ControllerEventHandler::PostEvent( + getNothingEvent); + + GetIntEvent getIntEvent( + makeICDelegate( + &TestContextFreeClass::OnIntReceive)); + m_controller->DPL::Event::ControllerEventHandler::PostEvent( + getIntEvent); + + GetIntAndStringEvent getIntAndStringEvent( + makeICDelegate( + &TestContextFreeClass::OnIntAndStringReceive)); + m_controller->DPL::Event::ControllerEventHandler::PostEvent( + getIntAndStringEvent); + + return Thread::ThreadEntry(); + } + + private: + TestResult* m_testResult; + DPL::WaitableEvent m_waitable; + ICTestController* m_controller; +}; + +RUNNER_TEST(ICDelegate_0) +{ + DPL::Thread thread; + thread.Run(); + LogDebug("Controller thread id = " << &thread); + + ICTestController testController; + testController.Touch(); + testController.SwitchToThread(&thread); + + TestResult result; + TestContextFreeClass* contextFree = + new TestContextFreeClass(&testController, &result); + result.TestEventsDidNotPass(); + + thread.Run(); + contextFree->Run(); + contextFree->Wait(); + contextFree->Quit(); + thread.Quit(); + + delete contextFree; + + result.TestEventsPassed(); +} + +RUNNER_TEST(ICDelegate_1) +{ + DPL::Thread thread; + LogDebug("Controller thread id = " << &thread); + + ICTestController testController; + testController.Touch(); + testController.SwitchToThread(&thread); + + TestResult result; + TestContextFreeClass* contextFree = + new TestContextFreeClass(&testController, &result); + result.TestEventsDidNotPass(); + + contextFree->Run(); + contextFree->Quit(); + delete contextFree; //deleting Delegates before actual Events are worked out + thread.Run(); + thread.Quit(); + + result.TestEventsDidNotPass(); +} + +class TestContextFree; +class TestRunnerInThread; + +namespace +{ +const int ControllersPerThread = 40; +const int ContextFreePerThread = 180; +const int TestsPerController = 110; +const int TestThreads = 23; +const int TestsPerThread = 100; +const int NumberOfEvents = 230; + +typedef std::shared_ptr ICTestControllerPtr; +typedef std::shared_ptr TestContextFreePtr; +typedef std::shared_ptr TestRunnerInThreadPtr; +typedef std::shared_ptr ThreadPtr; + +DPL::Mutex mutex; +std::list frees; +std::list ctrls; +std::list frees_threads; +std::list ctrls_threads; + +} + +class TestContextFree : public DPL::Event::ICDelegateSupport +{ + public: + TestContextFree(ICTestController* controller, + int eventsCount) : + m_controller(controller), + m_eventsCount(eventsCount) + { + } + + void Wait() + { + LogDebug("Waiting for thread"); + DPL::WaitForSingleHandle(m_waitable.GetHandle()); + } + + + void OnNothing() + { + LogDebug("Got"); + m_eventsCount--; + if (m_eventsCount > 0) { + LogDebug("posting next event"); + GetIntAndStringEvent getIntAndStringEvent( + makeICDelegate( + &TestContextFree::OnIntAndStringReceive)); + LogDebug("posting next event ..."); + m_controller->DPL::Event::ControllerEventHandler::PostEvent( + getIntAndStringEvent); + LogDebug("posting next event done"); + } else { + LogDebug("test finished"); + m_waitable.Signal(); + } + } + + void OnIntReceive(int) + { + LogDebug("Got"); + m_eventsCount--; + if (m_eventsCount > 0) { + LogDebug("posting next event"); + GetNothingEvent getNothingEvent( + makeICDelegate( + &TestContextFree::OnNothing)); + LogDebug("posting next event ..."); + m_controller->DPL::Event::ControllerEventHandler::PostEvent( + getNothingEvent); + LogDebug("posting next event done"); + } else { + LogDebug("test finished"); + m_waitable.Signal(); + } + } + + void OnIntAndStringReceive(int, std::string) + { + LogDebug("Got"); + m_eventsCount--; + if (m_eventsCount > 0) { + LogDebug("posting next event"); + + GetIntEvent getIntEvent( + makeICDelegate( + &TestContextFree::OnIntReceive)); + LogDebug("posting next event ..."); + m_controller->DPL::Event::ControllerEventHandler::PostEvent( + getIntEvent); + LogDebug("posting next event done"); + } else { + LogDebug("test finished"); + m_waitable.Signal(); + } + } + + void StartTestOnNothing() + { + GetNothingEvent getNothingEvent( + makeICDelegate( + &TestContextFree::OnNothing)); + m_controller->DPL::Event::ControllerEventHandler::PostEvent( + getNothingEvent); + } + + void StartTestOnInt() + { + GetIntEvent getIntEvent( + makeICDelegate( + &TestContextFree::OnIntReceive)); + m_controller->DPL::Event::ControllerEventHandler::PostEvent( + getIntEvent); + } + + void StartTestOnIntAndString() + { + GetIntAndStringEvent getIntAndStringEvent( + makeICDelegate( + &TestContextFree::OnIntAndStringReceive)); + m_controller->DPL::Event::ControllerEventHandler::PostEvent( + getIntAndStringEvent); + } + + bool CheckTest() + { + LogDebug("Checking test result"); + return m_eventsCount == 0; + } + + private: + ICTestController* m_controller; + int m_eventsCount; + DPL::WaitableEvent m_waitable; +}; + +class TestRunnerInThread : public DPL::Thread +{ + public: + TestRunnerInThread(int events, int tests) : + m_eventsCount(events), + m_tests(tests) {} + + void WaitForInit() + { + LogDebug("Waiting for thread"); + DPL::WaitForSingleHandle(m_init.GetHandle()); + } + + protected: + virtual int ThreadEntry() + { + LogDebug("Thread starts"); + { + DPL::Mutex::ScopedLock lock(&mutex); + for (int i = 0; i < m_tests; ++i) + { + if (i % TestsPerController == 0) { + if (ctrls.size() % ControllersPerThread == 0) { + ThreadPtr thread(new DPL::Thread()); + thread->Run(); + ctrls_threads.push_back(thread); + } + ICTestControllerPtr ptr(new ICTestController()); + ptr->Touch(); + ptr->SwitchToThread(ctrls_threads.back().get()); + ctrls.push_back(ptr); + + TestContextFreePtr t(new TestContextFree(ctrls.back().get(), + m_eventsCount)); + t->StartTestOnNothing(); + LogDebug(""); + frees.push_back(t); + } + } + } + m_init.Signal(); + LogDebug("Thread starts loop"); + return DPL::Thread::ThreadEntry(); + } + + private: + DPL::WaitableEvent m_init; + int m_eventsCount; + int m_tests; +}; + +RUNNER_TEST(ICDelegate_2) +{ + LogDebug("Creating test threads"); + for (int i = 0; i < TestThreads; ++i) + { + TestRunnerInThreadPtr ptr( + new TestRunnerInThread(NumberOfEvents, TestsPerThread)); + frees_threads.push_back(ptr); + frees_threads.back()->Run(); + } + + FOREACH(it, frees_threads) { + (*it)->WaitForInit(); + } + LogDebug("Creating test threads done"); + + FOREACH(it, frees) { + LogDebug("..."); + (*it)->Wait(); + } + + FOREACH(it, frees) { + RUNNER_ASSERT((*it)->CheckTest()); + } + + frees.clear(); + + FOREACH(it, frees_threads) { + (*it)->Quit(); + } + + frees_threads.clear(); + + FOREACH(it, ctrls) { + (*it)->SwitchToThread(NULL); + } + + FOREACH(it, ctrls_threads) { + (*it)->Quit(); + } + + ctrls.clear(); + ctrls_threads.clear(); +} + +namespace ReuseCheck { +const int ReuseCount = 5; +typedef DPL::Event::ICDelegate<> GetNothingDlpType; +DECLARE_GENERIC_EVENT_1(ReuseCountEvent, GetNothingDlpType) + +class ICReuseTestController +: public DPL::Event::Controller::Type> +{ + public: + ICReuseTestController() { m_reuseCount = 0; } + + protected: + virtual void OnEventReceived(const ReuseCountEvent& event) + { + event.GetArg0()(); //calling intercontext delegate + if(++m_reuseCount < ReuseCount){ + LogInfo("[Send] Reuse: " << m_reuseCount); + DPL::Event::ControllerEventHandler::PostEvent(event); + } + } + + int m_reuseCount; +}; + +class ReuseTestContextFreeClass : + protected DPL::Thread, + public DPL::Event::ICDelegateSupport +{ + public: + ReuseTestContextFreeClass(ICReuseTestController* controller) : + Thread(), + m_controller(controller), + m_reuseCount(0) + { } + + void Run() { Thread::Run(); } + void Quit() { Thread::Quit(); } + void Wait() { DPL::WaitForSingleHandle(m_waitable.GetHandle()); } + + protected: + void OnReuseReceive() + { + LogDebug("[Received] : " << ++m_reuseCount); + if(m_reuseCount == ReuseCount) + m_waitable.Signal(); + } + + virtual int ThreadEntry() + { + ReuseCountEvent reuseEvent( + makeICDelegate( + &ReuseTestContextFreeClass::OnReuseReceive, + DPL::Event::ICD::Reuse::Yes)); + m_controller->DPL::Event::ControllerEventHandler::PostEvent( + reuseEvent); + + return Thread::ThreadEntry(); + } + + private: + DPL::WaitableEvent m_waitable; + ICReuseTestController* m_controller; + int m_reuseCount; +}; + +RUNNER_TEST(ICDelegate_3) +{ + DPL::Thread thread; + thread.Run(); + LogDebug("Controller thread id = " << &thread); + + ICReuseTestController testController; + testController.Touch(); + testController.SwitchToThread(&thread); + + ReuseTestContextFreeClass* contextFree = + new ReuseTestContextFreeClass(&testController); + + thread.Run(); + contextFree->Run(); + contextFree->Wait(); + contextFree->Quit(); + thread.Quit(); + + delete contextFree; + + RUNNER_ASSERT(true); +} +} //namespace ReuseCheck diff --git a/tests/dpl/event/test_property.cpp b/tests/dpl/event/test_property.cpp new file mode 100644 index 0000000..c095e5b --- /dev/null +++ b/tests/dpl/event/test_property.cpp @@ -0,0 +1,111 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file test_property.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of test property + */ +#include +#include +#include +#include + +namespace { +const int PROPERTY_VALUE_INT = 2; +const std::string PROPERTY_VALUE_STRING = "aaa"; +} + +int ReadSomething2(DPL::Event::Model */*model*/); +int ReadSomething2(DPL::Event::Model */*model*/) +{ + return PROPERTY_VALUE_INT; +} + +std::string ReadSomething(DPL::Event::Model */*model*/); +std::string ReadSomething(DPL::Event::Model */*model*/) +{ + return PROPERTY_VALUE_STRING; +} + +void WriteSomething(const std::string &/*value*/, DPL::Event::Model */*model*/); +void WriteSomething(const std::string &/*value*/, DPL::Event::Model */*model*/) +{ +} + +class MyModel + : public DPL::Event::Model +{ +public: + ~MyModel() {} + + DPL::Event::Property + Caption; + + DPL::Event::Property + Testproperty0; + + DPL::Event::Property + Testproperty1; + + DPL::Event::Property + Testproperty2; + + DPL::Event::Property Testproperty3; + + DPL::Event::Property Testproperty4; + + DPL::Event::Property Testproperty5; + + MyModel() + : Caption(this, "Foo caption"), + Testproperty0(this, "", &ReadSomething), + Testproperty1(this), + Testproperty2(this), + Testproperty3(this), + Testproperty4(this, "test", &ReadSomething, &WriteSomething), + Testproperty5(this, &ReadSomething2) + { + } +}; + +std::string g_caption; + +void OnNameChanged(const DPL::Event::PropertyEvent &event); +void OnNameChanged(const DPL::Event::PropertyEvent &event) +{ + g_caption = event.value; +} + +RUNNER_TEST(Model_Test) +{ + MyModel model; + + g_caption = "It is a bad caption"; + + model.Caption.AddListener(&OnNameChanged); + model.Caption.Set("Test name"); + + RUNNER_ASSERT(model.Testproperty4.Get() == PROPERTY_VALUE_STRING); + RUNNER_ASSERT(PROPERTY_VALUE_INT == model.Testproperty5.Get()); + RUNNER_ASSERT(g_caption == "Test name"); + RUNNER_ASSERT(model.Caption.Get() == "Test name"); + + model.Caption.RemoveListener(&OnNameChanged); +} diff --git a/tests/dpl/localization/CMakeLists.txt b/tests/dpl/localization/CMakeLists.txt new file mode 100644 index 0000000..a50727a --- /dev/null +++ b/tests/dpl/localization/CMakeLists.txt @@ -0,0 +1,51 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# @file CMakeLists.txt +# @author Bartlomiej Grzelewski (b.grzelewski@samsung.com) +# @version 1.0 +# @brief +# + +# +# Test files +# +# Define all DPL tests sources. +# Runner is responsible for runnint it all and +# generating proper output files +# + +SET(TARGET_LOC "dpl-tests-loc") + +SET(LOC_TESTS_SOURCES + ${DPL_TESTS_DIR}/localization/test_localization.cpp + ${DPL_TESTS_DIR}/localization/test_suite01.cpp + #${DPL_TESTS_DIR}/localization/mockup_src/widget_dao.cpp + #${PROJECT_SOURCE_DIR}/modules/localization/src/localization_utils.cpp + #${PROJECT_SOURCE_DIR}/modules/localization/src/w3c_file_localization.cpp +) + +#WRT_INCLUDE_DIRECTORIES( + #${SYS_EFL_INCLUDE_DIRS} + #${DPL_TEST_INCLUDE_DIR} + #${DPL_TESTS_DIR}/localization/mockup_include + #${PROJECT_SOURCE_DIR}/modules/localization/include +#) + +#LINK_DIRECTORIES(${SYS_EFL_LIBRARY_DIRS}) + +WRT_TEST_BUILD(${TARGET_LOC} ${LOC_TESTS_SOURCES}) +WRT_TEST_INSTALL(${TARGET_LOC}) + +ADD_SUBDIRECTORY(files) diff --git a/tests/dpl/localization/files/CMakeLists.txt b/tests/dpl/localization/files/CMakeLists.txt new file mode 100644 index 0000000..17c7fda --- /dev/null +++ b/tests/dpl/localization/files/CMakeLists.txt @@ -0,0 +1,19 @@ +INSTALL(FILES + ${DPL_TESTS_DIR}/localization/files/one + DESTINATION + /opt/share/widget/tests/localization/widget1/locales/pl-en + ) + +INSTALL(FILES + ${DPL_TESTS_DIR}/localization/files/one + ${DPL_TESTS_DIR}/localization/files/two + DESTINATION + /opt/share/widget/tests/localization/widget2/locales/pl-en + ) + +INSTALL(FILES + ${DPL_TESTS_DIR}/localization/files/two + DESTINATION + /opt/share/widget/tests/localization/widget2/locales/en-en + ) + diff --git a/tests/dpl/localization/files/one b/tests/dpl/localization/files/one new file mode 100644 index 0000000..e69de29 diff --git a/tests/dpl/localization/files/two b/tests/dpl/localization/files/two new file mode 100644 index 0000000..e69de29 diff --git a/tests/dpl/localization/mockup_include/dpl/wrt-dao-ro/common_dao_types.h b/tests/dpl/localization/mockup_include/dpl/wrt-dao-ro/common_dao_types.h new file mode 100644 index 0000000..ad8443f --- /dev/null +++ b/tests/dpl/localization/mockup_include/dpl/wrt-dao-ro/common_dao_types.h @@ -0,0 +1,485 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * + * @file common_dao_types.h + * @author Michal Ciepielski (m.ciepielski@samsung.com) + * @version 1.0 + * @brief This file contains the declaration of common data types for wrtdb + */ + +#ifndef WRT_SRC_CONFIGURATION_COMMON_DAO_TYPES_H_ +#define WRT_SRC_CONFIGURATION_COMMON_DAO_TYPES_H_ + +#include +#include +#include +#include +#include +#include +#include + +namespace WrtDB { +namespace Powder { + +typedef std::set StringSet; +//! Widget description +struct Description +{ + //!Content level + typedef enum + { + Level0 = 0, + Level1, + Level2, + Level3, + Level4, + Level5, + LevelUnknown + } LevelEnum; + struct LevelEntry + { + LevelEnum level; //!< content level + + typedef StringSet Context; + + //! POWDER context + //! xa This material appears in an artistic context + //! xb This material appears in an educational context + //! xc This material appears in a medical context + //! xd This material appears in a sports context + //! xe This material appears in a violent context + Context context; + explicit LevelEntry(LevelEnum level = LevelUnknown); + //! Function checks if context is valid + //! \param[in] level POWDER content level + //! \param[in] context POWDER context + bool isContextValid(LevelEnum level, + const DPL::OptionalString& context) const; + }; + + struct CategoryEntry + { + //! Levels entries for POWDER description + typedef std::vector LevelsContainer; + LevelsContainer levels; + //! Function checks if context is valid + //! \param[out] reason set if context invalid + //! \param[in] level POWDER content level + //! \param[in] context POWDER context + bool isCategoryValid(LevelEntry& reason, + LevelEnum level, + const DPL::OptionalString& context) const; + }; + + //! POWDER Category -> Category entry map for Widget + //! + //! nu Nudity + //! se Sex + //! vi Violence + //! la Potentially offensive language + //! dr Drug use + //! ga Gambling + //! ha Hate or harmful activities + //! ug Use of user-generated content + typedef std::map CategoryEntries; + + CategoryEntries categories; + + //! Age rating for widget + //! If Null not set + DPL::OptionalInt ageRating; +}; +} // namespace Powder + +namespace ChildProtection { + +//! Blacklist with forbidden URLs +//! It should be stored in WidgetDAO +typedef std::vector BlackList; + +//! Widget Child protection record +//! Record should be stored in WingetDAO +struct Record +{ + //! Child protection enabled + bool enabled; + explicit Record(bool enabled) : + enabled(enabled) + { + } +}; + +//! Powder processing +struct PowderRules +{ + //! Rule set by parent about forbidden category + //! Powder category + //! nu Nudity + //! se Sex + //! vi Violence + //! la Potentially offensive language + //! dr Drug use + //! ga Gambling + //! ha Hate or harmful activities + //! ug Use of user-generated content + //! Powder context + //! xa This material appears in an artistic conteaxt + //! xb This material appears in an educational context + //! xc This material appears in a medical context + //! xd This material appears in a sports context + //! xe This material appears in a violent context + struct CategoryRule + { + DPL::String category; + Powder::Description::LevelEnum level; + DPL::OptionalString context; + explicit CategoryRule(const DPL::String& category = DPL::String(), + Powder::Description::LevelEnum level = + Powder::Description::LevelUnknown, + const DPL::OptionalString& context = DPL::OptionalString()); + }; + + struct PowderResult + { + //! Reasoning outcome: part of POWDER description used to invalidate + Powder::Description::LevelEntry invalidDescription; + //! Reasoning outcome: rule set by parent not full filed by description + CategoryRule invalidRule; + + //! Reasoning outcome: type of invalidity + enum InvalidReason + { + InvalidRule, //!< One of rules was not fulfilled + InvalidAge, //!< Age is invalid + AgeRatingNotSet, //!< Age rating for widget is not set + Valid //!< Description valid + }; + InvalidReason reason; + explicit PowderResult(InvalidReason reason = Valid, + const Powder::Description::LevelEntry& invalidDescription = + Powder::Description::LevelEntry(), + const CategoryRule& invalidRule = CategoryRule()); + }; + + typedef std::pair ResultPair; + + //! Function checks if rule is fulfilled by description + //! \param[in] rule checked rule + //! \param[in] description + //! \retval true rule is valid + //! \retval false rule is invalid + ResultPair isRuleValidForDescription(const CategoryRule& rule, + const Powder::Description& description) const; + //! Function checks if age limit is fulfilled by description + //! \param[in] description + //! \retval true age is valid + //! \retval false age is invalid + ResultPair isAgeValidForDescription( + const Powder::Description& description) const; + + //! It is the maximum age rating valid for child + //! Uniform age is stored in WidgetDAO + DPL::OptionalInt ageLimit; + + //! Set to true if age rating is required + //! If ageLimit is not set value is ignored + bool isAgeRatingRequired; + + //! Set of rules configured by parent + //! Rules are stored in WidgetDAO and are uniform for all widgets + typedef std::vector RulesContainer; + RulesContainer rules; + + //! Function check if Widget description is valid for ChildProtection + //! configuration + //! \param description widget description + //! \retval true widget is valid + //! \retval false widget is invalid + ResultPair isDescriptionValid(const Powder::Description& description) + const; + + PowderRules() : + isAgeRatingRequired(false) + { + } +}; +} // namespace ChildProtection + +class PluginMetafileData +{ + public: + struct Feature + { + std::string m_name; + std::set m_deviceCapabilities; + + bool operator< (const Feature& obj) const + { + return m_name < obj.m_name; + } + }; + typedef std::set FeatureContainer; + + public: + + PluginMetafileData() + { + } + + std::string m_libraryName; + std::string m_featuresInstallURI; + std::string m_featuresKeyCN; + std::string m_featuresRootCN; + std::string m_featuresRootFingerprint; + + FeatureContainer m_featureContainer; +}; + +class PluginObjectsDAO +{ + public: + typedef std::set Objects; + typedef std::shared_ptr ObjectsPtr; + + public: + explicit PluginObjectsDAO() {} + + protected: + ObjectsPtr m_implemented; + ObjectsPtr m_dependent; +}; + +/** + * @brief Widget id describes web-runtime global widget identifier. + * + * Notice that only up to one widget can exist at the same time. + * DbWidgetHandle can be translated into corresponding WidgetModel by invoking + * FindWidgetModel routine. + */ +typedef int DbWidgetHandle; + +/** + * @brief Structure to hold the information of widget's size + */ +struct DbWidgetSize +{ + DPL::OptionalInt width; + DPL::OptionalInt height; + + DbWidgetSize(DPL::OptionalInt w = DPL::OptionalInt::Null, + DPL::OptionalInt h = DPL::OptionalInt::Null) : + width(w), + height(h) + { + } +}; + +inline bool operator ==(const DbWidgetSize &objA, const DbWidgetSize &objB) +{ + if (!objA.height || !objA.width || !objB.width || !objB.height) { + return false; + } else { + return *objA.height == *objB.height && *objA.width == *objB.width; + } +} + +/** + * Widget [G]lobal [U]nique [ID]entifier + * Orginated from appstore ID + */ +typedef DPL::OptionalString WidgetGUID; + +struct WidgetAccessInfo +{ + DPL::String strIRI; /* origin iri */ + bool bSubDomains; /* do we want access to subdomains ? */ + + bool operator ==(const WidgetAccessInfo& info) const + { + return info.strIRI == strIRI && + info.bSubDomains == bSubDomains; + } +}; + +typedef std::list WidgetAccessInfoList; + +typedef std::list WindowModeList; + +/** + * @brief Widget configuration parameter key + */ +typedef DPL::String WidgetParamKey; + +/** + * @brief Widget configuration parameter value + */ +typedef DPL::String WidgetParamValue; + +/** + * @brief A map of widget configuration parameters. + * + * Widget configuration parameters are read from database and are stored + * along with feature that they describe. + */ +typedef std::multimap WidgetParamMap; + +/** + * @brief Widget feature host information about possible javascript extensions + * that widget may use + * + * Widget features are declared in configuration file in widget installation + * package. Each declared special feature is contained in some wrt-plugin that + * declares to implement it. After widget launch wrt searches for proper plugin + * libraries and load needed features. + * + * Widget features can be required or optional. It is possible to start widget + * without missing feature. When required feature cannot be loaded widget will + * not start. + */ + +enum { + INVALID_PLUGIN_HANDLE = -1 +}; +typedef int DbPluginHandle; + +struct DbWidgetFeature +{ + DPL::String name; /// Feature name + bool required; /// Whether feature is required + DbPluginHandle pluginId; /// Plugin id that implement this feature + WidgetParamMap params; /// Widget's params + + DbWidgetFeature() : + required(false), + pluginId(INVALID_PLUGIN_HANDLE) + { + } +}; + +inline bool operator < (const DbWidgetFeature &objA, + const DbWidgetFeature &objB) +{ + return objA.name.compare(objB.name) < 0; +} + +inline bool operator==(const DbWidgetFeature &featureA, + const DbWidgetFeature &featureB) +{ + return featureA.name == featureB.name && + featureA.required == featureB.required && + featureA.pluginId == featureB.pluginId; +} + +/** + * @brief Default container for features list + */ +typedef std::multiset DbWidgetFeatureSet; + +/** + * @brief Default container with DbWidgetHandle's + */ +typedef std::list DbWidgetHandleList; + +/** + * @brief Widget specific type + * + * Widget type describes belowed in WAC, TIZEN WebApp + */ +enum AppType +{ + APP_TYPE_UNKNOWN = 0, // unknown + APP_TYPE_WAC20, // WAC 2.0 + APP_TYPE_TIZENWEBAPP, // slp webapp +}; + +class WidgetType +{ + public: + WidgetType() + :appType(APP_TYPE_UNKNOWN) + { + } + WidgetType(const AppType type) + :appType(type) + { + } + bool operator== (const AppType& other) const + { + return appType == other; + } + std::string getApptypeToString() + { + switch (appType) { +#define X(x) case x: return #x; + X(APP_TYPE_UNKNOWN) + X(APP_TYPE_WAC20) + X(APP_TYPE_TIZENWEBAPP) +#undef X + default: + return "UNKNOWN"; + } + } + + AppType appType; +}; + +} // namespace WrtDB + +struct WidgetSetting +{ + DPL::String settingName; + DPL::String settingValue; + + bool operator ==(const WidgetSetting& info) const + { + return (info.settingName == settingName && + info.settingValue == settingValue); + } + bool operator !=(const WidgetSetting& info) const + { + return (info.settingName != settingName || + info.settingValue != settingValue); + } +}; + +typedef std::list WidgetSettings; + +/** + * @brief Widget Application Service + * + * Application sercvice describes details of behaviour + * when widget receives aul bundle data. + */ +struct WidgetApplicationService +{ + public: + DPL::String src; /* start uri */ + DPL::String operation; /* service name */ + DPL::String scheme; /* scheme type*/ + DPL::String mime; /* mime type */ + + bool operator== (const WidgetApplicationService& other) const + { + return src == other.src && + operation == other.operation && + scheme == other.scheme && + mime == other.mime; + } +}; + +typedef std::list WidgetApplicationServiceList; +#endif /* WRT_SRC_CONFIGURATION_COMMON_DAO_TYPES_H_ */ diff --git a/tests/dpl/localization/mockup_include/dpl/wrt-dao-rw/widget_dao.h b/tests/dpl/localization/mockup_include/dpl/wrt-dao-rw/widget_dao.h new file mode 100644 index 0000000..aae9ce2 --- /dev/null +++ b/tests/dpl/localization/mockup_include/dpl/wrt-dao-rw/widget_dao.h @@ -0,0 +1,231 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This file contains the declaration of widget dao class. + * + * @file widget_dao_read_only.h + * @author Yang Jie (jie2.yang@samsung.com) + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @author Pawel Sikorski (p.sikorski@samsung.com) + * @version 1.0 + * @brief This file contains the declaration of widget dao + */ + +#ifndef _WRT_SRC_CONFIGURATION_WIDGET_DAO_READ_ONLY_H_ +#define _WRT_SRC_CONFIGURATION_WIDGET_DAO_READ_ONLY_H_ + +#include + +#include +#include +#include +#include + +#include +#include +#include + +#include +//#include "../wrt-dao-ro/common_dao_types.h" + +typedef DPL::OptionalString WidgetGUID; + +namespace ConfigParserData { + +struct Icon +{ + Icon(const DPL::String& src) : src(src) + { + } + DPL::String src; + DPL::OptionalInt width; + DPL::OptionalInt height; + bool operator==(const Icon&) const; + bool operator!=(const Icon&) const; + bool operator >(const Icon&) const; + bool operator>=(const Icon&) const; + bool operator <(const Icon&) const; + bool operator<=(const Icon&) const; +}; +} // namespace ConfigParserData +namespace WrtDB { + +typedef std::list StringList; + +struct WidgetLocalizedInfo +{ + DPL::OptionalString name; + DPL::OptionalString shortName; + DPL::OptionalString description; + DPL::OptionalString license; + DPL::OptionalString licenseHref; +}; + +typedef std::list LanguageTagList; + +class WidgetDAO +{ + public: + /** + * WidgetDAO Exception classes + */ + class Exception + { + public: + DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) + DECLARE_EXCEPTION_TYPE(Base, DatabaseError) + DECLARE_EXCEPTION_TYPE(Base, ReadOnlyProperty) + DECLARE_EXCEPTION_TYPE(Base, GUIDisNull) + DECLARE_EXCEPTION_TYPE(Base, UnexpectedEmptyResult) + DECLARE_EXCEPTION_TYPE(Base, WidgetNotExist) + DECLARE_EXCEPTION_TYPE(Base, AlreadyRegistered) + }; + + protected: + DbWidgetHandle m_widgetHandle; + + public: + struct WidgetLocalizedIconRow + { + int appId; + int iconId; + DPL::String widgetLocale; + }; + typedef std::list WidgetLocalizedIconList; + + struct WidgetIconRow + { + int iconId; + int appId; + DPL::String iconSrc; + DPL::OptionalInt iconWidth; + DPL::OptionalInt iconHeight; + }; + typedef std::list WidgetIconList; + + struct WidgetStartFileRow + { + int startFileId; + int appId; + DPL::String src; + }; + typedef std::list WidgetStartFileList; + + struct WidgetLocalizedStartFileRow + { + int startFileId; + int appId; + DPL::String widgetLocale; + DPL::String type; + DPL::String encoding; + }; + typedef std::list LocalizedStartFileList; + + + /** + * This is a constructor. + * + * @param[in] widgetHandle application id of widget. + */ + WidgetDAO(DbWidgetHandle widgetHandle) + : m_widgetHandle(widgetHandle) + {} + + /** + * Destructor + */ + virtual ~WidgetDAO(){} + + /** + * This method returns widget handle(m_widgetHandle). + * + * @return widget handle(m_widgetHandle). + * @exception WRT_CONF_ERR_EMDB_FAILURE - Fail to query DB table. + * @exception WRT_CONF_ERR_EMDB_NO_RECORD - Can not find matching records in DB table. + */ + DbWidgetHandle getHandle() const { return m_widgetHandle; } + DbWidgetHandle getHandle(const WidgetGUID GUID) const; + static DbWidgetHandle getHandle(const DPL::String pkgName); + + /** + * This method returns the root directory of widget resource. + * + * @return path name of root directory. + * @exception WRT_CONF_ERR_EMDB_FAILURE - Fail to query DB table. + * @exception WRT_CONF_ERR_EMDB_NO_RECORD - Can not find matching records in + * DB table. + */ + DPL::String getPath() const; + void setPath(const DPL::String &path) const; + + /** + * This method returns the defaultlocale for the widget. + * + * @return defaultlocale + * @exception WRT_CONF_ERR_EMDB_FAILURE - Fail to query DB table. + * @exception WRT_CONF_ERR_EMDB_NO_RECORD - Can not find matching records in + * DB table. + */ + DPL::OptionalString getDefaultlocale() const; + + /** + * This method returns list of localized icons files; + * + * @exception WRT_CONF_ERR_EMDB_FAILURE - Fail to query DB table. + * @exception WRT_CONF_ERR_EMDB_NO_RECORD - Can not find matching records in + * DB table. + */ + WidgetLocalizedIconList getLocalizedIconList() const; + + /** + * This method returns list of icons files; + * + * @exception WRT_CONF_ERR_EMDB_FAILURE - Fail to query DB table. + * @exception WRT_CONF_ERR_EMDB_NO_RECORD - Can not find matching records in + * DB table. + */ + WidgetIconList getIconList() const; + + /** + * This method returns list of localized start files; + * + * @exception WRT_CONF_ERR_EMDB_FAILURE - Fail to query DB table. + * @exception WRT_CONF_ERR_EMDB_NO_RECORD - Can not find matching records in + * DB table. + */ + LocalizedStartFileList getLocalizedStartFileList() const; + void setLocalizedStartFileList(const LocalizedStartFileList &list) const; + /** + * This method returns list of start files; + * + * @exception WRT_CONF_ERR_EMDB_FAILURE - Fail to query DB table. + * @exception WRT_CONF_ERR_EMDB_NO_RECORD - Can not find matching records in + * DB table. + */ + WidgetStartFileList getStartFileList() const; + void setStartFileList(const WidgetStartFileList &list) const; + + WidgetLocalizedInfo getLocalizedInfo(const DPL::String& languageTag) const; + protected: + static std::map s_startFileMap; + static std::map s_localizedStartFileMap; + static std::map s_pathMap; +}; + +} // namespace WrtDB + +#endif // _WRT_SRC_CONFIGURATION_WIDGET_DAO_READ_ONLY_H_ + diff --git a/tests/dpl/localization/mockup_src/widget_dao.cpp b/tests/dpl/localization/mockup_src/widget_dao.cpp new file mode 100644 index 0000000..d781c05 --- /dev/null +++ b/tests/dpl/localization/mockup_src/widget_dao.cpp @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This file contains the declaration of widget dao class. + * + * @file widget_dao_read_only.cpp + * @author Yang Jie (jie2.yang@samsung.com) + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @author Pawel Sikorski (p.sikorski@samsung.com) + * @version 1.0 + * @brief This file contains the declaration of widget dao + */ + +//#include "../mockup_include/dpl/wrt-dao-rw/widget_dao.h" +#include + +#include +#include +#include +#include + +namespace WrtDB { + +std::map WidgetDAO::s_startFileMap; +std::map WidgetDAO::s_localizedStartFileMap; +std::map WidgetDAO::s_pathMap; + +DbWidgetHandle WidgetDAO::getHandle(const WidgetGUID /* GUID */) const +{ + LogError("Not impleneted!"); + return 0; +} + +DbWidgetHandle WidgetDAO::getHandle(const DPL::String /* pkgName */) +{ + LogError("Not implemented!"); + return 0; +} + +DPL::String WidgetDAO::getPath() const +{ + return s_pathMap[m_widgetHandle]; +} + +void WidgetDAO::setPath(const DPL::String &path) const +{ + s_pathMap[m_widgetHandle] = path; +} + +WidgetLocalizedInfo + WidgetDAO::getLocalizedInfo(const DPL::String& /* languageTag */) + const +{ + LogError("Not implemented!"); + return WidgetLocalizedInfo(); +} + +DPL::OptionalString WidgetDAO::getDefaultlocale() const +{ + LogError("Not implemented!"); + return DPL::OptionalString(); +} + +WidgetDAO::WidgetLocalizedIconList WidgetDAO::getLocalizedIconList() const +{ + LogError("Not implemented!"); + return WidgetLocalizedIconList(); +} + +WidgetDAO::WidgetIconList WidgetDAO::getIconList() const +{ + LogError("Not implemented!"); + return WidgetIconList(); +} + +WidgetDAO::LocalizedStartFileList WidgetDAO::getLocalizedStartFileList() const +{ + return s_localizedStartFileMap[m_widgetHandle]; +} + +void WidgetDAO::setLocalizedStartFileList(const LocalizedStartFileList &list) const { + s_localizedStartFileMap[m_widgetHandle] = list; +} + +WidgetDAO::WidgetStartFileList WidgetDAO::getStartFileList() const +{ + return s_startFileMap[m_widgetHandle]; +} + +void WidgetDAO::setStartFileList(const WidgetStartFileList &list) const +{ + s_startFileMap[m_widgetHandle] = list; +} + +} // namespace WrtDB diff --git a/tests/dpl/localization/test_localization.cpp b/tests/dpl/localization/test_localization.cpp new file mode 100644 index 0000000..42ffe3a --- /dev/null +++ b/tests/dpl/localization/test_localization.cpp @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file main.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of main + */ +#include + +int main(int argc, char *argv[]) +{ + return DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, argv); +} + diff --git a/tests/dpl/localization/test_suite01.cpp b/tests/dpl/localization/test_suite01.cpp new file mode 100644 index 0000000..b752bf5 --- /dev/null +++ b/tests/dpl/localization/test_suite01.cpp @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This file contains the declaration of widget dao class. + * + * @file test_suite01.cpp + * @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) + * @version 1.0 + * @brief + */ + +#include +#include + +//#include "mockup_include/dpl/wrt-dao-rw/widget_dao.h" +#include +#include + +namespace { + +WrtDB::LanguageTagList generateLanguageTags(){ + WrtDB::LanguageTagList tags; + tags.push_back(L"pl-pl"); + tags.push_back(L"en-en"); + tags.push_back(L"pl-en"); + return tags; +} + +static const WrtDB::LanguageTagList languageTags = generateLanguageTags(); +static const DPL::String widget1Path = L"/opt/share/widget/tests/localization/widget1/"; +static const DPL::String widget2Path = L"/opt/share/widget/tests/localization/widget2/"; + +} // anonymous namespace + +RUNNER_TEST(test01_getFilePathInWidgetPackageFromUrl){ + const int widgetHandle = 1; + WrtDB::WidgetDAO dao(widgetHandle); + //dao.setPath(widget1Path); + + auto result = W3CFileLocalization::getFilePathInWidgetPackageFromUrl( + widgetHandle, + languageTags, + L"widget://one"); + + RUNNER_ASSERT(*result == L"/opt/share/widget/tests/localization/widget1/locales/pl-en/one"); +} + +RUNNER_TEST(test02_getFilePathInWidgetPackageFromUrl){ + const int widgetHandle = 2; + WrtDB::WidgetDAO dao(widgetHandle); + //dao.setPath(widget2Path); + + auto result = W3CFileLocalization::getFilePathInWidgetPackageFromUrl( + widgetHandle, + languageTags, + L"widget://one"); + + RUNNER_ASSERT(*result == L"/opt/share/widget/tests/localization/widget2/locales/pl-en/one"); +} + +RUNNER_TEST(test03_getFilePathInWidgetPackageFromUrl){ + const int widgetHandle = 2; + WrtDB::WidgetDAO dao(widgetHandle); + //dao.setPath(widget2Path); + + auto result = W3CFileLocalization::getFilePathInWidgetPackageFromUrl( + widgetHandle, + languageTags, + L"widget://two"); + + RUNNER_ASSERT(*result == L"/opt/share/widget/tests/localization/widget2/locales/en-en/two"); +} + +RUNNER_TEST(test04_getFilePathInWidgetPackage){ + const int widgetHandle = 1; + WrtDB::WidgetDAO dao(widgetHandle); + //dao.setPath(widget1Path); + + auto result = W3CFileLocalization::getFilePathInWidgetPackage( + widgetHandle, + languageTags, + L"one"); + + RUNNER_ASSERT(*result == L"locales/pl-en/one"); +} + +RUNNER_TEST(test05_getFilePathInWidgetPackage){ + const int widgetHandle = 2; + WrtDB::WidgetDAO dao(widgetHandle); + //dao.setPath(widget2Path); + + auto result = W3CFileLocalization::getFilePathInWidgetPackage( + widgetHandle, + languageTags, + L"two"); + + RUNNER_ASSERT(*result == L"locales/en-en/two"); +} + diff --git a/tests/dpl/unused/test_caller.cpp b/tests/dpl/unused/test_caller.cpp new file mode 100644 index 0000000..17de24b --- /dev/null +++ b/tests/dpl/unused/test_caller.cpp @@ -0,0 +1,128 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file test_address.cpp + * @author Tomasz Swierczek (t.swierczek@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of caller tests + */ + +#include +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL) + +// test stream class +class BinaryStream : public DPL::IStream { + public: + virtual void Read(size_t num, void * bytes) + { + for (unsigned i = 0; i < num; ++i) { + ((unsigned char*)bytes)[i] = data[i + readPosition]; + } + readPosition += num; + } + virtual void Write(size_t num, const void * bytes) + { + for (unsigned i = 0; i < num; ++i) { + data.push_back(((unsigned char*)bytes)[i]); + } + } + BinaryStream() + { + readPosition = 0; + } + virtual ~BinaryStream(){}; + + private: + std::vector data; + unsigned readPosition; +}; + +static int return_func(int a, bool b) +{ + if (b) { + return a; + } else { + return 0; + } +} + +static int called = 0; + +static void void_func(int a) +{ + called = a; +} + +static struct VoidDelegate +{ + void operator()(int a) + { + called = a; + } +} voidDelegate; + +static struct ReturnDelegate +{ + int operator()(int a) + { + return a; + } +} returnDelegate; + +RUNNER_TEST(Caller_function_void) +{ + int a = 23; + BinaryStream stream; + DPL::Serialization::Serialize(stream,a); + called = 0; + DPL::Caller::Call(stream,void_func); + RUNNER_ASSERT(called == a); +} + +RUNNER_TEST(Caller_function_return) +{ + int a = 23; + bool b = true; + BinaryStream stream; + DPL::Serialization::Serialize(stream,a); + DPL::Serialization::Serialize(stream,b); + int result = DPL::Caller::Call(stream,return_func); + RUNNER_ASSERT(result == a); +} + +RUNNER_TEST(Caller_delegate_void) +{ + int a = 23; + BinaryStream stream; + called = 0; + DPL::Serialization::Serialize(stream,a); + DPL::Caller::CallDelegate(stream,voidDelegate); + RUNNER_ASSERT(called == a); +} + +RUNNER_TEST(Caller_delegate_return) +{ + int a = 23; + BinaryStream stream; + called = 0; + DPL::Serialization::Serialize(stream,a); + int result = 0; + DPL::Caller::CallDelegate(stream,returnDelegate,result); + RUNNER_ASSERT(result == a); +} diff --git a/tests/dpl/unused/test_crypto_hash.cpp b/tests/dpl/unused/test_crypto_hash.cpp new file mode 100644 index 0000000..2c0accb --- /dev/null +++ b/tests/dpl/unused/test_crypto_hash.cpp @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file test_crypto_hash.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of test crypto hash + */ +#include +#include +RUNNER_TEST_GROUP_INIT(DPL) + +#define TEST_CRYPTO_HASH(Class, Input, Output) \ + Class crypto; \ + crypto.Append(Input); \ + crypto.Finish(); \ + RUNNER_ASSERT(crypto.ToString() == Output); + +RUNNER_TEST(CryptoHash_MD2) +{ + TEST_CRYPTO_HASH(DPL::Crypto::Hash::MD2, "sample_input_string", "c9f26439c9882cccc98467dbdf07b1fc"); +} + +RUNNER_TEST(CryptoHash_MD4) +{ + TEST_CRYPTO_HASH(DPL::Crypto::Hash::MD4, "sample_input_string", "8cd0720f7ec98c8e5f008afb54054677"); +} + +RUNNER_TEST(CryptoHash_MD5) +{ + TEST_CRYPTO_HASH(DPL::Crypto::Hash::MD5, "sample_input_string", "eb7ae4f28fecbd1fd777d9b7495fc8ec"); +} + +RUNNER_TEST(CryptoHash_SHA) +{ + TEST_CRYPTO_HASH(DPL::Crypto::Hash::SHA, "sample_input_string", "0a5725f3586616a4049730f3ba14c8aeda79ab21"); +} + +RUNNER_TEST(CryptoHash_SHA1) +{ + TEST_CRYPTO_HASH(DPL::Crypto::Hash::SHA1, "sample_input_string", "be0ed9040af0c2b772b2dd0776f6966b5f4d1206"); +} + +RUNNER_TEST(CryptoHash_DSS) +{ + TEST_CRYPTO_HASH(DPL::Crypto::Hash::DSS, "sample_input_string", "be0ed9040af0c2b772b2dd0776f6966b5f4d1206"); +} + +RUNNER_TEST(CryptoHash_DSS1) +{ + TEST_CRYPTO_HASH(DPL::Crypto::Hash::DSS1, "sample_input_string", "be0ed9040af0c2b772b2dd0776f6966b5f4d1206"); +} + +RUNNER_TEST(CryptoHash_ECDSA) +{ + TEST_CRYPTO_HASH(DPL::Crypto::Hash::ECDSA, "sample_input_string", "be0ed9040af0c2b772b2dd0776f6966b5f4d1206"); +} + +RUNNER_TEST(CryptoHash_SHA224) +{ + TEST_CRYPTO_HASH(DPL::Crypto::Hash::SHA224, "sample_input_string", "d4dde2370eb869f6e790133b94d58e45417392b9d899af883a274011"); +} + +RUNNER_TEST(CryptoHash_SHA256) +{ + TEST_CRYPTO_HASH(DPL::Crypto::Hash::SHA256, "sample_input_string", "a470ec7c783ac51f9eb1772132e6bde1a053bbc81650719dd0ac62ecd93caf12"); +} + +RUNNER_TEST(CryptoHash_SHA384) +{ + TEST_CRYPTO_HASH(DPL::Crypto::Hash::SHA384, "sample_input_string", "63d8bfa95c95c6906d1816965431c065278a655c60f786c9b246c1f73ba7ac557007f5064ba54ebd3a1988e6f37baa97"); +} + +RUNNER_TEST(CryptoHash_SHA512) +{ + TEST_CRYPTO_HASH(DPL::Crypto::Hash::SHA512, "sample_input_string", "799317a140741937d9e5d8dbf9d3045d2c220de5ac33b3d5897acf873291ed14379eb15ef406d2284313d40edb0e01affac8efeb01cb47c2042e3e62a4a83d7d"); +} diff --git a/tests/dpl/unused/test_message_queue.cpp b/tests/dpl/unused/test_message_queue.cpp new file mode 100644 index 0000000..6340b57 --- /dev/null +++ b/tests/dpl/unused/test_message_queue.cpp @@ -0,0 +1,158 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file test_message_queue.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of message queue tests + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +DECLARE_GENERIC_EVENT_0(QuitEvent) + +class QuitController + : public DPL::Controller::Type>, + public DPL::ApplicationExt +{ +public: + QuitController() : DPL::ApplicationExt(1, NULL, "test-app") { Touch(); } + +protected: + virtual void OnEventReceived(const QuitEvent &) { Quit(); } +}; + +RUNNER_TEST_GROUP_INIT(DPL) + +class CopyThread + : public DPL::Thread +{ +private: + bool m_success; + DPL::AbstractWaitableInput *m_input; + DPL::AbstractWaitableOutput *m_output; + std::size_t m_dataSize; + +public: + CopyThread(DPL::AbstractWaitableInput *input, + DPL::AbstractWaitableOutput *output, + std::size_t dataSize) + : m_success(true), + m_input(input), + m_output(output), + m_dataSize(dataSize) + { + LogInfo("Thread created"); + } + +protected: + virtual int ThreadEntry() + { + LogInfo("Entering copy thread"); + + Try + { + DPL::Copy(m_input, m_output, m_dataSize); + } + Catch (DPL::CopyFailed) + { + m_success = false; + + LogWarning("Copy failed!"); + return 0; + } + + LogInfo("Copy finished"); + return 0; + } +}; + +inline std::string BinaryQueueToString(const DPL::BinaryQueue &queue) +{ + char *buffer = new char[queue.Size()]; + queue.Flatten(buffer, queue.Size()); + std::string result = std::string(buffer, buffer + queue.Size()); + delete [] buffer; + return result; +} + +RUNNER_TEST(MessageQueue_DoubleCopy) +{ + DPL::BinaryQueue dataA; + DPL::MessageQueue dataB("/test_mqueue_dataB", true, false, 0660, true); + DPL::MessageQueue dataC("/test_mqueue_dataC", true, false, 0660, true); + DPL::BinaryQueue dataD; + + DPL::AbstractWaitableInputAdapter dataAdapterA(&dataA); + DPL::AbstractWaitableOutputAdapter dataAdapterD(&dataD); + + const std::string testData = + "Lorem ipsum dolor sit amet, consectetur adipiscing elit." + "Cras elementum venenatis velit, sit amet vehicula odio gravida a." + "Curabitur id nibh id ante adipiscing sollicitudin." + "Maecenas in tellus vel augue vehicula pharetra hendrerit cursus est." + "" + "Ut malesuada quam porttitor dui euismod lacinia." + "Phasellus quis lectus sed lectus dictum tincidunt et vitae leo." + "Fusce id est massa, condimentum bibendum urna." + "Donec venenatis quam eget sapien vulputate egestas." + "Maecenas scelerisque lorem a neque molestie a varius erat condimentum." + "Maecenas varius hendrerit ligula, sed iaculis justo pretium id." + "Nunc sit amet nisl vitae justo tristique suscipit id eget tortor." + "" + "Pellentesque sollicitudin nulla at metus dapibus tincidunt." + "Integer consequat justo eget dui imperdiet iaculis." + "Sed vestibulum ipsum vitae libero accumsan non molestie metus adipiscing." + "" + "Vivamus quis dui enim, in blandit urna." + "In imperdiet lacus at orci elementum a scelerisque dui blandit." + "Donec vulputate enim metus, eget convallis ante." + "Etiam mollis enim eget eros pulvinar nec sagittis justo fermentum." + "" + "Vestibulum sed nunc eu leo lobortis ultrices." + "Nullam placerat nulla et est blandit nec interdum nunc pulvinar." + "Vivamus a lectus eget dui fermentum hendrerit."; + + QuitController quitter; + quitter.PostTimedEvent(QuitEvent(), 1.0); + + CopyThread threadA(&dataAdapterA, &dataB, testData.size()); + CopyThread threadB(&dataB, &dataC, testData.size()); + CopyThread threadC(&dataC, &dataAdapterD, testData.size()); + + dataA.AppendCopy(testData.c_str(), testData.size()); + + threadA.Run(); + threadB.Run(); + threadC.Run(); + + quitter.Exec(); + + threadA.Quit(); + threadB.Quit(); + threadC.Quit(); + + // Now, test data should be in dataD + RUNNER_ASSERT(BinaryQueueToString(dataD) == testData); +} diff --git a/tests/dpl/unused/test_shm.cpp b/tests/dpl/unused/test_shm.cpp new file mode 100644 index 0000000..e62a5ac --- /dev/null +++ b/tests/dpl/unused/test_shm.cpp @@ -0,0 +1,1658 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file test_shm.h + * @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) + * @version 1.0 + * @brief Implementation file for test cases for shared data framework + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL) + +using namespace DPL; + +namespace { +const SharedMemory::Key SHM_KEY = 12345; +const char* SEM_NAME = "/wrt_engine_shared_object_semaphore"; +const size_t VERSION = 1; + +const size_t MAX_THREADS = 10; +const size_t TEST_AND_SET_REPEATS = 100; + +const size_t SHARED_PROP_REPEATS = 3; + +const size_t SINGLETON_TEST_REPEATS = 3; + +// maximum random delay in singleton listener addition/removal +const size_t MAX_SINGLETON_LISTENER_DELAY = 50; + +const int SINGLE_PROCESS_REPEATS = 50; + +/* + * 5 seconds expected timeout for waitable events + * 30 seconds unexpected timeout for waitable events + * We don't want to block tests + */ +const size_t EXPECTED_WAITABLE_TIMEOUT = 5*1000; +const size_t UNEXPECTED_WAITABLE_TIMEOUT = 30*1000; + +bool g_enumTestCorrect = false; +bool g_enumTestIncorrect = false; +size_t g_delegateCalls = 0; + +void Wait(DPL::WaitableEvent& event, bool expectedTimeout = false) +{ + LogDebug("WaitForSingleHandle..."); + DPL::WaitableHandleIndexList list = DPL::WaitForSingleHandle( + event.GetHandle(), + expectedTimeout ? + EXPECTED_WAITABLE_TIMEOUT : UNEXPECTED_WAITABLE_TIMEOUT); + if (list.size() == 0) { + LogDebug("...timeout."); + } + else { + LogDebug("...signaled."); + event.Reset(); + } + + if (expectedTimeout) { + RUNNER_ASSERT(list.size() == 0); + } else { + RUNNER_ASSERT(list.size() == 1); + } +} + +void RemoveIpcs() +{ + Try { + SharedMemory::Remove(SHM_KEY); + } + Catch(SharedMemory::Exception::RemoveFailed) { + // ignore + } + + Try { + DPL::Semaphore::Remove(SEM_NAME); + } + Catch(DPL::Semaphore::Exception::RemoveFailed) { + // ignore + } +} + +typedef DPL::TypeListDecl::Type TestTypeList; +typedef DPL::TypeListDecl::Type TestTypeList2; +typedef DPL::TypeListDecl::Type TestTypeList3; + +typedef SharedObject TestSharedObject; +typedef SharedObject TestSharedObject2; +typedef SharedObject TestSharedObject3; + +typedef std::shared_ptr TestSharedObjectPtr; + +const int INIT_EVENT = 0; +const int DESTROY_EVENT = 1; + +int g_values[TestTypeList::Size]; + +/* + * helper listening controller + */ +template +class ListeningController : + public DPL::Controller::Type> +{ + public: + explicit ListeningController(DPL::WaitableEvent* waitable); + ~ListeningController(); + + virtual void OnEventReceived(const int &event); + + virtual void OnEvent(const int /*event*/) {} + + protected: + std::shared_ptr m_so; + DPL::Thread m_thread; + DPL::WaitableEvent* m_waitable; +}; + +template +ListeningController::ListeningController( + DPL::WaitableEvent* waitable) : + m_waitable(waitable) +{ + Touch(); + m_thread.Run(); + SwitchToThread(&m_thread); + PostEvent(INIT_EVENT); +} + +template +ListeningController::~ListeningController() +{ + m_thread.Quit(); +} + +template +void ListeningController::OnEventReceived(const int& event) +{ + if (event == INIT_EVENT) { + m_so = SharedObjectFactory::Create(SHM_KEY, SEM_NAME); + OnEvent(event); + m_waitable->Signal(); + } + else if (event == DESTROY_EVENT) { + LogDebug("Destroying shared object"); + OnEvent(event); + + // deregister, destroy ad notify main thread + m_so.Reset(); + LogDebug("4"); + m_waitable->Signal(); + LogDebug("5"); + } + else { + OnEvent(event); + } +} + +typedef DPL::TypeListDecl::Type SharedTypeList; + +class TestSharedObject4; +typedef std::shared_ptr TestSharedObject4Ptr; + +class TestSharedObject4 : public SharedObject +{ + public: + enum + { + SIZE_T, + BOOLEAN + }; + + static TestSharedObject4Ptr Create() + { + return SharedObjectFactory::Create(SHM_KEY, SEM_NAME); + } + + ~TestSharedObject4() + { + LogDebug("dtor"); + } + + protected: + explicit TestSharedObject4(const std::string& semaphore) : + SharedObject(semaphore) + { + } + + private: + void Init() + { + SetPropertyInternal(false); + } + friend class SharedObjectFactory; +}; + + + +} // anonymus namespace + +////////////////////////////////////////////// + +RUNNER_TEST(SharedMemory_002_AccessByType) +{ + RemoveIpcs(); + + SharedData str; + + // access by type + str.Embedded<0, int>::value = 4; + str.Embedded<1, int>::value = 5; + str.Embedded<2, char>::value = 'd'; + str.Embedded<3, int[64]>::value[0] = 1; + str.Embedded<3, int[64]>::value[1] = 20; + + RUNNER_ASSERT((str.Embedded<0, int>::value) == 4); + RUNNER_ASSERT((str.Embedded<1, int>::value) == 5); + RUNNER_ASSERT((str.Embedded<2, char>::value) == 'd'); + RUNNER_ASSERT((str.Embedded<3, int[64]>::value[0]) == 1); + RUNNER_ASSERT((str.Embedded<3, int[64]>::value[1]) == 20); +} + +////////////////////////////////////////////// + +RUNNER_TEST(SharedMemory_003_AccessByIndex) +{ + RemoveIpcs(); + + SharedData str; + // access by enum + str.Embedded<0, TestTypeList::Element<0>::Type>::value = 4; + str.Embedded<1, TestTypeList::Element<1>::Type>::value = 5; + str.Embedded<2, TestTypeList::Element<2>::Type>::value = 'd'; + str.Embedded<3, TestTypeList::Element<3>::Type>::value[0] = 1; + str.Embedded<3, TestTypeList::Element<3>::Type>::value[1] = 20; + + RUNNER_ASSERT( + (str.Embedded<0, TestTypeList::Element<0>::Type>::value) == 4); + RUNNER_ASSERT( + (str.Embedded<1, TestTypeList::Element<1>::Type>::value) == 5); + RUNNER_ASSERT( + (str.Embedded<2, TestTypeList::Element<2>::Type>::value) == 'd'); + RUNNER_ASSERT( + (str.Embedded<3, TestTypeList::Element<3>::Type>::value[0]) == 1); + RUNNER_ASSERT( + (str.Embedded<3, TestTypeList::Element<3>::Type>::value[1]) == 20); +} + +////////////////////////////////////////////// + +RUNNER_TEST(SharedMemory_004_SimplifiedAccess) +{ + RemoveIpcs(); + + SharedData str; + + // access via PropertyRef + str.PropertyRef<1>() = 3; + RUNNER_ASSERT(str.PropertyRef<1>() == 3); + + int (&array)[64] = str.PropertyRef<3>(); + array[0] = 2; + RUNNER_ASSERT(str.PropertyRef<3>()[0] == 2); + + str.PropertyRef<3>()[1] = 19; + RUNNER_ASSERT(str.PropertyRef<3>()[1] == 19); + + // access via macro + str.SHARED_PROPERTY(0) = 2; + RUNNER_ASSERT(str.SHARED_PROPERTY(0) == 2); + + str.SHARED_PROPERTY(2) = 'c'; + RUNNER_ASSERT(str.SHARED_PROPERTY(2) == 'c'); + + str.SHARED_PROPERTY(3)[2] = 10; + RUNNER_ASSERT(str.SHARED_PROPERTY(3)[2] == 10); + + // old style check + RUNNER_ASSERT((str.Embedded<0, int>::value) == 2); + RUNNER_ASSERT((str.Embedded<1, int>::value) == 3); + RUNNER_ASSERT((str.Embedded<2, char>::value) == 'c'); + RUNNER_ASSERT((str.Embedded<3, int[64]>::value[0]) == 2); + RUNNER_ASSERT((str.Embedded<3, int[64]>::value[1]) == 19); + RUNNER_ASSERT((str.Embedded<3, int[64]>::value[2]) == 10); +} + +////////////////////////////////////////////// + +struct SharedStruct +{ + int a; + int b; + char c; + int d[64]; +}; + +typedef std::shared_ptr > SharedStructPtr; + +RUNNER_TEST(SharedMemory_010_BaseShmTest) +{ + RemoveIpcs(); + + typedef std::unique_ptr SharedMemoryPtr; + + // write + SharedMemoryPtr shm; + Try { + shm.Reset(SharedMemory::Create(SHM_KEY, false)); + } + Catch (SharedMemory::Exception::NotFound) { + shm.Reset(SharedMemory::Create(SHM_KEY, true, true)); + } + + SharedStructPtr str = shm->Attach(); + + str->Data()->a = 1; + str->Data()->b = 2; + str->Data()->c = '3'; + str->Data()->d[0] = 4; + str->Data()->d[1] = 5; + + // read + SharedMemoryPtr shm2; + Try { + shm2.Reset(SharedMemory::Create(SHM_KEY, false)); + } + Catch (SharedMemory::Exception::NotFound) { + shm2.Reset(SharedMemory::Create(SHM_KEY, true, true)); + } + + SharedStructPtr str2 = shm2->Attach(); + SharedStructPtr str3 = shm2->Attach(); + + RUNNER_ASSERT(str2->Data()->a == 1); + RUNNER_ASSERT(str2->Data()->b == 2); + RUNNER_ASSERT(str2->Data()->c == '3'); + RUNNER_ASSERT(str2->Data()->d[0] == 4); + RUNNER_ASSERT(str2->Data()->d[1] == 5); + + RUNNER_ASSERT(str3->Data()->a == 1); + RUNNER_ASSERT(str3->Data()->b == 2); + RUNNER_ASSERT(str3->Data()->c == '3'); + RUNNER_ASSERT(str3->Data()->d[0] == 4); + RUNNER_ASSERT(str3->Data()->d[1] == 5); + + str2->Data()->b = 4; + str2->Data()->c = 'c'; + str2->Data()->d[0] = 0; + RUNNER_ASSERT(str3->Data()->a == 1); + RUNNER_ASSERT(str3->Data()->b == 4); + RUNNER_ASSERT(str3->Data()->c == 'c'); + RUNNER_ASSERT(str3->Data()->d[0] == 0); + RUNNER_ASSERT(str3->Data()->d[1] == 5); +} + +////////////////////////////////////////////// + +RUNNER_TEST(SharedMemory_020_SharedObjectTest) +{ + RemoveIpcs(); + + typedef SharedObject MySharedObj; + + MySharedObj::Ptr so = + SharedObjectFactory::Create(SHM_KEY, SEM_NAME); + + RUNNER_ASSERT((so->GetProperty<0, size_t>()) == 0); + so->SetProperty<0,size_t>(4); + RUNNER_ASSERT((so->GetProperty<0, size_t>()) == 4); +} + +////////////////////////////////////////////// + +class InitTestSharedObject : public TestSharedObject +{ + protected: + explicit InitTestSharedObject(const std::string& semaphore) : + TestSharedObject(semaphore) {} + + virtual void Init(); // from SharedObject + + private: + friend class SharedObjectFactory; +}; + +void InitTestSharedObject::Init() +{ + SetPropertyInternal<0>(1); + SetPropertyInternal<1>(2); + SetPropertyInternal<2>('c'); +} + +RUNNER_TEST(SharedMemory_021_InitTest) +{ + RemoveIpcs(); // we need non existing shm + + std::shared_ptr sho = + SharedObjectFactory::Create( + SHM_KEY, SEM_NAME); + RUNNER_ASSERT((sho->GetProperty<0,int>()) == 1); + RUNNER_ASSERT((sho->GetProperty<1,int>()) == 2); + RUNNER_ASSERT((sho->GetProperty<2,char>()) == 'c'); +} + +////////////////////////////////////////////// + +class VersionTestSO1 : public TestSharedObject +{ + protected: + explicit VersionTestSO1(const std::string& semaphore) : + TestSharedObject(semaphore) {} + + virtual SizeType GetVersion() const { return 1; } // from SharedObject + + private: + friend class SharedObjectFactory; +}; + +class VersionTestSO2 : public TestSharedObject +{ + protected: + explicit VersionTestSO2(const std::string& semaphore) : + TestSharedObject(semaphore) {} + + virtual SizeType GetVersion() const { return 2; } // from SharedObject + + private: + friend class SharedObjectFactory; +}; + +RUNNER_TEST(SharedMemory_022_InvalidVersionTest) +{ + RemoveIpcs(); // we need non existing shm + + std::shared_ptr sho = + SharedObjectFactory::Create(SHM_KEY, SEM_NAME); + + Try { + std::shared_ptr sho2 = + SharedObjectFactory::Create(SHM_KEY, SEM_NAME); + + RUNNER_ASSERT_MSG(false, "Invalid shm version has been accepted"); + } + Catch(SharedObjectBase::Exception::InvalidVersion) { + RUNNER_ASSERT(true); + } +} + +////////////////////////////////////////////// + +RUNNER_TEST(SharedMemory_023_InvalidSizeTest) +{ + RemoveIpcs(); // we need non existing shm + + typedef SharedObject SO1; + typedef SharedObject SO2; + + SO1::Ptr sho = SharedObjectFactory::Create(SHM_KEY, SEM_NAME); + + Try { + SO2::Ptr sho2 = SharedObjectFactory::Create(SHM_KEY, SEM_NAME); + + RUNNER_ASSERT_MSG(false, "Invalid shm size has been accepted"); + } + Catch(SharedObjectBase::Exception::InvalidSize) { + RUNNER_ASSERT(true); + } +} + +////////////////////////////////////////////// + +class MagicTestSO1 : public TestSharedObject +{ + protected: + explicit MagicTestSO1(const std::string& semaphore) : + TestSharedObject(semaphore) {} + + // from SharedObject + virtual MagicType GetMagicNumber() const { return 661; } + + private: + friend class SharedObjectFactory; +}; + +class MagicTestSO2 : public TestSharedObject +{ + protected: + explicit MagicTestSO2(const std::string& semaphore) : + TestSharedObject(semaphore) {} + + // from SharedObject + virtual MagicType GetMagicNumber() const { return 662; } + + private: + friend class SharedObjectFactory; +}; + +RUNNER_TEST(SharedMemory_024_InvalidMagicTest) +{ + RemoveIpcs(); // we need non existing shm + + std::shared_ptr sho = + SharedObjectFactory::Create(SHM_KEY, SEM_NAME); + + Try { + std::shared_ptr sho2 = + SharedObjectFactory::Create(SHM_KEY, SEM_NAME); + + RUNNER_ASSERT_MSG(false, "Invalid shm magic number has been accepted"); + } + Catch(SharedObjectBase::Exception::InvalidMagicNumber) { + RUNNER_ASSERT(true); + } +} + +////////////////////////////////////////////// + +/* + * Listening shared object + */ +class EnumTestSO1 : public TestSharedObject +{ + public: + void SetWaitable(DPL::WaitableEvent* waitable) { m_waitable = waitable; } + + protected: + explicit EnumTestSO1(const std::string& semaphore) : + TestSharedObject(semaphore) {} + + virtual void PropertyChanged(size_t propertyEnum); + + private: + friend class SharedObjectFactory; + + DPL::WaitableEvent* m_waitable; +}; + +void EnumTestSO1::PropertyChanged(size_t propertyEnum) +{ + if (propertyEnum == 1) + { + LogDebug("Property enum " << propertyEnum << " correctly set"); + g_enumTestCorrect = true; + } + if (propertyEnum == 4) + { + // This is bad. We only have 4 types + LogError("Property enum " << propertyEnum << " should be skipped"); + g_enumTestIncorrect = true; + } + // confirm property change notification + m_waitable->Signal(); +} + +class EnumController : public ListeningController +{ + public: + explicit EnumController(DPL::WaitableEvent* waitable) : + ListeningController(waitable) {} + + virtual void OnEvent(const int event); +}; + +void EnumController::OnEvent(const int event) +{ + if (event == INIT_EVENT) { + m_so->SetWaitable(m_waitable); + } +} + +/* + * Writing shared object with correct size but different number of types + */ +class EnumTestSO2 : public TestSharedObject3 +{ + protected: + explicit EnumTestSO2(const std::string& semaphore) : + TestSharedObject3(semaphore) {} + + private: + friend class SharedObjectFactory; +}; + +RUNNER_TEST(SharedMemory_025_InvalidEnumTest) +{ + RemoveIpcs(); // we need non existing shm + + g_enumTestCorrect = false; + g_enumTestIncorrect = false; + + DPL::WaitableEvent waitable; + + // create listening controller and wait until it registers + EnumController controller(&waitable); + Wait(waitable); + LogDebug("Listening controller created"); + + // create writing shared object + std::shared_ptr sho2 = + SharedObjectFactory::Create(SHM_KEY, SEM_NAME); + DPL::WaitableHandleIndexList list; + + // write property and wait for confirmation + sho2->SetProperty<1>(2); + Wait(waitable); + + // write incorrect property and wait for confirmation + // we expect timeout + sho2->SetProperty<4>(2); + Wait(waitable, true); + + // schedule listener deregistration and wait for confirmation + controller.PostEvent(DESTROY_EVENT); + Wait(waitable); + + // check results + RUNNER_ASSERT(g_enumTestCorrect == true); + RUNNER_ASSERT(g_enumTestIncorrect == false); +} + +////////////////////////////////////////////// + +class MultiThreadSO : public TestSharedObject +{ + public: + void TestAndSetProperty(); + + protected: + explicit MultiThreadSO(const std::string& semaphore) : + TestSharedObject(semaphore) {} + + private: + friend class SharedObjectFactory; +}; + +void MultiThreadSO::TestAndSetProperty() +{ + ScopedFlaggedLock lock(*this); + + int value = PropertyRef<0,int>(); + DPL::Thread::MicroSleep(100); + SetPropertyInternal<0>(value+1); +} + +class ShmController : public ListeningController +{ + public: + explicit ShmController(DPL::WaitableEvent* event) : + ListeningController(event), m_counter(0) + {} + + virtual void OnEventReceived(const int& event); + + private: + size_t m_counter; +}; + +void ShmController::OnEventReceived(const int& event) +{ + if (event == INIT_EVENT) { + m_so = SharedObjectFactory::Create(SHM_KEY, SEM_NAME); + PostEvent(2); + } + else if (event == DESTROY_EVENT) { + LogDebug("Destroying shared object"); + // deregister, destroy ad notify main thread + m_so.Reset(); + m_waitable->Signal(); + } + else if (event == 2){ + m_so->TestAndSetProperty(); + m_counter++; + if (m_counter >= TEST_AND_SET_REPEATS) { + LogDebug("Max tests reached. Finishing thread"); + PostEvent(DESTROY_EVENT); + return; + } + PostEvent(2); + } +} + +RUNNER_TEST(SharedMemory_030_MultithreadTest) +{ + RemoveIpcs(); // we need non existing shm + + typedef SharedObject SHO; + SHO::Ptr sho = SharedObjectFactory::Create(SHM_KEY, SEM_NAME); + + ShmController* controller[MAX_THREADS]; + DPL::WaitableEvent finalEvent[MAX_THREADS]; + + for (size_t i=0;iGetProperty<0,int>(); + LogDebug("Final value is " << value << ", expected " << + MAX_THREADS * TEST_AND_SET_REPEATS); + RUNNER_ASSERT(value == MAX_THREADS * TEST_AND_SET_REPEATS); +} + +////////////////////////////////////////////// + +class MyModel10: public DPL::Model +{ + public: + explicit MyModel10(const TestSharedObject4Ptr& shared_object) + : DPL::Model(), boolValue(this, shared_object) {} + + SharedProperty + boolValue; +}; + +/* + * Listening controller + */ +class ShmController3: public ListeningController +{ + public: + explicit ShmController3(DPL::WaitableEvent* event) : + ListeningController(event) + {} + + virtual void OnEvent(const int event); + + void OnValueChanged(const DPL::PropertyEvent& event); + + private: + typedef std::unique_ptr MyModelPtr; + + // model with property bound to shared object + MyModelPtr m_model; +}; + +void ShmController3::OnEvent(const int event) +{ + if (event == INIT_EVENT) { + m_model.Reset(new MyModel10(m_so)); + m_model->boolValue.AddListener( + DPL::FastDelegate&)>( + this, + &ShmController3::OnValueChanged)); + } else if (event == DESTROY_EVENT) { + m_model->boolValue.RemoveListener( + DPL::FastDelegate&)>( + this, + &ShmController3::OnValueChanged)); + m_model.Reset(); + } +} + +void ShmController3::OnValueChanged(const DPL::PropertyEvent& event) +{ + if (event.value) { + // change back + m_model->boolValue.Set(false); + } else { + LogError("Expected value = true, got false"); + } + + m_waitable->Signal(); +} + +RUNNER_TEST(SharedMemory_050_SharedProperty) +{ + RemoveIpcs(); + + bool result = true; + DPL::WaitableEvent waitable; + // listener controller + ShmController3 controller(&waitable); + Wait(waitable); + + TestSharedObject4Ptr sharedObject = TestSharedObject4::Create(); + + for (size_t i = 0; i < SHARED_PROP_REPEATS; ++i) { + sharedObject->SetProperty(true); + Wait(waitable); + result = sharedObject->GetProperty(); + RUNNER_ASSERT(result == false); + } + controller.PostEvent(DESTROY_EVENT); + Wait(waitable); +} + +////////////////////////////////////////////// + +class MyModel2: public DPL::Model +{ + public: + explicit MyModel2(const TestSharedObjectPtr& shared_object) : + counter(this, shared_object) {} + + SharedProperty counter; +}; + +class SPController : public ListeningController +{ + public: + explicit SPController(DPL::WaitableEvent* event) : + ListeningController(event), m_repeats(1) {} + + virtual void OnEvent(const int event); + + void OnValueChanged1(const DPL::PropertyEvent& event); + void OnValueChanged2(const DPL::PropertyEvent& event); + + private: + std::unique_ptr m_model1; + std::unique_ptr m_model2; + + int m_repeats; + std::shared_ptr m_so2; +}; + +void SPController::OnEvent(const int event) +{ + if (event == INIT_EVENT) { + m_so2 = SharedObjectFactory::Create(SHM_KEY, + SEM_NAME); + + // create and register 2 models sharing the same property + m_model1.Reset(new MyModel2(m_so)); + m_model2.Reset(new MyModel2(m_so2)); + m_model1->counter.AddListener( + DPL::FastDelegate&)>( + this, + &SPController::OnValueChanged1)); + m_model2->counter.AddListener( + DPL::FastDelegate&)>( + this, + &SPController::OnValueChanged2)); + m_model1->counter.Set(1); + } + else if (event == DESTROY_EVENT) { + m_model1->counter.RemoveListener( + DPL::FastDelegate&)>( + this, + &SPController::OnValueChanged1)); + m_model2->counter.RemoveListener( + DPL::FastDelegate&)>( + this, + &SPController::OnValueChanged2)); + + m_model1.Reset(); + m_model2.Reset(); + m_so2.Reset(); + } +} + +void SPController::OnValueChanged1(const DPL::PropertyEvent& event) +{ + if (m_repeats >= SINGLE_PROCESS_REPEATS) { + PostEvent(DESTROY_EVENT); + return; + } + + LogDebug("[1] Value changed to " << event.value); + m_repeats++; + m_model1->counter.Set(event.value+1); +} + +void SPController::OnValueChanged2(const DPL::PropertyEvent& event) +{ + if (m_repeats >= SINGLE_PROCESS_REPEATS) { + PostEvent(DESTROY_EVENT); + return; + } + + LogDebug("[2] Value changed to " << event.value); + m_repeats++; + m_model2->counter.Set(event.value+1); +} + +RUNNER_TEST(SharedMemory_060_SingleProcess) +{ + RemoveIpcs(); + + DPL::WaitableEvent waitable; + SPController controller(&waitable); + TestSharedObjectPtr sho = SharedObjectFactory::Create( + SHM_KEY, + SEM_NAME); + + // wait for creation + Wait(waitable); + + // wait for destruction + Wait(waitable); + + int value = sho->GetProperty<0,int>(); + + LogDebug("final value: " << value); + + // check value + RUNNER_ASSERT(value == SINGLE_PROCESS_REPEATS); +} + +////////////////////////////////////////////// + +class ListenerTestController: public ListeningController, + public ISharedObjectListener<0,int>, + public ISharedObjectListener<1,int>, + public ISharedObjectListener<2,char>, + public ISharedObjectListener<3,int[64]> +{ + public: + explicit ListenerTestController(DPL::WaitableEvent* event) : + ListeningController(event) {} + + ~ListenerTestController(); + + virtual void OnEvent(const int event); + + virtual void ValueChanged(size_t propertyEnum, + const int& value, + const void* info = NULL); + virtual void ValueChanged(size_t propertyEnum, + const char& value, + const void* info = NULL); + virtual void ValueChanged(size_t propertyEnum, + const int(& value)[64], + const void* info = NULL); +}; + +ListenerTestController::~ListenerTestController() +{} + +void ListenerTestController::OnEvent(const int event) +{ + if (event == INIT_EVENT) { + // add self as a listener to shared object + m_so->AddListener<0,int>(this); + m_so->AddListener<1,int>(this); + m_so->AddListener<2,char>(this); + m_so->AddListener<3,int[64]>(this); + } + else if (event == DESTROY_EVENT) { + // remove self from listener list + m_so->RemoveListener<0,int>(this); + m_so->RemoveListener<1,int>(this); + m_so->RemoveListener<2,char>(this); + m_so->RemoveListener<3,int[64]>(this); + } +} + +void ListenerTestController::ValueChanged(size_t propertyEnum, + const int& value, + const void* /*info*/) +{ + LogDebug("ValueChanged(int) " << propertyEnum << " " << value); + if ((propertyEnum == 0 && value == 1) || (propertyEnum == 1 && value == 2)) + { + g_values[propertyEnum]++; + if (g_values[propertyEnum] == 3) { + m_waitable->Signal(); + } + } +} + +void ListenerTestController::ValueChanged(size_t propertyEnum, + const char& value, + const void* /*info*/) +{ + LogDebug("ValueChanged(char) " << propertyEnum << " " << value); + if (propertyEnum == 2 && value == 'c') + { + g_values[propertyEnum]++; + if (g_values[propertyEnum] == 3) { + m_waitable->Signal(); + } + } +} + +void ListenerTestController::ValueChanged(size_t propertyEnum, + const int(& value)[64], + const void* /*info*/) +{ + LogDebug("ValueChanged(int[64]) " << propertyEnum << " " << value[5]); + if (propertyEnum == 3 && value[5] == 5) + { + g_values[propertyEnum]++; + if (g_values[propertyEnum] == 3) { + m_waitable->Signal(); + } + } +} + +RUNNER_TEST(SharedMemory_070_SharedObjectListeners) +{ + RemoveIpcs(); + + // setup global flags + for (size_t i=0;i::Create( + SHM_KEY, SEM_NAME); + + // create 1st listener and wait for it + DPL::WaitableEvent waitable; + ListenerTestController c1(&waitable); + Wait(waitable); + + // create 2nd listener and wait for it + ListenerTestController c2(&waitable); + Wait(waitable); + + // create 3rd listener and wait for it + ListenerTestController c3(&waitable); + Wait(waitable); + + // set properties and wait for result + sho->SetProperty<0,int>(1); + Wait(waitable); + + RUNNER_ASSERT(g_values[0] == 3); + + sho->SetProperty<1,int>(2); + Wait(waitable); + + RUNNER_ASSERT(g_values[1] == 3); + + sho->SetProperty<2,char>('c'); + Wait(waitable); + + RUNNER_ASSERT(g_values[2] == 3); + + int array[64]; + memset(array,64*sizeof(array[0]),0); + array[5] = 5; + sho->SetProperty<3,int[64]>(array); + Wait(waitable); + + RUNNER_ASSERT(g_values[3] == 3); + + // finalize listeners + c1.PostEvent(DESTROY_EVENT); + Wait(waitable); + + c2.PostEvent(DESTROY_EVENT); + Wait(waitable); + + c3.PostEvent(DESTROY_EVENT); + Wait(waitable); +} + +////////////////////////////////////////////// + +/* + * class simulating DB access + */ +class DAO : public DPL::Noncopyable +{ + public: + DAO() : m_boolValue(false) {} + + void SetBoolValue(const bool& value) { m_boolValue = value; } + + bool GetBoolValue() const { return m_boolValue; } + + private: + bool m_boolValue; +}; + +/* + * Model with property having set delegate defined + */ +class MyModel3: public DPL::Model +{ + public: + typedef SharedPropertyEx PropertyType; + + MyModel3(const TestSharedObject4Ptr& shared_object, DAO* dao) : + boolValue(this, + shared_object, + PropertyType::SetDelegate(dao, &DAO::SetBoolValue)) + { + } + + PropertyType boolValue; +}; + +RUNNER_TEST(SharedMemory_090_SetPropertyDelegate) +{ + RemoveIpcs(); + + // dao object + DAO dao; + + // create shared object + TestSharedObject4Ptr sho = TestSharedObject4::Create(); + + // set property but call dao delegate within semaphore + sho->SetProperty( + true, + MyModel3::PropertyType::SetDelegate(&dao, &DAO::SetBoolValue)); + + // check dao value + RUNNER_ASSERT(dao.GetBoolValue() == true); + + // check shared object value + bool shoValue = sho->GetProperty(); + RUNNER_ASSERT(shoValue == true); + + // try the same with shared property + MyModel3 model(sho, &dao); + + // set property + model.boolValue.Set(false); + + // check dao value + RUNNER_ASSERT(dao.GetBoolValue() == false); + + // check sho value + shoValue = sho->GetProperty(); + RUNNER_ASSERT(shoValue == false); + + // check property value + RUNNER_ASSERT(model.boolValue.Get() == false); +} + +////////////////////////////////////////////// + +/* + * Lazy initialization test shared object + */ +class LazySharedObject : public SharedObject +{ + public: + explicit LazySharedObject(const std::string& semaphore) : + SharedObject(semaphore) + ,m_read(false) + { + } + + void Init(); + + bool IsRead() const { return m_read; } + + private: + friend class SharedObjectFactory; + + bool m_read; +}; + +void LazySharedObject::Init() +{ + SetPropertyInternal<0>(42); + m_read = true; +} + +RUNNER_TEST(SharedMemory_100_LazyInit) +{ + RemoveIpcs(); + + typedef std::shared_ptr LazySharedObjectPtr; + + // create shared object + LazySharedObjectPtr sho = SharedObjectFactory::Create( + SHM_KEY, SEM_NAME); + + RUNNER_ASSERT(sho->IsRead() == false); + + // get property causing lazy init + int value = sho->GetProperty<0, int>(); + + RUNNER_ASSERT(sho->IsRead() == true); + RUNNER_ASSERT(value == 42); + + // create another object + LazySharedObjectPtr sho2 = SharedObjectFactory::Create( + SHM_KEY, SEM_NAME); + + RUNNER_ASSERT(sho2->IsRead() == false); + + // get property NOT causing lazy init + value = sho2->GetProperty<0, int>(); + + RUNNER_ASSERT(sho2->IsRead() == false); + RUNNER_ASSERT(value == 42); + + // destroy both objects + sho.Reset(); + sho2.Reset(); + + // create shared object + LazySharedObjectPtr sho3 = SharedObjectFactory::Create( + SHM_KEY, SEM_NAME); + + RUNNER_ASSERT(sho3->IsRead() == false); + + // set property causing lazy init + sho3->SetProperty<0>(43); + value = sho3->GetProperty<0, int>(); + + RUNNER_ASSERT(sho3->IsRead() == true); + RUNNER_ASSERT(value == 43); + +} + +////////////////////////////////////////////// + +bool SetCondition(const int& readValue, int& setValue); +bool SetCondition(const int& readValue, int& setValue) +{ + LogDebug("Condition delegate called with read value = " << readValue << + " and set value = " << setValue); + + if (readValue > 3) { + LogDebug("Condition is false"); + return false; + } + + LogDebug("Condition is true"); + if (4 == setValue) { + setValue = 10; + LogDebug("Changing set value to " << setValue); + } + return true; +} + +void SetDelegate(const int& readValue); +void SetDelegate(const int& readValue) +{ + LogDebug("Set delegate called " << readValue); + g_delegateCalls++; +} + +RUNNER_TEST(SharedMemory_120_ConditionalSet) +{ + RemoveIpcs(); + + TestSharedObjectPtr sho = SharedObjectFactory::Create( + SHM_KEY, + SEM_NAME); + + g_delegateCalls = 0; + + RUNNER_ASSERT(0 == (sho->GetProperty<0,int>())); + + DPL::FastDelegate condition(&SetCondition); + DPL::FastDelegate delegate(&SetDelegate); + + bool succeeded = false; + + succeeded = sho->ConditionalSetProperty<0>(-2, condition); + + RUNNER_ASSERT(succeeded); + RUNNER_ASSERT(-2 == (sho->GetProperty<0,int>())); + + succeeded = sho->ConditionalSetProperty<0>(4, condition, delegate); + + RUNNER_ASSERT(succeeded); + RUNNER_ASSERT(10 == (sho->GetProperty<0,int>())); + RUNNER_ASSERT(1 == g_delegateCalls); + + succeeded = sho->ConditionalSetProperty<0>(5, condition); + + RUNNER_ASSERT(!succeeded); + RUNNER_ASSERT(10 == (sho->GetProperty<0,int>())); + + succeeded = sho->ConditionalSetProperty<0>(666, condition, delegate); + + RUNNER_ASSERT(!succeeded); + RUNNER_ASSERT(10 == (sho->GetProperty<0,int>())); + RUNNER_ASSERT(1 == g_delegateCalls); +} + +////////////////////////////////////////////// + +/* + * Shared object used by multiple threads as a singleton. + */ +class MTSharedObject : public SharedObject +{ + public: + explicit MTSharedObject(const std::string& semaphore) : + SharedObject(semaphore) + { + } + + void Clear(); + + private: + friend class SharedObjectFactory; +}; + +typedef std::shared_ptr MTSharedObjectPtr; + +void MTSharedObject::Clear() +{ + int array[64] = {}; + SetProperty<0>(0); + SetProperty<1>(0); + SetProperty<2>(static_cast(0)); + SetProperty<3>(array); +} + +/* + * Shared object singleton + */ +class SharedObjectSingleton +{ + public: + static MTSharedObjectPtr Instance(); + static void Destroy(); + + private: + static MTSharedObjectPtr m_sho; + static DPL::Mutex m_mutex; +}; + +MTSharedObjectPtr SharedObjectSingleton::m_sho; +DPL::Mutex SharedObjectSingleton::m_mutex; + +MTSharedObjectPtr SharedObjectSingleton::Instance() +{ + DPL::Mutex::ScopedLock lock(&m_mutex); + if (!m_sho) { + m_sho = SharedObjectFactory::Create(SHM_KEY, SEM_NAME); + } + return m_sho; +} + +void SharedObjectSingleton::Destroy() +{ + DPL::Mutex::ScopedLock lock(&m_mutex); + m_sho.Reset(); +} + +/* + * Listening controller + */ +class ShmController4 : public ListeningController, + public ISharedObjectListener<0,int>, + public ISharedObjectListener<1,int>, + public ISharedObjectListener<2,char>, + public ISharedObjectListener<3,int[64]> +{ + public: + enum { + ADD_LISTENERS = 2, + REMOVE_LISTENERS = 3, + DESTROY_SINGLETON = 4 + }; + + explicit ShmController4(DPL::WaitableEvent* event) : + ListeningController(event) + {} + + virtual void OnEventReceived(const int& event); + + virtual void ValueChanged(size_t propertyEnum, + const int& value, + const void* info = NULL); + virtual void ValueChanged(size_t propertyEnum, + const char& value, + const void* info = NULL); + virtual void ValueChanged(size_t propertyEnum, + const int(& value)[64], + const void* info = NULL); + + bool NotRegistered(); + + private: + void Sleep(); + + size_t m_counter; +}; + +void ShmController4::ValueChanged(size_t propertyEnum, + const int& value, + const void* /*info*/) +{ + LogDebug("ValueChanged(int) " << propertyEnum << " " << value); + if ((propertyEnum == 0 && value == 1) || + (propertyEnum == 1 && value == 11)) + { + m_waitable->Signal(); + } +} + +void ShmController4::ValueChanged(size_t propertyEnum, + const char& value, + const void* /*info*/) +{ + LogDebug("ValueChanged(char) " << propertyEnum << " " << value); + if (propertyEnum == 2 && value == 'a') { + m_waitable->Signal(); + } +} + +void ShmController4::ValueChanged(size_t propertyEnum, + const int(& value)[64], + const void* /*info*/) +{ + LogDebug("ValueChanged(int[64]) " << propertyEnum << " " << value[5]); + if (propertyEnum == 3 && value[0] == 0 && value[1] == 1 && value[2] == 2) { + m_waitable->Signal(); + } +} + +void ShmController4::Sleep() +{ + DPL::Thread::GetCurrentThread()->MiliSleep( + rand() % MAX_SINGLETON_LISTENER_DELAY); +} + +void ShmController4::OnEventReceived(const int& event) +{ + switch (event) { + case INIT_EVENT: + m_so = SharedObjectSingleton::Instance(); + m_waitable->Signal(); + break; + + case DESTROY_EVENT: + LogDebug("Destroying shared object"); + // deregister, destroy and notify main thread + m_so.Reset(); + m_waitable->Signal(); + break; + + case ADD_LISTENERS: + // add listener and notify + m_so->AddListener<0,int>(this); + Sleep(); + m_so->AddListener<1,int>(this); + Sleep(); + m_so->AddListener<2,char>(this); + Sleep(); + m_so->AddListener<3,int[64]>(this); + Sleep(); + m_waitable->Signal(); + break; + + case REMOVE_LISTENERS: + // remove listener and notify + m_so->RemoveListener<0,int>(this); + Sleep(); + m_so->RemoveListener<1,int>(this); + Sleep(); + m_so->RemoveListener<2,char>(this); + Sleep(); + m_so->RemoveListener<3,int[64]>(this); + Sleep(); + m_waitable->Signal(); + break; + + case DESTROY_SINGLETON: + SharedObjectSingleton::Destroy(); + m_waitable->Signal(); + break; + + default: + LogError("Unsupported event received: " << event); + } +} + +void MultipleWait(DPL::WaitableEvent (& event)[MAX_THREADS]); +void MultipleWait(DPL::WaitableEvent (& event)[MAX_THREADS]) +{ + for (size_t i=0;iRemoveListener<(property)>(controller[i]); \ + LogError("Controller " << i << " is still listening for property " \ + << #property); \ + RUNNER_ASSERT_MSG(false, "No listeners expected"); \ + } \ + Catch (MTSharedObject::Exception::ListenerNotFound) { \ + RUNNER_ASSERT(true); \ + } \ + +// test +RUNNER_TEST(SharedMemory_130_SharedObjectSingleton) +{ + RemoveIpcs(); // we need non existing shm + + srand(time(NULL)); + + // writer shared object + TestSharedObjectPtr sho = SharedObjectFactory::Create( + SHM_KEY, SEM_NAME); + + ShmController4* controller[MAX_THREADS]; + DPL::WaitableEvent waitable[MAX_THREADS]; + + const int array[64] = {0,1,2}; + + // Create and wait for notification. Make sure that the thread/controller 0 + // is created first + LogInfo("Creating controllers"); + for (size_t i=0;iClear(); + + // add listeners + LogInfo("Adding listeners"); + for (size_t i=0;iPostEvent(ShmController4::ADD_LISTENERS); + } + // wait for listeners + MultipleWait(waitable); + + RUNNER_ASSERT((singleton->GetProperty<0,int>()) == 0); + RUNNER_ASSERT((singleton->GetProperty<1,int>()) == 0); + RUNNER_ASSERT((singleton->GetProperty<2,char>()) == 0); + + int checkArray[64] = {}; + singleton->GetProperty<3>(checkArray); + RUNNER_ASSERT(checkArray[0] == 0); + RUNNER_ASSERT(checkArray[1] == 0); + RUNNER_ASSERT(checkArray[2] == 0); + + // change + LogInfo("Setting property 0"); + sho->SetProperty<0>(1); + // wait for confirmations + MultipleWait(waitable); + + // change + LogInfo("Setting property 1"); + sho->SetProperty<1>(11); + // wait for confirmations + MultipleWait(waitable); + + // change + LogInfo("Setting property 2"); + sho->SetProperty<2>('a'); + // wait for confirmations + MultipleWait(waitable); + + // change + LogInfo("Setting property 3"); + sho->SetProperty<3>(array); + // wait for confirmations + MultipleWait(waitable); + + // remove listeners + LogInfo("Removing listeners"); + for (size_t i=0;iPostEvent(ShmController4::REMOVE_LISTENERS); + } + // wait for listeners + MultipleWait(waitable); + + // check if listeners array is empty + LogInfo("Checking listeners"); + for (size_t i=0;iGetProperty<0,int>()) == 1); + RUNNER_ASSERT((singleton->GetProperty<1,int>()) == 11); + RUNNER_ASSERT((singleton->GetProperty<2,char>()) == 'a'); + singleton->GetProperty<3>(checkArray); + RUNNER_ASSERT(checkArray[0] == 0); + RUNNER_ASSERT(checkArray[1] == 1); + RUNNER_ASSERT(checkArray[2] == 2); + } + + singleton.Reset(); + + // Destroy controllers and wait for confirmation. Make sure that + // thread/controller 0 is destroyed in the end + LogInfo("Destroying controllers"); + for (int i=MAX_THREADS-1;i>=0;--i) { + controller[i]->PostEvent(DESTROY_EVENT); + Wait(waitable[i]); + if (i==0) { + /* + * Destroy singleton before thread that created it finishes. + * This is to properly close all waitable handles opened by + * SharedObject in thread 0. + */ + LogInfo("Destroying singleton"); + controller[i]->PostEvent(ShmController4::DESTROY_SINGLETON); + Wait(waitable[i]); + } + delete controller[i]; + } +} + +#undef LISTENER_ASSERT + +/* + * test preconditions & postconditions: + * - no existing shared memory with given SHM_KEY + * - no existing semaphore of given SEM_NAME + */ +RUNNER_TEST(SharedMemory_001_Preconditions) { + RemoveIpcs(); +} + +RUNNER_TEST(SharedMemory_999_Postconditions) { + RemoveIpcs(); +} diff --git a/tests/dpl/unused/test_sql_connection.cpp b/tests/dpl/unused/test_sql_connection.cpp new file mode 100644 index 0000000..2c2fc4f --- /dev/null +++ b/tests/dpl/unused/test_sql_connection.cpp @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file test_sql_connection.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of sql connection tests + */ + + +/* + +This test has been saved from original test_sql_connection.cpp in wrt-commons project. + +*/ + +#include + +RUNNER_TEST(SqlConnection_MassiveReadWrite_SemaphoreSynchronization) +{ + srand(time(NULL)); + + std::ostringstream dbSemaporeFileNameStream; + dbSemaporeFileNameStream << "dpl_tests_dbso_sem_"; + dbSemaporeFileNameStream << rand() << ".sem"; + + std::string dbSemaphoreFileName = dbSemaporeFileNameStream.str(); + + SemaphoreSynchronizationObjectGenerator m_generator(dbSemaphoreFileName); + MassiveReadWriteTest(&m_generator); +} diff --git a/tests/dpl/unused/test_task.cpp b/tests/dpl/unused/test_task.cpp new file mode 100644 index 0000000..94bd357 --- /dev/null +++ b/tests/dpl/unused/test_task.cpp @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file test_task.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of task tests + */ +#include +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL) + +class MySingleTask + : public DPL::TaskDecl +{ +protected: + void StepOne() + { + } + +public: + MySingleTask() + : DPL::TaskDecl(this) + { + AddStep(&MySingleTask::StepOne); + } +}; + +class MyMultiTask + : public DPL::MultiTaskDecl +{ +protected: + typedef DPL::MultiTaskDecl BaseType; + + void StepOne() + { + LogInfo("Step one"); + } + + void StepTwo() + { + LogInfo("Step two"); + } + + void StepThree() + { + LogInfo("Step three"); + } + +public: + MyMultiTask() + : BaseType(this, 2) + { + BaseType::StepList depListStepThree; + depListStepThree.push_back(&MyMultiTask::StepOne); + depListStepThree.push_back(&MyMultiTask::StepTwo); + AddStep(&MyMultiTask::StepThree, depListStepThree); + + BaseType::StepList depListStepTwo; + depListStepTwo.push_back(&MyMultiTask::StepOne); + AddStep(&MyMultiTask::StepTwo, depListStepTwo); + + BaseType::StepList depListStepOne; + AddStep(&MyMultiTask::StepOne, depListStepOne); + } +}; + +RUNNER_TEST(Task_SingleTask) +{ + MySingleTask task; + while (task.NextStep()); +} + +RUNNER_TEST(Task_MultiTask) +{ + MyMultiTask task; + while (task.NextStep()); +} diff --git a/tests/dpl/utils/CMakeLists.txt b/tests/dpl/utils/CMakeLists.txt new file mode 100644 index 0000000..b3ce494 --- /dev/null +++ b/tests/dpl/utils/CMakeLists.txt @@ -0,0 +1,33 @@ +# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# @file CMakeLists.txt +# @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) +# @version 1.0 +# @brief +# + +SET(TARGET_NAME "dpl-tests-utils") + +# Set DPL tests sources +SET(DPL_TESTS_UTIL_SOURCES + ${TESTS_DPL_DIR}/utils/main.cpp + ${TESTS_DPL_DIR}/utils/widget_version.cpp + ${TESTS_DPL_DIR}/utils/bash_utils.cpp + ${TESTS_DPL_DIR}/utils/wrt_utility.cpp +) + +#WRT_TEST_ADD_INTERNAL_DEPENDENCIES(${TARGET_NAME} ${TARGET_DPL_UTILS_EFL}) +WRT_TEST_BUILD(${TARGET_NAME} ${DPL_TESTS_UTIL_SOURCES}) +WRT_TEST_INSTALL(${TARGET_NAME}) diff --git a/tests/dpl/utils/bash_utils.cpp b/tests/dpl/utils/bash_utils.cpp new file mode 100644 index 0000000..f433fd8 --- /dev/null +++ b/tests/dpl/utils/bash_utils.cpp @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @file bash_utils.cpp + * @author Iwanek Tomasz + * @version 1.0 + */ +#include +#include +#include + +using namespace BashUtils; + +RUNNER_TEST_GROUP_INIT(DPL_BASH_UTILS) + +RUNNER_TEST(Bash_Utils_escape_arg) +{ + RUNNER_ASSERT_MSG(escape_arg(std::string("valid")) == "\"valid\"", "Valid argument failed"); + LogDebug("\"val\\!d\"" << " " << escape_arg(std::string("val!d"))); + RUNNER_ASSERT_MSG(escape_arg(std::string("val!d")) == "\"val\\!d\"", "Single escaped character in argument failed"); + LogDebug("\"v\\$l\\$\\$\"" << " " << escape_arg(std::string("v$l$$"))); + RUNNER_ASSERT_MSG(escape_arg(std::string("v$l$$")) == "\"v\\$l\\$\\$\"", "Multiple occurences of single special character in argument failed"); + LogDebug("\"v\\`\\$\\\"\\!d\\`\"" << " " << escape_arg(std::string("v`$\"!d`"))); + RUNNER_ASSERT_MSG(escape_arg(std::string("v`$\"!d`")) == "\"v\\`\\$\\\"\\!d\\`\"", "Multiple occurences of multiple special character in argument failed"); +} diff --git a/tests/dpl/utils/main.cpp b/tests/dpl/utils/main.cpp new file mode 100644 index 0000000..42ffe3a --- /dev/null +++ b/tests/dpl/utils/main.cpp @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file main.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of main + */ +#include + +int main(int argc, char *argv[]) +{ + return DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, argv); +} + diff --git a/tests/dpl/utils/widget_version.cpp b/tests/dpl/utils/widget_version.cpp new file mode 100644 index 0000000..2413b65 --- /dev/null +++ b/tests/dpl/utils/widget_version.cpp @@ -0,0 +1,278 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file widget_version.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief Implementation file for test cases for engine internal tests + */ +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL_WIDGET_VERSION) + +RUNNER_TEST(WidgetVersion_M2_O0) +{ + DPL::String raw(L"1.2"); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == true); + RUNNER_ASSERT(version.Major() == DPL::String(L"1")); + RUNNER_ASSERT(version.Minor() == DPL::String(L"2")); + RUNNER_ASSERT(version.Micro() == DPL::Optional()); + RUNNER_ASSERT(version.Optional() == DPL::Optional()); + RUNNER_ASSERT(version.Raw() == raw); +} + +RUNNER_TEST(WidgetVersion_M2_O0_nonwac_1) +{ + DPL::String raw(L"a1.2"); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == false); + RUNNER_ASSERT(version.Raw() == raw); +} + +RUNNER_TEST(WidgetVersion_M2_O0_nonwac_2) +{ + DPL::String raw(L"1.2a"); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == false); + RUNNER_ASSERT(version.Raw() == raw); +} + +RUNNER_TEST(WidgetVersion_M2_O0_nonwac_3) +{ + DPL::String raw(L"aaa1.2bbb"); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == false); + RUNNER_ASSERT(version.Raw() == raw); +} + +RUNNER_TEST(WidgetVersion_M2_O0_nonwac_4) +{ + DPL::String raw(L"1a.a2"); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == false); + RUNNER_ASSERT(version.Raw() == raw); +} + +RUNNER_TEST(WidgetVersion_M2_O0_long) +{ + DPL::String raw(L"123456789012345678901234567890.98765432109876543210987654321"); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == true); + RUNNER_ASSERT(version.Major() == DPL::String(L"123456789012345678901234567890")); + RUNNER_ASSERT(version.Minor() == DPL::String(L"98765432109876543210987654321")); + RUNNER_ASSERT(version.Micro() == DPL::Optional()); + RUNNER_ASSERT(version.Optional() == DPL::Optional()); + RUNNER_ASSERT(version.Raw() == raw); +} + +RUNNER_TEST(WidgetVersion_M3_O0) +{ + DPL::String raw(L"1.2.3"); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == true); + RUNNER_ASSERT(version.Major() == DPL::String(L"1")); + RUNNER_ASSERT(version.Minor() == DPL::String(L"2")); + RUNNER_ASSERT(version.Micro() == DPL::Optional(L"3")); + RUNNER_ASSERT(version.Optional() == DPL::Optional()); + RUNNER_ASSERT(version.Raw() == raw); +} + +RUNNER_TEST(WidgetVersion_M3_O0_nonwac_1) +{ + DPL::String raw(L"a1a.2.3"); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == false); + RUNNER_ASSERT(version.Raw() == raw); +} + +RUNNER_TEST(WidgetVersion_M3_O0_nonwac_2) +{ + DPL::String raw(L"1.b2.3"); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == false); + RUNNER_ASSERT(version.Raw() == raw); +} + +RUNNER_TEST(WidgetVersion_M3_O0_nonwac_3) +{ + DPL::String raw(L"1.2.3c"); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == false); + RUNNER_ASSERT(version.Raw() == raw); +} + +RUNNER_TEST(WidgetVersion_M3_O0_nonwac_4) +{ + DPL::String raw(L"1.2.3a"); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == false); + RUNNER_ASSERT(version.Raw() == raw); +} + +RUNNER_TEST(WidgetVersion_M3_O1_1) +{ + DPL::String raw(L"1.2.3 test111"); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == true); + RUNNER_ASSERT(version.Major() == DPL::String(L"1")); + RUNNER_ASSERT(version.Minor() == DPL::String(L"2")); + RUNNER_ASSERT(version.Micro() == DPL::Optional(L"3")); + RUNNER_ASSERT(version.Optional() == DPL::Optional(L"test111")); + RUNNER_ASSERT(version.Raw() == raw); +} + +RUNNER_TEST(WidgetVersion_M3_O1_2) +{ + DPL::String raw(L"1.2.3 111"); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == true); + RUNNER_ASSERT(version.Major() == DPL::String(L"1")); + RUNNER_ASSERT(version.Minor() == DPL::String(L"2")); + RUNNER_ASSERT(version.Micro() == DPL::Optional(L"3")); + RUNNER_ASSERT(version.Optional() == DPL::Optional(L"111")); + RUNNER_ASSERT(version.Raw() == raw); +} + +RUNNER_TEST(WidgetVersion_M3_O1_3) +{ + DPL::String raw(L"1.2.3 "); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == false); + RUNNER_ASSERT(version.Raw() == raw); +} + +RUNNER_TEST(WidgetVersion_M2_O1_1) +{ + DPL::String raw(L"1.2 t"); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == true); + RUNNER_ASSERT(version.Major() == DPL::String(L"1")); + RUNNER_ASSERT(version.Minor() == DPL::String(L"2")); + RUNNER_ASSERT(version.Micro() == DPL::Optional()); + RUNNER_ASSERT(version.Optional() == DPL::Optional(L"t")); + RUNNER_ASSERT(version.Raw() == raw); +} + +RUNNER_TEST(WidgetVersion_Strange_0) +{ + DPL::String raw(L"1"); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == false); + RUNNER_ASSERT(version.Raw() == raw); +} + +RUNNER_TEST(WidgetVersion_Strange_1) +{ + DPL::String raw(L".1"); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == false); + RUNNER_ASSERT(version.Raw() == raw); +} + +RUNNER_TEST(WidgetVersion_Strange_2) +{ + DPL::String raw(L"..1"); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == false); + RUNNER_ASSERT(version.Raw() == raw); +} + +RUNNER_TEST(WidgetVersion_Strange_3) +{ + DPL::String raw(L"...1"); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == false); + RUNNER_ASSERT(version.Raw() == raw); +} + +RUNNER_TEST(WidgetVersion_Strange_4) +{ + DPL::String raw(L"qwerty"); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == false); + RUNNER_ASSERT(version.Raw() == raw); +} + +RUNNER_TEST(WidgetVersion_Strange_5) +{ + DPL::String raw(L"!@#$%^&*()_+ ^&%^*&%$^*&%*()& JHKJLHKJLH 685685687"); + WidgetVersion version(raw); + + RUNNER_ASSERT(version.IsWac() == false); + RUNNER_ASSERT(version.Raw() == raw); +} + +RUNNER_TEST(WidgetVersion_Compare_0) +{ + RUNNER_ASSERT(WidgetVersion(L"1.1") < WidgetVersion(L"1.2")); +} + +RUNNER_TEST(WidgetVersion_Compare_1) +{ + RUNNER_ASSERT(WidgetVersion(L"01.001") < WidgetVersion(L"0001.002")); +} + +RUNNER_TEST(WidgetVersion_Compare_2) +{ + RUNNER_ASSERT(WidgetVersion(L"0.1") == WidgetVersion(L"00.1")); +} + +RUNNER_TEST(WidgetVersion_Compare_3) +{ + RUNNER_ASSERT(WidgetVersion(L"1.00000000000000") >= WidgetVersion(L"1.0 test")); +} + +RUNNER_TEST(WidgetVersion_Compare_4) +{ + RUNNER_ASSERT(WidgetVersion(L"19647963733338932479072098437089778943732432.00000000000000004324324324324321") > WidgetVersion(L"4324324324324324324321.000432")); +} + +RUNNER_TEST(WidgetVersion_Compare_5) +{ + RUNNER_ASSERT(WidgetVersion(L"12345.1") == WidgetVersion(L"12345.1")); +} + +RUNNER_TEST(WidgetVersion_Compare_6) +{ + RUNNER_ASSERT(WidgetVersion(L"1.1") != WidgetVersion(L"1.11")); +} + +RUNNER_TEST(WidgetVersion_Compare_7) +{ + RUNNER_ASSERT(WidgetVersion(L"000123000.0 notatest") == WidgetVersion(L"00123000.0 testtesttest")); +} diff --git a/tests/dpl/utils/wrt_utility.cpp b/tests/dpl/utils/wrt_utility.cpp new file mode 100644 index 0000000..31d5abe --- /dev/null +++ b/tests/dpl/utils/wrt_utility.cpp @@ -0,0 +1,163 @@ +/* + * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * @file wrt_utility.cpp + * @author Janusz Majnert (j.majnert@samsung.com) + * @version 1.0 + * @brief Implementation file for test cases for wrt_utility functions + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +RUNNER_TEST_GROUP_INIT(DPL_WRT_UTILITY) + +RUNNER_TEST(wrt_utility_WrtUtilJoinPaths) +{ + std::string result; + + WrtUtilJoinPaths(result, "a/b/c/", "e/f/g.asd"); + RUNNER_ASSERT(result == "a/b/c/e/f/g.asd"); + + WrtUtilJoinPaths(result, "/a/b/c", "/e/f/g/"); + RUNNER_ASSERT(result == "/a/b/c/e/f/g/"); + + WrtUtilJoinPaths(result, "/a/b/c/", "/e/f/g/"); + RUNNER_ASSERT(result == "/a/b/c/e/f/g/"); + + WrtUtilJoinPaths(result, "/a/b/c", "e/f/g/"); + RUNNER_ASSERT(result == "/a/b/c/e/f/g/"); +} + +/** + * Create recursive path with specified permissions. + * Check if folders exist. + * Check if permissions are set. + */ +RUNNER_TEST(wrt_utility_WrtUtilMakeDir) +{ + struct stat st; + //First delete the dir if it exists + WrtUtilRemove("/tmp/test"); + WrtUtilMakeDir("/tmp/test/1/2/3/4/5/6/7/8/9", 0755); + if (stat("/tmp/test/1/2/3/4/5/6/7/8/9", &st) == 0) { + RUNNER_ASSERT_MSG(st.st_mode & S_IRWXU, + "read, write, execute/search by owner"); + RUNNER_ASSERT_MSG(st.st_mode & S_IXGRP, + "execute/search permission, group"); + RUNNER_ASSERT_MSG(st.st_mode & S_IRGRP, "read permission, group"); + RUNNER_ASSERT_MSG(!(st.st_mode & S_IWGRP), + "NO write permission, group "); + RUNNER_ASSERT_MSG(st.st_mode & S_IXOTH, + "execute/search permission, others"); + RUNNER_ASSERT_MSG(st.st_mode & S_IROTH, "read permission, others"); + RUNNER_ASSERT_MSG(!(st.st_mode & S_IWOTH), + "NO write permission, others "); + } else { + RUNNER_ASSERT_MSG(false, "Cannot stat folder"); + } +} + +/** + * Create directory without permission to write. + */ +RUNNER_TEST(wrt_utility_WrtUtilMakeDir_PermissionError) +{ + if (0 == getuid()) { + //Change UID to execute the test correctly + errno = 0; + struct passwd *p = getpwnam("app"); + if (p == NULL) { + int error = errno; + RUNNER_ASSERT_MSG(false, "Getting app user UID failed: " + << (error == 0 ? "No error detected" : strerror(error))); + } + if (setuid(p->pw_uid) != 0) { + int error = errno; + RUNNER_ASSERT_MSG(false, "Changing to app user's UID failed: " + << (error == 0 ? "No error detected" : strerror(error))); + } + } + RUNNER_ASSERT_MSG(WrtUtilMakeDir("/tmp/test2/1", 0055) == false, + "Creating directory '1' in /temp/test2/ should have failed"); + //Going back to root UID + if (setuid(0) != 0) { + int error = errno; + LogWarning("Changing back to root UID failed: " + << (error == 0 ? "No error detected" : strerror(error))); + } + +} + +/** + * Create directory with file inside. + * Check if file was removed with directory. + */ +RUNNER_TEST(wrt_utility_WrtUtilRemoveDir) { + RUNNER_ASSERT_MSG(WrtUtilMakeDir("/tmp/test3/", 0755) == true, + "Could not set up directory for test"); + + std::ofstream file; + file.open("/tmp/test3/example.txt"); + file.close(); + struct stat tmp; + RUNNER_ASSERT_MSG(stat("/tmp/test3/example.txt",&tmp) == 0, + "Couldn't create the test file"); + + WrtUtilRemove("/tmp/test3"); + if (stat("/tmp/test3", &tmp) != 0) { + int error=errno; + RUNNER_ASSERT(error == ENOENT); + return; + } + RUNNER_ASSERT(false); +} + +/** + * Try to remove not existing folder. + */ +RUNNER_TEST(wrt_utility_WrtUtilRemoveDir_NoDirError) +{ + //First making sure the test dir doesn't exist + WrtUtilRemove("/tmp/NOT_EXISTING"); + + RUNNER_ASSERT_MSG(WrtUtilRemove("/tmp/NOT_EXISTING") == false, + "Removing non existing directory returned success"); +} + +RUNNER_TEST(wrt_utility_WrtUtilFileExists) +{ + std::ofstream file; + file.open("/tmp/test_file1"); + file.close(); + RUNNER_ASSERT(WrtUtilFileExists("/tmp/test_file1")); + + WrtUtilRemove("/tmp/test_file1"); + RUNNER_ASSERT(WrtUtilFileExists("/tmp/test_file1") == false); +} + +RUNNER_TEST(wrt_utility_WrtUtilDirExists) +{ + RUNNER_ASSERT(WrtUtilDirExists("/tmp")); + RUNNER_ASSERT(WrtUtilDirExists("/UNAVAILABLE_DIR") == false); +} diff --git a/wrt-commons.manifest b/wrt-commons.manifest index e797580..fb4bfc3 100644 --- a/wrt-commons.manifest +++ b/wrt-commons.manifest @@ -4,6 +4,7 @@ -- 2.34.1