From 66378dd435c0d04db5467429987eb98d49ebf2a6 Mon Sep 17 00:00:00 2001 From: Pawel Sikorski Date: Wed, 6 Feb 2013 13:53:31 +0100 Subject: [PATCH] Source code formating unification [Issue#] N/A [Problem] Source code was not formatted to any rules. In this situation creating new patches or making review may become uncomfortable. [Cause] No formatting rules/tool used. [Solution] To make implementation and review process more comfortable, whole commons repository source code has been formatted with uncrustify tool. The configuration of the tool is located in the repository (./uncrustify.cfg). Command used (stored in uncrustify.sh): uncrustify -c ./uncrustify.cfg --no-backup `find . -regex "\(.*\.cpp\|.*\.h\|.*\.c\|.*\.cc\)" | grep -v "orm.h\|orm_generator.h\|3rdpartyi\|examples"` [Verification] Build the repository Change-Id: I3ee7d6af0408b760a3af003e488c1e48dfaf0395 --- modules/auto_save_dao/dao/AutoSaveDatabase.cpp | 2 +- modules/auto_save_dao/dao/auto_save_dao.cpp | 14 +- .../auto_save_dao/dao/auto_save_dao_read_only.cpp | 13 +- modules/auto_save_dao/dao/common_dao_types.cpp | 3 +- .../auto-save-dao-ro/auto_save_dao_read_only.h | 5 +- .../wrt-commons/auto-save-dao-rw/auto_save_dao.h | 4 +- .../wrt-commons/auto-save-dao/AutoSaveDatabase.h | 10 +- .../wrt-commons/auto-save-dao/common_dao_types.h | 10 +- modules/core/include/dpl/abstract_input.h | 9 +- modules/core/include/dpl/abstract_input_output.h | 12 +- modules/core/include/dpl/abstract_output.h | 12 +- modules/core/include/dpl/abstract_waitable_input.h | 11 +- .../include/dpl/abstract_waitable_input_adapter.h | 13 +- .../include/dpl/abstract_waitable_input_output.h | 13 +- .../dpl/abstract_waitable_input_output_adapter.h | 16 +- .../core/include/dpl/abstract_waitable_output.h | 11 +- .../include/dpl/abstract_waitable_output_adapter.h | 13 +- modules/core/include/dpl/address.h | 12 +- modules/core/include/dpl/aligned.h | 3 +- modules/core/include/dpl/application.h | 31 +- modules/core/include/dpl/apply.h | 50 +- modules/core/include/dpl/assert.h | 14 +- modules/core/include/dpl/atomic.h | 9 +- modules/core/include/dpl/auto_ptr.h | 5 +- modules/core/include/dpl/binary_queue.h | 50 +- modules/core/include/dpl/char_traits.h | 11 +- modules/core/include/dpl/colors.h | 20 +- modules/core/include/dpl/copy.h | 16 +- modules/core/include/dpl/enable_shared_from_this.h | 20 +- modules/core/include/dpl/errno_string.h | 3 +- modules/core/include/dpl/exception.h | 162 ++-- modules/core/include/dpl/fast_delegate.h | 3 +- modules/core/include/dpl/file_input.h | 17 +- modules/core/include/dpl/file_output.h | 17 +- modules/core/include/dpl/foreach.h | 19 +- modules/core/include/dpl/generic_event.h | 595 ++++++++------ modules/core/include/dpl/lexical_cast.h | 3 +- modules/core/include/dpl/main.h | 33 +- modules/core/include/dpl/mutex.h | 24 +- modules/core/include/dpl/named_base_pipe.h | 9 +- modules/core/include/dpl/named_input_pipe.h | 9 +- modules/core/include/dpl/named_output_pipe.h | 19 +- modules/core/include/dpl/noncopyable.h | 9 +- modules/core/include/dpl/once.h | 11 +- modules/core/include/dpl/optional.h | 74 +- modules/core/include/dpl/optional_typedefs.h | 5 +- modules/core/include/dpl/preprocessor.h | 2 +- modules/core/include/dpl/read_write_mutex.h | 32 +- modules/core/include/dpl/recursive_mutex.h | 24 +- modules/core/include/dpl/scoped_array.h | 13 +- modules/core/include/dpl/scoped_close.h | 17 +- modules/core/include/dpl/scoped_fclose.h | 18 +- modules/core/include/dpl/scoped_free.h | 13 +- modules/core/include/dpl/scoped_gpointer.h | 10 +- modules/core/include/dpl/scoped_ptr.h | 13 +- modules/core/include/dpl/scoped_resource.h | 13 +- modules/core/include/dpl/semaphore.h | 25 +- modules/core/include/dpl/serialization.h | 480 +++++------ modules/core/include/dpl/shared_ptr.h | 114 +-- modules/core/include/dpl/single_instance.h | 15 +- modules/core/include/dpl/singleton.h | 18 +- modules/core/include/dpl/singleton_impl.h | 9 +- modules/core/include/dpl/singleton_safe_impl.h | 33 +- modules/core/include/dpl/sstream.h | 6 +- modules/core/include/dpl/string.h | 26 +- modules/core/include/dpl/task.h | 68 +- modules/core/include/dpl/task_list.h | 13 +- modules/core/include/dpl/thread.h | 103 +-- modules/core/include/dpl/type_list.h | 31 +- modules/core/include/dpl/union_cast.h | 3 +- modules/core/include/dpl/unused.h | 3 +- modules/core/include/dpl/waitable_event.h | 17 +- modules/core/include/dpl/waitable_handle.h | 29 +- .../include/dpl/waitable_handle_watch_support.h | 50 +- modules/core/include/dpl/zip_input.h | 63 +- .../core/src/abstract_waitable_input_adapter.cpp | 11 +- .../src/abstract_waitable_input_output_adapter.cpp | 18 +- .../core/src/abstract_waitable_output_adapter.cpp | 16 +- modules/core/src/address.cpp | 32 +- modules/core/src/application.cpp | 54 +- modules/core/src/assert.cpp | 27 +- modules/core/src/atomic.cpp | 14 +- modules/core/src/binary_queue.cpp | 109 +-- modules/core/src/char_traits.cpp | 6 +- modules/core/src/colors.cpp | 21 +- modules/core/src/copy.cpp | 63 +- modules/core/src/errno_string.cpp | 22 +- modules/core/src/exception.cpp | 14 +- modules/core/src/file_input.cpp | 46 +- modules/core/src/file_output.cpp | 45 +- modules/core/src/main.cpp | 242 +++--- modules/core/src/mutex.cpp | 27 +- modules/core/src/named_base_pipe.cpp | 14 +- modules/core/src/named_output_pipe.cpp | 39 +- modules/core/src/noncopyable.cpp | 9 +- modules/core/src/once.cpp | 9 +- modules/core/src/read_write_mutex.cpp | 26 +- modules/core/src/recursive_mutex.cpp | 19 +- modules/core/src/semaphore.cpp | 124 ++- modules/core/src/single_instance.cpp | 41 +- modules/core/src/string.cpp | 85 +- modules/core/src/task_list.cpp | 38 +- modules/core/src/thread.cpp | 340 ++++---- modules/core/src/waitable_event.cpp | 23 +- modules/core/src/waitable_handle.cpp | 56 +- modules/core/src/waitable_handle_watch_support.cpp | 225 +++--- modules/core/src/zip_input.cpp | 168 ++-- .../dao/CustomHandlerDatabase.cpp | 2 - .../custom_handler_dao/dao/custom_handler_dao.cpp | 159 ++-- .../dao/custom_handler_dao_read_only.cpp | 88 +-- .../custom-handler-dao-ro/CustomHandlerDatabase.h | 20 +- .../custom-handler-dao-ro/common_dao_types.h | 5 +- .../custom_handler_dao_read_only.h | 10 +- .../custom-handler-dao-rw/custom_handler_dao.h | 2 - .../include/dpl/db/naive_synchronization_object.h | 17 +- modules/db/include/dpl/db/orm_interface.h | 17 +- modules/db/include/dpl/db/orm_macros.h | 9 +- modules/db/include/dpl/db/sql_connection.h | 37 +- .../db/include/dpl/db/thread_database_support.h | 23 +- modules/db/src/naive_synchronization_object.cpp | 11 +- modules/db/src/orm.cpp | 32 +- modules/db/src/sql_connection.cpp | 239 +++--- modules/dbus/include/dpl/dbus/connection.h | 26 +- modules/dbus/include/dpl/dbus/dbus_client.h | 97 ++- .../dbus/include/dpl/dbus/dbus_deserialization.h | 79 +- .../include/dpl/dbus/dbus_interface_dispatcher.h | 18 +- modules/dbus/include/dpl/dbus/dbus_serialization.h | 48 +- .../include/dpl/dbus/dbus_server_deserialization.h | 17 +- .../include/dpl/dbus/dbus_server_serialization.h | 13 +- modules/dbus/include/dpl/dbus/dbus_signature.h | 26 +- modules/dbus/include/dpl/dbus/dispatcher.h | 8 +- modules/dbus/include/dpl/dbus/exception.h | 2 - modules/dbus/include/dpl/dbus/interface.h | 10 +- modules/dbus/include/dpl/dbus/method_proxy.h | 66 +- modules/dbus/include/dpl/dbus/object.h | 6 +- modules/dbus/include/dpl/dbus/object_proxy.h | 29 +- modules/dbus/include/dpl/dbus/server.h | 17 +- modules/dbus/src/connection.cpp | 130 ++- modules/dbus/src/dispatcher.cpp | 8 +- modules/dbus/src/interface.cpp | 50 +- modules/dbus/src/object.cpp | 11 +- modules/dbus/src/object_proxy.cpp | 10 +- modules/dbus/src/server.cpp | 36 +- .../include/dpl/encryption/resource_decryption.h | 39 +- .../include/dpl/encryption/resource_encryption.h | 38 +- modules/encryption/src/resource_decryption.cpp | 23 +- modules/encryption/src/resource_encryption.cpp | 17 +- .../event/include/dpl/event/abstract_event_call.h | 15 +- .../include/dpl/event/abstract_event_dispatcher.h | 20 +- modules/event/include/dpl/event/controller.h | 85 +- modules/event/include/dpl/event/event_listener.h | 20 +- modules/event/include/dpl/event/event_support.h | 366 ++++----- .../event/include/dpl/event/generic_event_call.h | 31 +- .../include/dpl/event/inter_context_delegate.h | 61 +- .../include/dpl/event/main_event_dispatcher.h | 53 +- modules/event/include/dpl/event/model.h | 16 +- .../event/include/dpl/event/model_bind_to_dao.h | 8 +- modules/event/include/dpl/event/property.h | 204 +++-- .../include/dpl/event/thread_event_dispatcher.h | 19 +- modules/event/src/abstract_event_call.cpp | 14 +- modules/event/src/abstract_event_dispatcher.cpp | 17 +- modules/event/src/event_support.cpp | 9 +- modules/event/src/main_event_dispatcher.cpp | 154 ++-- modules/event/src/model.cpp | 9 +- modules/event/src/thread_event_dispatcher.cpp | 45 +- .../localization/include/LanguageTagsProvider.h | 13 +- .../include/dpl/localization/localization_utils.h | 3 +- .../dpl/localization/w3c_file_localization.h | 39 +- modules/localization/src/LanguageTagsProvider.cpp | 39 +- modules/localization/src/localization_utils.cpp | 8 +- modules/localization/src/w3c_file_localization.cpp | 112 +-- .../log/include/dpl/log/abstract_log_provider.h | 37 +- modules/log/include/dpl/log/dlog_log_provider.h | 47 +- modules/log/include/dpl/log/log.h | 79 +- .../log/include/dpl/log/old_style_log_provider.h | 51 +- modules/log/src/abstract_log_provider.cpp | 6 +- modules/log/src/dlog_log_provider.cpp | 65 +- modules/log/src/log.cpp | 137 ++-- modules/log/src/old_style_log_provider.cpp | 110 ++- .../rpc/include/dpl/rpc/abstract_rpc_connection.h | 26 +- .../rpc/include/dpl/rpc/abstract_rpc_connector.h | 21 +- .../rpc/include/dpl/rpc/generic_rpc_connection.h | 21 +- .../include/dpl/rpc/generic_socket_rpc_client.h | 79 +- .../dpl/rpc/generic_socket_rpc_connection.h | 21 +- .../include/dpl/rpc/generic_socket_rpc_server.h | 83 +- modules/rpc/include/dpl/rpc/rpc_function.h | 39 +- .../rpc/include/dpl/rpc/unix_socket_rpc_client.h | 19 +- .../include/dpl/rpc/unix_socket_rpc_connection.h | 14 +- .../rpc/include/dpl/rpc/unix_socket_rpc_server.h | 19 +- modules/rpc/src/generic_rpc_connection.cpp | 132 ++-- modules/rpc/src/generic_socket_rpc_client.cpp | 3 +- modules/rpc/src/generic_socket_rpc_connection.cpp | 3 +- modules/rpc/src/unix_socket_rpc_client.cpp | 12 +- modules/rpc/src/unix_socket_rpc_connection.cpp | 17 +- modules/rpc/src/unix_socket_rpc_server.cpp | 13 +- .../dao/security_origin_dao.cpp | 67 +- .../dao/security_origin_dao_types.cpp | 3 +- .../security-origin-dao/security_origin_dao.h | 3 +- .../security_origin_dao_types.h | 14 +- .../security-origin-dao/security_origin_database.h | 8 +- .../socket/include/dpl/socket/abstract_socket.h | 183 +++-- modules/socket/include/dpl/socket/generic_socket.h | 879 ++++++++++++--------- modules/socket/include/dpl/socket/unix_socket.h | 32 +- ...itable_input_output_execution_context_support.h | 28 +- modules/socket/src/unix_socket.cpp | 42 +- ...able_input_output_execution_context_support.cpp | 149 ++-- modules/support/wrt_plugin_export.h | 17 +- .../test/include/dpl/test/test_results_collector.h | 33 +- modules/test/include/dpl/test/test_runner.h | 89 ++- modules/test/include/dpl/test/test_runner_child.h | 2 - modules/test/src/test_results_collector.cpp | 422 +++++----- modules/test/src/test_runner.cpp | 172 ++-- modules/test/src/test_runner_child.cpp | 91 ++- modules/utils/include/dpl/utils/bash_utils.h | 4 +- modules/utils/include/dpl/utils/file_utils.h | 1 - modules/utils/include/dpl/utils/folder_size.h | 2 - modules/utils/include/dpl/utils/mime_type_utils.h | 2 +- modules/utils/include/dpl/utils/warp_iri.h | 5 +- modules/utils/include/dpl/utils/widget_version.h | 65 +- .../utils/include/dpl/utils/wrt_global_settings.h | 2 - modules/utils/include/dpl/utils/wrt_utility.h | 6 +- modules/utils/src/bash_utils.cpp | 19 +- modules/utils/src/file_utils.cpp | 13 +- modules/utils/src/folder_size.cpp | 111 ++- modules/utils/src/mime_type_utils.cpp | 8 +- modules/utils/src/warp_iri.cpp | 26 +- modules/utils/src/widget_version.cpp | 82 +- modules/utils/src/wrt_global_settings.cpp | 38 +- modules/utils/src/wrt_utility.cpp | 135 ++-- modules/widget_dao/dao/WrtDatabase.cpp | 6 +- modules/widget_dao/dao/common_dao_types.cpp | 3 +- modules/widget_dao/dao/config_parser_data.cpp | 40 +- modules/widget_dao/dao/feature_dao.cpp | 22 +- modules/widget_dao/dao/feature_dao_read_only.cpp | 53 +- modules/widget_dao/dao/global_dao.cpp | 25 +- modules/widget_dao/dao/global_dao_read_only.cpp | 52 +- modules/widget_dao/dao/path_builder.cpp | 13 +- modules/widget_dao/dao/plugin_dao.cpp | 33 +- modules/widget_dao/dao/plugin_dao_read_only.cpp | 26 +- modules/widget_dao/dao/property_dao.cpp | 11 +- modules/widget_dao/dao/property_dao_read_only.cpp | 23 +- modules/widget_dao/dao/widget_dao.cpp | 148 ++-- modules/widget_dao/dao/widget_dao_read_only.cpp | 180 ++--- .../include/dpl/wrt-dao-ro/WrtDatabase.h | 4 +- .../include/dpl/wrt-dao-ro/common_dao_types.h | 78 +- .../include/dpl/wrt-dao-ro/config_parser_data.h | 47 +- .../include/dpl/wrt-dao-ro/feature_dao_read_only.h | 4 +- .../include/dpl/wrt-dao-ro/feature_model.h | 13 +- .../include/dpl/wrt-dao-ro/global_config.h | 1 - .../include/dpl/wrt-dao-ro/global_dao_read_only.h | 7 +- .../include/dpl/wrt-dao-ro/path_builder.h | 2 - .../include/dpl/wrt-dao-ro/plugin_dao_read_only.h | 13 +- .../dpl/wrt-dao-ro/property_dao_read_only.h | 16 +- .../include/dpl/wrt-dao-ro/vconf_config.h | 1 - .../include/dpl/wrt-dao-ro/webruntime_database.h | 24 +- .../include/dpl/wrt-dao-ro/widget_config.h | 1 - .../include/dpl/wrt-dao-ro/widget_dao_read_only.h | 78 +- .../include/dpl/wrt-dao-rw/feature_dao.h | 6 +- .../widget_dao/include/dpl/wrt-dao-rw/global_dao.h | 5 +- .../widget_dao/include/dpl/wrt-dao-rw/plugin_dao.h | 22 +- .../include/dpl/wrt-dao-rw/property_dao.h | 5 +- .../widget_dao/include/dpl/wrt-dao-rw/widget_dao.h | 144 ++-- modules/widget_dao/orm/wrt_db_sql_generator.h | 3 +- tests/common/include/loop_control.h | 6 +- tests/common/src/loop_control.cpp | 7 +- tests/dao/TestCases_CustomHandlerDAO.cpp | 24 +- tests/dao/TestCases_FeatureDAO.cpp | 100 +-- tests/dao/TestCases_GlobalDAO.cpp | 50 +- tests/dao/TestCases_PluginDAO.cpp | 185 ++--- tests/dao/TestCases_PropertyDAO.cpp | 81 +- tests/dao/TestCases_WidgetDAO.cpp | 557 +++++++------ tests/dao/tests_dao.cpp | 7 +- tests/dpl/core/test_binary_queue.cpp | 38 +- tests/dpl/core/test_fast_delegate.cpp | 72 +- tests/dpl/core/test_foreach.cpp | 12 +- tests/dpl/core/test_log_unhandled_exception.cpp | 22 +- tests/dpl/core/test_once.cpp | 23 +- tests/dpl/core/test_scoped_fclose.cpp | 8 +- tests/dpl/core/test_semaphore.cpp | 24 +- tests/dpl/core/test_serialization.cpp | 121 +-- tests/dpl/core/test_string.cpp | 79 +- tests/dpl/core/test_thread.cpp | 10 +- tests/dpl/db/orm/dpl_orm_test_db_sql_generator.h | 3 +- tests/dpl/db/test_orm.cpp | 460 +++++++---- tests/dpl/db/test_sql_connection.cpp | 76 +- tests/dpl/dbus/dbus_test.cpp | 12 +- tests/dpl/dbus/dbus_test.h | 11 +- tests/dpl/dbus/main.cpp | 3 +- tests/dpl/dbus/test_cases.cpp | 87 +- tests/dpl/dbus/test_service.cpp | 33 +- tests/dpl/event/test_controller.cpp | 200 +++-- tests/dpl/event/test_event_support.cpp | 58 +- tests/dpl/event/test_ic_delegate.cpp | 96 ++- tests/dpl/event/test_property.cpp | 49 +- .../dpl/wrt-dao-ro/common_dao_types.h | 88 +-- .../mockup_include/dpl/wrt-dao-rw/widget_dao.h | 29 +- tests/dpl/localization/mockup_src/widget_dao.cpp | 18 +- tests/dpl/localization/test_suite01.cpp | 53 +- tests/dpl/test/runner_child.cpp | 10 +- tests/dpl/unused/test_caller.cpp | 39 +- tests/dpl/unused/test_crypto_hash.cpp | 51 +- tests/dpl/unused/test_message_queue.cpp | 94 +-- tests/dpl/unused/test_shm.cpp | 340 ++++---- tests/dpl/unused/test_sql_connection.cpp | 10 +- tests/dpl/unused/test_task.cpp | 31 +- tests/dpl/utils/bash_utils.cpp | 19 +- tests/dpl/utils/widget_version.cpp | 19 +- tests/dpl/utils/wrt_utility.cpp | 34 +- uncrustify.cfg | 170 ++++ uncrustify.sh | 1 + 310 files changed, 8518 insertions(+), 7441 deletions(-) mode change 100755 => 100644 modules/core/src/string.cpp mode change 100755 => 100644 modules/widget_dao/dao/config_parser_data.cpp mode change 100755 => 100644 modules/widget_dao/dao/feature_dao.cpp mode change 100755 => 100644 modules/widget_dao/include/dpl/wrt-dao-ro/config_parser_data.h mode change 100755 => 100644 modules/widget_dao/include/dpl/wrt-dao-rw/feature_dao.h create mode 100644 uncrustify.cfg create mode 100755 uncrustify.sh diff --git a/modules/auto_save_dao/dao/AutoSaveDatabase.cpp b/modules/auto_save_dao/dao/AutoSaveDatabase.cpp index 16813c9..5b21316 100644 --- a/modules/auto_save_dao/dao/AutoSaveDatabase.cpp +++ b/modules/auto_save_dao/dao/AutoSaveDatabase.cpp @@ -26,5 +26,5 @@ DPL::DB::SqlConnection::Flag::Type AUTOSAVE_DB_FLAGS = DPL::Mutex g_autoSaveDbQueriesMutex; DPL::DB::ThreadDatabaseSupport Interface::m_autoSavedbInterface( - AUTOSAVE_DB_DATABASE, AUTOSAVE_DB_FLAGS); + AUTOSAVE_DB_DATABASE, AUTOSAVE_DB_FLAGS); diff --git a/modules/auto_save_dao/dao/auto_save_dao.cpp b/modules/auto_save_dao/dao/auto_save_dao.cpp index 9c811a9..8c9ecf5 100644 --- a/modules/auto_save_dao/dao/auto_save_dao.cpp +++ b/modules/auto_save_dao/dao/auto_save_dao.cpp @@ -30,7 +30,6 @@ using namespace DPL::DB::ORM::autosave; using namespace AutoSaveDB::Interface; namespace AutoSaveDB { - #define SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN Try #define SQL_CONNECTION_EXCEPTION_HANDLER_END(message) \ @@ -42,12 +41,10 @@ namespace AutoSaveDB { AutoSaveDAO::AutoSaveDAO() : AutoSaveDAOReadOnly() -{ -} +{} AutoSaveDAO::~AutoSaveDAO() -{ -} +{} void AutoSaveDAO::attachDatabaseRW(void) { @@ -60,8 +57,10 @@ void AutoSaveDAO::detachDatabase(void) m_autoSavedbInterface.DetachFromThread(); } -void AutoSaveDAO::setAutoSaveSubmitFormData(const DPL::String &url, - const SubmitFormData &submitFormData) +void AutoSaveDAO::setAutoSaveSubmitFormData( + const DPL::String &url, + const SubmitFormData & + submitFormData) { SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { @@ -95,5 +94,4 @@ void AutoSaveDAO::setAutoSaveSubmitFormData(const DPL::String &url, } #undef SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN #undef SQL_CONNECTION_EXCEPTION_HANDLER_END - } // namespace AutoSaveDB diff --git a/modules/auto_save_dao/dao/auto_save_dao_read_only.cpp b/modules/auto_save_dao/dao/auto_save_dao_read_only.cpp index 28e0bb6..0089e19 100644 --- a/modules/auto_save_dao/dao/auto_save_dao_read_only.cpp +++ b/modules/auto_save_dao/dao/auto_save_dao_read_only.cpp @@ -31,9 +31,7 @@ using namespace DPL::DB::ORM; using namespace DPL::DB::ORM::autosave; using namespace AutoSaveDB::Interface; - namespace AutoSaveDB { - #define SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN Try #define SQL_CONNECTION_EXCEPTION_HANDLER_END(message) \ @@ -44,12 +42,10 @@ namespace AutoSaveDB { } AutoSaveDAOReadOnly::AutoSaveDAOReadOnly() -{ -} +{} AutoSaveDAOReadOnly::~AutoSaveDAOReadOnly() -{ -} +{} void AutoSaveDAOReadOnly::attachDatabaseRO(void) { @@ -67,7 +63,9 @@ SubmitFormData AutoSaveDAOReadOnly::getAutoSaveSubmitFormData( { SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { - AUTOSAVE_DB_SELECT(select, AutoSaveSubmitFormElement, &m_autoSavedbInterface); + AUTOSAVE_DB_SELECT(select, + AutoSaveSubmitFormElement, + &m_autoSavedbInterface); select->Where(Equals(url)); AutoSaveSubmitFormElement::Select::RowList rows = select->GetRowList(); @@ -85,5 +83,4 @@ SubmitFormData AutoSaveDAOReadOnly::getAutoSaveSubmitFormData( #undef SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN #undef SQL_CONNECTION_EXCEPTION_HANDLER_END - } // namespace AutoSaveDB diff --git a/modules/auto_save_dao/dao/common_dao_types.cpp b/modules/auto_save_dao/dao/common_dao_types.cpp index 0eb25c5..5dec0e7 100644 --- a/modules/auto_save_dao/dao/common_dao_types.cpp +++ b/modules/auto_save_dao/dao/common_dao_types.cpp @@ -25,5 +25,4 @@ #include #include -namespace AutoSaveDB { -} // namespace AutoSaveDB +namespace AutoSaveDB {} // namespace AutoSaveDB diff --git a/modules/auto_save_dao/include/wrt-commons/auto-save-dao-ro/auto_save_dao_read_only.h b/modules/auto_save_dao/include/wrt-commons/auto-save-dao-ro/auto_save_dao_read_only.h index 96a665b..7c1c449 100644 --- a/modules/auto_save_dao/include/wrt-commons/auto-save-dao-ro/auto_save_dao_read_only.h +++ b/modules/auto_save_dao/include/wrt-commons/auto-save-dao-ro/auto_save_dao_read_only.h @@ -31,7 +31,6 @@ #include namespace AutoSaveDB { - class AutoSaveDAOReadOnly { public: @@ -57,10 +56,8 @@ class AutoSaveDAOReadOnly * This method gets Autofill for Webkit */ static SubmitFormData getAutoSaveSubmitFormData( - const DPL::String &url); - + const DPL::String &url); }; - } // namespace AutoSaveDB #endif // _AUTO_SAVE_DAO_READ_ONLY_H_ diff --git a/modules/auto_save_dao/include/wrt-commons/auto-save-dao-rw/auto_save_dao.h b/modules/auto_save_dao/include/wrt-commons/auto-save-dao-rw/auto_save_dao.h index 123d5f1..d0bd940 100644 --- a/modules/auto_save_dao/include/wrt-commons/auto-save-dao-rw/auto_save_dao.h +++ b/modules/auto_save_dao/include/wrt-commons/auto-save-dao-rw/auto_save_dao.h @@ -27,7 +27,6 @@ #include namespace AutoSaveDB { - class AutoSaveDAO : public AutoSaveDAOReadOnly { public: @@ -42,9 +41,8 @@ class AutoSaveDAO : public AutoSaveDAOReadOnly * This method sets Autofill for Webkit */ static void setAutoSaveSubmitFormData( - const DPL::String& url, const SubmitFormData &submitFormData); + const DPL::String& url, const SubmitFormData &submitFormData); }; - } // namespace AutoSaveDB #endif // _AUTO_SAVE_DAO_H_ diff --git a/modules/auto_save_dao/include/wrt-commons/auto-save-dao/AutoSaveDatabase.h b/modules/auto_save_dao/include/wrt-commons/auto-save-dao/AutoSaveDatabase.h index 93404c6..3d7bcd2 100644 --- a/modules/auto_save_dao/include/wrt-commons/auto-save-dao/AutoSaveDatabase.h +++ b/modules/auto_save_dao/include/wrt-commons/auto-save-dao/AutoSaveDatabase.h @@ -24,15 +24,15 @@ extern DPL::Mutex g_autoSaveDbQueriesMutex; #define AUTOSAVE_DB_INTERNAL(tlsCommand, InternalType, interface) \ - static DPL::ThreadLocalVariable *tlsCommand ## Ptr = NULL; \ + static DPL::ThreadLocalVariable *tlsCommand##Ptr = NULL; \ { \ DPL::Mutex::ScopedLock lock(&g_autoSaveDbQueriesMutex); \ - if (!tlsCommand ## Ptr) { \ + if (!tlsCommand##Ptr) { \ static DPL::ThreadLocalVariable tmp; \ - tlsCommand ## Ptr = &tmp; \ + tlsCommand##Ptr = &tmp; \ } \ } \ - DPL::ThreadLocalVariable &tlsCommand = *tlsCommand ## Ptr; \ + DPL::ThreadLocalVariable &tlsCommand = *tlsCommand##Ptr; \ if (tlsCommand.IsNull()) { tlsCommand = InternalType(interface); } #define AUTOSAVE_DB_SELECT(name, type, interface) \ @@ -49,9 +49,7 @@ extern DPL::Mutex g_autoSaveDbQueriesMutex; namespace AutoSaveDB { namespace Interface { - extern DPL::DB::ThreadDatabaseSupport m_autoSavedbInterface; - } // namespace Interface } // namespace AutoSaveDB diff --git a/modules/auto_save_dao/include/wrt-commons/auto-save-dao/common_dao_types.h b/modules/auto_save_dao/include/wrt-commons/auto-save-dao/common_dao_types.h index 420725d..f0c22b6 100644 --- a/modules/auto_save_dao/include/wrt-commons/auto-save-dao/common_dao_types.h +++ b/modules/auto_save_dao/include/wrt-commons/auto-save-dao/common_dao_types.h @@ -28,28 +28,25 @@ #include namespace AutoSaveDB { - struct SubmitFormElement { DPL::String key; DPL::String value; SubmitFormElement() - { - } + {} SubmitFormElement( const DPL::String& keyData, const DPL::String& valueData) : key(keyData), value(valueData) - { - } + {} bool operator== (const SubmitFormElement& other) const { return (!DPL::StringCompare(key, other.key) && - !DPL::StringCompare(value, other.value)); + !DPL::StringCompare(value, other.value)); } bool operator!= (const SubmitFormElement& other) const @@ -58,7 +55,6 @@ struct SubmitFormElement } }; typedef std::list SubmitFormData; - } // namespace AutoSaveDB #endif /* SHARE_COMMON_DAO_TYPES_H_ */ diff --git a/modules/core/include/dpl/abstract_input.h b/modules/core/include/dpl/abstract_input.h index 89ed8fc..8c0e16a 100644 --- a/modules/core/include/dpl/abstract_input.h +++ b/modules/core/include/dpl/abstract_input.h @@ -25,22 +25,21 @@ #include #include -namespace DPL -{ +namespace DPL { class BinaryQueue; typedef std::auto_ptr BinaryQueueAutoPtr; class AbstractInput { -public: + public: class Exception { - public: + public: DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) DECLARE_EXCEPTION_TYPE(Base, ReadFailed) }; -public: + public: virtual ~AbstractInput() {} /** diff --git a/modules/core/include/dpl/abstract_input_output.h b/modules/core/include/dpl/abstract_input_output.h index f775afc..153d5c4 100644 --- a/modules/core/include/dpl/abstract_input_output.h +++ b/modules/core/include/dpl/abstract_input_output.h @@ -25,16 +25,14 @@ #include #include -namespace DPL +namespace DPL { +class AbstractInputOutput : + public AbstractInput, + public AbstractOutput { -class AbstractInputOutput - : public AbstractInput, - public AbstractOutput -{ -public: + public: virtual ~AbstractInputOutput() {} }; - } // namespace DPL #endif // DPL_ABSTRACT_INPUT_OUTPUT_H diff --git a/modules/core/include/dpl/abstract_output.h b/modules/core/include/dpl/abstract_output.h index 160907c..56c86fb 100644 --- a/modules/core/include/dpl/abstract_output.h +++ b/modules/core/include/dpl/abstract_output.h @@ -25,22 +25,21 @@ #include #include -namespace DPL -{ +namespace DPL { class BinaryQueue; typedef std::auto_ptr BinaryQueueAutoPtr; class AbstractOutput { -public: + public: class Exception { - public: + public: DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) DECLARE_EXCEPTION_TYPE(Base, WriteFailed) }; -public: + public: virtual ~AbstractOutput() {} /** @@ -50,7 +49,8 @@ public: * * @param[in] buffer Input buffer with data to be written * @param[in] bufferSize Maximum number of bytes to write from buffer - * @return Number of bytes success successfuly written or zero if output is blocked + * @return Number of bytes success successfuly written or zero if output is + * blocked * @throw WriteFailed */ virtual size_t Write(const BinaryQueue &buffer, size_t bufferSize) = 0; diff --git a/modules/core/include/dpl/abstract_waitable_input.h b/modules/core/include/dpl/abstract_waitable_input.h index 6b39ea7..9d957d6 100644 --- a/modules/core/include/dpl/abstract_waitable_input.h +++ b/modules/core/include/dpl/abstract_waitable_input.h @@ -25,18 +25,15 @@ #include #include -namespace DPL +namespace DPL { +class AbstractWaitableInput : + public AbstractInput { - -class AbstractWaitableInput - : public AbstractInput -{ -public: + public: virtual ~AbstractWaitableInput() {} virtual WaitableHandle WaitableReadHandle() const = 0; }; - } // namespace DPL #endif // DPL_ABSTRACT_WAITABLE_INPUT_H diff --git a/modules/core/include/dpl/abstract_waitable_input_adapter.h b/modules/core/include/dpl/abstract_waitable_input_adapter.h index a9d396a..43efaee 100644 --- a/modules/core/include/dpl/abstract_waitable_input_adapter.h +++ b/modules/core/include/dpl/abstract_waitable_input_adapter.h @@ -26,24 +26,21 @@ #include #include -namespace DPL +namespace DPL { +class AbstractWaitableInputAdapter : + public AbstractWaitableInput { - -class AbstractWaitableInputAdapter - : public AbstractWaitableInput -{ -private: + private: AbstractInput *m_input; WaitableEvent m_waitableEvent; -public: + public: explicit AbstractWaitableInputAdapter(AbstractInput *input); virtual BinaryQueueAutoPtr Read(size_t size); virtual WaitableHandle WaitableReadHandle() const; }; - } // namespace DPL #endif // DPL_ABSTRACT_WAITABLE_INPUT_ADAPTER_H diff --git a/modules/core/include/dpl/abstract_waitable_input_output.h b/modules/core/include/dpl/abstract_waitable_input_output.h index 3d3e6f2..e858f51 100644 --- a/modules/core/include/dpl/abstract_waitable_input_output.h +++ b/modules/core/include/dpl/abstract_waitable_input_output.h @@ -25,17 +25,14 @@ #include #include -namespace DPL +namespace DPL { +class AbstractWaitableInputOutput : + public AbstractWaitableInput, + public AbstractWaitableOutput { - -class AbstractWaitableInputOutput - : public AbstractWaitableInput, - public AbstractWaitableOutput -{ -public: + public: virtual ~AbstractWaitableInputOutput() {} }; - } // namespace DPL #endif // DPL_ABSTRACT_WAITABLE_INPUT_OUTPUT_H diff --git a/modules/core/include/dpl/abstract_waitable_input_output_adapter.h b/modules/core/include/dpl/abstract_waitable_input_output_adapter.h index 6ac2228..a0322d0 100644 --- a/modules/core/include/dpl/abstract_waitable_input_output_adapter.h +++ b/modules/core/include/dpl/abstract_waitable_input_output_adapter.h @@ -26,17 +26,15 @@ #include #include -namespace DPL +namespace DPL { +class AbstractWaitableInputOutputAdapter : + public AbstractWaitableInputAdapter, + public AbstractWaitableOutputAdapter { - -class AbstractWaitableInputOutputAdapter - : public AbstractWaitableInputAdapter, - public AbstractWaitableOutputAdapter -{ -public: - explicit AbstractWaitableInputOutputAdapter(AbstractInputOutput *inputOutput); + public: + explicit AbstractWaitableInputOutputAdapter( + AbstractInputOutput *inputOutput); }; - } // namespace DPL #endif // DPL_ABSTRACT_WAITABLE_INPUT_OUTPUT_ADAPTER_H diff --git a/modules/core/include/dpl/abstract_waitable_output.h b/modules/core/include/dpl/abstract_waitable_output.h index 6cc8d23..abcc3f8 100644 --- a/modules/core/include/dpl/abstract_waitable_output.h +++ b/modules/core/include/dpl/abstract_waitable_output.h @@ -25,18 +25,15 @@ #include #include -namespace DPL +namespace DPL { +class AbstractWaitableOutput : + public AbstractOutput { - -class AbstractWaitableOutput - : public AbstractOutput -{ -public: + public: virtual ~AbstractWaitableOutput() {} virtual WaitableHandle WaitableWriteHandle() const = 0; }; - } // namespace DPL #endif // DPL_ABSTRACT_WAITABLE_OUTPUT_H diff --git a/modules/core/include/dpl/abstract_waitable_output_adapter.h b/modules/core/include/dpl/abstract_waitable_output_adapter.h index 64fc3b3..9e40bc4 100644 --- a/modules/core/include/dpl/abstract_waitable_output_adapter.h +++ b/modules/core/include/dpl/abstract_waitable_output_adapter.h @@ -26,24 +26,21 @@ #include #include -namespace DPL +namespace DPL { +class AbstractWaitableOutputAdapter : + public AbstractWaitableOutput { - -class AbstractWaitableOutputAdapter - : public AbstractWaitableOutput -{ -private: + private: AbstractOutput *m_output; WaitableEvent m_waitableEvent; -public: + public: explicit AbstractWaitableOutputAdapter(AbstractOutput *output); virtual size_t Write(const BinaryQueue &buffer, size_t bufferSize); virtual WaitableHandle WaitableWriteHandle() const; }; - } // namespace DPL #endif // DPL_ABSTRACT_WAITABLE_OUTPUT_ADAPTER_H diff --git a/modules/core/include/dpl/address.h b/modules/core/include/dpl/address.h index 7b1d8e8..05893f9 100644 --- a/modules/core/include/dpl/address.h +++ b/modules/core/include/dpl/address.h @@ -25,23 +25,22 @@ #include #include -namespace DPL -{ +namespace DPL { class Address { -public: + public: class Exception { - public: + public: DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) DECLARE_EXCEPTION_TYPE(Base, InvalidAddress) }; -private: + private: std::string m_address; unsigned short m_port; -public: + public: Address(); Address(const std::string &address); Address(const std::string &address, unsigned short port); @@ -55,7 +54,6 @@ public: bool operator<(const Address &addr) const; }; - } // namespace DPL #endif // DPL_ADDRESS_H diff --git a/modules/core/include/dpl/aligned.h b/modules/core/include/dpl/aligned.h index 902deb6..4400545 100644 --- a/modules/core/include/dpl/aligned.h +++ b/modules/core/include/dpl/aligned.h @@ -17,7 +17,8 @@ * @file aligned.h * @author Lukasz Wrzosek (l.wrzosek@samsung.com) * @version 1.0 - * @brief This file is the implementation file of aligned attribute from gcc + * @brief This file is the implementation file of aligned attribute from + * gcc */ #ifndef DPL_ALIGNED_H #define DPL_ALIGNED_H diff --git a/modules/core/include/dpl/application.h b/modules/core/include/dpl/application.h index f2c309e..d4d9754 100644 --- a/modules/core/include/dpl/application.h +++ b/modules/core/include/dpl/application.h @@ -28,27 +28,26 @@ #include #include -namespace DPL -{ +namespace DPL { class Application { -public: + public: class Exception { - public: + public: DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) DECLARE_EXCEPTION_TYPE(Base, TooManyInstances) DECLARE_EXCEPTION_TYPE(Base, FrameworkError) }; -private: + private: static int app_create(void *data); static int app_terminate(void *data); static int app_pause(void *data); static int app_resume(void *data); static int app_reset(bundle *b, void *data); -protected: + protected: int m_argc; char **m_argv; std::string m_applicationName; @@ -67,15 +66,18 @@ protected: virtual void OnLowBattery(); virtual void OnLanguageChanged(); -public: - Application(int argc, char **argv, const std::string &applicationName, bool showMainWindow = true); + public: + Application(int argc, + char **argv, + const std::string &applicationName, + bool showMainWindow = true); virtual ~Application(); /** * @brief Execute application and start message processing */ virtual int Exec(); - + /* * @brief Sends quit message to application message loop */ @@ -84,8 +86,11 @@ public: class ApplicationExt : public Application { -public: - ApplicationExt(int argc, char **argv, const std::string &applicationName, bool showMainWindow = true); + public: + ApplicationExt(int argc, + char **argv, + const std::string &applicationName, + bool showMainWindow = true); virtual ~ApplicationExt(); /** @@ -97,10 +102,10 @@ public: * @brief Sends quit message to application message loop */ virtual void Quit(); -private: + + private: static DPL::Atomic m_useCount; }; - } // namespace DPL #endif // DPL_APPLICATION_H diff --git a/modules/core/include/dpl/apply.h b/modules/core/include/dpl/apply.h index f441072..fc1be53 100644 --- a/modules/core/include/dpl/apply.h +++ b/modules/core/include/dpl/apply.h @@ -29,8 +29,7 @@ #include #include -namespace DPL -{ +namespace DPL { enum class ExtraArgsInsertPolicy { /** @@ -59,7 +58,7 @@ Result Apply(Operation op, ArgsE && ... extra) { return _ApplyDispatchByPolicy:: - template Apply(op, t, std::forward(extra) ...); + template Apply(op, t, std::forward(extra) ...); } template @@ -76,11 +75,11 @@ struct _ApplyTuple Args && ... args) { return _ApplyTuple:: - template Apply(op, - t1, - t2, - std::get(t1), - std::forward(args) ...); + template Apply(op, + t1, + t2, + std::get(t1), + std::forward(args) ...); } }; @@ -98,11 +97,11 @@ struct _ApplyTuple<0, M> Args && ... args) { return _ApplyTuple<0, M - 1>:: - template Apply(op, - t1, - t2, - std::get(t2), - std::forward(args) ...); + template Apply(op, + t1, + t2, + std::get(t2), + std::forward(args) ...); } }; @@ -131,14 +130,14 @@ struct _ApplyArgs typename ... ArgsT, typename ... Args> static Result Apply(Operation op, - const std::tuple& t, - Args && ... args) + const std::tuple& t, + Args && ... args) { return _ApplyArgs:: - template Apply(op, - t, - std::get(t), - std::forward(args) ...); + template Apply(op, + t, + std::get(t), + std::forward(args) ...); } }; @@ -169,9 +168,9 @@ struct _ApplyDispatchByPolicy ArgsE && ... extra) { return _ApplyArgs:: - template Apply(op, - t, - std::forward(extra) ...); + template Apply(op, + t, + std::forward(extra) ...); } }; @@ -187,9 +186,10 @@ struct _ApplyDispatchByPolicy ArgsE && ... extra) { return _ApplyTuple:: - template Apply(op, - t, - std::make_tuple(std::forward(extra) ...)); + template Apply(op, + t, + std::make_tuple(std::forward( + extra) ...)); } }; } // namespace DPL diff --git a/modules/core/include/dpl/assert.h b/modules/core/include/dpl/assert.h index f0b62f7..59331a0 100644 --- a/modules/core/include/dpl/assert.h +++ b/modules/core/include/dpl/assert.h @@ -24,14 +24,20 @@ #include -namespace DPL -{ +namespace DPL { // Assertion handler procedure // Do not call directly // Always use Assert macro -DPL_NORETURN void AssertProc(const char *condition, const char *file, int line, const char *function); +DPL_NORETURN void AssertProc(const char *condition, + const char *file, + int line, + const char *function); } // namespace DPL -#define Assert(Condition) do { if (!(Condition)) DPL::AssertProc(#Condition, __FILE__, __LINE__, __FUNCTION__); } while (0) +#define Assert(Condition) do { if (!(Condition)) { DPL::AssertProc(#Condition, \ + __FILE__, \ + __LINE__, \ + __FUNCTION__); \ + } } while (0) #endif // DPL_ASSERT_H diff --git a/modules/core/include/dpl/atomic.h b/modules/core/include/dpl/atomic.h index 33ea8a9..50c4a1a 100644 --- a/modules/core/include/dpl/atomic.h +++ b/modules/core/include/dpl/atomic.h @@ -25,17 +25,16 @@ #pragma GCC system_header #include -namespace DPL -{ +namespace DPL { class Atomic { -public: + public: typedef gint ValueType; -private: + private: volatile ValueType m_value; -public: + public: Atomic(ValueType value = static_cast(0)); ValueType ExchangeAndAdd(ValueType value); diff --git a/modules/core/include/dpl/auto_ptr.h b/modules/core/include/dpl/auto_ptr.h index 5fa458e..f5838d8 100644 --- a/modules/core/include/dpl/auto_ptr.h +++ b/modules/core/include/dpl/auto_ptr.h @@ -38,7 +38,7 @@ struct UniversalFree {}; #define DECLARE_DELETER(type, function) \ template <> \ struct UniversalFree { \ - void universal_free(type *ptr){ \ + void universal_free(type * ptr){ \ if (ptr) { \ function(ptr); } \ } \ @@ -50,8 +50,7 @@ class AutoPtr public: AutoPtr(T *ptr) : m_data(ptr) - { - } + {} AutoPtr(const AutoPtr &second) { diff --git a/modules/core/include/dpl/binary_queue.h b/modules/core/include/dpl/binary_queue.h index ae85ceb..f4fa278 100644 --- a/modules/core/include/dpl/binary_queue.h +++ b/modules/core/include/dpl/binary_queue.h @@ -28,30 +28,32 @@ #include #include -namespace DPL -{ +namespace DPL { /** * Binary stream implemented as constant size bucket list * * @todo Add optimized implementation for FlattenConsume */ -class BinaryQueue - : public AbstractInputOutput +class BinaryQueue : + public AbstractInputOutput { -public: + public: class Exception { - public: + public: DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) DECLARE_EXCEPTION_TYPE(Base, OutOfData) }; - typedef void (*BufferDeleter)(const void *buffer, size_t bufferSize, void *userParam); - static void BufferDeleterFree(const void *buffer, size_t bufferSize, void *userParam); + typedef void (*BufferDeleter)(const void *buffer, size_t bufferSize, + void *userParam); + static void BufferDeleterFree(const void *buffer, + size_t bufferSize, + void *userParam); class BucketVisitor { - public: + public: /** * Destructor */ @@ -67,9 +69,9 @@ public: virtual void OnVisitBucket(const void *buffer, size_t bufferSize) = 0; }; -private: - struct Bucket - : private Noncopyable + private: + struct Bucket : + private Noncopyable { const void *buffer; const void *ptr; @@ -79,7 +81,10 @@ private: BufferDeleter deleter; void *param; - Bucket(const void *buffer, size_t bufferSize, BufferDeleter deleter, void *userParam); + Bucket(const void *buffer, + size_t bufferSize, + BufferDeleter deleter, + void *userParam); virtual ~Bucket(); }; @@ -91,17 +96,17 @@ private: class BucketVisitorCall { - private: + private: BucketVisitor *m_visitor; - public: + public: BucketVisitorCall(BucketVisitor *visitor); virtual ~BucketVisitorCall(); void operator()(Bucket *bucket) const; }; -public: + public: /** * Construct empty binary queue */ @@ -148,17 +153,24 @@ public: * @return none * @param[in] buffer Pointer to data buffer * @param[in] bufferSize Number of bytes available in buffer - * @param[in] deleter Pointer to deleter procedure used to free provided buffer + * @param[in] deleter Pointer to deleter procedure used to free provided + * buffer * @param[in] userParam User parameter passed to deleter routine * @exception std::bad_alloc Cannot allocate memory to hold additional data */ - void AppendUnmanaged(const void *buffer, size_t bufferSize, BufferDeleter deleter = &BinaryQueue::BufferDeleterFree, void *userParam = NULL); + void AppendUnmanaged( + const void *buffer, + size_t bufferSize, + BufferDeleter deleter = + &BinaryQueue::BufferDeleterFree, + void *userParam = NULL); /** * Append copy of other binary queue to the end of this binary queue * * @return none - * @param[in] other Constant reference to other binary queue to copy data from + * @param[in] other Constant reference to other binary queue to copy data + * from * @exception std::bad_alloc Cannot allocate memory to hold additional data * @warning One cannot assume that bucket structure is preserved during copy */ diff --git a/modules/core/include/dpl/char_traits.h b/modules/core/include/dpl/char_traits.h index 1b50c51..eb2988f 100644 --- a/modules/core/include/dpl/char_traits.h +++ b/modules/core/include/dpl/char_traits.h @@ -17,8 +17,10 @@ * @file char_traits.h * @author Piotr Marcinkiewicz (p.marcinkiew@samsung.com) * @version 1.0 - * @brief Char traits are used to create basic_string extended with additional features - * Current char traits could be extended in feature to boost performance + * @brief Char traits are used to create basic_string extended with + * additional features + * Current char traits could be extended in feature to boost + * performance */ #ifndef DPL_CHAR_TRAITS #define DPL_CHAR_TRAITS @@ -29,11 +31,8 @@ #include #include -namespace DPL -{ - +namespace DPL { typedef std::char_traits CharTraits; - } // namespace DPL #endif // DPL_CHAR_TRAITS diff --git a/modules/core/include/dpl/colors.h b/modules/core/include/dpl/colors.h index efc104d..c7cfd53 100644 --- a/modules/core/include/dpl/colors.h +++ b/modules/core/include/dpl/colors.h @@ -24,15 +24,9 @@ #ifndef DPL_COLORS_H #define DPL_COLORS_H -namespace DPL -{ - -namespace Colors -{ - -namespace Text -{ - +namespace DPL { +namespace Colors { +namespace Text { extern const char* BOLD_GREEN_BEGIN; extern const char* BOLD_GREEN_END; extern const char* PURPLE_BEGIN; @@ -51,12 +45,9 @@ extern const char* BOLD_GOLD_BEGIN; extern const char* BOLD_GOLD_END; extern const char* BOLD_WHITE_BEGIN; extern const char* BOLD_WHITE_END; - } //namespace Text -namespace Html -{ - +namespace Html { extern const char* BOLD_GREEN_BEGIN; extern const char* BOLD_GREEN_END; extern const char* PURPLE_BEGIN; @@ -75,11 +66,8 @@ extern const char* BOLD_GOLD_BEGIN; extern const char* BOLD_GOLD_END; extern const char* BOLD_WHITE_BEGIN; extern const char* BOLD_WHITE_END; - } //namespace Html - } //namespace Colors - } //namespace DPL #endif /* DPL_COLORS_H */ diff --git a/modules/core/include/dpl/copy.h b/modules/core/include/dpl/copy.h index d91fbbc..e796a61 100644 --- a/modules/core/include/dpl/copy.h +++ b/modules/core/include/dpl/copy.h @@ -26,8 +26,7 @@ #include #include -namespace DPL -{ +namespace DPL { /** * Copy failed exception */ @@ -38,18 +37,23 @@ DECLARE_EXCEPTION_TYPE(Exception, CopyFailed) * * @param[in] input Abstract waitable input to copy from * @param[in] output Abstract waitable output to copy to - * @throw CopyFailed An error occurred while copying. Look into exception trace for details. + * @throw CopyFailed An error occurred while copying. Look into exception trace + * for details. */ void Copy(AbstractWaitableInput *input, AbstractWaitableOutput *output); /** - * Copy exactly totalBytes bytes abstract waitable input to abstract waitable output + * Copy exactly totalBytes bytes abstract waitable input to abstract waitable + * output * * @param[in] input Abstract waitable input to copy from * @param[in] output Abstract waitable output to copy to - * @throw CopyFailed An error occurred while copying. Look into exception trace for details. + * @throw CopyFailed An error occurred while copying. Look into exception trace + * for details. */ -void Copy(AbstractWaitableInput *input, AbstractWaitableOutput *output, size_t totalBytes); +void Copy(AbstractWaitableInput *input, + AbstractWaitableOutput *output, + size_t totalBytes); } // namespace DPL #endif // DPL_COPY_H diff --git a/modules/core/include/dpl/enable_shared_from_this.h b/modules/core/include/dpl/enable_shared_from_this.h index ed84130..0a0fb3a 100644 --- a/modules/core/include/dpl/enable_shared_from_this.h +++ b/modules/core/include/dpl/enable_shared_from_this.h @@ -26,18 +26,16 @@ #include #include -namespace DPL -{ +namespace DPL { template class EnableSharedFromThis : private Noncopyable { - -private: + private: // A weak pointer to shared counter SharedCounter *m_counter; Class *m_ptr; -public: + public: DPL::SharedPtr SharedFromThis() { Assert(m_counter != NULL && "Pointer is not shared!"); @@ -57,15 +55,13 @@ public: m_ptr = ptr; } - EnableSharedFromThis() - : m_counter(NULL), - m_ptr(NULL) - { - } + EnableSharedFromThis() : + m_counter(NULL), + m_ptr(NULL) + {} virtual ~EnableSharedFromThis() - { - } + {} }; } // namespace DPL diff --git a/modules/core/include/dpl/errno_string.h b/modules/core/include/dpl/errno_string.h index d3da348..446dbc9 100644 --- a/modules/core/include/dpl/errno_string.h +++ b/modules/core/include/dpl/errno_string.h @@ -26,8 +26,7 @@ #include #include -namespace DPL -{ +namespace DPL { DECLARE_EXCEPTION_TYPE(DPL::Exception, InvalidErrnoValue) std::string GetErrnoString(int error = errno); diff --git a/modules/core/include/dpl/exception.h b/modules/core/include/dpl/exception.h index a2e3dcf..cdbdc53 100644 --- a/modules/core/include/dpl/exception.h +++ b/modules/core/include/dpl/exception.h @@ -29,25 +29,27 @@ #include #include -namespace DPL -{ +namespace DPL { void LogUnhandledException(const std::string &str); -void LogUnhandledException(const std::string &str, const char *filename, int line, const char *function); +void LogUnhandledException(const std::string &str, + const char *filename, + int line, + const char *function); } -namespace DPL -{ +namespace DPL { class Exception { -private: + private: static unsigned int m_exceptionCount; static Exception* m_lastException; static void (*m_terminateHandler)(); static void AddRef(Exception* exception) { - if (!m_exceptionCount) - m_terminateHandler = std::set_terminate(&TerminateHandler); + if (!m_exceptionCount) { + m_terminateHandler = std::set_terminate(&TerminateHandler); + } ++m_exceptionCount; m_lastException = exception; @@ -55,13 +57,13 @@ private: static void UnRef(Exception* e) { - if (m_lastException == e) + if (m_lastException == e) { m_lastException = NULL; + } --m_exceptionCount; - if (!m_exceptionCount) - { + if (!m_exceptionCount) { std::set_terminate(m_terminateHandler); m_terminateHandler = NULL; } @@ -69,13 +71,10 @@ private: static void TerminateHandler() { - if (m_lastException != NULL) - { + if (m_lastException != NULL) { DisplayKnownException(*m_lastException); abort(); - } - else - { + } else { DisplayUnknownException(); abort(); } @@ -86,15 +85,16 @@ private: std::string m_function; int m_line; -protected: + protected: std::string m_message; std::string m_className; -public: + public: static std::string KnownExceptionToString(const Exception &e) { std::ostringstream message; - message << "\033[1;5;31m\n=== Unhandled DPL exception occurred ===\033[m\n\n"; + message << + "\033[1;5;31m\n=== Unhandled DPL exception occurred ===\033[m\n\n"; message << "\033[1;33mException trace:\033[m\n\n"; message << e.DumpToString(); message << "\033[1;31m\n=== Will now abort ===\033[m\n"; @@ -105,8 +105,9 @@ public: static std::string UnknownExceptionToString() { std::ostringstream message; - message << "\033[1;5;31m\n=== Unhandled non-DPL exception occurred ===\033[m\n\n"; - message << "\033[1;31m\n=== Will now abort ===\033[m\n"; + message << + "\033[1;5;31m\n=== Unhandled non-DPL exception occurred ===\033[m\n\n"; + message << "\033[1;31m\n=== Will now abort ===\033[m\n"; return message.str(); } @@ -124,10 +125,11 @@ public: Exception(const Exception &other) { // Deep copy - if (other.m_reason != NULL) + if (other.m_reason != NULL) { m_reason = new Exception(*other.m_reason); - else + } else { m_reason = NULL; + } m_message = other.m_message; m_path = other.m_path; @@ -141,14 +143,16 @@ public: const Exception &operator =(const Exception &other) { - if (this == &other) + if (this == &other) { return *this; + } // Deep copy - if (other.m_reason != NULL) + if (other.m_reason != NULL) { m_reason = new Exception(*other.m_reason); - else + } else { m_reason = NULL; + } m_message = other.m_message; m_path = other.m_path; @@ -162,30 +166,36 @@ public: return *this; } - Exception(const char *path, const char *function, int line, const std::string &message) - : m_reason(NULL), - m_path(path), - m_function(function), - m_line(line), - m_message(message) + Exception(const char *path, + const char *function, + int line, + const std::string &message) : + m_reason(NULL), + m_path(path), + m_function(function), + m_line(line), + m_message(message) { AddRef(this); } - Exception(const char *path, const char *function, int line, const Exception &reason, const std::string &message) - : m_reason(new Exception(reason)), - m_path(path), - m_function(function), - m_line(line), - m_message(message) + Exception(const char *path, + const char *function, + int line, + const Exception &reason, + const std::string &message) : + m_reason(new Exception(reason)), + m_path(path), + m_function(function), + m_line(line), + m_message(message) { AddRef(this); } virtual ~Exception() throw() { - if (m_reason != NULL) - { + if (m_reason != NULL) { delete m_reason; m_reason = NULL; } @@ -196,16 +206,18 @@ public: void Dump() const { // Show reason first - if (m_reason != NULL) + if (m_reason != NULL) { m_reason->Dump(); + } // Afterward, dump exception const char *file = strchr(m_path.c_str(), '/'); - if (file == NULL) + if (file == NULL) { file = m_path.c_str(); - else + } else { ++file; + } printf("\033[0;36m[%s:%i]\033[m %s() \033[4;35m%s\033[m: %s\033[m\n", file, m_line, @@ -217,24 +229,29 @@ public: std::string DumpToString() const { std::string ret; - if (m_reason != NULL) + if (m_reason != NULL) { ret = m_reason->DumpToString(); + } const char *file = strchr(m_path.c_str(), '/'); - if (file == NULL) + if (file == NULL) { file = m_path.c_str(); - else + } else { ++file; + } char buf[1024]; - snprintf(buf, sizeof(buf), "\033[0;36m[%s:%i]\033[m %s() \033[4;35m%s\033[m: %s\033[m\n", - file, m_line, - m_function.c_str(), - m_className.c_str(), - m_message.empty() ? "" : m_message.c_str()); - - buf[sizeof(buf)-1] = '\n'; + snprintf(buf, + sizeof(buf), + "\033[0;36m[%s:%i]\033[m %s() \033[4;35m%s\033[m: %s\033[m\n", + file, + m_line, + m_function.c_str(), + m_className.c_str(), + m_message.empty() ? "" : m_message.c_str()); + + buf[sizeof(buf) - 1] = '\n'; ret += buf; return ret; @@ -283,30 +300,41 @@ public: std::ostringstream dplLoggingStream; \ dplLoggingStream << Message; \ throw ClassName(__FILE__, __FUNCTION__, __LINE__, dplLoggingStream.str()); \ - }while(0) + } while (0) #define ReThrow(ClassName) \ throw ClassName(__FILE__, __FUNCTION__, __LINE__, _rethrown_exception) #define ReThrowMsg(ClassName, Message) \ - throw ClassName(__FILE__, __FUNCTION__, __LINE__, _rethrown_exception, Message) + throw ClassName(__FILE__, \ + __FUNCTION__, \ + __LINE__, \ + _rethrown_exception, \ + Message) #define Catch(ClassName) \ catch (const ClassName &_rethrown_exception) #define DECLARE_EXCEPTION_TYPE(BaseClass, Class) \ - class Class \ - : public BaseClass \ + class Class : \ + public BaseClass \ { \ - public: \ - Class(const char *path, const char *function, int line, const std::string &message = std::string()) \ - : BaseClass(path, function, line, message) \ + public: \ + Class(const char *path, \ + const char *function, \ + int line, \ + const std::string & message = std::string()) : \ + BaseClass(path, function, line, message) \ { \ BaseClass::m_className = #Class; \ } \ \ - Class(const char *path, const char *function, int line, const DPL::Exception &reason, const std::string &message = std::string()) \ - : BaseClass(path, function, line, reason, message) \ + Class(const char *path, \ + const char *function, \ + int line, \ + const DPL::Exception & reason, \ + const std::string & message = std::string()) : \ + BaseClass(path, function, line, reason, message) \ { \ BaseClass::m_className = #Class; \ } \ @@ -339,10 +367,8 @@ public: abort(); \ } -namespace DPL -{ -namespace CommonException -{ +namespace DPL { +namespace CommonException { /** * Internal exception definitions * @@ -350,7 +376,9 @@ namespace CommonException * Usually, exception trace with internal error includes * important messages. */ -DECLARE_EXCEPTION_TYPE(Exception, InternalError) ///< Unexpected error from underlying libraries or kernel +DECLARE_EXCEPTION_TYPE(Exception, InternalError) ///< Unexpected error from + // underlying libraries or + // kernel } } diff --git a/modules/core/include/dpl/fast_delegate.h b/modules/core/include/dpl/fast_delegate.h index 501c801..8bc1a4b 100644 --- a/modules/core/include/dpl/fast_delegate.h +++ b/modules/core/include/dpl/fast_delegate.h @@ -30,8 +30,7 @@ #include #include -namespace DPL -{ +namespace DPL { using namespace fastdelegate; } // namespace DPL diff --git a/modules/core/include/dpl/file_input.h b/modules/core/include/dpl/file_input.h index d1e4641..3adcf21 100644 --- a/modules/core/include/dpl/file_input.h +++ b/modules/core/include/dpl/file_input.h @@ -26,25 +26,24 @@ #include #include -namespace DPL +namespace DPL { +class FileInput : + private Noncopyable, + public AbstractWaitableInput { -class FileInput - : private Noncopyable, - public AbstractWaitableInput -{ -public: + public: class Exception { - public: + public: DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) DECLARE_EXCEPTION_TYPE(Base, OpenFailed) DECLARE_EXCEPTION_TYPE(Base, CloseFailed) }; -protected: + protected: int m_fd; -public: + public: FileInput(); FileInput(const std::string &fileName); virtual ~FileInput(); diff --git a/modules/core/include/dpl/file_output.h b/modules/core/include/dpl/file_output.h index 48532dc..90be8cd 100644 --- a/modules/core/include/dpl/file_output.h +++ b/modules/core/include/dpl/file_output.h @@ -26,25 +26,24 @@ #include #include -namespace DPL +namespace DPL { +class FileOutput : + private Noncopyable, + public AbstractWaitableOutput { -class FileOutput - : private Noncopyable, - public AbstractWaitableOutput -{ -public: + public: class Exception { - public: + public: DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) DECLARE_EXCEPTION_TYPE(Base, OpenFailed) DECLARE_EXCEPTION_TYPE(Base, CloseFailed) }; -protected: + protected: int m_fd; -public: + public: FileOutput(); FileOutput(const std::string &fileName); virtual ~FileOutput(); diff --git a/modules/core/include/dpl/foreach.h b/modules/core/include/dpl/foreach.h index 0923609..bbe477a 100644 --- a/modules/core/include/dpl/foreach.h +++ b/modules/core/include/dpl/foreach.h @@ -18,18 +18,16 @@ * @author Bartosz Janiak (b.janiak@samsung.com) * @author Lukasz Wrzosek (l.wrzosek@samsung.com) * @version 1.0 - * @brief This file is the implementation file of foreach macro for stl containers + * @brief This file is the implementation file of foreach macro for stl + * containers */ #ifndef DPL_FOREACH_H #define DPL_FOREACH_H #include -namespace DPL -{ -namespace Private -{ - +namespace DPL { +namespace Private { /* * Used to detect type of valid reference to value object. */ @@ -44,23 +42,20 @@ const T& ValueReference(const T& t) { return(t); } - - } //Private } //DPL - #define DPL_FOREACH_IMPL(temporaryName, iterator, container) \ __typeof__ (DPL::Private::ValueReference((container))) & \ temporaryName = (container); \ - for (__typeof__ (temporaryName.begin()) iterator = \ + for (__typeof__ (temporaryName.begin())iterator = \ temporaryName.begin(); \ (iterator) != temporaryName.end(); ++iterator) #define FOREACH(iterator, container) \ DPL_FOREACH_IMPL( \ DPL_MACRO_CONCAT(foreachContainerReference, __COUNTER__), \ - iterator, \ - container) + iterator, \ + container) #endif // DPL_FOREACH_H diff --git a/modules/core/include/dpl/generic_event.h b/modules/core/include/dpl/generic_event.h index 371717a..b20d913 100644 --- a/modules/core/include/dpl/generic_event.h +++ b/modules/core/include/dpl/generic_event.h @@ -22,40 +22,35 @@ #ifndef DPL_GENERIC_EVENT_H #define DPL_GENERIC_EVENT_H -namespace DPL -{ - +namespace DPL { class EventSender { -public: - explicit EventSender(void *sender) - : m_sender(sender) - { - } + public: + explicit EventSender(void *sender) : + m_sender(sender) + {} void* GetSender() const { return m_sender; } -private: + private: void *m_sender; }; class GenericEvent { -protected: + protected: void *m_sender; -public: - explicit GenericEvent(const EventSender &sender) - : m_sender(sender.GetSender()) - { - } + public: + explicit GenericEvent(const EventSender &sender) : + m_sender(sender.GetSender()) + {} virtual ~GenericEvent() - { - } + {} void *GetSender() const { @@ -63,46 +58,40 @@ public: } }; -class GenericEvent0 - : public GenericEvent +class GenericEvent0 : + public GenericEvent { -public: - explicit GenericEvent0(const EventSender &sender) - : GenericEvent(sender) - { - } + public: + explicit GenericEvent0(const EventSender &sender) : + GenericEvent(sender) + {} virtual ~GenericEvent0() - { - } - + {} }; template -class GenericEvent1 - : public GenericEvent0 +class GenericEvent1 : + public GenericEvent0 { -public: + public: typedef Arg0Type Arg0; -protected: + protected: Arg0 m_arg0; -public: - explicit GenericEvent1(const EventSender &sender) - : GenericEvent0(sender) - { - } + public: + explicit GenericEvent1(const EventSender &sender) : + GenericEvent0(sender) + {} - GenericEvent1(Arg0 arg0, const EventSender &sender) - : GenericEvent0(sender), - m_arg0(arg0) - { - } + GenericEvent1(Arg0 arg0, const EventSender &sender) : + GenericEvent0(sender), + m_arg0(arg0) + {} virtual ~GenericEvent1() - { - } + {} Arg0 GetArg0() const { @@ -111,31 +100,28 @@ public: }; template -class GenericEvent2 - : public GenericEvent1 +class GenericEvent2 : + public GenericEvent1 { -public: + public: typedef Arg0Type Arg0; typedef Arg1Type Arg1; -protected: + protected: Arg1 m_arg1; -public: - explicit GenericEvent2(const EventSender &sender) - : GenericEvent1(sender) - { - } + public: + explicit GenericEvent2(const EventSender &sender) : + GenericEvent1(sender) + {} - GenericEvent2(Arg0 arg0, Arg1 arg1, const EventSender &sender) - : GenericEvent1(arg0, sender), - m_arg1(arg1) - { - } + GenericEvent2(Arg0 arg0, Arg1 arg1, const EventSender &sender) : + GenericEvent1(arg0, sender), + m_arg1(arg1) + {} virtual ~GenericEvent2() - { - } + {} Arg1 GetArg1() const { @@ -144,32 +130,29 @@ public: }; template -class GenericEvent3 - : public GenericEvent2 +class GenericEvent3 : + public GenericEvent2 { -public: + public: typedef Arg0Type Arg0; typedef Arg1Type Arg1; typedef Arg2Type Arg2; -protected: + protected: Arg2 m_arg2; -public: - explicit GenericEvent3(const EventSender &sender) - : GenericEvent2(sender) - { - } + public: + explicit GenericEvent3(const EventSender &sender) : + GenericEvent2(sender) + {} - GenericEvent3(Arg0 arg0, Arg1 arg1, Arg2 arg2, const EventSender &sender) - : GenericEvent2(arg0, arg1, sender), - m_arg2(arg2) - { - } + GenericEvent3(Arg0 arg0, Arg1 arg1, Arg2 arg2, const EventSender &sender) : + GenericEvent2(arg0, arg1, sender), + m_arg2(arg2) + {} virtual ~GenericEvent3() - { - } + {} Arg2 GetArg2() const { @@ -177,34 +160,36 @@ public: } }; -template -class GenericEvent4 - : public GenericEvent3 +template +class GenericEvent4 : + public GenericEvent3 { -public: + public: typedef Arg0Type Arg0; typedef Arg1Type Arg1; typedef Arg2Type Arg2; typedef Arg3Type Arg3; -protected: + protected: Arg3 m_arg3; -public: - explicit GenericEvent4(const EventSender &sender) - : GenericEvent3(sender) - { - } + public: + explicit GenericEvent4(const EventSender &sender) : + GenericEvent3(sender) + {} - GenericEvent4(Arg0 arg0, Arg1 arg1, Arg2 arg2, Arg3 arg3, const EventSender &sender) - : GenericEvent3(arg0, arg1, arg2, sender), - m_arg3(arg3) - { - } + GenericEvent4(Arg0 arg0, + Arg1 arg1, + Arg2 arg2, + Arg3 arg3, + const EventSender &sender) : + GenericEvent3(arg0, arg1, arg2, sender), + m_arg3(arg3) + {} virtual ~GenericEvent4() - { - } + {} Arg3 GetArg3() const { @@ -212,35 +197,39 @@ public: } }; -template -class GenericEvent5 - : public GenericEvent4 +template +class GenericEvent5 : + public GenericEvent4 { -public: + public: typedef Arg0Type Arg0; typedef Arg1Type Arg1; typedef Arg2Type Arg2; typedef Arg3Type Arg3; typedef Arg4Type Arg4; -protected: + protected: Arg4 m_arg4; -public: - explicit GenericEvent5(const EventSender &sender) - : GenericEvent4(sender) - { - } - - GenericEvent5(Arg0 arg0, Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, const EventSender &sender) - : GenericEvent4(arg0, arg1, arg2, arg3, sender), - m_arg4(arg4) - { - } + public: + explicit GenericEvent5(const EventSender &sender) : + GenericEvent4(sender) + {} + + GenericEvent5(Arg0 arg0, + Arg1 arg1, + Arg2 arg2, + Arg3 arg3, + Arg4 arg4, + const EventSender &sender) : + GenericEvent4(arg0, arg1, arg2, + arg3, sender), + m_arg4(arg4) + {} virtual ~GenericEvent5() - { - } + {} Arg4 GetArg4() const { @@ -248,11 +237,12 @@ public: } }; -template -class GenericEvent6 - : public GenericEvent5 +template +class GenericEvent6 : + public GenericEvent5 { -public: + public: typedef Arg0Type Arg0; typedef Arg1Type Arg1; typedef Arg2Type Arg2; @@ -260,24 +250,32 @@ public: typedef Arg4Type Arg4; typedef Arg5Type Arg5; -protected: + protected: Arg5 m_arg5; -public: - explicit GenericEvent6(const EventSender &sender) - : GenericEvent5(sender) - { - } - - GenericEvent6(Arg0 arg0, Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, const EventSender &sender) - : GenericEvent5(arg0, arg1, arg2, arg3, arg4, sender), - m_arg5(arg5) - { - } + public: + explicit GenericEvent6(const EventSender &sender) : + GenericEvent5(sender) + {} + + GenericEvent6(Arg0 arg0, + Arg1 arg1, + Arg2 arg2, + Arg3 arg3, + Arg4 arg4, + Arg5 arg5, + const EventSender &sender) : + GenericEvent5(arg0, + arg1, + arg2, + arg3, + arg4, + sender), + m_arg5(arg5) + {} virtual ~GenericEvent6() - { - } + {} Arg5 GetArg5() const { @@ -285,11 +283,14 @@ public: } }; -template -class GenericEvent7 - : public GenericEvent6 +template +class GenericEvent7 : + public GenericEvent6 { -public: + public: typedef Arg0Type Arg0; typedef Arg1Type Arg1; typedef Arg2Type Arg2; @@ -298,24 +299,30 @@ public: typedef Arg5Type Arg5; typedef Arg6Type Arg6; -protected: + protected: Arg6 m_arg6; -public: - explicit GenericEvent7(const EventSender &sender) - : GenericEvent6(sender) - { - } - - GenericEvent7(Arg0 arg0, Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, const EventSender &sender) - : GenericEvent6(arg0, arg1, arg2, arg3, arg4, arg5, sender), - m_arg6(arg6) - { - } + public: + explicit GenericEvent7(const EventSender &sender) : + GenericEvent6(sender) + {} + + GenericEvent7(Arg0 arg0, + Arg1 arg1, + Arg2 arg2, + Arg3 arg3, + Arg4 arg4, + Arg5 arg5, + Arg6 arg6, + const EventSender &sender) : + GenericEvent6(arg0, arg1, arg2, arg3, arg4, arg5, sender), + m_arg6(arg6) + {} virtual ~GenericEvent7() - { - } + {} Arg6 GetArg6() const { @@ -323,11 +330,15 @@ public: } }; -template -class GenericEvent8 - : public GenericEvent7 +template +class GenericEvent8 : + public GenericEvent7 { -public: + public: typedef Arg0Type Arg0; typedef Arg1Type Arg1; typedef Arg2Type Arg2; @@ -337,176 +348,290 @@ public: typedef Arg6Type Arg6; typedef Arg7Type Arg7; -protected: + protected: Arg7 m_arg7; -public: - explicit GenericEvent8(const EventSender &sender) - : GenericEvent7(sender) - { - } - - GenericEvent8(Arg0 arg0, Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4, Arg5 arg5, Arg6 arg6, Arg7 arg7, const EventSender &sender) - : GenericEvent7(arg0, arg1, arg2, arg3, arg4, arg5, arg6, sender), - m_arg7(arg7) - { - } + public: + explicit GenericEvent8(const EventSender &sender) : + GenericEvent7(sender) + {} + + GenericEvent8(Arg0 arg0, + Arg1 arg1, + Arg2 arg2, + Arg3 arg3, + Arg4 arg4, + Arg5 arg5, + Arg6 arg6, + Arg7 arg7, + const EventSender &sender) : + GenericEvent7(arg0, arg1, arg2, arg3, arg4, arg5, + arg6, sender), + m_arg7(arg7) + {} virtual ~GenericEvent8() - { - } + {} Arg7 GetArg7() const { return m_arg7; } }; - } // namespace DPL #define DECLARE_GENERIC_EVENT_0(ClassName) \ - class ClassName \ - : public DPL::GenericEvent0 \ + class ClassName : \ + public DPL::GenericEvent0 \ { \ - public: \ - explicit ClassName(const DPL::EventSender &sender = DPL::EventSender(NULL)) \ - : DPL::GenericEvent0(sender) \ + public: \ + explicit ClassName(const DPL::EventSender & sender = \ + DPL::EventSender(NULL)) : \ + DPL::GenericEvent0(sender) \ { \ } \ }; #define DECLARE_GENERIC_EVENT_1(ClassName, Arg0Type) \ - class ClassName \ - : public DPL::GenericEvent1 \ + class ClassName : \ + public DPL::GenericEvent1 \ { \ - public: \ - explicit ClassName(const DPL::EventSender &sender = DPL::EventSender(NULL)) \ - : DPL::GenericEvent1(sender) \ + public: \ + explicit ClassName(const DPL::EventSender & sender = \ + DPL::EventSender(NULL)) : \ + DPL::GenericEvent1(sender) \ { \ } \ \ explicit ClassName(Arg0Type arg0, \ - const DPL::EventSender &sender = DPL::EventSender(NULL)) \ - : DPL::GenericEvent1(arg0, sender) \ + const DPL::EventSender & sender = \ + DPL::EventSender(NULL)) : \ + DPL::GenericEvent1(arg0, sender) \ { \ } \ }; #define DECLARE_GENERIC_EVENT_2(ClassName, Arg0Type, Arg1Type) \ - class ClassName \ - : public DPL::GenericEvent2 \ + class ClassName : \ + public DPL::GenericEvent2 \ { \ - public: \ - explicit ClassName(const DPL::EventSender &sender = DPL::EventSender(NULL)) \ - : DPL::GenericEvent2(sender) \ + public: \ + explicit ClassName(const DPL::EventSender & sender = \ + DPL::EventSender(NULL)) : \ + DPL::GenericEvent2(sender) \ { \ } \ \ ClassName(Arg0Type arg0, Arg1Type arg1, \ - const DPL::EventSender &sender = DPL::EventSender(NULL)) \ - : DPL::GenericEvent2(arg0, arg1, sender) \ + const DPL::EventSender & sender = DPL::EventSender(NULL)) : \ + DPL::GenericEvent2(arg0, arg1, sender) \ { \ } \ }; #define DECLARE_GENERIC_EVENT_3(ClassName, Arg0Type, Arg1Type, Arg2Type) \ - class ClassName \ - : public DPL::GenericEvent3 \ + class ClassName : \ + public DPL::GenericEvent3 \ { \ - public: \ - explicit ClassName(const DPL::EventSender &sender = DPL::EventSender(NULL)) \ - : DPL::GenericEvent3(sender) \ + public: \ + explicit ClassName(const DPL::EventSender & sender = \ + DPL::EventSender(NULL)) : \ + DPL::GenericEvent3(sender) \ { \ } \ \ ClassName(Arg0Type arg0, Arg1Type arg1, Arg2Type arg2, \ - const DPL::EventSender &sender = DPL::EventSender(NULL)) \ - : DPL::GenericEvent3(arg0, arg1, arg2, sender) \ + const DPL::EventSender & sender = DPL::EventSender(NULL)) : \ + DPL::GenericEvent3(arg0, \ + arg1, \ + arg2, \ + sender) \ { \ } \ }; -#define DECLARE_GENERIC_EVENT_4(ClassName, Arg0Type, Arg1Type, Arg2Type, Arg3Type) \ - class ClassName \ - : public DPL::GenericEvent4 \ +#define DECLARE_GENERIC_EVENT_4(ClassName, \ + Arg0Type, \ + Arg1Type, \ + Arg2Type, \ + Arg3Type) \ + class ClassName : \ + public DPL::GenericEvent4 \ { \ - public: \ - explicit ClassName(const DPL::EventSender &sender = DPL::EventSender(NULL)) \ - : DPL::GenericEvent4(sender) \ + public: \ + explicit ClassName(const DPL::EventSender & sender = \ + DPL::EventSender(NULL)) : \ + DPL::GenericEvent4(sender) \ { \ } \ \ ClassName(Arg0Type arg0, Arg1Type arg1, Arg2Type arg2, Arg3Type arg3, \ - const DPL::EventSender &sender = DPL::EventSender(NULL)) \ - : DPL::GenericEvent4(arg0, arg1, arg2, arg3, sender) \ + const DPL::EventSender & sender = DPL::EventSender(NULL)) : \ + DPL::GenericEvent4(arg0, \ + arg1, \ + arg2, \ + arg3, \ + sender) \ { \ } \ }; -#define DECLARE_GENERIC_EVENT_5(ClassName, Arg0Type, Arg1Type, Arg2Type, Arg3Type, Arg4Type) \ - class ClassName \ - : public DPL::GenericEvent5 \ +#define DECLARE_GENERIC_EVENT_5(ClassName, \ + Arg0Type, \ + Arg1Type, \ + Arg2Type, \ + Arg3Type, \ + Arg4Type) \ + class ClassName : \ + public DPL::GenericEvent5 \ { \ - public: \ - explicit ClassName(const DPL::EventSender &sender = DPL::EventSender(NULL)) \ - : DPL::GenericEvent5(sender) \ + public: \ + explicit ClassName(const DPL::EventSender & sender = \ + DPL::EventSender(NULL)) : \ + DPL::GenericEvent5( \ + sender) \ { \ } \ \ - ClassName(Arg0Type arg0, Arg1Type arg1, Arg2Type arg2, Arg3Type arg3, Arg4Type arg4, \ - const DPL::EventSender &sender = DPL::EventSender(NULL)) \ - : DPL::GenericEvent5(arg0, arg1, arg2, arg3, arg4, sender) \ + ClassName(Arg0Type arg0, \ + Arg1Type arg1, \ + Arg2Type arg2, \ + Arg3Type arg3, \ + Arg4Type arg4, \ + const DPL::EventSender & sender = DPL::EventSender(NULL)) : \ + DPL::GenericEvent5( \ + arg0, \ + arg1, \ + arg2, \ + arg3, \ + arg4, \ + sender) \ { \ } \ }; -#define DECLARE_GENERIC_EVENT_6(ClassName, Arg0Type, Arg1Type, Arg2Type, Arg3Type, Arg4Type, Arg5Type) \ - class ClassName \ - : public DPL::GenericEvent6 \ +#define DECLARE_GENERIC_EVENT_6(ClassName, \ + Arg0Type, \ + Arg1Type, \ + Arg2Type, \ + Arg3Type, \ + Arg4Type, \ + Arg5Type) \ + class ClassName : \ + public DPL::GenericEvent6 \ { \ - public: \ - explicit ClassName(const DPL::EventSender &sender = DPL::EventSender(NULL)) \ - : DPL::GenericEvent6(sender) \ + public: \ + explicit ClassName(const DPL::EventSender & sender = \ + DPL::EventSender(NULL)) : \ + DPL::GenericEvent6(sender) \ { \ } \ \ - ClassName(Arg0Type arg0, Arg1Type arg1, Arg2Type arg2, Arg3Type arg3, Arg4Type arg4, Arg5Type arg5, \ - const DPL::EventSender &sender = DPL::EventSender(NULL)) \ - : DPL::GenericEvent6(arg0, arg1, arg2, arg3, arg4, arg5, sender) \ + ClassName(Arg0Type arg0, \ + Arg1Type arg1, \ + Arg2Type arg2, \ + Arg3Type arg3, \ + Arg4Type arg4, \ + Arg5Type arg5, \ + const DPL::EventSender & sender = DPL::EventSender(NULL)) : \ + DPL::GenericEvent6(arg0, \ + arg1, \ + arg2, \ + arg3, \ + arg4, \ + arg5, \ + sender) \ { \ } \ }; -#define DECLARE_GENERIC_EVENT_7(ClassName, Arg0Type, Arg1Type, Arg2Type, Arg3Type, Arg4Type, Arg5Type, Arg6Type) \ - class ClassName \ - : public DPL::GenericEvent7 \ +#define DECLARE_GENERIC_EVENT_7(ClassName, \ + Arg0Type, \ + Arg1Type, \ + Arg2Type, \ + Arg3Type, \ + Arg4Type, \ + Arg5Type, \ + Arg6Type) \ + class ClassName : \ + public DPL::GenericEvent7 \ { \ - public: \ - explicit ClassName(const DPL::EventSender &sender = DPL::EventSender(NULL)) \ - : DPL::GenericEvent7(sender) \ + public: \ + explicit ClassName(const DPL::EventSender & sender = \ + DPL::EventSender(NULL)) : \ + DPL::GenericEvent7(sender) \ { \ } \ \ - ClassName(Arg0Type arg0, Arg1Type arg1, Arg2Type arg2, Arg3Type arg3, Arg4Type arg4, Arg5Type arg5, Arg6Type arg6, \ - const DPL::EventSender &sender = DPL::EventSender(NULL)) \ - : DPL::GenericEvent7(arg0, arg1, arg2, arg3, arg4, arg5, arg6, sender) \ + ClassName(Arg0Type arg0, \ + Arg1Type arg1, \ + Arg2Type arg2, \ + Arg3Type arg3, \ + Arg4Type arg4, \ + Arg5Type arg5, \ + Arg6Type arg6, \ + const DPL::EventSender & sender = DPL::EventSender(NULL)) : \ + DPL::GenericEvent7(arg0, \ + arg1, \ + arg2, \ + arg3, \ + arg4, \ + arg5, \ + arg6, \ + sender) \ { \ } \ }; -#define DECLARE_GENERIC_EVENT_8(ClassName, Arg0Type, Arg1Type, Arg2Type, Arg3Type, Arg4Type, Arg5Type, Arg6Type, Arg7Type) \ - class ClassName \ - : public DPL::GenericEvent8 \ +#define DECLARE_GENERIC_EVENT_8(ClassName, \ + Arg0Type, \ + Arg1Type, \ + Arg2Type, \ + Arg3Type, \ + Arg4Type, \ + Arg5Type, \ + Arg6Type, \ + Arg7Type) \ + class ClassName : \ + public DPL::GenericEvent8 \ { \ - public: \ - explicit ClassName(const DPL::EventSender &sender = DPL::EventSender(NULL)) \ - : DPL::GenericEvent8(sender) \ + public: \ + explicit ClassName(const DPL::EventSender & sender = \ + DPL::EventSender(NULL)) : \ + DPL::GenericEvent8(sender) \ { \ } \ \ - ClassName(Arg0Type arg0, Arg1Type arg1, Arg2Type arg2, Arg3Type arg3, Arg4Type arg4, Arg5Type arg5, Arg6Type arg6, Arg7Type arg7, \ - const DPL::EventSender &sender = DPL::EventSender(NULL)) \ - : DPL::GenericEvent8(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, sender) \ + ClassName(Arg0Type arg0, \ + Arg1Type arg1, \ + Arg2Type arg2, \ + Arg3Type arg3, \ + Arg4Type arg4, \ + Arg5Type arg5, \ + Arg6Type arg6, \ + Arg7Type arg7, \ + const DPL::EventSender & sender = DPL::EventSender(NULL)) : \ + DPL::GenericEvent8(arg0, \ + arg1, \ + arg2, \ + arg3, \ + arg4, \ + arg5, \ + arg6, \ + arg7, \ + sender) \ { \ } \ }; diff --git a/modules/core/include/dpl/lexical_cast.h b/modules/core/include/dpl/lexical_cast.h index 57eb5e0..1b54026 100644 --- a/modules/core/include/dpl/lexical_cast.h +++ b/modules/core/include/dpl/lexical_cast.h @@ -24,8 +24,7 @@ #include -namespace DPL -{ +namespace DPL { template TargetType lexical_cast(const SourceType &data) { diff --git a/modules/core/include/dpl/main.h b/modules/core/include/dpl/main.h index 62bd7e0..cb088cf 100644 --- a/modules/core/include/dpl/main.h +++ b/modules/core/include/dpl/main.h @@ -29,25 +29,27 @@ #include #include -namespace DPL +namespace DPL { +class Main : + public WaitableHandleWatchSupport { -class Main - : public WaitableHandleWatchSupport -{ -public: + public: class Exception { - public: + public: DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) DECLARE_EXCEPTION_TYPE(Base, CreateFailed) }; -protected: + protected: Ecore_Fd_Handler *m_invokerHandler; - static Eina_Bool StaticDispatchInvoker(void *data, Ecore_Fd_Handler *fd_handler); - static Eina_Bool StaticDispatchReadWatcher(void *data, Ecore_Fd_Handler *fd_handler); - static Eina_Bool StaticDispatchWriteWatcher(void *data, Ecore_Fd_Handler *fd_handler); + static Eina_Bool StaticDispatchInvoker(void *data, + Ecore_Fd_Handler *fd_handler); + static Eina_Bool StaticDispatchReadWatcher(void *data, + Ecore_Fd_Handler *fd_handler); + static Eina_Bool StaticDispatchWriteWatcher(void *data, + Ecore_Fd_Handler *fd_handler); typedef std::list EcoreFdHandlerList; @@ -66,13 +68,18 @@ protected: #ifdef DPL_ENABLE_GLIB_LOOP_INTEGRATION_WORKAROUND // GLIB loop intergration workaround - typedef int (*EcoreSelectType)(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout); + typedef int (*EcoreSelectType)(int nfds, fd_set *readfds, fd_set *writefds, + fd_set *exceptfds, struct timeval *timeout); EcoreSelectType m_oldEcoreSelect; - static int EcoreSelectInterceptor(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout); + static int EcoreSelectInterceptor(int nfds, + fd_set *readfds, + fd_set *writefds, + fd_set *exceptfds, + struct timeval *timeout); #endif // DPL_ENABLE_GLIB_LOOP_INTEGRATION_WORKAROUND -public: + public: explicit Main(); virtual ~Main(); }; diff --git a/modules/core/include/dpl/mutex.h b/modules/core/include/dpl/mutex.h index fbc0c5b..315a92c 100644 --- a/modules/core/include/dpl/mutex.h +++ b/modules/core/include/dpl/mutex.h @@ -26,43 +26,41 @@ #include #include -namespace DPL +namespace DPL { +class Mutex : + private Noncopyable { -class Mutex - : private Noncopyable -{ -public: - class ScopedLock - : private Noncopyable + public: + class ScopedLock : + private Noncopyable { - private: + private: Mutex *m_mutex; - public: + public: explicit ScopedLock(Mutex *mutex); ~ScopedLock(); }; class Exception { - public: + public: DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) DECLARE_EXCEPTION_TYPE(Base, CreateFailed) DECLARE_EXCEPTION_TYPE(Base, LockFailed) DECLARE_EXCEPTION_TYPE(Base, UnlockFailed) }; -private: + private: mutable pthread_mutex_t m_mutex; void Lock() const; void Unlock() const; -public: + public: Mutex(); ~Mutex(); }; - } // namespace DPL #endif // DPL_MUTEX_H diff --git a/modules/core/include/dpl/named_base_pipe.h b/modules/core/include/dpl/named_base_pipe.h index ab7630b..45714ef 100644 --- a/modules/core/include/dpl/named_base_pipe.h +++ b/modules/core/include/dpl/named_base_pipe.h @@ -24,21 +24,20 @@ #include -namespace DPL -{ +namespace DPL { class NamedBasePipe { -public: + public: class Exception { - public: + public: DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) DECLARE_EXCEPTION_TYPE(Base, AlreadyExist) DECLARE_EXCEPTION_TYPE(Base, CreateFailed) DECLARE_EXCEPTION_TYPE(Base, DestroyFailed) }; -public: + public: virtual ~NamedBasePipe(); static void Create(const std::string &fileName); diff --git a/modules/core/include/dpl/named_input_pipe.h b/modules/core/include/dpl/named_input_pipe.h index 7f10c5d..cf7b4b7 100644 --- a/modules/core/include/dpl/named_input_pipe.h +++ b/modules/core/include/dpl/named_input_pipe.h @@ -26,11 +26,10 @@ #include #include -namespace DPL -{ -class NamedInputPipe - : public NamedBasePipe, - public FileInput +namespace DPL { +class NamedInputPipe : + public NamedBasePipe, + public FileInput {}; } // namespace DPL diff --git a/modules/core/include/dpl/named_output_pipe.h b/modules/core/include/dpl/named_output_pipe.h index 9855a81..573d1d2 100644 --- a/modules/core/include/dpl/named_output_pipe.h +++ b/modules/core/include/dpl/named_output_pipe.h @@ -27,26 +27,25 @@ #include #include -namespace DPL +namespace DPL { +class NamedOutputPipe : + private Noncopyable, + public NamedBasePipe, + public AbstractWaitableOutput { -class NamedOutputPipe - : private Noncopyable, - public NamedBasePipe, - public AbstractWaitableOutput -{ -public: + public: class Exception { - public: + public: DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) DECLARE_EXCEPTION_TYPE(Base, OpenFailed) DECLARE_EXCEPTION_TYPE(Base, CloseFailed) }; -protected: + protected: int m_fifo; -public: + public: NamedOutputPipe(); virtual ~NamedOutputPipe(); diff --git a/modules/core/include/dpl/noncopyable.h b/modules/core/include/dpl/noncopyable.h index 2cc95d4..98d57dd 100644 --- a/modules/core/include/dpl/noncopyable.h +++ b/modules/core/include/dpl/noncopyable.h @@ -22,18 +22,17 @@ #ifndef DPL_NONCOPYABLE_H #define DPL_NONCOPYABLE_H -namespace DPL -{ +namespace DPL { class Noncopyable { -private: + private: Noncopyable(const Noncopyable &); const Noncopyable &operator=(const Noncopyable &); -public: + + public: Noncopyable(); virtual ~Noncopyable(); }; - } // namespace DPL #endif // DPL_NONCOPYABLE_H diff --git a/modules/core/include/dpl/once.h b/modules/core/include/dpl/once.h index 2b9039e..610f366 100644 --- a/modules/core/include/dpl/once.h +++ b/modules/core/include/dpl/once.h @@ -27,17 +27,16 @@ #include #include -namespace DPL +namespace DPL { +class Once : + private Noncopyable { -class Once - : private Noncopyable -{ -public: + public: typedef FastDelegate Delegate; void Call(Delegate delegate); -private: + private: Atomic m_atomic; Mutex m_mutex; }; diff --git a/modules/core/include/dpl/optional.h b/modules/core/include/dpl/optional.h index 0a0736c..f1fb9ba 100644 --- a/modules/core/include/dpl/optional.h +++ b/modules/core/include/dpl/optional.h @@ -24,31 +24,27 @@ #include -namespace DPL -{ - +namespace DPL { template class Optional { class Exception { - public: + public: DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) DECLARE_EXCEPTION_TYPE(Base, NullReference) }; -public: + public: Optional() : m_null(true), m_value() - { - } + {} Optional(const Type& t) : m_null(false), m_value(t) - { - } + {} bool IsNull() const { @@ -57,25 +53,33 @@ public: Type& operator*() { - if (m_null) Throw(typename Exception::NullReference); + if (m_null) { + Throw(typename Exception::NullReference); + } return m_value; } const Type& operator*() const { - if (m_null) Throw(typename Exception::NullReference); + if (m_null) { + Throw(typename Exception::NullReference); + } return m_value; } const Type* operator->() const { - if (m_null) Throw(typename Exception::NullReference); + if (m_null) { + Throw(typename Exception::NullReference); + } return &m_value; } Type* operator->() { - if (m_null) Throw(typename Exception::NullReference); + if (m_null) { + Throw(typename Exception::NullReference); + } return &m_value; } @@ -93,7 +97,8 @@ public: bool operator==(const Optional& aSecond) const { - return LogicalOperator(*this, aSecond, std::equal_to(), std::equal_to()); + return LogicalOperator(*this, aSecond, + std::equal_to(), std::equal_to()); } bool operator==(const Type& aSecond) const @@ -108,12 +113,14 @@ public: bool operator<(const Optional& aSecond) const { - return LogicalOperator(*this, aSecond, std::less(), std::less()); + return LogicalOperator(*this, aSecond, + std::less(), std::less()); } bool operator>(const Optional& aSecond) const { - return LogicalOperator(*this, aSecond, std::greater(), std::greater()); + return LogicalOperator(*this, aSecond, + std::greater(), std::greater()); } bool operator<=(const Optional& aSecond) const @@ -128,27 +135,23 @@ public: static Optional Null; -private: + private: bool m_null; Type m_value; template - static bool LogicalOperator(const Optional& aFirst, const Optional& aSecond, - taComparator aComparator, taNullComparator aNullComparator) + static bool LogicalOperator(const Optional& aFirst, + const Optional& aSecond, + taComparator aComparator, + taNullComparator aNullComparator) { - if (aFirst.m_null == aSecond.m_null) - { - if (aFirst.m_null) - { + if (aFirst.m_null == aSecond.m_null) { + if (aFirst.m_null) { return taEquality; + } else { + return aComparator(aFirst.m_value, aSecond.m_value); } - else - { - return aComparator(aFirst.m_value, aSecond.m_value); - } - } - else - { + } else { return aNullComparator(aFirst.m_null, aSecond.m_null); } } @@ -156,18 +159,15 @@ private: template Optional Optional::Null = Optional(); - } //namespace DPL template -std::ostream& operator<<(std::ostream& aStream, const DPL::Optional& aOptional) +std::ostream& operator<<(std::ostream& aStream, + const DPL::Optional& aOptional) { - if (aOptional.IsNull()) - { + if (aOptional.IsNull()) { return aStream << "null optional"; - } - else - { + } else { return aStream << *aOptional; } } diff --git a/modules/core/include/dpl/optional_typedefs.h b/modules/core/include/dpl/optional_typedefs.h index 153e4df..356060a 100644 --- a/modules/core/include/dpl/optional_typedefs.h +++ b/modules/core/include/dpl/optional_typedefs.h @@ -19,14 +19,11 @@ #include #include -namespace DPL -{ - +namespace DPL { typedef Optional OptionalString; typedef Optional OptionalInt; typedef Optional OptionalBool; typedef Optional OptionalFloat; - } //namespace DPL #endif /* DPL_OPTIONAL_TYPEDEFS_H */ diff --git a/modules/core/include/dpl/preprocessor.h b/modules/core/include/dpl/preprocessor.h index 83a41e3..0118d76 100644 --- a/modules/core/include/dpl/preprocessor.h +++ b/modules/core/include/dpl/preprocessor.h @@ -26,4 +26,4 @@ #define DPL_MACRO_CONCAT_IMPL(x, y) x##y #define DPL_MACRO_CONCAT(x, y) DPL_MACRO_CONCAT_IMPL(x, y) -#endif//DPL_PREPROCESSOR_H +#endif //DPL_PREPROCESSOR_H diff --git a/modules/core/include/dpl/read_write_mutex.h b/modules/core/include/dpl/read_write_mutex.h index 1e224de..75d9f06 100644 --- a/modules/core/include/dpl/read_write_mutex.h +++ b/modules/core/include/dpl/read_write_mutex.h @@ -26,37 +26,36 @@ #include #include -namespace DPL +namespace DPL { +class ReadWriteMutex : + private Noncopyable { -class ReadWriteMutex - : private Noncopyable -{ -public: - class ScopedReadLock - : private Noncopyable + public: + class ScopedReadLock : + private Noncopyable { - private: + private: ReadWriteMutex *m_mutex; - public: + public: ScopedReadLock(ReadWriteMutex *mutex); virtual ~ScopedReadLock(); }; - class ScopedWriteLock - : private Noncopyable + class ScopedWriteLock : + private Noncopyable { - private: + private: ReadWriteMutex *m_mutex; - public: + public: ScopedWriteLock(ReadWriteMutex *mutex); virtual ~ScopedWriteLock(); }; class Exception { - public: + public: DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) DECLARE_EXCEPTION_TYPE(Base, CreateFailed) DECLARE_EXCEPTION_TYPE(Base, DestroyFailed) @@ -65,18 +64,17 @@ public: DECLARE_EXCEPTION_TYPE(Base, UnlockFailed) }; -private: + private: mutable pthread_rwlock_t m_rwlock; void ReadLock() const; void WriteLock() const; void Unlock() const; -public: + public: explicit ReadWriteMutex(); virtual ~ReadWriteMutex(); }; - } // namespace DPL #endif // DPL_READ_WRITE_MUTEX_H diff --git a/modules/core/include/dpl/recursive_mutex.h b/modules/core/include/dpl/recursive_mutex.h index ec1e23c..e4744cc 100644 --- a/modules/core/include/dpl/recursive_mutex.h +++ b/modules/core/include/dpl/recursive_mutex.h @@ -26,26 +26,25 @@ #include #include -namespace DPL +namespace DPL { +class RecursiveMutex : + private Noncopyable { -class RecursiveMutex - : private Noncopyable -{ -public: - class ScopedLock - : private Noncopyable + public: + class ScopedLock : + private Noncopyable { - private: + private: RecursiveMutex *m_mutex; - public: + public: ScopedLock(RecursiveMutex *mutex); virtual ~ScopedLock(); }; class Exception { - public: + public: DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) DECLARE_EXCEPTION_TYPE(Base, CreateFailed) DECLARE_EXCEPTION_TYPE(Base, DestroyFailed) @@ -53,17 +52,16 @@ public: DECLARE_EXCEPTION_TYPE(Base, UnlockFailed) }; -private: + private: mutable pthread_mutex_t m_mutex; void Lock() const; void Unlock() const; -public: + public: explicit RecursiveMutex(); virtual ~RecursiveMutex(); }; - } // namespace DPL #endif // DPL_RECURSIVE_MUTEX_H diff --git a/modules/core/include/dpl/scoped_array.h b/modules/core/include/dpl/scoped_array.h index fa0c540..48d970f 100644 --- a/modules/core/include/dpl/scoped_array.h +++ b/modules/core/include/dpl/scoped_array.h @@ -27,14 +27,19 @@ #include #include -namespace DPL -{ +namespace DPL { template struct ScopedArrayPolicy { typedef Class* Type; - static Type NullValue() { return NULL; } - static void Destroy(Type ptr) { delete [] ptr; } + static Type NullValue() + { + return NULL; + } + static void Destroy(Type ptr) + { + delete[] ptr; + } }; template diff --git a/modules/core/include/dpl/scoped_close.h b/modules/core/include/dpl/scoped_close.h index e51b7b4..45477af 100644 --- a/modules/core/include/dpl/scoped_close.h +++ b/modules/core/include/dpl/scoped_close.h @@ -29,25 +29,24 @@ #include #include -namespace DPL -{ +namespace DPL { struct ScopedClosePolicy { typedef int Type; - static Type NullValue() { return -1; } + static Type NullValue() + { + return -1; + } static void Destroy(Type handle) { - if (handle != -1) - { - if (TEMP_FAILURE_RETRY(::fsync(handle)) == -1) - { + if (handle != -1) { + if (TEMP_FAILURE_RETRY(::fsync(handle)) == -1) { std::string errString = GetErrnoString(); LogPedantic("Failed to fsync scoped close error: " << errString); } - if (::close(handle) == -1) - { + if (::close(handle) == -1) { std::string errString = GetErrnoString(); LogPedantic("Failed to scoped close error: " << errString); diff --git a/modules/core/include/dpl/scoped_fclose.h b/modules/core/include/dpl/scoped_fclose.h index 9758b8d..b029803 100644 --- a/modules/core/include/dpl/scoped_fclose.h +++ b/modules/core/include/dpl/scoped_fclose.h @@ -22,7 +22,6 @@ #ifndef DPL_SCOPED_FCLOSE_H #define DPL_SCOPED_FCLOSE_H - #include #include #include @@ -31,27 +30,26 @@ #include #include -namespace DPL -{ +namespace DPL { struct ScopedFClosePolicy { typedef FILE* Type; - static Type NullValue() { return NULL; } + static Type NullValue() + { + return NULL; + } static void Destroy(Type file) { - if (file != NULL) - { + if (file != NULL) { // Try to flush first - if (TEMP_FAILURE_RETRY(fflush(file)) != 0) - { + if (TEMP_FAILURE_RETRY(fflush(file)) != 0) { std::string errString = GetErrnoString(); LogPedantic("Failed to fflush scoped fclose error: " << errString); } // fclose cannot be retried, try to close once - if (fclose(file) != 0) - { + if (fclose(file) != 0) { std::string errString = GetErrnoString(); LogPedantic("Failed scoped fclose error: " << errString); } diff --git a/modules/core/include/dpl/scoped_free.h b/modules/core/include/dpl/scoped_free.h index 7b3bd5a..7bebe39 100644 --- a/modules/core/include/dpl/scoped_free.h +++ b/modules/core/include/dpl/scoped_free.h @@ -28,14 +28,19 @@ #include -namespace DPL -{ +namespace DPL { template struct ScopedFreePolicy { typedef Class* Type; - static Type NullValue() { return NULL; } - static void Destroy(Type ptr) { free(ptr); } + static Type NullValue() + { + return NULL; + } + static void Destroy(Type ptr) + { + free(ptr); + } }; template diff --git a/modules/core/include/dpl/scoped_gpointer.h b/modules/core/include/dpl/scoped_gpointer.h index 2f78bec..289d469 100644 --- a/modules/core/include/dpl/scoped_gpointer.h +++ b/modules/core/include/dpl/scoped_gpointer.h @@ -28,9 +28,7 @@ #include #include -namespace DPL -{ - +namespace DPL { struct ScopedGPointerPolicy { typedef gpointer Type; @@ -54,10 +52,9 @@ class ScopedGPointer : public DPL::ScopedResource public: explicit ScopedGPointer(typename Policy::Type pointer = - Policy::NullValue()) : + Policy::NullValue()) : BaseType(pointer) - { - } + {} Class *operator->() const throw() { @@ -73,7 +70,6 @@ class ScopedGPointer : public DPL::ScopedResource return *static_cast(this->m_value); } }; - } // namespace DPL #endif // DPL_SCOPED_GPOINTER_H diff --git a/modules/core/include/dpl/scoped_ptr.h b/modules/core/include/dpl/scoped_ptr.h index 3788dc1..27ab3bf 100644 --- a/modules/core/include/dpl/scoped_ptr.h +++ b/modules/core/include/dpl/scoped_ptr.h @@ -27,14 +27,19 @@ #include #include -namespace DPL -{ +namespace DPL { template struct ScopedPtrPolicy { typedef Class* Type; - static Type NullValue() { return NULL; } - static void Destroy(Type ptr) { delete ptr; } + static Type NullValue() + { + return NULL; + } + static void Destroy(Type ptr) + { + delete ptr; + } }; template > diff --git a/modules/core/include/dpl/scoped_resource.h b/modules/core/include/dpl/scoped_resource.h index a902d72..63287da 100644 --- a/modules/core/include/dpl/scoped_resource.h +++ b/modules/core/include/dpl/scoped_resource.h @@ -24,11 +24,10 @@ #include -namespace DPL -{ +namespace DPL { template -class ScopedResource - : private Noncopyable +class ScopedResource : + private Noncopyable { public: typedef typename ClassPolicy::Type ValueType; @@ -45,7 +44,10 @@ class ScopedResource ClassPolicy::Destroy(m_value); } - ValueType Get() const { return m_value; } + ValueType Get() const + { + return m_value; + } void Reset(ValueType value = ClassPolicy::NullValue()) { @@ -72,7 +74,6 @@ class ScopedResource { return m_value == ClassPolicy::NullValue(); } - }; } // namespace DPL diff --git a/modules/core/include/dpl/semaphore.h b/modules/core/include/dpl/semaphore.h index 8d51071..0505621 100644 --- a/modules/core/include/dpl/semaphore.h +++ b/modules/core/include/dpl/semaphore.h @@ -27,26 +27,25 @@ #include #include -namespace DPL +namespace DPL { +class Semaphore : + private Noncopyable { -class Semaphore - : private Noncopyable -{ -public: - class ScopedLock - : private Noncopyable + public: + class ScopedLock : + private Noncopyable { - private: + private: Semaphore *m_semaphore; - public: + public: explicit ScopedLock(Semaphore *semaphore); ~ScopedLock(); }; class Exception { - public: + public: DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) DECLARE_EXCEPTION_TYPE(Base, CreateFailed) DECLARE_EXCEPTION_TYPE(Base, LockFailed) @@ -54,7 +53,7 @@ public: DECLARE_EXCEPTION_TYPE(Base, RemoveFailed) }; -private: + private: enum Type { Type_Unnamed, @@ -81,7 +80,7 @@ private: sem_t *InternalGet() const; void InternalDestroy(); -public: + public: /** * decrement the semaphore counter */ @@ -92,7 +91,7 @@ public: */ void Unlock() const; - /** + /** * Remove a named semaphore * * @param fileName Name of the semaphore diff --git a/modules/core/include/dpl/serialization.h b/modules/core/include/dpl/serialization.h index 8369665..d72c488 100644 --- a/modules/core/include/dpl/serialization.h +++ b/modules/core/include/dpl/serialization.h @@ -28,264 +28,300 @@ #include namespace DPL { - // Abstract data stream buffer -class IStream { +class IStream +{ public: virtual void Read(size_t num, void * bytes) = 0; virtual void Write(size_t num, const void * bytes) = 0; - virtual ~IStream(){}; + virtual ~IStream(){} }; // Serializable interface -class ISerializable { +class ISerializable +{ public: -/* ISerializable(){}; - ISerializable(IStream&){}; */ + /* ISerializable(){}; + * ISerializable(IStream&){}; */ virtual void Serialize(IStream &) const = 0; - virtual ~ISerializable(){}; + virtual ~ISerializable(){} }; struct Serialization { -// serialization -// normal functions + // serialization + // normal functions -// ISerializable objects -static void Serialize(IStream& stream, const ISerializable& object){ - object.Serialize(stream); -} -static void Serialize(IStream& stream, const ISerializable* const object){ - object->Serialize(stream); -} + // ISerializable objects + static void Serialize(IStream& stream, const ISerializable& object) + { + object.Serialize(stream); + } + static void Serialize(IStream& stream, const ISerializable* const object) + { + object->Serialize(stream); + } -// unsigned int -static void Serialize(IStream& stream, const unsigned value){ - stream.Write(sizeof(value),&value); -} -static void Serialize(IStream& stream, const unsigned* const value){ - stream.Write(sizeof(*value),value); -} + // unsigned int + static void Serialize(IStream& stream, const unsigned value) + { + stream.Write(sizeof(value), &value); + } + static void Serialize(IStream& stream, const unsigned* const value) + { + stream.Write(sizeof(*value), value); + } -// int -static void Serialize(IStream& stream, const int value){ - stream.Write(sizeof(value),&value); -} -static void Serialize(IStream& stream, const int* const value){ - stream.Write(sizeof(*value),value); -} + // int + static void Serialize(IStream& stream, const int value) + { + stream.Write(sizeof(value), &value); + } + static void Serialize(IStream& stream, const int* const value) + { + stream.Write(sizeof(*value), value); + } -// bool -static void Serialize(IStream& stream, const bool value){ - stream.Write(sizeof(value),&value); -} -static void Serialize(IStream& stream, const bool* const value){ - stream.Write(sizeof(*value),value); -} + // bool + static void Serialize(IStream& stream, const bool value) + { + stream.Write(sizeof(value), &value); + } + static void Serialize(IStream& stream, const bool* const value) + { + stream.Write(sizeof(*value), value); + } -// std::string -static void Serialize(IStream& stream, const std::string& str){ - int length = str.size(); - stream.Write(sizeof(length),&length); - stream.Write(length,str.c_str()); -} -static void Serialize(IStream& stream, const std::string* const str){ - int length = str->size(); - stream.Write(sizeof(length),&length); - stream.Write(length,str->c_str()); -} + // std::string + static void Serialize(IStream& stream, const std::string& str) + { + int length = str.size(); + stream.Write(sizeof(length), &length); + stream.Write(length, str.c_str()); + } + static void Serialize(IStream& stream, const std::string* const str) + { + int length = str->size(); + stream.Write(sizeof(length), &length); + stream.Write(length, str->c_str()); + } -// STL templates + // STL templates -// std::list -template -static void Serialize(IStream& stream, const std::list& list){ - int length = list.size(); - stream.Write(sizeof(length),&length); - for(typename std::list::const_iterator list_iter = list.begin(); - list_iter != list.end(); list_iter++) - { - Serialize(stream, *list_iter); - } -} -template -static void Serialize(IStream& stream, const std::list* const list){ - Serialize(stream,*list); -} + // std::list + template + static void Serialize(IStream& stream, const std::list& list) + { + int length = list.size(); + stream.Write(sizeof(length), &length); + for (typename std::list::const_iterator list_iter = list.begin(); + list_iter != list.end(); list_iter++) + { + Serialize(stream, *list_iter); + } + } + template + static void Serialize(IStream& stream, const std::list* const list) + { + Serialize(stream, *list); + } -// std::vector -template -static void Serialize(IStream& stream, const std::vector& vec){ - int length = vec.size(); - stream.Write(sizeof(length),&length); - for(typename std::vector::const_iterator vec_iter = vec.begin(); - vec_iter != vec.end(); vec_iter ++) - { - Serialize(stream, *vec_iter); - } -} -template -static void Serialize(IStream& stream, const std::vector* const vec){ - Serialize(stream,*vec); -} + // std::vector + template + static void Serialize(IStream& stream, const std::vector& vec) + { + int length = vec.size(); + stream.Write(sizeof(length), &length); + for (typename std::vector::const_iterator vec_iter = vec.begin(); + vec_iter != vec.end(); vec_iter++) + { + Serialize(stream, *vec_iter); + } + } + template + static void Serialize(IStream& stream, const std::vector* const vec) + { + Serialize(stream, *vec); + } -// std::pair -template -static void Serialize(IStream& stream, const std::pair& p){ - Serialize(stream, p.first); - Serialize(stream, p.second); -} -template -static void Serialize(IStream& stream, const std::pair* const p){ - Serialize(stream,*p); -} + // std::pair + template + static void Serialize(IStream& stream, const std::pair& p) + { + Serialize(stream, p.first); + Serialize(stream, p.second); + } + template + static void Serialize(IStream& stream, const std::pair* const p) + { + Serialize(stream, *p); + } -// std::map -template -static void Serialize(IStream& stream, const std::map& map){ - int length = map.size(); - stream.Write(sizeof(length),&length); - typename std::map::const_iterator it; - for (it = map.begin(); it != map.end(); ++it) { - Serialize(stream,(*it).first); - Serialize(stream,(*it).second); - } -} -template -static void Serialize(IStream& stream, const std::map* const map){ - Serialize(stream,*map); -} + // std::map + template + static void Serialize(IStream& stream, const std::map& map) + { + int length = map.size(); + stream.Write(sizeof(length), &length); + typename std::map::const_iterator it; + for (it = map.begin(); it != map.end(); ++it) { + Serialize(stream, (*it).first); + Serialize(stream, (*it).second); + } + } + template + static void Serialize(IStream& stream, const std::map* const map) + { + Serialize(stream, *map); + } }; // struct Serialization struct Deserialization { -// deserialization -// normal functions + // deserialization + // normal functions -// ISerializable objects -// T instead of ISerializable is needed to call proper constructor -template -static void Deserialize(IStream& stream, T& object){ - object = T(stream); -} -template -static void Deserialize(IStream& stream, T*& object){ - object = new T(stream); -} + // ISerializable objects + // T instead of ISerializable is needed to call proper constructor + template + static void Deserialize(IStream& stream, T& object) + { + object = T(stream); + } + template + static void Deserialize(IStream& stream, T*& object) + { + object = new T(stream); + } -// unsigned int -static void Deserialize(IStream& stream, unsigned& value){ - stream.Read(sizeof(value),&value); -} -static void Deserialize(IStream& stream, unsigned*& value){ - value = new unsigned; - stream.Read(sizeof(*value),value); -} + // unsigned int + static void Deserialize(IStream& stream, unsigned& value) + { + stream.Read(sizeof(value), &value); + } + static void Deserialize(IStream& stream, unsigned*& value) + { + value = new unsigned; + stream.Read(sizeof(*value), value); + } -// int -static void Deserialize(IStream& stream, int& value){ - stream.Read(sizeof(value),&value); -} -static void Deserialize(IStream& stream, int*& value){ - value = new int; - stream.Read(sizeof(*value),value); -} + // int + static void Deserialize(IStream& stream, int& value) + { + stream.Read(sizeof(value), &value); + } + static void Deserialize(IStream& stream, int*& value) + { + value = new int; + stream.Read(sizeof(*value), value); + } -// bool -static void Deserialize(IStream& stream, bool& value){ - stream.Read(sizeof(value),&value); -} -static void Deserialize(IStream& stream, bool*& value){ - value = new bool; - stream.Read(sizeof(*value),value); -} + // bool + static void Deserialize(IStream& stream, bool& value) + { + stream.Read(sizeof(value), &value); + } + static void Deserialize(IStream& stream, bool*& value) + { + value = new bool; + stream.Read(sizeof(*value), value); + } -// std::string -static void Deserialize(IStream& stream, std::string& str){ - int length; - stream.Read(sizeof(length),&length); - char * buf = new char[length+1]; - stream.Read(length,buf); - buf[length] = 0; - str = std::string(buf); - delete [] buf; -} -static void Deserialize(IStream& stream, std::string*& str){ - int length; - stream.Read(sizeof(length),&length); - char * buf = new char[length+1]; - stream.Read(length,buf); - buf[length] = 0; - str = new std::string(buf); - delete [] buf; -} + // std::string + static void Deserialize(IStream& stream, std::string& str) + { + int length; + stream.Read(sizeof(length), &length); + char * buf = new char[length + 1]; + stream.Read(length, buf); + buf[length] = 0; + str = std::string(buf); + delete[] buf; + } + static void Deserialize(IStream& stream, std::string*& str) + { + int length; + stream.Read(sizeof(length), &length); + char * buf = new char[length + 1]; + stream.Read(length, buf); + buf[length] = 0; + str = new std::string(buf); + delete[] buf; + } -// STL templates + // STL templates -// std::list -template -static void Deserialize(IStream& stream, std::list& list){ - int length; - stream.Read(sizeof(length),&length); - for (int i = 0; i < length; ++i) { - T obj; - Deserialize(stream, obj); - list.push_back(obj); - } -} -template -static void Deserialize(IStream& stream, std::list*& list){ - list = new std::list; - Deserialize(stream,*list); -} + // std::list + template + static void Deserialize(IStream& stream, std::list& list) + { + int length; + stream.Read(sizeof(length), &length); + for (int i = 0; i < length; ++i) { + T obj; + Deserialize(stream, obj); + list.push_back(obj); + } + } + template + static void Deserialize(IStream& stream, std::list*& list) + { + list = new std::list; + Deserialize(stream, *list); + } -// std::vector -template -static void Deserialize(IStream& stream, std::vector& vec){ - int length; - stream.Read(sizeof(length),&length); - for (int i = 0; i < length; ++i) { - T obj; - Deserialize(stream, obj); - vec.push_back(obj); - } -} -template -static void Deserialize(IStream& stream, std::vector*& vec){ - vec = new std::vector; - Deserialize(stream,*vec); -} + // std::vector + template + static void Deserialize(IStream& stream, std::vector& vec) + { + int length; + stream.Read(sizeof(length), &length); + for (int i = 0; i < length; ++i) { + T obj; + Deserialize(stream, obj); + vec.push_back(obj); + } + } + template + static void Deserialize(IStream& stream, std::vector*& vec) + { + vec = new std::vector; + Deserialize(stream, *vec); + } -// std::pair -template -static void Deserialize(IStream& stream, std::pair& p){ - Deserialize(stream, p.first); - Deserialize(stream, p.second); -} -template -static void Deserialize(IStream& stream, std::pair*& p){ - p = new std::pair; - Deserialize(stream,*p); -} + // std::pair + template + static void Deserialize(IStream& stream, std::pair& p) + { + Deserialize(stream, p.first); + Deserialize(stream, p.second); + } + template + static void Deserialize(IStream& stream, std::pair*& p) + { + p = new std::pair; + Deserialize(stream, *p); + } -// std::map -template -static void Deserialize(IStream& stream, std::map& map){ - int length; - stream.Read(sizeof(length),&length); - for (int i = 0; i < length; ++i) { - K key; - T obj; - Deserialize(stream,key); - Deserialize(stream,obj); - map[key] = obj; - } -} -template -static void Deserialize(IStream& stream, std::map*& map){ - map = new std::map; - Deserialize(stream,*map); -} + // std::map + template + static void Deserialize(IStream& stream, std::map& map) + { + int length; + stream.Read(sizeof(length), &length); + for (int i = 0; i < length; ++i) { + K key; + T obj; + Deserialize(stream, key); + Deserialize(stream, obj); + map[key] = obj; + } + } + template + static void Deserialize(IStream& stream, std::map*& map) + { + map = new std::map; + Deserialize(stream, *map); + } }; // struct Deserialization - } // namespace DPL #endif // SERIALIZATION_H diff --git a/modules/core/include/dpl/shared_ptr.h b/modules/core/include/dpl/shared_ptr.h index d2fc91d..0ae6245 100644 --- a/modules/core/include/dpl/shared_ptr.h +++ b/modules/core/include/dpl/shared_ptr.h @@ -28,18 +28,16 @@ #include #include -namespace DPL -{ +namespace DPL { struct StaticPointerCastTag {}; struct ConstPointerCastTag {}; struct DynamicPointerCastTag {}; struct SharedCounter { - SharedCounter() - : ref(1) - { - } + SharedCounter() : + ref(1) + {} Atomic ref; }; @@ -48,7 +46,9 @@ template class EnableSharedFromThis; template -inline void _Internal_AcceptSharedPtr(SharedCounter *counter, Other *other, EnableSharedFromThis *otherBase) +inline void _Internal_AcceptSharedPtr(SharedCounter *counter, + Other *other, + EnableSharedFromThis *otherBase) { otherBase->_Internal_AcceptSharedPtr(counter, other); } @@ -57,22 +57,20 @@ struct AnyPointer { template AnyPointer(Other *) - { - } + {} }; inline void _Internal_AcceptSharedPtr(SharedCounter *, AnyPointer, AnyPointer) -{ -} +{} template class SharedPtr { -public: + public: typedef Class ValueType; typedef SharedPtr ThisType; -private: + private: SharedCounter *m_counter; Class *m_ptr; @@ -81,16 +79,15 @@ private: // Attention: R-Value const cast m_counter = const_cast(counter); - if (m_counter != NULL) + if (m_counter != NULL) { ++m_counter->ref; + } } void DetachCounter() { - if (m_counter) - { - if (!--m_counter->ref) - { + if (m_counter) { + if (!--m_counter->ref) { delete m_ptr; delete m_counter; } @@ -100,34 +97,32 @@ private: } } -public: - SharedPtr() - : m_counter(NULL), - m_ptr(NULL) - { - } + public: + SharedPtr() : + m_counter(NULL), + m_ptr(NULL) + {} - explicit SharedPtr(Class *ptr) - : m_counter(NULL), - m_ptr(ptr) + explicit SharedPtr(Class *ptr) : + m_counter(NULL), + m_ptr(ptr) { - if (m_ptr != NULL) - { + if (m_ptr != NULL) { m_counter = new SharedCounter(); _Internal_AcceptSharedPtr(m_counter, m_ptr, m_ptr); } } - SharedPtr(const SharedPtr &other) - : m_counter(NULL), - m_ptr(other.m_ptr) + SharedPtr(const SharedPtr &other) : + m_counter(NULL), + m_ptr(other.m_ptr) { AttachCounter(other.m_counter); } - SharedPtr(SharedCounter *counter, Class *ptr) - : m_counter(NULL), - m_ptr(ptr) + SharedPtr(SharedCounter *counter, Class *ptr) : + m_counter(NULL), + m_ptr(ptr) { AttachCounter(counter); } @@ -136,32 +131,33 @@ public: friend class SharedPtr; template - SharedPtr(const SharedPtr &other, const StaticPointerCastTag &) - : m_counter(NULL), - m_ptr(NULL) + SharedPtr(const SharedPtr &other, const StaticPointerCastTag &) : + m_counter(NULL), + m_ptr(NULL) { m_ptr = static_cast(other.m_ptr); AttachCounter(other.m_counter); } template - SharedPtr(const SharedPtr &other, const ConstPointerCastTag &) - : m_counter(NULL), - m_ptr(NULL) + SharedPtr(const SharedPtr &other, const ConstPointerCastTag &) : + m_counter(NULL), + m_ptr(NULL) { m_ptr = const_cast(other.m_ptr); AttachCounter(other.m_counter); } template - SharedPtr(const SharedPtr &other, const DynamicPointerCastTag &) - : m_counter(NULL), - m_ptr(NULL) + SharedPtr(const SharedPtr &other, const DynamicPointerCastTag &) : + m_counter(NULL), + m_ptr(NULL) { Class *ptr = dynamic_cast(other.Get()); - if (ptr == NULL) + if (ptr == NULL) { return; + } m_ptr = ptr; AttachCounter(other.m_counter); @@ -193,8 +189,7 @@ public: { DetachCounter(); - if (ptr != NULL) - { + if (ptr != NULL) { m_ptr = ptr; m_counter = new SharedCounter(); _Internal_AcceptSharedPtr(m_counter, m_ptr, m_ptr); @@ -203,8 +198,7 @@ public: SharedPtr &operator=(const SharedPtr &other) { - if (this != &other) - { + if (this != &other) { DetachCounter(); m_ptr = other.m_ptr; AttachCounter(other.m_counter); @@ -215,8 +209,9 @@ public: Atomic::ValueType GetUseCount() const { - if (m_counter == NULL) + if (m_counter == NULL) { return Atomic::ValueType(0); + } return m_counter->ref; } @@ -243,40 +238,45 @@ SharedPtr DynamicPointerCast(const SharedPtr &ptr) } template -inline bool operator ==(const SharedPtr &first, const SharedPtr &second) +inline bool operator ==(const SharedPtr &first, + const SharedPtr &second) { return first.Get() == second.Get(); } template -inline bool operator !=(const SharedPtr &first, const SharedPtr &second) +inline bool operator !=(const SharedPtr &first, + const SharedPtr &second) { return first.Get() != second.Get(); } template -inline bool operator <(const SharedPtr &first, const SharedPtr &second) +inline bool operator <(const SharedPtr &first, + const SharedPtr &second) { return first.Get() < second.Get(); } template -inline bool operator >(const SharedPtr &first, const SharedPtr &second) +inline bool operator >(const SharedPtr &first, + const SharedPtr &second) { return first.Get() > second.Get(); } template -inline bool operator <=(const SharedPtr &first, const SharedPtr &second) +inline bool operator <=(const SharedPtr &first, + const SharedPtr &second) { return first.Get() <= second.Get(); } template -inline bool operator >=(const SharedPtr &first, const SharedPtr &second) +inline bool operator >=(const SharedPtr &first, + const SharedPtr &second) { return first.Get() >= second.Get(); } - } // namespace DPL #endif // DPL_SHARED_PTR_H diff --git a/modules/core/include/dpl/single_instance.h b/modules/core/include/dpl/single_instance.h index a480b2b..afcaf52 100644 --- a/modules/core/include/dpl/single_instance.h +++ b/modules/core/include/dpl/single_instance.h @@ -26,25 +26,24 @@ #include #include -namespace DPL +namespace DPL { +class SingleInstance : + private Noncopyable { -class SingleInstance - : private Noncopyable -{ -public: + public: class Exception { - public: + public: DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) DECLARE_EXCEPTION_TYPE(Base, LockError) DECLARE_EXCEPTION_TYPE(Base, ReleaseError) }; -private: + private: bool m_locked; int m_fdLock; -public: + public: SingleInstance(); virtual ~SingleInstance(); diff --git a/modules/core/include/dpl/singleton.h b/modules/core/include/dpl/singleton.h index 44886d9..530f5c1 100644 --- a/modules/core/include/dpl/singleton.h +++ b/modules/core/include/dpl/singleton.h @@ -26,11 +26,10 @@ #include #include -namespace DPL -{ +namespace DPL { template -class Singleton - : private Class +class Singleton : + private Class { // // Note: @@ -39,23 +38,20 @@ class Singleton // make Class' default constructor protected // -private: + private: Singleton() - { - } + {} typedef Optional OptionalThreadPtr; static Singleton &InternalInstance(); -public: + public: virtual ~Singleton() - { - } + {} static Class &Instance(); }; - } // namespace DPL #endif // DPL_SINGLETON_H diff --git a/modules/core/include/dpl/singleton_impl.h b/modules/core/include/dpl/singleton_impl.h index 6ebe48c..12dbf32 100644 --- a/modules/core/include/dpl/singleton_impl.h +++ b/modules/core/include/dpl/singleton_impl.h @@ -30,9 +30,7 @@ * singleton_safe_impl.h if possible. */ -namespace DPL -{ - +namespace DPL { template Singleton& Singleton::InternalInstance() { @@ -46,11 +44,10 @@ Class &Singleton::Instance() Singleton& instance = Singleton::InternalInstance(); return instance; } - } // namespace DPL #define IMPLEMENT_SINGLETON(Type) \ -template DPL::Singleton& DPL::Singleton::InternalInstance(); \ -template Type& DPL::Singleton::Instance(); \ + template DPL::Singleton&DPL::Singleton::InternalInstance(); \ + template Type & DPL::Singleton::Instance(); \ #endif // DPL_SINGLETON_IMPL_H diff --git a/modules/core/include/dpl/singleton_safe_impl.h b/modules/core/include/dpl/singleton_safe_impl.h index 6bf6451..c8923b7 100644 --- a/modules/core/include/dpl/singleton_safe_impl.h +++ b/modules/core/include/dpl/singleton_safe_impl.h @@ -23,24 +23,23 @@ #define DPL_SINGLETON_SAFE_IMPL_H #define IMPLEMENT_SAFE_SINGLETON(Class) \ -namespace DPL { \ -template<> \ -Singleton& Singleton::InternalInstance() \ -{ \ - static Singleton instance; \ - return instance; \ -} \ + namespace DPL { \ + template<> \ + Singleton&Singleton::InternalInstance() \ + { \ + static Singleton instance; \ + return instance; \ + } \ \ -template<> \ -Class &Singleton::Instance() \ -{ \ - Singleton& instance = Singleton::InternalInstance(); \ - return instance; \ -} \ + template<> \ + Class & Singleton::Instance() \ + { \ + Singleton& instance = Singleton::InternalInstance(); \ + return instance; \ + } \ \ -template Singleton& Singleton::InternalInstance(); \ -template Class& Singleton::Instance(); \ -} // namespace DPL - + template Singleton&Singleton::InternalInstance(); \ + template Class & Singleton::Instance(); \ + } // namespace DPL #endif // DPL_SINGLETON_SAFE_IMPL_H diff --git a/modules/core/include/dpl/sstream.h b/modules/core/include/dpl/sstream.h index 32e21d3..aba4e0f 100644 --- a/modules/core/include/dpl/sstream.h +++ b/modules/core/include/dpl/sstream.h @@ -25,9 +25,7 @@ #include #include -namespace DPL -{ - +namespace DPL { // @brief DPL IStringStream typedef std::basic_istringstream IStringStream; @@ -35,8 +33,6 @@ typedef std::basic_istringstream OStringStream; - } //namespace DPL - #endif // DPL_CORE_INCLUDE_SSTREAM_H_ diff --git a/modules/core/include/dpl/string.h b/modules/core/include/dpl/string.h index 7c35cdb..59cd5e1 100644 --- a/modules/core/include/dpl/string.h +++ b/modules/core/include/dpl/string.h @@ -26,15 +26,14 @@ #include #include -namespace DPL -{ +namespace DPL { // @brief DPL string typedef std::basic_string String; // @brief String exception class class StringException { -public: + public: DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) // @brief Invalid init for UTF8 to UTF32 converter @@ -76,33 +75,36 @@ int StringCompare(const String &left, //@brief Splits the string into substrings. //@param[in] str Input string -//@param[in] delimiters array or string containing a sequence of substring delimiters. Can be also a single delimiter character. +//@param[in] delimiters array or string containing a sequence of substring +// delimiters. Can be also a single delimiter character. //@param[in] it InserterIterator that is used to save the generated substrings. template -void Tokenize(const StringType& str, const Delimiters& delimiters, InserterIterator it, bool ignoreEmpty = false) +void Tokenize(const StringType& str, + const Delimiters& delimiters, + InserterIterator it, + bool ignoreEmpty = false) { typename StringType::size_type nextSearchStart = 0; typename StringType::size_type pos; typename StringType::size_type length; - while ( true ) - { + while (true) { pos = str.find_first_of(delimiters, nextSearchStart); - length = ((pos == StringType::npos) ? str.length() : pos) - nextSearchStart; + length = + ((pos == StringType::npos) ? str.length() : pos) - nextSearchStart; - if ( !ignoreEmpty || length > 0 ) - { + if (!ignoreEmpty || length > 0) { *it = str.substr(nextSearchStart, length); it++; } - if ( pos == StringType::npos ) + if (pos == StringType::npos) { return; + } nextSearchStart = pos + 1; } } - } //namespace DPL std::ostream& operator<<(std::ostream& aStream, const DPL::String& aString); diff --git a/modules/core/include/dpl/task.h b/modules/core/include/dpl/task.h index 84f5b45..393ab4d 100644 --- a/modules/core/include/dpl/task.h +++ b/modules/core/include/dpl/task.h @@ -29,14 +29,13 @@ #include #include -namespace DPL -{ +namespace DPL { class TaskList; -class Task - : private Noncopyable +class Task : + private Noncopyable { -public: + public: virtual ~Task() {} virtual bool NextStep() = 0; @@ -45,13 +44,13 @@ public: }; template -class TaskDecl - : public Task +class TaskDecl : + public Task { -protected: + protected: typedef void (Impl::*Step)(); -private: + private: typedef std::list StepList; StepList m_steps; @@ -63,26 +62,36 @@ private: Impl *m_impl; bool m_running; -protected: + protected: void AddStep(Step step) { Assert(!m_running && "AddStep is not allowed after calling NextStep!"); - Assert(m_steps.end() == std::find(m_steps.begin(), m_steps.end(), step) && "The same step started twice is not supported"); + Assert(m_steps.end() == std::find(m_steps.begin(), + m_steps.end(), + step) && + "The same step started twice is not supported"); m_steps.push_back(step); m_nextStep = m_steps.begin(); } void AddAbortStep(Step step) { - Assert(!m_running && "AddAbortStep is not allowed after calling NextStep!"); - Assert(m_abortSteps.end() == std::find(m_abortSteps.begin(), m_abortSteps.end(), step) && "The same step started twice is not supported"); + Assert( + !m_running && "AddAbortStep is not allowed after calling NextStep!"); + Assert(m_abortSteps.end() == + std::find(m_abortSteps.begin(), + m_abortSteps.end(), + step) && + "The same step started twice is not supported"); m_abortSteps.push_front(step); } void SwitchToStep(Step step) { - /// @TODO There can be problem here if user sets the same method two times in task list. - typename StepList::iterator i = std::find(m_steps.begin(), m_steps.end(), step); + /// @TODO There can be problem here if user sets the same method two + // times in task list. + typename StepList::iterator i = std::find(m_steps.begin(), + m_steps.end(), step); Assert(i != m_steps.end()); m_nextStep = i; m_switched = true; @@ -90,17 +99,18 @@ protected: Step GetCurrentStep() const { - if(m_currentStep == m_steps.end()) + if (m_currentStep == m_steps.end()) { return NULL; + } return *m_currentStep; } -public: - TaskDecl(Impl *impl) - : m_switched(false), - m_impl(impl), - m_running(false) + public: + TaskDecl(Impl *impl) : + m_switched(false), + m_impl(impl), + m_running(false) { Assert(this == m_impl); m_currentStep = m_steps.end(); @@ -111,7 +121,9 @@ public: { m_running = true; - Assert(m_nextStep != m_steps.end() && "Step list is empty or all steps done"); + Assert( + m_nextStep != m_steps.end() && + "Step list is empty or all steps done"); m_switched = false; @@ -120,10 +132,11 @@ public: m_currentStep = m_nextStep; - if (m_switched) + if (m_switched) { return true; - else + } else { return ++m_nextStep != m_steps.end(); + } } bool Abort() @@ -132,11 +145,12 @@ public: m_steps.clear(); - if (m_abortSteps.empty()) + if (m_abortSteps.empty()) { return false; + } - FOREACH (it, m_abortSteps) - m_steps.push_back(*it); + FOREACH(it, m_abortSteps) + m_steps.push_back(*it); m_nextStep = m_steps.begin(); diff --git a/modules/core/include/dpl/task_list.h b/modules/core/include/dpl/task_list.h index b010dfc..2b3d34a 100644 --- a/modules/core/include/dpl/task_list.h +++ b/modules/core/include/dpl/task_list.h @@ -26,12 +26,11 @@ #include #include -namespace DPL +namespace DPL { +class TaskList : + public Task { -class TaskList - : public Task -{ -private: + private: typedef std::list Tasks; Tasks m_tasks; @@ -40,11 +39,11 @@ private: bool m_running; -protected: + protected: void AddTask(Task *task); void SwitchToTask(Task *task); -public: + public: TaskList(); virtual ~TaskList(); diff --git a/modules/core/include/dpl/thread.h b/modules/core/include/dpl/thread.h index 8406282..a0040eb 100644 --- a/modules/core/include/dpl/thread.h +++ b/modules/core/include/dpl/thread.h @@ -39,16 +39,15 @@ #include #include -namespace DPL +namespace DPL { +class Thread : + private Noncopyable, + public WaitableHandleWatchSupport { -class Thread - : private Noncopyable, - public WaitableHandleWatchSupport -{ -public: + public: class Exception { - public: + public: DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) DECLARE_EXCEPTION_TYPE(Base, CreateFailed) DECLARE_EXCEPTION_TYPE(Base, DestroyFailed) @@ -60,7 +59,7 @@ public: typedef void (*EventDeleteProc)(void *event, void *userParam); typedef void (*EventDispatchProc)(void *event, void *userParam); -protected: + protected: /** * Main thread entry * The method is intended to be overloaded with custom code. @@ -74,7 +73,7 @@ protected: */ int Exec(); -private: + private: struct InternalEvent { void *event; @@ -85,17 +84,16 @@ private: InternalEvent(void *eventArg, void *userParamArg, EventDispatchProc eventDispatchProcArg, - EventDeleteProc eventDeleteProcArg) - : event(eventArg), - userParam(userParamArg), - eventDispatchProc(eventDispatchProcArg), - eventDeleteProc(eventDeleteProcArg) - { - } + EventDeleteProc eventDeleteProcArg) : + event(eventArg), + userParam(userParamArg), + eventDispatchProc(eventDispatchProcArg), + eventDeleteProc(eventDeleteProcArg) + {} }; - struct InternalTimedEvent - : InternalEvent + struct InternalTimedEvent : + InternalEvent { unsigned long dueTimeMiliseconds; unsigned long registerTimeMiliseconds; @@ -105,19 +103,19 @@ private: unsigned long dueTimeMilisecondsArg, unsigned long registerTimeMilisecondsArg, EventDispatchProc eventDispatchProcArg, - EventDeleteProc eventDeleteProcArg) - : InternalEvent(eventArg, - userParamArg, - eventDispatchProcArg, - eventDeleteProcArg), - dueTimeMiliseconds(dueTimeMilisecondsArg), - registerTimeMiliseconds(registerTimeMilisecondsArg) - { - } + EventDeleteProc eventDeleteProcArg) : + InternalEvent(eventArg, + userParamArg, + eventDispatchProcArg, + eventDeleteProcArg), + dueTimeMiliseconds(dueTimeMilisecondsArg), + registerTimeMiliseconds(registerTimeMilisecondsArg) + {} bool operator<(const InternalTimedEvent &other) { - return registerTimeMiliseconds + dueTimeMiliseconds > other.registerTimeMiliseconds + other.dueTimeMiliseconds; + return registerTimeMiliseconds + dueTimeMiliseconds > + other.registerTimeMiliseconds + other.dueTimeMiliseconds; } }; @@ -156,7 +154,7 @@ private: static void *StaticThreadEntry(void *param); -public: + public: explicit Thread(); virtual ~Thread(); @@ -186,12 +184,19 @@ public: /** * Low-level event push, usually used only by EventSupport */ - void PushEvent(void *event, EventDispatchProc eventDispatchProc, EventDeleteProc eventDeleteProc, void *userParam); + void PushEvent(void *event, + EventDispatchProc eventDispatchProc, + EventDeleteProc eventDeleteProc, + void *userParam); /** * Low-level timed event push, usually used only by EventSupport */ - void PushTimedEvent(void *event, double dueTimeSeconds, EventDispatchProc eventDispatchProc, EventDeleteProc eventDeleteProc, void *userParam); + void PushTimedEvent(void *event, + double dueTimeSeconds, + EventDispatchProc eventDispatchProc, + EventDeleteProc eventDeleteProc, + void *userParam); /** * Sleep for a number of seconds @@ -223,21 +228,21 @@ extern bool g_TLSforMainCreated; // (process can become non-responsive) // TODO further investigation is required. template -class ThreadLocalVariable - : public Noncopyable +class ThreadLocalVariable : + public Noncopyable { -public: + public: typedef Type ValueType; class Exception { - public: + public: DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) DECLARE_EXCEPTION_TYPE(Base, NullReference) DECLARE_EXCEPTION_TYPE(Base, KeyCreateFailed) }; -private: + private: pthread_key_t m_key; struct ManagedValue @@ -260,12 +265,9 @@ private: { // Destroy underlying type ManagedValue *instance = static_cast(specific); - if(instance->guardKey.IsNull()) - { + if (instance->guardKey.IsNull()) { delete instance; - } - else - { + } else { int result = pthread_setspecific(*(instance->guardKey), instance); Assert(result == 0 && @@ -278,18 +280,16 @@ private: ManagedValue *instance = static_cast(pthread_getspecific(m_key)); - if (!instance) - { + if (!instance) { // Check if it is allowed to instantiate - if (!allowInstantiate) + if (!allowInstantiate) { Throw(typename Exception::NullReference); + } // checking, if specific data is created for Main thread // If yes, pthread_exit(NULL) is required - if (!g_TLSforMainCreated) - { - if (Thread::IsMainThread()) - { + if (!g_TLSforMainCreated) { + if (Thread::IsMainThread()) { g_TLSforMainCreated = true; atexit(&MainThreadExitClean); } @@ -307,13 +307,13 @@ private: return instance->value; } -public: + public: ThreadLocalVariable() { int result = pthread_key_create(&m_key, &InternalDestroy); if (result != 0) { ThrowMsg(typename Exception::KeyCreateFailed, - "Failed to allocate thread local variable: " << result); + "Failed to allocate thread local variable: " << result); } } @@ -364,8 +364,9 @@ public: ManagedValue *specific = static_cast(pthread_getspecific(m_key)); - if (!specific) + if (!specific) { return; + } // TODO Should be an assert? is it developers fault to Reset Guarded // value? diff --git a/modules/core/include/dpl/type_list.h b/modules/core/include/dpl/type_list.h index e5c0f77..88afaf2 100644 --- a/modules/core/include/dpl/type_list.h +++ b/modules/core/include/dpl/type_list.h @@ -24,11 +24,10 @@ #include -namespace DPL -{ +namespace DPL { class TypeListGuard { -public: + public: template struct Element { @@ -42,15 +41,13 @@ public: template class TypeList { -private: + private: class DummyClass - { - }; + {}; template - struct TypeCounter : public TypeCounter - { - }; + struct TypeCounter : public TypeCounter + {}; template struct TypeCounter @@ -58,7 +55,7 @@ private: static const size_t Size = Enum; }; -public: + public: typedef TailType Tail; typedef HeadType Head; typedef TypeList ThisType; @@ -90,11 +87,11 @@ public: static const size_t Size = TypeCounter::Size; }; -template -namespace DPL -{ +namespace DPL { template TargetType union_cast(const SourceType &data) { diff --git a/modules/core/include/dpl/unused.h b/modules/core/include/dpl/unused.h index 18729db..2cbf133 100644 --- a/modules/core/include/dpl/unused.h +++ b/modules/core/include/dpl/unused.h @@ -17,7 +17,8 @@ * @file unused.h * @author Lukasz Wrzosek (l.wrzosek@samsung.com) * @version 1.0 - * @brief This file is the implementation file of unused attribute from gcc + * @brief This file is the implementation file of unused attribute from + * gcc */ #ifndef DPL_UNUSED_H #define DPL_UNUSED_H diff --git a/modules/core/include/dpl/waitable_event.h b/modules/core/include/dpl/waitable_event.h index ee53dfc..364bc5c 100644 --- a/modules/core/include/dpl/waitable_event.h +++ b/modules/core/include/dpl/waitable_event.h @@ -27,16 +27,14 @@ #include #include -namespace DPL +namespace DPL { +class WaitableEvent : + private Noncopyable { - -class WaitableEvent - : private Noncopyable -{ -public: + public: class Exception { - public: + public: DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) DECLARE_EXCEPTION_TYPE(Base, CreateFailed) DECLARE_EXCEPTION_TYPE(Base, DestroyFailed) @@ -44,10 +42,10 @@ public: DECLARE_EXCEPTION_TYPE(Base, ResetFailed) }; -private: + private: int m_pipe[2]; -public: + public: WaitableEvent(); virtual ~WaitableEvent(); @@ -56,7 +54,6 @@ public: void Signal() const; void Reset() const; }; - } // namespace DPL #endif // DPL_WAITABLE_EVENT_H diff --git a/modules/core/include/dpl/waitable_handle.h b/modules/core/include/dpl/waitable_handle.h index 865cca4..9864f78 100644 --- a/modules/core/include/dpl/waitable_handle.h +++ b/modules/core/include/dpl/waitable_handle.h @@ -26,9 +26,7 @@ #include #include -namespace DPL -{ - +namespace DPL { /** * Waitable unix wait handle definition */ @@ -44,7 +42,7 @@ typedef std::vector WaitableHandleList; */ class WaitMode { -public: + public: enum Type { Read, ///< Wait for readability state changes @@ -55,7 +53,8 @@ public: /** * Waitable handle list ex */ -typedef std::vector > WaitableHandleListEx; +typedef std::vector > WaitableHandleListEx; /** * Waitable handle index list @@ -74,7 +73,10 @@ DECLARE_EXCEPTION_TYPE(DPL::Exception, WaitFailed) * @return Signaled waitable handle index list * @throw WaitFailed Fatal error occurred while waiting for signal */ -WaitableHandleIndexList WaitForSingleHandle(WaitableHandle handle, unsigned long miliseconds = 0xFFFFFFFF); +WaitableHandleIndexList WaitForSingleHandle( + WaitableHandle handle, + unsigned long miliseconds = + 0xFFFFFFFF); /** * Wait for single handle @@ -83,7 +85,11 @@ WaitableHandleIndexList WaitForSingleHandle(WaitableHandle handle, unsigned long * @return Signaled waitable handle index list * @throw WaitFailed Fatal error occurred while waiting for signal */ -WaitableHandleIndexList WaitForSingleHandle(WaitableHandle handle, WaitMode::Type mode, unsigned long miliseconds = 0xFFFFFFFF); +WaitableHandleIndexList WaitForSingleHandle( + WaitableHandle handle, + WaitMode::Type mode, + unsigned long miliseconds = + 0xFFFFFFFF); /** * Wait for multiple handles readability @@ -91,7 +97,9 @@ WaitableHandleIndexList WaitForSingleHandle(WaitableHandle handle, WaitMode::Typ * @return Signaled waitable handle index list * @throw WaitFailed Fatal error occurred while waiting for signal */ -WaitableHandleIndexList WaitForMultipleHandles(const WaitableHandleList &handleList, unsigned long miliseconds = 0xFFFFFFFF); +WaitableHandleIndexList WaitForMultipleHandles( + const WaitableHandleList &handleList, + unsigned long miliseconds = 0xFFFFFFFF); /** * Wait for multiple handles readability @@ -99,8 +107,9 @@ WaitableHandleIndexList WaitForMultipleHandles(const WaitableHandleList &handleL * @return Signaled waitable handle index list * @throw WaitFailed Fatal error occurred while waiting for signal */ -WaitableHandleIndexList WaitForMultipleHandles(const WaitableHandleListEx &handleListEx, unsigned long miliseconds = 0xFFFFFFFF); - +WaitableHandleIndexList WaitForMultipleHandles( + const WaitableHandleListEx &handleListEx, + unsigned long miliseconds = 0xFFFFFFFF); } // namespace DPL #endif // DPL_WAITABLE_HANDLE_H diff --git a/modules/core/include/dpl/waitable_handle_watch_support.h b/modules/core/include/dpl/waitable_handle_watch_support.h index 0ff29b1..ac0987f 100644 --- a/modules/core/include/dpl/waitable_handle_watch_support.h +++ b/modules/core/include/dpl/waitable_handle_watch_support.h @@ -17,7 +17,8 @@ * @file waitable_handle_watch_support.h * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) * @version 1.0 - * @brief This file is the implementation file of waitable handle watch support + * @brief This file is the implementation file of waitable handle watch + * support */ #ifndef DPL_WAITABLE_HANDLE_WATCH_SUPPORT_H #define DPL_WAITABLE_HANDLE_WATCH_SUPPORT_H @@ -29,23 +30,22 @@ #include #include -namespace DPL -{ - +namespace DPL { class Thread; class WaitableHandleWatchSupport { -public: + public: class WaitableHandleListener { - public: + public: virtual ~WaitableHandleListener() {} - virtual void OnWaitableHandleEvent(WaitableHandle waitableHandle, WaitMode::Type mode) = 0; + virtual void OnWaitableHandleEvent(WaitableHandle waitableHandle, + WaitMode::Type mode) = 0; }; -protected: + protected: // Invoker waitable handle // Signaled by Add/Remove methods // After being signaled one must call Handle invoke to reset invoker @@ -67,18 +67,17 @@ protected: // Invoke direct invoker virtual void HandleDirectInvoker() = 0; -private: + private: // Waitable event watchers struct WaitableHandleWatcher { WaitableHandleListener *listener; WaitMode::Type mode; - WaitableHandleWatcher(WaitableHandleListener *l, WaitMode::Type m) - : listener(l), - mode(m) - { - } + WaitableHandleWatcher(WaitableHandleListener *l, WaitMode::Type m) : + listener(l), + mode(m) + {} }; typedef std::list WaitableHandleListenerList; @@ -89,14 +88,14 @@ private: size_t readListenersCount; size_t writeListenersCount; - WaitableHandleWatchers() - : readListenersCount(0), - writeListenersCount(0) - { - } + WaitableHandleWatchers() : + readListenersCount(0), + writeListenersCount(0) + {} }; - typedef std::map WaitableHandleWatchersMap; + typedef std::map WaitableHandleWatchersMap; // Waitable event watch support mutable RecursiveMutex m_watchersMutex; @@ -107,7 +106,7 @@ private: // Invoke call void CommitInvoker(); -public: + public: /** * Constructor */ @@ -127,7 +126,9 @@ public: * @return none * @see WaitMode::Type */ - void AddWaitableHandleWatch(WaitableHandleListener *listener, WaitableHandle waitableHandle, WaitMode::Type mode); + void AddWaitableHandleWatch(WaitableHandleListener *listener, + WaitableHandle waitableHandle, + WaitMode::Type mode); /** * Remove listener for specific waitable event @@ -138,7 +139,9 @@ public: * @return none * @see WaitMode::Type */ - void RemoveWaitableHandleWatch(WaitableHandleListener *listener, WaitableHandle waitableHandle, WaitMode::Type mode); + void RemoveWaitableHandleWatch(WaitableHandleListener *listener, + WaitableHandle waitableHandle, + WaitMode::Type mode); /** * Retrieve inherited context @@ -147,7 +150,6 @@ public: */ static WaitableHandleWatchSupport *InheritedContext(); }; - } // namespace DPL #endif // DPL_WAITABLE_HANDLE_WATCH_SUPPORT_H diff --git a/modules/core/include/dpl/zip_input.h b/modules/core/include/dpl/zip_input.h index 633dbc8..1363fac 100644 --- a/modules/core/include/dpl/zip_input.h +++ b/modules/core/include/dpl/zip_input.h @@ -29,15 +29,14 @@ #include #include -namespace DPL +namespace DPL { +class ZipInput : + private Noncopyable { -class ZipInput - : private Noncopyable -{ -public: + public: class Exception { - public: + public: DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) DECLARE_EXCEPTION_TYPE(Base, OpenFailed) DECLARE_EXCEPTION_TYPE(Base, ReadGlobalInfoFailed) @@ -60,49 +59,47 @@ public: std::string comment; // File information - off64_t compressedSize; //< compressed size - off64_t uncompressedSize; //< uncompressed size - - FileInfo() - : handle(), - name(), - comment(), - compressedSize(0), - uncompressedSize(0) - { - } + off64_t compressedSize; //< compressed size + off64_t uncompressedSize; //< uncompressed size + + FileInfo() : + handle(), + name(), + comment(), + compressedSize(0), + uncompressedSize(0) + {} FileInfo(const FileHandle &handleArg, const std::string &nameArg, const std::string &commentArg, const off64_t &compressedSizeArg, - const off64_t &uncompressedSizeArg) - : handle(handleArg), - name(nameArg), - comment(commentArg), - compressedSize(compressedSizeArg), - uncompressedSize(uncompressedSizeArg) - { - } + const off64_t &uncompressedSizeArg) : + handle(handleArg), + name(nameArg), + comment(commentArg), + compressedSize(compressedSizeArg), + uncompressedSize(uncompressedSizeArg) + {} }; - class File - : public DPL::AbstractInput + class File : + public DPL::AbstractInput { - private: + private: void *m_file; friend class ZipInput; File(class Device *device, FileHandle handle); - public: + public: ~File(); virtual DPL::BinaryQueueAutoPtr Read(size_t size); }; -private: - class Device *m_device; + private: + class Device * m_device; void *m_masterFile; size_t m_numberOfFiles; @@ -117,12 +114,12 @@ private: void ReadGlobalComment(void *masterFile); void ReadInfos(void *masterFile); -public: + public: typedef FileInfoList::const_iterator const_iterator; typedef FileInfoList::const_reverse_iterator const_reverse_iterator; typedef FileInfoList::size_type size_type; -public: + public: /** * Open zip file from file */ diff --git a/modules/core/src/abstract_waitable_input_adapter.cpp b/modules/core/src/abstract_waitable_input_adapter.cpp index 9de97d5..a802a7f 100644 --- a/modules/core/src/abstract_waitable_input_adapter.cpp +++ b/modules/core/src/abstract_waitable_input_adapter.cpp @@ -17,16 +17,16 @@ * @file abstract_waitable_input_adapter.cpp * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) * @version 1.0 - * @brief This file is the implementation file of abstract waitable input adapter + * @brief This file is the implementation file of abstract waitable input + * adapter */ #include #include -namespace DPL -{ - +namespace DPL { AbstractWaitableInputAdapter::AbstractWaitableInputAdapter(AbstractInput *input) - : m_input(input) + : + m_input(input) { m_waitableEvent.Signal(); } @@ -40,5 +40,4 @@ WaitableHandle AbstractWaitableInputAdapter::WaitableReadHandle() const { return m_waitableEvent.GetHandle(); } - } // namespace DPL diff --git a/modules/core/src/abstract_waitable_input_output_adapter.cpp b/modules/core/src/abstract_waitable_input_output_adapter.cpp index e6f3a0f..e432b31 100644 --- a/modules/core/src/abstract_waitable_input_output_adapter.cpp +++ b/modules/core/src/abstract_waitable_input_output_adapter.cpp @@ -17,18 +17,16 @@ * @file abstract_waitable_input_output_adapter.cpp * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) * @version 1.0 - * @brief This file is the implementation file of abstract waitable input output adapter + * @brief This file is the implementation file of abstract waitable input + * output adapter */ #include #include -namespace DPL -{ - -AbstractWaitableInputOutputAdapter::AbstractWaitableInputOutputAdapter(AbstractInputOutput *inputOutput) - : AbstractWaitableInputAdapter(inputOutput), - AbstractWaitableOutputAdapter(inputOutput) -{ -} - +namespace DPL { +AbstractWaitableInputOutputAdapter::AbstractWaitableInputOutputAdapter( + AbstractInputOutput *inputOutput) : + AbstractWaitableInputAdapter(inputOutput), + AbstractWaitableOutputAdapter(inputOutput) +{} } // namespace DPL diff --git a/modules/core/src/abstract_waitable_output_adapter.cpp b/modules/core/src/abstract_waitable_output_adapter.cpp index f3cf9cb..82c2347 100644 --- a/modules/core/src/abstract_waitable_output_adapter.cpp +++ b/modules/core/src/abstract_waitable_output_adapter.cpp @@ -17,21 +17,22 @@ * @file abstract_waitable_output_adapter.cpp * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) * @version 1.0 - * @brief This file is the implementation file of abstract waitable output adapter + * @brief This file is the implementation file of abstract waitable output + * adapter */ #include #include -namespace DPL -{ - -AbstractWaitableOutputAdapter::AbstractWaitableOutputAdapter(AbstractOutput *output) - : m_output(output) +namespace DPL { +AbstractWaitableOutputAdapter::AbstractWaitableOutputAdapter( + AbstractOutput *output) : + m_output(output) { m_waitableEvent.Signal(); } -size_t AbstractWaitableOutputAdapter::Write(const BinaryQueue &buffer, size_t bufferSize) +size_t AbstractWaitableOutputAdapter::Write(const BinaryQueue &buffer, + size_t bufferSize) { return m_output->Write(buffer, bufferSize); } @@ -40,5 +41,4 @@ WaitableHandle AbstractWaitableOutputAdapter::WaitableWriteHandle() const { return m_waitableEvent.GetHandle(); } - } // namespace DPL diff --git a/modules/core/src/address.cpp b/modules/core/src/address.cpp index 52a1c78..34c8861 100644 --- a/modules/core/src/address.cpp +++ b/modules/core/src/address.cpp @@ -24,28 +24,23 @@ #include #include -namespace DPL -{ -Address::Address() - : m_port(0) -{ -} +namespace DPL { +Address::Address() : + m_port(0) +{} -Address::Address(const std::string &address) - : m_address(address), - m_port(0) -{ -} +Address::Address(const std::string &address) : + m_address(address), + m_port(0) +{} -Address::Address(const std::string &address, unsigned short port) - : m_address(address), - m_port(port) -{ -} +Address::Address(const std::string &address, unsigned short port) : + m_address(address), + m_port(port) +{} Address::~Address() -{ -} +{} std::string Address::GetAddress() const { @@ -68,5 +63,4 @@ bool Address::operator<(const Address &addr) const { return ToString() < addr.ToString(); } - } // namespace DPL diff --git a/modules/core/src/application.cpp b/modules/core/src/application.cpp index d25e5ad..b2c9cc0 100644 --- a/modules/core/src/application.cpp +++ b/modules/core/src/application.cpp @@ -28,53 +28,54 @@ namespace // anonymous static DPL::Application *g_application = NULL; } // namespace anonymous -namespace DPL -{ +namespace DPL { int Application::app_create(void *data) { - Application *This=static_cast(data); + Application *This = static_cast(data); This->OnCreate(); return 0; } int Application::app_terminate(void *data) { - Application *This=static_cast(data); + Application *This = static_cast(data); This->OnTerminate(); return 0; } int Application::app_pause(void *data) { - Application *This=static_cast(data); + Application *This = static_cast(data); This->OnPause(); return 0; } int Application::app_resume(void *data) { - Application *This=static_cast(data); + Application *This = static_cast(data); This->OnResume(); return 0; } int Application::app_reset(bundle *b, void *data) { - Application *This=static_cast(data); + Application *This = static_cast(data); This->OnReset(b); return 0; } Application::Application(int argc, char** argv, const std::string& applicationName, - bool showMainWindow) - : m_argc(argc), - m_argv(argv), - m_applicationName(applicationName), - m_mainWindowVisible(showMainWindow) -{ - if (g_application != NULL) - ThrowMsg(Exception::TooManyInstances, "Only single instance of Application allowed at one time!"); + bool showMainWindow) : + m_argc(argc), + m_argv(argv), + m_applicationName(applicationName), + m_mainWindowVisible(showMainWindow) +{ + if (g_application != NULL) { + ThrowMsg(Exception::TooManyInstances, + "Only single instance of Application allowed at one time!"); + } g_application = this; } @@ -94,9 +95,10 @@ int Application::Exec() ops.pause = app_pause; ops.resume = app_resume; ops.reset = app_reset; - ops.data=this; + ops.data = this; - int result = appcore_efl_main(m_applicationName.c_str(), &m_argc, &m_argv, &ops); + int result = appcore_efl_main( + m_applicationName.c_str(), &m_argc, &m_argv, &ops); LogPedantic("Exited application framework"); @@ -166,23 +168,21 @@ void Application::Quit() DPL::Atomic ApplicationExt::m_useCount(0); -ApplicationExt::ApplicationExt(int argc, char** argv, const std::string& applicationName, bool showMainWindow) : +ApplicationExt::ApplicationExt(int argc, + char** argv, + const std::string& applicationName, + bool showMainWindow) : Application(argc, argv, applicationName, showMainWindow) -{ -} +{} ApplicationExt::~ApplicationExt() -{ -} +{} int ApplicationExt::Exec() { - if (0 == m_useCount.CompareAndExchange(0, 1)) - { + if (0 == m_useCount.CompareAndExchange(0, 1)) { return Application::Exec(); - } - else - { + } else { elm_run(); } return 0; diff --git a/modules/core/src/assert.cpp b/modules/core/src/assert.cpp index e3e4f82..b8a12c8 100644 --- a/modules/core/src/assert.cpp +++ b/modules/core/src/assert.cpp @@ -25,9 +25,11 @@ #include #include -namespace DPL -{ -void AssertProc(const char *condition, const char *file, int line, const char *function) +namespace DPL { +void AssertProc(const char *condition, + const char *file, + int line, + const char *function) { #define INTERNAL_LOG(message) \ do \ @@ -37,22 +39,25 @@ void AssertProc(const char *condition, const char *file, int line, const char *f DPL::Log::LogSystemSingleton::Instance().Pedantic( \ platformLog.str().c_str(), \ __FILE__, __LINE__, __FUNCTION__); \ - } while (0) + } \ + while (0) // Try to log failed assertion to log system Try { - INTERNAL_LOG("################################################################################"); - INTERNAL_LOG("### DPL assertion failed! ###"); - INTERNAL_LOG("################################################################################"); + INTERNAL_LOG( + "################################################################################"); + INTERNAL_LOG( + "### DPL assertion failed! ###"); + INTERNAL_LOG( + "################################################################################"); INTERNAL_LOG("### Condition: " << condition); INTERNAL_LOG("### File: " << file); INTERNAL_LOG("### Line: " << line); INTERNAL_LOG("### Function: " << function); - INTERNAL_LOG("################################################################################"); - } - catch (Exception) - { + INTERNAL_LOG( + "################################################################################"); + } catch (Exception) { // Just ignore possible double errors } diff --git a/modules/core/src/atomic.cpp b/modules/core/src/atomic.cpp index 032fbb8..2f50074 100644 --- a/modules/core/src/atomic.cpp +++ b/modules/core/src/atomic.cpp @@ -22,12 +22,10 @@ #include #include -namespace DPL -{ -Atomic::Atomic(ValueType value) - : m_value(value) -{ -} +namespace DPL { +Atomic::Atomic(ValueType value) : + m_value(value) +{} Atomic::ValueType Atomic::ExchangeAndAdd(ValueType value) { @@ -36,7 +34,9 @@ Atomic::ValueType Atomic::ExchangeAndAdd(ValueType value) bool Atomic::CompareAndExchange(ValueType oldValue, ValueType newValue) { - return g_atomic_int_compare_and_exchange(const_cast(&m_value), oldValue, newValue); + return g_atomic_int_compare_and_exchange(const_cast(&m_value), + oldValue, + newValue); } bool Atomic::operator--() diff --git a/modules/core/src/binary_queue.cpp b/modules/core/src/binary_queue.cpp index 3efecd0..2234c8f 100644 --- a/modules/core/src/binary_queue.cpp +++ b/modules/core/src/binary_queue.cpp @@ -28,15 +28,13 @@ #include #include -namespace DPL -{ -BinaryQueue::BinaryQueue() - : m_size(0) -{ -} +namespace DPL { +BinaryQueue::BinaryQueue() : + m_size(0) +{} -BinaryQueue::BinaryQueue(const BinaryQueue &other) - : m_size(0) +BinaryQueue::BinaryQueue(const BinaryQueue &other) : + m_size(0) { AppendCopyFrom(other); } @@ -49,8 +47,7 @@ BinaryQueue::~BinaryQueue() const BinaryQueue &BinaryQueue::operator=(const BinaryQueue &other) { - if (this != &other) - { + if (this != &other) { Clear(); AppendCopyFrom(other); } @@ -63,16 +60,14 @@ void BinaryQueue::AppendCopyFrom(const BinaryQueue &other) // To speed things up, always copy as one bucket void *bufferCopy = malloc(other.m_size); - if (bufferCopy == NULL) + if (bufferCopy == NULL) { throw std::bad_alloc(); + } - try - { + try { other.Flatten(bufferCopy, other.m_size); AppendUnmanaged(bufferCopy, other.m_size, &BufferDeleterFree, NULL); - } - catch (const std::bad_alloc &) - { + } catch (const std::bad_alloc &) { // Free allocated memory free(bufferCopy); throw; @@ -82,7 +77,8 @@ void BinaryQueue::AppendCopyFrom(const BinaryQueue &other) void BinaryQueue::AppendMoveFrom(BinaryQueue &other) { // Copy all buckets - std::copy(other.m_buckets.begin(), other.m_buckets.end(), std::back_inserter(m_buckets)); + std::copy(other.m_buckets.begin(), + other.m_buckets.end(), std::back_inserter(m_buckets)); m_size += other.m_size; // Clear other, but do not free memory @@ -113,30 +109,30 @@ void BinaryQueue::AppendCopy(const void* buffer, size_t bufferSize) void *bufferCopy = malloc(bufferSize); // Check if allocation succeded - if (bufferCopy == NULL) + if (bufferCopy == NULL) { throw std::bad_alloc(); + } // Copy user data memcpy(bufferCopy, buffer, bufferSize); - try - { + try { // Try to append new bucket AppendUnmanaged(bufferCopy, bufferSize, &BufferDeleterFree, NULL); - } - catch (const std::bad_alloc &) - { + } catch (const std::bad_alloc &) { // Free allocated memory free(bufferCopy); throw; } } -void BinaryQueue::AppendUnmanaged(const void* buffer, size_t bufferSize, BufferDeleter deleter, void* userParam) +void BinaryQueue::AppendUnmanaged(const void* buffer, + size_t bufferSize, + BufferDeleter deleter, + void* userParam) { // Do not attach empty buckets - if (bufferSize == 0) - { + if (bufferSize == 0) { deleter(buffer, bufferSize, userParam); return; } @@ -161,24 +157,24 @@ bool BinaryQueue::Empty() const void BinaryQueue::Consume(size_t size) { // Check parameters - if (size > m_size) + if (size > m_size) { Throw(Exception::OutOfData); + } size_t bytesLeft = size; // Consume data and/or remove buckets - while (bytesLeft > 0) - { + while (bytesLeft > 0) { // Get consume size size_t count = std::min(bytesLeft, m_buckets.front()->left); - m_buckets.front()->ptr = static_cast(m_buckets.front()->ptr) + count; + m_buckets.front()->ptr = + static_cast(m_buckets.front()->ptr) + count; m_buckets.front()->left -= count; bytesLeft -= count; m_size -= count; - if (m_buckets.front()->left == 0) - { + if (m_buckets.front()->left == 0) { DeleteBucket(m_buckets.front()); m_buckets.pop_front(); } @@ -188,11 +184,13 @@ void BinaryQueue::Consume(size_t size) void BinaryQueue::Flatten(void *buffer, size_t bufferSize) const { // Check parameters - if (bufferSize == 0) + if (bufferSize == 0) { return; + } - if (bufferSize > m_size) + if (bufferSize > m_size) { Throw(Exception::OutOfData); + } size_t bytesLeft = bufferSize; void *ptr = buffer; @@ -200,8 +198,7 @@ void BinaryQueue::Flatten(void *buffer, size_t bufferSize) const Assert(m_buckets.end() != bucketIterator); // Flatten data - while (bytesLeft > 0) - { + while (bytesLeft > 0) { // Get consume size size_t count = std::min(bytesLeft, (*bucketIterator)->left); @@ -229,7 +226,9 @@ void BinaryQueue::DeleteBucket(BinaryQueue::Bucket *bucket) delete bucket; } -void BinaryQueue::BufferDeleterFree(const void* data, size_t dataSize, void* userParam) +void BinaryQueue::BufferDeleterFree(const void* data, + size_t dataSize, + void* userParam) { (void)dataSize; (void)userParam; @@ -238,13 +237,16 @@ void BinaryQueue::BufferDeleterFree(const void* data, size_t dataSize, void* use free(const_cast(data)); } -BinaryQueue::Bucket::Bucket(const void* data, size_t dataSize, BufferDeleter dataDeleter, void* userParam) - : buffer(data), - ptr(data), - size(dataSize), - left(dataSize), - deleter(dataDeleter), - param(userParam) +BinaryQueue::Bucket::Bucket(const void* data, + size_t dataSize, + BufferDeleter dataDeleter, + void* userParam) : + buffer(data), + ptr(data), + size(dataSize), + left(dataSize), + deleter(dataDeleter), + param(userParam) { Assert(data != NULL); Assert(deleter != NULL); @@ -257,17 +259,14 @@ BinaryQueue::Bucket::~Bucket() } BinaryQueue::BucketVisitor::~BucketVisitor() -{ -} +{} -BinaryQueue::BucketVisitorCall::BucketVisitorCall(BucketVisitor *visitor) - : m_visitor(visitor) -{ -} +BinaryQueue::BucketVisitorCall::BucketVisitorCall(BucketVisitor *visitor) : + m_visitor(visitor) +{} BinaryQueue::BucketVisitorCall::~BucketVisitorCall() -{ -} +{} void BinaryQueue::BucketVisitorCall::operator()(Bucket *bucket) const { @@ -289,13 +288,15 @@ BinaryQueueAutoPtr BinaryQueue::Read(size_t size) ScopedFree bufferCopy(malloc(available)); - if (!bufferCopy) + if (!bufferCopy) { throw std::bad_alloc(); + } BinaryQueueAutoPtr result(new BinaryQueue()); Flatten(bufferCopy.Get(), available); - result->AppendUnmanaged(bufferCopy.Get(), available, &BufferDeleterFree, NULL); + result->AppendUnmanaged( + bufferCopy.Get(), available, &BufferDeleterFree, NULL); bufferCopy.Release(); Consume(available); diff --git a/modules/core/src/char_traits.cpp b/modules/core/src/char_traits.cpp index 6e4bec8..32b9197 100644 --- a/modules/core/src/char_traits.cpp +++ b/modules/core/src/char_traits.cpp @@ -17,8 +17,10 @@ * @file char_traits.cpp * @author Piotr Marcinkiewicz (p.marcinkiew@samsung.com) * @version 1.0 - * @biref Char traits are used to create basic_string extended with additional features - * Current char traits could be extended in feature to boost performance + * @biref Char traits are used to create basic_string extended with + * additional features + * Current char traits could be extended in feature to boost + * performance */ #include #include diff --git a/modules/core/src/colors.cpp b/modules/core/src/colors.cpp index fc0f2e2..0b2fcd4 100644 --- a/modules/core/src/colors.cpp +++ b/modules/core/src/colors.cpp @@ -23,16 +23,9 @@ #include #include - -namespace DPL -{ - -namespace Colors -{ - -namespace Text -{ - +namespace DPL { +namespace Colors { +namespace Text { const char* BOLD_GREEN_BEGIN = "\033[1;32m"; const char* BOLD_GREEN_END = "\033[m"; const char* RED_BEGIN = "\033[0;31m"; @@ -51,12 +44,9 @@ const char* BOLD_GOLD_BEGIN = "\033[0;33m"; const char* BOLD_GOLD_END = "\033[m"; const char* BOLD_WHITE_BEGIN = "\033[1;37m"; const char* BOLD_WHITE_END = "\033[m"; - } //namespace Text -namespace Html -{ - +namespace Html { const char* BOLD_GREEN_BEGIN = ""; const char* BOLD_GREEN_END = ""; const char* PURPLE_BEGIN = ""; @@ -75,9 +65,6 @@ const char* BOLD_GOLD_BEGIN = ""; const char* BOLD_GOLD_END = ""; const char* BOLD_WHITE_BEGIN = ""; const char* BOLD_WHITE_END = ""; - } //namespace Html - } //namespace Colors - } //namespace DPL diff --git a/modules/core/src/copy.cpp b/modules/core/src/copy.cpp index a302fb8..c05d06c 100644 --- a/modules/core/src/copy.cpp +++ b/modules/core/src/copy.cpp @@ -24,8 +24,7 @@ #include #include -namespace DPL -{ +namespace DPL { namespace // anonymous { const size_t DEFAULT_COPY_BUFFER_SIZE = 16768; @@ -35,39 +34,36 @@ void Copy(AbstractWaitableInput *input, AbstractWaitableOutput *output) { Try { - while (true) - { + while (true) { BinaryQueueAutoPtr buffer; - while (true) - { + while (true) { // Try to get data immediately buffer = input->Read(DEFAULT_COPY_BUFFER_SIZE); // Do we need to wait for data ? - if (!buffer.get()) - { - WaitForSingleHandle(input->WaitableReadHandle(), WaitMode::Read); + if (!buffer.get()) { + WaitForSingleHandle( + input->WaitableReadHandle(), WaitMode::Read); continue; } - if (buffer->Empty()) + if (buffer->Empty()) { return; // Done - + } // Ok, to process break; } // Write out all data - while (!buffer->Empty()) - { + while (!buffer->Empty()) { // Try to write all data immediately size_t count = output->Write(*buffer, buffer->Size()); // Do we need to wait for writing data ? - if (count == 0) - { - WaitForSingleHandle(output->WaitableWriteHandle(), WaitMode::Write); + if (count == 0) { + WaitForSingleHandle( + output->WaitableWriteHandle(), WaitMode::Write); continue; } @@ -76,54 +72,55 @@ void Copy(AbstractWaitableInput *input, AbstractWaitableOutput *output) } } } - Catch (DPL::Exception) + Catch(DPL::Exception) { ReThrow(CopyFailed); } } -void Copy(AbstractWaitableInput *input, AbstractWaitableOutput *output, size_t totalBytes) +void Copy(AbstractWaitableInput *input, + AbstractWaitableOutput *output, + size_t totalBytes) { Try { size_t bytesLeft = totalBytes; - while (bytesLeft > 0) - { + while (bytesLeft > 0) { BinaryQueueAutoPtr buffer; // Copy at most left bytes - size_t bytesToCopy = bytesLeft > DEFAULT_COPY_BUFFER_SIZE ? DEFAULT_COPY_BUFFER_SIZE : bytesLeft; + size_t bytesToCopy = bytesLeft > + DEFAULT_COPY_BUFFER_SIZE ? DEFAULT_COPY_BUFFER_SIZE : bytesLeft; - while (true) - { + while (true) { // Try to get data immediately buffer = input->Read(bytesToCopy); // Do we need to wait for data ? - if (!buffer.get()) - { - WaitForSingleHandle(input->WaitableReadHandle(), WaitMode::Read); + if (!buffer.get()) { + WaitForSingleHandle( + input->WaitableReadHandle(), WaitMode::Read); continue; } - if (buffer->Empty()) + if (buffer->Empty()) { ThrowMsg(CopyFailed, "Unexpected end of abstract input"); + } // Ok, to process break; } // Write out all data - while (!buffer->Empty()) - { + while (!buffer->Empty()) { // Try to write all data immediately size_t count = output->Write(*buffer, buffer->Size()); // Do we need to wait for writing data ? - if (count == 0) - { - WaitForSingleHandle(output->WaitableWriteHandle(), WaitMode::Write); + if (count == 0) { + WaitForSingleHandle( + output->WaitableWriteHandle(), WaitMode::Write); continue; } @@ -133,7 +130,7 @@ void Copy(AbstractWaitableInput *input, AbstractWaitableOutput *output, size_t t } } } - Catch (DPL::Exception) + Catch(DPL::Exception) { ReThrow(CopyFailed); } diff --git a/modules/core/src/errno_string.cpp b/modules/core/src/errno_string.cpp index 24b9b5a..cb607f5 100644 --- a/modules/core/src/errno_string.cpp +++ b/modules/core/src/errno_string.cpp @@ -32,8 +32,7 @@ #include #include -namespace DPL -{ +namespace DPL { namespace // anonymous { const size_t DEFAULT_ERRNO_STRING_SIZE = 32; @@ -44,13 +43,11 @@ std::string GetErrnoString(int error) size_t size = DEFAULT_ERRNO_STRING_SIZE; char *buffer = NULL; - for (;;) - { + for (;;) { // Add one extra characted for end of string null value char *newBuffer = static_cast(::realloc(buffer, size + 1)); - if (!newBuffer) - { + if (!newBuffer) { // Failed to realloc ::free(buffer); throw std::bad_alloc(); @@ -61,12 +58,11 @@ std::string GetErrnoString(int error) ::memset(buffer, 0, size + 1); // Try to retrieve error string -#if (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && ! _GNU_SOURCE +#if (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && !_GNU_SOURCE // The XSI-compliant version of strerror_r() is provided if: int result = ::strerror_r(error, buffer, size); - if (result == 0) - { + if (result == 0) { ScopedFree scopedBufferFree(buffer); return std::string(buffer); } @@ -76,19 +72,17 @@ std::string GetErrnoString(int error) // Otherwise, the GNU-specific version is provided. char *result = ::strerror_r(error, buffer, size); - if (result != NULL) - { + if (result != NULL) { ScopedFree scopedBufferFree(buffer); return std::string(result); } #endif // Interpret errors - switch (errno) - { + switch (errno) { case EINVAL: // We got an invalid errno value - ::free(buffer); + ::free(buffer); ThrowMsg(InvalidErrnoValue, "Invalid errno value: " << error); case ERANGE: diff --git a/modules/core/src/exception.cpp b/modules/core/src/exception.cpp index ea6624e..d3673e6 100644 --- a/modules/core/src/exception.cpp +++ b/modules/core/src/exception.cpp @@ -24,8 +24,7 @@ #include #include -namespace DPL -{ +namespace DPL { Exception* Exception::m_lastException = NULL; unsigned int Exception::m_exceptionCount = 0; void (*Exception::m_terminateHandler)() = NULL; @@ -39,15 +38,20 @@ void LogUnhandledException(const std::string &str) LogPedantic(str); } -void LogUnhandledException(const std::string &str, const char *filename, int line, const char *function) +void LogUnhandledException(const std::string &str, + const char *filename, + int line, + const char *function) { // Logging to console std::ostringstream msg; - msg << "\033[1;5;31m\n=== [" << filename << ":" << line << "] " << function << " ===\033[m"; + msg << "\033[1;5;31m\n=== [" << filename << ":" << line << "] " << + function << " ===\033[m"; msg << str; printf("%s\n", msg.str().c_str()); // Logging to dlog - DPL::Log::LogSystemSingleton::Instance().Error(str.c_str(), filename, line, function); + DPL::Log::LogSystemSingleton::Instance().Error( + str.c_str(), filename, line, function); } } // namespace DPL diff --git a/modules/core/src/file_input.cpp b/modules/core/src/file_input.cpp index c0007e4..36fb4b5 100644 --- a/modules/core/src/file_input.cpp +++ b/modules/core/src/file_input.cpp @@ -28,21 +28,18 @@ #include #include -namespace DPL -{ - +namespace DPL { namespace // anonymous { const size_t DEFAULT_READ_BUFFER_SIZE = 4096; } // namespace anonymous -FileInput::FileInput() - : m_fd(-1) -{ -} +FileInput::FileInput() : + m_fd(-1) +{} -FileInput::FileInput(const std::string& fileName) - : m_fd(-1) +FileInput::FileInput(const std::string& fileName) : + m_fd(-1) { Open(fileName); } @@ -58,8 +55,9 @@ void FileInput::Open(const std::string& fileName) int fd = TEMP_FAILURE_RETRY(open(fileName.c_str(), O_RDONLY | O_NONBLOCK)); // Throw an exception if an error occurred - if (fd == -1) + if (fd == -1) { ThrowMsg(Exception::OpenFailed, fileName); + } // Close if any existing Close(); @@ -72,11 +70,13 @@ void FileInput::Open(const std::string& fileName) void FileInput::Close() { - if (m_fd == -1) + if (m_fd == -1) { return; + } - if (TEMP_FAILURE_RETRY(close(m_fd)) == -1) + if (TEMP_FAILURE_RETRY(close(m_fd)) == -1) { Throw(Exception::CloseFailed); + } m_fd = -1; @@ -85,14 +85,16 @@ void FileInput::Close() BinaryQueueAutoPtr FileInput::Read(size_t size) { - size_t bytesToRead = size > DEFAULT_READ_BUFFER_SIZE ? DEFAULT_READ_BUFFER_SIZE : 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) + if (buffer == NULL) { throw std::bad_alloc(); + } LogPedantic("Trying to read " << bytesToRead << " bytes"); @@ -100,27 +102,25 @@ BinaryQueueAutoPtr FileInput::Read(size_t size) LogPedantic("Read " << result << " bytes from file"); - if (result > 0) - { + if (result > 0) { // Succedded to read socket data BinaryQueueAutoPtr binaryQueue(new BinaryQueue()); // Append unmanaged memory - binaryQueue->AppendUnmanaged(buffer, result, &BinaryQueue::BufferDeleterFree, NULL); + binaryQueue->AppendUnmanaged(buffer, + result, + &BinaryQueue::BufferDeleterFree, + NULL); // Return buffer return binaryQueue; - } - else if (result == 0) - { + } else if (result == 0) { // Socket was gracefuly closed free(buffer); // Return empty buffer return BinaryQueueAutoPtr(new BinaryQueue()); - } - else - { + } else { // Must first save errno value, because it may be altered int lastErrno = errno; diff --git a/modules/core/src/file_output.cpp b/modules/core/src/file_output.cpp index 3106e17..8342698 100644 --- a/modules/core/src/file_output.cpp +++ b/modules/core/src/file_output.cpp @@ -29,15 +29,13 @@ #include #include -namespace DPL -{ -FileOutput::FileOutput() - : m_fd(-1) -{ -} +namespace DPL { +FileOutput::FileOutput() : + m_fd(-1) +{} -FileOutput::FileOutput(const std::string& fileName) - : m_fd(-1) +FileOutput::FileOutput(const std::string& fileName) : + m_fd(-1) { Open(fileName); } @@ -50,11 +48,15 @@ FileOutput::~FileOutput() void FileOutput::Open(const std::string& fileName) { // Open non-blocking - int fd = TEMP_FAILURE_RETRY(open(fileName.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_NONBLOCK, 0664)); + int fd = + TEMP_FAILURE_RETRY(open(fileName.c_str(), O_WRONLY | O_CREAT | + O_TRUNC | + O_NONBLOCK, 0664)); // Throw an exception if an error occurred - if (fd == -1) + if (fd == -1) { ThrowMsg(Exception::OpenFailed, fileName); + } // Close if any existing Close(); @@ -67,11 +69,13 @@ void FileOutput::Open(const std::string& fileName) void FileOutput::Close() { - if (m_fd == -1) + if (m_fd == -1) { return; + } - if (TEMP_FAILURE_RETRY(close(m_fd)) == -1) + if (TEMP_FAILURE_RETRY(close(m_fd)) == -1) { Throw(Exception::CloseFailed); + } m_fd = -1; @@ -81,8 +85,9 @@ void FileOutput::Close() size_t FileOutput::Write(const BinaryQueue &buffer, size_t bufferSize) { // Adjust write size - if (bufferSize > buffer.Size()) + if (bufferSize > buffer.Size()) { bufferSize = buffer.Size(); + } // FIXME: User write visitor to write ! // WriteVisitor visitor @@ -96,18 +101,14 @@ size_t FileOutput::Write(const BinaryQueue &buffer, size_t bufferSize) LogPedantic("Wrote " << result << " bytes to file"); - if (result > 0) - { + if (result > 0) { // Successfuly written some bytes return static_cast(result); - } - else if (result == 0) - { + } else if (result == 0) { // This is abnormal result - ThrowMsg(CommonException::InternalError, "Invalid write result, 0 bytes written"); - } - else - { + ThrowMsg(CommonException::InternalError, + "Invalid write result, 0 bytes written"); + } else { // Interpret error result // FIXME: Handle errno Throw(AbstractOutput::Exception::WriteFailed); diff --git a/modules/core/src/main.cpp b/modules/core/src/main.cpp index 80f8cb5..1d0326b 100644 --- a/modules/core/src/main.cpp +++ b/modules/core/src/main.cpp @@ -30,8 +30,7 @@ IMPLEMENT_SINGLETON(DPL::Main) -namespace DPL -{ +namespace DPL { namespace // anonymous { // Late EFL event handling @@ -40,7 +39,7 @@ Main *g_lateMain = NULL; Main::Main() #ifdef DPL_ENABLE_GLIB_LOOP_INTEGRATION_WORKAROUND - // GLIB loop intergration workaround +// GLIB loop intergration workaround : m_oldEcoreSelect(NULL) #endif // DPL_ENABLE_GLIB_LOOP_INTEGRATION_WORKAROUND { @@ -69,11 +68,17 @@ Main::Main() #endif // DPL_ENABLE_GLIB_LOOP_INTEGRATION_WORKAROUND // Register event invoker - m_invokerHandler = ecore_main_fd_handler_add(WaitableHandleWatchSupport::WaitableInvokerHandle(), - ECORE_FD_READ, &StaticDispatchInvoker, this, NULL, NULL); - - if (m_invokerHandler == NULL) + m_invokerHandler = ecore_main_fd_handler_add( + WaitableHandleWatchSupport::WaitableInvokerHandle(), + ECORE_FD_READ, + &StaticDispatchInvoker, + this, + NULL, + NULL); + + if (m_invokerHandler == NULL) { ThrowMsg(Exception::CreateFailed, "Failed to register invoker handler!"); + } // It is impossible that there exist watchers at this time // No need to add watchers @@ -83,13 +88,21 @@ Main::Main() Main::~Main() { // Remove any watchers - for (EcoreFdHandlerList::iterator iterator = m_readWatchersList.begin(); iterator != m_readWatchersList.end(); ++iterator) + for (EcoreFdHandlerList::iterator iterator = m_readWatchersList.begin(); + iterator != m_readWatchersList.end(); + ++iterator) + { ecore_main_fd_handler_del(*iterator); + } m_readWatchersList.clear(); - for (EcoreFdHandlerList::iterator iterator = m_writeWatchersList.begin(); iterator != m_writeWatchersList.end(); ++iterator) + for (EcoreFdHandlerList::iterator iterator = m_writeWatchersList.begin(); + iterator != m_writeWatchersList.end(); + ++iterator) + { ecore_main_fd_handler_del(*iterator); + } m_writeWatchersList.clear(); @@ -119,19 +132,17 @@ Eina_Bool Main::StaticDispatchInvoker(void *data, Ecore_Fd_Handler *fd_handler) Assert(This != NULL); // Late EFL event handling - if (g_lateMain == NULL) - { + if (g_lateMain == NULL) { LogPedantic("WARNING: Late EFL invoker dispatch!"); - } - else - { + } else { This->DispatchInvoker(); } return ECORE_CALLBACK_RENEW; } -Eina_Bool Main::StaticDispatchReadWatcher(void* data, Ecore_Fd_Handler* fd_handler) +Eina_Bool Main::StaticDispatchReadWatcher(void* data, + Ecore_Fd_Handler* fd_handler) { LogPedantic("Static ECORE dispatch read watcher"); @@ -140,19 +151,18 @@ Eina_Bool Main::StaticDispatchReadWatcher(void* data, Ecore_Fd_Handler* fd_handl Assert(This != NULL); // Late EFL event handling - if (g_lateMain == NULL) - { + if (g_lateMain == NULL) { LogPedantic("WARNING: Late EFL read watcher dispatch!"); - } - else - { - This->DispatchReadWatcher(static_cast(ecore_main_fd_handler_fd_get(fd_handler))); + } else { + This->DispatchReadWatcher(static_cast( + ecore_main_fd_handler_fd_get(fd_handler))); } return ECORE_CALLBACK_RENEW; } -Eina_Bool Main::StaticDispatchWriteWatcher(void* data, Ecore_Fd_Handler* fd_handler) +Eina_Bool Main::StaticDispatchWriteWatcher(void* data, + Ecore_Fd_Handler* fd_handler) { LogPedantic("Static ECORE dispatch write watcher"); @@ -161,13 +171,11 @@ Eina_Bool Main::StaticDispatchWriteWatcher(void* data, Ecore_Fd_Handler* fd_hand Assert(This != NULL); // Late EFL event handling - if (g_lateMain == NULL) - { + if (g_lateMain == NULL) { LogPedantic("WARNING: Late EFL write watcher dispatch!"); - } - else - { - This->DispatchWriteWatcher(static_cast(ecore_main_fd_handler_fd_get(fd_handler))); + } else { + This->DispatchWriteWatcher(static_cast( + ecore_main_fd_handler_fd_get(fd_handler))); } return ECORE_CALLBACK_RENEW; @@ -188,31 +196,36 @@ void Main::DispatchInvoker() void Main::ReloadWatchList() { - LogPedantic("Reloading watch list... (" << m_readWatchersList.size() << " + " << m_writeWatchersList.size() << ")"); + LogPedantic( + "Reloading watch list... (" << m_readWatchersList.size() << " + " << + m_writeWatchersList.size() << ")"); // Reload list of watchers - WaitableHandleListEx waitableWatcherHandles = WaitableHandleWatchSupport::WaitableWatcherHandles(); + WaitableHandleListEx waitableWatcherHandles = + WaitableHandleWatchSupport::WaitableWatcherHandles(); // Remove not existing read watchers EcoreFdHandlerList::iterator watchersIterator = m_readWatchersList.begin(); WaitableHandleListEx::iterator handlesIterator; - while (watchersIterator != m_readWatchersList.end()) - { + while (watchersIterator != m_readWatchersList.end()) { bool found = false; - for (handlesIterator = waitableWatcherHandles.begin(); handlesIterator != waitableWatcherHandles.end(); ++handlesIterator) + for (handlesIterator = waitableWatcherHandles.begin(); + handlesIterator != waitableWatcherHandles.end(); + ++handlesIterator) { if (handlesIterator->second == WaitMode::Read && - handlesIterator->first == static_cast(ecore_main_fd_handler_fd_get(*watchersIterator))) + handlesIterator->first == + static_cast(ecore_main_fd_handler_fd_get(* + watchersIterator))) { found = true; break; } } - if (!found) - { + if (!found) { // Unregister handler ecore_main_fd_handler_del(*watchersIterator); @@ -222,9 +235,7 @@ void Main::ReloadWatchList() m_readWatchersList.erase(watchersIterator); watchersIterator = next; - } - else - { + } else { ++watchersIterator; } } @@ -232,22 +243,24 @@ void Main::ReloadWatchList() // Remove not existing write watchers watchersIterator = m_writeWatchersList.begin(); - while (watchersIterator != m_writeWatchersList.end()) - { + while (watchersIterator != m_writeWatchersList.end()) { bool found = false; - for (handlesIterator = waitableWatcherHandles.begin(); handlesIterator != waitableWatcherHandles.end(); ++handlesIterator) + for (handlesIterator = waitableWatcherHandles.begin(); + handlesIterator != waitableWatcherHandles.end(); + ++handlesIterator) { if (handlesIterator->second == WaitMode::Write && - handlesIterator->first == static_cast(ecore_main_fd_handler_fd_get(*watchersIterator))) + handlesIterator->first == + static_cast(ecore_main_fd_handler_fd_get(* + watchersIterator))) { found = true; break; } } - if (!found) - { + if (!found) { // Unregister handler ecore_main_fd_handler_del(*watchersIterator); @@ -257,71 +270,88 @@ void Main::ReloadWatchList() m_writeWatchersList.erase(watchersIterator); watchersIterator = next; - } - else - { + } else { ++watchersIterator; } } // Add new read/write watchers - for (handlesIterator = waitableWatcherHandles.begin(); handlesIterator != waitableWatcherHandles.end(); ++handlesIterator) + for (handlesIterator = waitableWatcherHandles.begin(); + handlesIterator != waitableWatcherHandles.end(); + ++handlesIterator) { - if (handlesIterator->second == WaitMode::Read) - { + if (handlesIterator->second == WaitMode::Read) { bool found = false; - for (watchersIterator = m_readWatchersList.begin(); watchersIterator != m_readWatchersList.end(); ++watchersIterator) + for (watchersIterator = m_readWatchersList.begin(); + watchersIterator != m_readWatchersList.end(); + ++watchersIterator) { - if (handlesIterator->first == static_cast(ecore_main_fd_handler_fd_get(*watchersIterator))) + if (handlesIterator->first == + static_cast(ecore_main_fd_handler_fd_get(* + watchersIterator))) { found = true; break; } } - if (!found) - { - Ecore_Fd_Handler *handler = ecore_main_fd_handler_add(handlesIterator->first, - ECORE_FD_READ, &StaticDispatchReadWatcher, this, NULL, NULL); - if (handler == NULL) - ThrowMsg(Exception::CreateFailed, "Failed to register read watcher handler!"); + if (!found) { + Ecore_Fd_Handler *handler = ecore_main_fd_handler_add( + handlesIterator->first, + ECORE_FD_READ, + &StaticDispatchReadWatcher, + this, + NULL, + NULL); + if (handler == NULL) { + ThrowMsg(Exception::CreateFailed, + "Failed to register read watcher handler!"); + } // Push new watcher to list m_readWatchersList.push_back(handler); } - } - else if (handlesIterator->second == WaitMode::Write) - { + } else if (handlesIterator->second == WaitMode::Write) { bool found = false; - for (watchersIterator = m_writeWatchersList.begin(); watchersIterator != m_writeWatchersList.end(); ++watchersIterator) + for (watchersIterator = m_writeWatchersList.begin(); + watchersIterator != m_writeWatchersList.end(); + ++watchersIterator) { - if (handlesIterator->first == static_cast(ecore_main_fd_handler_fd_get(*watchersIterator))) + if (handlesIterator->first == + static_cast(ecore_main_fd_handler_fd_get(* + watchersIterator))) { found = true; break; } } - if (!found) - { - Ecore_Fd_Handler *handler = ecore_main_fd_handler_add(handlesIterator->first, - ECORE_FD_WRITE, &StaticDispatchWriteWatcher, this, NULL, NULL); - if (handler == NULL) - ThrowMsg(Exception::CreateFailed, "Failed to register write watcher handler!"); + if (!found) { + Ecore_Fd_Handler *handler = ecore_main_fd_handler_add( + handlesIterator->first, + ECORE_FD_WRITE, + &StaticDispatchWriteWatcher, + this, + NULL, + NULL); + if (handler == NULL) { + ThrowMsg(Exception::CreateFailed, + "Failed to register write watcher handler!"); + } // Push new watcher to list m_writeWatchersList.push_back(handler); } - } - else - { + } else { Assert(0); } } - LogPedantic("Watch list reloaded (" << m_readWatchersList.size() << " + " << m_writeWatchersList.size() << ")"); + LogPedantic( + "Watch list reloaded (" << m_readWatchersList.size() << " + " << + m_writeWatchersList.size() << ")"); } void Main::DispatchReadWatcher(WaitableHandle waitableHandle) @@ -357,51 +387,59 @@ void Main::HandleDirectInvoker() #ifdef DPL_ENABLE_GLIB_LOOP_INTEGRATION_WORKAROUND // GLIB loop intergration workaround -int Main::EcoreSelectInterceptor(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout) +int Main::EcoreSelectInterceptor(int nfds, + fd_set *readfds, + fd_set *writefds, + fd_set *exceptfds, + struct timeval *timeout) { - // We have to check error code here and make another try because of some glib error's. + // 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)); memcpy(&wfds, writefds, sizeof(fd_set)); memcpy(&efds, exceptfds, sizeof(fd_set)); - int ret = MainSingleton::Instance().m_oldEcoreSelect(nfds, readfds, writefds, exceptfds, timeout); + int ret = MainSingleton::Instance().m_oldEcoreSelect(nfds, + readfds, + writefds, + exceptfds, + timeout); - if (ret == -1) - { + if (ret == -1) { // 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)) + 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) - { + 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); + 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); + 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); + if (FD_ISSET(i, exceptfds)) { + LogPedantic( + "GLIB_LOOP_INTEGRATION_WORKAROUND: Bad exception descriptor: " + << i); FD_CLR(i, exceptfds); } - } - else - { + } else { // Unexpected error Assert(0); } @@ -409,7 +447,8 @@ int Main::EcoreSelectInterceptor(int nfds, fd_set *readfds, fd_set *writefds, fd } } - LogPedantic("GLIB_LOOP_INTEGRATION_WORKAROUND: Bad read descriptor. Retrying with default select."); + LogPedantic( + "GLIB_LOOP_INTEGRATION_WORKAROUND: Bad read descriptor. Retrying with default select."); //Retry with old values and return new error memcpy(readfds, &rfds, sizeof(fd_set)); @@ -421,10 +460,11 @@ int Main::EcoreSelectInterceptor(int nfds, fd_set *readfds, fd_set *writefds, fd tm.tv_sec = 0; tm.tv_usec = 10; - if (timeout) + if (timeout) { ret = select(nfds, readfds, writefds, exceptfds, &tm); - else + } else { ret = select(nfds, readfds, writefds, exceptfds, NULL); + } } return ret; diff --git a/modules/core/src/mutex.cpp b/modules/core/src/mutex.cpp index 6a7fd99..eed1f2e 100644 --- a/modules/core/src/mutex.cpp +++ b/modules/core/src/mutex.cpp @@ -25,25 +25,22 @@ #include #include -namespace DPL -{ +namespace DPL { Mutex::Mutex() { - if (pthread_mutex_init(&m_mutex, NULL) != 0) - { + if (pthread_mutex_init(&m_mutex, NULL) != 0) { int error = errno; LogPedantic("Failed to create mutex. Errno: " << error); ThrowMsg(Exception::CreateFailed, - "Failed to create mutex. Errno: " << error); + "Failed to create mutex. Errno: " << error); } } Mutex::~Mutex() { - if (pthread_mutex_destroy(&m_mutex) != 0) - { + if (pthread_mutex_destroy(&m_mutex) != 0) { int error = errno; LogPedantic("Failed to destroy mutex. Errno: " << error); @@ -52,32 +49,30 @@ Mutex::~Mutex() void Mutex::Lock() const { - if (pthread_mutex_lock(&m_mutex) != 0) - { + if (pthread_mutex_lock(&m_mutex) != 0) { int error = errno; LogPedantic("Failed to lock mutex. Errno: " << error); ThrowMsg(Exception::LockFailed, - "Failed to lock mutex. Errno: " << error); + "Failed to lock mutex. Errno: " << error); } } void Mutex::Unlock() const { - if (pthread_mutex_unlock(&m_mutex) != 0) - { + if (pthread_mutex_unlock(&m_mutex) != 0) { int error = errno; LogPedantic("Failed to unlock mutex. Errno: " << error); ThrowMsg(Exception::UnlockFailed, - "Failed to unlock mutex. Errno: " << error); + "Failed to unlock mutex. Errno: " << error); } } -Mutex::ScopedLock::ScopedLock(Mutex *mutex) - : m_mutex(mutex) +Mutex::ScopedLock::ScopedLock(Mutex *mutex) : + m_mutex(mutex) { Assert(mutex != NULL); m_mutex->Lock(); @@ -89,7 +84,7 @@ Mutex::ScopedLock::~ScopedLock() { m_mutex->Unlock(); } - Catch (Mutex::Exception::UnlockFailed) + Catch(Mutex::Exception::UnlockFailed) { LogPedantic("Failed to leave mutex scoped lock"); } diff --git a/modules/core/src/named_base_pipe.cpp b/modules/core/src/named_base_pipe.cpp index f582000..9f91d30 100644 --- a/modules/core/src/named_base_pipe.cpp +++ b/modules/core/src/named_base_pipe.cpp @@ -27,29 +27,27 @@ #include #include -namespace DPL -{ +namespace DPL { namespace // anonymous { const mode_t FIFO_MODE = 0600; } // namespace anonymous NamedBasePipe::~NamedBasePipe() -{ -} +{} void NamedBasePipe::Create(const std::string &pipeName) { // Create new fifo int status = mkfifo(pipeName.c_str(), FIFO_MODE); - if (status == -1) - { + if (status == -1) { // Ignore error it it already exists - if (errno == EEXIST) + if (errno == EEXIST) { ThrowMsg(Exception::AlreadyExist, pipeName); - else + } else { ThrowMsg(Exception::CreateFailed, pipeName); + } } } diff --git a/modules/core/src/named_output_pipe.cpp b/modules/core/src/named_output_pipe.cpp index df9b03e..2a9a1fa 100644 --- a/modules/core/src/named_output_pipe.cpp +++ b/modules/core/src/named_output_pipe.cpp @@ -29,12 +29,10 @@ #include #include -namespace DPL -{ -NamedOutputPipe::NamedOutputPipe() - : m_fifo(-1) -{ -} +namespace DPL { +NamedOutputPipe::NamedOutputPipe() : + m_fifo(-1) +{} NamedOutputPipe::~NamedOutputPipe() { @@ -46,19 +44,22 @@ void NamedOutputPipe::Open(const std::string& pipeName) // Then open it for reading or writing int fifo = TEMP_FAILURE_RETRY(open(pipeName.c_str(), O_WRONLY | O_NONBLOCK)); - if (fifo == -1) + if (fifo == -1) { ThrowMsg(Exception::OpenFailed, pipeName); + } m_fifo = fifo; } void NamedOutputPipe::Close() { - if (m_fifo == -1) + if (m_fifo == -1) { return; + } - if (TEMP_FAILURE_RETRY(close(m_fifo)) == -1) + if (TEMP_FAILURE_RETRY(close(m_fifo)) == -1) { Throw(Exception::CloseFailed); + } m_fifo = -1; } @@ -66,8 +67,9 @@ void NamedOutputPipe::Close() size_t NamedOutputPipe::Write(const BinaryQueue &buffer, size_t bufferSize) { // Adjust write size - if (bufferSize > buffer.Size()) + if (bufferSize > buffer.Size()) { bufferSize = buffer.Size(); + } // FIXME: User write visitor to write ! // WriteVisitor visitor @@ -75,20 +77,17 @@ size_t NamedOutputPipe::Write(const BinaryQueue &buffer, size_t bufferSize) ScopedFree flattened(malloc(bufferSize)); buffer.Flatten(flattened.Get(), bufferSize); - ssize_t result = TEMP_FAILURE_RETRY(write(m_fifo, flattened.Get(), bufferSize)); + ssize_t result = + TEMP_FAILURE_RETRY(write(m_fifo, flattened.Get(), bufferSize)); - if (result > 0) - { + if (result > 0) { // Successfuly written some bytes return static_cast(result); - } - else if (result == 0) - { + } else if (result == 0) { // This is abnormal result - ThrowMsg(CommonException::InternalError, "Invalid socket write result, 0 bytes written"); - } - else - { + ThrowMsg(CommonException::InternalError, + "Invalid socket write result, 0 bytes written"); + } else { // Interpret error result // FIXME: Handle errno Throw(AbstractOutput::Exception::WriteFailed); diff --git a/modules/core/src/noncopyable.cpp b/modules/core/src/noncopyable.cpp index 48aff28..9453655 100644 --- a/modules/core/src/noncopyable.cpp +++ b/modules/core/src/noncopyable.cpp @@ -22,13 +22,10 @@ #include #include -namespace DPL -{ +namespace DPL { Noncopyable::Noncopyable() -{ -} +{} Noncopyable::~Noncopyable() -{ -} +{} } // namespace DPL diff --git a/modules/core/src/once.cpp b/modules/core/src/once.cpp index c29d928..f2d4a1a 100644 --- a/modules/core/src/once.cpp +++ b/modules/core/src/once.cpp @@ -22,20 +22,21 @@ #include #include -namespace DPL -{ +namespace DPL { void Once::Call(Delegate delegate) { // First chance test - if (m_atomic == 1) + if (m_atomic == 1) { return; + } // Enter mutex Mutex::ScopedLock lock(&m_mutex); // Second chance test - if (m_atomic == 1) + if (m_atomic == 1) { return; + } // Initialization: call delegate delegate(); diff --git a/modules/core/src/read_write_mutex.cpp b/modules/core/src/read_write_mutex.cpp index 596b0f6..ef34758 100644 --- a/modules/core/src/read_write_mutex.cpp +++ b/modules/core/src/read_write_mutex.cpp @@ -23,40 +23,44 @@ #include #include -namespace DPL -{ +namespace DPL { ReadWriteMutex::ReadWriteMutex() { - if (pthread_rwlock_init(&m_rwlock, NULL) != 0) + if (pthread_rwlock_init(&m_rwlock, NULL) != 0) { Throw(Exception::CreateFailed); + } } ReadWriteMutex::~ReadWriteMutex() { - if (pthread_rwlock_destroy(&m_rwlock) != 0) + if (pthread_rwlock_destroy(&m_rwlock) != 0) { Throw(Exception::DestroyFailed); + } } void ReadWriteMutex::ReadLock() const { - if (pthread_rwlock_rdlock(&m_rwlock) != 0) + if (pthread_rwlock_rdlock(&m_rwlock) != 0) { Throw(Exception::ReadLockFailed); + } } void ReadWriteMutex::WriteLock() const { - if (pthread_rwlock_wrlock(&m_rwlock) != 0) + if (pthread_rwlock_wrlock(&m_rwlock) != 0) { Throw(Exception::WriteLockFailed); + } } void ReadWriteMutex::Unlock() const { - if (pthread_rwlock_unlock(&m_rwlock) != 0) + if (pthread_rwlock_unlock(&m_rwlock) != 0) { Throw(Exception::UnlockFailed); + } } -ReadWriteMutex::ScopedReadLock::ScopedReadLock(ReadWriteMutex *mutex) - : m_mutex(mutex) +ReadWriteMutex::ScopedReadLock::ScopedReadLock(ReadWriteMutex *mutex) : + m_mutex(mutex) { Assert(mutex != NULL); m_mutex->ReadLock(); @@ -67,8 +71,8 @@ ReadWriteMutex::ScopedReadLock::~ScopedReadLock() m_mutex->Unlock(); } -ReadWriteMutex::ScopedWriteLock::ScopedWriteLock(ReadWriteMutex *mutex) - : m_mutex(mutex) +ReadWriteMutex::ScopedWriteLock::ScopedWriteLock(ReadWriteMutex *mutex) : + m_mutex(mutex) { Assert(mutex != NULL); m_mutex->WriteLock(); diff --git a/modules/core/src/recursive_mutex.cpp b/modules/core/src/recursive_mutex.cpp index c9fcd5d..234d25f 100644 --- a/modules/core/src/recursive_mutex.cpp +++ b/modules/core/src/recursive_mutex.cpp @@ -23,8 +23,7 @@ #include #include -namespace DPL -{ +namespace DPL { RecursiveMutex::RecursiveMutex() { pthread_mutexattr_t attr; @@ -32,30 +31,34 @@ RecursiveMutex::RecursiveMutex() pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); - if (pthread_mutex_init(&m_mutex, &attr) != 0) + if (pthread_mutex_init(&m_mutex, &attr) != 0) { Throw(Exception::CreateFailed); + } } RecursiveMutex::~RecursiveMutex() { - if (pthread_mutex_destroy(&m_mutex) != 0) + if (pthread_mutex_destroy(&m_mutex) != 0) { Throw(Exception::DestroyFailed); + } } void RecursiveMutex::Lock() const { - if (pthread_mutex_lock(&m_mutex) != 0) + if (pthread_mutex_lock(&m_mutex) != 0) { Throw(Exception::LockFailed); + } } void RecursiveMutex::Unlock() const { - if (pthread_mutex_unlock(&m_mutex) != 0) + if (pthread_mutex_unlock(&m_mutex) != 0) { Throw(Exception::UnlockFailed); + } } -RecursiveMutex::ScopedLock::ScopedLock(RecursiveMutex *mutex) - : m_mutex(mutex) +RecursiveMutex::ScopedLock::ScopedLock(RecursiveMutex *mutex) : + m_mutex(mutex) { Assert(mutex != NULL); m_mutex->Lock(); diff --git a/modules/core/src/semaphore.cpp b/modules/core/src/semaphore.cpp index bc96cff..387c009 100644 --- a/modules/core/src/semaphore.cpp +++ b/modules/core/src/semaphore.cpp @@ -29,15 +29,14 @@ #include #include -namespace DPL -{ +namespace DPL { void Semaphore::Remove(const std::string &fileName) { if (sem_unlink(fileName.c_str()) == -1) { int error = errno; LogPedantic("Failed to unlink semaphore. Errno: " << error); ThrowMsg(Exception::RemoveFailed, - "Failed to unlink semaphore. Errno: " << error); + "Failed to unlink semaphore. Errno: " << error); } } @@ -55,7 +54,7 @@ Semaphore::Semaphore(size_t maxLockCount) LogPedantic("Failed to create semaphore. Errno: " << error); ThrowMsg(Exception::CreateFailed, - "Failed to create semaphore. Errno: " << error); + "Failed to create semaphore. Errno: " << error); } m_type = Type_Unnamed; @@ -79,50 +78,42 @@ Semaphore::Semaphore(const std::string &fileName, sem_t *semaphore; - do - { - if (allowCreate) - { - if (exclusiveCreate) - { + do { + if (allowCreate) { + if (exclusiveCreate) { semaphore = sem_open(fileName.c_str(), O_CREAT | O_EXCL, permissions, static_cast(maxLockCount)); - } - else - { + } else { semaphore = sem_open(fileName.c_str(), O_CREAT, permissions, static_cast(maxLockCount)); } - } - else - { + } else { semaphore = sem_open(fileName.c_str(), 0); } - } - while (semaphore == SEM_FAILED && errno == EINTR); + } while (semaphore == SEM_FAILED && errno == EINTR); - if (semaphore == SEM_FAILED) - { + if (semaphore == SEM_FAILED) { int error = errno; LogPedantic("Failed to create semaphore '" << fileName - << "'. Errno: " << error); + << "'. Errno: " << error); ThrowMsg(Exception::CreateFailed, "Failed to create semaphore '" << fileName - << "'. Errno: " << error); + << "'. Errno: " << error); } m_semaphore.named.handle = semaphore; m_semaphore.named.name = strdup(fileName.c_str()); // May be NULL - if (m_semaphore.named.name == NULL) + if (m_semaphore.named.name == NULL) { LogPedantic("Out of memory while duplicating semaphore name"); + } m_semaphore.named.unlinkOnDestroy = unlinkOnDestroy; @@ -136,16 +127,15 @@ Semaphore::~Semaphore() sem_t *Semaphore::InternalGet() const { - switch (m_type) - { - case Type_Unnamed: - return &m_semaphore.unnamed.handle; + switch (m_type) { + case Type_Unnamed: + return &m_semaphore.unnamed.handle; - case Type_Named: - return m_semaphore.named.handle; + case Type_Named: + return m_semaphore.named.handle; - default: - Assert(false && "Invalid type"); + default: + Assert(false && "Invalid type"); } return NULL; @@ -153,75 +143,69 @@ sem_t *Semaphore::InternalGet() const void Semaphore::InternalDestroy() { - switch (m_type) - { - case Type_Unnamed: - if (sem_destroy(&m_semaphore.unnamed.handle) == -1) - { - int error = errno; + switch (m_type) { + case Type_Unnamed: + if (sem_destroy(&m_semaphore.unnamed.handle) == -1) { + int error = errno; - LogPedantic("Failed to destroy semaphore. Errno: " << error); - } - break; + LogPedantic("Failed to destroy semaphore. Errno: " << error); + } + break; + + case Type_Named: + if (sem_close(m_semaphore.named.handle) == -1) { + int error = errno; + + LogPedantic("Failed to close semaphore. Errno: " << error); + } - case Type_Named: - if (sem_close(m_semaphore.named.handle) == -1) + if (m_semaphore.named.name != NULL) { + // Unlink named semaphore + if (m_semaphore.named.unlinkOnDestroy && + sem_unlink(m_semaphore.named.name) == -1) { int error = errno; - LogPedantic("Failed to close semaphore. Errno: " << error); + LogPedantic("Failed to unlink semaphore. Errno: " + << error); } - if (m_semaphore.named.name != NULL) - { - // Unlink named semaphore - if (m_semaphore.named.unlinkOnDestroy && - sem_unlink(m_semaphore.named.name) == -1) - { - int error = errno; - - LogPedantic("Failed to unlink semaphore. Errno: " - << error); - } - - // Free name - free(m_semaphore.named.name); - } - break; + // Free name + free(m_semaphore.named.name); + } + break; - default: - Assert(false && "Invalid type"); + default: + Assert(false && "Invalid type"); } } void Semaphore::Lock() const { - if (TEMP_FAILURE_RETRY(sem_wait(InternalGet())) != 0) - { + if (TEMP_FAILURE_RETRY(sem_wait(InternalGet())) != 0) { int error = errno; LogPedantic("Failed to lock semaphore. Errno: " << error); ThrowMsg(Exception::LockFailed, - "Failed to lock semaphore. Errno: " << error); + "Failed to lock semaphore. Errno: " << error); } } void Semaphore::Unlock() const { - if (sem_post(InternalGet()) != 0) - { + if (sem_post(InternalGet()) != 0) { int error = errno; LogPedantic("Failed to unlock semaphore. Errno: " << error); ThrowMsg(Exception::UnlockFailed, - "Failed to unlock semaphore. Errno: " << error); + "Failed to unlock semaphore. Errno: " << error); } } -Semaphore::ScopedLock::ScopedLock(Semaphore *semaphore) - : m_semaphore(semaphore) +Semaphore::ScopedLock::ScopedLock(Semaphore *semaphore) : + m_semaphore(semaphore) { Assert(semaphore != NULL); m_semaphore->Lock(); @@ -233,7 +217,7 @@ Semaphore::ScopedLock::~ScopedLock() { m_semaphore->Unlock(); } - Catch (Semaphore::Exception::UnlockFailed) + Catch(Semaphore::Exception::UnlockFailed) { LogPedantic("Failed to leave semaphore scoped lock"); } diff --git a/modules/core/src/single_instance.cpp b/modules/core/src/single_instance.cpp index 71b68da..5f95836 100644 --- a/modules/core/src/single_instance.cpp +++ b/modules/core/src/single_instance.cpp @@ -27,17 +27,15 @@ #include #include -namespace DPL -{ +namespace DPL { namespace // anonumous { const char *LOCK_PREFIX_PATH = "/tmp/dpl_single_instance_"; } -SingleInstance::SingleInstance() - : m_locked(false), - m_fdLock(-1) -{ -} +SingleInstance::SingleInstance() : + m_locked(false), + m_fdLock(-1) +{} SingleInstance::~SingleInstance() { @@ -56,17 +54,20 @@ bool SingleInstance::TryLock(const std::string &lockName) lock.l_len = 1; // Open lock file - m_fdLock = TEMP_FAILURE_RETRY(open((std::string(LOCK_PREFIX_PATH) + lockName).c_str(), O_WRONLY | O_CREAT, 0666)); + m_fdLock = + TEMP_FAILURE_RETRY(open((std::string(LOCK_PREFIX_PATH) + + lockName).c_str(), + O_WRONLY | O_CREAT, 0666)); - if (m_fdLock == -1) + if (m_fdLock == -1) { ThrowMsg(Exception::LockError, "Cannot open single instance lock file!"); + } // Lock file int result = TEMP_FAILURE_RETRY(fcntl(m_fdLock, F_SETLK, &lock)); // Was the instance successfuly locked ? - if (result == 0) - { + if (result == 0) { LogPedantic("Instance locked: " << lockName); // It is locked now @@ -76,8 +77,7 @@ bool SingleInstance::TryLock(const std::string &lockName) return true; } - if (errno == EACCES || errno == EAGAIN) - { + if (errno == EACCES || errno == EAGAIN) { LogPedantic("Instance is already running: " << lockName); return false; } @@ -88,8 +88,9 @@ bool SingleInstance::TryLock(const std::string &lockName) void SingleInstance::Release() { - if (!m_locked) + if (!m_locked) { return; + } LogPedantic("Unlocking single instance"); @@ -104,12 +105,16 @@ void SingleInstance::Release() int result = TEMP_FAILURE_RETRY(fcntl(m_fdLock, F_SETLK, &lock)); // Was the instance successfuly unlocked ? - if (result == -1) - ThrowMsg(Exception::LockError, "Cannot unlock single instance lock file!"); + if (result == -1) { + ThrowMsg(Exception::LockError, + "Cannot unlock single instance lock file!"); + } // Close lock file - if (TEMP_FAILURE_RETRY(close(m_fdLock)) == -1) - ThrowMsg(Exception::LockError, "Cannot close single instance lock file!"); + if (TEMP_FAILURE_RETRY(close(m_fdLock)) == -1) { + ThrowMsg(Exception::LockError, + "Cannot close single instance lock file!"); + } m_fdLock = -1; diff --git a/modules/core/src/string.cpp b/modules/core/src/string.cpp old mode 100755 new mode 100644 index f39e59a..e81ae22 --- a/modules/core/src/string.cpp +++ b/modules/core/src/string.cpp @@ -35,34 +35,33 @@ #include // TODO: Completely move to ICU -namespace DPL -{ +namespace DPL { namespace //anonymous { class ASCIIValidator { const std::string& m_TestedString; -public: + public: ASCIIValidator(const std::string& aTestedString); void operator()(char aCharacter) const; }; -ASCIIValidator::ASCIIValidator(const std::string& aTestedString) - : m_TestedString(aTestedString) -{ -} +ASCIIValidator::ASCIIValidator(const std::string& aTestedString) : + m_TestedString(aTestedString) +{} void ASCIIValidator::operator()(char aCharacter) const { // Check for ASCII data range - if (aCharacter <= 0) - { - ThrowMsg(StringException::InvalidASCIICharacter, - "invalid character code " << static_cast(aCharacter) - << " from string [" << m_TestedString - << "] passed as ASCII"); + if (aCharacter <= 0) { + ThrowMsg( + StringException::InvalidASCIICharacter, + "invalid character code " << static_cast(aCharacter) + << " from string [" << + m_TestedString + << "] passed as ASCII"); } } @@ -72,9 +71,9 @@ const size_t gc_IconvConvertError = static_cast(-1); String FromUTF8String(const std::string& aIn) { - if (aIn.empty()) - + if (aIn.empty()) { return String(); + } size_t inbytes = aIn.size(); @@ -85,7 +84,7 @@ String FromUTF8String(const std::string& aIn) // oldsize - letters in UTF-8 string // end - end character for UTF-32 (\0) // bom - Unicode header in front of string (0xfeff) - size_t outbytes = sizeof(wchar_t)*(inbytes + 2); + size_t outbytes = sizeof(wchar_t) * (inbytes + 2); std::vector output(inbytes + 2, 0); size_t outbytesleft = outbytes; @@ -95,10 +94,9 @@ String FromUTF8String(const std::string& aIn) // but during conversion from UTF32 uses internaly wchar_t char* outbuf = reinterpret_cast(&output[0]); - iconv_t iconvHandle = iconv_open("UTF-32","UTF-8"); + iconv_t iconvHandle = iconv_open("UTF-32", "UTF-8"); - if (gc_IconvOperError == iconvHandle) - { + if (gc_IconvOperError == iconvHandle) { int error = errno; ThrowMsg(StringException::IconvInitErrorUTF8ToUTF32, @@ -106,15 +104,18 @@ String FromUTF8String(const std::string& aIn) "error: " << GetErrnoString(error)); } - size_t iconvRet = iconv(iconvHandle, &inbuf, &inbytes, &outbuf, &outbytesleft); + size_t iconvRet = iconv(iconvHandle, + &inbuf, + &inbytes, + &outbuf, + &outbytesleft); iconv_close(iconvHandle); - if (gc_IconvConvertError == iconvRet) - { + if (gc_IconvConvertError == iconvRet) { ThrowMsg(StringException::IconvConvertErrorUTF8ToUTF32, "iconv failed for " << "UTF-32 <- UTF-8" << "error: " - << GetErrnoString()); + << GetErrnoString()); } // Ignore BOM in front of UTF-32 @@ -123,39 +124,41 @@ String FromUTF8String(const std::string& aIn) std::string ToUTF8String(const DPL::String& aIn) { - if (aIn.empty()) - + if (aIn.empty()) { return std::string(); + } size_t inbytes = aIn.size() * sizeof(wchar_t); size_t outbytes = inbytes + sizeof(char); // wstring returns wchar_t but iconv expects char* // iconv internally is processing input as wchar_t - char* inbuf = reinterpret_cast(const_cast(aIn.c_str())); + char* inbuf = reinterpret_cast(const_cast(aIn.c_str())); std::vector output(inbytes, 0); char* outbuf = &output[0]; size_t outbytesleft = outbytes; - iconv_t iconvHandle = iconv_open("UTF-8","UTF-32"); + iconv_t iconvHandle = iconv_open("UTF-8", "UTF-32"); - if (gc_IconvOperError == iconvHandle) - { + if (gc_IconvOperError == iconvHandle) { ThrowMsg(StringException::IconvInitErrorUTF32ToUTF8, "iconv_open failed for " << "UTF-8 <- UTF-32" - << "error: " << GetErrnoString()); + << "error: " << GetErrnoString()); } - size_t iconvRet = iconv(iconvHandle, &inbuf, &inbytes, &outbuf, &outbytesleft); + size_t iconvRet = iconv(iconvHandle, + &inbuf, + &inbytes, + &outbuf, + &outbytesleft); iconv_close(iconvHandle); - if (gc_IconvConvertError == iconvRet) - { + if (gc_IconvConvertError == iconvRet) { ThrowMsg(StringException::IconvConvertErrorUTF32ToUTF8, "iconv failed for " << "UTF-8 <- UTF-32" - << "error: " << GetErrnoString()); + << "error: " << GetErrnoString()); } return &output[0]; @@ -196,9 +199,7 @@ static UChar *ConvertToICU(const String &inputString) { // What buffer size is ok ? LogPedantic("ICU: Output buffer size: " << size); - } - else - { + } else { ThrowMsg(StringException::ICUInvalidCharacterFound, "ICU: Failed to retrieve output string size. Error: " << error); @@ -218,8 +219,7 @@ static UChar *ConvertToICU(const String &inputString) -1, &error); - if (!U_SUCCESS(error)) - { + if (!U_SUCCESS(error)) { ThrowMsg(StringException::ICUInvalidCharacterFound, "ICU: Failed to convert string. Error: " << error); } @@ -236,12 +236,9 @@ int StringCompare(const String &left, ScopedArray leftICU(ConvertToICU(left)); ScopedArray rightICU(ConvertToICU(right)); - if (caseInsensitive) - { + if (caseInsensitive) { return static_cast(u_strcasecmp(leftICU.Get(), rightICU.Get(), 0)); - } - else - { + } else { return static_cast(u_strcmp(leftICU.Get(), rightICU.Get())); } } diff --git a/modules/core/src/task_list.cpp b/modules/core/src/task_list.cpp index 2176c31..928f254 100644 --- a/modules/core/src/task_list.cpp +++ b/modules/core/src/task_list.cpp @@ -24,19 +24,19 @@ #include #include -namespace DPL -{ -TaskList::TaskList() - : m_switched(false), - m_running(false) +namespace DPL { +TaskList::TaskList() : + m_switched(false), + m_running(false) { m_currentTask = m_tasks.end(); } TaskList::~TaskList() { - for (Tasks::iterator i = m_tasks.begin(); i != m_tasks.end(); ++i) + for (Tasks::iterator i = m_tasks.begin(); i != m_tasks.end(); ++i) { delete *i; + } } void TaskList::AddTask(Task *task) @@ -50,38 +50,40 @@ bool TaskList::NextStep() { m_running = true; - Assert(m_currentTask != m_tasks.end() && "Task list is empty or all tasks done"); + Assert( + m_currentTask != m_tasks.end() && + "Task list is empty or all tasks done"); m_switched = false; bool result = (*m_currentTask)->NextStep(); - if (result || m_switched) + if (result || m_switched) { return true; + } return ++m_currentTask != m_tasks.end(); } bool TaskList::Abort() { - m_tasks.erase(m_currentTask,m_tasks.end()); + m_tasks.erase(m_currentTask, m_tasks.end()); m_tasks.reverse(); - for (Tasks::iterator i = m_tasks.begin(); i != m_tasks.end();) - { + for (Tasks::iterator i = m_tasks.begin(); i != m_tasks.end();) { //If given task does not have any "abortSteps", remove it from the list - if(!(*i)->Abort()) - { + if (!(*i)->Abort()) { delete *i; - i=m_tasks.erase(i); + i = m_tasks.erase(i); continue; } ++i; } - if(m_tasks.empty()) + if (m_tasks.empty()) { return false; + } - m_currentTask=m_tasks.begin(); + m_currentTask = m_tasks.begin(); return true; } @@ -103,10 +105,10 @@ size_t TaskList::GetStepCount() const { size_t count = 0; - for (Tasks::const_iterator i = m_tasks.begin(); i != m_tasks.end(); ++i) + for (Tasks::const_iterator i = m_tasks.begin(); i != m_tasks.end(); ++i) { count += (*i)->GetStepCount(); + } return count; } - } // namespace DPL diff --git a/modules/core/src/thread.cpp b/modules/core/src/thread.cpp index 3974406..0e75810 100644 --- a/modules/core/src/thread.cpp +++ b/modules/core/src/thread.cpp @@ -44,13 +44,13 @@ static const pthread_t g_mainThread = pthread_self(); class ThreadSpecific { -public: + public: pthread_key_t threadSpecific; - ThreadSpecific() - : threadSpecific(0) + ThreadSpecific() : + threadSpecific(0) { - threadSpecific=0; + threadSpecific = 0; pthread_key_create(&threadSpecific, NULL); } @@ -63,17 +63,15 @@ public: static ThreadSpecific g_threadSpecific; } // namespace anonymous -namespace DPL -{ +namespace DPL { bool g_TLSforMainCreated = false; -Thread::Thread() - : m_thread(0), - m_abandon(false), - m_running(false), - m_directInvoke(false) -{ -} +Thread::Thread() : + m_thread(0), + m_abandon(false), + m_running(false), + m_directInvoke(false) +{} Thread::~Thread() { @@ -85,8 +83,12 @@ Thread::~Thread() // Remove any remainig events // Thread proc is surely not running now - for (InternalEventList::iterator iterator = m_eventList.begin(); iterator != m_eventList.end(); ++iterator) + for (InternalEventList::iterator iterator = m_eventList.begin(); + iterator != m_eventList.end(); + ++iterator) + { iterator->eventDeleteProc(iterator->event, iterator->userParam); + } m_eventList.clear(); } @@ -98,14 +100,16 @@ bool Thread::IsMainThread() Thread *Thread::GetCurrentThread() { - if (pthread_equal(pthread_self(), g_mainThread)) + if (pthread_equal(pthread_self(), g_mainThread)) { return NULL; + } void *threadSpecific = pthread_getspecific(g_threadSpecific.threadSpecific); // Is this a managed thread ? - if (threadSpecific == NULL) + if (threadSpecific == NULL) { Throw(Exception::UnmanagedThread); + } return static_cast(threadSpecific); } @@ -119,10 +123,9 @@ void *Thread::StaticThreadEntry(void *param) Assert(This != NULL); // Set thread specific - int result = pthread_setspecific(g_threadSpecific.threadSpecific, This); + int result = pthread_setspecific(g_threadSpecific.threadSpecific, This); - if (result!=0) - { + if (result != 0) { LogError("Failed to set threadSpecific. Error: " << strerror(result)); } @@ -142,13 +145,10 @@ void *Thread::StaticThreadEntry(void *param) This->m_running = false; // Abandon thread - if (This->m_abandon) - { + if (This->m_abandon) { LogPedantic("Thread was abandoned"); pthread_detach(This->m_thread); - } - else - { + } else { LogPedantic("Thread is joinable"); } } @@ -165,7 +165,7 @@ int Thread::ThreadEntry() void Thread::ProcessEvents() { LogPedantic("Processing events"); - + // Steal current event list InternalEventList stolenEvents; @@ -179,7 +179,9 @@ void Thread::ProcessEvents() // Process event list LogPedantic("Stolen " << stolenEvents.size() << " internal events"); - for (InternalEventList::iterator iterator = stolenEvents.begin(); iterator != stolenEvents.end(); ++iterator) + for (InternalEventList::iterator iterator = stolenEvents.begin(); + iterator != stolenEvents.end(); + ++iterator) { // Dispatch immediate event iterator->eventDispatchProc(iterator->event, iterator->userParam); @@ -199,16 +201,24 @@ void Thread::ProcessTimedEvents() unsigned long currentTimeMiliseconds = GetCurrentTimeMiliseconds(); // Info - LogPedantic("Processing timed events. Time now: " << currentTimeMiliseconds << " ms"); + LogPedantic( + "Processing timed events. Time now: " << currentTimeMiliseconds << + " ms"); // All timed events are sorted chronologically // Emit timed out events while (!m_timedEventVector.empty() && - currentTimeMiliseconds >= m_timedEventVector.begin()->registerTimeMiliseconds + m_timedEventVector.begin()->dueTimeMiliseconds) + currentTimeMiliseconds >= + m_timedEventVector.begin()->registerTimeMiliseconds + + m_timedEventVector.begin()->dueTimeMiliseconds) { // Info - LogPedantic("Transforming timed event into immediate event. Absolute due time: " << - (m_timedEventVector.begin()->registerTimeMiliseconds + m_timedEventVector.begin()->dueTimeMiliseconds) << " ms"); + LogPedantic( + "Transforming timed event into immediate event. Absolute due time: " + << + (m_timedEventVector.begin()->registerTimeMiliseconds + + m_timedEventVector.begin()->dueTimeMiliseconds) << + " ms"); // Emit immediate event PushEvent(m_timedEventVector.begin()->event, @@ -227,7 +237,8 @@ unsigned long Thread::GetCurrentTimeMiliseconds() const { timeval tv; gettimeofday(&tv, NULL); - return static_cast(tv.tv_sec) * 1000 + static_cast(tv.tv_usec) / 1000; + return static_cast(tv.tv_sec) * 1000 + + static_cast(tv.tv_usec) / 1000; } int Thread::Exec() @@ -243,28 +254,34 @@ int Thread::Exec() handleList.push_back(std::make_pair(m_quitEvent.GetHandle(), WaitMode::Read)); // index 1: Event occurred event handle - handleList.push_back(std::make_pair(m_eventInvoker.GetHandle(), WaitMode::Read)); + handleList.push_back(std::make_pair(m_eventInvoker.GetHandle(), + WaitMode::Read)); // index 2: Timed event occurred event handle - handleList.push_back(std::make_pair(m_timedEventInvoker.GetHandle(), WaitMode::Read)); + handleList.push_back(std::make_pair(m_timedEventInvoker.GetHandle(), + WaitMode::Read)); // index 3: Waitable handle watch support invoker - handleList.push_back(std::make_pair(WaitableHandleWatchSupport::WaitableInvokerHandle(), WaitMode::Read)); + handleList.push_back(std::make_pair(WaitableHandleWatchSupport:: + WaitableInvokerHandle(), + WaitMode::Read)); // // Watch list might have been initialized before threaded started // Need to fill waitable event watch list in this case // { - WaitableHandleListEx waitableHandleWatchHandles = WaitableHandleWatchSupport::WaitableWatcherHandles(); - std::copy(waitableHandleWatchHandles.begin(), waitableHandleWatchHandles.end(), std::back_inserter(handleList)); + WaitableHandleListEx waitableHandleWatchHandles = + WaitableHandleWatchSupport::WaitableWatcherHandles(); + std::copy( + waitableHandleWatchHandles.begin(), + waitableHandleWatchHandles.end(), std::back_inserter(handleList)); } // Quit flag bool quit = false; - while (!quit) - { + while (!quit) { // Retrieve minimum wait time, according to timed events list unsigned long minimumWaitTime; @@ -272,29 +289,34 @@ int Thread::Exec() { Mutex::ScopedLock lock(&m_timedEventMutex); - if (!m_timedEventVector.empty()) - { - unsigned long currentTimeMiliseconds = GetCurrentTimeMiliseconds(); - unsigned long destinationTimeMiliseconds = m_timedEventVector.begin()->registerTimeMiliseconds + m_timedEventVector.begin()->dueTimeMiliseconds; + if (!m_timedEventVector.empty()) { + unsigned long currentTimeMiliseconds = + GetCurrentTimeMiliseconds(); + unsigned long destinationTimeMiliseconds = + m_timedEventVector.begin()->registerTimeMiliseconds + + m_timedEventVector.begin()->dueTimeMiliseconds; // Are we already late with timed event ? - if (currentTimeMiliseconds > destinationTimeMiliseconds) + if (currentTimeMiliseconds > destinationTimeMiliseconds) { minimumWaitTime = 0; - else - minimumWaitTime = destinationTimeMiliseconds - currentTimeMiliseconds; - } - else + } else { + minimumWaitTime = destinationTimeMiliseconds - + currentTimeMiliseconds; + } + } else { minimumWaitTime = 0xFFFFFFFF; // Infinity + } } // Info - LogPedantic("Thread loop minimum wait time: " << minimumWaitTime << " ms"); + LogPedantic( + "Thread loop minimum wait time: " << minimumWaitTime << " ms"); // Do thread waiting - WaitableHandleIndexList waitableHandleIndexList = WaitForMultipleHandles(handleList, minimumWaitTime); + WaitableHandleIndexList waitableHandleIndexList = + WaitForMultipleHandles(handleList, minimumWaitTime); - if (waitableHandleIndexList.empty()) - { + if (waitableHandleIndexList.empty()) { // Timeout occurred. Process timed events. LogPedantic("Timed event list elapsed invoker"); ProcessTimedEvents(); @@ -302,7 +324,8 @@ int Thread::Exec() } // Go through each index - for (WaitableHandleIndexList::const_iterator waitableHandleIndexIterator = waitableHandleIndexList.begin(); + for (WaitableHandleIndexList::const_iterator + waitableHandleIndexIterator = waitableHandleIndexList.begin(); waitableHandleIndexIterator != waitableHandleIndexList.end(); ++waitableHandleIndexIterator) { @@ -310,106 +333,116 @@ int Thread::Exec() LogPedantic("Event loop triggered with index: " << index); - switch (index) - { - case 0: - // Quit waitable event handle - quit = true; - break; + switch (index) { + case 0: + // Quit waitable event handle + quit = true; + break; - case 1: - // Event occurred event handle - ProcessEvents(); + case 1: + // Event occurred event handle + ProcessEvents(); - // Handle direct invoker - if (m_directInvoke) - { - m_directInvoke = false; + // Handle direct invoker + if (m_directInvoke) { + m_directInvoke = false; - LogPedantic("Handling direct invoker"); + LogPedantic("Handling direct invoker"); - // Update list - while (handleList.size() > MIN_HANDLE_LIST_SIZE) - handleList.pop_back(); + // Update list + while (handleList.size() > MIN_HANDLE_LIST_SIZE) { + handleList.pop_back(); + } - // Insert current waitable event handles instead - { - WaitableHandleListEx waitableHandleWatchHandles = WaitableHandleWatchSupport::WaitableWatcherHandles(); - std::copy(waitableHandleWatchHandles.begin(), waitableHandleWatchHandles.end(), std::back_inserter(handleList)); - } + // Insert current waitable event handles instead + { + WaitableHandleListEx waitableHandleWatchHandles = + WaitableHandleWatchSupport::WaitableWatcherHandles(); + std::copy( + waitableHandleWatchHandles.begin(), + waitableHandleWatchHandles.end(), + std::back_inserter(handleList)); } + } - // Done - break; + // Done + break; - case 2: - // Timed event list changed - LogPedantic("Timed event list changed invoker"); - ProcessTimedEvents(); + case 2: + // Timed event list changed + LogPedantic("Timed event list changed invoker"); + ProcessTimedEvents(); - // Reset timed event invoker - m_timedEventInvoker.Reset(); + // Reset timed event invoker + m_timedEventInvoker.Reset(); - // Done - break; + // Done + break; - case 3: - // Waitable handle watch support invoker - LogPedantic("Waitable handle watch invoker event occurred"); + case 3: + // Waitable handle watch support invoker + LogPedantic("Waitable handle watch invoker event occurred"); - // First, remove all previous handles - while (handleList.size() > MIN_HANDLE_LIST_SIZE) - handleList.pop_back(); + // First, remove all previous handles + while (handleList.size() > MIN_HANDLE_LIST_SIZE) { + handleList.pop_back(); + } - // Insert current waitable event handles instead - { - WaitableHandleListEx waitableHandleWatchHandles = WaitableHandleWatchSupport::WaitableWatcherHandles(); - std::copy(waitableHandleWatchHandles.begin(), waitableHandleWatchHandles.end(), std::back_inserter(handleList)); - } + // Insert current waitable event handles instead + { + WaitableHandleListEx waitableHandleWatchHandles = + WaitableHandleWatchSupport::WaitableWatcherHandles(); + std::copy( + waitableHandleWatchHandles.begin(), + waitableHandleWatchHandles.end(), + std::back_inserter(handleList)); + } - // Handle invoker in waitable watch support - WaitableHandleWatchSupport::InvokerFinished(); + // Handle invoker in waitable watch support + WaitableHandleWatchSupport::InvokerFinished(); - LogPedantic("Waitable handle watch invoker event handled"); + LogPedantic("Waitable handle watch invoker event handled"); - // Done - break; + // Done + break; - default: - // Waitable event watch list - LogPedantic("Waitable handle watch event occurred"); + default: + // Waitable event watch list + LogPedantic("Waitable handle watch event occurred"); - // Handle event in waitable handle watch - { - std::pair handle = handleList[index]; - WaitableHandleWatchSupport::HandleWatcher(handle.first, handle.second); + // Handle event in waitable handle watch + { + std::pair handle = handleList[index]; + WaitableHandleWatchSupport::HandleWatcher(handle.first, + handle.second); + } + + if (m_directInvoke) { + m_directInvoke = false; + + LogPedantic("Handling direct invoker"); + + // Update list + while (handleList.size() > MIN_HANDLE_LIST_SIZE) { + handleList.pop_back(); } - if (m_directInvoke) + // Insert current waitable event handles instead { - m_directInvoke = false; - - LogPedantic("Handling direct invoker"); - - // Update list - while (handleList.size() > MIN_HANDLE_LIST_SIZE) - handleList.pop_back(); - - // Insert current waitable event handles instead - { - WaitableHandleListEx waitableHandleWatchHandles = - WaitableHandleWatchSupport:: - WaitableWatcherHandles(); - std::copy(waitableHandleWatchHandles.begin(), - waitableHandleWatchHandles.end(), - std::back_inserter(handleList)); - } + WaitableHandleListEx waitableHandleWatchHandles = + WaitableHandleWatchSupport:: + WaitableWatcherHandles(); + std::copy(waitableHandleWatchHandles.begin(), + waitableHandleWatchHandles.end(), + std::back_inserter(handleList)); } + } - LogPedantic("Waitable handle watch event handled"); + LogPedantic("Waitable handle watch event handled"); - // Done - break; + // Done + break; } } } @@ -426,12 +459,14 @@ void Thread::Run() { Mutex::ScopedLock lock(&m_stateMutex); - if (m_running) + if (m_running) { return; + } // Try to create new thread - if (pthread_create(&m_thread, NULL, &StaticThreadEntry, this) != 0) + if (pthread_create(&m_thread, NULL, &StaticThreadEntry, this) != 0) { Throw(Exception::RunFailed); + } // At default, we abandon thread m_abandon = true; @@ -452,8 +487,9 @@ void Thread::Quit() Mutex::ScopedLock lock(&m_stateMutex); // Is thread running ? - if (!m_running) + if (!m_running) { return; + } LogPedantic("Quitting thread..."); @@ -471,19 +507,24 @@ void Thread::Quit() // Wait for joinable thread void *result; - if (pthread_join(joinableThread, &result) != 0) + if (pthread_join(joinableThread, &result) != 0) { Throw(Exception::QuitFailed); + } LogPedantic("Thread quit"); } -void Thread::PushEvent(void *event, EventDispatchProc eventDispatchProc, EventDeleteProc eventDeleteProc, void *userParam) +void Thread::PushEvent(void *event, + EventDispatchProc eventDispatchProc, + EventDeleteProc eventDeleteProc, + void *userParam) { // Enter event list critical section Mutex::ScopedLock lock(&m_eventMutex); // Push new event - m_eventList.push_back(InternalEvent(event, userParam, eventDispatchProc, eventDeleteProc)); + m_eventList.push_back(InternalEvent(event, userParam, eventDispatchProc, + eventDeleteProc)); // Trigger invoker m_eventInvoker.Signal(); @@ -491,7 +532,11 @@ void Thread::PushEvent(void *event, EventDispatchProc eventDispatchProc, EventDe LogPedantic("Event pushed and invoker signaled"); } -void Thread::PushTimedEvent(void *event, double dueTimeSeconds, EventDispatchProc eventDispatchProc, EventDeleteProc eventDeleteProc, void *userParam) +void Thread::PushTimedEvent(void *event, + double dueTimeSeconds, + EventDispatchProc eventDispatchProc, + EventDeleteProc eventDeleteProc, + void *userParam) { // Check for developer errors Assert(dueTimeSeconds >= 0.0); @@ -503,10 +548,15 @@ void Thread::PushTimedEvent(void *event, double dueTimeSeconds, EventDispatchPro unsigned long currentTimeMiliseconds = GetCurrentTimeMiliseconds(); // Convert to miliseconds - unsigned long dueTimeMiliseconds = static_cast(1000.0 * dueTimeSeconds); + unsigned long dueTimeMiliseconds = + static_cast(1000.0 * dueTimeSeconds); // Push new timed event - m_timedEventVector.push_back(InternalTimedEvent(event, userParam, dueTimeMiliseconds, currentTimeMiliseconds, eventDispatchProc, eventDeleteProc)); + m_timedEventVector.push_back(InternalTimedEvent(event, userParam, + dueTimeMiliseconds, + currentTimeMiliseconds, + eventDispatchProc, + eventDeleteProc)); // Heapify timed events std::make_heap(m_timedEventVector.begin(), m_timedEventVector.end()); @@ -514,7 +564,10 @@ void Thread::PushTimedEvent(void *event, double dueTimeSeconds, EventDispatchPro // Trigger invoker m_timedEventInvoker.Signal(); - LogPedantic("Timed event pushed and invoker signaled: due time: " << dueTimeMiliseconds << " ms, absolute due time: " << currentTimeMiliseconds + dueTimeMiliseconds << " ms"); + LogPedantic( + "Timed event pushed and invoker signaled: due time: " << + dueTimeMiliseconds << " ms, absolute due time: " << + currentTimeMiliseconds + dueTimeMiliseconds << " ms"); } Thread *Thread::GetInvokerThread() @@ -531,7 +584,7 @@ void Thread::HandleDirectInvoker() void Thread::Sleep(uint64_t seconds) { - NanoSleep(seconds * NANOSECONDS_PER_SECOND); + NanoSleep(seconds * NANOSECONDS_PER_SECOND); } void Thread::MiliSleep(uint64_t miliseconds) @@ -546,8 +599,7 @@ void Thread::MicroSleep(uint64_t microseconds) void Thread::NanoSleep(uint64_t nanoseconds) { - timespec requestedTime = - { + timespec requestedTime = { static_cast( nanoseconds / NANOSECONDS_PER_SECOND), @@ -557,10 +609,10 @@ void Thread::NanoSleep(uint64_t nanoseconds) timespec remainingTime; - for (;;) - { - if (nanosleep(&requestedTime, &remainingTime) == 0) + for (;;) { + if (nanosleep(&requestedTime, &remainingTime) == 0) { break; + } int error = errno; Assert(error == EINTR); diff --git a/modules/core/src/waitable_event.cpp b/modules/core/src/waitable_event.cpp index f72190b..4808896 100644 --- a/modules/core/src/waitable_event.cpp +++ b/modules/core/src/waitable_event.cpp @@ -27,24 +27,29 @@ #include #include -namespace DPL -{ +namespace DPL { WaitableEvent::WaitableEvent() { - if (pipe(m_pipe) == -1) + if (pipe(m_pipe) == -1) { Throw(Exception::CreateFailed); + } - if (fcntl(m_pipe[0], F_SETFL, O_NONBLOCK | fcntl(m_pipe[0], F_GETFL)) == -1) + if (fcntl(m_pipe[0], F_SETFL, O_NONBLOCK | + fcntl(m_pipe[0], F_GETFL)) == -1) + { Throw(Exception::CreateFailed); + } } WaitableEvent::~WaitableEvent() { - if (TEMP_FAILURE_RETRY(close(m_pipe[0])) == -1) + if (TEMP_FAILURE_RETRY(close(m_pipe[0])) == -1) { Throw(Exception::DestroyFailed); + } - if (TEMP_FAILURE_RETRY(close(m_pipe[1])) == -1) + if (TEMP_FAILURE_RETRY(close(m_pipe[1])) == -1) { Throw(Exception::DestroyFailed); + } } WaitableHandle WaitableEvent::GetHandle() const @@ -56,15 +61,17 @@ void WaitableEvent::Signal() const { char data = 0; - if (TEMP_FAILURE_RETRY(write(m_pipe[1], &data, 1)) != 1) + if (TEMP_FAILURE_RETRY(write(m_pipe[1], &data, 1)) != 1) { Throw(Exception::SignalFailed); + } } void WaitableEvent::Reset() const { char data; - if (TEMP_FAILURE_RETRY(read(m_pipe[0], &data, 1)) != 1) + if (TEMP_FAILURE_RETRY(read(m_pipe[0], &data, 1)) != 1) { Throw(Exception::ResetFailed); + } } } // namespace DPL diff --git a/modules/core/src/waitable_handle.cpp b/modules/core/src/waitable_handle.cpp index 8875563..2894022 100644 --- a/modules/core/src/waitable_handle.cpp +++ b/modules/core/src/waitable_handle.cpp @@ -29,8 +29,7 @@ #include #include -namespace DPL -{ +namespace DPL { namespace // anonymous { void CheckWaitableHandle(WaitableHandle handle) @@ -39,29 +38,35 @@ void CheckWaitableHandle(WaitableHandle handle) // Try to get descriptor flags int result = fcntl(handle, F_GETFL); - if (result == -1 && errno == EBADF) + if (result == -1 && errno == EBADF) { Assert(0 && "CheckWaitableHandle: Invalid WaitableHandle! (EBADF)"); + } Assert(result != -1 && "CheckWaitableHandle: Invalid WaitableHandle!"); #endif // DPL_ENABLE_WAITABLE_HANDLE_BADF_CHECK } } // namespace anonymous -WaitableHandleIndexList WaitForSingleHandle(WaitableHandle handle, unsigned long miliseconds) +WaitableHandleIndexList WaitForSingleHandle(WaitableHandle handle, + unsigned long miliseconds) { WaitableHandleList waitHandles; waitHandles.push_back(handle); return WaitForMultipleHandles(waitHandles, miliseconds); } -WaitableHandleIndexList WaitForSingleHandle(WaitableHandle handle, WaitMode::Type mode, unsigned long miliseconds) +WaitableHandleIndexList WaitForSingleHandle(WaitableHandle handle, + WaitMode::Type mode, + unsigned long miliseconds) { WaitableHandleListEx waitHandles; waitHandles.push_back(std::make_pair(handle, mode)); return WaitForMultipleHandles(waitHandles, miliseconds); } -WaitableHandleIndexList WaitForMultipleHandles(const WaitableHandleList &waitableHandleList, unsigned long miliseconds) +WaitableHandleIndexList WaitForMultipleHandles( + const WaitableHandleList &waitableHandleList, + unsigned long miliseconds) { WaitableHandleListEx handleList; @@ -77,7 +82,9 @@ WaitableHandleIndexList WaitForMultipleHandles(const WaitableHandleList &waitabl return WaitForMultipleHandles(handleList, miliseconds); } -WaitableHandleIndexList WaitForMultipleHandles(const WaitableHandleListEx &waitableHandleListEx, unsigned long miliseconds) +WaitableHandleIndexList WaitForMultipleHandles( + const WaitableHandleListEx &waitableHandleListEx, + unsigned long miliseconds) { fd_set readFds, writeFds, errorFds; @@ -89,24 +96,23 @@ WaitableHandleIndexList WaitForMultipleHandles(const WaitableHandleListEx &waita FD_ZERO(&errorFds); // Add read wait handles - for (WaitableHandleListEx::const_iterator iterator = waitableHandleListEx.begin(); + for (WaitableHandleListEx::const_iterator iterator = + waitableHandleListEx.begin(); iterator != waitableHandleListEx.end(); ++iterator) { - if (iterator->first > maxFd) + if (iterator->first > maxFd) { maxFd = iterator->first; + } CheckWaitableHandle(iterator->first); // Handle errors along with read and write events FD_SET(iterator->first, &errorFds); - if (iterator->second == WaitMode::Read) - { + if (iterator->second == WaitMode::Read) { FD_SET(iterator->first, &readFds); - } - else if (iterator->second == WaitMode::Write) - { + } else if (iterator->second == WaitMode::Write) { FD_SET(iterator->first, &writeFds); } } @@ -120,30 +126,32 @@ WaitableHandleIndexList WaitForMultipleHandles(const WaitableHandleListEx &waita effectiveTimeout = &timeout; } - if (TEMP_FAILURE_RETRY(select(maxFd + 1, &readFds, &writeFds, &errorFds, effectiveTimeout)) == -1) + if (TEMP_FAILURE_RETRY(select(maxFd + 1, &readFds, &writeFds, &errorFds, + effectiveTimeout)) == -1) + { Throw(WaitFailed); + } // Check results WaitableHandleIndexList indexes; size_t index = 0; - for (WaitableHandleListEx::const_iterator iterator = waitableHandleListEx.begin(); + for (WaitableHandleListEx::const_iterator iterator = + waitableHandleListEx.begin(); iterator != waitableHandleListEx.end(); ++iterator) { // Always return errors, no matter what type of listening is set if (FD_ISSET(iterator->first, &errorFds)) { indexes.push_back(index); - } - else if (iterator->second == WaitMode::Read) - { - if (FD_ISSET(iterator->first, &readFds)) + } else if (iterator->second == WaitMode::Read) { + if (FD_ISSET(iterator->first, &readFds)) { indexes.push_back(index); - } - else if (iterator->second == WaitMode::Write) - { - if (FD_ISSET(iterator->first, &writeFds)) + } + } else if (iterator->second == WaitMode::Write) { + if (FD_ISSET(iterator->first, &writeFds)) { indexes.push_back(index); + } } ++index; } diff --git a/modules/core/src/waitable_handle_watch_support.cpp b/modules/core/src/waitable_handle_watch_support.cpp index 66fc8b5..53f8b65 100644 --- a/modules/core/src/waitable_handle_watch_support.cpp +++ b/modules/core/src/waitable_handle_watch_support.cpp @@ -17,7 +17,8 @@ * @file waitable_handle_watch_support.cpp * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) * @version 1.0 - * @brief This file is the implementation file of waitable handle watch support + * @brief This file is the implementation file of waitable handle watch + * support */ #include #include @@ -27,33 +28,38 @@ #include #include -namespace DPL -{ +namespace DPL { WaitableHandleWatchSupport::WaitableHandleWatchSupport() -{ -} +{} WaitableHandleWatchSupport::~WaitableHandleWatchSupport() { // Developer assertions - if (!m_watchersMap.empty()) - { + if (!m_watchersMap.empty()) { LogWarning("### Leaked watchers map dump ###"); - for (WaitableHandleWatchersMap::const_iterator iterator = m_watchersMap.begin(); + for (WaitableHandleWatchersMap::const_iterator iterator = + m_watchersMap.begin(); iterator != m_watchersMap.end(); ++iterator) { LogWarning("### Waitable handle: " << iterator->first); - LogWarning("### Read listeners: " << iterator->second.readListenersCount); - LogWarning("### Write listeners: " << iterator->second.writeListenersCount); + LogWarning( + "### Read listeners: " << + iterator->second.readListenersCount); + LogWarning( + "### Write listeners: " << + iterator->second.writeListenersCount); - for (WaitableHandleListenerList::const_iterator listenersIterator = iterator->second.listeners.begin(); + for (WaitableHandleListenerList::const_iterator listenersIterator = + iterator->second.listeners.begin(); listenersIterator != iterator->second.listeners.end(); ++listenersIterator) { - LogWarning("### Mode: " << listenersIterator->mode << ". Listener: 0x" << std::hex << listenersIterator->listener); + LogWarning( + "### Mode: " << listenersIterator->mode << + ". Listener: 0x" << std::hex << listenersIterator->listener); } } } @@ -72,18 +78,23 @@ WaitableHandleListEx WaitableHandleWatchSupport::WaitableWatcherHandles() const WaitableHandleListEx handleList; - for (WaitableHandleWatchersMap::const_iterator iterator = m_watchersMap.begin(); + for (WaitableHandleWatchersMap::const_iterator iterator = + m_watchersMap.begin(); iterator != m_watchersMap.end(); ++iterator) { // Register waitable event id for wait // Check if there are any read listeners and write listeners // and register for both if applicable - if (iterator->second.readListenersCount > 0) - handleList.push_back(std::make_pair(iterator->first, WaitMode::Read)); + if (iterator->second.readListenersCount > 0) { + handleList.push_back(std::make_pair(iterator->first, + WaitMode::Read)); + } - if (iterator->second.writeListenersCount > 0) - handleList.push_back(std::make_pair(iterator->first, WaitMode::Write)); + if (iterator->second.writeListenersCount > 0) { + handleList.push_back(std::make_pair(iterator->first, + WaitMode::Write)); + } } return handleList; @@ -101,13 +112,15 @@ void WaitableHandleWatchSupport::InvokerFinished() m_watchersInvokerCommit.Signal(); } -void WaitableHandleWatchSupport::HandleWatcher(WaitableHandle waitableHandle, WaitMode::Type mode) +void WaitableHandleWatchSupport::HandleWatcher(WaitableHandle waitableHandle, + WaitMode::Type mode) { // // Waitable event occurred // Now call all listeners for that waitable event. It is possible // that some of listeners early disappeared. This is not a problem. - // Warning: Listeners and/or watcher may also disappear during dispatching handlers! + // Warning: Listeners and/or watcher may also disappear during dispatching + // handlers! // LogPedantic("Waitable event occurred"); @@ -115,44 +128,58 @@ void WaitableHandleWatchSupport::HandleWatcher(WaitableHandle waitableHandle, Wa { RecursiveMutex::ScopedLock lock(&m_watchersMutex); - // Notice: We must carefully call watchers here as they may disappear (zero listeners) or be created during each of handler call - // All removed listeners are handled correctly. Adding additional listener to the same waitable handle + // Notice: We must carefully call watchers here as they may disappear + // (zero listeners) or be created during each of handler call + // All removed listeners are handled correctly. Adding + // additional listener to the same waitable handle // during handler dispatch sequence is _not_ supported. WaitableHandleWatchersMap trackedWatchers = m_watchersMap; - for (WaitableHandleWatchersMap::const_iterator trackedWatchersIterator = trackedWatchers.begin(); + for (WaitableHandleWatchersMap::const_iterator trackedWatchersIterator + = trackedWatchers.begin(); trackedWatchersIterator != trackedWatchers.end(); ++trackedWatchersIterator) { // Check if this watcher still exists // If not, go to next tracked watcher - if (m_watchersMap.find(trackedWatchersIterator->first) == m_watchersMap.end()) + if (m_watchersMap.find(trackedWatchersIterator->first) == + m_watchersMap.end()) { LogPedantic("Watcher disappeared during watcher handler"); continue; } // Is this is a waitable handle that we are searching for ? - if (waitableHandle != trackedWatchersIterator->first) + if (waitableHandle != trackedWatchersIterator->first) { continue; + } // Track watcher listeners list - WaitableHandleListenerList trackedListeners = trackedWatchersIterator->second.listeners; + WaitableHandleListenerList trackedListeners = + trackedWatchersIterator->second.listeners; - LogPedantic("Calling waitable event listeners (" << trackedListeners.size() << ")..."); + LogPedantic( + "Calling waitable event listeners (" << + trackedListeners.size() << ")..."); + + // Notice: We must carefully call listeners here as they may + // disappear or be created during each of handler call + // All removed listeners are handled correctly. Adding + // additional listener to the same waitable handle + // during handler dispatch sequence is should be also + // handled, as an extremly case. - // Notice: We must carefully call listeners here as they may disappear or be created during each of handler call - // All removed listeners are handled correctly. Adding additional listener to the same waitable handle - // during handler dispatch sequence is should be also handled, as an extremly case. - // Call all waitable event listeners who listen for that event - for (WaitableHandleListenerList::const_iterator trackedListenersIterator = trackedListeners.begin(); + for (WaitableHandleListenerList::const_iterator + trackedListenersIterator = trackedListeners.begin(); trackedListenersIterator != trackedListeners.end(); ++trackedListenersIterator) { // Check if this watcher still exists - // If not, there cannot be another one. Must exit now (after break, we actually exit) - if (m_watchersMap.find(trackedWatchersIterator->first) == m_watchersMap.end()) + // If not, there cannot be another one. Must exit now (after + // break, we actually exit) + if (m_watchersMap.find(trackedWatchersIterator->first) == + m_watchersMap.end()) { LogPedantic("Watcher disappeared during watcher handler"); break; @@ -162,31 +189,39 @@ void WaitableHandleWatchSupport::HandleWatcher(WaitableHandle waitableHandle, Wa // If not, go to next tracked watcher listener bool listenerStillExists = false; - for (WaitableHandleListenerList::const_iterator searchListenerIterator = trackedWatchersIterator->second.listeners.begin(); - searchListenerIterator != trackedWatchersIterator->second.listeners.end(); + for (WaitableHandleListenerList::const_iterator + searchListenerIterator = + trackedWatchersIterator->second.listeners.begin(); + searchListenerIterator != + trackedWatchersIterator->second.listeners.end(); ++searchListenerIterator) { - if (searchListenerIterator->listener == trackedListenersIterator->listener && - searchListenerIterator->mode == trackedListenersIterator->mode) + if (searchListenerIterator->listener == + trackedListenersIterator->listener && + searchListenerIterator->mode == + trackedListenersIterator->mode) { listenerStillExists = true; break; } } - if (!listenerStillExists) - { - LogPedantic("Watcher listener disappeared during watcher handler"); + if (!listenerStillExists) { + LogPedantic( + "Watcher listener disappeared during watcher handler"); break; } // Is this is a listener mode that we are searching for ? - if (mode != trackedListenersIterator->mode) + if (mode != trackedListenersIterator->mode) { continue; + } // Call waitable event watch listener LogPedantic("Before tracker listener call..."); - trackedListenersIterator->listener->OnWaitableHandleEvent(trackedWatchersIterator->first, trackedListenersIterator->mode); + trackedListenersIterator->listener->OnWaitableHandleEvent( + trackedWatchersIterator->first, + trackedListenersIterator->mode); LogPedantic("After tracker listener call..."); } @@ -201,47 +236,56 @@ void WaitableHandleWatchSupport::HandleWatcher(WaitableHandle waitableHandle, Wa } } -void WaitableHandleWatchSupport::AddWaitableHandleWatch(WaitableHandleListener* listener, WaitableHandle waitableHandle, WaitMode::Type mode) +void WaitableHandleWatchSupport::AddWaitableHandleWatch( + WaitableHandleListener* listener, + WaitableHandle waitableHandle, + WaitMode::Type mode) { // Enter waitable event list critical section RecursiveMutex::ScopedLock lock(&m_watchersMutex); // Find proper list to register into - WaitableHandleWatchersMap::iterator mapIterator = m_watchersMap.find(waitableHandle); - - if (mapIterator != m_watchersMap.end()) - { - // Assert if there is no such listener already that is listening in this mode - for (WaitableHandleListenerList::iterator listenersIterator = mapIterator->second.listeners.begin(); + WaitableHandleWatchersMap::iterator mapIterator = m_watchersMap.find( + waitableHandle); + + if (mapIterator != m_watchersMap.end()) { + // Assert if there is no such listener already that is listening in this + // mode + for (WaitableHandleListenerList::iterator listenersIterator = + mapIterator->second.listeners.begin(); listenersIterator != mapIterator->second.listeners.end(); ++listenersIterator) { // Must not insert same listener-mode pair - Assert(listenersIterator->listener != listener || listenersIterator->mode != mode); + Assert( + listenersIterator->listener != listener || + listenersIterator->mode != mode); } } LogPedantic("Adding waitable handle watch: " << waitableHandle); // Push new waitable event watch - if (mapIterator != m_watchersMap.end()) - mapIterator->second.listeners.push_back(WaitableHandleWatcher(listener, mode)); - else - m_watchersMap[waitableHandle].listeners.push_back(WaitableHandleWatcher(listener, mode)); + if (mapIterator != m_watchersMap.end()) { + mapIterator->second.listeners.push_back(WaitableHandleWatcher(listener, + mode)); + } else { + m_watchersMap[waitableHandle].listeners.push_back(WaitableHandleWatcher( + listener, mode)); + } // Update counters - switch (mode) - { - case WaitMode::Read: - m_watchersMap[waitableHandle].readListenersCount++; - break; + switch (mode) { + case WaitMode::Read: + m_watchersMap[waitableHandle].readListenersCount++; + break; - case WaitMode::Write: - m_watchersMap[waitableHandle].writeListenersCount++; - break; + case WaitMode::Write: + m_watchersMap[waitableHandle].writeListenersCount++; + break; - default: - Assert(0); + default: + Assert(0); } // Trigger waitable event invoker to commit changes @@ -250,25 +294,32 @@ void WaitableHandleWatchSupport::AddWaitableHandleWatch(WaitableHandleListener* LogPedantic("Waitable event watch added and invoker signaled"); } -void WaitableHandleWatchSupport::RemoveWaitableHandleWatch(WaitableHandleListener *listener, WaitableHandle waitableHandle, WaitMode::Type mode) +void WaitableHandleWatchSupport::RemoveWaitableHandleWatch( + WaitableHandleListener *listener, + WaitableHandle waitableHandle, + WaitMode::Type mode) { // Enter waitable event list critical section RecursiveMutex::ScopedLock lock(&m_watchersMutex); // Find proper list with listener - WaitableHandleWatchersMap::iterator mapIterator = m_watchersMap.find(waitableHandle); + WaitableHandleWatchersMap::iterator mapIterator = m_watchersMap.find( + waitableHandle); Assert(mapIterator != m_watchersMap.end()); // Assert if there is such listener and mode - WaitableHandleListenerList::iterator listIterator = mapIterator->second.listeners.end(); + WaitableHandleListenerList::iterator listIterator = + mapIterator->second.listeners.end(); - for (WaitableHandleListenerList::iterator listenersIterator = mapIterator->second.listeners.begin(); + for (WaitableHandleListenerList::iterator listenersIterator = + mapIterator->second.listeners.begin(); listenersIterator != mapIterator->second.listeners.end(); ++listenersIterator) { // Check same pair listener-mode - if (listenersIterator->listener == listener && listenersIterator->mode == mode) + if (listenersIterator->listener == listener && + listenersIterator->mode == mode) { listIterator = listenersIterator; break; @@ -279,28 +330,28 @@ void WaitableHandleWatchSupport::RemoveWaitableHandleWatch(WaitableHandleListene Assert(listIterator != mapIterator->second.listeners.end()); LogPedantic("Removing waitable handle watch: " << waitableHandle); - + // Remove waitable event watch mapIterator->second.listeners.erase(listIterator); // Update counters - switch (mode) - { - case WaitMode::Read: - mapIterator->second.readListenersCount--; - break; + switch (mode) { + case WaitMode::Read: + mapIterator->second.readListenersCount--; + break; - case WaitMode::Write: - mapIterator->second.writeListenersCount--; - break; + case WaitMode::Write: + mapIterator->second.writeListenersCount--; + break; - default: - Assert(0); + default: + Assert(0); } // If list is empty, remove it too - if (mapIterator->second.listeners.empty()) + if (mapIterator->second.listeners.empty()) { m_watchersMap.erase(mapIterator); + } // Trigger waitable event invoker to commit changes CommitInvoker(); @@ -311,15 +362,12 @@ void WaitableHandleWatchSupport::RemoveWaitableHandleWatch(WaitableHandleListene void WaitableHandleWatchSupport::CommitInvoker() { // Check calling context and execute invoker - if (Thread::GetCurrentThread() == GetInvokerThread()) - { + if (Thread::GetCurrentThread() == GetInvokerThread()) { LogPedantic("Calling direct invoker"); // Direct invoker call HandleDirectInvoker(); - } - else - { + } else { LogPedantic("Calling indirect invoker"); // Indirect invoker call @@ -337,9 +385,10 @@ WaitableHandleWatchSupport *WaitableHandleWatchSupport::InheritedContext() { // In threaded context, return thread waitable handle watch implementation // In main loop, return main waitable handle watch implementation - if (Thread::GetCurrentThread() != NULL) + if (Thread::GetCurrentThread() != NULL) { return Thread::GetCurrentThread(); - else + } else { return &MainSingleton::Instance(); + } } } // namespace DPL diff --git a/modules/core/src/zip_input.cpp b/modules/core/src/zip_input.cpp index 691a2ec..4023ed8 100644 --- a/modules/core/src/zip_input.cpp +++ b/modules/core/src/zip_input.cpp @@ -36,30 +36,30 @@ #include #include -namespace DPL -{ +namespace DPL { namespace // anonymous { const size_t EXTRACT_BUFFER_SIZE = 4096; class ScopedUnzClose { -private: + private: unzFile m_file; -public: - ScopedUnzClose(unzFile file) - : m_file(file) - { - } + public: + ScopedUnzClose(unzFile file) : + m_file(file) + {} ~ScopedUnzClose() { - if (!m_file) + if (!m_file) { return; + } - if (unzClose(m_file) != UNZ_OK) + if (unzClose(m_file) != UNZ_OK) { LogPedantic("Failed to close zip input file"); + } } unzFile Release() @@ -86,13 +86,14 @@ public: * * About generalization: * To achieve the same results on abstract input device, there must be - * provided a mechanism to read data from random address without synchronization. + * provided a mechanism to read data from random address without + * synchronization. * In other words: stateless. As described above, stateless property can be * achieved via memory mapping. */ class Device { -private: + private: int m_handle; off64_t m_size; // file mapping size unsigned char *m_address; // mapping base address @@ -102,22 +103,20 @@ private: off64_t offset; Device *device; - File(Device *d) - : offset(0), - device(d) - { - } + File(Device *d) : + offset(0), + device(d) + {} }; -public: + public: Device(const std::string &fileName) { LogPedantic("Creating file mapping"); // Open device and map it to user space int file = TEMP_FAILURE_RETRY(open(fileName.c_str(), O_RDONLY)); - if (file == -1) - { + if (file == -1) { int error = errno; ThrowMsg(ZipInput::Exception::OpenFailed, "Failed to open file. errno = " << error); @@ -129,8 +128,7 @@ public: // Calculate file size off64_t size = lseek64(file, 0, SEEK_END); - if (size == static_cast(-1)) - { + if (size == static_cast(-1)) { int error = errno; ThrowMsg(ZipInput::Exception::OpenFailed, "Failed to seek file. errno = " << error); @@ -140,8 +138,7 @@ public: void *address = mmap(0, static_cast(size), PROT_READ, MAP_SHARED, file, 0); - if (address == MAP_FAILED) - { + if (address == MAP_FAILED) { int error = errno; ThrowMsg(ZipInput::Exception::OpenFailed, "Failed to map file. errno = " << error); @@ -156,21 +153,20 @@ public: LogPedantic("Created file mapping: " << fileName << " of size: " << m_size << - " at address: " << std::hex << static_cast(m_address)); + " at address: " << std::hex << + static_cast(m_address)); } ~Device() { // Close mapping - if (munmap(m_address, static_cast(m_size)) == -1) - { + if (munmap(m_address, static_cast(m_size)) == -1) { int error = errno; LogPedantic("Failed to munmap file. errno = " << error); } // Close file descriptor - if (close(m_handle) == -1) - { + if (close(m_handle) == -1) { int error = errno; LogPedantic("Failed to close file. errno = " << error); } @@ -196,22 +192,22 @@ public: File *deviceFile = static_cast(pstream); // Check if offset is out of bounds - if (deviceFile->offset >= device->m_size) - { + if (deviceFile->offset >= device->m_size) { LogPedantic("Device: read offset out of bounds"); return -1; } off64_t bytesLeft = device->m_size - - deviceFile->offset; + deviceFile->offset; off64_t bytesToRead; // Calculate bytes to read - if (static_cast(size) > bytesLeft) + if (static_cast(size) > bytesLeft) { bytesToRead = bytesLeft; - else + } else { bytesToRead = static_cast(size); + } // Do copy memcpy(buf, @@ -267,38 +263,37 @@ public: Device *device = static_cast(opaque); File *deviceFile = static_cast(stream); - switch (origin) - { - case ZLIB_FILEFUNC_SEEK_SET: - deviceFile->offset = static_cast(offset); + switch (origin) { + case ZLIB_FILEFUNC_SEEK_SET: + deviceFile->offset = static_cast(offset); - break; + break; - case ZLIB_FILEFUNC_SEEK_CUR: - deviceFile->offset += static_cast(offset); + case ZLIB_FILEFUNC_SEEK_CUR: + deviceFile->offset += static_cast(offset); - break; + break; - case ZLIB_FILEFUNC_SEEK_END: - deviceFile->offset = - device->m_size - - static_cast(offset); + case ZLIB_FILEFUNC_SEEK_END: + deviceFile->offset = + device->m_size - + static_cast(offset); - break; + break; - default: - return -1; + default: + return -1; } return 0; } }; -ZipInput::ZipInput(const std::string &fileName) - : m_device(NULL), - m_numberOfFiles(0), - m_globalComment(), - m_fileInfos() +ZipInput::ZipInput(const std::string &fileName) : + m_device(NULL), + m_numberOfFiles(0), + m_globalComment(), + m_fileInfos() { LogPedantic("Zip input file: " << fileName); @@ -320,11 +315,10 @@ ZipInput::ZipInput(const std::string &fileName) LogPedantic("Opening zip file"); unzFile file = unzOpen2_64(NULL, &interface); - if (file == NULL) - { + if (file == NULL) { LogPedantic("Failed to open zip file"); - // Some errror occured + // Some errror occured ThrowMsg(Exception::OpenFailed, "Failed to open zip file: " << fileName); } @@ -347,8 +341,9 @@ ZipInput::ZipInput(const std::string &fileName) ZipInput::~ZipInput() { // Close zip - if (unzClose(static_cast(m_masterFile)) != UNZ_OK) + if (unzClose(static_cast(m_masterFile)) != UNZ_OK) { LogPedantic("Failed to close zip input file"); + } // Close device delete m_device; @@ -398,14 +393,12 @@ void ZipInput::ReadInfos(void *masterFile) // Read infos m_fileInfos.reserve(m_numberOfFiles); - if (unzGoToFirstFile(static_cast(masterFile)) != UNZ_OK) - { + if (unzGoToFirstFile(static_cast(masterFile)) != UNZ_OK) { LogPedantic("Failed to go to first file"); ThrowMsg(Exception::SeekFileFailed, "Failed to seek first file"); } - for (size_t i = 0; i < m_numberOfFiles; ++i) - { + for (size_t i = 0; i < m_numberOfFiles; ++i) { unz_file_pos_s filePos; if (unzGetFilePos(static_cast(masterFile), @@ -451,19 +444,18 @@ void ZipInput::ReadInfos(void *masterFile) FileHandle( static_cast(filePos.pos_in_zip_directory), static_cast(filePos.num_of_file) - ), + ), std::string(fileName.Get()), std::string(fileComment.Get()), static_cast(fileInfo.compressed_size), static_cast(fileInfo.uncompressed_size) - ) - ); + ) + ); // If this is not the last file, go to next one - if (i != m_numberOfFiles - 1) - { + if (i != m_numberOfFiles - 1) { if (unzGoToNextFile( - static_cast(masterFile))!= UNZ_OK) + static_cast(masterFile)) != UNZ_OK) { LogPedantic("Failed to go to next file"); @@ -503,8 +495,7 @@ ZipInput::File *ZipInput::OpenFile(const std::string &fileName) { FOREACH(iterator, m_fileInfos) { - if (iterator->name == fileName) - { + if (iterator->name == fileName) { return new File(m_device, iterator->handle); } } @@ -529,11 +520,10 @@ ZipInput::File::File(class Device *device, FileHandle handle) LogPedantic("Opening zip file"); unzFile file = unzOpen2_64(NULL, &interface); - if (file == NULL) - { + if (file == NULL) { LogPedantic("Failed to open zip file"); - // Some errror occured + // Some errror occured ThrowMsg(ZipInput::Exception::OpenFileFailed, "Failed to open zip file"); } @@ -542,27 +532,24 @@ ZipInput::File::File(class Device *device, FileHandle handle) ScopedUnzClose scopedUnzClose(file); // Look up file handle - unz64_file_pos filePos = - { + unz64_file_pos filePos = { static_cast(handle.first), static_cast(handle.second) }; - if (unzGoToFilePos64(file, &filePos) != UNZ_OK) - { + if (unzGoToFilePos64(file, &filePos) != UNZ_OK) { LogPedantic("Failed to seek to zip file"); - // Some errror occured + // Some errror occured ThrowMsg(ZipInput::Exception::OpenFileFailed, "Failed to open zip file"); } // Open current file for reading - if (unzOpenCurrentFile(file) != UNZ_OK) - { + if (unzOpenCurrentFile(file) != UNZ_OK) { LogPedantic("Failed to open current zip file"); - // Some errror occured + // Some errror occured ThrowMsg(ZipInput::Exception::OpenFileFailed, "Failed to open current zip file"); } @@ -576,30 +563,34 @@ ZipInput::File::File(class Device *device, FileHandle handle) ZipInput::File::~File() { // Close current file for reading - if (unzCloseCurrentFile(static_cast(m_file)) != UNZ_OK) + if (unzCloseCurrentFile(static_cast(m_file)) != UNZ_OK) { LogPedantic("Failed to close current zip input file"); + } // Close zip file - if (unzClose(static_cast(m_file)) != UNZ_OK) + if (unzClose(static_cast(m_file)) != UNZ_OK) { LogPedantic("Failed to close zip input file"); + } } DPL::BinaryQueueAutoPtr ZipInput::File::Read(size_t size) { // Do not even try to unzip if requested zero bytes - if (size == 0) + if (size == 0) { return DPL::BinaryQueueAutoPtr(new DPL::BinaryQueue()); + } // Calc data to read size_t sizeToRead = size > EXTRACT_BUFFER_SIZE ? - EXTRACT_BUFFER_SIZE : - size; + EXTRACT_BUFFER_SIZE : + size; // Extract zip file data (one-copy) ScopedFree rawBuffer(malloc(sizeToRead)); - if (!rawBuffer) + if (!rawBuffer) { throw std::bad_alloc(); + } // Do unpack int bytes = unzReadCurrentFile(static_cast(m_file), @@ -607,8 +598,7 @@ DPL::BinaryQueueAutoPtr ZipInput::File::Read(size_t size) sizeToRead); // Internal unzipper error - if (bytes < 0) - { + if (bytes < 0) { LogPedantic("Extract failed. Error: " << bytes); ThrowMsg(ZipInput::Exception::ReadFileFailed, diff --git a/modules/custom_handler_dao/dao/CustomHandlerDatabase.cpp b/modules/custom_handler_dao/dao/CustomHandlerDatabase.cpp index d0b26c5..d6f70a8 100644 --- a/modules/custom_handler_dao/dao/CustomHandlerDatabase.cpp +++ b/modules/custom_handler_dao/dao/CustomHandlerDatabase.cpp @@ -17,7 +17,6 @@ namespace CustomHandlerDB { namespace Interface { - namespace { const char* CustomHandler_DB_DATABASE = "/opt/dbspace/.wrt_custom_handler.db"; DPL::DB::SqlConnection::Flag::Type CustomHandler_DB_FLAGS = @@ -42,6 +41,5 @@ 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 index 555655e..6d57771 100644 --- a/modules/custom_handler_dao/dao/custom_handler_dao.cpp +++ b/modules/custom_handler_dao/dao/custom_handler_dao.cpp @@ -29,9 +29,7 @@ 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) { @@ -42,49 +40,54 @@ void fillRow(T& row, const CustomHandler& handler, const DPL::String& pkgName) 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); + 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)) - )); + 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->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)) - )); + update->Where(And(Equals(handler. + target), + Or(Equals( + Agreed), + Equals( + AgreedPermanently)) + )); ContentHandlers::Row rowToUpdate = rows.front(); if (handler.user_decision & DecisionSaved) { @@ -105,9 +108,12 @@ void CustomHandlerDAO::registerContentHandler(const CustomHandler& handler) 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))))); + And(Equals(handler. + target), + And(Equals(handler. + url), + Equals( + handler.base_url))))); updateRow->Values(row); updateRow->Execute(); LogDebug("updated"); @@ -127,34 +133,41 @@ void CustomHandlerDAO::registerContentHandler(const CustomHandler& handler) void CustomHandlerDAO::registerProtocolHandler(const CustomHandler& handler) { LogDebug("Registering protocol handler " << handler.target << " " << - handler.base_url); + 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)) - )); + 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->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)) - )); + update->Where(And(Equals(handler. + target), + Or(Equals( + Agreed), + Equals( + AgreedPermanently)) + )); ProtocolHandlers::Row rowToUpdate = rows.front(); if (handler.user_decision & DecisionSaved) { @@ -171,13 +184,18 @@ void CustomHandlerDAO::registerProtocolHandler(const CustomHandler& handler) LogDebug("Inserting new protocol handler"); ProtocolHandlers::Row row; fillRow(row, handler, m_pkgName); - if (getProtocolHandler(handler.target, handler.url, handler.base_url)) { + 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))))); + And(Equals(handler. + target), + And(Equals(handler. + url), + Equals( + handler.base_url))))); updateRow->Values(row); updateRow->Execute(); LogDebug("updated"); @@ -199,15 +217,15 @@ void CustomHandlerDAO::unregisterContentHandler(const DPL::String& target, { 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(); + 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"); + ReThrowMsg(CustomHandlerDAO::Exception::DatabaseError, + "Failed to remove content handler"); } } @@ -216,17 +234,16 @@ void CustomHandlerDAO::unregisterProtocolHandler(const DPL::String& target, { 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(); + 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"); + ReThrowMsg(CustomHandlerDAO::Exception::DatabaseError, + "Failed to remove content handler"); } - } void CustomHandlerDAO::unregisterContentHandler(const DPL::String& target, @@ -235,16 +252,16 @@ void CustomHandlerDAO::unregisterContentHandler(const DPL::String& target, { 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(); + 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"); + ReThrowMsg(CustomHandlerDAO::Exception::DatabaseError, + "Failed to remove content handler"); } } @@ -254,18 +271,18 @@ void CustomHandlerDAO::unregisterProtocolHandler(const DPL::String& target, { 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(); + 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"); + ReThrowMsg(CustomHandlerDAO::Exception::DatabaseError, + "Failed to remove content handler"); } - } void CustomHandlerDAO::removeWidgetProtocolHandlers() @@ -275,7 +292,6 @@ void CustomHandlerDAO::removeWidgetProtocolHandlers() 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"); @@ -289,12 +305,9 @@ void CustomHandlerDAO::removeWidgetContentHandlers() 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 index a7159fa..ff43613 100644 --- a/modules/custom_handler_dao/dao/custom_handler_dao_read_only.cpp +++ b/modules/custom_handler_dao/dao/custom_handler_dao_read_only.cpp @@ -31,9 +31,7 @@ using namespace DPL::DB::ORM; using namespace DPL::DB::ORM::custom_handler; namespace CustomHandlerDB { - namespace { - template CustomHandlerPtr getSingleHandler(std::list row) { @@ -56,29 +54,27 @@ CustomHandlerPtr getSingleHandler(std::list row) } return handler; } - } // namespace -CustomHandlerDAOReadOnly::CustomHandlerDAOReadOnly(const DPL::String& pkgName) : - m_pkgName(pkgName) -{ -} +CustomHandlerDAOReadOnly::CustomHandlerDAOReadOnly(const DPL::String& pkgName) + : + m_pkgName(pkgName) +{} CustomHandlerDAOReadOnly::~CustomHandlerDAOReadOnly() -{ -} +{} CustomHandlerPtr CustomHandlerDAOReadOnly::getProtocolHandler( - const DPL::String& protocol, - const DPL::String& url) + const DPL::String& protocol, + const DPL::String& url) { LogDebug("Getting protocol handler"); - Try{ + Try { CUSTOM_HANDLER_DB_SELECT(select, ProtocolHandlers); select->Where(And(Equals(m_pkgName), - And(Equals(protocol), - Equals(url)))); + And(Equals(protocol), + Equals(url)))); std::list list = select->GetRowList(); return getSingleHandler(list); @@ -89,16 +85,16 @@ CustomHandlerPtr CustomHandlerDAOReadOnly::getProtocolHandler( } CustomHandlerPtr CustomHandlerDAOReadOnly::getContentHandler( - const DPL::String& content, - const DPL::String& url) + const DPL::String& content, + const DPL::String& url) { LogDebug("Getting content handler"); - Try{ + Try { CUSTOM_HANDLER_DB_SELECT(select, ContentHandlers); select->Where(And(Equals(m_pkgName), - And(Equals(content), - Equals(url)))); + And(Equals(content), + Equals(url)))); std::list list = select->GetRowList(); return getSingleHandler(list); @@ -109,10 +105,10 @@ CustomHandlerPtr CustomHandlerDAOReadOnly::getContentHandler( } CustomHandlerPtr CustomHandlerDAOReadOnly::getActivProtocolHandler( - const DPL::String& protocol) + const DPL::String& protocol) { LogDebug("Getting active protocol handler"); - Try{ + Try { CUSTOM_HANDLER_DB_SELECT(select, ProtocolHandlers); select->Where(And(Equals(m_pkgName), @@ -142,22 +138,22 @@ CustomHandlerPtr CustomHandlerDAOReadOnly::getActivProtocolHandler( } CustomHandlerPtr CustomHandlerDAOReadOnly::getProtocolHandler( - const DPL::String& protocol, - const DPL::String& url, - const DPL::String& baseURL) + const DPL::String& protocol, + const DPL::String& url, + const DPL::String& baseURL) { LogDebug("Check if protocol is registered"); - Try{ + 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); @@ -167,12 +163,11 @@ CustomHandlerPtr CustomHandlerDAOReadOnly::getProtocolHandler( } } - CustomHandlerPtr CustomHandlerDAOReadOnly::getActivContentHandler( - const DPL::String& content) + const DPL::String& content) { LogDebug("Getting active content handler"); - Try{ + Try { CUSTOM_HANDLER_DB_SELECT(select, ContentHandlers); select->Where(And(Equals(m_pkgName), @@ -202,18 +197,18 @@ CustomHandlerPtr CustomHandlerDAOReadOnly::getActivContentHandler( } CustomHandlerPtr CustomHandlerDAOReadOnly::getContentHandler( - const DPL::String& content, - const DPL::String& url, - const DPL::String& baseURL) + const DPL::String& content, + const DPL::String& url, + const DPL::String& baseURL) { LogDebug("Check if content is registered"); - Try{ + Try { CUSTOM_HANDLER_DB_SELECT(select, ContentHandlers); select->Where(And(Equals(m_pkgName), - And(Equals(content), - And(Equals(url), - Equals(baseURL))))); + And(Equals(content), + And(Equals(url), + Equals(baseURL))))); std::list list = select->GetRowList(); return getSingleHandler(list); @@ -224,15 +219,15 @@ CustomHandlerPtr CustomHandlerDAOReadOnly::getContentHandler( } CustomHandlerPtr CustomHandlerDAOReadOnly::getAllowedProtocolHandler( - const DPL::String& protocol) + const DPL::String& protocol) { LogDebug("Getting allowed protocol handler"); - Try{ + Try { CUSTOM_HANDLER_DB_SELECT(select, ProtocolHandlers); select->Where(And(Equals(m_pkgName), - And(Equals(protocol), - Equals(true)))); + And(Equals(protocol), + Equals(true)))); std::list list = select->GetRowList(); return getSingleHandler(list); @@ -243,15 +238,15 @@ CustomHandlerPtr CustomHandlerDAOReadOnly::getAllowedProtocolHandler( } CustomHandlerPtr CustomHandlerDAOReadOnly::getAllowedContentHandler( - const DPL::String& protocol) + const DPL::String& protocol) { LogDebug("Getting allowed content handler"); - Try{ + Try { CUSTOM_HANDLER_DB_SELECT(select, ContentHandlers) select->Where(And(Equals(m_pkgName), - And(Equals(protocol), - Equals(true)))); + And(Equals(protocol), + Equals(true)))); std::list list = select->GetRowList(); return getSingleHandler(list); @@ -260,5 +255,4 @@ CustomHandlerPtr CustomHandlerDAOReadOnly::getAllowedContentHandler( "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 index fea6309..4eabd55 100644 --- 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 @@ -23,44 +23,42 @@ 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; \ + static DPL::ThreadLocalVariable *tlsCommand##Ptr = NULL; \ { \ DPL::Mutex::ScopedLock lock( \ - &CustomHandlerDB::Interface::g_dbQueriesMutex); \ - if (!tlsCommand ## Ptr) { \ + &CustomHandlerDB::Interface::g_dbQueriesMutex); \ + if (!tlsCommand##Ptr) { \ static DPL::ThreadLocalVariable tmp; \ - tlsCommand ## Ptr = &tmp; \ + tlsCommand##Ptr = &tmp; \ } \ } \ - DPL::ThreadLocalVariable &tlsCommand = *tlsCommand ## Ptr; \ + 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) + CUSTOM_HANDLER_DB_INTERNAL(name, type::Select) #define CUSTOM_HANDLER_DB_INSERT(name, type) \ - CUSTOM_HANDLER_DB_INTERNAL(name, type::Insert) + CUSTOM_HANDLER_DB_INTERNAL(name, type::Insert) #define CUSTOM_HANDLER_DB_UPDATE(name, type) \ - CUSTOM_HANDLER_DB_INTERNAL(name, type::Update) + CUSTOM_HANDLER_DB_INTERNAL(name, type::Update) #define CUSTOM_HANDLER_DB_DELETE(name, type) \ - CUSTOM_HANDLER_DB_INTERNAL(name, type::Delete) + 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 index b08142a..c798cea 100644 --- 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 @@ -29,7 +29,6 @@ #include namespace CustomHandlerDB { - /** * @brief Custom Handler struct * @@ -40,7 +39,8 @@ enum HandlerState { //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 + //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, @@ -59,7 +59,6 @@ struct CustomHandler 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 index 88c720d..42a9936 100644 --- 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 @@ -30,7 +30,6 @@ #include "common_dao_types.h" namespace CustomHandlerDB { - class CustomHandlerDAOReadOnly { public: @@ -58,12 +57,11 @@ class CustomHandlerDAOReadOnly const DPL::String& baseURL); /** - * Returns protocol handler that is agreed or agreed and saved and match tizenID + * Returns protocol handler that is agreed or agreed and saved and match + * tizenID */ CustomHandlerPtr getActivProtocolHandler(const DPL::String& protocol); - - /** * Returns content handler */ @@ -74,7 +72,8 @@ class CustomHandlerDAOReadOnly const DPL::String& baseURL); /** - * Returns content handler that is agreed or agreed and saved and match tizenID + * Returns content handler that is agreed or agreed and saved and match + * tizenID */ CustomHandlerPtr getActivContentHandler(const DPL::String& content); @@ -91,7 +90,6 @@ class CustomHandlerDAOReadOnly 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 index 1ce61cf..9a478cb 100644 --- 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 @@ -27,7 +27,6 @@ #include namespace CustomHandlerDB { - class CustomHandlerDAO : public CustomHandlerDAOReadOnly { public: @@ -69,7 +68,6 @@ class CustomHandlerDAO : public CustomHandlerDAOReadOnly void removeWidgetProtocolHandlers(); void removeWidgetContentHandlers(); }; - } // namespace CustomHandlerDB #endif // _CUSTOM_HANDLER_DAO_H_ diff --git a/modules/db/include/dpl/db/naive_synchronization_object.h b/modules/db/include/dpl/db/naive_synchronization_object.h index 37d268c..2f63a0f 100644 --- a/modules/db/include/dpl/db/naive_synchronization_object.h +++ b/modules/db/include/dpl/db/naive_synchronization_object.h @@ -17,31 +17,28 @@ * @file naive_synchronization_object.h * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) * @version 1.0 - * @brief This file is the implementation file of SQL naive synchronization object + * @brief This file is the implementation file of SQL naive + * synchronization object */ #ifndef DPL_NAIVE_SYNCHRONIZATION_OBJECT_H #define DPL_NAIVE_SYNCHRONIZATION_OBJECT_H #include -namespace DPL -{ -namespace DB -{ - +namespace DPL { +namespace DB { /** * Naive synchronization object used to synchronize SQL connection * to the same database across different threads and processes */ -class NaiveSynchronizationObject - : public SqlConnection::SynchronizationObject +class NaiveSynchronizationObject : + public SqlConnection::SynchronizationObject { -public: + public: // [SqlConnection::SynchronizationObject] virtual void Synchronize(); virtual void NotifyAll(); }; - } // namespace DB } // namespace DPL diff --git a/modules/db/include/dpl/db/orm_interface.h b/modules/db/include/dpl/db/orm_interface.h index 74908fd..62ec073 100644 --- a/modules/db/include/dpl/db/orm_interface.h +++ b/modules/db/include/dpl/db/orm_interface.h @@ -25,25 +25,22 @@ #ifndef DPL_ORM_INTERFACE_H #define DPL_ORM_INTERFACE_H -namespace DPL -{ -namespace DB -{ -namespace ORM -{ - +namespace DPL { +namespace DB { +namespace ORM { class IOrmInterface { public: virtual ~IOrmInterface() {} - virtual DPL::DB::SqlConnection::DataCommand *AllocDataCommand(const std::string &statement) = 0; - virtual void FreeDataCommand(DPL::DB::SqlConnection::DataCommand *command) = 0; + virtual DPL::DB::SqlConnection::DataCommand *AllocDataCommand( + const std::string &statement) = 0; + virtual void FreeDataCommand(DPL::DB::SqlConnection::DataCommand *command) + = 0; virtual void TransactionBegin() = 0; virtual void TransactionCommit() = 0; virtual void TransactionRollback() = 0; virtual DPL::DB::SqlConnection::RowID GetLastInsertRowID() = 0; }; - } } } diff --git a/modules/db/include/dpl/db/orm_macros.h b/modules/db/include/dpl/db/orm_macros.h index c70a3b0..a038523 100644 --- a/modules/db/include/dpl/db/orm_macros.h +++ b/modules/db/include/dpl/db/orm_macros.h @@ -17,16 +17,17 @@ * @file orm_macros.h * @author Bartosz Janiak (b.janiak@samsung.com) * @version 1.0 - * @brief Macro definitions for generating the SQL input file from database definition. + * @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. -#define CREATE_TABLE(name) CREATE TABLE name ( -#define COLUMN(name, type, ...) name type __VA_ARGS__ , +#define CREATE_TABLE(name) CREATE TABLE name( +#define COLUMN(name, type, ...) name type __VA_ARGS__, #define COLUMN_NOT_NULL(name, type, ...) name type __VA_ARGS__ not null, #define SQL(...) __VA_ARGS__ -#define TABLE_CONSTRAINTS(...) __VA_ARGS__ , +#define TABLE_CONSTRAINTS(...) __VA_ARGS__, #define CREATE_TABLE_END() CHECK(1) ); #define DATABASE_START(db_name) #define DATABASE_END() diff --git a/modules/db/include/dpl/db/sql_connection.h b/modules/db/include/dpl/db/sql_connection.h index f1b3b62..5a3b0c1 100644 --- a/modules/db/include/dpl/db/sql_connection.h +++ b/modules/db/include/dpl/db/sql_connection.h @@ -34,23 +34,20 @@ #include #include -namespace DPL -{ -namespace DB -{ - +namespace DPL { +namespace DB { /** * SQL connection class */ class SqlConnection { -public: + public: /** * SQL Exception classes */ class Exception { - public: + public: DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) DECLARE_EXCEPTION_TYPE(Base, SyntaxError) DECLARE_EXCEPTION_TYPE(Base, ConnectionBroken) @@ -64,10 +61,10 @@ public: /* * SQL processed data command */ - class DataCommand - : private Noncopyable + class DataCommand : + private Noncopyable { - private: + private: SqlConnection *m_masterConnection; sqlite3_stmt *m_stmt; @@ -78,7 +75,7 @@ public: friend class SqlConnection; - public: + public: virtual ~DataCommand(); /** @@ -371,21 +368,22 @@ public: // Open flags class Flag { - public: + public: enum Type { - None = 1<<0, - UseLucene = 1<<1 + None = 1 << 0, + UseLucene = 1 << 1 }; enum Option { RO = SQLITE_OPEN_NOMUTEX | SQLITE_OPEN_READONLY, /** - *TODO: please remove CREATE option from RW flag when all places + * *TODO: please remove CREATE option from RW flag when all places * that need that switched do CRW */ - RW = SQLITE_OPEN_NOMUTEX | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, + RW = SQLITE_OPEN_NOMUTEX | SQLITE_OPEN_READWRITE | + SQLITE_OPEN_CREATE, CRW = RW | SQLITE_OPEN_CREATE }; }; @@ -399,7 +397,7 @@ public: */ class SynchronizationObject { - public: + public: virtual ~SynchronizationObject() {} /** @@ -413,7 +411,7 @@ public: virtual void NotifyAll() = 0; }; -protected: + protected: sqlite3 *m_connection; // Options @@ -433,7 +431,7 @@ protected: static SynchronizationObject *AllocDefaultSynchronizationObject(); -public: + public: /** * Open SQL connection * @@ -488,7 +486,6 @@ public: */ RowID GetLastInsertRowID() const; }; - } // namespace DB } // namespace DPL diff --git a/modules/db/include/dpl/db/thread_database_support.h b/modules/db/include/dpl/db/thread_database_support.h index d0e8cb2..52cfb33 100644 --- a/modules/db/include/dpl/db/thread_database_support.h +++ b/modules/db/include/dpl/db/thread_database_support.h @@ -30,11 +30,8 @@ #include #include -namespace DPL -{ -namespace DB -{ - +namespace DPL { +namespace DB { /** * Thread database support * @@ -142,16 +139,14 @@ class ThreadDatabaseSupport : DPL::DB::SqlConnection::Flag::Type flags) : m_address(address), m_flags(flags) - { - } + {} virtual ~ThreadDatabaseSupport() - { - } + {} void AttachToThread( - DPL::DB::SqlConnection::Flag::Option options = - DPL::DB::SqlConnection::Flag::RO) + DPL::DB::SqlConnection::Flag::Option options = + DPL::DB::SqlConnection::Flag::RO) { Linger() = false; @@ -164,7 +159,8 @@ class ThreadDatabaseSupport : // Initialize SQL connection described in traits LogInfo("Attaching thread database connection: " << m_address); - Connection() = new DPL::DB::SqlConnection(m_address.c_str(), m_flags, options); + Connection() = new DPL::DB::SqlConnection( + m_address.c_str(), m_flags, options); RefCounter() = 0; @@ -213,7 +209,7 @@ class ThreadDatabaseSupport : } DPL::DB::SqlConnection::DataCommand *AllocDataCommand( - const std::string &statement) + const std::string &statement) { // Calling thread must support thread database connections Assert(!Connection().IsNull()); @@ -298,7 +294,6 @@ class ThreadDatabaseSupport : return (*Connection())->CheckTableExist(name); } }; - } } diff --git a/modules/db/src/naive_synchronization_object.cpp b/modules/db/src/naive_synchronization_object.cpp index 9078f8a..0fbc386 100644 --- a/modules/db/src/naive_synchronization_object.cpp +++ b/modules/db/src/naive_synchronization_object.cpp @@ -17,17 +17,15 @@ * @file naive_synchronization_object.cpp * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) * @version 1.0 - * @brief This file is the implementation file of SQL naive synchronization object + * @brief This file is the implementation file of SQL naive + * synchronization object */ #include #include #include -namespace DPL -{ -namespace DB -{ - +namespace DPL { +namespace DB { void NaiveSynchronizationObject::Synchronize() { // Sleep for about 10ms - 30ms @@ -38,6 +36,5 @@ void NaiveSynchronizationObject::NotifyAll() { // No need to inform about anything } - } // namespace DB } // namespace DPL diff --git a/modules/db/src/orm.cpp b/modules/db/src/orm.cpp index acdbcca..c69415d 100644 --- a/modules/db/src/orm.cpp +++ b/modules/db/src/orm.cpp @@ -17,16 +17,15 @@ * @file orm.cpp * @author Bartosz Janiak (b.janiak@samsung.com) * @version 1.0 - * @brief Static definitions and function template specialziations of DPL-ORM. + * @brief Static definitions and function template specialziations of + * DPL-ORM. */ #include #include - namespace DPL { namespace DB { namespace ORM { - namespace RelationTypes { const char Equal[] = "="; const char LessThan[] = "<"; @@ -38,67 +37,66 @@ const char In[] = "IN"; template<> int GetColumnFromCommand(ColumnIndex columnIndex, - DataCommand *command) + DataCommand *command) { return command->GetColumnInteger(columnIndex); } template<> DPL::String GetColumnFromCommand(ColumnIndex columnIndex, - DataCommand *command) + DataCommand *command) { return DPL::FromUTF8String(command->GetColumnString(columnIndex)); } template<> OptionalInteger GetColumnFromCommand(ColumnIndex columnIndex, - DataCommand *command) + DataCommand *command) { return command->GetColumnOptionalInteger(columnIndex); } template<> OptionalString GetColumnFromCommand(ColumnIndex columnIndex, - DataCommand *command) + DataCommand *command) { return command->GetColumnOptionalString(columnIndex); } template<> double GetColumnFromCommand(ColumnIndex columnIndex, - DataCommand *command) + DataCommand *command) { return command->GetColumnDouble(columnIndex); } void DataCommandUtils::BindArgument(DataCommand *command, - ArgumentIndex index, - int argument) + ArgumentIndex index, + int argument) { command->BindInteger(index, argument); } void DataCommandUtils::BindArgument(DataCommand *command, - ArgumentIndex index, - const OptionalInteger& argument) + ArgumentIndex index, + const OptionalInteger& argument) { command->BindInteger(index, argument); } void DataCommandUtils::BindArgument(DataCommand *command, - ArgumentIndex index, - const DPL::String& argument) + ArgumentIndex index, + const DPL::String& argument) { command->BindString(index, argument); } void DataCommandUtils::BindArgument(DataCommand *command, - ArgumentIndex index, - const OptionalString& argument) + ArgumentIndex index, + const OptionalString& argument) { command->BindString(index, argument); } - } } } diff --git a/modules/db/src/sql_connection.cpp b/modules/db/src/sql_connection.cpp index d1b44dd..dab6116 100644 --- a/modules/db/src/sql_connection.cpp +++ b/modules/db/src/sql_connection.cpp @@ -30,30 +30,27 @@ #include #include -namespace DPL -{ -namespace DB -{ - +namespace DPL { +namespace DB { namespace // anonymous { -class ScopedNotifyAll - : public Noncopyable +class ScopedNotifyAll : + public Noncopyable { -private: + private: SqlConnection::SynchronizationObject *m_synchronizationObject; -public: + public: explicit ScopedNotifyAll( - SqlConnection::SynchronizationObject *synchronizationObject) - : m_synchronizationObject(synchronizationObject) - { - } + SqlConnection::SynchronizationObject *synchronizationObject) : + m_synchronizationObject(synchronizationObject) + {} ~ScopedNotifyAll() { - if (!m_synchronizationObject) + if (!m_synchronizationObject) { return; + } LogPedantic("Notifying after successful synchronize"); m_synchronizationObject->NotifyAll(); @@ -62,33 +59,28 @@ public: } // namespace anonymous SqlConnection::DataCommand::DataCommand(SqlConnection *connection, - const char *buffer) - : m_masterConnection(connection), - m_stmt(NULL) + const char *buffer) : + m_masterConnection(connection), + m_stmt(NULL) { Assert(connection != NULL); // Notify all after potentially synchronized database connection access ScopedNotifyAll notifyAll(connection->m_synchronizationObject.get()); - for (;;) - { + for (;;) { int ret = sqlite3_prepare_v2(connection->m_connection, buffer, strlen(buffer), &m_stmt, NULL); - if (ret == SQLITE_OK) - { + if (ret == SQLITE_OK) { LogPedantic("Data command prepared successfuly"); break; - } - else if (ret == SQLITE_BUSY) - { + } else if (ret == SQLITE_BUSY) { LogPedantic("Collision occurred while preparing SQL command"); // Synchronize if synchronization object is available - if (connection->m_synchronizationObject) - { + if (connection->m_synchronizationObject) { LogPedantic("Performing synchronization"); connection->m_synchronizationObject->Synchronize(); continue; @@ -117,8 +109,9 @@ SqlConnection::DataCommand::~DataCommand() { LogPedantic("SQL data command finalizing"); - if (sqlite3_finalize(m_stmt) != SQLITE_OK) + if (sqlite3_finalize(m_stmt) != SQLITE_OK) { LogPedantic("Failed to finalize data command"); + } // Decrement stored data command count --m_masterConnection->m_dataCommandsCount; @@ -126,10 +119,9 @@ SqlConnection::DataCommand::~DataCommand() void SqlConnection::DataCommand::CheckBindResult(int result) { - if (result != SQLITE_OK) - { + if (result != SQLITE_OK) { const char *error = sqlite3_errmsg( - m_masterConnection->m_connection); + m_masterConnection->m_connection); LogPedantic("Failed to bind SQL statement parameter"); LogPedantic(" Error: " << error); @@ -218,8 +210,7 @@ void SqlConnection::DataCommand::BindString( SqlConnection::ArgumentIndex position, const char *value) { - if (!value) - { + if (!value) { BindNull(position); return; } @@ -244,80 +235,88 @@ void SqlConnection::DataCommand::BindInteger( SqlConnection::ArgumentIndex position, const Optional &value) { - if (value.IsNull()) + if (value.IsNull()) { BindNull(position); - else + } else { BindInteger(position, *value); + } } void SqlConnection::DataCommand::BindInt8( SqlConnection::ArgumentIndex position, const Optional &value) { - if (value.IsNull()) + if (value.IsNull()) { BindNull(position); - else + } else { BindInt8(position, *value); + } } void SqlConnection::DataCommand::BindInt16( SqlConnection::ArgumentIndex position, const Optional &value) { - if (value.IsNull()) + if (value.IsNull()) { BindNull(position); - else + } else { BindInt16(position, *value); + } } void SqlConnection::DataCommand::BindInt32( SqlConnection::ArgumentIndex position, const Optional &value) { - if (value.IsNull()) + if (value.IsNull()) { BindNull(position); - else + } else { BindInt32(position, *value); + } } void SqlConnection::DataCommand::BindInt64( SqlConnection::ArgumentIndex position, const Optional &value) { - if (value.IsNull()) + if (value.IsNull()) { BindNull(position); - else + } else { BindInt64(position, *value); + } } void SqlConnection::DataCommand::BindFloat( SqlConnection::ArgumentIndex position, const Optional &value) { - if (value.IsNull()) + if (value.IsNull()) { BindNull(position); - else + } else { BindFloat(position, *value); + } } void SqlConnection::DataCommand::BindDouble( SqlConnection::ArgumentIndex position, const Optional &value) { - if (value.IsNull()) + if (value.IsNull()) { BindNull(position); - else + } else { BindDouble(position, *value); + } } void SqlConnection::DataCommand::BindString( SqlConnection::ArgumentIndex position, const Optional &value) { - if (!!value) + if (!!value) { BindString(position, ToUTF8String(*value).c_str()); - else + } else { BindNull(position); + } } bool SqlConnection::DataCommand::Step() @@ -326,27 +325,20 @@ bool SqlConnection::DataCommand::Step() ScopedNotifyAll notifyAll( m_masterConnection->m_synchronizationObject.get()); - for (;;) - { + for (;;) { int ret = sqlite3_step(m_stmt); - if (ret == SQLITE_ROW) - { + if (ret == SQLITE_ROW) { LogPedantic("SQL data command step ROW"); return true; - } - else if (ret == SQLITE_DONE) - { + } else if (ret == SQLITE_DONE) { LogPedantic("SQL data command step DONE"); return false; - } - else if (ret == SQLITE_BUSY) - { + } else if (ret == SQLITE_BUSY) { LogPedantic("Collision occurred while executing SQL command"); // Synchronize if synchronization object is available - if (m_masterConnection->m_synchronizationObject) - { + if (m_masterConnection->m_synchronizationObject) { LogPedantic("Performing synchronization"); m_masterConnection-> @@ -386,8 +378,9 @@ void SqlConnection::DataCommand::Reset() void SqlConnection::DataCommand::CheckColumnIndex( SqlConnection::ColumnIndex column) { - if (column < 0 || column >= sqlite3_column_count(m_stmt)) + if (column < 0 || column >= sqlite3_column_count(m_stmt)) { ThrowMsg(Exception::InvalidColumn, "Column index is out of bounds"); + } } bool SqlConnection::DataCommand::IsColumnNull( @@ -475,12 +468,13 @@ std::string SqlConnection::DataCommand::GetColumnString( CheckColumnIndex(column); const char *value = reinterpret_cast( - sqlite3_column_text(m_stmt, column)); + sqlite3_column_text(m_stmt, column)); LogPedantic("Value: " << (value ? value : "NULL")); - if (value == NULL) + if (value == NULL) { return std::string(); + } return std::string(value); } @@ -491,8 +485,9 @@ Optional SqlConnection::DataCommand::GetColumnOptionalInteger( LogPedantic("SQL data command get column optional integer: [" << column << "]"); CheckColumnIndex(column); - if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) + if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) { return Optional::Null; + } int value = sqlite3_column_int(m_stmt, column); LogPedantic(" Value: " << value); return Optional(value); @@ -504,8 +499,9 @@ Optional SqlConnection::DataCommand::GetColumnOptionalInt8( LogPedantic("SQL data command get column optional int8: [" << column << "]"); CheckColumnIndex(column); - if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) + if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) { return Optional::Null; + } int8_t value = static_cast(sqlite3_column_int(m_stmt, column)); LogPedantic(" Value: " << value); return Optional(value); @@ -517,8 +513,9 @@ Optional SqlConnection::DataCommand::GetColumnOptionalInt16( LogPedantic("SQL data command get column optional int16: [" << column << "]"); CheckColumnIndex(column); - if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) + if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) { return Optional::Null; + } int16_t value = static_cast(sqlite3_column_int(m_stmt, column)); LogPedantic(" Value: " << value); return Optional(value); @@ -530,8 +527,9 @@ Optional SqlConnection::DataCommand::GetColumnOptionalInt32( LogPedantic("SQL data command get column optional int32: [" << column << "]"); CheckColumnIndex(column); - if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) + if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) { return Optional::Null; + } int32_t value = static_cast(sqlite3_column_int(m_stmt, column)); LogPedantic(" Value: " << value); return Optional(value); @@ -543,8 +541,9 @@ Optional SqlConnection::DataCommand::GetColumnOptionalInt64( LogPedantic("SQL data command get column optional int64: [" << column << "]"); CheckColumnIndex(column); - if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) + if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) { return Optional::Null; + } int64_t value = static_cast(sqlite3_column_int64(m_stmt, column)); LogPedantic(" Value: " << value); return Optional(value); @@ -556,8 +555,9 @@ Optional SqlConnection::DataCommand::GetColumnOptionalFloat( LogPedantic("SQL data command get column optional float: [" << column << "]"); CheckColumnIndex(column); - if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) + if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) { return Optional::Null; + } float value = static_cast(sqlite3_column_double(m_stmt, column)); LogPedantic(" Value: " << value); return Optional(value); @@ -569,8 +569,9 @@ Optional SqlConnection::DataCommand::GetColumnOptionalDouble( LogPedantic("SQL data command get column optional double: [" << column << "]"); CheckColumnIndex(column); - if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) + if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) { return Optional::Null; + } double value = sqlite3_column_double(m_stmt, column); LogPedantic(" Value: " << value); return Optional(value); @@ -582,18 +583,19 @@ Optional SqlConnection::DataCommand::GetColumnOptionalString( LogPedantic("SQL data command get column optional string: [" << column << "]"); CheckColumnIndex(column); - if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) + if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) { return Optional::Null; + } const char *value = reinterpret_cast( - sqlite3_column_text(m_stmt, column)); + sqlite3_column_text(m_stmt, column)); LogPedantic("Value: " << value); String s = FromUTF8String(value); return Optional(s); } void SqlConnection::Connect(const std::string &address, - Flag::Type type, - Flag::Option flag) + Flag::Type type, + Flag::Option flag) { if (m_connection != NULL) { LogPedantic("Already connected."); @@ -605,19 +607,19 @@ void SqlConnection::Connect(const std::string &address, int result; if (type & Flag::UseLucene) { result = db_util_open_with_options( - address.c_str(), - &m_connection, - flag, - NULL); + address.c_str(), + &m_connection, + flag, + NULL); m_usingLucene = true; LogPedantic("Lucene index enabled"); } else { result = sqlite3_open_v2( - address.c_str(), - &m_connection, - flag, - NULL); + address.c_str(), + &m_connection, + flag, + NULL); m_usingLucene = false; LogPedantic("Lucene index disabled"); @@ -636,8 +638,7 @@ void SqlConnection::Connect(const std::string &address, void SqlConnection::Disconnect() { - if (m_connection == NULL) - { + if (m_connection == NULL) { LogPedantic("Already disconnected."); return; } @@ -651,17 +652,13 @@ void SqlConnection::Disconnect() int result; - if (m_usingLucene) - { + if (m_usingLucene) { result = db_util_close(m_connection); - } - else - { + } else { result = sqlite3_close(m_connection); } - if (result != SQLITE_OK) - { + if (result != SQLITE_OK) { const char *error = sqlite3_errmsg(m_connection); LogPedantic("SQL close failed"); LogPedantic(" Error: " << error); @@ -675,8 +672,7 @@ void SqlConnection::Disconnect() bool SqlConnection::CheckTableExist(const char *tableName) { - if (m_connection == NULL) - { + if (m_connection == NULL) { LogPedantic("Cannot execute command. Not connected to DB!"); return false; } @@ -686,8 +682,7 @@ bool SqlConnection::CheckTableExist(const char *tableName) command->BindString(1, tableName); - if (!command->Step()) - { + if (!command->Step()) { LogPedantic("No matching records in table"); return false; } @@ -698,19 +693,18 @@ bool SqlConnection::CheckTableExist(const char *tableName) SqlConnection::SqlConnection(const std::string &address, Flag::Type flag, Flag::Option option, - SynchronizationObject *synchronizationObject) - : m_connection(NULL), - m_usingLucene(false), - m_dataCommandsCount(0), - m_synchronizationObject(synchronizationObject) + SynchronizationObject *synchronizationObject) : + m_connection(NULL), + m_usingLucene(false), + m_dataCommandsCount(0), + m_synchronizationObject(synchronizationObject) { LogPedantic("Opening database connection to: " << address); // Connect to DB SqlConnection::Connect(address, flag, option); - if (!m_synchronizationObject) - { + if (!m_synchronizationObject) { LogPedantic("No synchronization object defined"); } } @@ -724,7 +718,7 @@ SqlConnection::~SqlConnection() { SqlConnection::Disconnect(); } - Catch (Exception::Base) + Catch(Exception::Base) { LogPedantic("Failed to disconnect from database"); } @@ -732,14 +726,12 @@ SqlConnection::~SqlConnection() void SqlConnection::ExecCommand(const char *format, ...) { - if (m_connection == NULL) - { + if (m_connection == NULL) { LogPedantic("Cannot execute command. Not connected to DB!"); return; } - if (format == NULL) - { + if (format == NULL) { LogPedantic("Null query!"); ThrowMsg(Exception::SyntaxError, "Null statement"); } @@ -749,15 +741,15 @@ void SqlConnection::ExecCommand(const char *format, ...) va_list args; va_start(args, format); - if (vasprintf(&rawBuffer, format, args) == -1) + if (vasprintf(&rawBuffer, format, args) == -1) { rawBuffer = NULL; + } va_end(args); ScopedFree buffer(rawBuffer); - if (!buffer) - { + if (!buffer) { LogPedantic("Failed to allocate statement string"); return; } @@ -767,8 +759,7 @@ void SqlConnection::ExecCommand(const char *format, ...) // Notify all after potentially synchronized database connection access ScopedNotifyAll notifyAll(m_synchronizationObject.get()); - for (;;) - { + for (;;) { char *errorBuffer; int ret = sqlite3_exec(m_connection, @@ -780,22 +771,20 @@ void SqlConnection::ExecCommand(const char *format, ...) std::string errorMsg; // Take allocated error buffer - if (errorBuffer != NULL) - { + if (errorBuffer != NULL) { errorMsg = errorBuffer; sqlite3_free(errorBuffer); } - if (ret == SQLITE_OK) + if (ret == SQLITE_OK) { return; + } - if (ret == SQLITE_BUSY) - { + if (ret == SQLITE_BUSY) { LogPedantic("Collision occurred while executing SQL command"); // Synchronize if synchronization object is available - if (m_synchronizationObject) - { + if (m_synchronizationObject) { LogPedantic("Performing synchronization"); m_synchronizationObject->Synchronize(); continue; @@ -814,8 +803,7 @@ SqlConnection::DataCommandAutoPtr SqlConnection::PrepareDataCommand( const char *format, ...) { - if (m_connection == NULL) - { + if (m_connection == NULL) { LogPedantic("Cannot execute data command. Not connected to DB!"); return DataCommandAutoPtr(); } @@ -825,15 +813,15 @@ SqlConnection::DataCommandAutoPtr SqlConnection::PrepareDataCommand( va_list args; va_start(args, format); - if (vasprintf(&rawBuffer, format, args) == -1) + if (vasprintf(&rawBuffer, format, args) == -1) { rawBuffer = NULL; + } va_end(args); ScopedFree buffer(rawBuffer); - if (!buffer) - { + if (!buffer) { LogPedantic("Failed to allocate statement string"); return DataCommandAutoPtr(); } @@ -854,10 +842,9 @@ void SqlConnection::TurnOnForeignKeys() } SqlConnection::SynchronizationObject * - SqlConnection::AllocDefaultSynchronizationObject() +SqlConnection::AllocDefaultSynchronizationObject() { return new NaiveSynchronizationObject(); } - } // namespace DB } // namespace DPL diff --git a/modules/dbus/include/dpl/dbus/connection.h b/modules/dbus/include/dpl/dbus/connection.h index 49e8197..92a8ad3 100644 --- a/modules/dbus/include/dpl/dbus/connection.h +++ b/modules/dbus/include/dpl/dbus/connection.h @@ -34,9 +34,7 @@ namespace DPL { namespace DBus { - -namespace ConnectionEvents -{ +namespace ConnectionEvents { /** * Emitted when service name is acquired. * @@ -74,12 +72,12 @@ typedef std::shared_ptr ConnectionPtr; typedef std::shared_ptr ObjectProxyPtr; class Connection : - public DPL::Event::EventSupport, - public DPL::Event::EventSupport, - public DPL::Event::EventSupport, - public DPL::Event::EventSupport + public DPL::Event::EventSupport, + public DPL::Event::EventSupport, + public DPL::Event::EventSupport, + public DPL::Event::EventSupport { -public: + public: /** * Acquires connection to session bus. * @@ -165,18 +163,17 @@ public: ObjectProxyPtr createObjectProxy(const std::string& serviceName, const std::string& objectPath); -private: + private: friend class Server; typedef std::map RegisteredServices; struct ObjectRegistration { - ObjectRegistration(guint _registrationId, const ObjectPtr& _object) - : registrationId(_registrationId), - object(_object) - { - } + ObjectRegistration(guint _registrationId, const ObjectPtr& _object) : + registrationId(_registrationId), + object(_object) + {} guint registrationId; ObjectPtr object; @@ -204,7 +201,6 @@ private: RegisteredObjects m_registeredObjects; }; - } } diff --git a/modules/dbus/include/dpl/dbus/dbus_client.h b/modules/dbus/include/dpl/dbus/dbus_client.h index 6b86c57..061ec46 100644 --- a/modules/dbus/include/dpl/dbus/dbus_client.h +++ b/modules/dbus/include/dpl/dbus/dbus_client.h @@ -32,7 +32,6 @@ namespace DPL { namespace DBus { - /* * DBus::Client class is intended to act as simple DBus client. To call a method * on remote service "Service", on remote object "Object", interface @@ -58,7 +57,6 @@ namespace DBus { class Client { - public: class Exception { @@ -70,9 +68,9 @@ class Client Client(std::string serverPath, std::string serviceName, std::string interfaceName) : - m_serviceName(serviceName), - m_serverPath(serverPath), - m_interfaceName(interfaceName) + m_serviceName(serviceName), + m_serverPath(serverPath), + m_interfaceName(interfaceName) { DBusError error; @@ -80,15 +78,15 @@ class Client m_connection = dbus_bus_get(DBUS_BUS_SYSTEM, &error); if (NULL == m_connection) { LogPedantic("Couldn't get DBUS connection. Error: " << - error.message); + error.message); dbus_error_free(&error); ThrowMsg(Exception::DBusClientException, - "Couldn't get DBUS connection." ); + "Couldn't get DBUS connection."); } } - template - void call(const char* methodName, const Args&... args) + template + void call(const char* methodName, const Args& ... args) { DBusMessage* message = dbus_message_new_method_call( m_serviceName.c_str(), @@ -97,14 +95,14 @@ class Client methodName); DBusMessageIter argsIterator; dbus_message_iter_init_append(message, &argsIterator); - call(message, &argsIterator, args...); + call(message, &argsIterator, args ...); dbus_message_unref(message); } - template - void call(std::string methodName, const Args&... args) + template + void call(std::string methodName, const Args& ... args) { - call(methodName.c_str(), args...); + call(methodName.c_str(), args ...); } ~Client() @@ -115,7 +113,7 @@ class Client private: DBusMessage* makeCall( - DBusMessage* message) + DBusMessage* message) { DBusError error; dbus_error_init(&error); @@ -126,10 +124,10 @@ class Client &error); if (NULL == ret) { LogPedantic("Error sending DBUS message: " << - error.message); + error.message); dbus_error_free(&error); ThrowMsg(Exception::DBusClientException, - "Error sending DBUS message." ); + "Error sending DBUS message."); } return ret; } @@ -142,98 +140,97 @@ class Client } else { LogPedantic("Error getting DBUS response."); ThrowMsg(Exception::DBusClientException, - "Error getting DBUS response." ); + "Error getting DBUS response."); } } template void call( - DBusMessage* message, - DBusMessageIter* argsIterator, - const T& invalue, - const Args&... args) + DBusMessage* message, + DBusMessageIter* argsIterator, + const T& invalue, + const Args& ... args) { - if (!Serialization::serialize(argsIterator, invalue)){ + if (!Serialization::serialize(argsIterator, invalue)) { LogPedantic("Error in serialization."); ThrowMsg(Exception::DBusClientException, - "Error in serialization." ); + "Error in serialization."); } - call(message, argsIterator, args...); + call(message, argsIterator, args ...); } template void call( - DBusMessage* message, - DBusMessageIter* argsIterator, - const T* invalue, - const Args&... args) + DBusMessage* message, + DBusMessageIter* argsIterator, + const T* invalue, + const Args& ... args) { - if (!Serialization::serialize(argsIterator, invalue)){ + if (!Serialization::serialize(argsIterator, invalue)) { LogPedantic("Error in serialization."); ThrowMsg(Exception::DBusClientException, - "Error in serialization." ); + "Error in serialization."); } - call(message, argsIterator, args...); + call(message, argsIterator, args ...); } template void call( - DBusMessage* message, - DBusMessageIter* argsIterator, - const T* invalue) + DBusMessage* message, + DBusMessageIter* argsIterator, + const T* invalue) { - if (!Serialization::serialize(argsIterator, invalue)){ + if (!Serialization::serialize(argsIterator, invalue)) { LogPedantic("Error in serialization."); ThrowMsg(Exception::DBusClientException, - "Error in serialization." ); + "Error in serialization."); } call(message, argsIterator); } template void call( - DBusMessage* message, - DBusMessageIter* /*argsIterator*/, - T* out, - const Args&... args) + DBusMessage* message, + DBusMessageIter* /*argsIterator*/, + T* out, + const Args& ... args) { DBusMessage* ret = makeCall(message); if (ret != NULL) { DBusMessageIter responseIterator; dbus_message_iter_init(ret, &responseIterator); - returnFromCall(&responseIterator, out, args...); + returnFromCall(&responseIterator, out, args ...); dbus_message_unref(ret); } } template void returnFromCall( - DBusMessageIter* responseIterator, - T* out, - const Args&... args) + DBusMessageIter* responseIterator, + T* out, + const Args& ... args) { - if (!Deserialization::deserialize(responseIterator, out)){ + if (!Deserialization::deserialize(responseIterator, out)) { LogPedantic("Error in deserialization."); ThrowMsg(Exception::DBusClientException, - "Error in deserialization." ); + "Error in deserialization."); } - returnFromCall(responseIterator, args...); + returnFromCall(responseIterator, args ...); } template void returnFromCall(DBusMessageIter* responseIterator, T* out) { - if (!Deserialization::deserialize(responseIterator, out)){ + if (!Deserialization::deserialize(responseIterator, out)) { LogPedantic("Error in deserialization."); ThrowMsg(Exception::DBusClientException, - "Error in deserialization." ); + "Error in deserialization."); } } std::string m_serviceName, m_serverPath, m_interfaceName; DBusConnection* m_connection; }; - } // namespace DBus } // namespace DPL diff --git a/modules/dbus/include/dpl/dbus/dbus_deserialization.h b/modules/dbus/include/dpl/dbus/dbus_deserialization.h index 9f50f91..2a05db8 100644 --- a/modules/dbus/include/dpl/dbus/dbus_deserialization.h +++ b/modules/dbus/include/dpl/dbus/dbus_deserialization.h @@ -33,14 +33,12 @@ namespace DPL { namespace DBus { - struct Deserialization { - static bool deserializePrimitive( - DBusMessageIter* responseIterator, - void* arg, - int type) + DBusMessageIter* responseIterator, + void* arg, + int type) { if (dbus_message_iter_get_arg_type(responseIterator) != type) { return false; @@ -54,7 +52,8 @@ struct Deserialization static bool deserialize(DBusMessageIter* responseIterator, T* arg) { if (dbus_message_iter_get_arg_type(responseIterator) - != SimpleType::value) { + != SimpleType::value) + { return false; } dbus_message_iter_get_basic(responseIterator, arg); @@ -65,7 +64,7 @@ struct Deserialization static bool deserialize(DBusMessageIter* responseIterator, float* arg) { double d; - if (!deserialize(responseIterator, &d)){ + if (!deserialize(responseIterator, &d)) { return false; } *arg = static_cast(d); @@ -74,11 +73,11 @@ struct Deserialization // std::string static bool deserialize( - DBusMessageIter* responseIterator, - std::string* arg) + DBusMessageIter* responseIterator, + std::string* arg) { char* str = NULL; - if (!deserialize(responseIterator, &str)){ + if (!deserialize(responseIterator, &str)) { return false; } *arg = std::string(str); @@ -88,19 +87,21 @@ struct Deserialization // dbus array deserialization template static bool deserializeContainer( - DBusMessageIter* responseIterator, - T* arg) + DBusMessageIter* responseIterator, + T* arg) { if (dbus_message_iter_get_arg_type(responseIterator) - != DBUS_TYPE_ARRAY) { + != DBUS_TYPE_ARRAY) + { return false; } DBusMessageIter subIterator; dbus_message_iter_recurse(responseIterator, &subIterator); while (dbus_message_iter_get_arg_type(&subIterator) - != DBUS_TYPE_INVALID) { + != DBUS_TYPE_INVALID) + { arg->push_back(typename T::value_type()); - if (!deserialize(&subIterator, &arg->back())){ + if (!deserialize(&subIterator, &arg->back())) { return false; } dbus_message_iter_next(&subIterator); @@ -111,8 +112,8 @@ struct Deserialization // std::vector template static bool deserialize( - DBusMessageIter* responseIterator, - std::vector* arg) + DBusMessageIter* responseIterator, + std::vector* arg) { return deserializeContainer(responseIterator, arg); } @@ -120,8 +121,8 @@ struct Deserialization // std::list template static bool deserialize( - DBusMessageIter* responseIterator, - std::list* arg) + DBusMessageIter* responseIterator, + std::list* arg) { return deserializeContainer(responseIterator, arg); } @@ -129,19 +130,21 @@ struct Deserialization // std::set template static bool deserialize( - DBusMessageIter* responseIterator, - std::set* arg) + DBusMessageIter* responseIterator, + std::set* arg) { if (dbus_message_iter_get_arg_type(responseIterator) - != DBUS_TYPE_ARRAY) { + != DBUS_TYPE_ARRAY) + { return false; } DBusMessageIter subIterator; dbus_message_iter_recurse(responseIterator, &subIterator); while (dbus_message_iter_get_arg_type(&subIterator) - != DBUS_TYPE_INVALID) { + != DBUS_TYPE_INVALID) + { typename std::set::value_type element; - if (!deserialize(&subIterator, &element)){ + if (!deserialize(&subIterator, &element)) { return false; } arg->insert(element); @@ -153,20 +156,21 @@ struct Deserialization // std::pair template static bool deserialize( - DBusMessageIter* argsIterator, - const std::pair* arg) + DBusMessageIter* argsIterator, + const std::pair* arg) { if (dbus_message_iter_get_arg_type(argsIterator) - != DBUS_TYPE_DICT_ENTRY) { + != DBUS_TYPE_DICT_ENTRY) + { return false; } DBusMessageIter dictEntryIterator; dbus_message_iter_recurse(argsIterator, &dictEntryIterator); - if (!deserialize(dictEntryIterator, &arg->first)){ + if (!deserialize(dictEntryIterator, &arg->first)) { return false; } dbus_message_iter_next(&dictEntryIterator); - if (!deserialize(dictEntryIterator, &arg->second)){ + if (!deserialize(dictEntryIterator, &arg->second)) { return false; } return true; @@ -175,19 +179,21 @@ struct Deserialization // std::map template static bool deserialize( - DBusMessageIter* responseIterator, - const std::map* arg) + DBusMessageIter* responseIterator, + const std::map* arg) { if (dbus_message_iter_get_arg_type(responseIterator) - != DBUS_TYPE_ARRAY) { + != DBUS_TYPE_ARRAY) + { return false; } DBusMessageIter subIterator; dbus_message_iter_recurse(responseIterator, &subIterator); while (dbus_message_iter_get_arg_type(&subIterator) - != DBUS_TYPE_INVALID) { + != DBUS_TYPE_INVALID) + { typename std::pair element; - if (!deserialize(&subIterator, &element)){ + if (!deserialize(&subIterator, &element)) { return false; } arg->insert(element); @@ -195,7 +201,6 @@ struct Deserialization } return true; } - }; template<> @@ -205,14 +210,14 @@ inline bool Deserialization::deserialize( { unsigned int value; if (dbus_message_iter_get_arg_type(responseIterator) - != SimpleType::value) { + != SimpleType::value) + { return false; } dbus_message_iter_get_basic(responseIterator, &value); *arg = static_cast(value); return true; } - } // namespace DBus } // namespace DPL diff --git a/modules/dbus/include/dpl/dbus/dbus_interface_dispatcher.h b/modules/dbus/include/dpl/dbus/dbus_interface_dispatcher.h index d5e3591..ec1b06b 100644 --- a/modules/dbus/include/dpl/dbus/dbus_interface_dispatcher.h +++ b/modules/dbus/include/dpl/dbus/dbus_interface_dispatcher.h @@ -30,14 +30,12 @@ namespace DPL { namespace DBus { - class InterfaceDispatcher : public DBus::Dispatcher { -public: - explicit InterfaceDispatcher(const std::string& interfaceName): + public: + explicit InterfaceDispatcher(const std::string& interfaceName) : m_interfaceName(interfaceName) - { - } + {} virtual ~InterfaceDispatcher() {} @@ -69,11 +67,11 @@ public: GVariant* parameters, GDBusMethodInvocation* invocation) { - if (g_strcmp0(interfaceName, m_interfaceName.c_str()) == 0){ + if (g_strcmp0(interfaceName, m_interfaceName.c_str()) == 0) { onMethodCall(methodName, parameters, invocation); } else { LogPedantic("Called invalid interface: " << interfaceName << - " instead of: " << m_interfaceName); + " instead of: " << m_interfaceName); } } @@ -97,10 +95,10 @@ public: LogInfo("InterfaceDispatcher onPropertySet: " << propertyName); return false; } -private: - std::string m_interfaceName, m_xml; -}; + private: + std::string m_interfaceName, m_xml; +}; } // namespace DBus } // namespace DPL diff --git a/modules/dbus/include/dpl/dbus/dbus_serialization.h b/modules/dbus/include/dpl/dbus/dbus_serialization.h index 7bfa65b..c0fa338 100644 --- a/modules/dbus/include/dpl/dbus/dbus_serialization.h +++ b/modules/dbus/include/dpl/dbus/dbus_serialization.h @@ -34,14 +34,12 @@ namespace DPL { namespace DBus { - struct Serialization { - // std::string static bool serialize( - DBusMessageIter* argsIterator, - const std::string& str) + DBusMessageIter* argsIterator, + const std::string& str) { return serialize(argsIterator, str.c_str()); } @@ -65,17 +63,19 @@ struct Serialization // dbus array serialization template static bool serializeContainer( - DBusMessageIter* argsIterator, - const T& arg) + DBusMessageIter* argsIterator, + const T& arg) { typename T::const_iterator containerIt; DBusMessageIter subIterator; if (!dbus_message_iter_open_container(argsIterator, DBUS_TYPE_ARRAY, - Signature::value(), &subIterator)) { + Signature + ::value(), &subIterator)) + { return false; } - FOREACH(containerIt,arg) { - if (!serialize(&subIterator, *containerIt)){ + FOREACH(containerIt, arg) { + if (!serialize(&subIterator, *containerIt)) { return false; } } @@ -85,8 +85,8 @@ struct Serialization // std::vector template static bool serialize( - DBusMessageIter* argsIterator, - const std::vector &arg) + DBusMessageIter* argsIterator, + const std::vector &arg) { return serializeContainer(argsIterator, arg); } @@ -94,8 +94,8 @@ struct Serialization // std::list template static bool serialize( - DBusMessageIter* argsIterator, - const std::list &arg) + DBusMessageIter* argsIterator, + const std::list &arg) { return serializeContainer(argsIterator, arg); } @@ -103,8 +103,8 @@ struct Serialization // std::set template static bool serialize( - DBusMessageIter* argsIterator, - const std::set &arg) + DBusMessageIter* argsIterator, + const std::set &arg) { return serializeContainer(argsIterator, arg); } @@ -112,18 +112,20 @@ struct Serialization // std::pair template static bool serialize( - DBusMessageIter* argsIterator, - const std::pair &arg) + DBusMessageIter* argsIterator, + const std::pair &arg) { DBusMessageIter dictEntryIterator; if (!dbus_message_iter_open_container(argsIterator, - DBUS_TYPE_DICT_ENTRY, NULL, &dictEntryIterator)) { + DBUS_TYPE_DICT_ENTRY, NULL, + &dictEntryIterator)) + { return false; } - if (!serialize(dictEntryIterator, arg.first)){ + if (!serialize(dictEntryIterator, arg.first)) { return false; } - if (!serialize(dictEntryIterator, arg.second)){ + if (!serialize(dictEntryIterator, arg.second)) { return false; } return dbus_message_iter_close_container(argsIterator, @@ -133,12 +135,11 @@ struct Serialization // std::map template static bool serialize( - DBusMessageIter* argsIterator, - const std::map &arg) + DBusMessageIter* argsIterator, + const std::map &arg) { return serializeContainer(argsIterator, arg); } - }; // char* and all integer types + doubles @@ -151,7 +152,6 @@ inline bool Serialization::serialize(DBusMessageIter* argsIterator, SimpleType::value, &value); } - } // namespace DBus } // namespace DPL diff --git a/modules/dbus/include/dpl/dbus/dbus_server_deserialization.h b/modules/dbus/include/dpl/dbus/dbus_server_deserialization.h index 5f3b28b..eb09d6d 100644 --- a/modules/dbus/include/dpl/dbus/dbus_server_deserialization.h +++ b/modules/dbus/include/dpl/dbus/dbus_server_deserialization.h @@ -32,11 +32,9 @@ namespace DPL { namespace DBus { - struct ServerDeserialization { - - template - static bool deserialize(GVariant* g, T* arg1, Args... args) + template + static bool deserialize(GVariant* g, T* arg1, Args ... args) { Assert(NULL != g); Assert(NULL != arg1); @@ -48,7 +46,7 @@ struct ServerDeserialization { g_variant_iter_free(iterator); return false; } - if (!deserializeIterator(iterator, args...)) { + if (!deserializeIterator(iterator, args ...)) { g_variant_iter_free(iterator); return false; } @@ -74,8 +72,8 @@ struct ServerDeserialization { } // deserialization from GVariant tuple iterator - template - static bool deserializeIterator(GVariantIter* g, T* arg1, Args... args) + template + static bool deserializeIterator(GVariantIter* g, T* arg1, Args ... args) { Assert(NULL != g); Assert(NULL != arg1); @@ -86,7 +84,7 @@ struct ServerDeserialization { if (!deserializeElem(elem, arg1)) { return false; } - if (!deserializeIterator(g, args...)) { + if (!deserializeIterator(g, args ...)) { return false; } return true; @@ -145,7 +143,7 @@ struct ServerDeserialization { } static bool deserializeElem(GVariant* parameters, - std::vector* outArray) + std::vector* outArray) { unsigned int i = 0; gsize length = 0; @@ -174,7 +172,6 @@ struct ServerDeserialization { return true; } }; - } // namespace DBus } // namespace DPL diff --git a/modules/dbus/include/dpl/dbus/dbus_server_serialization.h b/modules/dbus/include/dpl/dbus/dbus_server_serialization.h index 8c299ef..9e47ca6 100644 --- a/modules/dbus/include/dpl/dbus/dbus_server_serialization.h +++ b/modules/dbus/include/dpl/dbus/dbus_server_serialization.h @@ -28,11 +28,9 @@ namespace DPL { namespace DBus { - struct ServerSerialization { - - template - static GVariant* serialize(Args... args) + template + static GVariant* serialize(Args ... args) { GVariantBuilder* builder = g_variant_builder_new(G_VARIANT_TYPE_TUPLE); if (NULL == builder) { @@ -43,10 +41,10 @@ struct ServerSerialization { } // serialization on GVariantBuilder - template + template static void serializeBuilder(GVariantBuilder* builder, const T& arg, - Args... args) + Args ... args) { serializeElem(builder, arg); serializeBuilder(builder, args ...); @@ -86,12 +84,11 @@ struct ServerSerialization { } static void serializeElem(GVariantBuilder* builder, - const std::string& arg) + const std::string& arg) { g_variant_builder_add_value(builder, g_variant_new_string(arg.c_str())); } }; - } // namespace DBus } // namespace DPL diff --git a/modules/dbus/include/dpl/dbus/dbus_signature.h b/modules/dbus/include/dpl/dbus/dbus_signature.h index af0c2ef..bc99108 100644 --- a/modules/dbus/include/dpl/dbus/dbus_signature.h +++ b/modules/dbus/include/dpl/dbus/dbus_signature.h @@ -28,7 +28,6 @@ namespace DPL { namespace DBus { - template struct SimpleType; @@ -119,7 +118,7 @@ template<> struct SimpleType { static const int value = - __UnsignedIntegerType::value; + __UnsignedIntegerType::value; }; template<> @@ -132,7 +131,7 @@ template<> struct SimpleType { static const int value = - __UnsignedIntegerType::value; + __UnsignedIntegerType::value; }; template<> @@ -145,7 +144,7 @@ template<> struct SimpleType { static const int value = - __UnsignedIntegerType::value; + __UnsignedIntegerType::value; }; template<> @@ -158,7 +157,7 @@ template<> struct SimpleType { static const int value = - __UnsignedIntegerType::value; + __UnsignedIntegerType::value; }; template<> @@ -221,20 +220,17 @@ struct ArraySignature // std::vector template struct Signature > : public ArraySignature -{ -}; +{}; // std::list template struct Signature > : public ArraySignature -{ -}; +{}; // std::set template struct Signature > : public ArraySignature -{ -}; +{}; // std::pair template @@ -244,8 +240,8 @@ struct Signature > { static const std::string signature = std::string( DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING) - + Signature::value() + Signature::value() - + DBUS_DICT_ENTRY_END_CHAR_AS_STRING; + + Signature::value() + Signature::value() + + DBUS_DICT_ENTRY_END_CHAR_AS_STRING; return signature.c_str(); } }; @@ -253,9 +249,7 @@ struct Signature > // std::map template struct Signature > : public ArraySignature > -{ -}; - +{}; } // namespace DBus } // namespace DPL diff --git a/modules/dbus/include/dpl/dbus/dispatcher.h b/modules/dbus/include/dpl/dbus/dispatcher.h index 68e4397..93e62e6 100644 --- a/modules/dbus/include/dpl/dbus/dispatcher.h +++ b/modules/dbus/include/dpl/dbus/dispatcher.h @@ -27,11 +27,10 @@ namespace DPL { namespace DBus { - class Dispatcher { -public: - virtual ~Dispatcher() =0; + public: + virtual ~Dispatcher() = 0; /** * Called on method invocation. @@ -52,7 +51,7 @@ public: const gchar* interfaceName, const gchar* methodName, GVariant* parameters, - GDBusMethodInvocation* invocation) =0; + GDBusMethodInvocation* invocation) = 0; /** * Called on property get. @@ -94,7 +93,6 @@ public: GVariant* value, GError** error); }; - } } diff --git a/modules/dbus/include/dpl/dbus/exception.h b/modules/dbus/include/dpl/dbus/exception.h index fb21bf0..035d16f 100644 --- a/modules/dbus/include/dpl/dbus/exception.h +++ b/modules/dbus/include/dpl/dbus/exception.h @@ -27,7 +27,6 @@ namespace DPL { namespace DBus { - /** * Thrown when none of the following, more specific exception fit. */ @@ -42,7 +41,6 @@ DECLARE_EXCEPTION_TYPE(DBus::Exception, ConnectionClosedException) * Thrown when passing invalid argument(s). */ DECLARE_EXCEPTION_TYPE(DBus::Exception, InvalidArgumentException) - } } diff --git a/modules/dbus/include/dpl/dbus/interface.h b/modules/dbus/include/dpl/dbus/interface.h index 1bf1148..6248dab 100644 --- a/modules/dbus/include/dpl/dbus/interface.h +++ b/modules/dbus/include/dpl/dbus/interface.h @@ -31,13 +31,12 @@ namespace DPL { namespace DBus { - class Interface; typedef std::shared_ptr InterfacePtr; class Interface : private DPL::Noncopyable { -public: + public: /** * Parses supplied XML string to produce DBus interface descriptions. * @@ -46,9 +45,9 @@ public: * @throw DPL::DBus::Exception If error while parsing occurs. */ static std::vector fromXMLString( - const std::string& xmlString); + const std::string& xmlString); -public: + public: ~Interface(); /** @@ -73,7 +72,7 @@ public: */ void setDispatcher(Dispatcher* dispatcher); -private: + private: static void onMethodCallFunc(GDBusConnection *connection, const gchar *sender, const gchar *objectPath, @@ -108,7 +107,6 @@ private: Dispatcher* m_dispatcher; }; - } } diff --git a/modules/dbus/include/dpl/dbus/method_proxy.h b/modules/dbus/include/dpl/dbus/method_proxy.h index 3d553cf..19c3b90 100644 --- a/modules/dbus/include/dpl/dbus/method_proxy.h +++ b/modules/dbus/include/dpl/dbus/method_proxy.h @@ -36,16 +36,15 @@ namespace DPL { namespace DBus { - class ObjectProxy; /** * Represents a remote method. */ -template +template class MethodProxy { -public: + public: ~MethodProxy() { g_object_unref(m_connection); @@ -60,24 +59,24 @@ public: * @throw DBus::ConnectionClosedException If connection is closed. * @throw DBus::Exception If some other error occurs. */ - Result operator()(const Args&... args) + Result operator()(const Args& ... args) { - return invoke(args...); + return invoke(args ...); } -private: + private: friend class ObjectProxy; MethodProxy(GDBusConnection* connection, const std::string& serviceName, const std::string& objectPath, const std::string& interfaceName, - const std::string& methodName) - : m_connection(connection), - m_serviceName(serviceName), - m_objectPath(objectPath), - m_interfaceName(interfaceName), - m_methodName(methodName) + const std::string& methodName) : + m_connection(connection), + m_serviceName(serviceName), + m_objectPath(objectPath), + m_interfaceName(interfaceName), + m_methodName(methodName) { Assert(m_connection && "Connection is not set."); @@ -91,9 +90,9 @@ private: */ template typename std::enable_if::value, R>::type - invoke(const Args&... args) + invoke(const Args& ... args) { - GVariant* parameters = serialize(args...); + GVariant* parameters = serialize(args ...); GVariant* invokeResult = invokeSync(parameters); @@ -111,9 +110,9 @@ private: */ template typename std::enable_if::value>::type - invoke(const Args&... args) + invoke(const Args& ... args) { - GVariant* parameters = serialize(args...); + GVariant* parameters = serialize(args ...); GVariant* invokeResult = invokeSync(parameters); @@ -124,10 +123,10 @@ private: * @remarks ArgsM... are the same as Args...; it has been made a template * to make overloading/specialization possible. */ - template - GVariant* serialize(ArgsM&&... args) + template + GVariant* serialize(ArgsM && ... args) { - return ServerSerialization::serialize(std::forward(args)...); + return ServerSerialization::serialize(std::forward(args) ...); } /** @@ -151,7 +150,8 @@ private: { GError* error = NULL; - LogPedantic("Invoking method: " << m_interfaceName << "." << m_methodName); + LogPedantic( + "Invoking method: " << m_interfaceName << "." << m_methodName); GVariant* result = g_dbus_connection_call_sync(m_connection, m_serviceName.c_str(), m_objectPath.c_str(), @@ -163,8 +163,7 @@ private: DBUS_SYNC_CALL_TIMEOUT, NULL, &error); - if (NULL == result) - { + if (NULL == result) { std::ostringstream oss; oss << "Error while invoking: " << m_interfaceName << "." << m_methodName @@ -175,8 +174,7 @@ private: g_error_free(error); - switch (code) - { + switch (code) { case G_IO_ERROR_INVALID_ARGUMENT: ThrowMsg(DBus::InvalidArgumentException, message); case G_IO_ERROR_CLOSED: @@ -206,26 +204,24 @@ private: /** * Smart pointer for MethodProxy objects. */ -template +template class MethodProxyPtr { -public: - explicit MethodProxyPtr(MethodProxy* method = NULL) - : m_method(method) - { - } + public: + explicit MethodProxyPtr(MethodProxy* method = NULL) : + m_method(method) + {} - Result operator()(const Args&... args) const + Result operator()(const Args& ... args) const { Assert(NULL != m_method.get() && "Method not set."); - return (*m_method)(args...); + return (*m_method)(args ...); } -private: - std::shared_ptr > m_method; + private: + std::shared_ptr > m_method; }; - } } diff --git a/modules/dbus/include/dpl/dbus/object.h b/modules/dbus/include/dpl/dbus/object.h index 7731dfa..191464c 100644 --- a/modules/dbus/include/dpl/dbus/object.h +++ b/modules/dbus/include/dpl/dbus/object.h @@ -30,13 +30,12 @@ namespace DPL { namespace DBus { - class Object; typedef std::shared_ptr ObjectPtr; class Object { -public: + public: /** * Creates an object. * @@ -61,13 +60,12 @@ public: */ InterfacePtr getInterface() const; -private: + private: Object(const std::string& path, const InterfacePtr& interface); std::string m_path; InterfacePtr m_interface; }; - } } diff --git a/modules/dbus/include/dpl/dbus/object_proxy.h b/modules/dbus/include/dpl/dbus/object_proxy.h index 3d727c0..17764f1 100644 --- a/modules/dbus/include/dpl/dbus/object_proxy.h +++ b/modules/dbus/include/dpl/dbus/object_proxy.h @@ -30,7 +30,6 @@ namespace DPL { namespace DBus { - class Connection; /** @@ -38,7 +37,7 @@ class Connection; */ class ObjectProxy { -public: + public: ~ObjectProxy(); /** @@ -51,25 +50,24 @@ public: * @return Proxy to remote method. * @throw DBus::ConnectionClosedException If connection is closed. */ - template - MethodProxyPtr createMethodProxy( - const std::string& interface, - const std::string& name) + template + MethodProxyPtr createMethodProxy( + const std::string& interface, + const std::string& name) { - if (g_dbus_connection_is_closed(m_connection)) - { + if (g_dbus_connection_is_closed(m_connection)) { ThrowMsg(DBus::ConnectionClosedException, "Connection closed."); } - return MethodProxyPtr( - new MethodProxy(m_connection, - m_serviceName, - m_objectPath, - interface, - name)); + return MethodProxyPtr( + new MethodProxy(m_connection, + m_serviceName, + m_objectPath, + interface, + name)); } -private: + private: friend class Connection; ObjectProxy(GDBusConnection* connection, @@ -80,7 +78,6 @@ private: std::string m_serviceName; std::string m_objectPath; }; - } } diff --git a/modules/dbus/include/dpl/dbus/server.h b/modules/dbus/include/dpl/dbus/server.h index 39220ae..795a757 100644 --- a/modules/dbus/include/dpl/dbus/server.h +++ b/modules/dbus/include/dpl/dbus/server.h @@ -30,13 +30,9 @@ #include #include -namespace DPL -{ -namespace DBus -{ - -namespace ServerEvents -{ +namespace DPL { +namespace DBus { +namespace ServerEvents { /** * Emitted when new connection is accepted. * @@ -57,7 +53,7 @@ typedef std::shared_ptr ServerPtr; */ class Server : public DPL::Event::EventSupport { -public: + public: /** * Creates server. * @@ -78,17 +74,16 @@ public: */ void stop(); -protected: + protected: explicit Server(GDBusServer* server); -private: + private: static gboolean onNewConnection(GDBusServer* server, GDBusConnection* connection, gpointer data); GDBusServer* m_server; }; - } } diff --git a/modules/dbus/src/connection.cpp b/modules/dbus/src/connection.cpp index 53d992c..52c0065 100644 --- a/modules/dbus/src/connection.cpp +++ b/modules/dbus/src/connection.cpp @@ -25,11 +25,8 @@ #include #include -namespace DPL -{ -namespace DBus -{ - +namespace DPL { +namespace DBus { ConnectionPtr Connection::sessionBus() { return connectTo(G_BUS_TYPE_SESSION); @@ -47,11 +44,9 @@ ConnectionPtr Connection::connectTo(GBusType busType) GDBusConnection* connection = g_bus_get_sync(busType, NULL, &error); - if (NULL == connection) - { + if (NULL == connection) { std::string message; - if (NULL != error) - { + if (NULL != error) { message = error->message; g_error_free(error); } @@ -69,16 +64,14 @@ ConnectionPtr Connection::connectTo(const std::string& address) GError* error = NULL; GDBusConnection* connection = g_dbus_connection_new_for_address_sync( - address.c_str(), - G_DBUS_CONNECTION_FLAGS_NONE, - NULL, - NULL, - &error); - if (NULL == connection) - { + address.c_str(), + G_DBUS_CONNECTION_FLAGS_NONE, + NULL, + NULL, + &error); + if (NULL == connection) { std::string message; - if (NULL != error) - { + if (NULL != error) { message = error->message; g_error_free(error); } @@ -89,8 +82,8 @@ ConnectionPtr Connection::connectTo(const std::string& address) return ConnectionPtr(new Connection(connection)); } -Connection::Connection(GDBusConnection* connection) - : m_connection(connection) +Connection::Connection(GDBusConnection* connection) : + m_connection(connection) { g_signal_connect(m_connection, "closed", @@ -102,28 +95,28 @@ Connection::~Connection() { std::for_each(m_registeredServices.begin(), m_registeredServices.end(), - [] (const RegisteredServices::value_type& value) + [] (const RegisteredServices::value_type & value) { g_bus_unown_name(value.second); }); std::for_each(m_registeredObjects.begin(), m_registeredObjects.end(), - [this] (const RegisteredObjects::value_type& value) + [this] (const RegisteredObjects::value_type & value) { g_dbus_connection_unregister_object( - m_connection, - value.second.registrationId); + m_connection, + value.second.registrationId); }); - if (!g_dbus_connection_is_closed(m_connection)) - { + if (!g_dbus_connection_is_closed(m_connection)) { GError* error = NULL; - if (FALSE == g_dbus_connection_flush_sync(m_connection, NULL, &error)) + if (FALSE == + g_dbus_connection_flush_sync(m_connection, NULL, &error)) { LogPedantic("Could not flush the connection" - << " <" << error->message << ">"); + << " <" << error->message << ">"); g_error_free(error); } } @@ -140,8 +133,7 @@ void Connection::registerService(const std::string& serviceName) onServiceNameLost, this, NULL); - if (0 >= regId) - { + if (0 >= regId) { ThrowMsg(DBus::Exception, "Error while registering service."); } @@ -152,8 +144,7 @@ void Connection::registerService(const std::string& serviceName) void Connection::unregisterService(const std::string& serviceName) { auto it = m_registeredServices.find(serviceName); - if (m_registeredServices.end() == it) - { + if (m_registeredServices.end() == it) { ThrowMsg(DBus::Exception, "Service not registered."); } @@ -167,45 +158,41 @@ void Connection::registerObject(const ObjectPtr& object) GError* error = NULL; guint regId = g_dbus_connection_register_object( - m_connection, - object->getPath().c_str(), - object->getInterface()->getInfo(), - object->getInterface()->getVTable(), - // TODO This is ugly, fix this! - object->getInterface().get(), - NULL, - &error); - if (0 == regId) - { + m_connection, + object->getPath().c_str(), + object->getInterface()->getInfo(), + object->getInterface()->getVTable(), + // TODO This is ugly, fix this! + object->getInterface().get(), + NULL, + &error); + if (0 == regId) { std::string message; - if (NULL != error) - { + if (NULL != error) { message = error->message; LogPedantic(error->message << " " << error->code); g_error_free(error); } ThrowMsg(DBus::Exception, "Error while registering an object: " - << message); + << message); } m_registeredObjects.insert(RegisteredObjects::value_type( - object->getPath(), - ObjectRegistration(regId, object))); + object->getPath(), + ObjectRegistration(regId, object))); } void Connection::unregisterObject(const std::string& objectPath) { auto it = m_registeredObjects.find(objectPath); - if (m_registeredObjects.end() == it) - { + if (m_registeredObjects.end() == it) { ThrowMsg(DBus::Exception, "Object not registered."); } gboolean result = g_dbus_connection_unregister_object( - m_connection, - it->second.registrationId); - if (FALSE == result) - { + m_connection, + it->second.registrationId); + if (FALSE == result) { ThrowMsg(DBus::Exception, "Unregistering object failed."); } m_registeredObjects.erase(it); @@ -214,13 +201,12 @@ void Connection::unregisterObject(const std::string& objectPath) ObjectProxyPtr Connection::createObjectProxy(const std::string& serviceName, const std::string& objectPath) { - if (g_dbus_connection_is_closed(m_connection)) - { + if (g_dbus_connection_is_closed(m_connection)) { ThrowMsg(DBus::ConnectionClosedException, "Connection closed."); } return ObjectProxyPtr( - new ObjectProxy(m_connection, serviceName, objectPath)); + new ObjectProxy(m_connection, serviceName, objectPath)); } void Connection::onServiceNameAcquired(GDBusConnection* /*connection*/, @@ -234,8 +220,9 @@ void Connection::onServiceNameAcquired(GDBusConnection* /*connection*/, LogPedantic("Emitting service name acquired event: " << serviceName); ConnectionEvents::ServiceNameAcquiredEvent event(serviceName); - self->DPL::Event::EventSupport:: - EmitEvent(event, DPL::Event::EmitMode::Queued); + self->DPL::Event::EventSupport + :: + EmitEvent(event, DPL::Event::EmitMode::Queued); } void Connection::onServiceNameLost(GDBusConnection* /*connection*/, @@ -250,7 +237,7 @@ void Connection::onServiceNameLost(GDBusConnection* /*connection*/, ConnectionEvents::ServiceNameLostEvent event(serviceName); self->DPL::Event::EventSupport:: - EmitEvent(event, DPL::Event::EmitMode::Queued); + EmitEvent(event, DPL::Event::EmitMode::Queued); } void Connection::onConnectionClosed(GDBusConnection* /*connection*/, @@ -262,32 +249,27 @@ void Connection::onConnectionClosed(GDBusConnection* /*connection*/, Connection* self = static_cast(data); - if ((NULL == error) && (FALSE == peerVanished)) - { + if ((NULL == error) && (FALSE == peerVanished)) { // Connection closed by this. - } - else if (NULL != error) - { + } else if (NULL != error) { std::string message = error->message; g_error_free(error); - if (TRUE == peerVanished) - { + if (TRUE == peerVanished) { // Connection closed by remote host. ConnectionEvents::ConnectionBrokenEvent event(message); - self->DPL::Event::EventSupport:: - EmitEvent(event, DPL::Event::EmitMode::Queued); - } - else - { + self->DPL::Event::EventSupport:: + EmitEvent(event, DPL::Event::EmitMode::Queued); + } else { // Invalid or malformed data on connection. ConnectionEvents::ConnectionInvalidEvent event(message); - self->DPL::Event::EventSupport:: - EmitEvent(event, DPL::Event::EmitMode::Queued); + self->DPL::Event::EventSupport:: + EmitEvent(event, DPL::Event::EmitMode::Queued); } } } - } } diff --git a/modules/dbus/src/dispatcher.cpp b/modules/dbus/src/dispatcher.cpp index 5411f35..d83a22a 100644 --- a/modules/dbus/src/dispatcher.cpp +++ b/modules/dbus/src/dispatcher.cpp @@ -22,11 +22,8 @@ #include #include -namespace DPL -{ -namespace DBus -{ - +namespace DPL { +namespace DBus { Dispatcher::~Dispatcher() { } GVariant* Dispatcher::onPropertyGet(GDBusConnection* /*connection*/, @@ -49,6 +46,5 @@ gboolean Dispatcher::onPropertySet(GDBusConnection* /*connection*/, { return false; } - } } diff --git a/modules/dbus/src/interface.cpp b/modules/dbus/src/interface.cpp index b151a75..0df3a59 100644 --- a/modules/dbus/src/interface.cpp +++ b/modules/dbus/src/interface.cpp @@ -28,13 +28,11 @@ namespace DPL { namespace DBus { - -const GDBusInterfaceVTable Interface::m_vTable = -{ +const GDBusInterfaceVTable Interface::m_vTable = { Interface::onMethodCallFunc, Interface::onPropertyGetFunc, Interface::onPropertySetFunc, - {0, 0, 0, 0, 0, 0, 0, 0} + { 0, 0, 0, 0, 0, 0, 0, 0 } }; std::vector Interface::fromXMLString(const std::string& xmlString) @@ -43,11 +41,9 @@ std::vector Interface::fromXMLString(const std::string& xmlString) GDBusNodeInfo* nodeInfo = g_dbus_node_info_new_for_xml(xmlString.c_str(), &error); - if (NULL == nodeInfo) - { + if (NULL == nodeInfo) { std::string message; - if (NULL != error) - { + if (NULL != error) { message = error->message; g_error_free(error); } @@ -58,8 +54,7 @@ std::vector Interface::fromXMLString(const std::string& xmlString) std::vector result; GDBusInterfaceInfo** interface = nodeInfo->interfaces; - while (NULL != *interface) - { + while (NULL != *interface) { result.push_back(InterfacePtr(new Interface(*interface))); ++interface; } @@ -69,8 +64,8 @@ std::vector Interface::fromXMLString(const std::string& xmlString) return result; } -Interface::Interface(GDBusInterfaceInfo* info) - : m_info(info) +Interface::Interface(GDBusInterfaceInfo* info) : + m_info(info) { g_dbus_interface_info_ref(m_info); } @@ -109,10 +104,8 @@ void Interface::onMethodCallFunc(GDBusConnection *connection, // TODO Verify interface name. - if (NULL != self->m_dispatcher) - { - try - { + if (NULL != self->m_dispatcher) { + try { self->m_dispatcher->onMethodCall(connection, sender, objectPath, @@ -120,9 +113,7 @@ void Interface::onMethodCallFunc(GDBusConnection *connection, methodName, parameters, invocation); - } - catch (const DPL::Exception& /*ex*/) - { + } catch (const DPL::Exception& /*ex*/) { // TODO Support for errors. } } @@ -141,10 +132,8 @@ GVariant* Interface::onPropertyGetFunc(GDBusConnection *connection, // TODO Verify interface name. - if (NULL != self->m_dispatcher) - { - try - { + if (NULL != self->m_dispatcher) { + try { // TODO Check if NULL is returned, if so set error variable. return self->m_dispatcher->onPropertyGet(connection, sender, @@ -152,9 +141,7 @@ GVariant* Interface::onPropertyGetFunc(GDBusConnection *connection, interfaceName, propertyName, error); - } - catch (const DPL::Exception& /*ex*/) - { + } catch (const DPL::Exception& /*ex*/) { // TODO Support for errors. } } @@ -178,10 +165,8 @@ gboolean Interface::onPropertySetFunc(GDBusConnection *connection, // TODO Verify interface name. - if (NULL != self->m_dispatcher) - { - try - { + if (NULL != self->m_dispatcher) { + try { return self->m_dispatcher->onPropertySet(connection, sender, objectPath, @@ -189,9 +174,7 @@ gboolean Interface::onPropertySetFunc(GDBusConnection *connection, propertyName, value, error); - } - catch (const DPL::Exception& /*ex*/) - { + } catch (const DPL::Exception& /*ex*/) { // TODO Support for errors. } } @@ -200,6 +183,5 @@ gboolean Interface::onPropertySetFunc(GDBusConnection *connection, return false; } - } } diff --git a/modules/dbus/src/object.cpp b/modules/dbus/src/object.cpp index 02781a7..a66796d 100644 --- a/modules/dbus/src/object.cpp +++ b/modules/dbus/src/object.cpp @@ -24,7 +24,6 @@ namespace DPL { namespace DBus { - ObjectPtr Object::create(const std::string& path, const InterfacePtr& interface) { return ObjectPtr(new Object(path, interface)); @@ -40,11 +39,9 @@ InterfacePtr Object::getInterface() const return m_interface; } -Object::Object(const std::string& path, const InterfacePtr& interface) - : m_path(path), - m_interface(interface) -{ -} - +Object::Object(const std::string& path, const InterfacePtr& interface) : + m_path(path), + m_interface(interface) +{} } } \ No newline at end of file diff --git a/modules/dbus/src/object_proxy.cpp b/modules/dbus/src/object_proxy.cpp index dcabb33..9b15bb7 100644 --- a/modules/dbus/src/object_proxy.cpp +++ b/modules/dbus/src/object_proxy.cpp @@ -24,13 +24,12 @@ namespace DPL { namespace DBus { - ObjectProxy::ObjectProxy(GDBusConnection* connection, const std::string& serviceName, - const std::string& objectPath) - : m_connection(connection), - m_serviceName(serviceName), - m_objectPath(objectPath) + const std::string& objectPath) : + m_connection(connection), + m_serviceName(serviceName), + m_objectPath(objectPath) { g_object_ref(m_connection); } @@ -39,6 +38,5 @@ ObjectProxy::~ObjectProxy() { g_object_unref(m_connection); } - } } \ No newline at end of file diff --git a/modules/dbus/src/server.cpp b/modules/dbus/src/server.cpp index 1f84ce6..421090f 100644 --- a/modules/dbus/src/server.cpp +++ b/modules/dbus/src/server.cpp @@ -26,30 +26,27 @@ namespace DPL { namespace DBus { - ServerPtr Server::create(const std::string& address) { GError* error = NULL; int flags = G_DBUS_SERVER_FLAGS_NONE | - G_DBUS_SERVER_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS; + G_DBUS_SERVER_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS; gchar* serverId = g_dbus_generate_guid(); GDBusServer* server = g_dbus_server_new_sync( - address.c_str(), - static_cast(flags), - serverId, - NULL, - NULL, - &error); + address.c_str(), + static_cast(flags), + serverId, + NULL, + NULL, + &error); g_free(serverId); - if (NULL == server) - { + if (NULL == server) { std::string message; - if (NULL != error) - { + if (NULL != error) { message = error->message; g_error_free(error); } @@ -60,15 +57,13 @@ ServerPtr Server::create(const std::string& address) return ServerPtr(new Server(server)); } -Server::Server(GDBusServer* server) - : m_server(server) -{ -} +Server::Server(GDBusServer* server) : + m_server(server) +{} Server::~Server() { - if (g_dbus_server_is_active(m_server)) - { + if (g_dbus_server_is_active(m_server)) { stop(); } g_object_unref(m_server); @@ -105,16 +100,15 @@ gboolean Server::onNewConnection(GDBusServer* /*server*/, Server* self = static_cast(data); ServerEvents::NewConnectionEvent event( - ConnectionPtr(new Connection(connection))); + ConnectionPtr(new Connection(connection))); LogInfo("Emitting new connection event"); // TODO Blocking to allow object registration before any DBus messages are // processed. self->DPL::Event::EventSupport:: - EmitEvent(event, DPL::Event::EmitMode::Blocking); + EmitEvent(event, DPL::Event::EmitMode::Blocking); return TRUE; } - } } diff --git a/modules/encryption/include/dpl/encryption/resource_decryption.h b/modules/encryption/include/dpl/encryption/resource_decryption.h index 2a39eb1..a6d7af0 100644 --- a/modules/encryption/include/dpl/encryption/resource_decryption.h +++ b/modules/encryption/include/dpl/encryption/resource_decryption.h @@ -30,30 +30,31 @@ extern char** calculate(char*pappId, int idLen, int keyLen); -namespace WRTDecryptor{ +namespace WRTDecryptor { class ResourceDecryptor { public: - class Exception - { - public: - DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) - DECLARE_EXCEPTION_TYPE(Base, GetDecKeyFailed) - DECLARE_EXCEPTION_TYPE(Base, EncryptionFailed) - }; - - ResourceDecryptor(); - ResourceDecryptor(std::string userKey); - virtual ~ResourceDecryptor(); - - void SetDecryptionKey(std::string userKey); - void GetDecryptedChunk(unsigned char* inBuf, unsigned char* decBuf, size_t chunkSize); + class Exception + { + public: + DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) + DECLARE_EXCEPTION_TYPE(Base, GetDecKeyFailed) + DECLARE_EXCEPTION_TYPE(Base, EncryptionFailed) + }; + + ResourceDecryptor(); + ResourceDecryptor(std::string userKey); + virtual ~ResourceDecryptor(); + + void SetDecryptionKey(std::string userKey); + void GetDecryptedChunk(unsigned char* inBuf, + unsigned char* decBuf, + size_t chunkSize); private: - AES_KEY* GetDecryptionKey(); - AES_KEY m_decKey; - + AES_KEY* GetDecryptionKey(); + AES_KEY m_decKey; }; -} //namespace WRTDecryptor +} //namespace WRTDecryptor #endif /* RESOURCE_DECRYPTION_H */ diff --git a/modules/encryption/include/dpl/encryption/resource_encryption.h b/modules/encryption/include/dpl/encryption/resource_encryption.h index 6f57a93..f2e4988 100644 --- a/modules/encryption/include/dpl/encryption/resource_encryption.h +++ b/modules/encryption/include/dpl/encryption/resource_encryption.h @@ -30,32 +30,32 @@ extern char** calculate(char*pappId, int idLen, int keyLen); -namespace WRTEncryptor{ +namespace WRTEncryptor { class ResourceEncryptor { public: - class Exception - { - public: - DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) - DECLARE_EXCEPTION_TYPE(DPL::Exception, CreateEncKeyFailed) - DECLARE_EXCEPTION_TYPE(DPL::Exception, CreateDecKeyFailed) - DECLARE_EXCEPTION_TYPE(DPL::Exception, CreateEncKeyFileFailed) - DECLARE_EXCEPTION_TYPE(DPL::Exception, CreateDecKeyFileFailed) - DECLARE_EXCEPTION_TYPE(DPL::Exception, EncryptionFailed) - }; + class Exception + { + public: + DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) + DECLARE_EXCEPTION_TYPE(DPL::Exception, CreateEncKeyFailed) + DECLARE_EXCEPTION_TYPE(DPL::Exception, CreateDecKeyFailed) + DECLARE_EXCEPTION_TYPE(DPL::Exception, CreateEncKeyFileFailed) + DECLARE_EXCEPTION_TYPE(DPL::Exception, CreateDecKeyFileFailed) + DECLARE_EXCEPTION_TYPE(DPL::Exception, EncryptionFailed) + }; - ResourceEncryptor(); - virtual ~ResourceEncryptor(); + ResourceEncryptor(); + virtual ~ResourceEncryptor(); - int GetBlockSize(int inSize); - void CreateEncryptionKey(std::string userKey); - void EncryptChunk(unsigned char* inputBuf, unsigned char* encBuf, size_t - chunkSize); + int GetBlockSize(int inSize); + void CreateEncryptionKey(std::string userKey); + void EncryptChunk(unsigned char* inputBuf, unsigned char* encBuf, size_t + chunkSize); private: - AES_KEY GetEncryptionkey(); - AES_KEY m_encKey; + AES_KEY GetEncryptionkey(); + AES_KEY m_encKey; }; } //namespace WRTEncryptor diff --git a/modules/encryption/src/resource_decryption.cpp b/modules/encryption/src/resource_decryption.cpp index 9e8b39f..2ec612e 100644 --- a/modules/encryption/src/resource_decryption.cpp +++ b/modules/encryption/src/resource_decryption.cpp @@ -31,21 +31,20 @@ namespace { #define BITS_SIZE 128 #define KEY_SIZE 16 } -namespace WRTDecryptor{ +namespace WRTDecryptor { ResourceDecryptor::ResourceDecryptor() { LogDebug("Started Decryption"); } -ResourceDecryptor::ResourceDecryptor(std::string userKey) +ResourceDecryptor::ResourceDecryptor(std::string userKey) { LogDebug("Finished Decryption"); SetDecryptionKey(userKey); } ResourceDecryptor::~ResourceDecryptor() -{ -} +{} void ResourceDecryptor::SetDecryptionKey(std::string userKey) { @@ -53,12 +52,13 @@ void ResourceDecryptor::SetDecryptionKey(std::string userKey) return; } - char **duk = calculate(const_cast(userKey.c_str()), userKey.size(), KEY_SIZE); + char **duk = calculate(const_cast(userKey.c_str()), + userKey.size(), KEY_SIZE); unsigned char *key = reinterpret_cast(*duk); - if ( 0 > AES_set_decrypt_key(key, BITS_SIZE, &m_decKey)) { + if (0 > AES_set_decrypt_key(key, BITS_SIZE, &m_decKey)) { ThrowMsg(ResourceDecryptor::Exception::GetDecKeyFailed, - "Failed to create decryption key"); + "Failed to create decryption key"); } } @@ -68,17 +68,18 @@ AES_KEY* ResourceDecryptor::GetDecryptionKey() } void ResourceDecryptor::GetDecryptedChunk(unsigned char* - inBuf, unsigned char* decBuf, size_t inBufSize) + inBuf, + unsigned char* decBuf, + size_t inBufSize) { Assert(decBuf); if (decBuf == NULL) { ThrowMsg(ResourceDecryptor::Exception::EncryptionFailed, - "Failed to Get Decryption Chunk"); + "Failed to Get Decryption Chunk"); } - unsigned char ivec[16] = {0, }; + unsigned char ivec[16] = { 0, }; AES_cbc_encrypt(inBuf, decBuf, inBufSize, &m_decKey, ivec, AES_DECRYPT); LogDebug("Success decryption"); } - } //namespace WRTDecryptor diff --git a/modules/encryption/src/resource_encryption.cpp b/modules/encryption/src/resource_encryption.cpp index a238705..96e90b7 100644 --- a/modules/encryption/src/resource_encryption.cpp +++ b/modules/encryption/src/resource_encryption.cpp @@ -29,7 +29,7 @@ namespace { #define BITS_SIZE 128 #define KEY_SIZE 16 } -namespace WRTEncryptor{ +namespace WRTEncryptor { ResourceEncryptor::ResourceEncryptor() { LogDebug("Started Encrytion"); @@ -43,7 +43,7 @@ ResourceEncryptor::~ResourceEncryptor() int ResourceEncryptor::GetBlockSize(int inSize) { if ((inSize % AES_BLOCK_SIZE) != 0) { - return (( inSize/ AES_BLOCK_SIZE) +1) * AES_BLOCK_SIZE; + return (( inSize / AES_BLOCK_SIZE) + 1) * AES_BLOCK_SIZE; } return inSize; } @@ -54,12 +54,13 @@ void ResourceEncryptor::CreateEncryptionKey(std::string userKey) return; } - char **duk = calculate(const_cast(userKey.c_str()), userKey.size(), KEY_SIZE); + 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)) { + if (0 > AES_set_encrypt_key(key, BITS_SIZE, &m_encKey)) { ThrowMsg(ResourceEncryptor::Exception::CreateEncKeyFailed, - "Failed to create encryption key"); + "Failed to create encryption key"); } LogDebug("Success to create ecryption and decryption key"); } @@ -70,12 +71,14 @@ AES_KEY ResourceEncryptor::GetEncryptionkey() } void ResourceEncryptor::EncryptChunk(unsigned char* - inputBuf, unsigned char* encBuf, size_t chunkSize) + inputBuf, + unsigned char* encBuf, + size_t chunkSize) { Assert(inputBuf); Assert(encBuf); - unsigned char ivec[16] = {0, }; + unsigned char ivec[16] = { 0, }; AES_cbc_encrypt(inputBuf, encBuf, chunkSize, &m_encKey, ivec, AES_ENCRYPT); } diff --git a/modules/event/include/dpl/event/abstract_event_call.h b/modules/event/include/dpl/event/abstract_event_call.h index e199897..db1bea4 100644 --- a/modules/event/include/dpl/event/abstract_event_call.h +++ b/modules/event/include/dpl/event/abstract_event_call.h @@ -24,16 +24,12 @@ #include -namespace DPL +namespace DPL { +namespace Event { +class AbstractEventCall : + private Noncopyable { -namespace Event -{ - - -class AbstractEventCall - : private Noncopyable -{ -public: + public: /** * Constructor */ @@ -49,7 +45,6 @@ public: */ virtual void Call() = 0; }; - } } // namespace DPL diff --git a/modules/event/include/dpl/event/abstract_event_dispatcher.h b/modules/event/include/dpl/event/abstract_event_dispatcher.h index ddd76ad..f5caa56 100644 --- a/modules/event/include/dpl/event/abstract_event_dispatcher.h +++ b/modules/event/include/dpl/event/abstract_event_dispatcher.h @@ -17,7 +17,8 @@ * @file abstract_event_dispatcher.h * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) * @version 1.0 - * @brief This file is the implementation file of abstract event dispatcher + * @brief This file is the implementation file of abstract event + * dispatcher */ #ifndef DPL_ABSTRACT_EVENT_DISPATCHER_H #define DPL_ABSTRACT_EVENT_DISPATCHER_H @@ -25,15 +26,12 @@ #include #include -namespace DPL +namespace DPL { +namespace Event { +class AbstractEventDispatcher : + private Noncopyable { -namespace Event -{ - -class AbstractEventDispatcher - : private Noncopyable -{ -public: + public: /** * Constructor */ @@ -59,9 +57,9 @@ public: * @param[in] dueTime Due time for timed event in seconds * @return none */ - virtual void AddTimedEventCall(AbstractEventCall *abstractEventCall, double dueTime) = 0; + virtual void AddTimedEventCall(AbstractEventCall *abstractEventCall, + double dueTime) = 0; }; - } } // namespace DPL diff --git a/modules/event/include/dpl/event/controller.h b/modules/event/include/dpl/event/controller.h index 1c5c75c..1b14632 100644 --- a/modules/event/include/dpl/event/controller.h +++ b/modules/event/include/dpl/event/controller.h @@ -28,22 +28,19 @@ #include #include -namespace DPL -{ -namespace Event -{ - +namespace DPL { +namespace Event { template -class ControllerEventHandler - : public EventListener, - private EventSupport +class ControllerEventHandler : + public EventListener, + private EventSupport { -private: + private: bool m_touched; -public: - ControllerEventHandler() - : m_touched(false) + public: + ControllerEventHandler() : + m_touched(false) { EventSupport::AddListener(this); } @@ -55,19 +52,25 @@ public: void PostEvent(const EventType &event) { - Assert(m_touched && "Default context not inherited. Call Touch() to inherit one."); + Assert( + m_touched && + "Default context not inherited. Call Touch() to inherit one."); EventSupport::EmitEvent(event, EmitMode::Queued); } void PostTimedEvent(const EventType &event, double dueTime) { - Assert(m_touched && "Default context not inherited. Call Touch() to inherit one."); + Assert( + m_touched && + "Default context not inherited. Call Touch() to inherit one."); EventSupport::EmitEvent(event, EmitMode::Deffered, dueTime); } void PostSyncEvent(const EventType &event) { - Assert(m_touched && "Default context not inherited. Call Touch() to inherit one."); + Assert( + m_touched && + "Default context not inherited. Call Touch() to inherit one."); // Check calling context EventSupport::EmitEvent(event, EmitMode::Blocking); @@ -75,33 +78,36 @@ public: void SwitchToThread(Thread *thread) { - Assert(m_touched && "Default context not inherited. Call Touch() to inherit one."); + Assert( + m_touched && + "Default context not inherited. Call Touch() to inherit one."); EventSupport::SwitchListenerToThread(this, thread); } void Touch() { m_touched = true; - EventSupport::SwitchListenerToThread(this, Thread::GetCurrentThread()); + EventSupport::SwitchListenerToThread( + this, + Thread:: + GetCurrentThread()); } }; template -class Controller - : public Controller, - public ControllerEventHandler +class Controller : + public Controller, + public ControllerEventHandler { -public: + public: typedef typename EventTypeList::Head EventType; -public: + public: Controller() - { - } + {} virtual ~Controller() - { - } + {} virtual void SwitchToThread(Thread *thread) { @@ -119,14 +125,12 @@ public: template<> class Controller::Type> { -public: + public: Controller() - { - } + {} virtual ~Controller() - { - } + {} virtual void SwitchToThread(Thread *thread) { @@ -134,16 +138,23 @@ public: } virtual void Touch() - { - } + {} }; - } } // namespace DPL // Utilities -#define CONTROLLER_POST_EVENT(Name, EventArg) Name##Singleton::Instance().DPL::Event::ControllerEventHandler<__typeof__ EventArg>::PostEvent(EventArg) -#define CONTROLLER_POST_TIMED_EVENT(Name, EventArg, DueTime) Name##Singleton::Instance().DPL::Event::ControllerEventHandler<__typeof__ EventArg>::PostTimedEvent(EventArg, DueTime) -#define CONTROLLER_POST_SYNC_EVENT(Name, EventArg) Name##Singleton::Instance().DPL::Event::ControllerEventHandler<__typeof__ EventArg>::PostSyncEvent(EventArg) +#define CONTROLLER_POST_EVENT(Name, \ + EventArg) Name##Singleton::Instance().DPL::Event \ + ::ControllerEventHandler< \ + __typeof__ EventArg>::PostEvent(EventArg) +#define CONTROLLER_POST_TIMED_EVENT(Name, EventArg, \ + DueTime) Name##Singleton::Instance().DPL:: \ + Event::ControllerEventHandler< \ + __typeof__ EventArg>::PostTimedEvent(EventArg, DueTime) +#define CONTROLLER_POST_SYNC_EVENT(Name, \ + EventArg) Name##Singleton::Instance().DPL:: \ + Event::ControllerEventHandler< \ + __typeof__ EventArg>::PostSyncEvent(EventArg) #endif // DPL_CONTROLLER_H diff --git a/modules/event/include/dpl/event/event_listener.h b/modules/event/include/dpl/event/event_listener.h index bc7ecbf..27fdbec 100644 --- a/modules/event/include/dpl/event/event_listener.h +++ b/modules/event/include/dpl/event/event_listener.h @@ -24,27 +24,21 @@ #include -namespace DPL -{ -namespace Event -{ - +namespace DPL { +namespace Event { template -class EventListener - : private Noncopyable +class EventListener : + private Noncopyable { -public: + public: EventListener() - { - } + {} virtual ~EventListener() - { - } + {} virtual void OnEventReceived(const EventType &event) = 0; }; - } } // namespace DPL diff --git a/modules/event/include/dpl/event/event_support.h b/modules/event/include/dpl/event/event_support.h index 2e8cfb2..f7a8d8f 100644 --- a/modules/event/include/dpl/event/event_support.h +++ b/modules/event/include/dpl/event/event_support.h @@ -41,12 +41,9 @@ #include #include -namespace DPL -{ -namespace Event -{ -namespace EmitMode -{ +namespace DPL { +namespace Event { +namespace EmitMode { enum Type { Auto, ///< If calling thread is the same as receiver's use @@ -62,10 +59,10 @@ enum Type } // namespace EmitMode template -class EventSupport - : private Noncopyable +class EventSupport : + private Noncopyable { -public: + public: typedef EventSupport EventSupportType; typedef EventListener EventListenerType; @@ -74,10 +71,10 @@ public: class EventSupportData; // Forward declaration typedef EventSupportData *EventSupportDataPtr; -private: + private: typedef typename GenericEventCall:: template Rebind:: - Other GenericEventCallType; + Other GenericEventCallType; // Event listener list typedef std::map EventListenerList; @@ -103,10 +100,10 @@ private: // Events list mutex Mutex m_eventListMutex; -public: + public: class EventSupportData { - private: + private: typedef void (EventSupportType::*ReceiveAbstractEventCallMethod)( const EventType &event, EventListenerType *eventListener, @@ -123,22 +120,20 @@ public: Mutex m_dataMutex; - public: + public: EventSupportData(EventSupportType *support, ReceiveAbstractEventCallMethod method, - WaitableEvent *synchronization) - : m_eventSupport(support), - m_method(method), - m_synchronization(synchronization) - { - } + WaitableEvent *synchronization) : + m_eventSupport(support), + m_method(method), + m_synchronization(synchronization) + {} ~EventSupportData() { Mutex::ScopedLock lock(&m_dataMutex); - if (!m_eventSupport) - { + if (!m_eventSupport) { LogPedantic("EventSupport for this call does not exist"); return; } @@ -160,15 +155,12 @@ public: { Mutex::ScopedLock lock(&m_dataMutex); - if (m_eventSupport != NULL) - { + if (m_eventSupport != NULL) { (*m_eventSupport.*m_method)(event, listener, delegate, m_synchronization); - } - else - { + } else { LogPedantic("EventSupport for this call does not " "exist anymore. Ignored."); } @@ -190,7 +182,7 @@ public: } }; -private: + private: GenericEventCallType *RegisterEventCall(const EventType &event, EventListenerType *eventListener, DelegateType delegate, @@ -241,7 +233,7 @@ private: } UNHANDLED_EXCEPTION_HANDLER_END - --m_guardedCallInProgress; + -- m_guardedCallInProgress; LogPedantic("Guarded event listener finished"); } @@ -260,7 +252,7 @@ private: } UNHANDLED_EXCEPTION_HANDLER_END - --m_guardedCallInProgress; + -- m_guardedCallInProgress; LogPedantic("Guarded delegate call finished"); } @@ -275,44 +267,41 @@ private: Thread *targetThread; // Listener might have been removed, ensure that it still exits - if (eventListener != NULL) - { + if (eventListener != NULL) { Mutex::ScopedLock lock(&m_listenerDelegateMutex); typename EventListenerList::iterator iterator = m_eventListenerList.find(eventListener); - if (iterator == m_eventListenerList.end()) - { + if (iterator == m_eventListenerList.end()) { LogPedantic("Abstract event call listener disappeared." "Event ignored."); // Even though, synchronize caller if needed - if (synchronization != NULL) + if (synchronization != NULL) { synchronization->Signal(); + } return; } // Get target thread id targetThread = iterator->second; - } - else - { + } else { // Delegate might have been removed, ensure that it still exits Mutex::ScopedLock lock(&m_listenerDelegateMutex); typename DelegateList::iterator iterator = m_delegateList.find(delegate); - if (iterator == m_delegateList.end()) - { + if (iterator == m_delegateList.end()) { LogPedantic("Abstract event call delegate disappeared." "Event ignored."); // Even though, synchronize caller if needed - if (synchronization != NULL) + if (synchronization != NULL) { synchronization->Signal(); + } return; } @@ -322,22 +311,19 @@ private: } // Ensure that we are now in proper thread now - if (targetThread != Thread::GetCurrentThread()) - { + if (targetThread != Thread::GetCurrentThread()) { LogPedantic("Detected event dispatching ping-pong scenario"); // Retry if it was not synchronized - if (synchronization == NULL) - { + if (synchronization == NULL) { // Cheat with event delivery EmitEvent(event, EmitMode::Queued); LogPedantic("Ping-Pong: Resent as queued event"); - } - else - { + } else { // There is a problem - // Developer did something nasty, and we will not clean up his mess + // Developer did something nasty, and we will not clean up his + // mess synchronization->Signal(); LogPedantic("### Ping-Pong: Failed to deliver synchronized" @@ -348,17 +334,19 @@ private: } // Guard listener code for exceptions - if (eventListener != NULL) + if (eventListener != NULL) { GuardedEventCall(event, eventListener); - else + } else { GuardedEventCall(event, delegate); + } // Release caller if synchronizing - if (synchronization != NULL) + if (synchronization != NULL) { synchronization->Signal(); + } } -protected: + protected: void EmitEvent(const EventType &event, EmitMode::Type mode = EmitMode::Queued, double dueTime = 0.0) @@ -368,26 +356,25 @@ protected: new Mutex::ScopedLock(&m_listenerDelegateMutex)); // Show some info - switch (mode) - { - case EmitMode::Auto: - LogPedantic("Emitting AUTO event..."); - break; + switch (mode) { + case EmitMode::Auto: + LogPedantic("Emitting AUTO event..."); + break; - case EmitMode::Queued: - LogPedantic("Emitting QUEUED event..."); - break; + case EmitMode::Queued: + LogPedantic("Emitting QUEUED event..."); + break; - case EmitMode::Blocking: - LogPedantic("Emitting BLOCKING event..."); - break; + case EmitMode::Blocking: + LogPedantic("Emitting BLOCKING event..."); + break; - case EmitMode::Deffered: - LogPedantic("Emitting DEFFERED event..."); - break; + case EmitMode::Deffered: + LogPedantic("Emitting DEFFERED event..."); + break; - default: - break; + default: + break; } // In some configurations there is a barrier @@ -399,14 +386,11 @@ protected: // Switch to proper dispatcher and emit event AbstractEventDispatcher *dispatcher = NULL; - if (iterator->second == NULL) - { + if (iterator->second == NULL) { // Send to main thread LogPedantic("Sending event to main dispatcher"); dispatcher = &GetMainEventDispatcherInstance(); - } - else - { + } else { // Setup thread dispatcher, and send to proper thread LogPedantic("Sending event to thread dispatcher"); m_threadEventDispatcher.SetThread(iterator->second); @@ -417,66 +401,59 @@ protected: WaitableEvent *synchronization; // TODO: Pool synchronization objects - switch (mode) - { - case EmitMode::Auto: - // Check thread - if (iterator->second == Thread::GetCurrentThread()) - { - // Guard listener code for exceptions - GuardedEventCall(event, iterator->first); - } - else - { - // Handle non-synchronized event - dispatcher->AddEventCall( - RegisterEventCall(event, iterator->first, - DelegateType(), NULL)); - } - break; - - case EmitMode::Queued: + switch (mode) { + case EmitMode::Auto: + // Check thread + if (iterator->second == Thread::GetCurrentThread()) { + // Guard listener code for exceptions + GuardedEventCall(event, iterator->first); + } else { // Handle non-synchronized event dispatcher->AddEventCall( RegisterEventCall(event, iterator->first, DelegateType(), NULL)); + } + break; - break; - - case EmitMode::Blocking: - // Check thread - if (iterator->second == Thread::GetCurrentThread()) - { - // Guard listener code for exceptions - GuardedEventCall(event, iterator->first); - } - else - { - // New synchronization object is needed - synchronization = new WaitableEvent(); - - // Handle synchronized event - dispatcher->AddEventCall( - RegisterEventCall(event, iterator->first, - DelegateType(), synchronization)); - - // Add to barrier - synchronizationBarrier.push_back(synchronization); - } - break; - - case EmitMode::Deffered: - // Handle deffered events - Assert(dueTime >= 0.0 && "Due time must be non-negative"); - - dispatcher->AddTimedEventCall( + case EmitMode::Queued: + // Handle non-synchronized event + dispatcher->AddEventCall( + RegisterEventCall(event, iterator->first, + DelegateType(), NULL)); + + break; + + case EmitMode::Blocking: + // Check thread + if (iterator->second == Thread::GetCurrentThread()) { + // Guard listener code for exceptions + GuardedEventCall(event, iterator->first); + } else { + // New synchronization object is needed + synchronization = new WaitableEvent(); + + // Handle synchronized event + dispatcher->AddEventCall( RegisterEventCall(event, iterator->first, - DelegateType(), NULL), dueTime); + DelegateType(), synchronization)); + + // Add to barrier + synchronizationBarrier.push_back(synchronization); + } + break; + + case EmitMode::Deffered: + // Handle deffered events + Assert(dueTime >= 0.0 && "Due time must be non-negative"); - break; + dispatcher->AddTimedEventCall( + RegisterEventCall(event, iterator->first, + DelegateType(), NULL), dueTime); + + break; - default: - Assert("Invalid emit mode"); + default: + Assert("Invalid emit mode"); } } @@ -488,14 +465,11 @@ protected: // Switch to proper dispatcher and emit event AbstractEventDispatcher *dispatcher = NULL; - if (iterator->second == NULL) - { + if (iterator->second == NULL) { // Send to main thread LogPedantic("Sending event to main dispatcher"); dispatcher = &GetMainEventDispatcherInstance(); - } - else - { + } else { // Setup thread dispatcher, and send to proper thread LogPedantic("Sending event to thread dispatcher"); m_threadEventDispatcher.SetThread(iterator->second); @@ -506,82 +480,74 @@ protected: WaitableEvent *synchronization; // TODO: Pool synchronization objects - switch (mode) - { - case EmitMode::Auto: - // Check thread - if (iterator->second == Thread::GetCurrentThread()) - { - // Guard listener code for exceptions - GuardedEventCall(event, iterator->first); - } - else - { - // Handle non-synchronized event - dispatcher->AddEventCall( - RegisterEventCall(event, - NULL, - iterator->first, - NULL)); - } - break; - - case EmitMode::Queued: + switch (mode) { + case EmitMode::Auto: + // Check thread + if (iterator->second == Thread::GetCurrentThread()) { + // Guard listener code for exceptions + GuardedEventCall(event, iterator->first); + } else { // Handle non-synchronized event dispatcher->AddEventCall( RegisterEventCall(event, NULL, iterator->first, NULL)); + } + break; + + case EmitMode::Queued: + // Handle non-synchronized event + dispatcher->AddEventCall( + RegisterEventCall(event, + NULL, + iterator->first, + NULL)); - break; - - case EmitMode::Blocking: - // Check thread - if (iterator->second == Thread::GetCurrentThread()) - { - // Guard listener code for exceptions - GuardedEventCall(event, iterator->first); - } - else - { - // New synchronization object is needed - synchronization = new WaitableEvent(); - - // Handle synchronized event - dispatcher->AddEventCall( - RegisterEventCall(event, - NULL, - iterator->first, - synchronization)); - - // Add to barrier - synchronizationBarrier.push_back(synchronization); - } - break; - - case EmitMode::Deffered: - // Handle deffered events - Assert(dueTime >= 0.0 && "Due time must be non-negative"); - - dispatcher->AddTimedEventCall( + break; + + case EmitMode::Blocking: + // Check thread + if (iterator->second == Thread::GetCurrentThread()) { + // Guard listener code for exceptions + GuardedEventCall(event, iterator->first); + } else { + // New synchronization object is needed + synchronization = new WaitableEvent(); + + // Handle synchronized event + dispatcher->AddEventCall( RegisterEventCall(event, NULL, iterator->first, - NULL), dueTime); + synchronization)); + + // Add to barrier + synchronizationBarrier.push_back(synchronization); + } + break; + + case EmitMode::Deffered: + // Handle deffered events + Assert(dueTime >= 0.0 && "Due time must be non-negative"); + + dispatcher->AddTimedEventCall( + RegisterEventCall(event, + NULL, + iterator->first, + NULL), dueTime); - break; + break; - default: - Assert("Invalid emit mode"); + default: + Assert("Invalid emit mode"); } } LogPedantic("Added event to dispatchers"); // Leave listeners lock in case of blocking call - if (!synchronizationBarrier.empty()) - { + if (!synchronizationBarrier.empty()) { LogPedantic("Leaving lock due to existing barrier"); lock.reset(); } @@ -590,13 +556,12 @@ protected: // Synchronize with barrier // TODO: Implement generic WaitForAllMultipleHandles call - while (!synchronizationBarrier.empty()) - { + while (!synchronizationBarrier.empty()) { // Get barrier waitable handles WaitableHandleList barrierHandles; FOREACH(iterator, synchronizationBarrier) - barrierHandles.push_back((*iterator)->GetHandle()); + barrierHandles.push_back((*iterator)->GetHandle()); // Await more events WaitableHandleIndexList indexList = @@ -618,8 +583,9 @@ protected: FOREACH(iterator, synchronizationBarrier) { - if (*iterator == NULL) + if (*iterator == NULL) { continue; + } clearedSynchronizationBarrier.push_back(*iterator); } @@ -633,11 +599,10 @@ protected: LogPedantic("Event emitted"); } -public: - EventSupport() - : m_guardedCallInProgress(false) - { - } + public: + EventSupport() : + m_guardedCallInProgress(false) + {} virtual ~EventSupport() { @@ -773,15 +738,14 @@ public: // Switch all listeners and delegates FOREACH(iterator, m_eventListenerList) - iterator->second = thread; + iterator->second = thread; FOREACH(iterator, m_delegateList) - iterator->second = thread; + iterator->second = thread; LogPedantic("All listeners and delegates switched"); } }; - } } // namespace DPL diff --git a/modules/event/include/dpl/event/generic_event_call.h b/modules/event/include/dpl/event/generic_event_call.h index 7c0567c..77fea72 100644 --- a/modules/event/include/dpl/event/generic_event_call.h +++ b/modules/event/include/dpl/event/generic_event_call.h @@ -29,26 +29,23 @@ #include #include -namespace DPL -{ -namespace Event -{ - +namespace DPL { +namespace Event { template -class GenericEventCall - : public AbstractEventCall +class GenericEventCall : + public AbstractEventCall { -public: + public: typedef EventListener EventListenerType; typedef FastDelegate1 DelegateType; -protected: + protected: SupportDataType m_supportData; EventListenerType *m_eventListener; DelegateType m_delegate; EventType m_event; -public: + public: template struct Rebind { @@ -58,13 +55,12 @@ public: GenericEventCall(SupportDataType supportData, EventListenerType *eventListener, DelegateType delegate, - const EventType &event) - : m_supportData(supportData), - m_eventListener(eventListener), - m_delegate(delegate), - m_event(event) - { - } + const EventType &event) : + m_supportData(supportData), + m_eventListener(eventListener), + m_delegate(delegate), + m_event(event) + {} virtual ~GenericEventCall() { @@ -94,7 +90,6 @@ public: // from the event queue (not just marked "disabled") } }; - } } // namespace DPL diff --git a/modules/event/include/dpl/event/inter_context_delegate.h b/modules/event/include/dpl/event/inter_context_delegate.h index 78efd5f..260a6a4 100644 --- a/modules/event/include/dpl/event/inter_context_delegate.h +++ b/modules/event/include/dpl/event/inter_context_delegate.h @@ -69,15 +69,17 @@ namespace DPL { namespace Event { - //forward declaration template class ICDelegate; -namespace ICD{ +namespace ICD { // This Type defines whether ICDelegate should be destroyed after the call, or // could be reused later. -enum class Reuse{ Yes, No }; +enum class Reuse +{ + Yes, No +}; } namespace ICDPrivate { @@ -95,19 +97,16 @@ class ICDSharedDataBase public: explicit ScopedLock(ICDSharedDataBasePtr helperBase) : m_scopedLock(&helperBase->m_mutex) - { - } + {} private: DPL::RecursiveMutex::ScopedLock m_scopedLock; }; ICDSharedDataBase() : m_disabled(false) - { - } + {} virtual ~ICDSharedDataBase() - { - } + {} bool isDisabled() const { @@ -139,10 +138,9 @@ class DeleteICDSharedDataBaseEventCall : public DPL::Event::AbstractEventCall { public: DeleteICDSharedDataBaseEventCall( - ICDSharedDataBase::ICDSharedDataBasePtr helperBase) : + ICDSharedDataBase::ICDSharedDataBasePtr helperBase) : m_helperBase(helperBase) - { - } + {} virtual void Call() { m_helperBase.reset(); @@ -152,17 +150,16 @@ class DeleteICDSharedDataBaseEventCall : public DPL::Event::AbstractEventCall ICDSharedDataBase::ICDSharedDataBasePtr m_helperBase; }; - class ICDelegateSupportInterface { protected: virtual ~ICDelegateSupportInterface() - { - } + {} virtual void unregisterICDSharedData( - ICDPrivate::ICDSharedDataBase::ICDSharedDataBasePtr helper) = 0; + ICDPrivate::ICDSharedDataBase::ICDSharedDataBasePtr helper) = 0; virtual void registerICDSharedData( - ICDPrivate::ICDSharedDataBase::ICDSharedDataBasePtr helper) = 0; + ICDPrivate::ICDSharedDataBase::ICDSharedDataBasePtr helper) = 0; + private: template friend class DPL::Event::ICDelegate; @@ -173,7 +170,7 @@ class ICDelegateSupportInterface template FastDelegate makeDelegate(ThisType* This, - void (ThisType::*Func)(ArgTypesList ...)) + void (ThisType::*Func)(ArgTypesList ...)) { return FastDelegate(This, Func); } @@ -186,8 +183,7 @@ class ICDelegate { public: ICDelegate() - { - } + {} ICDelegate(ICDPrivate::ICDelegateSupportInterface* base, DPL::FastDelegate outerDelegate, ICD::Reuse reuse) @@ -231,11 +227,10 @@ class ICDelegate struct PrivateEvent { PrivateEvent(ICDSharedDataPtr a_helper, - ArgTypesList ... arguments) : + ArgTypesList ... arguments) : helper(a_helper), args(std::make_tuple(arguments ...)) - { - } + {} ICDSharedDataPtr helper; std::tuple args; @@ -307,8 +302,9 @@ class ICDelegate } else { DPL::Apply(m_outerDelegate, event.args); - if(m_reuse == ICD::Reuse::Yes) + if (m_reuse == ICD::Reuse::Yes) { return; + } disable(); deleteICDSharedDataBase(ptr); @@ -317,12 +313,13 @@ class ICDelegate }; // Schedules helper removal. - static void deleteICDSharedDataBase(ICDPrivate::ICDSharedDataBase::ICDSharedDataBasePtr helper) + static void deleteICDSharedDataBase( + ICDPrivate::ICDSharedDataBase::ICDSharedDataBasePtr helper) { using namespace ICDPrivate; ICDSharedDataBase::ScopedLock lock(helper); DeleteICDSharedDataBaseEventCall* event = - new DeleteICDSharedDataBaseEventCall(helper); + new DeleteICDSharedDataBaseEventCall(helper); if (DPL::Thread::GetCurrentThread() == NULL) { DPL::Event::GetMainEventDispatcherInstance().AddEventCall(event); } else { @@ -341,8 +338,8 @@ class ICDelegateSupport : public ICDPrivate::ICDelegateSupportInterface protected: template ICDelegate makeICDelegate( - void (ThisType::*Func)(ArgTypesList ...), - ICD::Reuse reuse = ICD::Reuse::No) + void (ThisType::*Func)(ArgTypesList ...), + ICD::Reuse reuse = ICD::Reuse::No) { ThisType* This = static_cast(this); ICDelegate icdelegate( @@ -354,8 +351,7 @@ class ICDelegateSupport : public ICDPrivate::ICDelegateSupportInterface } ICDelegateSupport() - { - } + {} ~ICDelegateSupport() { @@ -371,13 +367,13 @@ class ICDelegateSupport : public ICDPrivate::ICDelegateSupportInterface private: virtual void unregisterICDSharedData( - ICDPrivate::ICDSharedDataBase::ICDSharedDataBasePtr helper) + ICDPrivate::ICDSharedDataBase::ICDSharedDataBasePtr helper) { m_ICDSharedDatas.erase(helper->getIterator()); } virtual void registerICDSharedData( - ICDPrivate::ICDSharedDataBase::ICDSharedDataBasePtr helper) + ICDPrivate::ICDSharedDataBase::ICDSharedDataBasePtr helper) { helper->setIterator( m_ICDSharedDatas.insert(m_ICDSharedDatas.begin(), @@ -387,7 +383,6 @@ class ICDelegateSupport : public ICDPrivate::ICDelegateSupportInterface private: ICDPrivate::ICDSharedDataBase::ICDSharedDataBaseList m_ICDSharedDatas; }; - } } //namespace diff --git a/modules/event/include/dpl/event/main_event_dispatcher.h b/modules/event/include/dpl/event/main_event_dispatcher.h index 7bfabad..db86b1f 100644 --- a/modules/event/include/dpl/event/main_event_dispatcher.h +++ b/modules/event/include/dpl/event/main_event_dispatcher.h @@ -17,7 +17,8 @@ * @file main_event_dispatcher.h * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) * @version 1.0 - * @brief This file is the implementation file of main event dispatcher for EFL + * @brief This file is the implementation file of main event dispatcher + * for EFL */ #ifndef DPL_MAIN_EVENT_DISPATCHER_H #define DPL_MAIN_EVENT_DISPATCHER_H @@ -31,25 +32,22 @@ #include #include -namespace DPL +namespace DPL { +namespace Event { +class MainEventDispatcher : + public AbstractEventDispatcher { -namespace Event -{ - -class MainEventDispatcher - : public AbstractEventDispatcher -{ -public: + public: class Exception { - public: + public: DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) DECLARE_EXCEPTION_TYPE(Base, CreateFailed) DECLARE_EXCEPTION_TYPE(Base, AddEventFailed) DECLARE_EXCEPTION_TYPE(Base, AddTimedEventFailed) }; -protected: + protected: struct WrappedEventCall { AbstractEventCall *abstractEventCall; @@ -58,12 +56,11 @@ protected: WrappedEventCall(AbstractEventCall *abstractEventCallArg, bool timedArg, - double dueTimeArg) - : abstractEventCall(abstractEventCallArg), - timed(timedArg), - dueTime(dueTimeArg) - { - } + double dueTimeArg) : + abstractEventCall(abstractEventCallArg), + timed(timedArg), + dueTime(dueTimeArg) + {} }; typedef std::list WrappedEventCallList; @@ -85,36 +82,38 @@ protected: MainEventDispatcher *This; TimedEventStruct(AbstractEventCall *abstractEventCallArg, - MainEventDispatcher *ThisArg) - : abstractEventCall(abstractEventCallArg), - This(ThisArg) - { - } + MainEventDispatcher *ThisArg) : + abstractEventCall(abstractEventCallArg), + This(ThisArg) + {} }; - void InternalAddEvent(AbstractEventCall *abstractEventCall, bool timed, double dueTime); + void InternalAddEvent(AbstractEventCall *abstractEventCall, + bool timed, + double dueTime); static void StaticDeleteEvent(void *data, void *event); static Eina_Bool StaticDispatchEvent(void *data, int type, void *event); static Eina_Bool StaticDispatchTimedEvent(void *event); - static Eina_Bool StaticDispatchCrossInvoker(void *data, Ecore_Fd_Handler *fd_handler); + static Eina_Bool StaticDispatchCrossInvoker(void *data, + Ecore_Fd_Handler *fd_handler); void DeleteEvent(AbstractEventCall *abstractEventCall); void DispatchEvent(AbstractEventCall *abstractEventCall); void DispatchTimedEvent(AbstractEventCall *abstractEventCall); void DispatchCrossInvoker(); -public: + public: explicit MainEventDispatcher(); virtual ~MainEventDispatcher(); virtual void AddEventCall(AbstractEventCall *abstractEventCall); - virtual void AddTimedEventCall(AbstractEventCall *abstractEventCall, double dueTime); + virtual void AddTimedEventCall(AbstractEventCall *abstractEventCall, + double dueTime); virtual void ResetCrossEventCallHandler(); }; MainEventDispatcher& GetMainEventDispatcherInstance(); - } } // namespace DPL diff --git a/modules/event/include/dpl/event/model.h b/modules/event/include/dpl/event/model.h index 07c0340..b149eee 100644 --- a/modules/event/include/dpl/event/model.h +++ b/modules/event/include/dpl/event/model.h @@ -25,15 +25,12 @@ #include #include -namespace DPL +namespace DPL { +namespace Event { +class Model : + public Noncopyable { -namespace Event -{ - -class Model - : public Noncopyable -{ -protected: + protected: mutable DPL::ReadWriteMutex m_mutex; template @@ -42,10 +39,9 @@ protected: template friend class Property; -public: + public: virtual ~Model() = 0; }; - } } // namespace DPL diff --git a/modules/event/include/dpl/event/model_bind_to_dao.h b/modules/event/include/dpl/event/model_bind_to_dao.h index 51473e8..2ed7e0e 100644 --- a/modules/event/include/dpl/event/model_bind_to_dao.h +++ b/modules/event/include/dpl/event/model_bind_to_dao.h @@ -23,11 +23,8 @@ #ifndef DPL_MODEL_BIND_TO_DAO_H_ #define DPL_MODEL_BIND_TO_DAO_H_ -namespace DPL -{ -namespace Event -{ - +namespace DPL { +namespace Event { /** * @param ObjectType type of object used as delegate argument * @param RetType Type returned from the external function @@ -70,7 +67,6 @@ struct BindToDAO return (extObject.*externalGetter)(); } }; - } } diff --git a/modules/event/include/dpl/event/property.h b/modules/event/include/dpl/event/property.h index 2817007..cb88431 100644 --- a/modules/event/include/dpl/event/property.h +++ b/modules/event/include/dpl/event/property.h @@ -30,11 +30,8 @@ #include #include -namespace DPL -{ -namespace Event -{ - +namespace DPL { +namespace Event { /** * Property is a class that encapsulates model's property fields. * Its main purpose is to automate things related to model's properties @@ -205,15 +202,13 @@ struct PropertyStorageDynamicCached {}; ///< Use dynamic then cache struct PropertyReadOnly {}; ///< Read only, not setter available struct PropertyReadWrite {}; ///< Read and write - template struct PropertyEvent { - PropertyEvent(const Type &v, Model *s) - : value(v), - sender(s) - { - } + PropertyEvent(const Type &v, Model *s) : + value(v), + sender(s) + {} Type value; Model *sender; @@ -222,36 +217,33 @@ struct PropertyEvent template class PropertyStorageMethodDynamicBase { -protected: + protected: ReadDelegateType m_readValue; WriteDelegateType m_writeValue; PropertyStorageMethodDynamicBase(ReadDelegateType readValue, - WriteDelegateType writeValue) - : m_readValue(readValue), - m_writeValue(writeValue) - { - } + WriteDelegateType writeValue) : + m_readValue(readValue), + m_writeValue(writeValue) + {} }; template class PropertyStorageMethodCachedBase { -protected: + protected: mutable Type m_value; PropertyStorageMethodCachedBase() - { - } + {} }; class PropertyStorageMethodBase { -protected: - explicit PropertyStorageMethodBase(Model *model) - : m_model(model) - { - } + protected: + explicit PropertyStorageMethodBase(Model *model) : + m_model(model) + {} Model *m_model; }; @@ -268,17 +260,16 @@ template - : protected PropertyStorageMethodBase, - protected PropertyStorageMethodCachedBase + WriteDelegateType>: + protected PropertyStorageMethodBase, + protected PropertyStorageMethodCachedBase { -public: + public: PropertyStorageMethod(Model *model, ReadDelegateType /*readValue*/, - WriteDelegateType /*writeValue*/) - : PropertyStorageMethodBase(model) - { - } + WriteDelegateType /*writeValue*/) : + PropertyStorageMethodBase(model) + {} Type Get() const { @@ -295,21 +286,20 @@ template class PropertyStorageMethod - : protected PropertyStorageMethodBase, - protected PropertyStorageMethodDynamicBase + WriteDelegateType>: + protected PropertyStorageMethodBase, + protected PropertyStorageMethodDynamicBase { -public: + public: PropertyStorageMethod(Model *model, ReadDelegateType readValue, - WriteDelegateType writeValue) - : PropertyStorageMethodBase(model), - PropertyStorageMethodDynamicBase( - readValue, - writeValue) - { - } + WriteDelegateType writeValue) : + PropertyStorageMethodBase(model), + PropertyStorageMethodDynamicBase( + readValue, + writeValue) + {} Type Get() const { @@ -328,13 +318,13 @@ template class PropertyStorageMethod - : protected PropertyStorageMethodBase, - protected PropertyStorageMethodDynamicBase, - protected PropertyStorageMethodCachedBase + WriteDelegateType>: + protected PropertyStorageMethodBase, + protected PropertyStorageMethodDynamicBase, + protected PropertyStorageMethodCachedBase { -private: + private: typedef PropertyStorageMethod( - readValue, writeValue) - { - } + WriteDelegateType writeValue) : + PropertyStorageMethodBase(model), + PropertyStorageMethodDynamicBase( + readValue, writeValue) + {} Type Get() const { @@ -381,23 +369,23 @@ public: }; template -class PropertyBase - : protected EventSupport > +class PropertyBase : + protected EventSupport > { -public: + public: typedef typename EventSupport >::EventListenerType - EventListenerType; + EventListenerType; typedef typename EventSupport >::DelegateType - DelegateType; + DelegateType; - typedef FastDelegate - ReadDelegateType; + typedef FastDelegate + ReadDelegateType; typedef FastDelegate - WriteDelegateType; + WriteDelegateType; -protected: + protected: PropertyStorageMethodm_mutex); @@ -436,68 +423,66 @@ template -class Property - : public PropertyBase +class Property: + public PropertyBase { -public: + public: typedef typename PropertyBase::EventListenerType - EventListenerType; + EventListenerType; typedef typename PropertyBase::DelegateType - DelegateType; + DelegateType; typedef typename PropertyBase::ReadDelegateType - ReadDelegateType; + ReadDelegateType; typedef typename PropertyBase::WriteDelegateType - WriteDelegateType; + WriteDelegateType; -public: + public: explicit Property(Model *model, - ReadDelegateType readValue = NULL) - : PropertyBase(model, readValue, NULL) - { - } + ReadDelegateType readValue = NULL) : + PropertyBase(model, readValue, NULL) + {} Property(Model *model, const Type &value, - ReadDelegateType readValue = NULL) - : PropertyBase(model, readValue, NULL) + ReadDelegateType readValue = NULL) : + PropertyBase(model, readValue, NULL) { this->m_storage.Set(value); } }; template -class Property - : public PropertyBase +class Property: + public PropertyBase { -public: + public: typedef typename PropertyBase::EventListenerType - EventListenerType; + EventListenerType; typedef typename PropertyBase::DelegateType - DelegateType; + DelegateType; typedef typename PropertyBase::ReadDelegateType - ReadDelegateType; + ReadDelegateType; typedef typename PropertyBase::WriteDelegateType - WriteDelegateType; + WriteDelegateType; -public: + public: explicit Property(Model *model, - ReadDelegateType readValue = NULL, - WriteDelegateType writeValue = NULL) - : PropertyBase(model, readValue, writeValue) - { - } + ReadDelegateType readValue = NULL, + WriteDelegateType writeValue = NULL) : + PropertyBase(model, readValue, writeValue) + {} Property(Model *model, const Type &value, ReadDelegateType readValue = NULL, - WriteDelegateType writeValue = NULL) - : PropertyBase(model, readValue, writeValue) + WriteDelegateType writeValue = NULL) : + PropertyBase(model, readValue, writeValue) { this->m_storage.Set(value); } @@ -506,24 +491,25 @@ public: { ReadWriteMutex::ScopedWriteLock lock(&this->m_model->m_mutex); - if (this->m_storage.Get() == value) + if (this->m_storage.Get() == value) { return; + } this->m_storage.Set(value); this->EmitEvent(PropertyEvent(value, this->m_model), - EmitMode::Auto); + EmitMode::Auto); } void SetWithoutLock(const Type &value) { - if (this->m_storage.Get() == value) + if (this->m_storage.Get() == value) { return; + } this->m_storage.Set(value); } }; - } } // namespace DPL diff --git a/modules/event/include/dpl/event/thread_event_dispatcher.h b/modules/event/include/dpl/event/thread_event_dispatcher.h index e5e81a4..f3846a6 100644 --- a/modules/event/include/dpl/event/thread_event_dispatcher.h +++ b/modules/event/include/dpl/event/thread_event_dispatcher.h @@ -26,15 +26,12 @@ #include #include -namespace DPL +namespace DPL { +namespace Event { +class ThreadEventDispatcher : + public AbstractEventDispatcher { -namespace Event -{ - -class ThreadEventDispatcher - : public AbstractEventDispatcher -{ -protected: + protected: Thread *m_thread; static void StaticEventDelete(void *event, void *userParam); @@ -43,16 +40,16 @@ protected: void EventDelete(AbstractEventCall *abstractEventCall); void EventDispatch(AbstractEventCall *abstractEventCall); -public: + public: explicit ThreadEventDispatcher(); virtual ~ThreadEventDispatcher(); void SetThread(Thread *thread); virtual void AddEventCall(AbstractEventCall *abstractEventCall); - virtual void AddTimedEventCall(AbstractEventCall *abstractEventCall, double dueTime); + virtual void AddTimedEventCall(AbstractEventCall *abstractEventCall, + double dueTime); }; - } } // namespace DPL diff --git a/modules/event/src/abstract_event_call.cpp b/modules/event/src/abstract_event_call.cpp index 2bd0d11..748b6da 100644 --- a/modules/event/src/abstract_event_call.cpp +++ b/modules/event/src/abstract_event_call.cpp @@ -22,18 +22,12 @@ #include #include -namespace DPL -{ -namespace Event -{ - +namespace DPL { +namespace Event { AbstractEventCall::AbstractEventCall() -{ -} +{} AbstractEventCall::~AbstractEventCall() -{ -} - +{} } } // namespace DPL diff --git a/modules/event/src/abstract_event_dispatcher.cpp b/modules/event/src/abstract_event_dispatcher.cpp index a3e6317..7c385a4 100644 --- a/modules/event/src/abstract_event_dispatcher.cpp +++ b/modules/event/src/abstract_event_dispatcher.cpp @@ -17,23 +17,18 @@ * @file abstract_event_dispatcher.cpp * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) * @version 1.0 - * @brief This file is the implementation file of abstract event dispatcher + * @brief This file is the implementation file of abstract event + * dispatcher */ #include #include -namespace DPL -{ -namespace Event -{ - +namespace DPL { +namespace Event { AbstractEventDispatcher::AbstractEventDispatcher() -{ -} +{} AbstractEventDispatcher::~AbstractEventDispatcher() -{ -} - +{} } } // namespace DPL diff --git a/modules/event/src/event_support.cpp b/modules/event/src/event_support.cpp index 73cdea3..d2e643c 100644 --- a/modules/event/src/event_support.cpp +++ b/modules/event/src/event_support.cpp @@ -22,11 +22,8 @@ #include #include -namespace DPL -{ -namespace Event -{ - +namespace DPL { +namespace Event { namespace // anonymous { int dummyInitializerProc() @@ -36,9 +33,7 @@ int dummyInitializerProc() } int g_dummyInitializer = dummyInitializerProc(); - } // namespace anonymous - } } // namespace DPL diff --git a/modules/event/src/main_event_dispatcher.cpp b/modules/event/src/main_event_dispatcher.cpp index ae1107d..c860398 100644 --- a/modules/event/src/main_event_dispatcher.cpp +++ b/modules/event/src/main_event_dispatcher.cpp @@ -17,7 +17,8 @@ * @file main_event_dispatcher.cpp * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) * @version 1.0 - * @brief This file is the implementation file of main event dispatcher for EFL + * @brief This file is the implementation file of main event dispatcher + * for EFL */ #include #include @@ -25,14 +26,10 @@ #include #include -namespace DPL -{ - +namespace DPL { IMPLEMENT_SINGLETON(Event::MainEventDispatcher) -namespace Event -{ - +namespace Event { typedef Singleton MainEventDispatcherSingleton; namespace // anonymous @@ -61,17 +58,29 @@ MainEventDispatcher::MainEventDispatcher() LogPedantic("ECORE event class registered: " << m_eventId); // Register event class handler - if ((m_eventCallHandler = ecore_event_handler_add(m_eventId, &StaticDispatchEvent, this)) == NULL) + if ((m_eventCallHandler = + ecore_event_handler_add(m_eventId, &StaticDispatchEvent, + this)) == NULL) + { ThrowMsg(Exception::CreateFailed, "Failed to register event handler!"); + } // Allocate WaitableEvent m_crossEventCallInvoker = new WaitableEvent(); // Register cross event handler - m_crossEventCallHandler = ecore_main_fd_handler_add(m_crossEventCallInvoker->GetHandle(), ECORE_FD_READ, &StaticDispatchCrossInvoker, this, NULL, NULL); + m_crossEventCallHandler = ecore_main_fd_handler_add( + m_crossEventCallInvoker->GetHandle(), + ECORE_FD_READ, + &StaticDispatchCrossInvoker, + this, + NULL, + NULL); - if (m_crossEventCallHandler == NULL) - ThrowMsg(Exception::CreateFailed, "Failed to register cross event handler!"); + if (m_crossEventCallHandler == NULL) { + ThrowMsg(Exception::CreateFailed, + "Failed to register cross event handler!"); + } LogPedantic("ECORE cross-event handler registered"); } @@ -121,7 +130,8 @@ void MainEventDispatcher::ResetCrossEventCallHandler() NULL); if (m_crossEventCallHandler == NULL) { - ThrowMsg(Exception::CreateFailed, "Failed to register cross event handler!"); + ThrowMsg(Exception::CreateFailed, + "Failed to register cross event handler!"); } LogPedantic("ECORE cross-event handler re-registered"); @@ -132,41 +142,39 @@ void MainEventDispatcher::StaticDeleteEvent(void *data, void *event) LogPedantic("Static ECORE delete event handler"); MainEventDispatcher *This = static_cast(data); - AbstractEventCall *abstractEventCall = static_cast(event); + AbstractEventCall *abstractEventCall = + static_cast(event); Assert(This != NULL); Assert(abstractEventCall != NULL); // Late EFL event handling - if (g_lateMainEventDispatcher == NULL) - { + if (g_lateMainEventDispatcher == NULL) { LogPedantic("WARNING: Late EFL event delete!"); delete abstractEventCall; - } - else - { + } else { This->DeleteEvent(abstractEventCall); } } -Eina_Bool MainEventDispatcher::StaticDispatchEvent(void *data, int type, void *event) +Eina_Bool MainEventDispatcher::StaticDispatchEvent(void *data, + int type, + void *event) { LogPedantic("Static ECORE dispatch event"); MainEventDispatcher *This = static_cast(data); - AbstractEventCall *abstractEventCall = static_cast(event); + AbstractEventCall *abstractEventCall = + static_cast(event); (void)type; Assert(This != NULL); Assert(abstractEventCall != NULL); // Late EFL event handling - if (g_lateMainEventDispatcher == NULL) - { + if (g_lateMainEventDispatcher == NULL) { LogPedantic("WARNING: Late EFL event dispatch!"); - } - else - { + } else { This->DispatchEvent(abstractEventCall); } @@ -187,26 +195,27 @@ Eina_Bool MainEventDispatcher::StaticDispatchTimedEvent(void *data) Assert(abstractEventCall != NULL); // Late EFL event handling - if (g_lateMainEventDispatcher == NULL) - { + if (g_lateMainEventDispatcher == NULL) { LogPedantic("WARNING: Late EFL timed event dispatch!"); - } - else - { + } else { // Dispatch timed event This->DispatchEvent(abstractEventCall); } // And delete manually event, because ECORE does not // use delete handler for timers - StaticDeleteEvent(static_cast(This), static_cast(abstractEventCall)); + StaticDeleteEvent(static_cast(This), + static_cast(abstractEventCall)); // Do not continue timed event handlers // This also releases ECORE timer return ECORE_CALLBACK_CANCEL; } -Eina_Bool MainEventDispatcher::StaticDispatchCrossInvoker(void *data, Ecore_Fd_Handler *fd_handler) +Eina_Bool MainEventDispatcher::StaticDispatchCrossInvoker( + void *data, + Ecore_Fd_Handler * + fd_handler) { LogPedantic("Static ECORE dispatch cross invoker"); @@ -216,12 +225,9 @@ Eina_Bool MainEventDispatcher::StaticDispatchCrossInvoker(void *data, Ecore_Fd_H Assert(This != NULL); // Late EFL event handling - if (g_lateMainEventDispatcher == NULL) - { + if (g_lateMainEventDispatcher == NULL) { LogPedantic("WARNING: Late EFL cross invoker dispatch!"); - } - else - { + } else { This->DispatchCrossInvoker(); } @@ -242,7 +248,8 @@ void MainEventDispatcher::DispatchEvent(AbstractEventCall *abstractEventCall) abstractEventCall->Call(); } -void MainEventDispatcher::DispatchTimedEvent(AbstractEventCall *abstractEventCall) +void MainEventDispatcher::DispatchTimedEvent( + AbstractEventCall *abstractEventCall) { LogPedantic("ECORE dispatch timed event"); @@ -264,16 +271,22 @@ void MainEventDispatcher::DispatchCrossInvoker() m_wrappedCrossEventCallList.swap(stolenCrossEvents); } - LogPedantic("Cross-thread event list stolen. Number of events: " << stolenCrossEvents.size()); + LogPedantic( + "Cross-thread event list stolen. Number of events: " << + stolenCrossEvents.size()); // Repush all stolen events WrappedEventCallList::const_iterator eventIterator; - for (eventIterator = stolenCrossEvents.begin(); eventIterator != stolenCrossEvents.end(); ++eventIterator) + for (eventIterator = stolenCrossEvents.begin(); + eventIterator != stolenCrossEvents.end(); + ++eventIterator) { // Unwrap events LogPedantic("Dispatching event from invoker"); - InternalAddEvent(eventIterator->abstractEventCall, eventIterator->timed, eventIterator->dueTime); + InternalAddEvent(eventIterator->abstractEventCall, + eventIterator->timed, + eventIterator->dueTime); } LogPedantic("Cross-thread events dispatched"); @@ -281,19 +294,18 @@ void MainEventDispatcher::DispatchCrossInvoker() void MainEventDispatcher::AddEventCall(AbstractEventCall *abstractEventCall) { - if (pthread_equal(pthread_self(), g_threadMain)) - { + if (pthread_equal(pthread_self(), g_threadMain)) { LogPedantic("Main thread ECORE event push"); InternalAddEvent(abstractEventCall, false, 0.0); - } - else - { + } else { LogPedantic("Cross-thread ECORE event push"); // Push event to cross event list { Mutex::ScopedLock lock(&m_crossEventCallMutex); - m_wrappedCrossEventCallList.push_back(WrappedEventCall(abstractEventCall, false, 0.0)); + m_wrappedCrossEventCallList.push_back(WrappedEventCall( + abstractEventCall, false, + 0.0)); m_crossEventCallInvoker->Signal(); } @@ -301,21 +313,22 @@ void MainEventDispatcher::AddEventCall(AbstractEventCall *abstractEventCall) } } -void MainEventDispatcher::AddTimedEventCall(AbstractEventCall *abstractEventCall, double dueTime) +void MainEventDispatcher::AddTimedEventCall( + AbstractEventCall *abstractEventCall, + double dueTime) { - if (pthread_equal(pthread_self(), g_threadMain)) - { + if (pthread_equal(pthread_self(), g_threadMain)) { LogPedantic("Main thread timed ECORE event push"); InternalAddEvent(abstractEventCall, true, dueTime); - } - else - { + } else { LogPedantic("Cross-thread timed ECORE event push"); // Push event to cross event list { Mutex::ScopedLock lock(&m_crossEventCallMutex); - m_wrappedCrossEventCallList.push_back(WrappedEventCall(abstractEventCall, true, dueTime)); + m_wrappedCrossEventCallList.push_back(WrappedEventCall( + abstractEventCall, true, + dueTime)); m_crossEventCallInvoker->Signal(); } @@ -323,32 +336,36 @@ void MainEventDispatcher::AddTimedEventCall(AbstractEventCall *abstractEventCall } } -void MainEventDispatcher::InternalAddEvent(AbstractEventCall *abstractEventCall, bool timed, double dueTime) +void MainEventDispatcher::InternalAddEvent(AbstractEventCall *abstractEventCall, + bool timed, + double dueTime) { LogPedantic("Adding base event"); - if (timed == true) - { + if (timed == true) { // Push timed event onto ecore stack - TimedEventStruct* eventData = new TimedEventStruct(abstractEventCall, this); - Ecore_Timer *timedEvent = ecore_timer_add(dueTime, &StaticDispatchTimedEvent, eventData); + TimedEventStruct* eventData = new TimedEventStruct(abstractEventCall, + this); + Ecore_Timer *timedEvent = ecore_timer_add(dueTime, + &StaticDispatchTimedEvent, + eventData); - if (timedEvent == NULL) - { + if (timedEvent == NULL) { delete eventData; delete abstractEventCall; - ThrowMsg(Exception::AddTimedEventFailed, "Failed to add ECORE timed event"); + ThrowMsg(Exception::AddTimedEventFailed, + "Failed to add ECORE timed event"); } LogPedantic("Timed wrapped event added"); - } - else - { + } else { // Push immediate event onto ecore stack - Ecore_Event *event = ecore_event_add(m_eventId, abstractEventCall, &StaticDeleteEvent, this); + Ecore_Event *event = ecore_event_add(m_eventId, + abstractEventCall, + &StaticDeleteEvent, + this); - if (event == NULL) - { + if (event == NULL) { delete abstractEventCall; ThrowMsg(Exception::AddEventFailed, "Failed to add ECORE event"); } @@ -361,6 +378,5 @@ MainEventDispatcher& GetMainEventDispatcherInstance() { return MainEventDispatcherSingleton::Instance(); } - } } // namespace DPL diff --git a/modules/event/src/model.cpp b/modules/event/src/model.cpp index 4f6f86e..58e9a1b 100644 --- a/modules/event/src/model.cpp +++ b/modules/event/src/model.cpp @@ -22,12 +22,9 @@ #include #include -namespace DPL -{ -namespace Event -{ +namespace DPL { +namespace Event { Model::~Model() -{ -} +{} } } // namespace DPL diff --git a/modules/event/src/thread_event_dispatcher.cpp b/modules/event/src/thread_event_dispatcher.cpp index 31aee44..7da99a2 100644 --- a/modules/event/src/thread_event_dispatcher.cpp +++ b/modules/event/src/thread_event_dispatcher.cpp @@ -24,19 +24,14 @@ #include #include -namespace DPL -{ -namespace Event -{ - -ThreadEventDispatcher::ThreadEventDispatcher() - : m_thread(NULL) -{ -} +namespace DPL { +namespace Event { +ThreadEventDispatcher::ThreadEventDispatcher() : + m_thread(NULL) +{} ThreadEventDispatcher::~ThreadEventDispatcher() -{ -} +{} void ThreadEventDispatcher::SetThread(Thread *thread) { @@ -45,8 +40,10 @@ void ThreadEventDispatcher::SetThread(Thread *thread) void ThreadEventDispatcher::StaticEventDelete(void *event, void *userParam) { - AbstractEventCall *abstractEventCall = static_cast(event); - ThreadEventDispatcher *This = static_cast(userParam); + AbstractEventCall *abstractEventCall = + static_cast(event); + ThreadEventDispatcher *This = + static_cast(userParam); LogPedantic("Received static event delete from thread"); @@ -58,8 +55,10 @@ void ThreadEventDispatcher::StaticEventDelete(void *event, void *userParam) void ThreadEventDispatcher::StaticEventDispatch(void *event, void *userParam) { - AbstractEventCall *abstractEventCall = static_cast(event); - ThreadEventDispatcher *This = static_cast(userParam); + AbstractEventCall *abstractEventCall = + static_cast(event); + ThreadEventDispatcher *This = + static_cast(userParam); LogPedantic("Received static event dispatch from thread"); @@ -89,10 +88,15 @@ void ThreadEventDispatcher::AddEventCall(AbstractEventCall *abstractEventCall) LogPedantic("Adding event to thread event loop"); // Call abstract event call in dedicated thread - m_thread->PushEvent(abstractEventCall, &StaticEventDispatch, &StaticEventDelete, this); + m_thread->PushEvent(abstractEventCall, + &StaticEventDispatch, + &StaticEventDelete, + this); } -void ThreadEventDispatcher::AddTimedEventCall(AbstractEventCall *abstractEventCall, double dueTime) +void ThreadEventDispatcher::AddTimedEventCall( + AbstractEventCall *abstractEventCall, + double dueTime) { // Thread must be set prior to call Assert(m_thread != NULL); @@ -100,8 +104,11 @@ void ThreadEventDispatcher::AddTimedEventCall(AbstractEventCall *abstractEventCa LogPedantic("Adding timed event to thread event loop"); // Call abstract event call in dedicated thread - m_thread->PushTimedEvent(abstractEventCall, dueTime, &StaticEventDispatch, &StaticEventDelete, this); + m_thread->PushTimedEvent(abstractEventCall, + dueTime, + &StaticEventDispatch, + &StaticEventDelete, + this); } - } } // namespace DPL diff --git a/modules/localization/include/LanguageTagsProvider.h b/modules/localization/include/LanguageTagsProvider.h index bb3e48c..529101f 100644 --- a/modules/localization/include/LanguageTagsProvider.h +++ b/modules/localization/include/LanguageTagsProvider.h @@ -29,9 +29,9 @@ typedef std::list LanguageTags; -class LanguageTagsProvider { - -public: +class LanguageTagsProvider +{ + public: /* * Get list of currently set language tags */ @@ -40,7 +40,7 @@ public: /* * Set new language tags (other than based on system locales) */ - void setLanguageTags(const LanguageTags& taglist ); + void setLanguageTags(const LanguageTags& taglist); /* * Set language tags from given locales. @@ -70,11 +70,12 @@ public: static DPL::String BCP47LanguageTagToLocale(const DPL::String&); /* - * Function converts locales string (i.e. en_US.UTF-8) into language tag (i.e. en-US) + * Function converts locales string (i.e. en_US.UTF-8) into language tag + * (i.e. en-US) */ static DPL::String LocaleToBCP47LanguageTag(const DPL::String&); -private: + private: friend class DPL::Singleton; LanguageTags m_languageTagsList; diff --git a/modules/localization/include/dpl/localization/localization_utils.h b/modules/localization/include/dpl/localization/localization_utils.h index f971f93..66a232d 100644 --- a/modules/localization/include/dpl/localization/localization_utils.h +++ b/modules/localization/include/dpl/localization/localization_utils.h @@ -39,8 +39,7 @@ struct WidgetIcon WidgetIcon() : width(DPL::Optional::Null), height(DPL::Optional::Null) - { - } + {} /* * a valid URI to an image file inside the widget package that represents an diff --git a/modules/localization/include/dpl/localization/w3c_file_localization.h b/modules/localization/include/dpl/localization/w3c_file_localization.h index e0e5737..4f6aa1d 100644 --- a/modules/localization/include/dpl/localization/w3c_file_localization.h +++ b/modules/localization/include/dpl/localization/w3c_file_localization.h @@ -36,24 +36,24 @@ namespace W3CFileLocalization { typedef std::list WidgetIconList; DPL::Optional getFilePathInWidgetPackageFromUrl( - WrtDB::DbWidgetHandle widgetHandle, - const DPL::String &url); + WrtDB::DbWidgetHandle widgetHandle, + const DPL::String &url); DPL::Optional getFilePathInWidgetPackageFromUrl( - const WrtDB::WidgetPkgName &pkgname, - const DPL::String &url); + const WrtDB::WidgetPkgName &pkgname, + const DPL::String &url); DPL::Optional getFilePathInWidgetPackageFromUrl( - WrtDB::WidgetDAOReadOnlyPtr dao, - const DPL::String &url); + WrtDB::WidgetDAOReadOnlyPtr dao, + const DPL::String &url); DPL::Optional getFilePathInWidgetPackage( - WrtDB::DbWidgetHandle widgetHandle, - const DPL::String& file); + WrtDB::DbWidgetHandle widgetHandle, + const DPL::String& file); DPL::Optional getFilePathInWidgetPackage( - const WrtDB::WidgetPkgName &pkgname, - const DPL::String& file); + const WrtDB::WidgetPkgName &pkgname, + const DPL::String& file); DPL::Optional getFilePathInWidgetPackage( - WrtDB::WidgetDAOReadOnlyPtr dao, - const DPL::String& file); + WrtDB::WidgetDAOReadOnlyPtr dao, + const DPL::String& file); DPL::OptionalString getStartFile(WrtDB::DbWidgetHandle handle); DPL::OptionalString getStartFile(const WrtDB::WidgetPkgName & pkgname); @@ -64,21 +64,22 @@ OptionalWidgetIcon getIcon(const WrtDB::WidgetPkgName & pkgname); OptionalWidgetIcon getIcon(WrtDB::WidgetDAOReadOnlyPtr dao); WidgetIconList getValidIconsList( - WrtDB::DbWidgetHandle widgetHandle); + WrtDB::DbWidgetHandle widgetHandle); WidgetIconList getValidIconsList( - const WrtDB::WidgetPkgName &pkgname); + const WrtDB::WidgetPkgName &pkgname); WidgetIconList getValidIconsList( - WrtDB::WidgetDAOReadOnlyPtr dao); + WrtDB::WidgetDAOReadOnlyPtr dao); OptionalWidgetStartFileInfo getStartFileInfo( - WrtDB::DbWidgetHandle widgetHandle); + WrtDB::DbWidgetHandle widgetHandle); OptionalWidgetStartFileInfo getStartFileInfo( - const WrtDB::WidgetPkgName &pkgname); + const WrtDB::WidgetPkgName &pkgname); OptionalWidgetStartFileInfo getStartFileInfo( - WrtDB::WidgetDAOReadOnlyPtr dao); + WrtDB::WidgetDAOReadOnlyPtr dao); WrtDB::WidgetLocalizedInfo getLocalizedInfo(WrtDB::DbWidgetHandle widgetHandle); -WrtDB::WidgetLocalizedInfo getLocalizedInfo(const WrtDB::WidgetPkgName & pkgname); +WrtDB::WidgetLocalizedInfo getLocalizedInfo( + const WrtDB::WidgetPkgName & pkgname); WrtDB::WidgetLocalizedInfo getLocalizedInfo(WrtDB::WidgetDAOReadOnlyPtr dao); } diff --git a/modules/localization/src/LanguageTagsProvider.cpp b/modules/localization/src/LanguageTagsProvider.cpp index 576d06a..fcf2077 100644 --- a/modules/localization/src/LanguageTagsProvider.cpp +++ b/modules/localization/src/LanguageTagsProvider.cpp @@ -43,8 +43,9 @@ void LanguageTagsProvider::setLanguageTags(const LanguageTags& taglist) * In case of empty list given as parameter only default value * will exist on m_languageTagsList. */ DPL::String tofind = L""; - if(std::find(m_languageTagsList.begin(), m_languageTagsList.end(), - tofind) == m_languageTagsList.end()) { + if (std::find(m_languageTagsList.begin(), m_languageTagsList.end(), + tofind) == m_languageTagsList.end()) + { m_languageTagsList.push_back(L""); } } @@ -60,17 +61,19 @@ void LanguageTagsProvider::resetLanguageTags() this->loadSystemTags(); } -void LanguageTagsProvider::addWidgetDefaultLocales(const DPL::String& defaultLocale){ +void LanguageTagsProvider::addWidgetDefaultLocales( + const DPL::String& defaultLocale) +{ if (defaultLocale.size() > 0 && - std::find(m_languageTagsList.begin(), m_languageTagsList.end(), defaultLocale) == m_languageTagsList.end()) + std::find(m_languageTagsList.begin(), m_languageTagsList.end(), + defaultLocale) == m_languageTagsList.end()) { if (m_languageTagsList.size() < 2) { m_languageTagsList.push_front(defaultLocale); } else { LanguageTags::iterator placeToInsert = m_languageTagsList.end(); --placeToInsert; - if (*placeToInsert != L"") - { + if (*placeToInsert != L"") { ++placeToInsert; } m_languageTagsList.insert(placeToInsert, defaultLocale); @@ -78,7 +81,8 @@ void LanguageTagsProvider::addWidgetDefaultLocales(const DPL::String& defaultLoc } } -DPL::String LanguageTagsProvider::BCP47LanguageTagToLocale(const DPL::String& inLanguageTag) +DPL::String LanguageTagsProvider::BCP47LanguageTagToLocale( + const DPL::String& inLanguageTag) { DPL::String languageTag(inLanguageTag); /* Replace all */ @@ -86,7 +90,8 @@ DPL::String LanguageTagsProvider::BCP47LanguageTagToLocale(const DPL::String& in return languageTag; } -DPL::String LanguageTagsProvider::LocaleToBCP47LanguageTag(const DPL::String& inLocaleString) +DPL::String LanguageTagsProvider::LocaleToBCP47LanguageTag( + const DPL::String& inLocaleString) { /* Cut off codepage information from given string (if any exists) * i.e. change en_US.UTF-8 into en_US */ @@ -105,16 +110,14 @@ LanguageTagsProvider::LanguageTagsProvider() } LanguageTagsProvider::~LanguageTagsProvider() -{ -} +{} void LanguageTagsProvider::loadSystemTags() { char* language = vconf_get_str(VCONFKEY_LANGSET); - if(!language) { + if (!language) { LogError("Failed to get language from vconf"); - } - else { + } else { LogDebug("Language fetched from vconf: " << language); } createTagsFromLocales(language); @@ -124,7 +127,7 @@ void LanguageTagsProvider::loadSystemTags() void LanguageTagsProvider::createTagsFromLocales(const char* language) { m_languageTagsList.clear(); - if(!language) { + if (!language) { LogDebug("Setting default language tags"); /* If NULL language given than set default language tags * and return. */ @@ -133,13 +136,13 @@ void LanguageTagsProvider::createTagsFromLocales(const char* language) } LogDebug("Setting tags for language: " << language); - DPL::String langdescr = LocaleToBCP47LanguageTag(DPL::FromUTF8String(language)); + DPL::String langdescr = + LocaleToBCP47LanguageTag(DPL::FromUTF8String(language)); size_t position; - if(langdescr.empty()) { + if (langdescr.empty()) { LogError("Empty language description while correct value needed"); - } - else { + } else { /* Language tags list should not be cleared before this place to * avoid losing current data when new data are invalid */ while (true) { diff --git a/modules/localization/src/localization_utils.cpp b/modules/localization/src/localization_utils.cpp index c463276..6298a5c 100644 --- a/modules/localization/src/localization_utils.cpp +++ b/modules/localization/src/localization_utils.cpp @@ -31,8 +31,8 @@ static DPL::ReadWriteMutex m_readWriteMutex; template void FindAndReplace(StringType& source, - const StringType& find, - const StringType& replace) + const StringType& find, + const StringType& replace) { size_t pos = 0; while ((pos = source.find(find, pos)) != StringType::npos) { @@ -68,7 +68,9 @@ void UpdateUserAgentLanguageTags() FOREACH(i, m_systemLanguageTags) { DPL::String tag = LocaleToBCP47LanguageTag(*i); while (true) { //W3C Packaging 9. Step 5. 2. D - if (tag.empty()) { continue; } + if (tag.empty()) { + continue; + } LogDebug("Adding user locale '" << tag << "'"); m_languageTags.push_back(tag); diff --git a/modules/localization/src/w3c_file_localization.cpp b/modules/localization/src/w3c_file_localization.cpp index 4a6cfe1..75a6bf2 100644 --- a/modules/localization/src/w3c_file_localization.cpp +++ b/modules/localization/src/w3c_file_localization.cpp @@ -44,26 +44,37 @@ const DPL::String WIDGET_URI_BEGIN = L"widget://"; const DPL::String LOCALE_PREFIX = L"locales/"; DPL::Optional GetFilePathInWidgetPackageInternal( - const std::string& basePath, - std::string filePath) + const std::string& basePath, + std::string filePath) { LogDebug("Looking for file: " << filePath << " in: " << basePath); - const LanguageTags& ltags = LanguageTagsProviderSingleton::Instance().getLanguageTags(); + const LanguageTags& ltags = + LanguageTagsProviderSingleton::Instance().getLanguageTags(); //Check if string isn't empty - if (filePath.size() == 0) { return DPL::Optional::Null; } + if (filePath.size() == 0) { + return DPL::Optional::Null; + } //Removing preceding '/' - if (filePath[0] == '/') { filePath.erase(0, 1); } - // In some cases (start file localization) url has unnecessary "/" at the end - if(filePath[filePath.size()-1] == '/') { filePath.erase(filePath.size()-1, 1); } + if (filePath[0] == '/') { + filePath.erase(0, 1); + } + // In some cases (start file localization) url has unnecessary "/" at the + // end + if (filePath[filePath.size() - 1] == '/') { + filePath.erase(filePath.size() - 1, 1); + } //Check if string isn't empty - if (filePath.size() == 0) { return DPL::Optional::Null; } + if (filePath.size() == 0) { + return DPL::Optional::Null; + } LogDebug("locales size = " << ltags.size()); for (LanguageTags::const_iterator it = ltags.begin(); - it != ltags.end(); - ++it) { + it != ltags.end(); + ++it) + { LogDebug("Trying locale: " << *it); std::string path = basePath; if (path[path.size() - 1] == '/') { @@ -90,8 +101,8 @@ DPL::Optional GetFilePathInWidgetPackageInternal( } DPL::Optional GetFilePathInWidgetPackageInternal( - const DPL::String& basePath, - const DPL::String& filePath) + const DPL::String& basePath, + const DPL::String& filePath) { DPL::Optional path = GetFilePathInWidgetPackageInternal(DPL::ToUTF8String(basePath), @@ -105,28 +116,27 @@ DPL::Optional GetFilePathInWidgetPackageInternal( } namespace W3CFileLocalization { - DPL::Optional getFilePathInWidgetPackageFromUrl( - DbWidgetHandle widgetHandle, - const DPL::String &url) + DbWidgetHandle widgetHandle, + const DPL::String &url) { return getFilePathInWidgetPackageFromUrl( - WidgetDAOReadOnlyPtr(new WidgetDAOReadOnly(widgetHandle)), - url); + WidgetDAOReadOnlyPtr(new WidgetDAOReadOnly(widgetHandle)), + url); } DPL::Optional getFilePathInWidgetPackageFromUrl( - const WrtDB::WidgetPkgName &pkgname, - const DPL::String &url) + const WrtDB::WidgetPkgName &pkgname, + const DPL::String &url) { return getFilePathInWidgetPackageFromUrl( - WidgetDAOReadOnlyPtr(new WidgetDAOReadOnly(pkgname)), - url); + WidgetDAOReadOnlyPtr(new WidgetDAOReadOnly(pkgname)), + url); } DPL::Optional getFilePathInWidgetPackageFromUrl( - WrtDB::WidgetDAOReadOnlyPtr dao, - const DPL::String &url) + WrtDB::WidgetDAOReadOnlyPtr dao, + const DPL::String &url) { DPL::String req = url; @@ -143,7 +153,7 @@ DPL::Optional getFilePathInWidgetPackageFromUrl( // should always be >0 as correct locales path is // always locales/xx/ or locales/xx-XX/ if (position != std::string::npos && position > 0) { - req.erase(0, position+1); + req.erase(0, position + 1); } } } else { @@ -167,26 +177,26 @@ DPL::Optional getFilePathInWidgetPackageFromUrl( } DPL::Optional getFilePathInWidgetPackage( - WrtDB::DbWidgetHandle widgetHandle, - const DPL::String& file) + WrtDB::DbWidgetHandle widgetHandle, + const DPL::String& file) { return getFilePathInWidgetPackage( - WidgetDAOReadOnlyPtr(new WidgetDAOReadOnly(widgetHandle)), - file); + WidgetDAOReadOnlyPtr(new WidgetDAOReadOnly(widgetHandle)), + file); } DPL::Optional getFilePathInWidgetPackage( - const WrtDB::WidgetPkgName &pkgname, - const DPL::String& file) + const WrtDB::WidgetPkgName &pkgname, + const DPL::String& file) { return getFilePathInWidgetPackage( - WidgetDAOReadOnlyPtr(new WidgetDAOReadOnly(pkgname)), - file); + WidgetDAOReadOnlyPtr(new WidgetDAOReadOnly(pkgname)), + file); } DPL::Optional getFilePathInWidgetPackage( - WrtDB::WidgetDAOReadOnlyPtr dao, - const DPL::String& file) + WrtDB::WidgetDAOReadOnlyPtr dao, + const DPL::String& file) { return GetFilePathInWidgetPackageInternal(dao->getPath(), file); } @@ -203,9 +213,11 @@ DPL::OptionalString getStartFile(const WrtDB::DbWidgetHandle handle) DPL::OptionalString getStartFile(WrtDB::WidgetDAOReadOnlyPtr dao) { - WidgetDAOReadOnly::LocalizedStartFileList locList = dao->getLocalizedStartFileList(); + WidgetDAOReadOnly::LocalizedStartFileList locList = + dao->getLocalizedStartFileList(); WidgetDAOReadOnly::WidgetStartFileList list = dao->getStartFileList(); - LanguageTags tagsList = LanguageTagsProviderSingleton::Instance().getLanguageTags(); + LanguageTags tagsList = + LanguageTagsProviderSingleton::Instance().getLanguageTags(); DPL::OptionalString defaultLoc = dao->getDefaultlocale(); if (!!defaultLoc) { @@ -242,9 +254,11 @@ OptionalWidgetIcon getIcon(WrtDB::DbWidgetHandle widgetHandle) OptionalWidgetIcon getIcon(WrtDB::WidgetDAOReadOnlyPtr dao) { - WidgetDAOReadOnly::WidgetLocalizedIconList locList = dao->getLocalizedIconList(); + WidgetDAOReadOnly::WidgetLocalizedIconList locList = + dao->getLocalizedIconList(); WidgetDAOReadOnly::WidgetIconList list = dao->getIconList(); - LanguageTags tagsList = LanguageTagsProviderSingleton::Instance().getLanguageTags(); + LanguageTags tagsList = + LanguageTagsProviderSingleton::Instance().getLanguageTags(); DPL::OptionalString defaultLoc = dao->getDefaultlocale(); if (!!defaultLoc) { @@ -276,13 +290,13 @@ OptionalWidgetIcon getIcon(WrtDB::WidgetDAOReadOnlyPtr dao) WidgetIconList getValidIconsList(WrtDB::DbWidgetHandle widgetHandle) { return getValidIconsList( - WidgetDAOReadOnlyPtr(new WidgetDAOReadOnly(widgetHandle))); + WidgetDAOReadOnlyPtr(new WidgetDAOReadOnly(widgetHandle))); } WidgetIconList getValidIconsList(const WrtDB::WidgetPkgName &pkgname) { return getValidIconsList( - WidgetDAOReadOnlyPtr(new WidgetDAOReadOnly(pkgname))); + WidgetDAOReadOnlyPtr(new WidgetDAOReadOnly(pkgname))); } WidgetIconList getValidIconsList(WrtDB::WidgetDAOReadOnlyPtr dao) @@ -310,17 +324,16 @@ WidgetIconList getValidIconsList(WrtDB::WidgetDAOReadOnlyPtr dao) OptionalWidgetStartFileInfo getStartFileInfo(WrtDB::DbWidgetHandle widgetHandle) { return getStartFileInfo( - WidgetDAOReadOnlyPtr(new WidgetDAOReadOnly(widgetHandle))); + WidgetDAOReadOnlyPtr(new WidgetDAOReadOnly(widgetHandle))); } -OptionalWidgetStartFileInfo getStartFileInfo(const WrtDB::WidgetPkgName &pkgname) +OptionalWidgetStartFileInfo getStartFileInfo( + const WrtDB::WidgetPkgName &pkgname) { return getStartFileInfo( - WidgetDAOReadOnlyPtr(new WidgetDAOReadOnly(pkgname))); - + WidgetDAOReadOnlyPtr(new WidgetDAOReadOnly(pkgname))); } - OptionalWidgetStartFileInfo getStartFileInfo(WrtDB::WidgetDAOReadOnlyPtr dao) { WidgetStartFileInfo info; @@ -328,7 +341,8 @@ OptionalWidgetStartFileInfo getStartFileInfo(WrtDB::WidgetDAOReadOnlyPtr dao) WidgetDAOReadOnly::LocalizedStartFileList locList = dao->getLocalizedStartFileList(); WidgetDAOReadOnly::WidgetStartFileList list = dao->getStartFileList(); - const LanguageTags tagsList = LanguageTagsProviderSingleton::Instance().getLanguageTags(); + const LanguageTags tagsList = + LanguageTagsProviderSingleton::Instance().getLanguageTags(); FOREACH(tag, tagsList) { @@ -338,7 +352,8 @@ OptionalWidgetStartFileInfo getStartFileInfo(WrtDB::WidgetDAOReadOnlyPtr dao) FOREACH(it, list) { if (it->startFileId == - sFile->startFileId) { + sFile->startFileId) + { info.file = it->src; info.encoding = sFile->encoding; info.type = sFile->type; @@ -370,7 +385,8 @@ WidgetLocalizedInfo getLocalizedInfo(const WrtDB::WidgetPkgName & pkgname) WidgetLocalizedInfo getLocalizedInfo(WidgetDAOReadOnlyPtr dao) { - LanguageTags languages = LanguageTagsProviderSingleton::Instance().getLanguageTags(); + LanguageTags languages = + LanguageTagsProviderSingleton::Instance().getLanguageTags(); DPL::OptionalString dl = dao->getDefaultlocale(); if (!!dl) { languages.push_back(*dl); diff --git a/modules/log/include/dpl/log/abstract_log_provider.h b/modules/log/include/dpl/log/abstract_log_provider.h index fdce9c0..62fa050 100644 --- a/modules/log/include/dpl/log/abstract_log_provider.h +++ b/modules/log/include/dpl/log/abstract_log_provider.h @@ -22,26 +22,37 @@ #ifndef DPL_ABSTRACT_LOG_PROVIDER_H #define DPL_ABSTRACT_LOG_PROVIDER_H -namespace DPL -{ -namespace Log -{ - +namespace DPL { +namespace Log { class AbstractLogProvider { -public: + public: virtual ~AbstractLogProvider() {} - virtual void Debug(const char *message, const char *fileName, int line, const char *function) = 0; - virtual void Info(const char *message, const char *fileName, int line, const char *function) = 0; - virtual void Warning(const char *message, const char *fileName, int line, const char *function) = 0; - virtual void Error(const char *message, const char *fileName, int line, const char *function) = 0; - virtual void Pedantic(const char *message, const char *fileName, int line, const char *function) = 0; + virtual void Debug(const char *message, + const char *fileName, + int line, + const char *function) = 0; + virtual void Info(const char *message, + const char *fileName, + int line, + const char *function) = 0; + virtual void Warning(const char *message, + const char *fileName, + int line, + const char *function) = 0; + virtual void Error(const char *message, + const char *fileName, + int line, + const char *function) = 0; + virtual void Pedantic(const char *message, + const char *fileName, + int line, + const char *function) = 0; -protected: + protected: static const char *LocateSourceFileName(const char *filename); }; - } } // namespace DPL diff --git a/modules/log/include/dpl/log/dlog_log_provider.h b/modules/log/include/dpl/log/dlog_log_provider.h index 0b3edb5..1dd4c2d 100644 --- a/modules/log/include/dpl/log/dlog_log_provider.h +++ b/modules/log/include/dpl/log/dlog_log_provider.h @@ -26,32 +26,47 @@ #include #include -namespace DPL +namespace DPL { +namespace Log { +class DLOGLogProvider : + public AbstractLogProvider { -namespace Log -{ - -class DLOGLogProvider - : public AbstractLogProvider -{ -private: + private: DPL::ScopedFree m_tag; - static std::string FormatMessage(const char *message, const char *filename, int line, const char *function); -public: + static std::string FormatMessage(const char *message, + const char *filename, + int line, + const char *function); + + public: DLOGLogProvider(); virtual ~DLOGLogProvider(); - virtual void Debug(const char *message, const char *fileName, int line, const char *function); - virtual void Info(const char *message, const char *fileName, int line, const char *function); - virtual void Warning(const char *message, const char *fileName, int line, const char *function); - virtual void Error(const char *message, const char *fileName, int line, const char *function); - virtual void Pedantic(const char *message, const char *fileName, int line, const char *function); + virtual void Debug(const char *message, + const char *fileName, + int line, + const char *function); + virtual void Info(const char *message, + const char *fileName, + int line, + const char *function); + virtual void Warning(const char *message, + const char *fileName, + int line, + const char *function); + virtual void Error(const char *message, + const char *fileName, + int line, + const char *function); + virtual void Pedantic(const char *message, + const char *fileName, + int line, + const char *function); // Set global Tag according to DLOG void SetTag(const char *tag); }; - } } // namespace DPL diff --git a/modules/log/include/dpl/log/log.h b/modules/log/include/dpl/log/log.h index 7be5c9d..d4d95ed 100644 --- a/modules/log/include/dpl/log/log.h +++ b/modules/log/include/dpl/log/log.h @@ -30,20 +30,18 @@ #include #include -namespace DPL -{ -namespace Log -{ +namespace DPL { +namespace Log { /** * DPL log system * * To switch logs into old style, export * DPL_USE_OLD_STYLE_LOGS before application start */ -class LogSystem - : private Noncopyable +class LogSystem : + private Noncopyable { -private: + private: typedef std::list AbstractLogProviderPtrList; AbstractLogProviderPtrList m_providers; @@ -52,7 +50,7 @@ private: bool m_isLoggingEnabled; -public: + public: bool IsLoggingEnabled() const; LogSystem(); virtual ~LogSystem(); @@ -60,27 +58,42 @@ public: /** * Log debug message */ - void Debug(const char *message, const char *filename, int line, const char *function); + void Debug(const char *message, + const char *filename, + int line, + const char *function); /** * Log info message */ - void Info(const char *message, const char *filename, int line, const char *function); + void Info(const char *message, + const char *filename, + int line, + const char *function); /** * Log warning message */ - void Warning(const char *message, const char *filename, int line, const char *function); + void Warning(const char *message, + const char *filename, + int line, + const char *function); /** * Log error message */ - void Error(const char *message, const char *filename, int line, const char *function); + void Error(const char *message, + const char *filename, + int line, + const char *function); /** * Log pedantic message */ - void Pedantic(const char *message, const char *filename, int line, const char *function); + void Pedantic(const char *message, + const char *filename, + int line, + const char *function); /** * Set default's DLOG provider Tag @@ -103,19 +116,22 @@ public: /* * Replacement low overhead null logging class */ -class NullStream { +class NullStream +{ public: NullStream() {} template - NullStream& operator<<(const T&) { return *this; } + NullStream& operator<<(const T&) + { + return *this; + } }; /** * Log system singleton */ typedef Singleton LogSystemSingleton; - } } // namespace DPL @@ -126,27 +142,26 @@ typedef Singleton LogSystemSingleton; #ifdef DPL_LOGS_ENABLED #define DPL_MACRO_FOR_LOGGING(message, function) \ - do \ - { \ - if (DPL::Log::LogSystemSingleton::Instance().IsLoggingEnabled()) \ - { \ - std::ostringstream platformLog; \ - platformLog << message; \ - DPL::Log::LogSystemSingleton::Instance().function( \ - platformLog.str().c_str(), \ - __FILE__, __LINE__, __FUNCTION__); \ - } \ - } while (0) + do \ + { \ + if (DPL::Log::LogSystemSingleton::Instance().IsLoggingEnabled()) \ + { \ + std::ostringstream platformLog; \ + platformLog << message; \ + DPL::Log::LogSystemSingleton::Instance().function( \ + platformLog.str().c_str(), \ + __FILE__, __LINE__, __FUNCTION__); \ + } \ + } while (0) #else /* avoid warnings about unused variables */ #define DPL_MACRO_FOR_LOGGING(message, function) \ - do { \ - DPL::Log::NullStream ns; \ - ns << message; \ - } while (0) + do { \ + DPL::Log::NullStream ns; \ + ns << message; \ + } while (0) #endif - #define LogDebug(message) DPL_MACRO_FOR_LOGGING(message, Debug) #define LogInfo(message) DPL_MACRO_FOR_LOGGING(message, Info) #define LogWarning(message) DPL_MACRO_FOR_LOGGING(message, Warning) diff --git a/modules/log/include/dpl/log/old_style_log_provider.h b/modules/log/include/dpl/log/old_style_log_provider.h index 3ff3d89..becdc93 100644 --- a/modules/log/include/dpl/log/old_style_log_provider.h +++ b/modules/log/include/dpl/log/old_style_log_provider.h @@ -25,33 +25,52 @@ #include #include -namespace DPL +namespace DPL { +namespace Log { +class OldStyleLogProvider : + public AbstractLogProvider { -namespace Log -{ -class OldStyleLogProvider - : public AbstractLogProvider -{ -private: + private: bool m_showDebug; bool m_showInfo; bool m_showWarning; bool m_showError; bool m_showPedantic; - static std::string FormatMessage(const char *message, const char *filename, int line, const char *function); + static std::string FormatMessage(const char *message, + const char *filename, + int line, + const char *function); -public: - OldStyleLogProvider(bool showDebug, bool showInfo, bool showWarning, bool showError, bool showPedantic); + public: + OldStyleLogProvider(bool showDebug, + bool showInfo, + bool showWarning, + bool showError, + bool showPedantic); virtual ~OldStyleLogProvider() {} - virtual void Debug(const char *message, const char *fileName, int line, const char *function); - virtual void Info(const char *message, const char *fileName, int line, const char *function); - virtual void Warning(const char *message, const char *fileName, int line, const char *function); - virtual void Error(const char *message, const char *fileName, int line, const char *function); - virtual void Pedantic(const char *message, const char *fileName, int line, const char *function); + virtual void Debug(const char *message, + const char *fileName, + int line, + const char *function); + virtual void Info(const char *message, + const char *fileName, + int line, + const char *function); + virtual void Warning(const char *message, + const char *fileName, + int line, + const char *function); + virtual void Error(const char *message, + const char *fileName, + int line, + const char *function); + virtual void Pedantic(const char *message, + const char *fileName, + int line, + const char *function); }; - } } // namespace DPL diff --git a/modules/log/src/abstract_log_provider.cpp b/modules/log/src/abstract_log_provider.cpp index 0b28573..a03f8a0 100644 --- a/modules/log/src/abstract_log_provider.cpp +++ b/modules/log/src/abstract_log_provider.cpp @@ -23,10 +23,8 @@ #include #include -namespace DPL -{ -namespace Log -{ +namespace DPL { +namespace Log { const char *AbstractLogProvider::LocateSourceFileName(const char *filename) { const char *ptr = strrchr(filename, '/'); diff --git a/modules/log/src/dlog_log_provider.cpp b/modules/log/src/dlog_log_provider.cpp index 2c05af4..943369f 100644 --- a/modules/log/src/dlog_log_provider.cpp +++ b/modules/log/src/dlog_log_provider.cpp @@ -25,59 +25,78 @@ #include #include -namespace DPL -{ -namespace Log -{ - -std::string DLOGLogProvider::FormatMessage(const char *message, const char *filename, int line, const char *function) +namespace DPL { +namespace Log { +std::string DLOGLogProvider::FormatMessage(const char *message, + const char *filename, + int line, + const char *function) { std::ostringstream val; val << std::string("[") << - LocateSourceFileName(filename) << std::string(":") << line << - std::string("] ") << function << std::string("(): ") << message; + LocateSourceFileName(filename) << std::string(":") << line << + std::string("] ") << function << std::string("(): ") << message; return val.str(); } DLOGLogProvider::DLOGLogProvider() -{ -} +{} DLOGLogProvider::~DLOGLogProvider() -{ -} +{} void DLOGLogProvider::SetTag(const char *tag) { m_tag.Reset(strdup(tag)); } -void DLOGLogProvider::Debug(const char *message, const char *filename, int line, const char *function) +void DLOGLogProvider::Debug(const char *message, + const char *filename, + int line, + const char *function) { - LOG(LOG_DEBUG, m_tag.Get(), "%s" , FormatMessage(message, filename, line, function).c_str()); + LOG(LOG_DEBUG, m_tag.Get(), "%s", + FormatMessage(message, filename, line, function).c_str()); } -void DLOGLogProvider::Info(const char *message, const char *filename, int line, const char *function) +void DLOGLogProvider::Info(const char *message, + const char *filename, + int line, + const char *function) { - LOG(LOG_INFO, m_tag.Get(), "%s" , FormatMessage(message, filename, line, function).c_str()); + LOG(LOG_INFO, m_tag.Get(), "%s", + FormatMessage(message, filename, line, function).c_str()); } -void DLOGLogProvider::Warning(const char *message, const char *filename, int line, const char *function) +void DLOGLogProvider::Warning(const char *message, + const char *filename, + int line, + const char *function) { - LOG(LOG_WARN, m_tag.Get(), "%s" , FormatMessage(message, filename, line, function).c_str()); + LOG(LOG_WARN, m_tag.Get(), "%s", + FormatMessage(message, filename, line, function).c_str()); } -void DLOGLogProvider::Error(const char *message, const char *filename, int line, const char *function) +void DLOGLogProvider::Error(const char *message, + const char *filename, + int line, + const char *function) { - LOG(LOG_ERROR, m_tag.Get(), "%s" , FormatMessage(message, filename, line, function).c_str()); + LOG(LOG_ERROR, m_tag.Get(), "%s", + FormatMessage(message, filename, line, function).c_str()); } -void DLOGLogProvider::Pedantic(const char *message, const char *filename, int line, const char *function) +void DLOGLogProvider::Pedantic(const char *message, + const char *filename, + int line, + const char *function) { - LOG(LOG_DEBUG, "DPL", "%s", FormatMessage(message, filename, line, function).c_str()); + LOG(LOG_DEBUG, "DPL", "%s", FormatMessage(message, + filename, + line, + function).c_str()); } - } } // namespace DPL diff --git a/modules/log/src/log.cpp b/modules/log/src/log.cpp index a2f1f94..7c0ebc2 100644 --- a/modules/log/src/log.cpp +++ b/modules/log/src/log.cpp @@ -25,28 +25,26 @@ IMPLEMENT_SINGLETON(DPL::Log::LogSystem) -namespace DPL -{ -namespace Log -{ +namespace DPL { +namespace Log { namespace // anonymous { const char *OLD_STYLE_LOGS_ENV_NAME = "DPL_USE_OLD_STYLE_LOGS"; -const char *OLD_STYLE_PEDANTIC_LOGS_ENV_NAME = "DPL_USE_OLD_STYLE_PEDANTIC_LOGS"; +const char *OLD_STYLE_PEDANTIC_LOGS_ENV_NAME = + "DPL_USE_OLD_STYLE_PEDANTIC_LOGS"; const char *OLD_STYLE_LOGS_MASK_ENV_NAME = "DPL_USE_OLD_STYLE_LOGS_MASK"; const char *DPL_LOG_OFF = "DPL_LOG_OFF"; } // namespace anonymous - bool LogSystem::IsLoggingEnabled() const { return m_isLoggingEnabled; } -LogSystem::LogSystem() - : m_dlogProvider(NULL), - m_oldStyleProvider(NULL), - m_isLoggingEnabled(!getenv(DPL_LOG_OFF)) +LogSystem::LogSystem() : + m_dlogProvider(NULL), + m_oldStyleProvider(NULL), + m_isLoggingEnabled(!getenv(DPL_LOG_OFF)) { bool oldStyleLogs = false; bool oldStyleDebugLogs = true; @@ -58,62 +56,64 @@ LogSystem::LogSystem() // Check environment settings about pedantic logs const char *value = getenv(OLD_STYLE_LOGS_ENV_NAME); - if (value != NULL && !strcmp(value, "1")) + if (value != NULL && !strcmp(value, "1")) { oldStyleLogs = true; + } value = getenv(OLD_STYLE_PEDANTIC_LOGS_ENV_NAME); - if (value != NULL && !strcmp(value, "1")) + if (value != NULL && !strcmp(value, "1")) { oldStylePedanticLogs = true; + } value = getenv(OLD_STYLE_LOGS_MASK_ENV_NAME); - if (value != NULL) - { + if (value != NULL) { size_t len = strlen(value); - if (len >= 1) - { - if (value[0] == '0') + if (len >= 1) { + if (value[0] == '0') { oldStyleDebugLogs = false; - else if (value[0] == '1') + } else if (value[0] == '1') { oldStyleDebugLogs = true; + } } - if (len >= 2) - { - if (value[1] == '0') + if (len >= 2) { + if (value[1] == '0') { oldStyleInfoLogs = false; - else if (value[1] == '1') + } else if (value[1] == '1') { oldStyleInfoLogs = true; + } } - if (len >= 3) - { - if (value[2] == '0') + if (len >= 3) { + if (value[2] == '0') { oldStyleWarningLogs = false; - else if (value[2] == '1') + } else if (value[2] == '1') { oldStyleWarningLogs = true; + } } - if (len >= 4) - { - if (value[3] == '0') + if (len >= 4) { + if (value[3] == '0') { oldStyleErrorLogs = false; - else if (value[3] == '1') + } else if (value[3] == '1') { oldStyleErrorLogs = true; + } } } // Setup default DLOG and old style logging - if (oldStyleLogs) - { + if (oldStyleLogs) { // Old style - m_oldStyleProvider = new OldStyleLogProvider(oldStyleDebugLogs, oldStyleInfoLogs, oldStyleWarningLogs, oldStyleErrorLogs, oldStylePedanticLogs); + m_oldStyleProvider = new OldStyleLogProvider(oldStyleDebugLogs, + oldStyleInfoLogs, + oldStyleWarningLogs, + oldStyleErrorLogs, + oldStylePedanticLogs); AddProvider(m_oldStyleProvider); - } - else - { + } else { // DLOG m_dlogProvider = new DLOGLogProvider(); AddProvider(m_dlogProvider); @@ -123,8 +123,12 @@ LogSystem::LogSystem() LogSystem::~LogSystem() { // Delete all providers - for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin(); iterator != m_providers.end(); ++iterator) + for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin(); + iterator != m_providers.end(); + ++iterator) + { delete *iterator; + } m_providers.clear(); @@ -135,8 +139,9 @@ LogSystem::~LogSystem() void LogSystem::SetTag(const char* tag) { - if (m_dlogProvider != NULL) + if (m_dlogProvider != NULL) { m_dlogProvider->SetTag(tag); + } } void LogSystem::AddProvider(AbstractLogProvider *provider) @@ -149,35 +154,69 @@ void LogSystem::RemoveProvider(AbstractLogProvider *provider) m_providers.remove(provider); } -void LogSystem::Debug(const char *message, const char *filename, int line, const char *function) +void LogSystem::Debug(const char *message, + const char *filename, + int line, + const char *function) { - for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin(); iterator != m_providers.end(); ++iterator) + for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin(); + iterator != m_providers.end(); + ++iterator) + { (*iterator)->Debug(message, filename, line, function); + } } -void LogSystem::Info(const char *message, const char *filename, int line, const char *function) +void LogSystem::Info(const char *message, + const char *filename, + int line, + const char *function) { - for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin(); iterator != m_providers.end(); ++iterator) + for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin(); + iterator != m_providers.end(); + ++iterator) + { (*iterator)->Info(message, filename, line, function); + } } -void LogSystem::Warning(const char *message, const char *filename, int line, const char *function) +void LogSystem::Warning(const char *message, + const char *filename, + int line, + const char *function) { - for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin(); iterator != m_providers.end(); ++iterator) + for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin(); + iterator != m_providers.end(); + ++iterator) + { (*iterator)->Warning(message, filename, line, function); + } } -void LogSystem::Error(const char *message, const char *filename, int line, const char *function) +void LogSystem::Error(const char *message, + const char *filename, + int line, + const char *function) { - for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin(); iterator != m_providers.end(); ++iterator) + for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin(); + iterator != m_providers.end(); + ++iterator) + { (*iterator)->Error(message, filename, line, function); + } } -void LogSystem::Pedantic(const char *message, const char *filename, int line, const char *function) +void LogSystem::Pedantic(const char *message, + const char *filename, + int line, + const char *function) { - for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin(); iterator != m_providers.end(); ++iterator) + for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin(); + iterator != m_providers.end(); + ++iterator) + { (*iterator)->Pedantic(message, filename, line, function); + } } - } } // namespace DPL diff --git a/modules/log/src/old_style_log_provider.cpp b/modules/log/src/old_style_log_provider.cpp index bd7db2b..84433af 100644 --- a/modules/log/src/old_style_log_provider.cpp +++ b/modules/log/src/old_style_log_provider.cpp @@ -28,10 +28,8 @@ #include #include -namespace DPL -{ -namespace Log -{ +namespace DPL { +namespace Log { namespace // anonymous { using namespace DPL::Colors::Text; @@ -46,7 +44,6 @@ const char *WARNING_END = BOLD_GOLD_END; const char *PEDANTIC_BEGIN = PURPLE_BEGIN; const char *PEDANTIC_END = PURPLE_END; - std::string GetFormattedTime() { timeval tv; @@ -56,62 +53,103 @@ std::string GetFormattedTime() localtime_r(&tv.tv_sec, &localNowTime); char format[64]; - snprintf(format, sizeof(format), "%02i:%02i:%02i.%03i", localNowTime.tm_hour, localNowTime.tm_min, localNowTime.tm_sec, static_cast(tv.tv_usec / 1000)); + snprintf(format, + sizeof(format), + "%02i:%02i:%02i.%03i", + localNowTime.tm_hour, + localNowTime.tm_min, + localNowTime.tm_sec, + static_cast(tv.tv_usec / 1000)); return format; } - } // namespace anonymous -std::string OldStyleLogProvider::FormatMessage(const char *message, const char *filename, int line, const char *function) +std::string OldStyleLogProvider::FormatMessage(const char *message, + const char *filename, + int line, + const char *function) { std::ostringstream val; val << std::string("[") << GetFormattedTime() << std::string("] [") << - static_cast(pthread_self()) << "/" << static_cast(getpid()) << std::string("] [") << - LocateSourceFileName(filename) << std::string(":") << line << - std::string("] ") << function << std::string("(): ") << message; + static_cast(pthread_self()) << "/" << + static_cast(getpid()) << std::string("] [") << + LocateSourceFileName(filename) << std::string(":") << line << + std::string("] ") << function << std::string("(): ") << message; return val.str(); } -OldStyleLogProvider::OldStyleLogProvider(bool showDebug, bool showInfo, bool showWarning, bool showError, bool showPedantic) - : m_showDebug(showDebug), - m_showInfo(showInfo), - m_showWarning(showWarning), - m_showError(showError), - m_showPedantic(showPedantic) +OldStyleLogProvider::OldStyleLogProvider(bool showDebug, + bool showInfo, + bool showWarning, + bool showError, + bool showPedantic) : + m_showDebug(showDebug), + m_showInfo(showInfo), + m_showWarning(showWarning), + m_showError(showError), + m_showPedantic(showPedantic) +{} + +void OldStyleLogProvider::Debug(const char *message, + const char *filename, + int line, + const char *function) { + if (m_showDebug) { + fprintf(stdout, "%s%s%s\n", DEBUG_BEGIN, + FormatMessage(message, filename, line, + function).c_str(), DEBUG_END); + } } -void OldStyleLogProvider::Debug(const char *message, const char *filename, int line, const char *function) +void OldStyleLogProvider::Info(const char *message, + const char *filename, + int line, + const char *function) { - if (m_showDebug) - fprintf(stdout, "%s%s%s\n", DEBUG_BEGIN, FormatMessage(message, filename, line, function).c_str(), DEBUG_END); + if (m_showInfo) { + fprintf(stdout, "%s%s%s\n", INFO_BEGIN, + FormatMessage(message, filename, line, + function).c_str(), INFO_END); + } } -void OldStyleLogProvider::Info(const char *message, const char *filename, int line, const char *function) +void OldStyleLogProvider::Warning(const char *message, + const char *filename, + int line, + const char *function) { - if (m_showInfo) - fprintf(stdout, "%s%s%s\n", INFO_BEGIN, FormatMessage(message, filename, line, function).c_str(), INFO_END); + if (m_showWarning) { + fprintf(stdout, "%s%s%s\n", WARNING_BEGIN, + FormatMessage(message, filename, line, + function).c_str(), WARNING_END); + } } -void OldStyleLogProvider::Warning(const char *message, const char *filename, int line, const char *function) +void OldStyleLogProvider::Error(const char *message, + const char *filename, + int line, + const char *function) { - if (m_showWarning) - fprintf(stdout, "%s%s%s\n", WARNING_BEGIN, FormatMessage(message, filename, line, function).c_str(), WARNING_END); + if (m_showError) { + fprintf(stdout, "%s%s%s\n", ERROR_BEGIN, + FormatMessage(message, filename, line, + function).c_str(), ERROR_END); + } } -void OldStyleLogProvider::Error(const char *message, const char *filename, int line, const char *function) +void OldStyleLogProvider::Pedantic(const char *message, + const char *filename, + int line, + const char *function) { - if (m_showError) - fprintf(stdout, "%s%s%s\n", ERROR_BEGIN, FormatMessage(message, filename, line, function).c_str(), ERROR_END); + if (m_showPedantic) { + fprintf(stdout, "%s%s%s\n", PEDANTIC_BEGIN, + FormatMessage(message, filename, line, + function).c_str(), PEDANTIC_END); + } } - -void OldStyleLogProvider::Pedantic(const char *message, const char *filename, int line, const char *function) -{ - if (m_showPedantic) - fprintf(stdout, "%s%s%s\n", PEDANTIC_BEGIN, FormatMessage(message, filename, line, function).c_str(), PEDANTIC_END); -} - } } // namespace DPL diff --git a/modules/rpc/include/dpl/rpc/abstract_rpc_connection.h b/modules/rpc/include/dpl/rpc/abstract_rpc_connection.h index 6f1fd63..7857c60 100644 --- a/modules/rpc/include/dpl/rpc/abstract_rpc_connection.h +++ b/modules/rpc/include/dpl/rpc/abstract_rpc_connection.h @@ -29,12 +29,9 @@ #include #include -namespace DPL -{ -namespace RPC -{ -namespace AbstractRPCConnectionEvents -{ +namespace DPL { +namespace RPC { +namespace AbstractRPCConnectionEvents { /** * Asynchronous call event */ @@ -51,21 +48,23 @@ DECLARE_GENERIC_EVENT_0(ConnectionClosedEvent) DECLARE_GENERIC_EVENT_0(ConnectionBrokenEvent) } // namespace AbstractRPCConnectionEvents -class AbstractRPCConnection - : public DPL::Event::EventSupport, - public DPL::Event::EventSupport, - public DPL::Event::EventSupport +class AbstractRPCConnection : + public DPL::Event::EventSupport, + public DPL::Event::EventSupport, + public DPL::Event::EventSupport { -public: + public: class Exception { - public: + public: DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) DECLARE_EXCEPTION_TYPE(Base, AsyncCallFailed) DECLARE_EXCEPTION_TYPE(Base, PingFailed) }; -public: + public: virtual ~AbstractRPCConnection() {} /** @@ -91,7 +90,6 @@ public: * or RPC server accepting connection */ typedef void *AbstractRPCConnectionID; - } } // namespace DPL diff --git a/modules/rpc/include/dpl/rpc/abstract_rpc_connector.h b/modules/rpc/include/dpl/rpc/abstract_rpc_connector.h index 38c1e97..c9e3b1f 100644 --- a/modules/rpc/include/dpl/rpc/abstract_rpc_connector.h +++ b/modules/rpc/include/dpl/rpc/abstract_rpc_connector.h @@ -26,28 +26,27 @@ #include #include -namespace DPL -{ -namespace RPC -{ -namespace AbstractRPCConnectorEvents -{ +namespace DPL { +namespace RPC { +namespace AbstractRPCConnectorEvents { /** * RPC connection established */ -DECLARE_GENERIC_EVENT_2(ConnectionEstablishedEvent, AbstractRPCConnectionID, AbstractRPCConnection *) +DECLARE_GENERIC_EVENT_2(ConnectionEstablishedEvent, + AbstractRPCConnectionID, + AbstractRPCConnection *) } // namespace AbstractRPCClientEvents -class AbstractRPCConnector - : public DPL::Event::EventSupport +class AbstractRPCConnector : + public DPL::Event::EventSupport { -public: + public: /** * Destructor */ virtual ~AbstractRPCConnector() {} }; - } } // namespace DPL diff --git a/modules/rpc/include/dpl/rpc/generic_rpc_connection.h b/modules/rpc/include/dpl/rpc/generic_rpc_connection.h index 353dd3a..7810ef9 100644 --- a/modules/rpc/include/dpl/rpc/generic_rpc_connection.h +++ b/modules/rpc/include/dpl/rpc/generic_rpc_connection.h @@ -27,16 +27,13 @@ #include #include -namespace DPL +namespace DPL { +namespace RPC { +class GenericRPCConnection : + public AbstractRPCConnection, + private DPL::Socket::WaitableInputOutputExecutionContextSupport { -namespace RPC -{ - -class GenericRPCConnection - : public AbstractRPCConnection, - private DPL::Socket::WaitableInputOutputExecutionContextSupport -{ -private: + private: // WaitableInputOutputExecutionContextSupport virtual void OnInputStreamRead(); virtual void OnInputStreamClosed(); @@ -44,11 +41,12 @@ private: std::unique_ptr m_inputOutput; -public: + public: /** * Costructor * - * Abstract waitable input/outobject is acquired by class and destroyed upon desctructor + * Abstract waitable input/outobject is acquired by class and destroyed upon + * desctructor */ explicit GenericRPCConnection(AbstractWaitableInputOutput *inputOutput); virtual ~GenericRPCConnection(); @@ -56,7 +54,6 @@ public: virtual void AsyncCall(const RPCFunction &function); virtual void Ping(); }; - } } // namespace DPL diff --git a/modules/rpc/include/dpl/rpc/generic_socket_rpc_client.h b/modules/rpc/include/dpl/rpc/generic_socket_rpc_client.h index 122dd0b..9629e61 100644 --- a/modules/rpc/include/dpl/rpc/generic_socket_rpc_client.h +++ b/modules/rpc/include/dpl/rpc/generic_socket_rpc_client.h @@ -26,34 +26,34 @@ #include #include -namespace DPL -{ -namespace RPC -{ - +namespace DPL { +namespace RPC { template -class GenericSocketRPCClient - : public AbstractRPCConnector, - private DPL::Event::EventListener +class GenericSocketRPCClient : + public AbstractRPCConnector, + private DPL::Event::EventListener { -public: + public: class Exception { - public: + public: DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) DECLARE_EXCEPTION_TYPE(Base, OpenFailed) DECLARE_EXCEPTION_TYPE(Base, CloseFailed) }; -protected: + protected: // Derived class implementations for connection managment - virtual AbstractRPCConnection *OpenSpecificConnection(SocketType *socket) = 0; + virtual AbstractRPCConnection *OpenSpecificConnection(SocketType *socket) = + 0; -private: + private: typedef std::set InternalConnectionSet; InternalConnectionSet m_internalConnectionSet; - virtual void OnEventReceived(const DPL::Socket::AbstractSocketEvents::ConnectedEvent &event) + virtual void OnEventReceived( + const DPL::Socket::AbstractSocketEvents::ConnectedEvent &event) { // Retrieve socket sender SocketType *socket = static_cast(event.GetSender()); @@ -62,10 +62,10 @@ private: // Is this connection still tracked ? // It might have disappeared on close - typename InternalConnectionSet::iterator iterator = m_internalConnectionSet.find(socket); + typename InternalConnectionSet::iterator iterator = + m_internalConnectionSet.find(socket); - if (iterator == m_internalConnectionSet.end()) - { + if (iterator == m_internalConnectionSet.end()) { LogPedantic("RPC client connection socket disappeared"); return; } @@ -74,22 +74,25 @@ private: AbstractRPCConnection *connection = OpenSpecificConnection(socket); // Remove internal connection - socket->EventSupport::RemoveListener(this); + socket->EventSupport + ::RemoveListener(this); m_internalConnectionSet.erase(iterator); // Retrieve ID once again - AbstractRPCConnectionID connectionID = static_cast(socket); + AbstractRPCConnectionID connectionID = + static_cast(socket); // Inform listeners - DPL::Event::EventSupport:: + DPL::Event::EventSupport:: EmitEvent(AbstractRPCConnectorEvents::ConnectionEstablishedEvent( - connectionID, connection, EventSender(this)), DPL::Event::EmitMode::Queued); + connectionID, connection, EventSender( + this)), DPL::Event::EmitMode::Queued); } -public: + public: explicit GenericSocketRPCClient() - { - } + {} virtual ~GenericSocketRPCClient() { @@ -105,7 +108,8 @@ public: SocketType *socket = new SocketType(); // Add socket listeners - socket->EventSupport::AddListener(this); + socket->EventSupport + ::AddListener(this); Try { @@ -115,10 +119,11 @@ public: // Start connecting to server socket->Connect(Address(socketAddress)); } - Catch (DPL::Socket::AbstractSocket::Exception::Base) + Catch(DPL::Socket::AbstractSocket::Exception::Base) { // Remove back socket listener - socket->EventSupport::RemoveListener(this); + socket->EventSupport::RemoveListener(this); // Log debug message LogPedantic("Cannot connect to: " << socketAddress.ToString()); @@ -131,7 +136,9 @@ public: m_internalConnectionSet.insert(socket); // Debug info - LogPedantic("Client started on interface: " << socket->GetLocalAddress().ToString()); + LogPedantic( + "Client started on interface: " << + socket->GetLocalAddress().ToString()); // Return unique identifier return static_cast(socket); @@ -145,16 +152,19 @@ public: SocketType *socket = static_cast(connectionID); // Find corresponding internal connection - typename InternalConnectionSet::iterator iterator = m_internalConnectionSet.find(socket); + typename InternalConnectionSet::iterator iterator = + m_internalConnectionSet.find(socket); - if (iterator == m_internalConnectionSet.end()) + if (iterator == m_internalConnectionSet.end()) { return; + } // Close socket socket->Close(); // Remove internal socket - socket->EventSupport::RemoveListener(this); + socket->EventSupport + ::RemoveListener(this); delete socket; m_internalConnectionSet.erase(iterator); @@ -165,11 +175,12 @@ public: void CloseAll() { - while (!m_internalConnectionSet.empty()) - Close(static_cast(*m_internalConnectionSet.begin())); + while (!m_internalConnectionSet.empty()) { + Close(static_cast(*m_internalConnectionSet + .begin())); + } } }; - } } // namespace DPL diff --git a/modules/rpc/include/dpl/rpc/generic_socket_rpc_connection.h b/modules/rpc/include/dpl/rpc/generic_socket_rpc_connection.h index 12e53de..6c2d0ce 100644 --- a/modules/rpc/include/dpl/rpc/generic_socket_rpc_connection.h +++ b/modules/rpc/include/dpl/rpc/generic_socket_rpc_connection.h @@ -24,23 +24,18 @@ #include -namespace DPL -{ -namespace RPC -{ - +namespace DPL { +namespace RPC { template -class GenericSocketRPCConnection - : public GenericRPCConnection +class GenericSocketRPCConnection : + public GenericRPCConnection { -protected: + protected: // Private construction with socket acquisition - GenericSocketRPCConnection(SocketType *socket) - : GenericRPCConnection(socket) - { - } + GenericSocketRPCConnection(SocketType *socket) : + GenericRPCConnection(socket) + {} }; - } } // namespace DPL diff --git a/modules/rpc/include/dpl/rpc/generic_socket_rpc_server.h b/modules/rpc/include/dpl/rpc/generic_socket_rpc_server.h index 87d6899..a4cae00 100644 --- a/modules/rpc/include/dpl/rpc/generic_socket_rpc_server.h +++ b/modules/rpc/include/dpl/rpc/generic_socket_rpc_server.h @@ -26,74 +26,77 @@ #include #include -namespace DPL -{ -namespace RPC -{ - +namespace DPL { +namespace RPC { template -class GenericSocketRPCServer - : public AbstractRPCConnector, - private DPL::Event::EventListener +class GenericSocketRPCServer : + public AbstractRPCConnector, + private DPL::Event::EventListener { -public: + public: class Exception { - public: + public: DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) DECLARE_EXCEPTION_TYPE(Base, OpenFailed) DECLARE_EXCEPTION_TYPE(Base, CloseFailed) }; -protected: + protected: // Derived class implementations for connection managment - virtual AbstractRPCConnection *OpenSpecificConnection(SocketType *socket) = 0; + virtual AbstractRPCConnection *OpenSpecificConnection(SocketType *socket) = + 0; -private: + private: typedef std::set InternalInterfaceSet; InternalInterfaceSet m_internalInterfacesSet; - virtual void OnEventReceived(const DPL::Socket::AbstractSocketEvents::AcceptEvent &event) + virtual void OnEventReceived( + const DPL::Socket::AbstractSocketEvents::AcceptEvent &event) { // Retrieve socket sender SocketType *server = static_cast(event.GetSender()); // Is this interface still tracked ? // It might have disappeared on close - typename InternalInterfaceSet::iterator iterator = m_internalInterfacesSet.find(server); + typename InternalInterfaceSet::iterator iterator = + m_internalInterfacesSet.find(server); - if (iterator == m_internalInterfacesSet.end()) - { + if (iterator == m_internalInterfacesSet.end()) { LogPedantic("RPC server interface socket disappeared"); return; } // Accept incoming client SocketType *client = static_cast(server->Accept()); - if(client == NULL) - { + if (client == NULL) { LogPedantic("Spontaneous accept on socket occurred"); return; } - LogPedantic("Client connected to server: " << client->GetRemoteAddress().ToString()); + LogPedantic( + "Client connected to server: " << + client->GetRemoteAddress().ToString()); // Open specific connection implementation AbstractRPCConnection *connection = OpenSpecificConnection(client); // Retrieve ID once again - AbstractRPCConnectionID connectionID = static_cast(server); + AbstractRPCConnectionID connectionID = + static_cast(server); // Inform listeners - DPL::Event::EventSupport:: + DPL::Event::EventSupport:: EmitEvent(AbstractRPCConnectorEvents::ConnectionEstablishedEvent( - connectionID, connection, EventSender(this)), DPL::Event::EmitMode::Queued); + connectionID, connection, EventSender( + this)), DPL::Event::EmitMode::Queued); } -public: + public: explicit GenericSocketRPCServer() - { - } + {} virtual ~GenericSocketRPCServer() { @@ -109,7 +112,8 @@ public: SocketType *socket = new SocketType(); // Add socket listener - socket->EventSupport::AddListener(this); + socket->EventSupport:: + AddListener(this); Try { @@ -122,10 +126,11 @@ public: // Start listening socket->Listen(8); } - Catch (DPL::Socket::AbstractSocket::Exception::Base) + Catch(DPL::Socket::AbstractSocket::Exception::Base) { // Remove back socket listener - socket->EventSupport::RemoveListener(this); + socket->EventSupport + ::RemoveListener(this); // Log debug LogPedantic("Cannot start server: " << socketAddress.ToString()); @@ -138,7 +143,9 @@ public: m_internalInterfacesSet.insert(socket); // Debug info - LogPedantic("Server started on interface: " << socket->GetLocalAddress().ToString()); + LogPedantic( + "Server started on interface: " << + socket->GetLocalAddress().ToString()); // Return unique identifier return static_cast(socket); @@ -152,16 +159,19 @@ public: SocketType *socket = static_cast(connectionID); // Find corresponding internal connection - typename InternalInterfaceSet::iterator iterator = m_internalInterfacesSet.find(socket); + typename InternalInterfaceSet::iterator iterator = + m_internalInterfacesSet.find(socket); - if (iterator == m_internalInterfacesSet.end()) + if (iterator == m_internalInterfacesSet.end()) { return; + } // Close socket socket->Close(); // Remove socket listeners - socket->EventSupport::RemoveListener(this); + socket->EventSupport:: + RemoveListener(this); delete socket; m_internalInterfacesSet.erase(iterator); @@ -172,11 +182,12 @@ public: void CloseAll() { - while (!m_internalInterfacesSet.empty()) - Close(static_cast(*m_internalInterfacesSet.begin())); + while (!m_internalInterfacesSet.empty()) { + Close(static_cast(*m_internalInterfacesSet + .begin())); + } } }; - } } // namespace DPL diff --git a/modules/rpc/include/dpl/rpc/rpc_function.h b/modules/rpc/include/dpl/rpc/rpc_function.h index 4a121ff..a01235f 100644 --- a/modules/rpc/include/dpl/rpc/rpc_function.h +++ b/modules/rpc/include/dpl/rpc/rpc_function.h @@ -29,20 +29,17 @@ #include #include -namespace DPL -{ -namespace RPC -{ - +namespace DPL { +namespace RPC { class RPCFunction : public IStream { -protected: + protected: BinaryQueue m_buffer; ///< Serialized RPC function call as a binary queue -public: + public: class Exception { - public: + public: DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) DECLARE_EXCEPTION_TYPE(Base, ParseFailed) }; @@ -51,8 +48,7 @@ public: * Constructor */ RPCFunction() - { - } + {} /** * Constructor @@ -68,15 +64,15 @@ public: * Destructor */ virtual ~RPCFunction() - { - } + {} /** * Append argument to call * * @param[in] arg Template based argument to append * @return none - * @warning Carefully add any pointers to buffer because of template nature of this method + * @warning Carefully add any pointers to buffer because of template nature + * of this method */ template void AppendArg(const Type &arg) @@ -116,7 +112,8 @@ public: * (same as they were pushed onto RPC function argument stack) * * @param[out] arg Reference to output template based argument - * @warning Carefully add any pointers to buffer because of template nature of this method + * @warning Carefully add any pointers to buffer because of template nature + * of this method * @return none */ template @@ -127,19 +124,21 @@ public: size_t argSize = sizeof(arg); m_buffer.FlattenConsume(&argSize, sizeof(argSize)); - if (argSize != sizeof(arg)) + if (argSize != sizeof(arg)) { ThrowMsg(Exception::ParseFailed, "Stream parse CRC failed"); + } m_buffer.FlattenConsume(&arg, sizeof(arg)); } - Catch (BinaryQueue::Exception::OutOfData) + Catch(BinaryQueue::Exception::OutOfData) { ReThrowMsg(Exception::ParseFailed, "Unexpected end of stream"); } } /** - * Consume @a std::string argument from call. Arguments are retrieved in non-reversed order + * Consume @a std::string argument from call. Arguments are retrieved in + * non-reversed order * (same as they were pushed onto RPC function argument stack) * * @param[out] arg Reference to output @a std::string argument @@ -155,14 +154,15 @@ public: m_buffer.FlattenConsume(str.Get(), size); arg = std::string(str.Get(), str.Get() + size); } - Catch (BinaryQueue::Exception::OutOfData) + Catch(BinaryQueue::Exception::OutOfData) { ReThrowMsg(Exception::ParseFailed, "Unexpected end of stream"); } } /** - * Consume @a DPL::String argument from call. Arguments are converted to UTF-8 string + * Consume @a DPL::String argument from call. Arguments are converted to + * UTF-8 string * * @param[out] arg Reference to output @a DPL::String argument * @return none @@ -206,7 +206,6 @@ public: m_buffer.AppendCopy(bytes, num); } }; - } } // namespace DPL diff --git a/modules/rpc/include/dpl/rpc/unix_socket_rpc_client.h b/modules/rpc/include/dpl/rpc/unix_socket_rpc_client.h index 730a349..aba62ec 100644 --- a/modules/rpc/include/dpl/rpc/unix_socket_rpc_client.h +++ b/modules/rpc/include/dpl/rpc/unix_socket_rpc_client.h @@ -26,21 +26,18 @@ #include #include -namespace DPL +namespace DPL { +namespace RPC { +class UnixSocketRPCClient : + public GenericSocketRPCClient { -namespace RPC -{ - -class UnixSocketRPCClient - : public GenericSocketRPCClient -{ -protected: - virtual AbstractRPCConnection *OpenSpecificConnection(DPL::Socket::UnixSocket *socket); + protected: + virtual AbstractRPCConnection *OpenSpecificConnection( + DPL::Socket::UnixSocket *socket); -public: + public: AbstractRPCConnectionID Open(const std::string &fileName); }; - } } // namespace DPL diff --git a/modules/rpc/include/dpl/rpc/unix_socket_rpc_connection.h b/modules/rpc/include/dpl/rpc/unix_socket_rpc_connection.h index 5981596..9b00141 100644 --- a/modules/rpc/include/dpl/rpc/unix_socket_rpc_connection.h +++ b/modules/rpc/include/dpl/rpc/unix_socket_rpc_connection.h @@ -25,19 +25,15 @@ #include #include -namespace DPL +namespace DPL { +namespace RPC { +class UnixSocketRPCConnection : + public GenericSocketRPCConnection { -namespace RPC -{ - -class UnixSocketRPCConnection - : public GenericSocketRPCConnection -{ -public: + public: // Socket acquisition UnixSocketRPCConnection(DPL::Socket::UnixSocket *socket); }; - } } // namespace DPL diff --git a/modules/rpc/include/dpl/rpc/unix_socket_rpc_server.h b/modules/rpc/include/dpl/rpc/unix_socket_rpc_server.h index a6d7335..de2b605 100644 --- a/modules/rpc/include/dpl/rpc/unix_socket_rpc_server.h +++ b/modules/rpc/include/dpl/rpc/unix_socket_rpc_server.h @@ -26,21 +26,18 @@ #include #include -namespace DPL +namespace DPL { +namespace RPC { +class UnixSocketRPCServer : + public GenericSocketRPCServer { -namespace RPC -{ - -class UnixSocketRPCServer - : public GenericSocketRPCServer -{ -protected: - virtual AbstractRPCConnection *OpenSpecificConnection(DPL::Socket::UnixSocket *socket); + protected: + virtual AbstractRPCConnection *OpenSpecificConnection( + DPL::Socket::UnixSocket *socket); -public: + public: AbstractRPCConnectionID Open(const std::string &fileName); }; - } } // namespace DPL diff --git a/modules/rpc/src/generic_rpc_connection.cpp b/modules/rpc/src/generic_rpc_connection.cpp index bd472b0..6b16f28 100644 --- a/modules/rpc/src/generic_rpc_connection.cpp +++ b/modules/rpc/src/generic_rpc_connection.cpp @@ -26,14 +26,11 @@ #include #include -namespace DPL -{ -namespace RPC -{ +namespace DPL { +namespace RPC { namespace // anonymous { -namespace Protocol -{ +namespace Protocol { // Packet definitions enum PacketType { @@ -47,17 +44,17 @@ struct Header unsigned short type; } DPL_ALIGNED(1); -struct AsyncCall - : public Header +struct AsyncCall : + public Header { unsigned char data[1]; } DPL_ALIGNED(1); - } // namespace Protocol } // namespace anonymous -GenericRPCConnection::GenericRPCConnection(AbstractWaitableInputOutput *inputOutput) - : m_inputOutput(inputOutput) +GenericRPCConnection::GenericRPCConnection( + AbstractWaitableInputOutput *inputOutput) : + m_inputOutput(inputOutput) { LogPedantic("Opening generic RPC..."); WaitableInputOutputExecutionContextSupport::Open(inputOutput); @@ -92,7 +89,7 @@ void GenericRPCConnection::AsyncCall(const RPCFunction &function) { FeedOutput(); } - Catch (WaitableInputOutputExecutionContextSupport::Exception::NotOpened) + Catch(WaitableInputOutputExecutionContextSupport::Exception::NotOpened) { // Error occurred while feeding ReThrow(AbstractRPCConnection::Exception::AsyncCallFailed); @@ -115,7 +112,7 @@ void GenericRPCConnection::Ping() { FeedOutput(); } - Catch (WaitableInputOutputExecutionContextSupport::Exception::NotOpened) + Catch(WaitableInputOutputExecutionContextSupport::Exception::NotOpened) { // Error occurred while feeding ReThrow(AbstractRPCConnection::Exception::PingFailed); @@ -127,76 +124,82 @@ void GenericRPCConnection::OnInputStreamRead() LogPedantic("Interpreting " << m_inputStream.Size() << " bytes buffer"); // Enough bytes to read at least one header ? - if (m_inputStream.Size() >= sizeof(Protocol::Header)) - { + if (m_inputStream.Size() >= sizeof(Protocol::Header)) { // Begin consuming as much packets as it is possible - while (m_inputStream.Size() >= sizeof(Protocol::Header)) - { + while (m_inputStream.Size() >= sizeof(Protocol::Header)) { Protocol::Header header; m_inputStream.Flatten(&header, sizeof(header)); - if (m_inputStream.Size() >= sizeof(Protocol::Header) + header.size) + if (m_inputStream.Size() >= sizeof(Protocol::Header) + + header.size) { LogPedantic("Will parse packet of type: " << header.type); // Allocate new packet (header + real packet data) - void *binaryPacket = malloc(sizeof(Protocol::Header) + header.size); + void *binaryPacket = malloc( + sizeof(Protocol::Header) + header.size); - if (binaryPacket == NULL) + if (binaryPacket == NULL) { throw std::bad_alloc(); + } // Get it from stream - m_inputStream.FlattenConsume(binaryPacket, sizeof(Protocol::Header) + header.size); + m_inputStream.FlattenConsume( + binaryPacket, + sizeof(Protocol::Header) + + header.size); // Parse specific packet - switch (header.type) + switch (header.type) { + case Protocol::PacketType_AsyncCall: { - case Protocol::PacketType_AsyncCall: - { - BinaryQueue call; - - // No need to delete packet data, we can use it - call.AppendUnmanaged(binaryPacket, sizeof(Protocol::Header) + header.size, &BinaryQueue::BufferDeleterFree, NULL); - - // ...but just remove protocol header - call.Consume(sizeof(Protocol::Header)); - - LogPedantic("Async call of size: " << header.size << " parsed"); - - // Call async call event listeners - DPL::Event::EventSupport:: - EmitEvent(AbstractRPCConnectionEvents::AsyncCallEvent( - RPCFunction(call), EventSender(this)), DPL::Event::EmitMode::Queued); - } - break; + BinaryQueue call; + + // No need to delete packet data, we can use it + call.AppendUnmanaged(binaryPacket, + sizeof(Protocol::Header) + header.size, + &BinaryQueue::BufferDeleterFree, + NULL); + + // ...but just remove protocol header + call.Consume(sizeof(Protocol::Header)); + + LogPedantic( + "Async call of size: " << header.size << + " parsed"); + + // Call async call event listeners + DPL::Event::EventSupport:: + EmitEvent(AbstractRPCConnectionEvents::AsyncCallEvent( + RPCFunction(call), EventSender( + this)), DPL::Event::EmitMode::Queued); + } + break; - case Protocol::PacketType_PingPong: - { - // Reply with ping/pong - Ping(); + case Protocol::PacketType_PingPong: + { + // Reply with ping/pong + Ping(); - // Do not need packet data - free(binaryPacket); + // Do not need packet data + free(binaryPacket); - LogPedantic("Ping pong replied"); - } - break; + LogPedantic("Ping pong replied"); + } + break; - default: - LogPedantic("Warning: Unknown packet type"); - free(binaryPacket); - break; + default: + LogPedantic("Warning: Unknown packet type"); + free(binaryPacket); + break; } - } - else - { + } else { LogPedantic("Too few bytes to read packet"); break; } } - } - else - { + } else { LogPedantic("Too few bytes to read header"); } } @@ -204,18 +207,19 @@ void GenericRPCConnection::OnInputStreamRead() void GenericRPCConnection::OnInputStreamClosed() { // Emit closed event - DPL::Event::EventSupport:: + DPL::Event::EventSupport + :: EmitEvent(AbstractRPCConnectionEvents::ConnectionClosedEvent( - EventSender(this)), DPL::Event::EmitMode::Queued); + EventSender(this)), DPL::Event::EmitMode::Queued); } void GenericRPCConnection::OnInputStreamBroken() { // Emit broken event - DPL::Event::EventSupport:: + DPL::Event::EventSupport + :: EmitEvent(AbstractRPCConnectionEvents::ConnectionBrokenEvent( - EventSender(this)), DPL::Event::EmitMode::Queued); + EventSender(this)), DPL::Event::EmitMode::Queued); } - } } // namespace DPL diff --git a/modules/rpc/src/generic_socket_rpc_client.cpp b/modules/rpc/src/generic_socket_rpc_client.cpp index f75fdc8..51c1b97 100644 --- a/modules/rpc/src/generic_socket_rpc_client.cpp +++ b/modules/rpc/src/generic_socket_rpc_client.cpp @@ -17,7 +17,8 @@ * @file generic_socket_rpc_client.cpp * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) * @version 1.0 - * @brief This file is the implementation file of generic socket RPC client + * @brief This file is the implementation file of generic socket RPC + * client */ #include #include diff --git a/modules/rpc/src/generic_socket_rpc_connection.cpp b/modules/rpc/src/generic_socket_rpc_connection.cpp index 961a4dc..2d84a4a 100644 --- a/modules/rpc/src/generic_socket_rpc_connection.cpp +++ b/modules/rpc/src/generic_socket_rpc_connection.cpp @@ -17,7 +17,8 @@ * @file generic_socket_rpc_connection.cpp * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) * @version 1.0 - * @brief This file is the implementation file of generic socket RPC connection + * @brief This file is the implementation file of generic socket RPC + * connection */ #include #include diff --git a/modules/rpc/src/unix_socket_rpc_client.cpp b/modules/rpc/src/unix_socket_rpc_client.cpp index b4bb1f4..8b105f2 100644 --- a/modules/rpc/src/unix_socket_rpc_client.cpp +++ b/modules/rpc/src/unix_socket_rpc_client.cpp @@ -23,11 +23,10 @@ #include #include -namespace DPL -{ -namespace RPC -{ -AbstractRPCConnection *UnixSocketRPCClient::OpenSpecificConnection(DPL::Socket::UnixSocket *socket) +namespace DPL { +namespace RPC { +AbstractRPCConnection *UnixSocketRPCClient::OpenSpecificConnection( + DPL::Socket::UnixSocket *socket) { // Allocate new UNIX/RPC connection object UnixSocketRPCConnection *connection = new UnixSocketRPCConnection(socket); @@ -38,7 +37,8 @@ AbstractRPCConnection *UnixSocketRPCClient::OpenSpecificConnection(DPL::Socket:: AbstractRPCConnectionID UnixSocketRPCClient::Open(const std::string &fileName) { - return GenericSocketRPCClient::Open(Address(fileName)); + return GenericSocketRPCClient::Open(Address( + fileName)); } } } // namespace DPL diff --git a/modules/rpc/src/unix_socket_rpc_connection.cpp b/modules/rpc/src/unix_socket_rpc_connection.cpp index 1a4615f..b21098d 100644 --- a/modules/rpc/src/unix_socket_rpc_connection.cpp +++ b/modules/rpc/src/unix_socket_rpc_connection.cpp @@ -17,18 +17,17 @@ * @file unix_socket_rpc_connection.cpp * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) * @version 1.0 - * @brief This file is the implementation file of unix socket RPC connection + * @brief This file is the implementation file of unix socket RPC + * connection */ #include #include -namespace DPL -{ -namespace RPC -{ -UnixSocketRPCConnection::UnixSocketRPCConnection(DPL::Socket::UnixSocket *socket) - : GenericSocketRPCConnection(socket) -{ -} +namespace DPL { +namespace RPC { +UnixSocketRPCConnection::UnixSocketRPCConnection( + DPL::Socket::UnixSocket *socket) : + GenericSocketRPCConnection(socket) +{} } } // namespace DPL diff --git a/modules/rpc/src/unix_socket_rpc_server.cpp b/modules/rpc/src/unix_socket_rpc_server.cpp index 38992ab..e9dd9ab 100644 --- a/modules/rpc/src/unix_socket_rpc_server.cpp +++ b/modules/rpc/src/unix_socket_rpc_server.cpp @@ -23,11 +23,10 @@ #include #include -namespace DPL -{ -namespace RPC -{ -AbstractRPCConnection *UnixSocketRPCServer::OpenSpecificConnection(DPL::Socket::UnixSocket *socket) +namespace DPL { +namespace RPC { +AbstractRPCConnection *UnixSocketRPCServer::OpenSpecificConnection( + DPL::Socket::UnixSocket *socket) { // Allocate new UNIX/RPC connection object UnixSocketRPCConnection *connection = new UnixSocketRPCConnection(socket); @@ -38,8 +37,8 @@ AbstractRPCConnection *UnixSocketRPCServer::OpenSpecificConnection(DPL::Socket:: AbstractRPCConnectionID UnixSocketRPCServer::Open(const std::string &fileName) { - return GenericSocketRPCServer::Open(Address(fileName)); + return GenericSocketRPCServer::Open(Address( + fileName)); } - } } // namespace DPL diff --git a/modules/security_origin_dao/dao/security_origin_dao.cpp b/modules/security_origin_dao/dao/security_origin_dao.cpp index dda13e6..07c816f 100644 --- a/modules/security_origin_dao/dao/security_origin_dao.cpp +++ b/modules/security_origin_dao/dao/security_origin_dao.cpp @@ -37,7 +37,6 @@ using namespace DPL::DB::ORM; using namespace DPL::DB::ORM::security_origin; namespace SecurityOriginDB { - #define SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN Try #define SQL_CONNECTION_EXCEPTION_HANDLER_END(message) \ @@ -58,12 +57,12 @@ const char* const SECURITY_ORIGIN_DB_SQL_PATH = std::string createDatabasePath(const WrtDB::WidgetPkgName &pkgName) { - std::stringstream filename; + std::stringstream filename; - filename << WrtDB::WidgetConfig::GetWidgetPersistentStoragePath(pkgName) - << "/" - << SECURITY_ORIGIN_DB_NAME; - return filename.str(); + filename << WrtDB::WidgetConfig::GetWidgetPersistentStoragePath(pkgName) + << "/" + << SECURITY_ORIGIN_DB_NAME; + return filename.str(); } std::string createDatabasePath(int widgetHandle) @@ -95,7 +94,6 @@ void checkDatabase(std::string databasePath) struct stat buffer; if (stat(databasePath.c_str(), &buffer) != 0) { - //Create fresh database LogInfo("Creating database " << databasePath); @@ -147,7 +145,9 @@ SecurityOriginDataList SecurityOriginDAO::getSecurityOriginDataList(void) SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { SecurityOriginDataList list; - SECURITY_ORIGIN_DB_SELECT(select, SecurityOriginInfo, &m_securityOriginDBInterface); + SECURITY_ORIGIN_DB_SELECT(select, + SecurityOriginInfo, + &m_securityOriginDBInterface); typedef std::list RowList; RowList rowList = select->GetRowList(); @@ -163,15 +163,21 @@ SecurityOriginDataList SecurityOriginDAO::getSecurityOriginDataList(void) SQL_CONNECTION_EXCEPTION_HANDLER_END("Failed to get data list") } -Result SecurityOriginDAO::getResult(const SecurityOriginData &securityOriginData) +Result SecurityOriginDAO::getResult( + const SecurityOriginData &securityOriginData) { SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { - SECURITY_ORIGIN_DB_SELECT(select, SecurityOriginInfo, &m_securityOriginDBInterface); + SECURITY_ORIGIN_DB_SELECT(select, + SecurityOriginInfo, + &m_securityOriginDBInterface); select->Where( - And(And(And(Equals(securityOriginData.feature), - Equals(securityOriginData.origin.scheme)), - Equals(securityOriginData.origin.host)), + And(And(And(Equals(securityOriginData. + feature), + Equals(securityOriginData. + origin.scheme)), + Equals(securityOriginData.origin. + host)), Equals(securityOriginData.origin.port))); SecurityOriginInfo::Select::RowList rows = select->GetRowList(); @@ -181,11 +187,13 @@ Result SecurityOriginDAO::getResult(const SecurityOriginData &securityOriginData SecurityOriginInfo::Row row = rows.front(); return static_cast(row.Get_result()); } - SQL_CONNECTION_EXCEPTION_HANDLER_END("Failed to get result for security origin") + SQL_CONNECTION_EXCEPTION_HANDLER_END( + "Failed to get result for security origin") } -void SecurityOriginDAO::setSecurityOriginData(const SecurityOriginData &securityOriginData, - const Result result) +void SecurityOriginDAO::setSecurityOriginData( + const SecurityOriginData &securityOriginData, + const Result result) { SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { @@ -199,8 +207,8 @@ void SecurityOriginDAO::setSecurityOriginData(const SecurityOriginData &security if (true == hasResult(securityOriginData)) { SECURITY_ORIGIN_DB_UPDATE(update, - SecurityOriginInfo, - &m_securityOriginDBInterface); + SecurityOriginInfo, + &m_securityOriginDBInterface); update->Values(row); update->Execute(); } else { @@ -224,12 +232,18 @@ void SecurityOriginDAO::removeSecurityOriginData( ScopedTransaction transaction(&m_securityOriginDBInterface); if (true == hasResult(securityOriginData)) { - SECURITY_ORIGIN_DB_DELETE(del, SecurityOriginInfo, &m_securityOriginDBInterface) + 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))); + And(And(And(Equals( + securityOriginData.feature), + Equals( + securityOriginData.origin.scheme)), + Equals(securityOriginData. + origin.host)), + Equals(securityOriginData.origin. + port))); del->Execute(); transaction.Commit(); } @@ -242,7 +256,9 @@ void SecurityOriginDAO::removeSecurityOriginData(const Result result) SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { ScopedTransaction transaction(&m_securityOriginDBInterface); - SECURITY_ORIGIN_DB_DELETE(del, SecurityOriginInfo, &m_securityOriginDBInterface) + SECURITY_ORIGIN_DB_DELETE(del, + SecurityOriginInfo, + &m_securityOriginDBInterface) del->Where(Equals(result)); del->Execute(); transaction.Commit(); @@ -252,11 +268,10 @@ void SecurityOriginDAO::removeSecurityOriginData(const Result result) bool SecurityOriginDAO::hasResult(const SecurityOriginData &securityOriginData) { - Result res=getResult(securityOriginData); + Result res = getResult(securityOriginData); return (res != RESULT_UNKNOWN); } #undef SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN #undef SQL_CONNECTION_EXCEPTION_HANDLER_END - } // namespace SecurityOriginDB diff --git a/modules/security_origin_dao/dao/security_origin_dao_types.cpp b/modules/security_origin_dao/dao/security_origin_dao_types.cpp index 2e87959..601b277 100644 --- a/modules/security_origin_dao/dao/security_origin_dao_types.cpp +++ b/modules/security_origin_dao/dao/security_origin_dao_types.cpp @@ -25,5 +25,4 @@ #include #include -namespace SecurityOriginDB { -} // namespace SecurityOriginDB \ No newline at end of file +namespace SecurityOriginDB {} // namespace SecurityOriginDB \ No newline at end of file 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 9dc7d9c..f9ad12f 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 @@ -27,7 +27,6 @@ #include namespace SecurityOriginDB { - class SecurityOriginDAO { public: @@ -48,6 +47,7 @@ class SecurityOriginDAO const Result result); void removeSecurityOriginData(const SecurityOriginData &securityOriginData); void removeSecurityOriginData(const Result result); + private: std::string m_securityOriginDBPath; DPL::DB::ThreadDatabaseSupport m_securityOriginDBInterface; @@ -55,7 +55,6 @@ class SecurityOriginDAO }; 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 35081ca..c517f05 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 @@ -29,7 +29,6 @@ #include namespace SecurityOriginDB { - enum Feature { FEATURE_START = 0, @@ -61,14 +60,13 @@ struct Origin scheme(Scheme), host(Host), port(Port) - { - } + {} - bool operator== (const Origin& other) const + bool operator== (const Origin& other) const { return (!DPL::StringCompare(scheme, other.scheme) && - !DPL::StringCompare(host, other.host) && - port == other.port); + !DPL::StringCompare(host, other.host) && + port == other.port); } bool operator!= (const Origin& other) const @@ -85,8 +83,7 @@ struct SecurityOriginData SecurityOriginData(const Feature features, const Origin& ori) : feature(features), origin(ori) - { - } + {} bool operator== (const SecurityOriginData& other) const { @@ -102,7 +99,6 @@ struct SecurityOriginData typedef std::shared_ptr SecurityOriginDataPtr; typedef std::list SecurityOriginDataList; - } // namespace SecurityOriginDB #endif // _SECURITY_ORIGIN_DAO_TYPES_H_ diff --git a/modules/security_origin_dao/include/wrt-commons/security-origin-dao/security_origin_database.h b/modules/security_origin_dao/include/wrt-commons/security-origin-dao/security_origin_database.h index d94b588..d401620 100644 --- a/modules/security_origin_dao/include/wrt-commons/security-origin-dao/security_origin_database.h +++ b/modules/security_origin_dao/include/wrt-commons/security-origin-dao/security_origin_database.h @@ -23,15 +23,15 @@ extern DPL::Mutex g_securityOriginDBQueriesMutex; #define SECURITY_ORIGIN_DB_INTERNAL(tlsCommand, InternalType, interface) \ - static DPL::ThreadLocalVariable *tlsCommand ## Ptr = NULL; \ + static DPL::ThreadLocalVariable *tlsCommand##Ptr = NULL; \ { \ DPL::Mutex::ScopedLock lock(&g_securityOriginDBQueriesMutex); \ - if (!tlsCommand ## Ptr) { \ + if (!tlsCommand##Ptr) { \ static DPL::ThreadLocalVariable tmp; \ - tlsCommand ## Ptr = &tmp; \ + tlsCommand##Ptr = &tmp; \ } \ } \ - DPL::ThreadLocalVariable &tlsCommand = *tlsCommand ## Ptr; \ + DPL::ThreadLocalVariable &tlsCommand = *tlsCommand##Ptr; \ if (tlsCommand.IsNull()) { tlsCommand = InternalType(interface); } #define SECURITY_ORIGIN_DB_SELECT(name, type, interface) \ diff --git a/modules/socket/include/dpl/socket/abstract_socket.h b/modules/socket/include/dpl/socket/abstract_socket.h index 90a8fa6..0c06f99 100644 --- a/modules/socket/include/dpl/socket/abstract_socket.h +++ b/modules/socket/include/dpl/socket/abstract_socket.h @@ -28,12 +28,9 @@ #include #include -namespace DPL -{ -namespace Socket -{ -namespace AbstractSocketEvents -{ +namespace DPL { +namespace Socket { +namespace AbstractSocketEvents { // Successfuly connected to server socket DECLARE_GENERIC_EVENT_0(ConnectedEvent) @@ -47,51 +44,144 @@ DECLARE_GENERIC_EVENT_0(ReadEvent) DECLARE_GENERIC_EVENT_0(WriteEvent) } // namespace AbstractSocketEvents -class AbstractSocket - : public AbstractWaitableInputOutput, - public DPL::Event::EventSupport, - public DPL::Event::EventSupport, - public DPL::Event::EventSupport, - public DPL::Event::EventSupport +class AbstractSocket : + public AbstractWaitableInputOutput, + public DPL::Event::EventSupport, + public DPL::Event::EventSupport, + public DPL::Event::EventSupport, + public DPL::Event::EventSupport { -public: + public: class Exception { - public: - DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) ///< Base abstract socket exception - - DECLARE_EXCEPTION_TYPE(Base, OpenFailed) ///< Fatal error occurred during open socket descriptor. Socket state is inconsistent and it should be not used anymore. - - DECLARE_EXCEPTION_TYPE(Base, ConnectFailed) ///< Fatal error occurred during connect. Socket state is inconsistent and it should be not used anymore. - ///< Warning: This exception does not mean that socket did not succeed to connect, see CannotConnect - ///< for this specific scenario - - DECLARE_EXCEPTION_TYPE(Base, SetNonBlockingFailed) ///< Fatal error occurred during setting socket to non-blocking mode. Socket state is inconsistent and it should be not used anymore. - - DECLARE_EXCEPTION_TYPE(Base, BindFailed) ///< Fatal error occurred during bind. Socket state is inconsistent and it should be not used anymore. - - DECLARE_EXCEPTION_TYPE(Base, AcceptFailed) ///< Fatal error occurred during accept. Socket state is inconsistent and it should be not used anymore. - - DECLARE_EXCEPTION_TYPE(Base, ListenFailed) ///< Fatal error occurred during listen. Socket state is inconsistent and it should be not used anymore. - - DECLARE_EXCEPTION_TYPE(Base, CloseFailed) ///< Fatal error occurred during close. Socket state is inconsistent and it should be not used anymore. - - DECLARE_EXCEPTION_TYPE(Base, ReadFailed) ///< Fatal error occurred during read. Socket state is inconsistent and it should be not used anymore. - ///< Warning: This exception does not mean that connection was broken, see ConnectionBroken - ///< for this specific scenario - - DECLARE_EXCEPTION_TYPE(Base, WriteFailed) ///< Fatal error occurred during write. Socket state is inconsistent and it should be not used anymore. - ///< Warning: This exception does not mean that connection was broken, see ConnectionBroken - ///< for this specific scenario - - DECLARE_EXCEPTION_TYPE(Base, GetPeerNameFailed) ///< Fatal error occurred during getpeername or getsockname. Socket state is inconsistent and it should be not used anymore. - - DECLARE_EXCEPTION_TYPE(Base, CannotConnect) ///< Cannot connect to remote socket. This is not fatal error, socket state is still consistent and it can be reconnected. - - DECLARE_EXCEPTION_TYPE(Base, ConnectionBroken) ///< Connection was broken. This is not fatal error, socket state is still consistent and it can be reconnected. + public: + DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) ///< Base abstract + // socket exception + + DECLARE_EXCEPTION_TYPE(Base, OpenFailed) ///< Fatal error + // occurred during + // open socket + // descriptor. Socket + // state is + // inconsistent and + // it should be not + // used anymore. + + DECLARE_EXCEPTION_TYPE(Base, ConnectFailed) ///< Fatal error + // occurred during + // connect. Socket + // state is + // inconsistent and + // it should be not + // used anymore. + ///< Warning: This + // exception does not + // mean that socket + // did not succeed to + // connect, see + // CannotConnect + ///< for this + // specific scenario + + DECLARE_EXCEPTION_TYPE(Base, SetNonBlockingFailed) ///< Fatal error + // occurred during + // setting socket to + // non-blocking mode. + // Socket state is + // inconsistent and + // it should be not + // used anymore. + + DECLARE_EXCEPTION_TYPE(Base, BindFailed) ///< Fatal error + // occurred during + // bind. Socket state + // is inconsistent + // and it should be + // not used anymore. + + DECLARE_EXCEPTION_TYPE(Base, AcceptFailed) ///< Fatal error + // occurred during + // accept. Socket + // state is + // inconsistent and + // it should be not + // used anymore. + + DECLARE_EXCEPTION_TYPE(Base, ListenFailed) ///< Fatal error + // occurred during + // listen. Socket + // state is + // inconsistent and + // it should be not + // used anymore. + + DECLARE_EXCEPTION_TYPE(Base, CloseFailed) ///< Fatal error + // occurred during + // close. Socket + // state is + // inconsistent and + // it should be not + // used anymore. + + DECLARE_EXCEPTION_TYPE(Base, ReadFailed) ///< Fatal error + // occurred during + // read. Socket state + // is inconsistent + // and it should be + // not used anymore. + ///< Warning: This + // exception does not + // mean that + // connection was + // broken, see + // ConnectionBroken + ///< for this + // specific scenario + + DECLARE_EXCEPTION_TYPE(Base, WriteFailed) ///< Fatal error + // occurred during + // write. Socket + // state is + // inconsistent and + // it should be not + // used anymore. + ///< Warning: This + // exception does not + // mean that + // connection was + // broken, see + // ConnectionBroken + ///< for this + // specific scenario + + DECLARE_EXCEPTION_TYPE(Base, GetPeerNameFailed) ///< Fatal error + // occurred during + // getpeername or + // getsockname. + // Socket state is + // inconsistent and + // it should be not + // used anymore. + + DECLARE_EXCEPTION_TYPE(Base, CannotConnect) ///< Cannot connect + // to remote socket. + // This is not fatal + // error, socket + // state is still + // consistent and it + // can be + // reconnected. + + DECLARE_EXCEPTION_TYPE(Base, ConnectionBroken) ///< Connection was + // broken. This is + // not fatal error, + // socket state is + // still consistent + // and it can be + // reconnected. }; -public: + public: virtual ~AbstractSocket() {} // Connect to remote host @@ -119,7 +209,6 @@ public: // Remote socket address virtual Address GetRemoteAddress() const = 0; }; - } } // namespace DPL diff --git a/modules/socket/include/dpl/socket/generic_socket.h b/modules/socket/include/dpl/socket/generic_socket.h index f54d752..3ed9b86 100644 --- a/modules/socket/include/dpl/socket/generic_socket.h +++ b/modules/socket/include/dpl/socket/generic_socket.h @@ -35,33 +35,33 @@ #include #include -namespace DPL -{ -namespace Socket -{ +namespace DPL { +namespace Socket { // // Generic abstract socket implementation // Execution context is inherited // template -class GenericSocket - : public AbstractSocket, - private WaitableHandleWatchSupport::WaitableHandleListener +class GenericSocket : + public AbstractSocket, + private WaitableHandleWatchSupport::WaitableHandleListener { -protected: + protected: /** * Translate generic Address to specific socket kernel structure * * @warning Must be implemented in derived class */ - virtual std::pair TranslateAddressGenericToSpecific(const Address &address) const = 0; + virtual std::pair TranslateAddressGenericToSpecific( + const Address &address) const = 0; /** * Translate specific socket kernel structure to generic Address * * @warning Must be implemented in derived class */ - virtual Address TranslateAddressSpecificToGeneric(sockaddr *, socklen_t) const = 0; + virtual Address TranslateAddressSpecificToGeneric(sockaddr *, + socklen_t) const = 0; /** * Get specific socket kernel structure size @@ -84,12 +84,13 @@ protected: */ virtual int AllocSpecificDescriptor() const = 0; -private: + private: // Constants static const size_t DEFAULT_READ_BUFFER_SIZE = 4096; // Socket handle - int m_socket; // FIXME: Consider generalization to WaitableHandle upon leaving nix platform + int m_socket; // FIXME: Consider generalization to WaitableHandle upon + // leaving nix platform // Internal state enum InternalState @@ -106,128 +107,143 @@ private: void SetNonBlocking() { // Set non-blocking mode - if (fcntl(m_socket, F_SETFL, O_NONBLOCK | fcntl(m_socket, F_GETFL)) == -1) + if (fcntl(m_socket, F_SETFL, O_NONBLOCK | + fcntl(m_socket, F_GETFL)) == -1) + { Throw(AbstractSocket::Exception::SetNonBlockingFailed); + } } // WaitableHandleWatchSupport::WaitableHandleListener - virtual void OnWaitableHandleEvent(WaitableHandle waitableHandle, WaitMode::Type mode) + virtual void OnWaitableHandleEvent(WaitableHandle waitableHandle, + WaitMode::Type mode) { (void)waitableHandle; Assert(waitableHandle == m_socket); - switch (m_internalState) - { - case InternalState_None: - break; - - case InternalState_Prepare: - Assert(0 && "Invalid internal generic socket state!"); - break; + switch (m_internalState) { + case InternalState_None: + break; - case InternalState_Listening: - Assert(mode == WaitMode::Read); + case InternalState_Prepare: + Assert(0 && "Invalid internal generic socket state!"); + break; - // New client waiting for accept - DPL::Event::EventSupport:: - EmitEvent(AbstractSocketEvents::AcceptEvent( - EventSender(this)), DPL::Event::EmitMode::Queued); + case InternalState_Listening: + Assert(mode == WaitMode::Read); - // Done - break; + // New client waiting for accept + DPL::Event::EventSupport:: + EmitEvent(AbstractSocketEvents::AcceptEvent( + EventSender(this)), DPL::Event::EmitMode::Queued); - case InternalState_Connecting: - Assert(mode == WaitMode::Write); + // Done + break; - // Connected to server - RemoveConnectWatch(); - m_internalState = InternalState_Connected; + case InternalState_Connecting: + Assert(mode == WaitMode::Write); - // Add read watch - AddReadWatch(); - - // Emit event - DPL::Event::EventSupport:: - EmitEvent(AbstractSocketEvents::ConnectedEvent( - EventSender(this)), DPL::Event::EmitMode::Queued); + // Connected to server + RemoveConnectWatch(); + m_internalState = InternalState_Connected; - // Done - break; + // Add read watch + AddReadWatch(); - case InternalState_Connected: - if (mode == WaitMode::Read) - { - // Emit ReadEvent - DPL::Event::EventSupport:: - EmitEvent(AbstractSocketEvents::ReadEvent( - EventSender(this)), DPL::Event::EmitMode::Queued); - } - else if (mode == WaitMode::Write) - { - // Emit WriteEvent - DPL::Event::EventSupport:: - EmitEvent(AbstractSocketEvents::WriteEvent( - EventSender(this)), DPL::Event::EmitMode::Queued); - } - else - { - Assert(0); - } + // Emit event + DPL::Event::EventSupport:: + EmitEvent(AbstractSocketEvents::ConnectedEvent( + EventSender(this)), DPL::Event::EmitMode::Queued); + + // Done + break; + + case InternalState_Connected: + if (mode == WaitMode::Read) { + // Emit ReadEvent + DPL::Event::EventSupport:: + EmitEvent(AbstractSocketEvents::ReadEvent( + EventSender( + this)), DPL::Event::EmitMode::Queued); + } else if (mode == WaitMode::Write) { + // Emit WriteEvent + DPL::Event::EventSupport:: + EmitEvent(AbstractSocketEvents::WriteEvent( + EventSender( + this)), DPL::Event::EmitMode::Queued); + } else { + Assert(0); + } - break; + break; - default: - Assert(0); - break; + default: + Assert(0); + break; } } void AddAcceptWatch() { - WaitableHandleWatchSupport::InheritedContext()->AddWaitableHandleWatch(this, m_socket, WaitMode::Read); + WaitableHandleWatchSupport::InheritedContext()->AddWaitableHandleWatch( + this, + m_socket, + WaitMode::Read); } void RemoveAcceptWatch() { - WaitableHandleWatchSupport::InheritedContext()->RemoveWaitableHandleWatch(this, m_socket, WaitMode::Read); + WaitableHandleWatchSupport::InheritedContext()-> + RemoveWaitableHandleWatch(this, m_socket, WaitMode::Read); } void AddConnectWatch() { - WaitableHandleWatchSupport::InheritedContext()->AddWaitableHandleWatch(this, m_socket, WaitMode::Write); + WaitableHandleWatchSupport::InheritedContext()->AddWaitableHandleWatch( + this, + m_socket, + WaitMode::Write); } void RemoveConnectWatch() { - WaitableHandleWatchSupport::InheritedContext()->RemoveWaitableHandleWatch(this, m_socket, WaitMode::Write); + WaitableHandleWatchSupport::InheritedContext()-> + RemoveWaitableHandleWatch(this, m_socket, WaitMode::Write); } void AddReadWatch() { - WaitableHandleWatchSupport::InheritedContext()->AddWaitableHandleWatch(this, m_socket, WaitMode::Read); + WaitableHandleWatchSupport::InheritedContext()->AddWaitableHandleWatch( + this, + m_socket, + WaitMode::Read); } void RemoveReadWatch() { - WaitableHandleWatchSupport::InheritedContext()->RemoveWaitableHandleWatch(this, m_socket, WaitMode::Read); + WaitableHandleWatchSupport::InheritedContext()-> + RemoveWaitableHandleWatch(this, m_socket, WaitMode::Read); } void AddWriteWatch() { - WaitableHandleWatchSupport::InheritedContext()->AddWaitableHandleWatch(this, m_socket, WaitMode::Write); + WaitableHandleWatchSupport::InheritedContext()->AddWaitableHandleWatch( + this, + m_socket, + WaitMode::Write); } void RemoveWriteWatch() { - WaitableHandleWatchSupport::InheritedContext()->RemoveWaitableHandleWatch(this, m_socket, WaitMode::Write); + WaitableHandleWatchSupport::InheritedContext()-> + RemoveWaitableHandleWatch(this, m_socket, WaitMode::Write); } -public: - GenericSocket() - : m_socket(-1), - m_internalState(InternalState_None) - { - } + public: + GenericSocket() : + m_socket(-1), + m_internalState(InternalState_None) + {} virtual ~GenericSocket() { @@ -247,8 +263,10 @@ public: virtual void Open() { - if (m_internalState != InternalState_None) - ThrowMsg(AbstractSocket::Exception::OpenFailed, "Invalid socket state, should be 'None'"); + if (m_internalState != InternalState_None) { + ThrowMsg(AbstractSocket::Exception::OpenFailed, + "Invalid socket state, should be 'None'"); + } LogPedantic("Opening socket..."); @@ -269,8 +287,10 @@ public: virtual void Connect(const Address &address) { - if (m_internalState != InternalState_Prepare) - ThrowMsg(AbstractSocket::Exception::ConnectFailed, "Invalid socket state, should be 'Prepare'"); + if (m_internalState != InternalState_Prepare) { + ThrowMsg(AbstractSocket::Exception::ConnectFailed, + "Invalid socket state, should be 'Prepare'"); + } LogPedantic("Connecting to: " << address.ToString()); @@ -282,17 +302,19 @@ public: // Translate address to specific socket address struct socketAddress = TranslateAddressGenericToSpecific(address); } - Catch (Address::Exception::InvalidAddress) + Catch(Address::Exception::InvalidAddress) { // This address is invalid. Cannot connect. - ReThrowMsg(AbstractSocket::Exception::ConnectFailed, address.ToString()); + ReThrowMsg(AbstractSocket::Exception::ConnectFailed, + address.ToString()); } // Do connect - int result = TEMP_FAILURE_RETRY(connect(m_socket, socketAddress.first, socketAddress.second)); + int result = + TEMP_FAILURE_RETRY(connect(m_socket, socketAddress.first, + socketAddress.second)); - if (result == 0) - { + if (result == 0) { // Immediate connect LogPedantic("Immediate connected to: " << address.ToString()); @@ -303,25 +325,22 @@ public: // Emit connected event DPL::Event::EventSupport:: EmitEvent(AbstractSocketEvents::ConnectedEvent( - EventSender(this)), DPL::Event::EmitMode::Queued); - } - else - { - if (errno == EINTR || errno == EINPROGRESS) - { - LogPedantic("Asynchronous connect in progress: " << address.ToString()); + EventSender(this)), DPL::Event::EmitMode::Queued); + } else { + if (errno == EINTR || errno == EINPROGRESS) { + LogPedantic( + "Asynchronous connect in progress: " << address.ToString()); // Connecting in progress AddConnectWatch(); m_internalState = InternalState_Connecting; - } - else - { + } else { // Free translation structure free(socketAddress.first); // Error occurred - ThrowMsg(AbstractSocket::Exception::ConnectFailed, address.ToString()); + ThrowMsg(AbstractSocket::Exception::ConnectFailed, + address.ToString()); } } @@ -331,40 +350,35 @@ public: virtual void Close() { - if (m_internalState == InternalState_None) + if (m_internalState == InternalState_None) { return; + } Assert(m_socket != -1); - if (m_internalState == InternalState_Listening) - { + if (m_internalState == InternalState_Listening) { // Remove watch in listening state LogPedantic("Removing accept watch"); RemoveAcceptWatch(); m_internalState = InternalState_None; - } - else if (m_internalState == InternalState_Connecting) - { + } else if (m_internalState == InternalState_Connecting) { // Remove watch in connecting state LogPedantic("Removing connect watch"); RemoveConnectWatch(); m_internalState = InternalState_None; - } - else if (m_internalState == InternalState_Connected) - { + } else if (m_internalState == InternalState_Connected) { // Remove watch in connected state LogPedantic("Removing read watch"); RemoveReadWatch(); m_internalState = InternalState_None; - } - else - { + } else { // State must be just prepared only Assert(m_internalState == InternalState_Prepare); } - if (TEMP_FAILURE_RETRY(close(m_socket)) == -1) + if (TEMP_FAILURE_RETRY(close(m_socket)) == -1) { Throw(Exception::CloseFailed); + } // Reset socket m_socket = -1; @@ -377,35 +391,48 @@ public: virtual void Bind(const Address &address) { - if (m_internalState != InternalState_Prepare) - ThrowMsg(AbstractSocket::Exception::BindFailed, "Invalid socket state, should be 'Prepare'"); + if (m_internalState != InternalState_Prepare) { + ThrowMsg(AbstractSocket::Exception::BindFailed, + "Invalid socket state, should be 'Prepare'"); + } - LogPedantic("Binding to: " << address.GetAddress() << ":" << address.GetPort()); + LogPedantic( + "Binding to: " << address.GetAddress() << ":" << address.GetPort()); // Translate address to specific socket address struct - std::pair socketAddress = TranslateAddressGenericToSpecific(address); + std::pair socketAddress = TranslateAddressGenericToSpecific( + address); // Do bind - if (::bind(m_socket, socketAddress.first, socketAddress.second) == -1) + if (::bind(m_socket, socketAddress.first, + socketAddress.second) == -1) + { ThrowMsg(AbstractSocket::Exception::BindFailed, address.ToString()); + } // Free translation structure free(socketAddress.first); // Show info - LogPedantic("Bound to address: " << address.GetAddress() << ":" << address.GetPort()); + LogPedantic( + "Bound to address: " << address.GetAddress() << ":" << + address.GetPort()); } virtual void Listen(int backlog) { - if (m_internalState != InternalState_Prepare) - ThrowMsg(AbstractSocket::Exception::ListenFailed, "Invalid socket state, should be 'None'"); + if (m_internalState != InternalState_Prepare) { + ThrowMsg(AbstractSocket::Exception::ListenFailed, + "Invalid socket state, should be 'None'"); + } LogPedantic("Starting to listen..."); // Do listen - if (listen(m_socket, backlog) != 0) + if (listen(m_socket, backlog) != 0) { Throw(AbstractSocket::Exception::ListenFailed); + } // Begin read watch AddAcceptWatch(); @@ -416,8 +443,10 @@ public: virtual AbstractSocket *Accept() { - if (m_internalState != InternalState_Listening) - ThrowMsg(AbstractSocket::Exception::AcceptFailed, "Invalid socket state, should be 'Listening'"); + if (m_internalState != InternalState_Listening) { + ThrowMsg(AbstractSocket::Exception::AcceptFailed, + "Invalid socket state, should be 'Listening'"); + } LogPedantic("Accepting..."); @@ -426,14 +455,15 @@ public: int client = TEMP_FAILURE_RETRY(accept(m_socket, NULL, &length)); LogPedantic("Socket accept returned " << client); - if (client == -1) - { + if (client == -1) { // Check if there is any client waiting - if (errno == EWOULDBLOCK || errno == EAGAIN) + if (errno == EWOULDBLOCK || errno == EAGAIN) { return NULL; + } int err = errno; - if (errno == ENOENT) + if (errno == ENOENT) { return NULL; + } LogPedantic("throwing error. errrno " << err); // Error occurred Throw(AbstractSocket::Exception::AcceptFailed); @@ -466,10 +496,16 @@ public: // FIXME: Additional internal state check socklen_t length = GetSpecificAddressSize(); - ScopedFree address(static_cast(calloc(static_cast(length), 1))); - - if (getsockname(m_socket, address.Get(), &length) == -1) - ThrowMsg(AbstractSocket::Exception::GetPeerNameFailed, "Failed to get local address"); + ScopedFree address(static_cast(calloc( + static_cast< + size_t>( + length), + 1))); + + if (getsockname(m_socket, address.Get(), &length) == -1) { + ThrowMsg(AbstractSocket::Exception::GetPeerNameFailed, + "Failed to get local address"); + } return TranslateAddressSpecificToGeneric(address.Get(), length); } @@ -479,55 +515,65 @@ public: // FIXME: Additional internal state check socklen_t length = GetSpecificAddressSize(); - ScopedFree address(static_cast(calloc(static_cast(length), 1))); - - if (getpeername(m_socket, address.Get(), &length) == -1) - ThrowMsg(AbstractSocket::Exception::GetPeerNameFailed, "Failed to get remote address"); + ScopedFree address(static_cast(calloc( + static_cast< + size_t>( + length), + 1))); + + if (getpeername(m_socket, address.Get(), &length) == -1) { + ThrowMsg(AbstractSocket::Exception::GetPeerNameFailed, + "Failed to get remote address"); + } return TranslateAddressSpecificToGeneric(address.Get(), length); } virtual BinaryQueueAutoPtr Read(size_t size) { - if (m_internalState != InternalState_Connected) - ThrowMsg(AbstractSocket::Exception::AcceptFailed, "Invalid socket state, should be 'Connected'"); + if (m_internalState != InternalState_Connected) { + ThrowMsg(AbstractSocket::Exception::AcceptFailed, + "Invalid socket state, should be 'Connected'"); + } Try { // Adjust bytes to be read - size_t bytesToRead = size > DEFAULT_READ_BUFFER_SIZE ? DEFAULT_READ_BUFFER_SIZE : 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 + // It is unmanaged, so it can be then attached directly to binary + // queue void *buffer = malloc(bytesToRead); - if (buffer == NULL) + if (buffer == NULL) { throw std::bad_alloc(); + } // Receive bytes from socket - ssize_t result = TEMP_FAILURE_RETRY(recv(m_socket, buffer, bytesToRead, 0)); + ssize_t result = + TEMP_FAILURE_RETRY(recv(m_socket, buffer, bytesToRead, 0)); - if (result > 0) - { + if (result > 0) { // Succedded to read socket data BinaryQueueAutoPtr binaryQueue(new BinaryQueue()); // Append unmanaged memory - binaryQueue->AppendUnmanaged(buffer, result, &BinaryQueue::BufferDeleterFree, NULL); + binaryQueue->AppendUnmanaged(buffer, + result, + &BinaryQueue::BufferDeleterFree, + NULL); // Return buffer return binaryQueue; - } - else if (result == 0) - { + } else if (result == 0) { // Socket was gracefuly closed free(buffer); // Return empty buffer return BinaryQueueAutoPtr(new BinaryQueue()); - } - else - { + } else { // Must first save errno value, because it may be altered int lastErrno = errno; @@ -535,108 +581,132 @@ public: free(buffer); // Interpret error result - switch (lastErrno) - { - case EAGAIN: // = EWOULDBLOCK - // - // * The socket's file descriptor is marked O_NONBLOCK and no data is waiting - // to be received; or MSG_OOB is set and no out-of-band data is available - // and either the socket's file descriptor is marked O_NONBLOCK or the socket - // does not support blocking to await out-of-band data. - // - // return null data buffer to indicate no data waiting - // - return BinaryQueueAutoPtr(); - - case EBADF: - // - // * The socket argument is not a valid file descriptor. - // - // This is internal error - // - ThrowMsg(CommonException::InternalError, "Invalid socket descriptor"); - - case ECONNRESET: - // - // * A connection was forcibly closed by a peer. - // - // In result, we can interpret this error as a broken connection - // - Throw(AbstractSocket::Exception::ConnectionBroken); - - case EINTR: - // - // * The recv() function was interrupted by a signal that was caught, before any - // data was available. - // - // No interrupt here is expected, due to fact that we used TEMP_FAILURE_RETRY - // - ThrowMsg(CommonException::InternalError, "Unexpected interrupt occurred"); - - case EINVAL: - // - // * The MSG_OOB flag is set and no out-of-band data is available. - // - // We did not specified OOB data. This is an error. - // - ThrowMsg(CommonException::InternalError, "Unexpected OOB error occurred"); - - case ENOTCONN: - // - // * A receive is attempted on a connection-mode socket that is not connected. - // - // FIXME: Is this proper exception here ? - // - ThrowMsg(CommonException::InternalError, "Socket is not connected"); - - case ENOTSOCK: - // - // * The socket argument does not refer to a socket. - // - ThrowMsg(CommonException::InternalError, "Handle is not a socket"); - - case EOPNOTSUPP: - // - // * The specified flags are not supported for this socket type or protocol. - // - ThrowMsg(CommonException::InternalError, "Socket flags not supported"); - - case ETIMEDOUT: - // - // * The connection timed out during connection establishment, or due to a transmission timeout on active connection. - // - // In result, we can interpret this error as a broken connection - // - Throw(AbstractSocket::Exception::ConnectionBroken); - - case EIO: - // - // * An I/O error occurred while reading from or writing to the file system. - // - // In result, we can interpret this error as a broken connection - // - Throw(AbstractSocket::Exception::ConnectionBroken); - - case ENOBUFS: - // - // * Insufficient resources were available in the system to perform the operation. - // - ThrowMsg(CommonException::InternalError, "Insufficient system resources"); - - case ENOMEM: - // - // * Insufficient memory was available to fulfill the request. - // - ThrowMsg(CommonException::InternalError, "Insufficient system memory"); - - default: - // Some kernel error occurred, should never happen - ThrowMsg(CommonException::InternalError, "Unknown kernel read error returned"); - break; + switch (lastErrno) { + case EAGAIN: // = EWOULDBLOCK + // + // * The socket's file descriptor is marked O_NONBLOCK and + // no data is waiting + // to be received; or MSG_OOB is set and no out-of-band + // data is available + // and either the socket's file descriptor is marked + // O_NONBLOCK or the socket + // does not support blocking to await out-of-band data. + // + // return null data buffer to indicate no data waiting + // + return BinaryQueueAutoPtr(); + + case EBADF: + // + // * The socket argument is not a valid file descriptor. + // + // This is internal error + // + ThrowMsg(CommonException::InternalError, + "Invalid socket descriptor"); + + case ECONNRESET: + // + // * A connection was forcibly closed by a peer. + // + // In result, we can interpret this error as a broken + // connection + // + Throw(AbstractSocket::Exception::ConnectionBroken); + + case EINTR: + // + // * The recv() function was interrupted by a signal that + // was caught, before any + // data was available. + // + // No interrupt here is expected, due to fact that we used + // TEMP_FAILURE_RETRY + // + ThrowMsg(CommonException::InternalError, + "Unexpected interrupt occurred"); + + case EINVAL: + // + // * The MSG_OOB flag is set and no out-of-band data is + // available. + // + // We did not specified OOB data. This is an error. + // + ThrowMsg(CommonException::InternalError, + "Unexpected OOB error occurred"); + + case ENOTCONN: + // + // * A receive is attempted on a connection-mode socket that + // is not connected. + // + // FIXME: Is this proper exception here ? + // + ThrowMsg(CommonException::InternalError, + "Socket is not connected"); + + case ENOTSOCK: + // + // * The socket argument does not refer to a socket. + // + ThrowMsg(CommonException::InternalError, + "Handle is not a socket"); + + case EOPNOTSUPP: + // + // * The specified flags are not supported for this socket + // type or protocol. + // + ThrowMsg(CommonException::InternalError, + "Socket flags not supported"); + + case ETIMEDOUT: + // + // * The connection timed out during connection + // establishment, or due to a transmission timeout on active + // connection. + // + // In result, we can interpret this error as a broken + // connection + // + Throw(AbstractSocket::Exception::ConnectionBroken); + + case EIO: + // + // * An I/O error occurred while reading from or writing to + // the file system. + // + // In result, we can interpret this error as a broken + // connection + // + Throw(AbstractSocket::Exception::ConnectionBroken); + + case ENOBUFS: + // + // * Insufficient resources were available in the system to + // perform the operation. + // + ThrowMsg(CommonException::InternalError, + "Insufficient system resources"); + + case ENOMEM: + // + // * Insufficient memory was available to fulfill the + // request. + // + ThrowMsg(CommonException::InternalError, + "Insufficient system memory"); + + default: + // Some kernel error occurred, should never happen + ThrowMsg(CommonException::InternalError, + "Unknown kernel read error returned"); + break; } } } - Catch (CommonException::InternalError) + Catch(CommonException::InternalError) { // If any internal error occurred, this is fatal for Write method // interpret this as WriteError exception and rethrow @@ -646,14 +716,17 @@ public: virtual size_t Write(const BinaryQueue &buffer, size_t bufferSize) { - if (m_internalState != InternalState_Connected) - ThrowMsg(AbstractSocket::Exception::AcceptFailed, "Invalid socket state, should be 'Connected'"); + if (m_internalState != InternalState_Connected) { + ThrowMsg(AbstractSocket::Exception::AcceptFailed, + "Invalid socket state, should be 'Connected'"); + } Try { // Adjust write size - if (bufferSize > buffer.Size()) + if (bufferSize > buffer.Size()) { bufferSize = buffer.Size(); + } // FIXME: User write visitor to write ! // WriteVisitor visitor @@ -663,149 +736,176 @@ public: // Linux: MSG_NOSIGNAL is supported, but it is not an ideal solution // FIXME: Should we setup signal PIPE ignoring for whole process ? - // In BSD, there is: setsockopt(c, SOL_SOCKET, SO_NOSIGPIPE, (void *)&on, sizeof(on)) - ssize_t result = TEMP_FAILURE_RETRY(send(m_socket, flattened.Get(), bufferSize, MSG_NOSIGNAL)); + // In BSD, there is: setsockopt(c, SOL_SOCKET, SO_NOSIGPIPE, (void + // *)&on, sizeof(on)) + ssize_t result = + TEMP_FAILURE_RETRY(send(m_socket, flattened.Get(), bufferSize, + MSG_NOSIGNAL)); - if (result > 0) - { + if (result > 0) { // Successfuly written some bytes return static_cast(result); - } - else if (result == 0) - { + } else if (result == 0) { // This is abnormal result - ThrowMsg(CommonException::InternalError, "Invalid socket write result, 0 bytes written"); - } - else if (result == -1) - { + ThrowMsg(CommonException::InternalError, + "Invalid socket write result, 0 bytes written"); + } else if (result == -1) { // Interpret error result - switch (errno) - { - case EAGAIN: // = EWOULDBLOCK - // - // * The socket's file descriptor is marked O_NONBLOCK and the requested operation would block. - // - // We should wait for writability - // - return 0; - - case EBADF: - // - // * The socket argument is not a valid file descriptor. - // - // This is internal error - // - ThrowMsg(CommonException::InternalError, "Invalid socket descriptor"); - - case ECONNRESET: - // - // * A connection was forcibly closed by a peer. - // - // In result, we can interpret this error as a broken connection - // - Throw(AbstractSocket::Exception::ConnectionBroken); - - case EDESTADDRREQ: - // - // * The socket is not connection-mode and no peer address is set. - // - // FIXME: Is this proper exception here ? - // - ThrowMsg(CommonException::InternalError, "Socket is not connected"); - - case EINTR: - // - // * A signal interrupted send() before any data was transmitted. - // - // No interrupt here is expected, due to fact that we used TEMP_FAILURE_RETRY - // - ThrowMsg(CommonException::InternalError, "Unexpected interrupt occurred"); - - case EMSGSIZE: - // - // * The message is too large to be sent all at once, as the socket requires. - // - // FIXME: Is this proper exception here ? - // - ThrowMsg(CommonException::InternalError, "Socket message is too big"); - - case ENOTCONN: - // - // * The socket is not connected or otherwise has not had the peer pre-specified. - // - // FIXME: Is this proper exception here ? - // - ThrowMsg(CommonException::InternalError, "Socket is not connected"); - - case ENOTSOCK: - // - // * The socket argument does not refer to a socket. - // - ThrowMsg(CommonException::InternalError, "Handle is not a socket"); - - case EOPNOTSUPP: - // - // * The socket argument is associated with a socket that does not support one or more of the values set in flags. - // - ThrowMsg(CommonException::InternalError, "Socket flags not supported"); - - case EPIPE: - // - // * The socket is shut down for writing, or the socket is connection-mode and - // is no longer connected. In the latter case, and if the socket is of type - // SOCK_STREAM, the SIGPIPE signal is generated to the calling thread. - // - // In result, we can interpret this error as a broken connection - // - Throw(AbstractSocket::Exception::ConnectionBroken); - - case EACCES: - // - // * The calling process does not have the appropriate privileges. - // - // Priviledges might have changed. - // In result, we can interpret this error as a broken connection - // - Throw(AbstractSocket::Exception::ConnectionBroken); - - case EIO: - // - // * An I/O error occurred while reading from or writing to the file system. - // - // In result, we can interpret this error as a broken connection - // - Throw(AbstractSocket::Exception::ConnectionBroken); - - case ENETDOWN: - // - // * The local network interface used to reach the destination is down. - // - // In result, we can interpret this error as a broken connection - // - Throw(AbstractSocket::Exception::ConnectionBroken); - - case ENETUNREACH: - // - // * No route to the network is present. - // - // In result, we can interpret this error as a broken connection - // - Throw(AbstractSocket::Exception::ConnectionBroken); - - case ENOBUFS: - // - // * Insufficient resources were available in the system to perform the operation. - // - ThrowMsg(CommonException::InternalError, "Insufficient system resources"); - - default: - // Some kernel error occurred, should never happen - ThrowMsg(CommonException::InternalError, "Unknown kernel write error returned"); - break; + switch (errno) { + case EAGAIN: // = EWOULDBLOCK + // + // * The socket's file descriptor is marked O_NONBLOCK and + // the requested operation would block. + // + // We should wait for writability + // + return 0; + + case EBADF: + // + // * The socket argument is not a valid file descriptor. + // + // This is internal error + // + ThrowMsg(CommonException::InternalError, + "Invalid socket descriptor"); + + case ECONNRESET: + // + // * A connection was forcibly closed by a peer. + // + // In result, we can interpret this error as a broken + // connection + // + Throw(AbstractSocket::Exception::ConnectionBroken); + + case EDESTADDRREQ: + // + // * The socket is not connection-mode and no peer address + // is set. + // + // FIXME: Is this proper exception here ? + // + ThrowMsg(CommonException::InternalError, + "Socket is not connected"); + + case EINTR: + // + // * A signal interrupted send() before any data was + // transmitted. + // + // No interrupt here is expected, due to fact that we used + // TEMP_FAILURE_RETRY + // + ThrowMsg(CommonException::InternalError, + "Unexpected interrupt occurred"); + + case EMSGSIZE: + // + // * The message is too large to be sent all at once, as the + // socket requires. + // + // FIXME: Is this proper exception here ? + // + ThrowMsg(CommonException::InternalError, + "Socket message is too big"); + + case ENOTCONN: + // + // * The socket is not connected or otherwise has not had + // the peer pre-specified. + // + // FIXME: Is this proper exception here ? + // + ThrowMsg(CommonException::InternalError, + "Socket is not connected"); + + case ENOTSOCK: + // + // * The socket argument does not refer to a socket. + // + ThrowMsg(CommonException::InternalError, + "Handle is not a socket"); + + case EOPNOTSUPP: + // + // * The socket argument is associated with a socket that + // does not support one or more of the values set in flags. + // + ThrowMsg(CommonException::InternalError, + "Socket flags not supported"); + + case EPIPE: + // + // * The socket is shut down for writing, or the socket is + // connection-mode and + // is no longer connected. In the latter case, and if the + // socket is of type + // SOCK_STREAM, the SIGPIPE signal is generated to the + // calling thread. + // + // In result, we can interpret this error as a broken + // connection + // + Throw(AbstractSocket::Exception::ConnectionBroken); + + case EACCES: + // + // * The calling process does not have the appropriate + // privileges. + // + // Priviledges might have changed. + // In result, we can interpret this error as a broken + // connection + // + Throw(AbstractSocket::Exception::ConnectionBroken); + + case EIO: + // + // * An I/O error occurred while reading from or writing to + // the file system. + // + // In result, we can interpret this error as a broken + // connection + // + Throw(AbstractSocket::Exception::ConnectionBroken); + + case ENETDOWN: + // + // * The local network interface used to reach the + // destination is down. + // + // In result, we can interpret this error as a broken + // connection + // + Throw(AbstractSocket::Exception::ConnectionBroken); + + case ENETUNREACH: + // + // * No route to the network is present. + // + // In result, we can interpret this error as a broken + // connection + // + Throw(AbstractSocket::Exception::ConnectionBroken); + + case ENOBUFS: + // + // * Insufficient resources were available in the system to + // perform the operation. + // + ThrowMsg(CommonException::InternalError, + "Insufficient system resources"); + + default: + // Some kernel error occurred, should never happen + ThrowMsg(CommonException::InternalError, + "Unknown kernel write error returned"); + break; } } } - Catch (CommonException::InternalError) + Catch(CommonException::InternalError) { // If any internal error occurred, this is fatal for Write method // interpret this as WriteError exception and rethrow @@ -828,7 +928,6 @@ public: return m_socket; } }; - } } // namespace DPL diff --git a/modules/socket/include/dpl/socket/unix_socket.h b/modules/socket/include/dpl/socket/unix_socket.h index 3d7b9fe..37614ce 100644 --- a/modules/socket/include/dpl/socket/unix_socket.h +++ b/modules/socket/include/dpl/socket/unix_socket.h @@ -25,32 +25,31 @@ #include #include -namespace DPL +namespace DPL { +namespace Socket { +class UnixSocket : + public GenericSocket { -namespace Socket -{ - -class UnixSocket - : public GenericSocket -{ -public: + public: class Exception { - public: + public: DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) DECLARE_EXCEPTION_TYPE(Base, CreateFailed) }; -protected: - /** - * Translate generic Address to specific socket kernel structure - */ - virtual std::pair TranslateAddressGenericToSpecific(const Address &address) const; + protected: + /** + * Translate generic Address to specific socket kernel structure + */ + virtual std::pair TranslateAddressGenericToSpecific( + const Address &address) const; /** * Translate specific socket kernel structure to generic Address */ - virtual Address TranslateAddressSpecificToGeneric(sockaddr *, socklen_t) const; + virtual Address TranslateAddressSpecificToGeneric(sockaddr *, + socklen_t) const; /** * Get specific socket kernel structure size @@ -67,12 +66,11 @@ protected: */ virtual int AllocSpecificDescriptor() const; -public: + public: UnixSocket(); virtual void Bind(const Address &address); }; - } } // namespace DPL diff --git a/modules/socket/include/dpl/socket/waitable_input_output_execution_context_support.h b/modules/socket/include/dpl/socket/waitable_input_output_execution_context_support.h index cfdbac2..f02df51 100644 --- a/modules/socket/include/dpl/socket/waitable_input_output_execution_context_support.h +++ b/modules/socket/include/dpl/socket/waitable_input_output_execution_context_support.h @@ -17,7 +17,8 @@ * @file waitable_input_output_execution_context_support.h * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) * @version 1.0 - * @brief This file is the header file for waitable input-output execution context support + * @brief This file is the header file for waitable input-output execution + * context support */ #ifndef DPL_WAITABLE_INPUT_OUTPUT_EXECUTION_CONTEXT_SUPPORT_H #define DPL_WAITABLE_INPUT_OUTPUT_EXECUTION_CONTEXT_SUPPORT_H @@ -26,18 +27,15 @@ #include #include -namespace DPL +namespace DPL { +namespace Socket { +class WaitableInputOutputExecutionContextSupport : + private WaitableHandleWatchSupport::WaitableHandleListener { -namespace Socket -{ - -class WaitableInputOutputExecutionContextSupport - : private WaitableHandleWatchSupport::WaitableHandleListener -{ -public: + public: class Exception { - public: + public: DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) DECLARE_EXCEPTION_TYPE(Base, AlreadyOpened) DECLARE_EXCEPTION_TYPE(Base, NotOpened) @@ -45,7 +43,7 @@ public: DECLARE_EXCEPTION_TYPE(Base, CloseFailed) }; -private: + private: bool m_opened; AbstractWaitableInputOutput *m_waitableInputOutput; @@ -65,9 +63,10 @@ private: void CheckedRemoveReadWriteWatch(); - virtual void OnWaitableHandleEvent(WaitableHandle waitableHandle, WaitMode::Type mode); + virtual void OnWaitableHandleEvent(WaitableHandle waitableHandle, + WaitMode::Type mode); -protected: + protected: // Incoming/Outgoing streams BinaryQueue m_inputStream; BinaryQueue m_outputStream; @@ -84,7 +83,7 @@ protected: void Open(AbstractWaitableInputOutput *waitableInputOutput); void Close(); -public: + public: /** * Constructor */ @@ -95,7 +94,6 @@ public: */ virtual ~WaitableInputOutputExecutionContextSupport(); }; - } } // namespace DPL diff --git a/modules/socket/src/unix_socket.cpp b/modules/socket/src/unix_socket.cpp index 3dd905c..36bff51 100644 --- a/modules/socket/src/unix_socket.cpp +++ b/modules/socket/src/unix_socket.cpp @@ -32,14 +32,10 @@ #include #include -namespace DPL -{ -namespace Socket -{ - +namespace DPL { +namespace Socket { UnixSocket::UnixSocket() -{ -} +{} int UnixSocket::AllocSpecificDescriptor() const { @@ -48,8 +44,9 @@ int UnixSocket::AllocSpecificDescriptor() const // Create new descriptor int newSocket = socket(AF_UNIX, SOCK_STREAM, 0); - if (newSocket == -1) + if (newSocket == -1) { Throw(Exception::CreateFailed); + } LogPedantic("UNIX socket created"); @@ -57,27 +54,36 @@ int UnixSocket::AllocSpecificDescriptor() const return newSocket; } -std::pair UnixSocket::TranslateAddressGenericToSpecific(const Address &address) const +std::pair UnixSocket::TranslateAddressGenericToSpecific( + const Address &address) const { // Allocate new socket address structure - sockaddr_un *sockAddress = static_cast(malloc(sizeof(sockaddr_un))); - if (!sockAddress) throw std::bad_alloc(); + sockaddr_un *sockAddress = + static_cast(malloc(sizeof(sockaddr_un))); + if (!sockAddress) { + throw std::bad_alloc(); + } memset(sockAddress, 0, sizeof(sockaddr_un)); // Copy address properties sockAddress->sun_family = AF_UNIX; - strncpy(sockAddress->sun_path, address.GetAddress().c_str(), sizeof(sockAddress->sun_path) - 1); - sockAddress->sun_path[sizeof(sockAddress->sun_path) - 1] = '\0'; // Prevent buffer overflows + strncpy(sockAddress->sun_path, address.GetAddress().c_str(), + sizeof(sockAddress->sun_path) - 1); + + //Prevent buffer overflows + sockAddress->sun_path[sizeof(sockAddress->sun_path) - 1] = '\0'; // Set proper address length socklen_t sockAddressLength = SUN_LEN(sockAddress); // Return new translated address - return std::make_pair(reinterpret_cast(sockAddress), sockAddressLength); + return std::make_pair(reinterpret_cast(sockAddress), + sockAddressLength); } -Address UnixSocket::TranslateAddressSpecificToGeneric(sockaddr *address, socklen_t) const +Address UnixSocket::TranslateAddressSpecificToGeneric(sockaddr *address, + socklen_t) const { // FIXME: Constrain check ? sockaddr_un *unixAddress = reinterpret_cast(address); @@ -103,8 +109,10 @@ void UnixSocket::Bind(const Address &address) GenericSocket::Bind(address); // Always set proper permissions to the socket file - if(chmod(address.GetAddress().c_str(), 0777)<0){ - LogError("Error setting permissions to the socket file. Errno " << strerror(errno)); + if (chmod(address.GetAddress().c_str(), 0777) < 0) { + LogError( + "Error setting permissions to the socket file. Errno " << + strerror(errno)); } } } diff --git a/modules/socket/src/waitable_input_output_execution_context_support.cpp b/modules/socket/src/waitable_input_output_execution_context_support.cpp index 6edf9b2..35635b5 100644 --- a/modules/socket/src/waitable_input_output_execution_context_support.cpp +++ b/modules/socket/src/waitable_input_output_execution_context_support.cpp @@ -17,7 +17,8 @@ * @file waitable_input_output_execution_context_support.cpp * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) * @version 1.0 - * @brief This file is the implementation file of waitable input-output execution context support + * @brief This file is the implementation file of waitable input-output + * execution context support */ #include #include @@ -26,34 +27,34 @@ #include #include -namespace DPL -{ -namespace Socket -{ - +namespace DPL { +namespace Socket { namespace // anonymous { const size_t DEFAULT_READ_SIZE = 2048; } // namespace anonymous -WaitableInputOutputExecutionContextSupport::WaitableInputOutputExecutionContextSupport() - : m_opened(false), - m_waitableInputOutput(NULL), - m_hasReadWatch(false), - m_hasWriteWatch(false) -{ -} +WaitableInputOutputExecutionContextSupport:: + WaitableInputOutputExecutionContextSupport() : + m_opened(false), + m_waitableInputOutput(NULL), + m_hasReadWatch(false), + m_hasWriteWatch(false) +{} -WaitableInputOutputExecutionContextSupport::~WaitableInputOutputExecutionContextSupport() +WaitableInputOutputExecutionContextSupport::~ +WaitableInputOutputExecutionContextSupport() { // Ensure support is closed Close(); } -void WaitableInputOutputExecutionContextSupport::Open(AbstractWaitableInputOutput *inputOutput) +void WaitableInputOutputExecutionContextSupport::Open( + AbstractWaitableInputOutput *inputOutput) { - if (m_opened) + if (m_opened) { Throw(Exception::AlreadyOpened); + } LogPedantic("Opening waitable input-output execution context support..."); @@ -74,8 +75,9 @@ void WaitableInputOutputExecutionContextSupport::Open(AbstractWaitableInputOutpu void WaitableInputOutputExecutionContextSupport::Close() { - if (!m_opened) + if (!m_opened) { return; + } LogPedantic("Closing waitable input-output execution context support..."); @@ -90,28 +92,45 @@ void WaitableInputOutputExecutionContextSupport::Close() void WaitableInputOutputExecutionContextSupport::AddReadWatch() { - WaitableHandleWatchSupport::InheritedContext()->AddWaitableHandleWatch(this, m_waitableInputOutput->WaitableReadHandle(), WaitMode::Read); + WaitableHandleWatchSupport::InheritedContext()->AddWaitableHandleWatch( + this, + m_waitableInputOutput + ->WaitableReadHandle(), + WaitMode + ::Read); } void WaitableInputOutputExecutionContextSupport::RemoveReadWatch() { - WaitableHandleWatchSupport::InheritedContext()->RemoveWaitableHandleWatch(this, m_waitableInputOutput->WaitableReadHandle(), WaitMode::Read); + WaitableHandleWatchSupport::InheritedContext()->RemoveWaitableHandleWatch( + this, + m_waitableInputOutput->WaitableReadHandle(), + WaitMode::Read); } void WaitableInputOutputExecutionContextSupport::AddWriteWatch() { - WaitableHandleWatchSupport::InheritedContext()->AddWaitableHandleWatch(this, m_waitableInputOutput->WaitableWriteHandle(), WaitMode::Write); + WaitableHandleWatchSupport::InheritedContext()->AddWaitableHandleWatch( + this, + m_waitableInputOutput + ->WaitableWriteHandle(), + WaitMode + ::Write); } void WaitableInputOutputExecutionContextSupport::RemoveWriteWatch() { - WaitableHandleWatchSupport::InheritedContext()->RemoveWaitableHandleWatch(this, m_waitableInputOutput->WaitableWriteHandle(), WaitMode::Write); + WaitableHandleWatchSupport::InheritedContext()->RemoveWaitableHandleWatch( + this, + m_waitableInputOutput->WaitableWriteHandle(), + WaitMode::Write); } void WaitableInputOutputExecutionContextSupport::CheckedRemoveReadWatch() { - if (!m_hasReadWatch) + if (!m_hasReadWatch) { return; + } RemoveReadWatch(); m_hasReadWatch = false; @@ -119,8 +138,9 @@ void WaitableInputOutputExecutionContextSupport::CheckedRemoveReadWatch() void WaitableInputOutputExecutionContextSupport::CheckedRemoveWriteWatch() { - if (!m_hasWriteWatch) + if (!m_hasWriteWatch) { return; + } RemoveWriteWatch(); m_hasWriteWatch = false; @@ -135,40 +155,40 @@ void WaitableInputOutputExecutionContextSupport::CheckedRemoveReadWriteWatch() CheckedRemoveWriteWatch(); } -void WaitableInputOutputExecutionContextSupport::OnWaitableHandleEvent(WaitableHandle waitableHandle, WaitMode::Type mode) +void WaitableInputOutputExecutionContextSupport::OnWaitableHandleEvent( + WaitableHandle waitableHandle, + WaitMode::Type mode) { (void)waitableHandle; - switch (mode) - { - case WaitMode::Read: - LogPedantic("Read event occurred"); + switch (mode) { + case WaitMode::Read: + LogPedantic("Read event occurred"); - // Read and parse bytes - ReadInput(); + // Read and parse bytes + ReadInput(); - // Done - break; + // Done + break; - case WaitMode::Write: - LogPedantic("Write event occurred"); + case WaitMode::Write: + LogPedantic("Write event occurred"); - // Push bytes and unregister from write event - FeedOutput(); + // Push bytes and unregister from write event + FeedOutput(); - // Unregister write watch only if no more data is available - if (m_outputStream.Empty()) - { - Assert(m_hasWriteWatch == true); - CheckedRemoveWriteWatch(); - } + // Unregister write watch only if no more data is available + if (m_outputStream.Empty()) { + Assert(m_hasWriteWatch == true); + CheckedRemoveWriteWatch(); + } - // Done - break; + // Done + break; - default: - Assert(0); - break; + default: + Assert(0); + break; } } @@ -178,17 +198,16 @@ void WaitableInputOutputExecutionContextSupport::ReadInput() Try { - BinaryQueueAutoPtr inputBuffer = m_waitableInputOutput->Read(DEFAULT_READ_SIZE); + BinaryQueueAutoPtr inputBuffer = m_waitableInputOutput->Read( + DEFAULT_READ_SIZE); - if (inputBuffer.get() == NULL) - { + if (inputBuffer.get() == NULL) { // No data, should not occur LogPedantic("WARNING: Spontaneous ReadSocket occurred"); return; } - if (inputBuffer->Empty()) - { + if (inputBuffer->Empty()) { // Connection was closed OnInputStreamClosed(); @@ -208,8 +227,9 @@ void WaitableInputOutputExecutionContextSupport::ReadInput() // Append all read data m_inputStream.AppendMoveFrom(*inputBuffer); } - Catch (AbstractSocket::Exception::ConnectionBroken) // FIXME: Inproper exception abstraction !!! + Catch(AbstractSocket::Exception::ConnectionBroken) { + //FIXME: Inproper exception abstraction!!! // Some errors occurred while feeding abstract IO // Interpret connection broken errors, and pass futher other ones LogPedantic("Abstract IO connection was broken during read"); @@ -234,12 +254,14 @@ void WaitableInputOutputExecutionContextSupport::ReadInput() void WaitableInputOutputExecutionContextSupport::FeedOutput() { - if (!m_opened) + if (!m_opened) { Throw(Exception::NotOpened); + } // Anything to feed ? - if (m_outputStream.Empty()) + if (m_outputStream.Empty()) { return; + } // OK to feed output LogPedantic("Feeding output"); @@ -247,13 +269,13 @@ void WaitableInputOutputExecutionContextSupport::FeedOutput() Try { // Try to write some bytes - size_t bytes = m_waitableInputOutput->Write(m_outputStream, m_outputStream.Size()); + size_t bytes = m_waitableInputOutput->Write(m_outputStream, + m_outputStream.Size()); - if (bytes < m_outputStream.Size()) - { - // Start exhaustive output feeding if it is blocked and not already started - if (!m_hasWriteWatch) - { + if (bytes < m_outputStream.Size()) { + // Start exhaustive output feeding if it is blocked and not already + // started + if (!m_hasWriteWatch) { AddWriteWatch(); m_hasWriteWatch = true; @@ -264,7 +286,9 @@ void WaitableInputOutputExecutionContextSupport::FeedOutput() // Some bytes were written, consume them m_outputStream.Consume(bytes); } - Catch (AbstractSocket::Exception::ConnectionBroken) // FIXME: Inproper exception abstraction !!! + Catch(AbstractSocket::Exception::ConnectionBroken) // FIXME: Inproper + // exception abstraction + // !!! { // Some errors occurred while feeding abstract IO // Interpret connection broken errors, and pass futher other ones @@ -284,6 +308,5 @@ void WaitableInputOutputExecutionContextSupport::FeedOutput() return; } } - } } // namespace DPL diff --git a/modules/support/wrt_plugin_export.h b/modules/support/wrt_plugin_export.h index d091809..ae1e8e1 100644 --- a/modules/support/wrt_plugin_export.h +++ b/modules/support/wrt_plugin_export.h @@ -107,7 +107,6 @@ typedef struct ace_request_2_s #define PLUGIN_API_ACCESS_DENIED 0 #define PLUGIN_API_ACCESS_ERROR -1 - typedef const void* java_script_context_t; typedef struct js_object_properties_s @@ -120,10 +119,11 @@ typedef const void* js_class_template_t; typedef void* js_object_ref_t; typedef const void* js_value_ref_t; -typedef js_class_template_t (*js_class_template_getter) (void); +typedef js_class_template_t (*js_class_template_getter)(void); typedef void* (*js_class_constructor_cb_t)(js_class_template_t, - js_object_ref_t, size_t, js_value_ref_t[], - js_value_ref_t*); + js_object_ref_t, size_t, + js_value_ref_t[], + js_value_ref_t*); typedef enum class_definition_type_e { @@ -159,9 +159,9 @@ typedef enum class_definition_iframe_overlay_e typedef void* js_object_instance_t; //global_context - id -typedef void(*iframe_loaded_cb)(java_script_context_t global_context, - js_object_instance_t iframe, - js_object_instance_t object); +typedef void (*iframe_loaded_cb)(java_script_context_t global_context, + js_object_instance_t iframe, + js_object_instance_t object); typedef void* (*js_function_impl)(void*); @@ -176,7 +176,6 @@ typedef struct class_definition_options_s js_function_impl function; } class_definition_options_t; - /* * list of device caps */ @@ -204,7 +203,6 @@ typedef struct feature_mapping_s size_t featuresCount; } feature_mapping_t; - typedef feature_mapping_t* pfeature_mapping_t; typedef pfeature_mapping_t (*features_getter)(void); @@ -227,7 +225,6 @@ typedef struct feature_mapping_interface_s */ } feature_mapping_interface_t; - /* * This is a structure describing a JS entity template (a class, an interface * or function), object name and it's parent class name (parent_name). JS diff --git a/modules/test/include/dpl/test/test_results_collector.h b/modules/test/include/dpl/test/test_results_collector.h index d3f44bb..73fe1bf 100644 --- a/modules/test/include/dpl/test/test_results_collector.h +++ b/modules/test/include/dpl/test/test_results_collector.h @@ -30,17 +30,14 @@ #include #include -namespace DPL -{ -namespace Test -{ - +namespace DPL { +namespace Test { class TestResultsCollectorBase; typedef std::shared_ptr - TestResultsCollectorBasePtr; +TestResultsCollectorBasePtr; -class TestResultsCollectorBase - : private DPL::Noncopyable +class TestResultsCollectorBase : + private DPL::Noncopyable { public: typedef TestResultsCollectorBase* (*CollectorConstructorFunc)(); @@ -58,32 +55,40 @@ class TestResultsCollectorBase virtual ~TestResultsCollectorBase() {} - virtual bool Configure() { return true; } + virtual bool Configure() + { + return true; + } virtual void Start() { } virtual void Finish() { } - virtual void CollectCurrentTestGroupName(const std::string& /*groupName*/) {} + virtual void CollectCurrentTestGroupName(const std::string& /*groupName*/) + {} virtual void CollectTestsCasesList(const TestCaseIdList& /*list*/) {} virtual void CollectResult(const std::string& id, const std::string& description, const FailStatus::Type status = FailStatus::NONE, const std::string& reason = "") = 0; - virtual std::string CollectorSpecificHelp() const { return ""; } + virtual std::string CollectorSpecificHelp() const + { + return ""; + } virtual bool ParseCollectorSpecificArg (const std::string& /*arg*/) { return false; } static TestResultsCollectorBase* Create(const std::string& name); - static void RegisterCollectorConstructor(const std::string& name, - CollectorConstructorFunc constructor); + static void RegisterCollectorConstructor( + const std::string& name, + CollectorConstructorFunc + constructor); static std::vector GetCollectorsNames(); private: typedef std::map ConstructorsMap; static ConstructorsMap m_constructorsMap; }; - } } diff --git a/modules/test/include/dpl/test/test_runner.h b/modules/test/include/dpl/test/test_runner.h index 1c4d28a..c82a04d 100644 --- a/modules/test/include/dpl/test/test_runner.h +++ b/modules/test/include/dpl/test/test_runner.h @@ -34,27 +34,25 @@ #include #include -namespace DPL -{ -namespace Test -{ +namespace DPL { +namespace Test { class TestRunner { typedef std::map - TestResultsCollectors; + TestResultsCollectors; TestResultsCollectors m_collectors; std::string m_startTestId; bool m_runIgnored; -public: - TestRunner() - : m_terminate(false) + public: + TestRunner() : + m_terminate(false) {} typedef void (*TestCase)(); -private: + private: struct TestCaseStruct { std::string name; @@ -70,11 +68,10 @@ private: return name == other.name; } - TestCaseStruct(const std::string &n, TestCase p) - : name(n), - proc(p) - { - } + TestCaseStruct(const std::string &n, TestCase p) : + name(n), + proc(p) + {} }; typedef std::list TestCaseStructList; @@ -109,16 +106,15 @@ private: = TestResultsCollectorBase::FailStatus::NONE, const std::string& reason = std::string()); -public: + public: class TestFailed { - private: + private: std::string m_message; - public: + public: TestFailed() - { - } + {} //! \brief Failed test message creator //! @@ -126,7 +122,10 @@ public: //! \param[in] aFile source file name //! \param[in] aLine source file line //! \param[in] aMessage error message - TestFailed(const char* aTest, const char* aFile, int aLine, const std::string &aMessage); + TestFailed(const char* aTest, + const char* aFile, + int aLine, + const std::string &aMessage); TestFailed(const std::string &message); @@ -138,18 +137,16 @@ public: class Ignored { - private: + private: std::string m_message; - public: + public: Ignored() - { - } + {} - Ignored(const std::string &message) - : m_message(message) - { - } + Ignored(const std::string &message) : + m_message(message) + {} std::string GetMessage() const { @@ -171,17 +168,16 @@ public: }; typedef DPL::Singleton TestRunnerSingleton; - } } // namespace DPL #define RUNNER_TEST_GROUP_INIT(GroupName) \ static int Static##GroupName##Init() \ { \ - DPL::Test::TestRunnerSingleton::Instance().InitGroup(#GroupName);\ + DPL::Test::TestRunnerSingleton::Instance().InitGroup(#GroupName); \ return 0; \ } \ - const int DPL_UNUSED Static##GroupName##InitVar = \ + const int DPL_UNUSED Static##GroupName##InitVar = \ Static##GroupName##Init(); #define RUNNER_TEST(Proc) \ @@ -191,28 +187,35 @@ typedef DPL::Singleton TestRunnerSingleton; DPL::Test::TestRunnerSingleton::Instance().RegisterTest(#Proc, &Proc); \ return 0; \ } \ - const int DPL_UNUSED Static##Proc##InitVar = Static##Proc##Init(); \ + const int DPL_UNUSED Static##Proc##InitVar = Static##Proc##Init(); \ void Proc() //! \brief Returns base name for path #define RUNNER_ASSERT_MSG(test, message) \ -do \ -{ \ - DPL::Test::TestRunnerSingleton::Instance().MarkAssertion(); \ + do \ + { \ + DPL::Test::TestRunnerSingleton::Instance().MarkAssertion(); \ \ - if (!(test)) \ - { \ - std::ostringstream assertMsg; \ - assertMsg << message; \ - throw DPL::Test::TestRunner::TestFailed(#test, __FILE__, __LINE__, assertMsg.str()); \ - } \ -} while (0) + if (!(test)) \ + { \ + std::ostringstream assertMsg; \ + assertMsg << message; \ + throw DPL::Test::TestRunner::TestFailed(#test, \ + __FILE__, \ + __LINE__, \ + assertMsg.str()); \ + } \ + } while (0) #define RUNNER_ASSERT(test) RUNNER_ASSERT_MSG(test, "") #define RUNNER_FAIL RUNNER_ASSERT(false) -#define RUNNER_IGNORED_MSG(message) do { std::ostringstream assertMsg; assertMsg << message; throw DPL::Test::TestRunner::Ignored(assertMsg.str()); } while (0) +#define RUNNER_IGNORED_MSG(message) do { std::ostringstream assertMsg; \ + assertMsg << message; \ + throw DPL::Test::TestRunner::Ignored( \ + assertMsg.str()); \ +} while (0) #endif // DPL_TEST_RUNNER_H diff --git a/modules/test/include/dpl/test/test_runner_child.h b/modules/test/include/dpl/test/test_runner_child.h index 1eb9ea6..b20c371 100644 --- a/modules/test/include/dpl/test/test_runner_child.h +++ b/modules/test/include/dpl/test/test_runner_child.h @@ -26,9 +26,7 @@ namespace DPL { namespace Test { - void RunChildProc(TestRunner::TestCase procChild); - } // namespace Test } // namespace DPL diff --git a/modules/test/src/test_results_collector.cpp b/modules/test/src/test_results_collector.cpp index cde4567..482b132 100644 --- a/modules/test/src/test_results_collector.cpp +++ b/modules/test/src/test_results_collector.cpp @@ -35,15 +35,12 @@ #include #include -#define GREEN_RESULT_OK "[%s%s%s]\n", BOLD_GREEN_BEGIN, " OK ", BOLD_GREEN_END +#define GREEN_RESULT_OK "[%s%s%s]\n", BOLD_GREEN_BEGIN, " OK ", \ + BOLD_GREEN_END -namespace DPL -{ -namespace Test -{ - -namespace -{ +namespace DPL { +namespace Test { +namespace { const char *DEFAULT_HTML_FILE_NAME = "index.html"; const char *DEFAULT_TAP_FILE_NAME = "results.tap"; const char *DEFAULT_XML_FILE_NAME = "results.xml"; @@ -66,27 +63,44 @@ class Statistic m_ignored(0), m_passed(0), m_count(0) - { - } + {} void AddTest(TestResultsCollectorBase::FailStatus::Type type) { ++m_count; switch (type) { - case TestResultsCollectorBase::FailStatus::INTERNAL: - case TestResultsCollectorBase::FailStatus::FAILED: ++m_failed; break; - case TestResultsCollectorBase::FailStatus::IGNORED: ++m_ignored; break; - case TestResultsCollectorBase::FailStatus::NONE: ++m_passed; break; - default: - Assert(false && "Bad FailStatus"); + case TestResultsCollectorBase::FailStatus::INTERNAL: + case TestResultsCollectorBase::FailStatus::FAILED: ++m_failed; + break; + case TestResultsCollectorBase::FailStatus::IGNORED: ++m_ignored; + break; + case TestResultsCollectorBase::FailStatus::NONE: ++m_passed; + break; + default: + Assert(false && "Bad FailStatus"); } } - std::size_t GetTotal() const { return m_count; } - std::size_t GetPassed() const { return m_passed; } - std::size_t GetSuccesed() const { return m_passed; } - std::size_t GetFailed() const { return m_failed; } - std::size_t GetIgnored() const { return m_ignored; } + std::size_t GetTotal() const + { + return m_count; + } + std::size_t GetPassed() const + { + return m_passed; + } + std::size_t GetSuccesed() const + { + return m_passed; + } + std::size_t GetFailed() const + { + return m_failed; + } + std::size_t GetIgnored() const + { + return m_ignored; + } float GetPassedOrIgnoredPercend() const { float passIgnoredPercent = @@ -103,8 +117,8 @@ class Statistic std::size_t m_count; }; -class ConsoleCollector - : public TestResultsCollectorBase +class ConsoleCollector : + public TestResultsCollectorBase { public: static TestResultsCollectorBase* Constructor(); @@ -138,17 +152,21 @@ class ConsoleCollector std::string tmp = "'" + id + "' ..."; printf("Running test case %-60s", tmp.c_str()); - switch(status) { - case TestResultsCollectorBase::FailStatus::NONE: - printf(GREEN_RESULT_OK); break; - case TestResultsCollectorBase::FailStatus::FAILED: - PrintfErrorMessage( " FAILED ", reason, true); break; - case TestResultsCollectorBase::FailStatus::IGNORED: - PrintfIgnoredMessage("Ignored ", reason, true); break; - case TestResultsCollectorBase::FailStatus::INTERNAL: - PrintfErrorMessage( "INTERNAL", reason, true); break; - default: - Assert(false && "Bad status"); + switch (status) { + case TestResultsCollectorBase::FailStatus::NONE: + printf(GREEN_RESULT_OK); + break; + case TestResultsCollectorBase::FailStatus::FAILED: + PrintfErrorMessage(" FAILED ", reason, true); + break; + case TestResultsCollectorBase::FailStatus::IGNORED: + PrintfIgnoredMessage("Ignored ", reason, true); + break; + case TestResultsCollectorBase::FailStatus::INTERNAL: + PrintfErrorMessage("INTERNAL", reason, true); + break; + default: + Assert(false && "Bad status"); } m_stats.AddTest(status); m_groupsStats[m_currentGroup].AddTest(status); @@ -169,9 +187,9 @@ class ConsoleCollector BOLD_YELLOW_END); } else { printf("[%s%s%s]\n", - BOLD_RED_BEGIN, - type, - BOLD_RED_END); + BOLD_RED_BEGIN, + type, + BOLD_RED_END); } } @@ -190,7 +208,7 @@ class ConsoleCollector BOLD_GOLD_END); } else { printf("[%s%s%s]\n", - CYAN_BEGIN , + CYAN_BEGIN, type, CYAN_END); } @@ -199,11 +217,28 @@ class ConsoleCollector void PrintStats(const std::string& title, const Statistic& stats) { using namespace DPL::Colors::Text; - printf("\n%sResults [%s]: %s\n", BOLD_GREEN_BEGIN, title.c_str(), BOLD_GREEN_END); - printf("%s%s%3d%s\n", CYAN_BEGIN, "Total tests: ", stats.GetTotal(), CYAN_END); - printf(" %s%s%3d%s\n", CYAN_BEGIN, "Succeeded: ", stats.GetPassed(), CYAN_END); - printf(" %s%s%3d%s\n", CYAN_BEGIN, "Failed: ", stats.GetFailed(), CYAN_END); - printf(" %s%s%3d%s\n", CYAN_BEGIN, "Ignored: ", stats.GetIgnored(), CYAN_END); + printf("\n%sResults [%s]: %s\n", BOLD_GREEN_BEGIN, + title.c_str(), BOLD_GREEN_END); + printf("%s%s%3d%s\n", + CYAN_BEGIN, + "Total tests: ", + stats.GetTotal(), + CYAN_END); + printf(" %s%s%3d%s\n", + CYAN_BEGIN, + "Succeeded: ", + stats.GetPassed(), + CYAN_END); + printf(" %s%s%3d%s\n", + CYAN_BEGIN, + "Failed: ", + stats.GetFailed(), + CYAN_END); + printf(" %s%s%3d%s\n", + CYAN_BEGIN, + "Ignored: ", + stats.GetIgnored(), + CYAN_END); } Statistic m_stats; @@ -211,15 +246,13 @@ class ConsoleCollector std::string m_currentGroup; }; - TestResultsCollectorBase* ConsoleCollector::Constructor() { return new ConsoleCollector(); } - -class HtmlCollector - : public TestResultsCollectorBase +class HtmlCollector : + public TestResultsCollectorBase { public: static TestResultsCollectorBase* Constructor(); @@ -229,13 +262,13 @@ class HtmlCollector virtual void CollectCurrentTestGroupName(const std::string& name) { - fprintf(m_fp.Get(),"Starting group %s", name.c_str()); + fprintf(m_fp.Get(), "Starting group %s", name.c_str()); m_currentGroup = name; } virtual bool Configure() { - m_fp.Reset(fopen (m_filename.c_str(), "w")); + m_fp.Reset(fopen(m_filename.c_str(), "w")); if (!m_fp) { LogPedantic("Could not open file " << m_filename << " for writing"); return false; @@ -292,17 +325,21 @@ class HtmlCollector std::string tmp = "'" + id + "' ..."; fprintf(m_fp.Get(), "Running test case %-100s", tmp.c_str()); - switch(status) { - case TestResultsCollectorBase::FailStatus::NONE: - fprintf(m_fp.Get(), GREEN_RESULT_OK); break; - case TestResultsCollectorBase::FailStatus::FAILED: - PrintfErrorMessage( " FAILED ", reason, true); break; - case TestResultsCollectorBase::FailStatus::IGNORED: - PrintfIgnoredMessage("Ignored ", reason, true); break; - case TestResultsCollectorBase::FailStatus::INTERNAL: - PrintfErrorMessage( "INTERNAL", reason, true); break; - default: - Assert(false && "Bad status"); + switch (status) { + case TestResultsCollectorBase::FailStatus::NONE: + fprintf(m_fp.Get(), GREEN_RESULT_OK); + break; + case TestResultsCollectorBase::FailStatus::FAILED: + PrintfErrorMessage(" FAILED ", reason, true); + break; + case TestResultsCollectorBase::FailStatus::IGNORED: + PrintfIgnoredMessage("Ignored ", reason, true); + break; + case TestResultsCollectorBase::FailStatus::INTERNAL: + PrintfErrorMessage("INTERNAL", reason, true); + break; + default: + Assert(false && "Bad status"); } m_groupsStats[m_currentGroup].AddTest(status); m_stats.AddTest(status); @@ -349,7 +386,7 @@ class HtmlCollector } else { fprintf(m_fp.Get(), "[%s%s%s]\n", - CYAN_BEGIN , + CYAN_BEGIN, type, CYAN_END); } @@ -358,11 +395,21 @@ class HtmlCollector void PrintStats(const std::string& name, const Statistic& stats) { using namespace DPL::Colors::Html; - fprintf(m_fp.Get(), "\n%sResults [%s]:%s\n", BOLD_GREEN_BEGIN, name.c_str(), BOLD_GREEN_END); - fprintf(m_fp.Get(), "%s%s%3d%s\n", CYAN_BEGIN, "Total tests: ", stats.GetTotal(), CYAN_END); - fprintf(m_fp.Get(), " %s%s%3d%s\n", CYAN_BEGIN, "Succeeded: ", stats.GetPassed(), CYAN_END); - fprintf(m_fp.Get(), " %s%s%3d%s\n", CYAN_BEGIN, "Failed: ", stats.GetFailed(), CYAN_END); - fprintf(m_fp.Get(), " %s%s%3d%s\n", CYAN_BEGIN, "Ignored: ", stats.GetIgnored(), CYAN_END); + fprintf( + m_fp.Get(), "\n%sResults [%s]:%s\n", BOLD_GREEN_BEGIN, + name.c_str(), BOLD_GREEN_END); + fprintf( + m_fp.Get(), "%s%s%3d%s\n", CYAN_BEGIN, + "Total tests: ", stats.GetTotal(), CYAN_END); + fprintf( + m_fp.Get(), " %s%s%3d%s\n", CYAN_BEGIN, + "Succeeded: ", stats.GetPassed(), CYAN_END); + fprintf( + m_fp.Get(), " %s%s%3d%s\n", CYAN_BEGIN, + "Failed: ", stats.GetFailed(), CYAN_END); + fprintf( + m_fp.Get(), " %s%s%3d%s\n", CYAN_BEGIN, + "Ignored: ", stats.GetIgnored(), CYAN_END); } std::string m_filename; @@ -377,9 +424,8 @@ TestResultsCollectorBase* HtmlCollector::Constructor() return new HtmlCollector(); } - -class XmlCollector - : public TestResultsCollectorBase +class XmlCollector : + public TestResultsCollectorBase { public: static TestResultsCollectorBase* Constructor(); @@ -390,16 +436,14 @@ class XmlCollector virtual void CollectCurrentTestGroupName(const std::string& name) { std::size_t pos = GetCurrentGroupPosition(); - if (std::string::npos != pos) - { + if (std::string::npos != pos) { GroupFinish(pos); FlushOutput(); m_stats = Statistic(); } pos = m_outputBuffer.find(""); - if (std::string::npos == pos) - { + if (std::string::npos == pos) { ThrowMsg(DPL::Exception, "Could not find test suites closing tag"); } GroupStart(pos, name); @@ -416,7 +460,8 @@ class XmlCollector groupHeader << ">"; groupHeader << "\n\t\t"; - groupHeader << "\n\t\t\t"; + groupHeader << + "\n\t\t\t"; groupHeader << "\n\t\t"; groupHeader << "\n\t"; @@ -426,7 +471,7 @@ class XmlCollector virtual bool Configure() { - m_fp.Reset(fopen (m_filename.c_str(), "w")); + m_fp.Reset(fopen(m_filename.c_str(), "w")); if (!m_fp) { LogPedantic("Could not open file " << m_filename << " for writing"); return false; @@ -451,8 +496,7 @@ class XmlCollector virtual void Finish() { std::size_t pos = GetCurrentGroupPosition(); - if (std::string::npos != pos) - { + if (std::string::npos != pos) { GroupFinish(pos); FlushOutput(); } @@ -472,37 +516,39 @@ class XmlCollector m_resultBuffer.append("\t\t\n"); - break; - case TestResultsCollectorBase::FailStatus::FAILED: - m_resultBuffer.append(" status=\"FAILED\">\n"); - PrintfErrorMessage("FAILED", EscapeSpecialCharacters(reason), true); - m_resultBuffer.append("\t\t\n"); - break; - case TestResultsCollectorBase::FailStatus::IGNORED: - m_resultBuffer.append(" status=\"Ignored\">\n"); - PrintfIgnoredMessage("Ignored", EscapeSpecialCharacters(reason), true); - m_resultBuffer.append("\t\t\n"); - break; - case TestResultsCollectorBase::FailStatus::INTERNAL: - m_resultBuffer.append(" status=\"FAILED\">\n"); - PrintfErrorMessage("INTERNAL", EscapeSpecialCharacters(reason), true); - m_resultBuffer.append("\t\t"); - break; - default: - Assert(false && "Bad status"); + switch (status) { + case TestResultsCollectorBase::FailStatus::NONE: + m_resultBuffer.append(" status=\"OK\"/>\n"); + break; + case TestResultsCollectorBase::FailStatus::FAILED: + m_resultBuffer.append(" status=\"FAILED\">\n"); + PrintfErrorMessage("FAILED", EscapeSpecialCharacters(reason), true); + m_resultBuffer.append("\t\t\n"); + break; + case TestResultsCollectorBase::FailStatus::IGNORED: + m_resultBuffer.append(" status=\"Ignored\">\n"); + PrintfIgnoredMessage("Ignored", EscapeSpecialCharacters( + reason), true); + m_resultBuffer.append("\t\t\n"); + break; + case TestResultsCollectorBase::FailStatus::INTERNAL: + m_resultBuffer.append(" status=\"FAILED\">\n"); + PrintfErrorMessage("INTERNAL", EscapeSpecialCharacters( + reason), true); + m_resultBuffer.append("\t\t"); + break; + default: + Assert(false && "Bad status"); } std::size_t group_pos = GetCurrentGroupPosition(); - if (std::string::npos == group_pos) - { + if (std::string::npos == group_pos) { ThrowMsg(DPL::Exception, "No current group set"); } - std::size_t last_case_pos = m_outputBuffer.find("\n"); - } else { - m_resultBuffer.append("\t\t\t\n"); @@ -651,7 +693,6 @@ class XmlCollector m_resultBuffer.append(EscapeSpecialCharacters(message)); m_resultBuffer.append("\"/>\n"); } else { - m_resultBuffer.append("\t\t\t\n"); @@ -661,35 +702,35 @@ class XmlCollector std::string EscapeSpecialCharacters(std::string s) { for (unsigned int i = 0; i < s.size();) { - switch(s[i]){ + switch (s[i]) { case '"': - s.erase(i,1); + s.erase(i, 1); s.insert(i, """); - i+=6; + i += 6; break; case '&': - s.erase(i,1); + s.erase(i, 1); s.insert(i, "&"); - i+=5; + i += 5; break; case '<': - s.erase(i,1); + s.erase(i, 1); s.insert(i, "<"); - i+=4; + i += 4; break; case '>': - s.erase(i,1); + s.erase(i, 1); s.insert(i, ">"); - i+=4; + i += 4; break; case '\'': - s.erase(i,1); + s.erase(i, 1); s.insert(i, "'"); - i+=5; + i += 5; break; default: ++i; @@ -711,10 +752,8 @@ TestResultsCollectorBase* XmlCollector::Constructor() return new XmlCollector(); } - - -class CSVCollector - : public TestResultsCollectorBase +class CSVCollector : + public TestResultsCollectorBase { public: static TestResultsCollectorBase* Constructor(); @@ -722,7 +761,8 @@ class CSVCollector private: CSVCollector() {} - virtual void Start() { + virtual void Start() + { printf("GROUP;ID;RESULT;REASON\n"); } @@ -737,13 +777,19 @@ class CSVCollector const std::string& reason = "") { std::string statusMsg = ""; - switch(status) { - case TestResultsCollectorBase::FailStatus::NONE: statusMsg = "OK"; break; - case TestResultsCollectorBase::FailStatus::FAILED: statusMsg = "FAILED"; break; - case TestResultsCollectorBase::FailStatus::IGNORED: statusMsg = "IGNORED"; break; - case TestResultsCollectorBase::FailStatus::INTERNAL: statusMsg = "FAILED"; break; - default: - Assert(false && "Bad status"); + switch (status) { + case TestResultsCollectorBase::FailStatus::NONE: statusMsg = "OK"; + break; + case TestResultsCollectorBase::FailStatus::FAILED: statusMsg = "FAILED"; + break; + case TestResultsCollectorBase::FailStatus::IGNORED: statusMsg = + "IGNORED"; + break; + case TestResultsCollectorBase::FailStatus::INTERNAL: statusMsg = + "FAILED"; + break; + default: + Assert(false && "Bad status"); } printf("%s;%s;%s;%s\n", m_currentGroup.c_str(), @@ -755,16 +801,14 @@ class CSVCollector std::string m_currentGroup; }; - TestResultsCollectorBase* CSVCollector::Constructor() { return new CSVCollector(); } - } -class TAPCollector - : public TestResultsCollectorBase +class TAPCollector : + public TestResultsCollectorBase { public: static TestResultsCollectorBase* Constructor(); @@ -815,41 +859,41 @@ class TAPCollector const std::string& reason = "") { m_testIndex++; - switch(status) { - case TestResultsCollectorBase::FailStatus::NONE: - LogBasicTAP(true, id, description); - endTAPLine(); - break; - case TestResultsCollectorBase::FailStatus::FAILED: - LogBasicTAP(false, id, description); - endTAPLine(); - break; - case TestResultsCollectorBase::FailStatus::IGNORED: - LogBasicTAP(true, id, description); - m_collectedData << " # skip " << reason; - endTAPLine(); - break; - case TestResultsCollectorBase::FailStatus::INTERNAL: - LogBasicTAP(true, id, description); - endTAPLine(); - m_collectedData << " ---" << std::endl; - m_collectedData << " message: " << reason << std::endl; - m_collectedData << " severity: Internal" << std::endl; - m_collectedData << " ..." << std::endl; - break; - default: - Assert(false && "Bad status"); + switch (status) { + case TestResultsCollectorBase::FailStatus::NONE: + LogBasicTAP(true, id, description); + endTAPLine(); + break; + case TestResultsCollectorBase::FailStatus::FAILED: + LogBasicTAP(false, id, description); + endTAPLine(); + break; + case TestResultsCollectorBase::FailStatus::IGNORED: + LogBasicTAP(true, id, description); + m_collectedData << " # skip " << reason; + endTAPLine(); + break; + case TestResultsCollectorBase::FailStatus::INTERNAL: + LogBasicTAP(true, id, description); + endTAPLine(); + m_collectedData << " ---" << std::endl; + m_collectedData << " message: " << reason << std::endl; + m_collectedData << " severity: Internal" << std::endl; + m_collectedData << " ..." << std::endl; + break; + default: + Assert(false && "Bad status"); } } void LogBasicTAP(bool isOK, const std::string& id, - const std::string& description) + const std::string& description) { if (!isOK) { m_collectedData << "not "; } m_collectedData << "ok " << m_testIndex << " [" << - id << "] " << description; + id << "] " << description; } void endTAPLine() @@ -857,20 +901,17 @@ class TAPCollector m_collectedData << std::endl; } - std::string m_filename; std::stringstream m_collectedData; std::ofstream m_output; int m_testIndex; }; - TestResultsCollectorBase* TAPCollector::Constructor() { return new TAPCollector(); } - void TestResultsCollectorBase::RegisterCollectorConstructor( const std::string& name, TestResultsCollectorBase::CollectorConstructorFunc func) @@ -883,10 +924,11 @@ TestResultsCollectorBase* TestResultsCollectorBase::Create( const std::string& name) { ConstructorsMap::iterator found = m_constructorsMap.find(name); - if (found != m_constructorsMap.end()) + if (found != m_constructorsMap.end()) { return found->second(); - else + } else { return NULL; + } } std::vector TestResultsCollectorBase::GetCollectorsNames() @@ -899,10 +941,10 @@ std::vector TestResultsCollectorBase::GetCollectorsNames() return list; } -TestResultsCollectorBase::ConstructorsMap TestResultsCollectorBase::m_constructorsMap; +TestResultsCollectorBase::ConstructorsMap TestResultsCollectorBase:: + m_constructorsMap; -namespace -{ +namespace { static int RegisterCollectorConstructors(); static const int RegisterHelperVariable = RegisterCollectorConstructors(); int RegisterCollectorConstructors() @@ -927,9 +969,7 @@ int RegisterCollectorConstructors() return 0; } - } - } } #undef GREEN_RESULT_OK diff --git a/modules/test/src/test_runner.cpp b/modules/test/src/test_runner.cpp index d2296e8..4826369 100644 --- a/modules/test/src/test_runner.cpp +++ b/modules/test/src/test_runner.cpp @@ -40,26 +40,20 @@ #include IMPLEMENT_SINGLETON(DPL::Test::TestRunner) -namespace DPL -{ -namespace Test -{ - +namespace DPL { +namespace Test { namespace // anonymous { - std::string BaseName(std::string aPath) { ScopedFree path(strdup(aPath.c_str())); - if (NULL == path.Get()) - { - throw std::bad_alloc(); + if (NULL == path.Get()) { + throw std::bad_alloc(); } char* baseName = basename(path.Get()); std::string retValue = baseName; return retValue; } - } // namespace anonymous //! \brief Failed test message creator @@ -95,24 +89,18 @@ void TestRunner::InitGroup(const char* name) m_currentGroup = name; } - TestRunner::Status TestRunner::RunTestCase(const TestCaseStruct& testCase) { - try - { + try { testCase.proc(); - } - catch (const TestFailed &e) - { + } catch (const TestFailed &e) { // Simple test failure CollectResult(testCase.name, "", TestResultsCollectorBase::FailStatus::FAILED, e.GetMessage()); return FAILED; - } - catch (const Ignored &e) - { + } catch (const Ignored &e) { if (m_runIgnored) { // Simple test have to be implemented CollectResult(testCase.name, @@ -122,9 +110,7 @@ TestRunner::Status TestRunner::RunTestCase(const TestCaseStruct& testCase) } return IGNORED; - } - catch (const DPL::Exception &e) - { + } catch (const DPL::Exception &e) { // DPL exception failure CollectResult(testCase.name, "", @@ -132,9 +118,7 @@ TestRunner::Status TestRunner::RunTestCase(const TestCaseStruct& testCase) "DPL exception:" + e.GetMessage()); return FAILED; - } - catch (const std::exception &) - { + } catch (const std::exception &) { // std exception failure CollectResult(testCase.name, "", @@ -142,9 +126,7 @@ TestRunner::Status TestRunner::RunTestCase(const TestCaseStruct& testCase) "std exception"); return FAILED; - } - catch (...) - { + } catch (...) { // Unknown exception failure CollectResult(testCase.name, "", @@ -169,7 +151,7 @@ void TestRunner::RunTests() Banner(); std::for_each(m_collectors.begin(), m_collectors.end(), - [](const TestResultsCollectors::value_type& collector) + [] (const TestResultsCollectors::value_type & collector) { collector.second->Start(); }); @@ -179,13 +161,13 @@ void TestRunner::RunTests() TestCaseStructList list = group->second; if (!list.empty()) { std::for_each( - m_collectors.begin(), - m_collectors.end(), - [&group](const TestResultsCollectors::value_type& collector) - { - collector.second-> - CollectCurrentTestGroupName(group->first); - }); + m_collectors.begin(), + m_collectors.end(), + [&group](const TestResultsCollectors::value_type & collector) + { + collector.second-> + CollectCurrentTestGroupName(group->first); + }); list.sort(); for (TestCaseStructList::const_iterator iterator = list.begin(); @@ -193,8 +175,9 @@ void TestRunner::RunTests() ++iterator) { TestCaseStruct test = *iterator; - if (m_startTestId == test.name) + if (m_startTestId == test.name) { m_startTestId = ""; + } if (m_startTestId.empty()) { RunTestCase(test); @@ -209,7 +192,7 @@ void TestRunner::RunTests() std::for_each(m_collectors.begin(), m_collectors.end(), - [](const TestResultsCollectors::value_type& collector) + [] (const TestResultsCollectors::value_type & collector) { collector.second->Finish(); }); @@ -219,14 +202,14 @@ void TestRunner::RunTests() } void TestRunner::CollectResult( - const std::string& id, - const std::string& description, - const TestResultsCollectorBase::FailStatus::Type status, - const std::string& reason) + const std::string& id, + const std::string& description, + const TestResultsCollectorBase::FailStatus::Type status, + const std::string& reason) { std::for_each(m_collectors.begin(), m_collectors.end(), - [&](const TestResultsCollectors::value_type& collector) + [&](const TestResultsCollectors::value_type & collector) { collector.second->CollectResult(id, description, @@ -267,11 +250,12 @@ void TestRunner::Usage() fprintf(stderr, "Output type:\n"); fprintf(stderr, " --output= --output= ...\n"); fprintf(stderr, "\n possible output types:\n"); - FOREACH (type, TestResultsCollectorBase::GetCollectorsNames()) { + FOREACH(type, TestResultsCollectorBase::GetCollectorsNames()) { fprintf(stderr, " --output=%s\n", type->c_str()); } fprintf(stderr, "\n example:\n"); - fprintf(stderr, " test-binary --output=text --output=xml --file=output.xml\n\n"); + fprintf(stderr, + " test-binary --output=text --output=xml --file=output.xml\n\n"); fprintf(stderr, "Other parameters:\n"); fprintf(stderr, " --regexp='regexp'\t Only selected tests" @@ -281,11 +265,13 @@ void TestRunner::Usage() fprintf(stderr, " --runignored\t Run also ignored tests\n"); fprintf(stderr, " --list\t Show a list of Test IDs\n"); fprintf(stderr, " --listgroups\t Show a list of Test Group names \n"); - fprintf(stderr, " --listingroup=\t Show a list of Test IDS in one group\n"); + fprintf( + stderr, + " --listingroup=\t Show a list of Test IDS in one group\n"); fprintf(stderr, " --help\t This help\n\n"); std::for_each(m_collectors.begin(), m_collectors.end(), - [](const TestResultsCollectors::value_type& collector) + [] (const TestResultsCollectors::value_type & collector) { fprintf(stderr, "Output %s has specific args:\n", @@ -293,7 +279,7 @@ void TestRunner::Usage() fprintf(stderr, "%s\n", collector.second-> - CollectorSpecificHelp().c_str()); + CollectorSpecificHelp().c_str()); }); fprintf(stderr, "For bug reporting, please write to:\n"); fprintf(stderr, "\n"); @@ -302,8 +288,7 @@ void TestRunner::Usage() int TestRunner::ExecTestRunner(int argc, char *argv[]) { std::vector args; - for (int i = 0; i < argc; ++i) - { + for (int i = 0; i < argc; ++i) { args.push_back(argv[i]); } return ExecTestRunner(args); @@ -319,8 +304,7 @@ int TestRunner::ExecTestRunner(const ArgsList& value) m_runIgnored = false; ArgsList args = value; // Parse command line - if (args.size() == 1) - { + if (args.size() == 1) { InvalidArgs(); Usage(); return -1; @@ -345,16 +329,13 @@ int TestRunner::ExecTestRunner(const ArgsList& value) const std::string listGroupsCmd = "--listgroups"; const std::string listInGroup = "--listingroup="; - if (currentCollector) - { - if (currentCollector->ParseCollectorSpecificArg(arg)) - { + if (currentCollector) { + if (currentCollector->ParseCollectorSpecificArg(arg)) { continue; } } - if (arg.find(startCmd) == 0) - { + if (arg.find(startCmd) == 0) { arg.erase(0, startCmd.length()); FOREACH(group, m_testGroups) { FOREACH(tc, group->second) { @@ -363,16 +344,18 @@ int TestRunner::ExecTestRunner(const ArgsList& value) break; } } - if (!m_startTestId.empty()) break; + if (!m_startTestId.empty()) { + break; + } + } + if (!m_startTestId.empty()) { + continue; } - if (!m_startTestId.empty()) continue; InvalidArgs(); fprintf(stderr, "Start test id has not been found\n"); Usage(); return 0; - } - else if (arg.find(groupId) == 0) - { + } else if (arg.find(groupId) == 0) { arg.erase(0, groupId.length()); TestCaseGroupMap::iterator found = m_testGroups.find(arg); if (found != m_testGroups.end()) { @@ -386,43 +369,33 @@ int TestRunner::ExecTestRunner(const ArgsList& value) Usage(); return -1; } - } - else if (arg == runIgnored) - { + } else if (arg == runIgnored) { m_runIgnored = true; - } - else if (arg == listCmd) - { + } else if (arg == listCmd) { FOREACH(group, m_testGroups) { FOREACH(test, group->second) { printf("ID:%s:%s\n", group->first.c_str(), test->name.c_str()); } } return 0; - } - else if (arg == listGroupsCmd) - { + } else if (arg == listGroupsCmd) { FOREACH(group, m_testGroups) { printf("GR:%s\n", group->first.c_str()); } return 0; - } - else if (arg.find(listInGroup) == 0) - { + } else if (arg.find(listInGroup) == 0) { arg.erase(0, listInGroup.length()); FOREACH(test, m_testGroups[arg]) { printf("ID:%s\n", test->name.c_str()); } return 0; - } - else if (arg == "--help") + } else if (arg == "--help") { showHelp = true; - else if (arg.find(output) == 0) - { + } else if (arg.find(output) == 0) { arg.erase(0, output.length()); - if (m_collectors.find(arg) != m_collectors.end()) - { - InvalidArgs("Multiple outputs of the same type are not supported!"); + if (m_collectors.find(arg) != m_collectors.end()) { + InvalidArgs( + "Multiple outputs of the same type are not supported!"); Usage(); return -1; } @@ -433,25 +406,20 @@ int TestRunner::ExecTestRunner(const ArgsList& value) return -1; } m_collectors[arg] = currentCollector; - } - else if (arg.find(regexp) == 0) - { + } else if (arg.find(regexp) == 0) { arg.erase(0, regexp.length()); - if (arg.length() == 0) - { + if (arg.length() == 0) { InvalidArgs(); Usage(); return -1; } - if (arg[0] == '\'' && arg[arg.length() - 1] == '\'') - { + if (arg[0] == '\'' && arg[arg.length() - 1] == '\'') { arg.erase(0); arg.erase(arg.length() - 1); } - if (arg.length() == 0) - { + if (arg.length() == 0) { InvalidArgs(); Usage(); return -1; @@ -462,16 +430,13 @@ int TestRunner::ExecTestRunner(const ArgsList& value) TestCaseStructList newList; FOREACH(iterator, group->second) { - if (re.PartialMatch(iterator->name)) - { + if (re.PartialMatch(iterator->name)) { newList.push_back(*iterator); } } group->second = newList; } - } - else - { + } else { InvalidArgs(); Usage(); return -1; @@ -481,23 +446,19 @@ int TestRunner::ExecTestRunner(const ArgsList& value) currentCollector.reset(); // Show help - if (showHelp) - { + if (showHelp) { Usage(); return 0; } - if (m_collectors.empty()) - { + if (m_collectors.empty()) { TestResultsCollectorBasePtr collector( - TestResultsCollectorBase::Create("text")); + TestResultsCollectorBase::Create("text")); m_collectors["text"] = collector; } - for (auto it = m_collectors.begin(); it != m_collectors.end(); ++it) - { - if (!it->second->Configure()) - { + for (auto it = m_collectors.begin(); it != m_collectors.end(); ++it) { + if (!it->second->Configure()) { fprintf(stderr, "Could not configure selected output"); return 0; } @@ -518,6 +479,5 @@ void TestRunner::terminate() { m_terminate = true; } - } } // namespace DPL diff --git a/modules/test/src/test_runner_child.cpp b/modules/test/src/test_runner_child.cpp index 1f1bd98..bd23771 100644 --- a/modules/test/src/test_runner_child.cpp +++ b/modules/test/src/test_runner_child.cpp @@ -46,13 +46,11 @@ namespace { const int PIPE_CLOSED = -1; } -namespace DPL +namespace DPL { +namespace Test { +class PipeWrapper : DPL::Noncopyable { -namespace Test -{ - -class PipeWrapper : DPL::Noncopyable { -public: + public: enum Usage { READONLY, WRITEONLY @@ -64,18 +62,21 @@ public: ERROR }; - PipeWrapper(){ + PipeWrapper() + { if (-1 == pipe(m_pipefd)) { m_pipefd[0] = PIPE_CLOSED; m_pipefd[1] = PIPE_CLOSED; } } - bool isReady(){ + bool isReady() + { return m_pipefd[0] != PIPE_CLOSED || m_pipefd[1] != PIPE_CLOSED; } - void setUsage(Usage usage) { + void setUsage(Usage usage) + { if (usage == READONLY) { closeHelp(1); } @@ -83,14 +84,17 @@ public: closeHelp(0); } } - ~PipeWrapper(){ + ~PipeWrapper() + { closeHelp(0); closeHelp(1); } - Status send(int code, std::string &message) { - if (m_pipefd[1] == PIPE_CLOSED) + Status send(int code, std::string &message) + { + if (m_pipefd[1] == PIPE_CLOSED) { return ERROR; + } std::ostringstream output; output << toBinaryString(code); @@ -100,27 +104,34 @@ public: std::string binary = output.str(); int size = binary.size(); - if ((writeHelp(&size, sizeof(int)) == ERROR) || (writeHelp(binary.c_str(), size) == ERROR)) { + if ((writeHelp(&size, + sizeof(int)) == ERROR) || + (writeHelp(binary.c_str(), size) == ERROR)) + { return ERROR; } return SUCCESS; } - Status receive(int &code, std::string &data, time_t deadline) { - if (m_pipefd[0] == PIPE_CLOSED) + Status receive(int &code, std::string &data, time_t deadline) + { + if (m_pipefd[0] == PIPE_CLOSED) { return ERROR; + } int size; Status ret; - if ((ret = readHelp(&size, sizeof(int), deadline)) != SUCCESS) + if ((ret = readHelp(&size, sizeof(int), deadline)) != SUCCESS) { return ret; + } std::vector buffer; buffer.resize(size); - if ((ret = readHelp(&buffer[0], size, deadline)) != SUCCESS) + if ((ret = readHelp(&buffer[0], size, deadline)) != SUCCESS) { return ret; + } try { DPL::BinaryQueue queue; @@ -139,33 +150,38 @@ public: return SUCCESS; } - void closeAll() { + void closeAll() + { closeHelp(0); closeHelp(1); } -private: - std::string toBinaryString(int data) { + + private: + std::string toBinaryString(int data) + { char buffer[sizeof(int)]; memcpy(buffer, &data, sizeof(int)); - return std::string(buffer, buffer+sizeof(int)); + return std::string(buffer, buffer + sizeof(int)); } - - void closeHelp(int desc) { + void closeHelp(int desc) + { if (m_pipefd[desc] != PIPE_CLOSED) { TEMP_FAILURE_RETRY(close(m_pipefd[desc])); m_pipefd[desc] = PIPE_CLOSED; } } - Status writeHelp(const void *buffer, int size) { + Status writeHelp(const void *buffer, int size) + { int ready = 0; const char *p = static_cast(buffer); while (ready != size) { - int ret = write(m_pipefd[1], &p[ready], size-ready); + int ret = write(m_pipefd[1], &p[ready], size - ready); - if (ret == -1 && (errno == EAGAIN || errno == EINTR)) + if (ret == -1 && (errno == EAGAIN || errno == EINTR)) { continue; + } if (ret == -1) { closeHelp(1); @@ -177,15 +193,16 @@ private: return SUCCESS; } - Status readHelp(void *buf, int size, time_t deadline) { + Status readHelp(void *buf, int size, time_t deadline) + { int ready = 0; char *buffer = static_cast(buf); while (ready != size) { time_t wait = deadline - time(0); wait = wait < 1 ? 1 : wait; - pollfd fds = { m_pipefd[0], POLLIN, 0}; + pollfd fds = { m_pipefd[0], POLLIN, 0 }; - int pollReturn = poll(&fds, 1, wait * 1000); + int pollReturn = poll(&fds, 1, wait * 1000); if (pollReturn == 0) { return TIMEOUT; // Timeout @@ -195,10 +212,11 @@ private: return ERROR; } - int ret = read(m_pipefd[0], &buffer[ready], size-ready); + int ret = read(m_pipefd[0], &buffer[ready], size - ready); - if (ret == -1 && (errno == EAGAIN || errno == EINTR)) + if (ret == -1 && (errno == EAGAIN || errno == EINTR)) { continue; + } if (ret == -1 || ret == 0) { closeHelp(0); @@ -213,7 +231,8 @@ private: int m_pipefd[2]; }; -void RunChildProc(TestRunner::TestCase procChild){ +void RunChildProc(TestRunner::TestCase procChild) +{ PipeWrapper pipe; if (!pipe.isReady()) { throw TestRunner::TestFailed("Pipe creation failed"); @@ -221,8 +240,9 @@ void RunChildProc(TestRunner::TestCase procChild){ pid_t pid = fork(); - if (pid == -1) + if (pid == -1) { throw TestRunner::TestFailed("Child creation failed"); + } if (pid != 0) { // parent code @@ -231,7 +251,7 @@ void RunChildProc(TestRunner::TestCase procChild){ int code; std::string message; - int pipeReturn = pipe.receive(code, message, time(0)+10); + int pipeReturn = pipe.receive(code, message, time(0) + 10); if (pipeReturn != PipeWrapper::SUCCESS) { // Timeout or reading error pipe.closeAll(); @@ -260,7 +280,7 @@ void RunChildProc(TestRunner::TestCase procChild){ int code = 1; std::string msg; -// close(0); // stdin + // close(0); // stdin close(1); // stdout close(2); // stderr @@ -278,6 +298,5 @@ void RunChildProc(TestRunner::TestCase procChild){ pipe.send(code, msg); } } - } // namespace Test } // namespace DPL diff --git a/modules/utils/include/dpl/utils/bash_utils.h b/modules/utils/include/dpl/utils/bash_utils.h index 1eb2ba9..33a5f9d 100644 --- a/modules/utils/include/dpl/utils/bash_utils.h +++ b/modules/utils/include/dpl/utils/bash_utils.h @@ -22,17 +22,15 @@ #ifndef BASH_UTILS_H #define BASH_UTILS_H -#include +#include namespace BashUtils { - /** * Escapes bash special characters in string and return string in double quotes * @param source string to be escaped * @return escaped string */ std::string escape_arg(const std::string & source); - } #endif // BASH_UTILS_H diff --git a/modules/utils/include/dpl/utils/file_utils.h b/modules/utils/include/dpl/utils/file_utils.h index 6cdfefd..9fbad4e 100644 --- a/modules/utils/include/dpl/utils/file_utils.h +++ b/modules/utils/include/dpl/utils/file_utils.h @@ -50,7 +50,6 @@ void MakePath(const std::string& path, mode_t mode); * @throw FileUtils::DirectoryRemoveException If an error occured. */ void RemoveDir(const std::string& path); - } // namespace FileUtils #endif diff --git a/modules/utils/include/dpl/utils/folder_size.h b/modules/utils/include/dpl/utils/folder_size.h index db51de9..71a77bd 100644 --- a/modules/utils/include/dpl/utils/folder_size.h +++ b/modules/utils/include/dpl/utils/folder_size.h @@ -29,11 +29,9 @@ #include namespace Utils { - size_t getFolderSize(const std::string& path); DPL::String fromFileSizeString(size_t fileSize); - } #endif /* SRC_COMMON_FOLDER_SIZE_H_ */ diff --git a/modules/utils/include/dpl/utils/mime_type_utils.h b/modules/utils/include/dpl/utils/mime_type_utils.h index b536c20..1d93385 100644 --- a/modules/utils/include/dpl/utils/mime_type_utils.h +++ b/modules/utils/include/dpl/utils/mime_type_utils.h @@ -44,7 +44,7 @@ class MimeTypeUtils typedef std::map MimeAttributes; static bool isValidIcon(const DPL::String& path); static bool isValidStartFile(const DPL::String& path, - const DPL::OptionalString& providedMimeType); + const DPL::OptionalString& providedMimeType); static bool isMimeTypeSupportedForStartFile(const DPL::String& mimeType); static bool isMimeTypeSupportedForIcon(const DPL::String& mimeType); static MimeAttributes getMimeAttributes(const DPL::String& mimeType); diff --git a/modules/utils/include/dpl/utils/warp_iri.h b/modules/utils/include/dpl/utils/warp_iri.h index 6968b66..71773cb 100644 --- a/modules/utils/include/dpl/utils/warp_iri.h +++ b/modules/utils/include/dpl/utils/warp_iri.h @@ -24,13 +24,14 @@ class WarpIRI { static const unsigned int UNKNOWN_PORT = 0; + public: WarpIRI(); void set(const char *iri, - bool domain); + bool domain); void set(const DPL::String &iristring, - bool domain); + bool domain); /* It also checks port and schema */ bool isSubDomain(const WarpIRI &second) const; diff --git a/modules/utils/include/dpl/utils/widget_version.h b/modules/utils/include/dpl/utils/widget_version.h index 5f40e72..de3d3aa 100644 --- a/modules/utils/include/dpl/utils/widget_version.h +++ b/modules/utils/include/dpl/utils/widget_version.h @@ -32,20 +32,28 @@ * WAC Waikiki Beta Release Core Specification: Widget Runtime * 10 Dec 2010 * - * WL-3370 The WRT MUST process widget packages as an update when received under the following conditions: + * WL-3370 The WRT MUST process widget packages as an update when received under + * the following conditions: * * - the Widget Id matches the Widget Id of an installed widget - * - the Widget version number is greater (as a compared string) than that of the installed widget, or no version + * - the Widget version number is greater (as a compared string) than that of + * the installed widget, or no version * information was provided for the installed widget * - * To ensure that a string comparison of widget versions can reliably determine which version is an updated widget, - * WAC will mandate a specific version string format for WAC widgets. All widgets coming through the WAC channel - * will be required to have version strings in this format. Side-loaded widgets may have any format and, in this - * case, there is no requirement that the WRT support version detection for update of these widgets. + * To ensure that a string comparison of widget versions can reliably determine + * which version is an updated widget, + * WAC will mandate a specific version string format for WAC widgets. All + * widgets coming through the WAC channel + * will be required to have version strings in this format. Side-loaded widgets + * may have any format and, in this + * case, there is no requirement that the WRT support version detection for + * update of these widgets. * - * The widget version format is the rec-version-tag grammar as described in [Widget Packaging]: + * The widget version format is the rec-version-tag grammar as described in + * [Widget Packaging]: * - * rec-version-tag = 1*DIGIT "." 1*DIGIT [ "." 1*DIGIT] *[ 1*ALPHA / SP / 1*DIGIT ] + * rec-version-tag = 1*DIGIT "." 1*DIGIT [ "." 1*DIGIT] *[ 1*ALPHA / SP / + * 1*DIGIT ] * * Examples of rec-version-tag: * @@ -53,20 +61,25 @@ * 1.10.1 beta1 * 1.02.12 RC1 * - * WL-3371 The WRT MUST use the following widget version comparison algorithm to compare WAC widget version strings: + * WL-3371 The WRT MUST use the following widget version comparison algorithm to + * compare WAC widget version strings: * * - prepare the version strings for comparison: * - all leading zeros are discarded * - the optional *[ 1*ALPHA / SP / 1*DIGIT ] part, if present, is discarded * - the resulting numbers are then in the format major.minor[.micro] - * - Version A = Amajor.Aminor[.Amicro] is equal to Version B = Bmajor.Bminor[.Bmicro] if and only if: + * - Version A = Amajor.Aminor[.Amicro] is equal to Version B = + * Bmajor.Bminor[.Bmicro] if and only if: * - Amajor Bmajor * - Aminor Bminor - * - both Amicro and Bmicro are present and Amicro == Bmicro; or both Amicro and Bmicro are absent. - * - Version A = Amajor.Aminor[.Amicro] is greater than Version B = Bmajor.Bminor[.Bmicro] if and only if: + * - both Amicro and Bmicro are present and Amicro == Bmicro; or both Amicro + * and Bmicro are absent. + * - Version A = Amajor.Aminor[.Amicro] is greater than Version B = + * Bmajor.Bminor[.Bmicro] if and only if: * - Amajor > Bmajor; or * - Amajor Bmajor && Aminor > Bminor; or - * - Amajor Bmajor && Aminor == Bminor && both Amicro and Bmicro are present and Amicro > Bmicro; or Bmicro is absent. + * - Amajor Bmajor && Aminor == Bminor && both Amicro and Bmicro are present + * and Amicro > Bmicro; or Bmicro is absent. */ class WidgetVersion { @@ -80,16 +93,16 @@ class WidgetVersion DPL::Optional m_optional; void WacCertify(const DPL::String &major, - const DPL::String &minor, - const DPL::Optional µ, - const DPL::Optional &optional); + const DPL::String &minor, + const DPL::Optional µ, + const DPL::Optional &optional); public: explicit WidgetVersion(const DPL::String &str = DPL::String()); WidgetVersion(const DPL::String &major, - const DPL::String &minor, - const DPL::Optional µ, - const DPL::Optional &optional); + const DPL::String &minor, + const DPL::Optional µ, + const DPL::Optional &optional); bool IsWac() const; const DPL::String &Raw() const; @@ -101,18 +114,18 @@ class WidgetVersion }; bool operator<(const WidgetVersion &left, - const WidgetVersion &right); + const WidgetVersion &right); bool operator<=(const WidgetVersion &left, - const WidgetVersion &right); + const WidgetVersion &right); bool operator>(const WidgetVersion &left, - const WidgetVersion &right); + const WidgetVersion &right); bool operator>=(const WidgetVersion &left, - const WidgetVersion &right); + const WidgetVersion &right); bool operator==(const WidgetVersion &left, - const WidgetVersion &right); + const WidgetVersion &right); bool operator!=(const WidgetVersion &left, - const WidgetVersion &right); + const WidgetVersion &right); std::ostream & operator<<(std::ostream& stream, - const WidgetVersion& version); + const WidgetVersion& version); #endif // WIDGET_VERSION_H diff --git a/modules/utils/include/dpl/utils/wrt_global_settings.h b/modules/utils/include/dpl/utils/wrt_global_settings.h index 35fabb3..14407ae 100644 --- a/modules/utils/include/dpl/utils/wrt_global_settings.h +++ b/modules/utils/include/dpl/utils/wrt_global_settings.h @@ -24,7 +24,6 @@ #define WRT_COMMON_GLOBAL_SETTINGS_H_ namespace GlobalSettings { - // Methods for getting test mode environment flag bool TestModeEnabled(); bool PopupsTestModeEnabled(); @@ -34,7 +33,6 @@ bool OCSPTestModeEnabled(); bool CrlTestModeEnabled(); bool MakeScreenTestModeEnabled(); bool IsEmulator(); - } #endif /* WRT_COMMON_GLOBAL_SETTINGS_H_ */ diff --git a/modules/utils/include/dpl/utils/wrt_utility.h b/modules/utils/include/dpl/utils/wrt_utility.h index fb2c920..165e167 100644 --- a/modules/utils/include/dpl/utils/wrt_utility.h +++ b/modules/utils/include/dpl/utils/wrt_utility.h @@ -35,7 +35,9 @@ * Data stored in joined before the function call will be replaced with joined * paths. */ -void WrtUtilJoinPaths(std::string &joined, const std::string &parent, const std::string &child); +void WrtUtilJoinPaths(std::string &joined, + const std::string &parent, + const std::string &child); /** * Creates directories specified by path @@ -49,7 +51,7 @@ void WrtUtilJoinPaths(std::string &joined, const std::string &parent, const std: * several nested directories, you must make sure that the mode flag allows you * to write and search the direcotries you create. */ -bool WrtUtilMakeDir(const std::string &newpath, mode_t mode=0755); +bool WrtUtilMakeDir(const std::string &newpath, mode_t mode = 0755); /** * This function removes the directory or file pointed to by path diff --git a/modules/utils/src/bash_utils.cpp b/modules/utils/src/bash_utils.cpp index b76a261..1222eda 100644 --- a/modules/utils/src/bash_utils.cpp +++ b/modules/utils/src/bash_utils.cpp @@ -19,29 +19,26 @@ * @version 1.0 */ #include -#include -#include +#include +#include -#include +#include namespace BashUtils { - std::string escape_arg(const std::string & source) { static const std::string special("!$`\\\""); std::string ret = "\""; - for(std::string::const_iterator iter = source.begin(); iter != source.end(); ++iter) + for (std::string::const_iterator iter = source.begin(); + iter != source.end(); + ++iter) { - if(special.find(*iter) != std::string::npos) - { + if (special.find(*iter) != std::string::npos) { ret += std::string("\\") + *iter; - } - else - { + } else { ret += *iter; } } return ret + "\""; } - } diff --git a/modules/utils/src/file_utils.cpp b/modules/utils/src/file_utils.cpp index e5100df..2510069 100644 --- a/modules/utils/src/file_utils.cpp +++ b/modules/utils/src/file_utils.cpp @@ -19,7 +19,6 @@ * @version 1.0 */ - #include #include #include @@ -35,7 +34,7 @@ namespace { int try_mkdir(const char* path, - mode_t mode) + mode_t mode) { struct stat st; int err = 0; @@ -53,7 +52,7 @@ int try_mkdir(const char* path, } int mkpath(const char* path, - mode_t mode) + mode_t mode) { char* copy = ::strdup(path); if (NULL == copy) { @@ -95,7 +94,8 @@ int RmDir(const char* path) errno = 0; if (NULL != (entry = ::readdir(dir))) { if (!::strncmp(entry->d_name, ".", 1) || - !::strncmp(entry->d_name, "..", 2)) { + !::strncmp(entry->d_name, "..", 2)) + { continue; } std::string fullPath = WrtDB::PathBuilder(path) @@ -108,8 +108,7 @@ int RmDir(const char* path) return -1; } } - } - while (NULL != entry); + } while (NULL != entry); int error = errno; if (TEMP_FAILURE_RETRY(::closedir(dir)) != 0) { @@ -142,7 +141,7 @@ bool FileExists(const DPL::String& absolutePath) } void MakePath(const std::string& path, - mode_t mode) + mode_t mode) { if (mkpath(path.c_str(), mode) == -1) { ThrowMsg(CreateDirectoryException, "Cannot make path"); diff --git a/modules/utils/src/folder_size.cpp b/modules/utils/src/folder_size.cpp index 2029434..522216a 100644 --- a/modules/utils/src/folder_size.cpp +++ b/modules/utils/src/folder_size.cpp @@ -34,74 +34,69 @@ #include namespace Utils { - size_t getFolderSize(const std::string& path) { size_t size = 0; FTS *fts; FTSENT *ftsent; - char * const paths[] = {const_cast(path.c_str()), NULL}; + char * const paths[] = { const_cast(path.c_str()), NULL }; - if ((fts = fts_open(paths, FTS_PHYSICAL|FTS_NOCHDIR, NULL)) == NULL) { + if ((fts = fts_open(paths, FTS_PHYSICAL | FTS_NOCHDIR, NULL)) == NULL) { //ERROR int error = errno; LogWarning(__PRETTY_FUNCTION__ << ": fts_open failed with error: " - << strerror(error)); + << strerror(error)); return 0; } while ((ftsent = fts_read(fts)) != NULL) { switch (ftsent->fts_info) { - case FTS_DP: - case FTS_DC: - //directory in postorder and directory causing a loop - break; - case FTS_F: - case FTS_D: - case FTS_NSOK: - case FTS_SL: - case FTS_SLNONE: - case FTS_DEFAULT: - //regular files and other objects that can be counted - size += ftsent->fts_statp->st_size; - break; - case FTS_NS: - case FTS_DOT: - case FTS_DNR: - case FTS_ERR: - default: - LogWarning(__PRETTY_FUNCTION__ - << ": traversal failed on file: " - << ftsent->fts_path - << " with error: " - << strerror(ftsent->fts_errno)); - return 0; + case FTS_DP: + case FTS_DC: + //directory in postorder and directory causing a loop + break; + case FTS_F: + case FTS_D: + case FTS_NSOK: + case FTS_SL: + case FTS_SLNONE: + case FTS_DEFAULT: + //regular files and other objects that can be counted + size += ftsent->fts_statp->st_size; + break; + case FTS_NS: + case FTS_DOT: + case FTS_DNR: + case FTS_ERR: + default: + LogWarning(__PRETTY_FUNCTION__ + << ": traversal failed on file: " + << ftsent->fts_path + << " with error: " + << strerror(ftsent->fts_errno)); + return 0; } } if (fts_close(fts) == -1) { int error = errno; LogWarning(__PRETTY_FUNCTION__ << ": fts_close failed with error: " - << strerror(error)); + << strerror(error)); return 0; } return size; } - - - - namespace { #define DECLARE_PREFIX_STRUCT(name) \ -struct Prefix##name \ -{ \ - static std::string get() \ - { \ - return std::string(#name); \ - } \ -}; \ + struct Prefix##name \ + { \ + static std::string get() \ + { \ + return std::string(#name); \ + } \ + }; \ DECLARE_PREFIX_STRUCT(B) DECLARE_PREFIX_STRUCT(KB) @@ -110,59 +105,51 @@ DECLARE_PREFIX_STRUCT(GB) #undef DECLARE_PREFIX_STRUCT - const int stepSize = 1024; -template +template struct Pre; - -template -struct Pre +template +struct Pre { static const double value; static std::string printSize(double fileSize) { - if(fileSize >= Pre::value) { - double now = fileSize / Pre::value; + if (fileSize >= Pre::value) { + double now = fileSize / Pre::value; std::ostringstream outputStream; outputStream.setf(std::ios::fixed, std::ios::floatfield); outputStream.precision(2); outputStream << now << Postfix::get(); return outputStream.str(); } else { - return Pre::printSize(fileSize); + return Pre::printSize(fileSize); } - } }; template<> struct Pre<> { - static const double value; - static std::string printSize(double /*fileSize*/) - { - return "0B"; - } - + static const double value; + static std::string printSize(double /*fileSize*/) + { + return "0B"; + } }; const double Pre<>::value = 1.0; -template const double Pre::value(Pre<>::value * stepSize); - +template const double Pre:: + value(Pre<>::value * stepSize); typedef Pre FolderSizeToStringType; - - } //anonymous namespace - DPL::String fromFileSizeString(size_t fileSize) { - std::string output = FolderSizeToStringType::printSize(static_cast(fileSize)); return DPL::FromUTF8String(output); } - } // end of namespace Utils diff --git a/modules/utils/src/mime_type_utils.cpp b/modules/utils/src/mime_type_utils.cpp index 2977a78..1dbe832 100644 --- a/modules/utils/src/mime_type_utils.cpp +++ b/modules/utils/src/mime_type_utils.cpp @@ -94,7 +94,7 @@ DPL::String MimeTypeUtils::stripMimeParameters(const DPL::String& mimeType) } MimeTypeUtils::MimeAttributes MimeTypeUtils::getMimeAttributes( - const DPL::String& mimeType) + const DPL::String& mimeType) { MimeAttributes attributes; std::vector tokens; @@ -110,8 +110,10 @@ bool MimeTypeUtils::isValidIcon(const DPL::String& path) return getMimeTypesSupportedForIcon().count(identifyFileMimeType(path)) > 0; } -bool MimeTypeUtils::isValidStartFile(const DPL::String& path, - const DPL::OptionalString& providedMimeType) +bool MimeTypeUtils::isValidStartFile( + const DPL::String& path, + const DPL::OptionalString& + providedMimeType) { DPL::String mimeType = (!!providedMimeType) ? stripMimeParameters( *providedMimeType) : identifyFileMimeType(path); diff --git a/modules/utils/src/warp_iri.cpp b/modules/utils/src/warp_iri.cpp index fb8ca70..9edf59f 100644 --- a/modules/utils/src/warp_iri.cpp +++ b/modules/utils/src/warp_iri.cpp @@ -41,7 +41,7 @@ namespace { // hard drive. What's why we cannot check any iri with file schema. const char *IRI_IGNORED_SCHEME[] = { "file://", "widget://", "tel:", "sms:", - "mmsto:", "mailto:", "data:", "blob:", 0 }; + "mmsto:", "mailto:", "data:", "blob:", 0 }; const DPL::String SCHEMA_HTTP = DPL::FromUTF8String("http"); const DPL::String SCHEMA_HTTPS = DPL::FromUTF8String("https"); @@ -51,7 +51,7 @@ const DPL::String SCHEMA_FTP = DPL::FromUTF8String("ftp"); // This will create AutoPtr deleter for iri_struct. // Deleter must be in the same namespace as definition of AutoPtr. -namespace DPL{ +namespace DPL { DECLARE_DELETER(iri_struct, iri_destroy) } // namespace DPL @@ -60,11 +60,10 @@ WarpIRI::WarpIRI() : m_port(UNKNOWN_PORT), m_isAccessDefinition(false), m_isIRIValid(false) -{ -} +{} void WarpIRI::set(const char *p_iri, - bool domain) + bool domain) { if (!p_iri) { m_isAccessDefinition = m_isIRIValid = false; @@ -147,7 +146,7 @@ void WarpIRI::set(const char *p_iri, } void WarpIRI::set(const DPL::String &iristring, - bool domain) + bool domain) { set(DPL::ToUTF8String(iristring).c_str(), domain); } @@ -167,9 +166,15 @@ unsigned int WarpIRI::getPort(const DPL::String &schema) const bool WarpIRI::isSubDomain(const WarpIRI &second) const { - if (!m_isAccessDefinition || !second.m_isIRIValid) { return false; } - if (m_schema != second.m_schema) { return false; } - if (m_port != second.m_port) { return false; } + if (!m_isAccessDefinition || !second.m_isIRIValid) { + return false; + } + if (m_schema != second.m_schema) { + return false; + } + if (m_port != second.m_port) { + return false; + } size_t size = m_host.size() < second.m_host.size() ? m_host.size() : second.m_host.size(); @@ -205,7 +210,8 @@ bool WarpIRI::isIRISchemaIgnored(const char *iri) for (int i = 0; IRI_IGNORED_SCHEME[i]; ++i) { if (0 == strncmp(iri, IRI_IGNORED_SCHEME[i], - strlen(IRI_IGNORED_SCHEME[i]))) { + strlen(IRI_IGNORED_SCHEME[i]))) + { return true; } } diff --git a/modules/utils/src/widget_version.cpp b/modules/utils/src/widget_version.cpp index e19610b..cbaf5d1 100644 --- a/modules/utils/src/widget_version.cpp +++ b/modules/utils/src/widget_version.cpp @@ -39,7 +39,8 @@ DPL::String::value_type LEADING_ZERO_CHAR = L'0'; // // [ABNF] -// Augmented BNF for Syntax Specifications: ABNF. RFC5234. D. Crocker and P. Overell. January 2008. +// Augmented BNF for Syntax Specifications: ABNF. RFC5234. D. Crocker and P. +// Overell. January 2008. // // ALPHA = %x41-5A / %x61-7A inline bool IsAlpha(int c) @@ -79,7 +80,7 @@ DPL::String RemoveLeadingZeroes(const DPL::String &str) // operator < bool NumberLessOperator(const DPL::String &left, - const DPL::String &right) + const DPL::String &right) { // Assume: No leading zeroes if (left.size() < right.size()) { @@ -161,7 +162,8 @@ WidgetVersion::WidgetVersion(const DPL::String &str) : LogDebug("Tokenized mandatory parts: " << parts.size()); if (parts.size() != WAC_CERTIFY_MANDATORY_PART_LOW_COUNT && - parts.size() != WAC_CERTIFY_MANDATORY_PART_HIGH_COUNT) { + parts.size() != WAC_CERTIFY_MANDATORY_PART_HIGH_COUNT) + { return; } @@ -181,9 +183,9 @@ WidgetVersion::WidgetVersion(const DPL::String &str) : } WidgetVersion::WidgetVersion(const DPL::String &major, - const DPL::String &minor, - const DPL::Optional µ, - const DPL::Optional &optional) : + const DPL::String &minor, + const DPL::Optional µ, + const DPL::Optional &optional) : m_isWac(false) { // Create Raw version @@ -206,9 +208,9 @@ WidgetVersion::WidgetVersion(const DPL::String &major, } void WidgetVersion::WacCertify(const DPL::String &major, - const DPL::String &minor, - const DPL::Optional µ, - const DPL::Optional &optional) + const DPL::String &minor, + const DPL::Optional µ, + const DPL::Optional &optional) { LogDebug("Certyfing..."); @@ -234,7 +236,8 @@ void WidgetVersion::WacCertify(const DPL::String &major, } if (!!optional && - (optional->empty() || !WacCertifyAlphaNumberStringSpace(*optional))) { + (optional->empty() || !WacCertifyAlphaNumberStringSpace(*optional))) + { LogDebug("Optional version not certified!"); return; } @@ -281,32 +284,49 @@ const DPL::Optional &WidgetVersion::Optional() const } bool operator<(const WidgetVersion &left, - const WidgetVersion &right) + const WidgetVersion &right) { Assert( left.IsWac() && right.IsWac() && "Only WAC version strings are comparable!"); if (NumberLessOperator(RemoveLeadingZeroes(left.Major()), - RemoveLeadingZeroes(right.Major()))) { return true; } + RemoveLeadingZeroes(right.Major()))) + { + return true; + } if (NumberLessOperator(RemoveLeadingZeroes(right.Major()), - RemoveLeadingZeroes(left.Major()))) { return false; } + RemoveLeadingZeroes(left.Major()))) + { + return false; + } if (NumberLessOperator(RemoveLeadingZeroes(left.Minor()), - RemoveLeadingZeroes(right.Minor()))) { return true; } + RemoveLeadingZeroes(right.Minor()))) + { + return true; + } if (NumberLessOperator(RemoveLeadingZeroes(right.Minor()), - RemoveLeadingZeroes(left.Minor()))) { return false; } + RemoveLeadingZeroes(left.Minor()))) + { + return false; + } if (!!left.Micro() && !!right.Micro() && NumberLessOperator(RemoveLeadingZeroes(*left.Micro()), - RemoveLeadingZeroes(*right.Micro()))) { return true; } - if (!left.Micro() && !!right.Micro()) { return true; } + RemoveLeadingZeroes(*right.Micro()))) + { + return true; + } + if (!left.Micro() && !!right.Micro()) { + return true; + } return false; } bool operator<=(const WidgetVersion &left, - const WidgetVersion &right) + const WidgetVersion &right) { Assert( left.IsWac() && right.IsWac() && @@ -316,7 +336,7 @@ bool operator<=(const WidgetVersion &left, } bool operator>(const WidgetVersion &left, - const WidgetVersion &right) + const WidgetVersion &right) { Assert( left.IsWac() && right.IsWac() && @@ -326,7 +346,7 @@ bool operator>(const WidgetVersion &left, } bool operator>=(const WidgetVersion &left, - const WidgetVersion &right) + const WidgetVersion &right) { Assert( left.IsWac() && right.IsWac() && @@ -336,26 +356,32 @@ bool operator>=(const WidgetVersion &left, } bool operator==(const WidgetVersion &left, - const WidgetVersion &right) + const WidgetVersion &right) { Assert( left.IsWac() && right.IsWac() && "Only WAC version strings are comparable!"); + //Major are equal + //and + //Minor are equal + //and + //Both Micro exist and are equal + //or both Micro do not exist return RemoveLeadingZeroes(left.Major()) == - RemoveLeadingZeroes(right.Major()) && // Major are equal + RemoveLeadingZeroes(right.Major()) && RemoveLeadingZeroes(left.Minor()) == - RemoveLeadingZeroes(right.Minor()) && // and Minor are equal - ( // and ... + RemoveLeadingZeroes(right.Minor()) && + ( (!!left.Micro() && !!right.Micro() && RemoveLeadingZeroes(*left.Micro()) == - RemoveLeadingZeroes(*right.Micro())) || // Both Micro exist and are equal - (!left.Micro() && !right.Micro()) // or both Micro do not exist + RemoveLeadingZeroes(*right.Micro())) || + (!left.Micro() && !right.Micro()) ); } bool operator!=(const WidgetVersion &left, - const WidgetVersion &right) + const WidgetVersion &right) { Assert( left.IsWac() && right.IsWac() && @@ -365,7 +391,7 @@ bool operator!=(const WidgetVersion &left, } std::ostream & operator<<(std::ostream& stream, - const WidgetVersion& version) + const WidgetVersion& version) { stream << version.Raw(); return stream; diff --git a/modules/utils/src/wrt_global_settings.cpp b/modules/utils/src/wrt_global_settings.cpp index 9428fb3..adaac78 100644 --- a/modules/utils/src/wrt_global_settings.cpp +++ b/modules/utils/src/wrt_global_settings.cpp @@ -29,10 +29,9 @@ #include namespace GlobalSettings { - namespace { const int ROAMING_TEST = 0x00000001; -const int POPUPS_TEST = 0x00000002; +const int POPUPS_TEST = 0x00000002; const int OCSP_TEST = 0x00000004; const int WARP_TEST = 0x00000008; const int CRL_TEST = 0x00000010; @@ -52,8 +51,8 @@ struct Settings { bool isEmulator; int testModes; - Settings() - : isEmulator(false), testModes(0) + Settings() : + isEmulator(false), testModes(0) {} }; @@ -101,17 +100,17 @@ bool initializeGlobalSettings() std::istringstream str(envStr); while (std::getline(str, env, '|')) { if ("popups" == env) { - testMode |= POPUPS_TEST; + testMode |= POPUPS_TEST; } else if ("roaming" == env) { - testMode |= ROAMING_TEST;; + testMode |= ROAMING_TEST; } else if ("ocsp" == env) { - testMode |= OCSP_TEST;; + testMode |= OCSP_TEST; } else if ("warp" == env) { - testMode |= WARP_TEST;; + testMode |= WARP_TEST; } else if ("crl" == env) { - testMode |= CRL_TEST; + testMode |= CRL_TEST; } else if ("screen" == env) { - testMode |= SCREEN_SHOT_TEST;; + testMode |= SCREEN_SHOT_TEST; } } } @@ -130,22 +129,28 @@ bool TestModeEnabled() return ((gSettings.testModes & ALL_TEST) == ALL_TEST); } -bool PopupsTestModeEnabled() { +bool PopupsTestModeEnabled() +{ return (gSettings.testModes & POPUPS_TEST); } -bool WarpTestModeEnabled() { +bool WarpTestModeEnabled() +{ return (gSettings.testModes & WARP_TEST); } -bool RoamingTestModeEnabled() { +bool RoamingTestModeEnabled() +{ return (gSettings.testModes & ROAMING_TEST); } -bool OCSPTestModeEnabled() { +bool OCSPTestModeEnabled() +{ return (gSettings.testModes & OCSP_TEST); } -bool CrlTestModeEnabled() { +bool CrlTestModeEnabled() +{ return (gSettings.testModes & CRL_TEST); } -bool MakeScreenTestModeEnabled() { +bool MakeScreenTestModeEnabled() +{ return (gSettings.testModes & SCREEN_SHOT_TEST); } @@ -153,5 +158,4 @@ bool IsEmulator() { return gSettings.isEmulator; } - } // GlobalSettings diff --git a/modules/utils/src/wrt_utility.cpp b/modules/utils/src/wrt_utility.cpp index 43888b3..44044f2 100644 --- a/modules/utils/src/wrt_utility.cpp +++ b/modules/utils/src/wrt_utility.cpp @@ -30,19 +30,24 @@ #include #include -void WrtUtilJoinPaths(std::string &joined, const std::string &parent, const std::string &child) +void WrtUtilJoinPaths(std::string &joined, + const std::string &parent, + const std::string &child) { - size_t parent_len = parent.length();; - joined=parent; - joined+=child; + size_t parent_len = parent.length(); + joined = parent; + joined += child; //In case someone used windows-style paths std::replace(joined.begin(), joined.end(), '\\', '/'); if (parent_len != 0 && child.length() != 0) { - if (joined[parent_len-1] != '/' && joined[parent_len] != '/') + if (joined[parent_len - 1] != '/' && joined[parent_len] != '/') { joined.insert(parent_len, "/"); - else if (joined[parent_len-1] == '/' && joined[parent_len] == '/') + } else if (joined[parent_len - 1] == '/' && joined[parent_len] == + '/') + { joined.erase(parent_len, 1); + } } } @@ -51,20 +56,26 @@ bool WrtUtilMakeDir(const std::string &newpath, mode_t mode) size_t pos = 0; int error; - if (newpath.length() == 0) return false; + if (newpath.length() == 0) { + return false; + } - std::string path=newpath; + std::string path = newpath; - if (*(path.rbegin()) != '/') path += '/'; + if (*(path.rbegin()) != '/') { + path += '/'; + } - while ((pos = path.find('/', pos+1)) != std::string::npos) { + while ((pos = path.find('/', pos + 1)) != std::string::npos) { if (mkdir(path.substr(0, pos).c_str(), mode) != 0) { - error=errno; - if (error == EEXIST) continue; + error = errno; + if (error == EEXIST) { + continue; + } LogWarning(__PRETTY_FUNCTION__ << ": failed to create directory " - << path.substr(0,pos) - << ". Error: " - << strerror(error)); + << path.substr(0, pos) + << ". Error: " + << strerror(error)); return false; } } @@ -77,70 +88,70 @@ bool WrtUtilRemove(const std::string &path) FTSENT *ftsent; bool rv = true; int error = 0; - char * const paths[] = {const_cast(path.c_str()), NULL}; + char * const paths[] = { const_cast(path.c_str()), NULL }; - if ((fts = fts_open(paths, FTS_PHYSICAL|FTS_NOCHDIR, NULL)) == NULL) { + if ((fts = fts_open(paths, FTS_PHYSICAL | FTS_NOCHDIR, NULL)) == NULL) { //ERROR error = errno; LogWarning(__PRETTY_FUNCTION__ << ": fts_open failed with error: " - << strerror(error)); + << strerror(error)); return false; } while ((ftsent = fts_read(fts)) != NULL) { switch (ftsent->fts_info) { - case FTS_D: - //directory in preorder - do nothing - break; - case FTS_DP: - //directory in postorder - remove - if (rmdir(ftsent->fts_accpath) != 0) { - error = errno; - LogWarning(__PRETTY_FUNCTION__ - << ": rmdir failed with error: " - << strerror(error)); - rv = false; - } - break; - case FTS_DC: - case FTS_F: - case FTS_NSOK: - case FTS_SL: - case FTS_SLNONE: - case FTS_DEFAULT: - //regular files and other objects that can safely be removed - if (unlink(ftsent->fts_accpath) != 0) { - error = errno; - LogWarning(__PRETTY_FUNCTION__ - << ": unlink failed with error: " - << strerror(error)); - rv = false; - } - break; - case FTS_NS: + case FTS_D: + //directory in preorder - do nothing + break; + case FTS_DP: + //directory in postorder - remove + if (rmdir(ftsent->fts_accpath) != 0) { + error = errno; LogWarning(__PRETTY_FUNCTION__ - << ": couldn't get stat info for file: " - << ftsent->fts_path - << ". The error was: " - << strerror(ftsent->fts_errno)); + << ": rmdir failed with error: " + << strerror(error)); rv = false; - break; - case FTS_DOT: - case FTS_DNR: - case FTS_ERR: - default: + } + break; + case FTS_DC: + case FTS_F: + case FTS_NSOK: + case FTS_SL: + case FTS_SLNONE: + case FTS_DEFAULT: + //regular files and other objects that can safely be removed + if (unlink(ftsent->fts_accpath) != 0) { + error = errno; LogWarning(__PRETTY_FUNCTION__ - << ": traversal failed with error: " - << strerror(ftsent->fts_errno)); + << ": unlink failed with error: " + << strerror(error)); rv = false; - break; + } + break; + case FTS_NS: + LogWarning(__PRETTY_FUNCTION__ + << ": couldn't get stat info for file: " + << ftsent->fts_path + << ". The error was: " + << strerror(ftsent->fts_errno)); + rv = false; + break; + case FTS_DOT: + case FTS_DNR: + case FTS_ERR: + default: + LogWarning(__PRETTY_FUNCTION__ + << ": traversal failed with error: " + << strerror(ftsent->fts_errno)); + rv = false; + break; } } if (fts_close(fts) == -1) { error = errno; LogWarning(__PRETTY_FUNCTION__ << ": fts_close failed with error: " - << strerror(error)); + << strerror(error)); rv = false; } return rv; @@ -149,7 +160,7 @@ bool WrtUtilRemove(const std::string &path) bool WrtUtilFileExists(const std::string &path) { struct stat tmp; - if (stat(path.c_str(),&tmp) == 0) { + if (stat(path.c_str(), &tmp) == 0) { return S_ISREG(tmp.st_mode); } else { return false; @@ -159,7 +170,7 @@ bool WrtUtilFileExists(const std::string &path) bool WrtUtilDirExists(const std::string &path) { struct stat tmp; - if (stat(path.c_str(),&tmp) == 0) { + if (stat(path.c_str(), &tmp) == 0) { return S_ISDIR(tmp.st_mode); } else { return false; diff --git a/modules/widget_dao/dao/WrtDatabase.cpp b/modules/widget_dao/dao/WrtDatabase.cpp index 106d98a..1cf6773 100644 --- a/modules/widget_dao/dao/WrtDatabase.cpp +++ b/modules/widget_dao/dao/WrtDatabase.cpp @@ -23,7 +23,6 @@ #include namespace WrtDB { - const char* WrtDatabase::Address() { using namespace WrtDB; @@ -36,8 +35,8 @@ DPL::DB::SqlConnection::Flag::Type WrtDatabase::Flags() } DPL::DB::ThreadDatabaseSupport WrtDatabase::m_interface( - WrtDatabase::Address(), - WrtDatabase::Flags()); + WrtDatabase::Address(), + WrtDatabase::Flags()); void WrtDatabase::attachToThreadRO() { @@ -63,5 +62,4 @@ bool WrtDatabase::CheckTableExist(const char *name) { return m_interface.CheckTableExist(name); } - } diff --git a/modules/widget_dao/dao/common_dao_types.cpp b/modules/widget_dao/dao/common_dao_types.cpp index 49abd87..7c0b8c3 100644 --- a/modules/widget_dao/dao/common_dao_types.cpp +++ b/modules/widget_dao/dao/common_dao_types.cpp @@ -21,5 +21,4 @@ * @brief This file contains the implementation of common data types for wrtdb */ #include -namespace WrtDB { -} // namespace WrtDB +namespace WrtDB {} // namespace WrtDB diff --git a/modules/widget_dao/dao/config_parser_data.cpp b/modules/widget_dao/dao/config_parser_data.cpp old mode 100755 new mode 100644 index 0e42448..eccbe40 --- a/modules/widget_dao/dao/config_parser_data.cpp +++ b/modules/widget_dao/dao/config_parser_data.cpp @@ -29,7 +29,6 @@ namespace WrtDB { bool IsSpace(const xmlChar* str); bool CopyChar(xmlChar* out, xmlChar* in); - bool IsSpace(const xmlChar* str) { int charlen = xmlUTF8Size(str); @@ -121,7 +120,7 @@ bool IsSpace(const xmlChar* str) } bool CopyChar(xmlChar* out, - xmlChar* in) + xmlChar* in) { int size = xmlUTF8Size(in); switch (size) { @@ -418,13 +417,13 @@ bool ConfigParserData::AccessInfo::operator <(const AccessInfo& info) const bool ConfigParserData::Setting::operator==(const Setting& other) const { return m_name == other.m_name && - m_value == other.m_value; + m_value == other.m_value; } bool ConfigParserData::Setting::operator!=(const Setting& other) const { return m_name != other.m_name || - m_value != other.m_value; + m_value != other.m_value; } bool ConfigParserData::Setting::operator >(const Setting& other) const @@ -450,37 +449,36 @@ bool ConfigParserData::Setting::operator<=(const Setting& other) const bool ConfigParserData::ServiceInfo::operator== (const ServiceInfo& info) const { return m_src == info.m_src && - m_operation == info.m_operation && - m_scheme == info.m_scheme && - m_mime == info.m_mime; + m_operation == info.m_operation && + m_scheme == info.m_scheme && + m_mime == info.m_mime; } bool ConfigParserData::ServiceInfo::operator!= (const ServiceInfo& info) const { return m_src != info.m_src && - m_operation != info.m_operation && - m_scheme != info.m_scheme && - m_mime != info.m_mime; + m_operation != info.m_operation && + 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; + 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; + 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/feature_dao.cpp b/modules/widget_dao/dao/feature_dao.cpp old mode 100755 new mode 100644 index 8fadeeb..ba12c24 --- a/modules/widget_dao/dao/feature_dao.cpp +++ b/modules/widget_dao/dao/feature_dao.cpp @@ -31,14 +31,14 @@ namespace WrtDB { namespace FeatureDAO { - FeatureHandle RegisterFeature(const PluginMetafileData::Feature &feature, const DbPluginHandle pluginHandle) { Try { LogDebug("Registering Feature " << feature.m_name); - DPL::DB::ORM::wrt::ScopedTransaction transaction(&WrtDatabase::interface()); + DPL::DB::ORM::wrt::ScopedTransaction transaction( + &WrtDatabase::interface()); if (FeatureDAOReadOnly::isFeatureInstalled(feature.m_name)) { LogError(" >> Feature " << feature.m_name << @@ -64,7 +64,7 @@ FeatureHandle RegisterFeature(const PluginMetafileData::Feature &feature, } FeatureHandle featureHandle = - FeatureDAOReadOnly(feature.m_name).GetFeatureHandle(); + FeatureDAOReadOnly(feature.m_name).GetFeatureHandle(); //register device capabilities // Device Capabilities is unused in current version @@ -76,7 +76,9 @@ FeatureHandle RegisterFeature(const PluginMetafileData::Feature &feature, LogInfo(" | |--DeviceCap " << *itdev << " already installed!"); - WRT_DB_SELECT(select, DeviceCapabilities, &WrtDatabase::interface()) + WRT_DB_SELECT(select, + DeviceCapabilities, + &WrtDatabase::interface()) select->Where(Equals( DPL::FromUTF8String(*itdev))); @@ -89,7 +91,9 @@ FeatureHandle RegisterFeature(const PluginMetafileData::Feature &feature, DeviceCapabilities::Row row; row.Set_DeviceCapName(DPL::FromUTF8String(*itdev)); - WRT_DB_INSERT(insert, DeviceCapabilities, &WrtDatabase::interface()) + WRT_DB_INSERT(insert, + DeviceCapabilities, + &WrtDatabase::interface()) insert->Values(row); deviceCapID = static_cast(insert->Execute()); } @@ -98,7 +102,9 @@ FeatureHandle RegisterFeature(const PluginMetafileData::Feature &feature, row.Set_FeatureUUID(featureHandle); row.Set_DeviceCapID(deviceCapID); - WRT_DB_INSERT(insert, FeatureDeviceCapProxy, &WrtDatabase::interface()) + WRT_DB_INSERT(insert, + FeatureDeviceCapProxy, + &WrtDatabase::interface()) insert->Values(row); insert->Execute(); } @@ -119,7 +125,7 @@ void UnregisterFeature(FeatureHandle featureHandle) { LogDebug("Unregistering Feature " << featureHandle); DPL::DB::ORM::wrt::ScopedTransaction transaction( - &WrtDatabase::interface()); + &WrtDatabase::interface()); if (FeatureDAOReadOnly::isFeatureInstalled(featureHandle)) { LogError("Feature handle is invalid"); @@ -154,7 +160,5 @@ void UnregisterFeature(FeatureHandle featureHandle) "Fail to unregister Feature"); } } - - } // namespace FeatureDAO } // namespace WrtDB diff --git a/modules/widget_dao/dao/feature_dao_read_only.cpp b/modules/widget_dao/dao/feature_dao_read_only.cpp index 1d20bdf..cab3fba 100644 --- a/modules/widget_dao/dao/feature_dao_read_only.cpp +++ b/modules/widget_dao/dao/feature_dao_read_only.cpp @@ -30,7 +30,6 @@ #include namespace WrtDB { - FeatureDAOReadOnly::FeatureDAOReadOnly(FeatureHandle featureHandle) : m_featureHandle(featureHandle) { @@ -63,17 +62,18 @@ FeatureDAOReadOnly::FeatureDAOReadOnly(const std::string &featureName) #define GET_PLUGIN_DATA(func) \ Try { \ - DPL::DB::ORM::wrt::ScopedTransaction transaction(&WrtDatabase::interface()); \ - LogDebug(# func << ". FeatureHandle: " << m_featureHandle); \ + DPL::DB::ORM::wrt::ScopedTransaction transaction( \ + &WrtDatabase::interface()); \ + LogDebug(#func << ". FeatureHandle: " << m_featureHandle); \ std::string ret = PluginDAOReadOnly(GetPluginHandle()).func(); \ transaction.Commit(); \ return ret; \ } \ Catch(DPL::DB::SqlConnection::Exception::Base) { \ std::ostringstream failure("Failure during "); \ - failure << # func; \ + failure << #func; \ ReThrowMsg(FeatureDAOReadOnly::Exception::DatabaseError, \ - failure.str()); \ + failure.str()); \ } std::string FeatureDAOReadOnly::GetLibraryPath() const @@ -208,7 +208,7 @@ bool FeatureDAOReadOnly::isFeatureInstalled(FeatureHandle handle) } bool FeatureDAOReadOnly::isDeviceCapabilityInstalled( - const std::string &deviceCapName) + const std::string &deviceCapName) { LogDebug("Check if DeviceCap is installed. Name: " << deviceCapName); Try { @@ -237,11 +237,14 @@ FeatureDAOReadOnly::GetDeviceCapabilities() const { Try { LogDebug("Get DeviceCap. FeatureHandle: " << m_featureHandle); - DPL::DB::ORM::wrt::ScopedTransaction transaction(&WrtDatabase::interface()); + DPL::DB::ORM::wrt::ScopedTransaction transaction( + &WrtDatabase::interface()); using namespace DPL::DB::ORM; using namespace DPL::DB::ORM::wrt; - WRT_DB_SELECT(selectDevCP, FeatureDeviceCapProxy, &WrtDatabase::interface()) + WRT_DB_SELECT(selectDevCP, + FeatureDeviceCapProxy, + &WrtDatabase::interface()) selectDevCP->Where(Equals( m_featureHandle)); @@ -251,7 +254,9 @@ FeatureDAOReadOnly::GetDeviceCapabilities() const selectDevCP->GetValueList(); FOREACH(devCId, deviceIDs) { - WRT_DB_SELECT(selectDevC, DeviceCapabilities, &WrtDatabase::interface()) + WRT_DB_SELECT(selectDevC, + DeviceCapabilities, + &WrtDatabase::interface()) selectDevC->Where(Equals(*devCId)); DPL::String devNames = @@ -270,7 +275,7 @@ FeatureDAOReadOnly::GetDeviceCapabilities() const } FeatureHandleListPtr FeatureDAOReadOnly::GetFeatureHandleListForPlugin( - DbPluginHandle pluginHandle) + DbPluginHandle pluginHandle) { LogDebug("Getting FeatureHandle list for pluginHandle: " << pluginHandle); Try { @@ -294,8 +299,8 @@ FeatureHandleListPtr FeatureDAOReadOnly::GetFeatureHandleListForPlugin( } Catch(DPL::DB::SqlConnection::Exception::Base){ ReThrowMsg( - FeatureDAOReadOnly::Exception::DatabaseError, - "Failure during getting FeatureHandle Set for plugin handle"); + FeatureDAOReadOnly::Exception::DatabaseError, + "Failure during getting FeatureHandle Set for plugin handle"); } } @@ -312,7 +317,10 @@ FeatureDAOReadOnly::GetNames() FeaturesList::Select::RowList rows = select->GetRowList(); FOREACH(rowIt, rows) { - nameMap.insert(std::pair(rowIt->Get_FeatureUUID(), DPL::ToUTF8String(rowIt->Get_FeatureName()))); + nameMap.insert(std::pair(rowIt->Get_FeatureUUID(), + DPL::ToUTF8String(rowIt-> + Get_FeatureName()))); } return nameMap; @@ -336,16 +344,22 @@ FeatureDAOReadOnly::GetDevCapWithFeatureHandle() DECLARE_COLUMN_TYPE_LIST_END(DevCapNameList) WRT_DB_SELECT(select, FeatureDeviceCapProxy, &WrtDatabase::interface()) - select->Join(Equal()); + select->Join(Equal()); DeviceCapabilitiesMap devCap; - std::list< CustomRow > rowList = select->GetCustomRowList< DevCapNameList, CustomRow >(); + std::list< CustomRow > rowList = + select->GetCustomRowList< DevCapNameList, CustomRow >(); FOREACH(rowIt, rowList) { - FeatureHandle featureHandle = (*rowIt).GetColumnData(); - std::string devName = DPL::ToUTF8String((*rowIt).GetColumnData()); - devCap.insert(std::pair(featureHandle, devName)); + FeatureHandle featureHandle = + (*rowIt).GetColumnData(); + std::string devName = + DPL::ToUTF8String((*rowIt).GetColumnData()); + devCap.insert(std::pair(featureHandle, + devName)); } return devCap; @@ -379,7 +393,7 @@ FeatureDAOReadOnly::GetFeatures(const std::list& featureNames) rowIt->Get_FeatureName()); featureData.pluginHandle = rowIt->Get_PluginPropertiesId(); featureMap.insert(std::pair( - rowIt->Get_FeatureUUID(), featureData)); + rowIt->Get_FeatureUUID(), featureData)); } return featureMap; @@ -389,5 +403,4 @@ FeatureDAOReadOnly::GetFeatures(const std::list& featureNames) "Failure during getting GetFeatures"); } } - } // namespace WrtDB diff --git a/modules/widget_dao/dao/global_dao.cpp b/modules/widget_dao/dao/global_dao.cpp index cf7d818..0c22d90 100644 --- a/modules/widget_dao/dao/global_dao.cpp +++ b/modules/widget_dao/dao/global_dao.cpp @@ -69,8 +69,9 @@ void GlobalDAO::SetSecureByDefault(bool secure) void GlobalDAO::setComplianceMode(bool mode) { LogDebug("Updating compliance mode to:" << mode); - Try{ - using namespace DPL::DB::ORM; using namespace DPL::DB::ORM::wrt; + Try { + using namespace DPL::DB::ORM; + using namespace DPL::DB::ORM::wrt; GlobalProperties::Row row; row.Set_compliance_mode(mode); @@ -78,7 +79,7 @@ void GlobalDAO::setComplianceMode(bool mode) update->Values(row); update->Execute(); } - Catch (DPL::DB::SqlConnection::Exception::Base){ + Catch(DPL::DB::SqlConnection::Exception::Base){ ReThrowMsg(GlobalDAO::Exception::DatabaseError, "Failed to update compliance mode"); } @@ -87,8 +88,9 @@ void GlobalDAO::setComplianceMode(bool mode) void GlobalDAO::setComplianceFakeImei(const std::string &imei) { LogDebug("Setting compliance fake IMEI: " << imei); - Try{ - using namespace DPL::DB::ORM; using namespace DPL::DB::ORM::wrt; + Try { + using namespace DPL::DB::ORM; + using namespace DPL::DB::ORM::wrt; GlobalProperties::Row row; row.Set_compliance_fake_imei(DPL::FromASCIIString(imei)); @@ -96,7 +98,7 @@ void GlobalDAO::setComplianceFakeImei(const std::string &imei) update->Values(row); update->Execute(); } - Catch (DPL::DB::SqlConnection::Exception::Base){ + Catch(DPL::DB::SqlConnection::Exception::Base){ ReThrowMsg(GlobalDAO::Exception::DatabaseError, "Failed to update compliance fake IMEI"); } @@ -105,8 +107,9 @@ void GlobalDAO::setComplianceFakeImei(const std::string &imei) void GlobalDAO::setComplianceFakeMeid(const std::string &meid) { LogDebug("Setting compliance fake MEID: " << meid); - Try{ - using namespace DPL::DB::ORM; using namespace DPL::DB::ORM::wrt; + Try { + using namespace DPL::DB::ORM; + using namespace DPL::DB::ORM::wrt; GlobalProperties::Row row; row.Set_compliance_fake_meid(DPL::FromASCIIString(meid)); @@ -114,7 +117,7 @@ void GlobalDAO::setComplianceFakeMeid(const std::string &meid) update->Values(row); update->Execute(); } - Catch (DPL::DB::SqlConnection::Exception::Base){ + Catch(DPL::DB::SqlConnection::Exception::Base){ ReThrowMsg(GlobalDAO::Exception::DatabaseError, "Failed to update compliance fake MEID"); } @@ -189,7 +192,8 @@ void GlobalDAO::RemoveWhiteURI(const std::string &uri) using namespace DPL::DB::ORM::wrt; WRT_DB_DELETE(deleteFrom, WidgetWhiteURIList, &WrtDatabase::interface()) - deleteFrom->Where(Equals(DPL::FromASCIIString(uri))); + deleteFrom->Where(Equals(DPL::FromASCIIString( + uri))); deleteFrom->Execute(); } Catch(DPL::DB::SqlConnection::Exception::Base) { ReThrowMsg(GlobalDAO::Exception::DatabaseError, @@ -215,5 +219,4 @@ void GlobalDAO::SetCookieSharingMode(bool mode) "Failed to update Cookie Sharing Mode"); } } - } // namespace WrtDB diff --git a/modules/widget_dao/dao/global_dao_read_only.cpp b/modules/widget_dao/dao/global_dao_read_only.cpp index 1936d38..04b914f 100644 --- a/modules/widget_dao/dao/global_dao_read_only.cpp +++ b/modules/widget_dao/dao/global_dao_read_only.cpp @@ -32,7 +32,6 @@ #include namespace WrtDB { - bool GlobalDAOReadOnly::GetDeveloperMode() { LogDebug("Getting Developer mode"); @@ -59,12 +58,13 @@ bool GlobalDAOReadOnly::GetSecureByDefault() bool GlobalDAOReadOnly::getComplianceMode() { LogDebug("Getting compliance mode"); - Try{ - using namespace DPL::DB::ORM; using namespace DPL::DB::ORM::wrt; + Try { + using namespace DPL::DB::ORM; + using namespace DPL::DB::ORM::wrt; WRT_DB_SELECT(select, GlobalProperties, &WrtDatabase::interface()) return select->GetSingleValue(); } - Catch (DPL::DB::SqlConnection::Exception::Base){ + Catch(DPL::DB::SqlConnection::Exception::Base){ ReThrowMsg(GlobalDAOReadOnly::Exception::DatabaseError, "Failed to get compliance mode"); } @@ -73,8 +73,9 @@ bool GlobalDAOReadOnly::getComplianceMode() std::string GlobalDAOReadOnly::getComplianceFakeImei() { LogDebug("Getting compliance fake IMEI"); - Try{ - using namespace DPL::DB::ORM; using namespace DPL::DB::ORM::wrt; + Try { + using namespace DPL::DB::ORM; + using namespace DPL::DB::ORM::wrt; WRT_DB_SELECT(select, GlobalProperties, &WrtDatabase::interface()) DPL::Optional result = select->GetSingleValue(); @@ -83,7 +84,7 @@ std::string GlobalDAOReadOnly::getComplianceFakeImei() } return DPL::ToUTF8String(*result); } - Catch (DPL::DB::SqlConnection::Exception::Base){ + Catch(DPL::DB::SqlConnection::Exception::Base){ ReThrowMsg(GlobalDAOReadOnly::Exception::DatabaseError, "Failed to get compliance fake IMEI"); } @@ -92,8 +93,9 @@ std::string GlobalDAOReadOnly::getComplianceFakeImei() std::string GlobalDAOReadOnly::getComplianceFakeMeid() { LogDebug("Getting compliance fake MEID"); - Try{ - using namespace DPL::DB::ORM; using namespace DPL::DB::ORM::wrt; + Try { + using namespace DPL::DB::ORM; + using namespace DPL::DB::ORM::wrt; WRT_DB_SELECT(select, GlobalProperties, &WrtDatabase::interface()) DPL::Optional result = select->GetSingleValue(); @@ -102,7 +104,7 @@ std::string GlobalDAOReadOnly::getComplianceFakeMeid() } return DPL::ToUTF8String(*result); } - Catch (DPL::DB::SqlConnection::Exception::Base){ + Catch(DPL::DB::SqlConnection::Exception::Base){ ReThrowMsg(GlobalDAOReadOnly::Exception::DatabaseError, "Failed to get compliance fake MEID"); } @@ -123,7 +125,7 @@ bool GlobalDAOReadOnly::IsValidSubTag(const DPL::String& tag, int type) } GlobalDAOReadOnly::NetworkAccessMode - GlobalDAOReadOnly::GetHomeNetworkDataUsage() +GlobalDAOReadOnly::GetHomeNetworkDataUsage() { LogDebug("Getting home network data usage"); Try { @@ -131,8 +133,8 @@ GlobalDAOReadOnly::NetworkAccessMode using namespace DPL::DB::ORM::wrt; WRT_DB_SELECT(select, GlobalProperties, &WrtDatabase::interface()) return static_cast( - select->GetSingleValue< - GlobalProperties::home_network_data_usage>()); + select->GetSingleValue< + GlobalProperties::home_network_data_usage>()); } Catch(DPL::DB::SqlConnection::Exception::Base){ ReThrowMsg(GlobalDAOReadOnly::Exception::DatabaseError, @@ -148,7 +150,7 @@ GlobalDAOReadOnly::NetworkAccessMode GlobalDAOReadOnly::GetRoamingDataUsage() using namespace DPL::DB::ORM::wrt; WRT_DB_SELECT(select, GlobalProperties, &WrtDatabase::interface()) return static_cast( - select->GetSingleValue()); + select->GetSingleValue()); } Catch(DPL::DB::SqlConnection::Exception::Base){ ReThrowMsg(GlobalDAOReadOnly::Exception::DatabaseError, @@ -181,12 +183,13 @@ DPL::String GlobalDAOReadOnly::GetUserAgentValue(const DPL::String &key) } DeviceCapabilitySet GlobalDAOReadOnly::GetDeviceCapability( - const DPL::String &apifeature) + const DPL::String &apifeature) { // This could be done with one simply sql query but support for join is // needed in orm. - Try{ - using namespace DPL::DB::ORM; using namespace DPL::DB::ORM::wrt; + Try { + using namespace DPL::DB::ORM; + using namespace DPL::DB::ORM::wrt; int featureUUID; FeatureDeviceCapProxy::Select::RowList rows; @@ -199,22 +202,24 @@ DeviceCapabilitySet GlobalDAOReadOnly::GetDeviceCapability( } { - WRT_DB_SELECT(select, FeatureDeviceCapProxy, &WrtDatabase::interface()) + WRT_DB_SELECT(select, + FeatureDeviceCapProxy, + &WrtDatabase::interface()) select->Where(Equals( - featureUUID)); + featureUUID)); rows = select->GetRowList(); } FOREACH(it, rows){ WRT_DB_SELECT(select, DeviceCapabilities, &WrtDatabase::interface()) select->Where(Equals( - it->Get_DeviceCapID())); + it->Get_DeviceCapID())); result.insert(select-> - GetSingleValue()); + GetSingleValue()); } return result; - }Catch(DPL::DB::SqlConnection::Exception::Base){ + } Catch(DPL::DB::SqlConnection::Exception::Base){ ReThrowMsg(GlobalDAOReadOnly::Exception::DatabaseError, "Failed to update roaming network data usage"); } @@ -223,7 +228,7 @@ DeviceCapabilitySet GlobalDAOReadOnly::GetDeviceCapability( WidgetAccessInfoList GlobalDAOReadOnly::GetWhiteURIList() { LogDebug("Getting WhiteURIList."); - Try{ + Try { using namespace DPL::DB::ORM; using namespace DPL::DB::ORM::wrt; WRT_DB_SELECT(select, WidgetWhiteURIList, &WrtDatabase::interface()) @@ -261,5 +266,4 @@ bool GlobalDAOReadOnly::GetCookieSharingMode() "Failed to get Cookie Sharing mode"); } } - } // namespace WrtDB diff --git a/modules/widget_dao/dao/path_builder.cpp b/modules/widget_dao/dao/path_builder.cpp index c55841a..ab55476 100644 --- a/modules/widget_dao/dao/path_builder.cpp +++ b/modules/widget_dao/dao/path_builder.cpp @@ -32,13 +32,11 @@ class PathBuilderImpl : DPL::Noncopyable { public: PathBuilderImpl() - { - } + {} explicit PathBuilderImpl(const std::string& path) : m_stream(path, std::ios_base::app) - { - } + {} void Append(const std::string& path) { @@ -80,13 +78,11 @@ class PathBuilderImpl : DPL::Noncopyable }; PathBuilder::PathBuilder() : m_impl(new PathBuilderImpl()) -{ -} +{} PathBuilder::PathBuilder(const std::string& path) : m_impl(new PathBuilderImpl(path)) -{ -} +{} PathBuilder::~PathBuilder() { @@ -126,5 +122,4 @@ std::string PathBuilder::GetFullPath() const { return m_impl->GetFullPath(); } - } // namespace WrtDB diff --git a/modules/widget_dao/dao/plugin_dao.cpp b/modules/widget_dao/dao/plugin_dao.cpp index bdbd993..cc8dcbf 100644 --- a/modules/widget_dao/dao/plugin_dao.cpp +++ b/modules/widget_dao/dao/plugin_dao.cpp @@ -29,24 +29,22 @@ #include namespace WrtDB { - PluginDAO::PluginDAO(DbPluginHandle pluginHandle) : PluginDAOReadOnly(pluginHandle) -{ -} +{} PluginDAO::PluginDAO(const std::string &libraryName) : PluginDAOReadOnly(libraryName) -{ -} +{} DbPluginHandle PluginDAO::registerPlugin(const PluginMetafileData& metafile, - const std::string& pluginPath) + const std::string& pluginPath) { LogDebug("Registering plugin. Path: " << pluginPath); Try { - DPL::DB::ORM::wrt::ScopedTransaction transaction(&WrtDatabase::interface()); + DPL::DB::ORM::wrt::ScopedTransaction transaction( + &WrtDatabase::interface()); DbPluginHandle handle; if (isPluginInstalled(metafile.m_libraryName)) { @@ -84,12 +82,13 @@ DbPluginHandle PluginDAO::registerPlugin(const PluginMetafileData& metafile, } void PluginDAO::registerPluginImplementedObject(const std::string& objectName, - DbPluginHandle pluginHandle) + DbPluginHandle pluginHandle) { LogDebug("Registering plugin object: " << objectName); Try { - DPL::DB::ORM::wrt::ScopedTransaction transaction(&WrtDatabase::interface()); + DPL::DB::ORM::wrt::ScopedTransaction transaction( + &WrtDatabase::interface()); LogDebug("Register Object: " << objectName); @@ -115,12 +114,13 @@ void PluginDAO::registerPluginImplementedObject(const std::string& objectName, } void PluginDAO::registerPluginRequiredObject(const std::string& objectName, - DbPluginHandle pluginHandle) + DbPluginHandle pluginHandle) { LogDebug("Registering plugin object: " << objectName); Try { - DPL::DB::ORM::wrt::ScopedTransaction transaction(&WrtDatabase::interface()); + DPL::DB::ORM::wrt::ScopedTransaction transaction( + &WrtDatabase::interface()); LogDebug("Register Object: " << objectName); @@ -146,13 +146,14 @@ void PluginDAO::registerPluginRequiredObject(const std::string& objectName, } void PluginDAO::registerPluginLibrariesDependencies( - DbPluginHandle pluginHandle, - const PluginHandleSetPtr& dependencies) + DbPluginHandle pluginHandle, + const PluginHandleSetPtr& dependencies) { LogDebug("Registering plugin library dependencies: " << pluginHandle); Try { - DPL::DB::ORM::wrt::ScopedTransaction transaction(&WrtDatabase::interface()); + DPL::DB::ORM::wrt::ScopedTransaction transaction( + &WrtDatabase::interface()); using namespace DPL::DB::ORM; using namespace DPL::DB::ORM::wrt; @@ -215,12 +216,11 @@ void PluginDAO::unregisterPlugin(DbPluginHandle pluginHandle) Try { DPL::DB::ORM::wrt::ScopedTransaction transaction( - &WrtDatabase::interface()); + &WrtDatabase::interface()); if (!isPluginInstalled(pluginHandle)) { LogInfo("PluginHandle is invalid. Handle: " << pluginHandle); return; - } else { using namespace DPL::DB::ORM; using namespace DPL::DB::ORM::wrt; @@ -240,5 +240,4 @@ void PluginDAO::unregisterPlugin(DbPluginHandle pluginHandle) "Failed in UnregisterPlugin"); } } - } // namespace WrtDB diff --git a/modules/widget_dao/dao/plugin_dao_read_only.cpp b/modules/widget_dao/dao/plugin_dao_read_only.cpp index a1aec8f..d5acba9 100644 --- a/modules/widget_dao/dao/plugin_dao_read_only.cpp +++ b/modules/widget_dao/dao/plugin_dao_read_only.cpp @@ -31,9 +31,7 @@ #include namespace WrtDB { - namespace { - typedef DPL::DB::ORM::wrt::PluginProperties::Row PluginRow; PluginRow getPluginRow(DbPluginHandle pluginHandle) @@ -101,7 +99,8 @@ PluginDAOReadOnly::PluginDAOReadOnly(const std::string &libraryName) void PluginDAOReadOnly::checkInstallationCompleted() { if (getInstallationStateForHandle(m_pluginHandle) - != PluginDAOReadOnly::INSTALLATION_COMPLETED) { + != PluginDAOReadOnly::INSTALLATION_COMPLETED) + { LogError("Plugin " << m_pluginHandle << " installation not completed"); Throw(PluginDAOReadOnly::Exception::PluginInstallationNotCompleted); } @@ -160,7 +159,6 @@ DbPluginHandle PluginDAOReadOnly::getPluginHandle() const return m_pluginHandle; } - //"value" cannot be null, as in registerPlugin it is always set #define RETURN_STD_STRING(in, what) \ std::string ret = ""; \ @@ -217,7 +215,7 @@ PluginHandleSetPtr PluginDAOReadOnly::getLibraryDependencies() const } DbPluginHandle PluginDAOReadOnly::getPluginHandleForImplementedObject( - const std::string& objectName) + const std::string& objectName) { LogDebug("GetPluginHandle for object: " << objectName); @@ -249,7 +247,7 @@ DbPluginHandle PluginDAOReadOnly::getPluginHandleForImplementedObject( } ImplementedObjectsList PluginDAOReadOnly::getImplementedObjectsForPluginHandle( - DbPluginHandle handle) + DbPluginHandle handle) { LogDebug("getImplementedObjects for pluginHandle: " << handle); @@ -281,8 +279,9 @@ ImplementedObjectsList PluginDAOReadOnly::getImplementedObjectsForPluginHandle( } } -PluginObjectsDAO::ObjectsPtr PluginDAOReadOnly::getRequiredObjectsForPluginHandle( - DbPluginHandle handle) +PluginObjectsDAO::ObjectsPtr PluginDAOReadOnly:: + getRequiredObjectsForPluginHandle( + DbPluginHandle handle) { Try { @@ -314,7 +313,7 @@ PluginObjectsDAO::ObjectsPtr PluginDAOReadOnly::getRequiredObjectsForPluginHandl } PluginHandleSetPtr PluginDAOReadOnly::getPluginHandleByStatus( - PluginInstallationState state) + PluginInstallationState state) { Try { @@ -344,14 +343,16 @@ PluginHandleSetPtr PluginDAOReadOnly::getPluginHandleByStatus( } } -PluginDAOReadOnly::PluginInstallationState PluginDAOReadOnly::getInstallationStatus() const +PluginDAOReadOnly::PluginInstallationState PluginDAOReadOnly:: + getInstallationStatus() const { PluginRow row = getPluginRow(m_pluginHandle); return ToState(row.Get_InstallationState()); } -PluginDAOReadOnly::PluginInstallationState PluginDAOReadOnly::getInstallationStateForHandle( - DbPluginHandle handle) +PluginDAOReadOnly::PluginInstallationState PluginDAOReadOnly:: + getInstallationStateForHandle( + DbPluginHandle handle) { Try { @@ -396,5 +397,4 @@ bool PluginDAOReadOnly::isPluginInstalled(DbPluginHandle pluginHandle) "Failed in isPluginInstalled"); } } - } // namespace WrtDB diff --git a/modules/widget_dao/dao/property_dao.cpp b/modules/widget_dao/dao/property_dao.cpp index 14fcb51..8b3dabb 100644 --- a/modules/widget_dao/dao/property_dao.cpp +++ b/modules/widget_dao/dao/property_dao.cpp @@ -30,7 +30,6 @@ namespace WrtDB { namespace PropertyDAO { - void RemoveProperty(TizenAppId tzAppid, const PropertyDAOReadOnly::WidgetPropertyKey &key) { @@ -40,7 +39,8 @@ void RemoveProperty(TizenAppId tzAppid, LogDebug("Removing Property. appid: " << tzAppid << ", key: " << key); Try { - DPL::DB::ORM::wrt::ScopedTransaction transaction(&WrtDatabase::interface()); + DPL::DB::ORM::wrt::ScopedTransaction transaction( + &WrtDatabase::interface()); DPL::OptionalInt readonly = PropertyDAOReadOnly::CheckPropertyReadFlag( tzAppid, @@ -76,7 +76,8 @@ void SetProperty(DbWidgetHandle widgetHandle, const PropertyDAOReadOnly::WidgetPropertyValue &value, bool readOnly) { - SetProperty(WidgetDAOReadOnly::getTzAppId(widgetHandle),key,value,readOnly); + SetProperty(WidgetDAOReadOnly::getTzAppId( + widgetHandle), key, value, readOnly); } void SetProperty(TizenAppId tzAppid, @@ -89,7 +90,8 @@ void SetProperty(TizenAppId tzAppid, Try { using namespace DPL::DB::ORM; using namespace DPL::DB::ORM::wrt; - DPL::DB::ORM::wrt::ScopedTransaction transaction(&WrtDatabase::interface()); + DPL::DB::ORM::wrt::ScopedTransaction transaction( + &WrtDatabase::interface()); DPL::OptionalInt readonly = PropertyDAOReadOnly::CheckPropertyReadFlag( tzAppid, @@ -158,6 +160,5 @@ void RegisterProperties(TizenAppId tzAppid, } } } - } // namespace PropertyDAO } // namespace WrtDB diff --git a/modules/widget_dao/dao/property_dao_read_only.cpp b/modules/widget_dao/dao/property_dao_read_only.cpp index c95f070..c475f2a 100644 --- a/modules/widget_dao/dao/property_dao_read_only.cpp +++ b/modules/widget_dao/dao/property_dao_read_only.cpp @@ -30,17 +30,15 @@ namespace WrtDB { namespace PropertyDAOReadOnly { - namespace { - typedef DPL::DB::ORM::wrt::WidgetPreference::key_name::ColumnType - ORMWidgetPropertyKey; +ORMWidgetPropertyKey; typedef DPL::DB::ORM::wrt::WidgetPreference::key_value::ColumnType - ORMWidgetPropertyValue; -typedef std::list ORMWidgetPreferenceList; +ORMWidgetPropertyValue; +typedef std::list +ORMWidgetPreferenceList; typedef std::list ORMWidgetPropertyKeyList; - void convertPropertyKey(const ORMWidgetPropertyKey& ormKey, WidgetPropertyKey& key) { @@ -75,20 +73,18 @@ void convertWidgetPropertyKeyList(const ORMWidgetPropertyKeyList& propKeyList, keyList.push_back(*it); } } - - } //deprecated DPL::OptionalInt CheckPropertyReadFlag(DbWidgetHandle widgetHandle, - const WidgetPropertyKey &key) + const WidgetPropertyKey &key) { return CheckPropertyReadFlag(WidgetDAOReadOnly::getTzAppId(widgetHandle), key); } DPL::OptionalInt CheckPropertyReadFlag(TizenAppId tzAppid, - const WidgetPropertyKey &key) + const WidgetPropertyKey &key) { LogDebug("Checking Property flag. appid: " << tzAppid << ", key: " << key); @@ -133,10 +129,10 @@ WidgetPropertyKeyList GetPropertyKeyList(TizenAppId tzAppid) //deprecated WidgetPreferenceList GetPropertyList(DbWidgetHandle widgetHandle) { - Try{ + Try { TizenAppId tzAppid = WidgetDAOReadOnly::getTzAppId(widgetHandle); return GetPropertyList(tzAppid); - }Catch(WidgetDAOReadOnly::Exception::WidgetNotExist){ + } Catch(WidgetDAOReadOnly::Exception::WidgetNotExist){ WidgetPreferenceList empty; return empty; } @@ -176,7 +172,7 @@ WidgetPropertyValue GetPropertyValue(TizenAppId tzAppid, Equals(key))); ORMWidgetPropertyValue ormPropValue = - select->GetSingleValue(); + select->GetSingleValue(); WidgetPropertyValue propValue; @@ -189,6 +185,5 @@ WidgetPropertyValue GetPropertyValue(TizenAppId tzAppid, "Failure during getting property"); } } - } // namespace PropertyDAOReadOnly } // namespace WrtDB diff --git a/modules/widget_dao/dao/widget_dao.cpp b/modules/widget_dao/dao/widget_dao.cpp index eef1558..6529fd0 100644 --- a/modules/widget_dao/dao/widget_dao.cpp +++ b/modules/widget_dao/dao/widget_dao.cpp @@ -37,7 +37,6 @@ #include namespace WrtDB { - //TODO in current solution in each getter there exists a check //"IsWidgetInstalled". Maybe it should be verified, if it could be done //differently (check in WidgetDAO constructor) @@ -53,22 +52,18 @@ namespace WrtDB { WidgetDAO::WidgetDAO(DPL::OptionalString widgetGUID) : WidgetDAOReadOnly(WidgetDAOReadOnly::getHandle(widgetGUID)) -{ -} +{} WidgetDAO::WidgetDAO(DPL::String tzAppId) : WidgetDAOReadOnly(WidgetDAOReadOnly::getHandle(tzAppId)) -{ -} +{} WidgetDAO::WidgetDAO(DbWidgetHandle handle) : WidgetDAOReadOnly(handle) -{ -} +{} WidgetDAO::~WidgetDAO() -{ -} +{} void WidgetDAO::setTizenAppId(const DPL::OptionalString& tzAppId) { @@ -79,7 +74,7 @@ void WidgetDAO::setTizenAppId(const DPL::OptionalString& tzAppId) if (!isWidgetInstalled(getHandle())) { ThrowMsg(WidgetDAOReadOnly::Exception::WidgetNotExist, - "Cannot find widget. Handle: " << getHandle()); + "Cannot find widget. Handle: " << getHandle()); } wrt::WidgetInfo::Row row; @@ -106,7 +101,7 @@ void WidgetDAO::setSecurityPopupUsage(const SettingsType value) ScopedTransaction transaction(&WrtDatabase::interface()); if (!isWidgetInstalled(getHandle())) { ThrowMsg(WidgetDAOReadOnly::Exception::WidgetNotExist, - "Cannot find widget. Handle: " << getHandle()); + "Cannot find widget. Handle: " << getHandle()); } WidgetSecuritySettings::Row row; @@ -132,7 +127,7 @@ void WidgetDAO::setGeolocationUsage(const SettingsType value) ScopedTransaction transaction(&WrtDatabase::interface()); if (!isWidgetInstalled(getHandle())) { ThrowMsg(WidgetDAOReadOnly::Exception::WidgetNotExist, - "Cannot find widget. Handle: " << getHandle()); + "Cannot find widget. Handle: " << getHandle()); } WidgetSecuritySettings::Row row; @@ -158,7 +153,7 @@ void WidgetDAO::setWebNotificationUsage(const SettingsType value) ScopedTransaction transaction(&WrtDatabase::interface()); if (!isWidgetInstalled(getHandle())) { ThrowMsg(WidgetDAOReadOnly::Exception::WidgetNotExist, - "Cannot find widget. Handle: " << getHandle()); + "Cannot find widget. Handle: " << getHandle()); } WidgetSecuritySettings::Row row; @@ -184,7 +179,7 @@ void WidgetDAO::setWebDatabaseUsage(const SettingsType value) ScopedTransaction transaction(&WrtDatabase::interface()); if (!isWidgetInstalled(getHandle())) { ThrowMsg(WidgetDAOReadOnly::Exception::WidgetNotExist, - "Cannot find widget. Handle: " << getHandle()); + "Cannot find widget. Handle: " << getHandle()); } WidgetSecuritySettings::Row row; @@ -210,7 +205,7 @@ void WidgetDAO::setFileSystemUsage(const SettingsType value) ScopedTransaction transaction(&WrtDatabase::interface()); if (!isWidgetInstalled(getHandle())) { ThrowMsg(WidgetDAOReadOnly::Exception::WidgetNotExist, - "Cannot find widget. Handle: " << getHandle()); + "Cannot find widget. Handle: " << getHandle()); } WidgetSecuritySettings::Row row; @@ -227,14 +222,15 @@ void WidgetDAO::setFileSystemUsage(const SettingsType value) } void WidgetDAO::registerWidget( - const TizenAppId & tzAppId, - const WidgetRegisterInfo &widgetRegInfo, - const IWacSecurity &wacSecurity) + const TizenAppId & tzAppId, + const WidgetRegisterInfo &widgetRegInfo, + const IWacSecurity &wacSecurity) { LogDebug("Registering widget"); SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { - DPL::DB::ORM::wrt::ScopedTransaction transaction(&WrtDatabase::interface()); + DPL::DB::ORM::wrt::ScopedTransaction transaction( + &WrtDatabase::interface()); registerWidgetInternal(tzAppId, widgetRegInfo, wacSecurity); transaction.Commit(); } @@ -242,8 +238,8 @@ void WidgetDAO::registerWidget( } DbWidgetHandle WidgetDAO::registerWidget( - const WidgetRegisterInfo &pWidgetRegisterInfo, - const IWacSecurity &wacSecurity) + const WidgetRegisterInfo &pWidgetRegisterInfo, + const IWacSecurity &wacSecurity) { //make it more precise due to very fast tests struct timeval tv; @@ -254,13 +250,15 @@ DbWidgetHandle WidgetDAO::registerWidget( widgetHandle = rand(); } while (isWidgetInstalled(widgetHandle)); - registerWidget(*pWidgetRegisterInfo.configInfo.tizenAppId, pWidgetRegisterInfo, wacSecurity); + registerWidget(*pWidgetRegisterInfo.configInfo.tizenAppId, + pWidgetRegisterInfo, + wacSecurity); return widgetHandle; } TizenAppId WidgetDAO::registerWidgetGeneratePkgId( - const WidgetRegisterInfo &pWidgetRegisterInfo, - const IWacSecurity &wacSecurity) + const WidgetRegisterInfo &pWidgetRegisterInfo, + const IWacSecurity &wacSecurity) { TizenAppId tzAppId = generatePkgId(); registerWidget(tzAppId, pWidgetRegisterInfo, wacSecurity); @@ -268,14 +266,17 @@ TizenAppId WidgetDAO::registerWidgetGeneratePkgId( } void WidgetDAO::registerWidgetInternal( - const TizenAppId & tzAppId, - const WidgetRegisterInfo &widgetRegInfo, - const IWacSecurity &wacSecurity, - const DPL::Optional handle) + const TizenAppId & tzAppId, + const WidgetRegisterInfo &widgetRegInfo, + const IWacSecurity &wacSecurity, + const DPL::Optional handle) { //Register into WidgetInfo has to be first //as all other tables depend upon that - DbWidgetHandle widgetHandle = registerWidgetInfo(tzAppId, widgetRegInfo, wacSecurity, handle); + DbWidgetHandle widgetHandle = registerWidgetInfo(tzAppId, + widgetRegInfo, + wacSecurity, + handle); registerWidgetExtendedInfo(widgetHandle, widgetRegInfo); @@ -317,14 +318,15 @@ void WidgetDAO::registerWidgetInternal( } void WidgetDAO::registerOrUpdateWidget( - const TizenAppId & widgetName, - const WidgetRegisterInfo &widgetRegInfo, - const IWacSecurity &wacSecurity) + const TizenAppId & widgetName, + const WidgetRegisterInfo &widgetRegInfo, + const IWacSecurity &wacSecurity) { LogDebug("Reregistering widget"); SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { - DPL::DB::ORM::wrt::ScopedTransaction transaction(&WrtDatabase::interface()); + DPL::DB::ORM::wrt::ScopedTransaction transaction( + &WrtDatabase::interface()); unregisterWidgetInternal(widgetName); registerWidgetInternal(widgetName, widgetRegInfo, wacSecurity); @@ -341,13 +343,12 @@ void WidgetDAO::registerOrUpdateWidget( } void WidgetDAO::registerWidgetExtendedInfo(DbWidgetHandle widgetHandle, - const WidgetRegisterInfo ®Info) + const WidgetRegisterInfo ®Info) { //Try and transaction not needed using namespace DPL::DB::ORM; using namespace DPL::DB::ORM::wrt; - WidgetExtendedInfo::Row row; row.Set_app_id(widgetHandle); // row.Set_share_href (DPL::FromUTF8String(regInfo.shareHref)); @@ -362,10 +363,10 @@ void WidgetDAO::registerWidgetExtendedInfo(DbWidgetHandle widgetHandle, } DbWidgetHandle WidgetDAO::registerWidgetInfo( - const TizenAppId & tzAppId, - const WidgetRegisterInfo ®Info, - const IWacSecurity &wacSecurity, - const DPL::Optional handle) + const TizenAppId & tzAppId, + const WidgetRegisterInfo ®Info, + const IWacSecurity &wacSecurity, + const DPL::Optional handle) { using namespace DPL::DB::ORM; using namespace DPL::DB::ORM::wrt; @@ -375,13 +376,13 @@ DbWidgetHandle WidgetDAO::registerWidgetInfo( // Because of that, "Optional" is not used there WidgetInfo::Row row; - if(!!handle) - { + if (!!handle) { row.Set_app_id(*handle); } if (regInfo.webAppType == APP_TYPE_UNKNOWN && regInfo.type != - APP_TYPE_UNKNOWN) { + APP_TYPE_UNKNOWN) + { // TODO : regInfo.type is temporary code for security. // This code will be removed. row.Set_widget_type(regInfo.type.appType); @@ -423,21 +424,18 @@ DbWidgetHandle WidgetDAO::registerWidgetInfo( "Failed to register widget info."); } - if(!handle) - { + if (!handle) { //get autoincremented value of widgetHandle WRT_DB_SELECT(select, WidgetInfo, &WrtDatabase::interface()) select->Where(Equals(tzAppId)); return select->GetSingleValue(); - } - else - { + } else { return *handle; } } void WidgetDAO::registerWidgetLocalizedInfo(DbWidgetHandle widgetHandle, - const WidgetRegisterInfo ®Info) + const WidgetRegisterInfo ®Info) { using namespace DPL::DB::ORM; using namespace DPL::DB::ORM::wrt; @@ -464,12 +462,11 @@ void WidgetDAO::registerWidgetLocalizedInfo(DbWidgetHandle widgetHandle, } void WidgetDAO::registerWidgetIcons(DbWidgetHandle widgetHandle, - const WidgetRegisterInfo ®Info) + const WidgetRegisterInfo ®Info) { using namespace DPL::DB::ORM; using namespace DPL::DB::ORM::wrt; - FOREACH(i, regInfo.localizationData.icons) { wrt::WidgetIcon::icon_id::ColumnType icon_id; @@ -497,12 +494,11 @@ void WidgetDAO::registerWidgetIcons(DbWidgetHandle widgetHandle, } void WidgetDAO::registerWidgetStartFile(DbWidgetHandle widgetHandle, - const WidgetRegisterInfo ®Info) + const WidgetRegisterInfo ®Info) { using namespace DPL::DB::ORM; using namespace DPL::DB::ORM::wrt; - FOREACH(i, regInfo.localizationData.startFiles) { WidgetStartFile::start_file_id::ColumnType startFileID; @@ -531,12 +527,11 @@ void WidgetDAO::registerWidgetStartFile(DbWidgetHandle widgetHandle, } void WidgetDAO::registerWidgetFeatures(DbWidgetHandle widgetHandle, - const WidgetRegisterInfo ®Info) + const WidgetRegisterInfo ®Info) { using namespace DPL::DB::ORM; const ConfigParserData& widgetConfigurationInfo = regInfo.configInfo; - FOREACH(pWidgetFeature, widgetConfigurationInfo.featuresList) { wrt::WidgetFeature::Row widgetFeature; @@ -582,9 +577,12 @@ void WidgetDAO::registerWidgetPrivilege(DbWidgetHandle widgetHandle, } } -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" +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" // And: // ConfigurationParserData shouldn't be called "ParserData" any more. using namespace DPL::DB::ORM; @@ -606,13 +604,12 @@ void WidgetDAO::updateFeatureRejectStatus(const DbWidgetFeature &widgetFeature){ } void WidgetDAO::registerWidgetWindowModes(DbWidgetHandle widgetHandle, - const WidgetRegisterInfo ®Info) + const WidgetRegisterInfo ®Info) { using namespace DPL::DB::ORM; using namespace DPL::DB::ORM::wrt; const ConfigParserData& widgetConfigurationInfo = regInfo.configInfo; - FOREACH(i, widgetConfigurationInfo.windowModes) { wrt::WidgetWindowModes::Row windowMode; @@ -624,13 +621,12 @@ void WidgetDAO::registerWidgetWindowModes(DbWidgetHandle widgetHandle, } void WidgetDAO::registerWidgetWarpInfo(DbWidgetHandle widgetHandle, - const WidgetRegisterInfo ®Info) + const WidgetRegisterInfo ®Info) { using namespace DPL::DB::ORM; using namespace DPL::DB::ORM::wrt; const ConfigParserData& widgetConfigurationInfo = regInfo.configInfo; - FOREACH(AccIt, widgetConfigurationInfo.accessInfoSet) { WidgetWARPInfo::Row row; @@ -644,12 +640,11 @@ void WidgetDAO::registerWidgetWarpInfo(DbWidgetHandle widgetHandle, } void WidgetDAO::registerWidgetCertificates(DbWidgetHandle widgetHandle, - const IWacSecurity &wacSecurity) + const IWacSecurity &wacSecurity) { using namespace DPL::DB::ORM; using namespace DPL::DB::ORM::wrt; - FOREACH(it, wacSecurity.getCertificateList()) { WidgetCertificateFingerprint::Row row; @@ -665,9 +660,11 @@ void WidgetDAO::registerWidgetCertificates(DbWidgetHandle widgetHandle, } } -void WidgetDAO::registerCertificatesChains(DbWidgetHandle widgetHandle, - CertificateSource certificateSource, - const CertificateChainList &certificateChainList) +void WidgetDAO::registerCertificatesChains( + DbWidgetHandle widgetHandle, + CertificateSource certificateSource, + const CertificateChainList & + certificateChainList) { using namespace DPL::DB::ORM; using namespace DPL::DB::ORM::wrt; @@ -683,7 +680,7 @@ void WidgetDAO::registerCertificatesChains(DbWidgetHandle widgetHandle, } void WidgetDAO::registerWidgetSettings(DbWidgetHandle widgetHandle, - const WidgetRegisterInfo ®Info) + const WidgetRegisterInfo ®Info) { using namespace DPL::DB::ORM; using namespace DPL::DB::ORM::wrt; @@ -722,7 +719,7 @@ void WidgetDAO::registerAppService(DbWidgetHandle widgetHandle, } void WidgetDAO::registerEncryptedResouceInfo(DbWidgetHandle widgetHandle, - const WidgetRegisterInfo ®Info) + const WidgetRegisterInfo ®Info) { using namespace DPL::DB::ORM; using namespace DPL::DB::ORM::wrt; @@ -738,14 +735,17 @@ void WidgetDAO::registerEncryptedResouceInfo(DbWidgetHandle widgetHandle, } } -void WidgetDAO::registerExternalLocations(DbWidgetHandle widgetHandle, - const ExternalLocationList & externals) +void WidgetDAO::registerExternalLocations( + DbWidgetHandle widgetHandle, + const ExternalLocationList & + externals) { SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { using namespace DPL::DB::ORM; using namespace DPL::DB::ORM::wrt; - DPL::DB::ORM::wrt::ScopedTransaction transaction(&WrtDatabase::interface()); + DPL::DB::ORM::wrt::ScopedTransaction transaction( + &WrtDatabase::interface()); LogDebug("Inserting external files for widgetHandle: " << widgetHandle); FOREACH(it, externals) { @@ -790,7 +790,8 @@ void WidgetDAO::unregisterWidget(const TizenAppId & tzAppId) LogDebug("Unregistering widget from DB. tzAppId: " << tzAppId); SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { - DPL::DB::ORM::wrt::ScopedTransaction transaction(&WrtDatabase::interface()); + DPL::DB::ORM::wrt::ScopedTransaction transaction( + &WrtDatabase::interface()); unregisterWidgetInternal(tzAppId); transaction.Commit(); } @@ -817,7 +818,7 @@ void WidgetDAO::unregisterWidget(WrtDB::DbWidgetHandle handle) } void WidgetDAO::unregisterWidgetInternal( - const TizenAppId & tzAppId) + const TizenAppId & tzAppId) { using namespace DPL::DB::ORM; using namespace DPL::DB::ORM::wrt; @@ -836,5 +837,4 @@ void WidgetDAO::unregisterWidgetInternal( #undef SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN #undef SQL_CONNECTION_EXCEPTION_HANDLER_END - } // namespace WrtDB diff --git a/modules/widget_dao/dao/widget_dao_read_only.cpp b/modules/widget_dao/dao/widget_dao_read_only.cpp index 468aa20..f8fdf0b 100644 --- a/modules/widget_dao/dao/widget_dao_read_only.cpp +++ b/modules/widget_dao/dao/widget_dao_read_only.cpp @@ -38,7 +38,6 @@ #include namespace WrtDB { - //TODO in current solution in each getter there exists a check //"IsWidgetInstalled". Maybe it should be verified, if it could be done //differently (check in WidgetDAOReadOnly constructor) @@ -61,15 +60,13 @@ namespace WrtDB { "Cannot find widget. Handle: " << macro_handle); \ } - 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; +WidgetSecuritySettingsRow; namespace { - using namespace DPL::DB::ORM; using namespace DPL::DB::ORM::wrt; @@ -108,7 +105,8 @@ WidgetSecuritySettingsRow getWidgetSecuritySettingsRow(int widgetHandle) } return rows.front(); } - SQL_CONNECTION_EXCEPTION_HANDLER_END("Failed in getWidgetSecuritySettingsRow") + SQL_CONNECTION_EXCEPTION_HANDLER_END( + "Failed in getWidgetSecuritySettingsRow") } const int MAX_TIZENID_LENGTH = 10; @@ -125,12 +123,11 @@ TizenAppId getTizenAppIdByHandle(const DbWidgetHandle handle) if (rowList.empty()) { ThrowMsg(WidgetDAOReadOnly::Exception::WidgetNotExist, - "Failed to get widget by handle"); + "Failed to get widget by handle"); } TizenAppId tzAppid = rowList.front().Get_tizen_appid(); return tzAppid; - } SQL_CONNECTION_EXCEPTION_HANDLER_END("Failed in getHandle") } @@ -146,42 +143,33 @@ TizenAppId getTizenAppIdByPkgId(const TizenPkgId tzPkgid) if (rowList.empty()) { ThrowMsg(WidgetDAOReadOnly::Exception::WidgetNotExist, - "Failed to get widget by handle"); + "Failed to get widget by handle"); } TizenAppId tzAppid = rowList.front().Get_tizen_appid(); return tzAppid; - } SQL_CONNECTION_EXCEPTION_HANDLER_END("Failed in getHandle") - } } // namespace - IWacSecurity::~IWacSecurity() -{ -} +{} WidgetDAOReadOnly::WidgetDAOReadOnly(DbWidgetHandle widgetHandle) : m_widgetHandle(widgetHandle) -{ -} +{} WidgetDAOReadOnly::WidgetDAOReadOnly(DPL::OptionalString widgetGUID) : m_widgetHandle(WidgetDAOReadOnly::getHandle(widgetGUID)) -{ -} +{} WidgetDAOReadOnly::WidgetDAOReadOnly(DPL::String tzAppid) : m_widgetHandle(WidgetDAOReadOnly::getHandle(tzAppid)) -{ - -} +{} WidgetDAOReadOnly::~WidgetDAOReadOnly() -{ -} +{} DbWidgetHandle WidgetDAOReadOnly::getHandle() const { @@ -200,7 +188,7 @@ DbWidgetHandle WidgetDAOReadOnly::getHandle(const WidgetGUID GUID) if (rowList.empty()) { ThrowMsg(WidgetDAOReadOnly::Exception::WidgetNotExist, - "Failed to get widget by guid"); + "Failed to get widget by guid"); } return rowList.front().Get_app_id(); } @@ -219,7 +207,7 @@ DbWidgetHandle WidgetDAOReadOnly::getHandle(const DPL::String tzAppId) if (rowList.empty()) { ThrowMsg(WidgetDAOReadOnly::Exception::WidgetNotExist, - "Failed to get widget by package name"); + "Failed to get widget by package name"); } return rowList.front().Get_app_id(); } @@ -243,7 +231,7 @@ WidgetPkgName WidgetDAOReadOnly::getPkgName(const DbWidgetHandle handle) TizenAppId WidgetDAOReadOnly::getTzAppId() const { - return getTizenAppIdByHandle(m_widgetHandle); + return getTizenAppIdByHandle(m_widgetHandle); } TizenAppId WidgetDAOReadOnly::getTzAppId(const WidgetGUID GUID) @@ -274,13 +262,13 @@ WidgetDAOReadOnly::getPropertyList() const } PropertyDAOReadOnly::WidgetPropertyValue WidgetDAOReadOnly::getPropertyValue( - const PropertyDAOReadOnly::WidgetPropertyKey &key) const + const PropertyDAOReadOnly::WidgetPropertyKey &key) const { return PropertyDAOReadOnly::GetPropertyValue(getTzAppId(), key); } DPL::OptionalInt WidgetDAOReadOnly::checkPropertyReadFlag( - const PropertyDAOReadOnly::WidgetPropertyKey &key) const + const PropertyDAOReadOnly::WidgetPropertyKey &key) const { return PropertyDAOReadOnly::CheckPropertyReadFlag(getTzAppId(), key); } @@ -301,8 +289,8 @@ DPL::String WidgetDAOReadOnly::getFullPath() const } WidgetLocalizedInfo - WidgetDAOReadOnly::getLocalizedInfo(const DPL::String& languageTag) - const +WidgetDAOReadOnly::getLocalizedInfo(const DPL::String& languageTag) +const { LogDebug("Getting Localized Info. Handle: " << m_widgetHandle); SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN @@ -375,7 +363,7 @@ WidgetParamMap WidgetDAOReadOnly::getFeatureParams(int id) RowList list = select->GetRowList(); FOREACH(i, list) - resultMap.insert(std::make_pair(i->Get_name(), i->Get_value())); + resultMap.insert(std::make_pair(i->Get_name(), i->Get_value())); return resultMap; } @@ -525,7 +513,7 @@ ExternalLocationList WidgetDAOReadOnly::getWidgetExternalLocations() const } CertificateChainList WidgetDAOReadOnly::getWidgetCertificate( - CertificateSource source) const + CertificateSource source) const { WRT_DB_SELECT(select, WidgetCertificate, &WrtDatabase::interface()) select->Where( @@ -538,7 +526,7 @@ CertificateChainList WidgetDAOReadOnly::getWidgetCertificate( CertificateChainList result; FOREACH(iter, chainList) - result.push_back(DPL::ToUTF8String(iter->Get_encoded_chain())); + result.push_back(DPL::ToUTF8String(iter->Get_encoded_chain())); return result; } @@ -708,7 +696,10 @@ bool WidgetDAOReadOnly::getWebkitPluginsRequired() const WidgetInfoRow row = getWidgetInfoRow(m_widgetHandle); DPL::OptionalInt ret = row.Get_webkit_plugins_required(); - if (ret.IsNull() || *ret == 0) { return false; } else { return true; } + if (ret.IsNull() || *ret == 0) { + return false; + } else { return true; + } } time_t WidgetDAOReadOnly::getInstallTime() const @@ -752,7 +743,8 @@ DPL::OptionalString WidgetDAOReadOnly::getSplashImgSrc() const SQL_CONNECTION_EXCEPTION_HANDLER_END("Failed to get splash image path") } -WidgetDAOReadOnly::WidgetLocalizedIconList WidgetDAOReadOnly::getLocalizedIconList() const +WidgetDAOReadOnly::WidgetLocalizedIconList WidgetDAOReadOnly:: + getLocalizedIconList() const { //TODO check widget existance?? SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN @@ -761,13 +753,13 @@ WidgetDAOReadOnly::WidgetLocalizedIconList WidgetDAOReadOnly::getLocalizedIconLi select->Where(Equals(m_widgetHandle)); std::list list = - select->GetRowList(); + select->GetRowList(); WidgetLocalizedIconList ret; - FOREACH(it,list) + FOREACH(it, list) { - WidgetLocalizedIconRow icon = {it->Get_app_id(), - it->Get_icon_id(), - it->Get_widget_locale()}; + WidgetLocalizedIconRow icon = { it->Get_app_id(), + it->Get_icon_id(), + it->Get_widget_locale() }; ret.push_back(icon); } return ret; @@ -782,18 +774,19 @@ WidgetDAOReadOnly::WidgetIconList WidgetDAOReadOnly::getIconList() const { WRT_DB_SELECT(select, wrt::WidgetIcon, &WrtDatabase::interface()) select->Where(Equals(m_widgetHandle)); - select->OrderBy(DPL::TypeListDecl >()); + select->OrderBy(DPL::TypeListDecl >()); std::list list = - select->GetRowList(); + select->GetRowList(); WidgetIconList ret; - FOREACH(it,list) + FOREACH(it, list) { - WidgetIconRow icon = {it->Get_icon_id(), - it->Get_app_id(), - it->Get_icon_src(), - it->Get_icon_width(), - it->Get_icon_height()}; + WidgetIconRow icon = { it->Get_icon_id(), + it->Get_app_id(), + it->Get_icon_src(), + it->Get_icon_width(), + it->Get_icon_height() }; ret.push_back(icon); } return ret; @@ -801,7 +794,8 @@ WidgetDAOReadOnly::WidgetIconList WidgetDAOReadOnly::getIconList() const SQL_CONNECTION_EXCEPTION_HANDLER_END("Failed to get icon data") } -WidgetDAOReadOnly::LocalizedStartFileList WidgetDAOReadOnly::getLocalizedStartFileList() const +WidgetDAOReadOnly::LocalizedStartFileList WidgetDAOReadOnly:: + getLocalizedStartFileList() const { //TODO check widget existance SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN @@ -812,15 +806,15 @@ WidgetDAOReadOnly::LocalizedStartFileList WidgetDAOReadOnly::getLocalizedStartFi select->OrderBy("start_file_id ASC"); std::list list = - select->GetRowList(); + select->GetRowList(); LocalizedStartFileList ret; - FOREACH(it,list) + FOREACH(it, list) { - WidgetLocalizedStartFileRow file = {it->Get_start_file_id(), - it->Get_app_id(), - it->Get_widget_locale(), - it->Get_type(), - it->Get_encoding()}; + WidgetLocalizedStartFileRow file = { it->Get_start_file_id(), + it->Get_app_id(), + it->Get_widget_locale(), + it->Get_type(), + it->Get_encoding() }; ret.push_back(file); } return ret; @@ -828,7 +822,8 @@ WidgetDAOReadOnly::LocalizedStartFileList WidgetDAOReadOnly::getLocalizedStartFi SQL_CONNECTION_EXCEPTION_HANDLER_END("Failed to get start file list data") } -WidgetDAOReadOnly::WidgetStartFileList WidgetDAOReadOnly::getStartFileList() const +WidgetDAOReadOnly::WidgetStartFileList WidgetDAOReadOnly::getStartFileList() +const { //TODO check widget existance SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN @@ -838,13 +833,13 @@ WidgetDAOReadOnly::WidgetStartFileList WidgetDAOReadOnly::getStartFileList() con select->OrderBy("start_file_id ASC"); std::list list = - select->GetRowList(); + select->GetRowList(); WidgetStartFileList ret; - FOREACH(it,list) + FOREACH(it, list) { - WidgetStartFileRow file = {it->Get_start_file_id(), - it->Get_app_id(), - it->Get_src()}; + WidgetStartFileRow file = { it->Get_start_file_id(), + it->Get_app_id(), + it->Get_src() }; ret.push_back(file); } return ret; @@ -886,7 +881,9 @@ WidgetCertificateDataList WidgetDAOReadOnly::getCertificateDataList() const //TODO check widget existance SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { - WRT_DB_SELECT(select, WidgetCertificateFingerprint, &WrtDatabase::interface()) + WRT_DB_SELECT(select, + WidgetCertificateFingerprint, + &WrtDatabase::interface()) select->Where(Equals( m_widgetHandle)); select->OrderBy("chainid"); @@ -921,17 +918,20 @@ WidgetCertificateDataList WidgetDAOReadOnly::getCertificateDataList() const } FingerPrintList WidgetDAOReadOnly::getKeyFingerprints( - WidgetCertificateData::Owner owner, - WidgetCertificateData::Type type) const + WidgetCertificateData::Owner owner, + WidgetCertificateData::Type type) const { //TODO check widget existance SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { - WRT_DB_SELECT(select, WidgetCertificateFingerprint, &WrtDatabase::interface()) + WRT_DB_SELECT(select, + WidgetCertificateFingerprint, + &WrtDatabase::interface()) select->Where(And(And( - Equals(m_widgetHandle), - Equals(owner)), - Equals(type))); + Equals( + m_widgetHandle), + Equals(owner)), + Equals(type))); WidgetCertificateFingerprint::Select::RowList rows = select->GetRowList(); @@ -954,17 +954,20 @@ FingerPrintList WidgetDAOReadOnly::getKeyFingerprints( } WidgetCertificateCNList WidgetDAOReadOnly::getKeyCommonNameList( - WidgetCertificateData::Owner owner, - WidgetCertificateData::Type type) const + WidgetCertificateData::Owner owner, + WidgetCertificateData::Type type) const { //TODO check widget existance SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN { - WRT_DB_SELECT(select, WidgetCertificateFingerprint, &WrtDatabase::interface()) + WRT_DB_SELECT(select, + WidgetCertificateFingerprint, + &WrtDatabase::interface()) select->Where(And(And( - Equals(m_widgetHandle), - Equals(owner)), - Equals(type))); + Equals( + m_widgetHandle), + Equals(owner)), + Equals(type))); WidgetCertificateFingerprint::Select::RowList rows = select->GetRowList(); @@ -981,7 +984,7 @@ WidgetCertificateCNList WidgetDAOReadOnly::getKeyCommonNameList( } ResourceAttributeList WidgetDAOReadOnly::getResourceAttribute( - const std::string &resourceId) const + const std::string &resourceId) const { WRT_DB_SELECT(select, WidgetFeature, &WrtDatabase::interface()) select->Where(And(Equals(m_widgetHandle), @@ -995,13 +998,13 @@ ResourceAttributeList WidgetDAOReadOnly::getResourceAttribute( WidgetParamMap map = getFeatureParams(widgetFeatureId); FOREACH(i, map) - result.push_back(DPL::ToUTF8String(i->first)); + result.push_back(DPL::ToUTF8String(i->first)); } return result; } void WidgetDAOReadOnly::getWidgetAccessInfo( - WidgetAccessInfoList& outAccessInfoList) const + WidgetAccessInfoList& outAccessInfoList) const { //TODO check widget existance SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN @@ -1075,7 +1078,7 @@ std::string WidgetDAOReadOnly::getPrivateLocalStoragePath() const } void WidgetDAOReadOnly::getWidgetSettings( - WidgetSettings& outWidgetSettings) const + WidgetSettings& outWidgetSettings) const { //TODO check widget existance SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN @@ -1098,7 +1101,7 @@ void WidgetDAOReadOnly::getWidgetSettings( } void WidgetDAOReadOnly::getAppServiceList( - WidgetApplicationServiceList& outAppServiceList) const + WidgetApplicationServiceList& outAppServiceList) const { LogDebug("Getting getAppServiceList. Handle: " << m_widgetHandle); SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN @@ -1137,7 +1140,8 @@ PackagingType WidgetDAOReadOnly::getPackagingType() const return PackagingType(static_cast(*result)); } -void WidgetDAOReadOnly::getEncryptedFileList(EncryptedFileList& filesList) const +void WidgetDAOReadOnly::getEncryptedFileList(EncryptedFileList& filesList) +const { //TODO check widget existance WRT_DB_SELECT(select, EncryptedResourceList, &WrtDatabase::interface()) @@ -1172,16 +1176,17 @@ DPL::OptionalString WidgetDAOReadOnly::getBackgroundPage() const SQL_CONNECTION_EXCEPTION_HANDLER_END("Failed to get background page") } -TizenPkgId WidgetDAOReadOnly::generatePkgId() { +TizenPkgId WidgetDAOReadOnly::generatePkgId() +{ std::string allowed("0123456789" - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz"); + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz"); TizenPkgId pkgId; pkgId.resize(MAX_TIZENID_LENGTH); do { - for (int i = 0; i < MAX_TIZENID_LENGTH; ++i) { - pkgId[i] = allowed[rand() % allowed.length()]; - } + for (int i = 0; i < MAX_TIZENID_LENGTH; ++i) { + pkgId[i] = allowed[rand() % allowed.length()]; + } } while (isWidgetInstalled(pkgId)); return pkgId; } @@ -1255,5 +1260,4 @@ TizenPkgId WidgetDAOReadOnly::getTizenPkgId() const #undef SQL_CONNECTION_EXCEPTION_HANDLER_BEGIN #undef SQL_CONNECTION_EXCEPTION_HANDLER_END #undef CHECK_WIDGET_EXISTENCE - } // namespace WrtDB diff --git a/modules/widget_dao/include/dpl/wrt-dao-ro/WrtDatabase.h b/modules/widget_dao/include/dpl/wrt-dao-ro/WrtDatabase.h index 28ebdf5..8caa49f 100644 --- a/modules/widget_dao/include/dpl/wrt-dao-ro/WrtDatabase.h +++ b/modules/widget_dao/include/dpl/wrt-dao-ro/WrtDatabase.h @@ -14,12 +14,11 @@ * limitations under the License. */ #ifndef WRT_SRC_CONFIGURATION_WRTDATABASE_H_ -#define WRT_SRC_CONFIGURATION_WRTDATABASE_H_ +#define WRT_SRC_CONFIGURATION_WRTDATABASE_H_ #include namespace WrtDB { - class WrtDatabase { public: @@ -34,7 +33,6 @@ class WrtDatabase private: static DPL::DB::ThreadDatabaseSupport m_interface; }; - } #endif /* WRTDATABASE_H */ 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 c76b5b5..ff30556 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 @@ -32,7 +32,6 @@ #include #include - namespace WrtDB { class PluginMetafileData { @@ -52,8 +51,7 @@ class PluginMetafileData public: PluginMetafileData() - { - } + {} std::string m_libraryName; FeatureContainer m_featureContainer; @@ -101,11 +99,10 @@ struct DbWidgetSize DPL::OptionalInt height; DbWidgetSize(DPL::OptionalInt w = DPL::OptionalInt::Null, - DPL::OptionalInt h = DPL::OptionalInt::Null) : + DPL::OptionalInt h = DPL::OptionalInt::Null) : width(w), height(h) - { - } + {} }; inline bool operator ==(const DbWidgetSize &objA, const DbWidgetSize &objB) @@ -210,18 +207,17 @@ struct DbWidgetFeature DbWidgetFeature() : required(false), pluginId(INVALID_PLUGIN_HANDLE) - { - } + {} }; inline bool operator < (const DbWidgetFeature &objA, - const DbWidgetFeature &objB) + const DbWidgetFeature &objB) { return objA.name.compare(objB.name) < 0; } inline bool operator==(const DbWidgetFeature &featureA, - const DbWidgetFeature &featureB) + const DbWidgetFeature &featureB) { return featureA.name == featureB.name && featureA.required == featureB.required && @@ -238,8 +234,12 @@ 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 TizenAppIdList; //TODO: this cannot be null -> appropriate changes in db schema needed +typedef std::list WidgetPkgNameList; //TODO: this cannot be null + // -> appropriate changes in + // db schema needed +typedef std::list TizenAppIdList; //TODO: this cannot be null -> + // appropriate changes in db + // schema needed class WidgetDAOReadOnly; //forward declaration typedef std::shared_ptr WidgetDAOReadOnlyPtr; @@ -263,14 +263,12 @@ enum AppType class WidgetType { public: - WidgetType() - :appType(APP_TYPE_UNKNOWN) - { - } - WidgetType(const AppType type) - :appType(type) - { - } + WidgetType() : + appType(APP_TYPE_UNKNOWN) + {} + WidgetType(const AppType type) : + appType(type) + {} bool operator== (const AppType& other) const { return appType == other; @@ -283,9 +281,9 @@ class WidgetType { switch (appType) { #define X(x) case x: return #x; - X(APP_TYPE_UNKNOWN) - X(APP_TYPE_WAC20) - X(APP_TYPE_TIZENWEBAPP) + X(APP_TYPE_UNKNOWN) + X(APP_TYPE_WAC20) + X(APP_TYPE_TIZENWEBAPP) #undef X default: return "UNKNOWN"; @@ -312,14 +310,12 @@ enum PkgType class PackagingType { public: - PackagingType() - :pkgType(PKG_TYPE_UNKNOWN) - { - } - PackagingType(const PkgType type) - :pkgType(type) - { - } + PackagingType() : + pkgType(PKG_TYPE_UNKNOWN) + {} + PackagingType(const PkgType type) : + pkgType(type) + {} bool operator== (const PkgType& other) const { return pkgType == other; @@ -332,11 +328,11 @@ class PackagingType { switch (pkgType) { #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) + 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 default: return "UNKNOWN"; @@ -363,12 +359,12 @@ struct WidgetSetting bool operator ==(const WidgetSetting& info) const { return (info.settingName == settingName && - info.settingValue == settingValue); + info.settingValue == settingValue); } bool operator !=(const WidgetSetting& info) const { return (info.settingName != settingName || - info.settingValue != settingValue); + info.settingValue != settingValue); } }; @@ -391,9 +387,9 @@ struct WidgetApplicationService bool operator== (const WidgetApplicationService& other) const { return src == other.src && - operation == other.operation && - scheme == other.scheme && - mime == other.mime; + operation == other.operation && + scheme == other.scheme && + mime == other.mime; } }; 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 100755 new mode 100644 index 2241a7a..c6ae0bd --- 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 @@ -31,7 +31,6 @@ #include namespace WrtDB { - void NormalizeString(DPL::OptionalString& txt, bool isTrimSpace = false); void NormalizeString(DPL::String& str); DPL::String GetSingleAttributeValue(const DPL::String value); @@ -45,8 +44,7 @@ class ConfigParserData struct Param { Param(const DPL::String& _name) : name(_name) - { - } + {} DPL::String name; DPL::String value; bool operator==(const Param&) const; @@ -63,8 +61,7 @@ class ConfigParserData Feature(const DPL::String& _name, bool _required = true) : name(_name), required(_required) - { - } + {} DPL::String name; bool required; ParamsList paramsList; @@ -81,8 +78,7 @@ class ConfigParserData struct Privilege { Privilege(const DPL::String& _name) : name(_name) - { - } + {} DPL::String name; bool operator==(const Privilege&) const; @@ -97,8 +93,7 @@ class ConfigParserData struct Icon { Icon(const DPL::String& _src) : src(_src) - { - } + {} DPL::String src; DPL::OptionalInt width; DPL::OptionalInt height; @@ -127,12 +122,11 @@ class ConfigParserData struct Preference { Preference(const DPL::String& _name, - bool _readonly = false) : + bool _readonly = false) : name(_name), value(), readonly(_readonly) - { - } + {} DPL::String name; DPL::OptionalString value; bool readonly; @@ -149,10 +143,9 @@ class ConfigParserData struct AccessInfo { AccessInfo(const DPL::String& strIRI, - bool bSubdomainAccess) : m_strIRI(strIRI), + bool bSubdomainAccess) : m_strIRI(strIRI), m_bSubDomainAccess(bSubdomainAccess) - { - } + {} bool operator==(const AccessInfo&) const; bool operator!=(const AccessInfo&) const; @@ -167,10 +160,9 @@ class ConfigParserData { Setting(const DPL::String& name, const DPL::String& value) : - m_name(name), - m_value(value) - { - } + m_name(name), + m_value(value) + {} DPL::String m_name; DPL::String m_value; @@ -198,8 +190,7 @@ class ConfigParserData m_operation(operation), m_scheme(scheme), m_mime(mime) - { - } + {} DPL::String m_src; DPL::String m_operation; DPL::String m_scheme; @@ -214,8 +205,7 @@ class ConfigParserData AppControlInfo( const DPL::String& operation) : m_operation(operation) - { - } + {} DPL::String m_src; DPL::String m_operation; std::set m_uriList; @@ -228,7 +218,7 @@ class ConfigParserData typedef std::list ServiceInfoList; // It will be removed. typedef std::list AppControlInfoList; - typedef std::list> BoxSizeList; + typedef std::list > BoxSizeList; struct LiveboxInfo { @@ -242,7 +232,8 @@ class ConfigParserData DPL::String m_pdSrc; DPL::String m_pdWidth; DPL::String m_pdHeight; - }; typedef BoxContent BoxContentInfo; + }; + typedef BoxContent BoxContentInfo; DPL::String m_label; DPL::String m_icon; @@ -260,7 +251,7 @@ class ConfigParserData bool operator <(const LiveboxInfo&) const; bool operator<=(const LiveboxInfo&) const; }; - typedef std::list> LiveboxList; + typedef std::list > LiveboxList; LiveboxList m_livebox; typedef std::list DependsPkgList; @@ -335,10 +326,8 @@ class ConfigParserData backSupported(false), accessNetwork(false), startFileEncountered(false) - { - } + {} }; - } // namespace WrtDB #endif //CONFIG_PARSER_DATA_H_ diff --git a/modules/widget_dao/include/dpl/wrt-dao-ro/feature_dao_read_only.h b/modules/widget_dao/include/dpl/wrt-dao-ro/feature_dao_read_only.h index 1a736f9..14aec55 100644 --- a/modules/widget_dao/include/dpl/wrt-dao-ro/feature_dao_read_only.h +++ b/modules/widget_dao/include/dpl/wrt-dao-ro/feature_dao_read_only.h @@ -32,7 +32,6 @@ #include namespace WrtDB { - class FeatureDAOReadOnly { public: @@ -58,7 +57,7 @@ class FeatureDAOReadOnly FeatureDAOReadOnly(const std::string &featureName); static FeatureHandleListPtr GetFeatureHandleListForPlugin( - DbPluginHandle pluginHandle); + DbPluginHandle pluginHandle); static bool isFeatureInstalled(const std::string &featureName); static bool isFeatureInstalled(FeatureHandle handle); @@ -79,7 +78,6 @@ class FeatureDAOReadOnly protected: FeatureHandle m_featureHandle; }; - } // namespace WrtDB #endif /* WRT_SRC_CONFIGURATION_FEATURE_DAO_READ_ONLY_H_ */ 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 fc9754d..8698d4a 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 @@ -31,7 +31,6 @@ #include namespace WrtDB { - typedef int FeatureHandle; typedef std::list FeatureHandleList; typedef std::shared_ptr FeatureHandleListPtr; @@ -40,8 +39,8 @@ typedef int FeatureSetHandle; typedef std::list FeatureSetHandleList; typedef struct { - std::string featureName; - DbPluginHandle pluginHandle; + std::string featureName; + DbPluginHandle pluginHandle; } FeatureData; class FeatureModel : public DPL::Event::Model @@ -58,10 +57,11 @@ class FeatureModel : public DPL::Event::Model Name(this), DeviceCapabilities(this), PHandle(this, -1) - { - } + {} - void SetData(const std::string& name, const std::set& deviceCapabilities, const DbPluginHandle& pluginHandle) + void SetData(const std::string& name, + const std::set& deviceCapabilities, + const DbPluginHandle& pluginHandle) { Name.SetWithoutLock(name); DeviceCapabilities.SetWithoutLock(deviceCapabilities); @@ -70,7 +70,6 @@ class FeatureModel : public DPL::Event::Model }; typedef std::shared_ptr FeatureModelPtr; - } // namespace WrtDB #endif // FEATURE_MODEL_H 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 5558dbd..67dcca6 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 @@ -319,7 +319,6 @@ inline const char* GetVconfKeyMemorySavingModePath() { return "/memory_saving_mode"; } - } // namespace GlobalConfig } // namespace WrtDB diff --git a/modules/widget_dao/include/dpl/wrt-dao-ro/global_dao_read_only.h b/modules/widget_dao/include/dpl/wrt-dao-ro/global_dao_read_only.h index 8442218..f5eab4e 100644 --- a/modules/widget_dao/include/dpl/wrt-dao-ro/global_dao_read_only.h +++ b/modules/widget_dao/include/dpl/wrt-dao-ro/global_dao_read_only.h @@ -33,7 +33,6 @@ #include namespace WrtDB { - typedef std::list WidgetPackageList; typedef std::set DeviceCapabilitySet; @@ -99,14 +98,12 @@ class GlobalDAOReadOnly * This method returns set of device capabilities used by apifeature. */ static DeviceCapabilitySet GetDeviceCapability( - const DPL::String &apifeature); + const DPL::String &apifeature); protected: GlobalDAOReadOnly() - { - } + {} }; - } // namespace WrtDB #endif // WRT_SRC_CONFIGURATION_GLOBAL_DAO_READ_ONLY_H_ diff --git a/modules/widget_dao/include/dpl/wrt-dao-ro/path_builder.h b/modules/widget_dao/include/dpl/wrt-dao-ro/path_builder.h index 18fcca3..4ea6a4f 100644 --- a/modules/widget_dao/include/dpl/wrt-dao-ro/path_builder.h +++ b/modules/widget_dao/include/dpl/wrt-dao-ro/path_builder.h @@ -26,7 +26,6 @@ #include namespace WrtDB { - class PathBuilderImpl; class PathBuilder : private DPL::Noncopyable @@ -51,7 +50,6 @@ class PathBuilder : private DPL::Noncopyable private: PathBuilderImpl* m_impl; }; - } // namespace WrtDB #endif 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 044d3d0..eb9c030 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 @@ -20,7 +20,6 @@ * @brief This file contains the declaration of plugin dao read only */ - #ifndef WRT_SRC_CONFIGURATION_PLUGIN_DAO_READ_ONLY_H_ #define WRT_SRC_CONFIGURATION_PLUGIN_DAO_READ_ONLY_H_ @@ -31,7 +30,6 @@ #include namespace WrtDB { - typedef std::list PluginHandleList; typedef std::set PluginHandleSet; typedef std::list ImplementedObjectsList; @@ -86,19 +84,19 @@ class PluginDAOReadOnly static bool isPluginInstalled(DbPluginHandle pluginHandle); static PluginHandleSetPtr getPluginHandleByStatus( - PluginInstallationState state); + PluginInstallationState state); static DbPluginHandle getPluginHandleForImplementedObject( - const std::string& objectName); + const std::string& objectName); static ImplementedObjectsList getImplementedObjectsForPluginHandle( - DbPluginHandle handle); + DbPluginHandle handle); static PluginObjectsDAO::ObjectsPtr getRequiredObjectsForPluginHandle( - DbPluginHandle handle); + DbPluginHandle handle); static PluginInstallationState getInstallationStateForHandle( - DbPluginHandle handle); + DbPluginHandle handle); DbPluginHandle getPluginHandle() const; PluginInstallationState getInstallationStatus() const; @@ -111,7 +109,6 @@ class PluginDAOReadOnly void checkInstallationCompleted(); }; - } // namespace WrtDB #endif /* WRT_SRC_CONFIGURATION_PLUGIN_DAO_READ_ONLY_H_ */ 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 beb3101..d7ff799 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 @@ -31,17 +31,16 @@ namespace WrtDB { namespace PropertyDAOReadOnly { - typedef DPL::String WidgetPropertyKey; typedef DPL::OptionalString WidgetPropertyValue; typedef std::list WidgetPropertyKeyList; struct WidgetPreferenceRow { - TizenAppId tizen_appid; - WidgetPropertyKey key_name; + TizenAppId tizen_appid; + WidgetPropertyKey key_name; WidgetPropertyValue key_value; - DPL::OptionalInt readonly; + DPL::OptionalInt readonly; }; typedef std::list WidgetPreferenceList; @@ -61,13 +60,13 @@ class Exception /* This method checks read only flag for given property */ DPL::OptionalInt CheckPropertyReadFlag(DbWidgetHandle widgetHandle, - const WidgetPropertyKey &key) - __attribute__((deprecated)); + const WidgetPropertyKey &key) +__attribute__((deprecated)); /* This method checks read only flag for given property */ DPL::OptionalInt CheckPropertyReadFlag(TizenAppId tzAppid, - const WidgetPropertyKey &key); + const WidgetPropertyKey &key); /* This method gets widget property key list */ @@ -77,7 +76,7 @@ WidgetPropertyKeyList GetPropertyKeyList(TizenAppId tzAppid); /* This method gets widget property list */ WidgetPreferenceList GetPropertyList(DbWidgetHandle widgetHandle) - __attribute__((deprecated)); +__attribute__((deprecated)); /* This method gets widget property list */ @@ -87,7 +86,6 @@ WidgetPreferenceList GetPropertyList(TizenAppId tzAppid); */ WidgetPropertyValue GetPropertyValue(TizenAppId tzAppid, 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 index e90e737..5f23262 100644 --- a/modules/widget_dao/include/dpl/wrt-dao-ro/vconf_config.h +++ b/modules/widget_dao/include/dpl/wrt-dao-ro/vconf_config.h @@ -91,7 +91,6 @@ inline std::string GetVconfKeyMemorySavingMode(DPL::String tzPkgId) .Concat(GlobalConfig::GetVconfKeyMemorySavingModePath()) .GetFullPath(); } - } // namespace VconfConfig } // namespace WrtDB diff --git a/modules/widget_dao/include/dpl/wrt-dao-ro/webruntime_database.h b/modules/widget_dao/include/dpl/wrt-dao-ro/webruntime_database.h index 96afd44..67c88a9 100644 --- a/modules/widget_dao/include/dpl/wrt-dao-ro/webruntime_database.h +++ b/modules/widget_dao/include/dpl/wrt-dao-ro/webruntime_database.h @@ -28,23 +28,31 @@ extern DPL::Mutex g_wrtDbQueriesMutex; #define WRT_DB_INTERNAL(tlsCommand, InternalType, interface) \ - static DPL::ThreadLocalVariable *tlsCommand ## Ptr = NULL; \ + static DPL::ThreadLocalVariable *tlsCommand##Ptr = NULL; \ { \ DPL::Mutex::ScopedLock lock(&g_wrtDbQueriesMutex); \ - if (!tlsCommand ## Ptr) { \ + if (!tlsCommand##Ptr) { \ static DPL::ThreadLocalVariable tmp; \ - tlsCommand ## Ptr = &tmp; \ + tlsCommand##Ptr = &tmp; \ } \ } \ - DPL::ThreadLocalVariable &tlsCommand = *tlsCommand ## Ptr; \ + DPL::ThreadLocalVariable &tlsCommand = *tlsCommand##Ptr; \ if (tlsCommand.IsNull()) { tlsCommand = InternalType(interface); } -#define WRT_DB_SELECT(name, type, interface) WRT_DB_INTERNAL(name, type::Select, interface) +#define WRT_DB_SELECT(name, type, interface) WRT_DB_INTERNAL(name, \ + type::Select, \ + interface) -#define WRT_DB_INSERT(name, type, interface) WRT_DB_INTERNAL(name, type::Insert, interface) +#define WRT_DB_INSERT(name, type, interface) WRT_DB_INTERNAL(name, \ + type::Insert, \ + interface) -#define WRT_DB_UPDATE(name, type, interface) WRT_DB_INTERNAL(name, type::Update, interface) +#define WRT_DB_UPDATE(name, type, interface) WRT_DB_INTERNAL(name, \ + type::Update, \ + interface) -#define WRT_DB_DELETE(name, type, interface) WRT_DB_INTERNAL(name, type::Delete, interface) +#define WRT_DB_DELETE(name, type, interface) WRT_DB_INTERNAL(name, \ + type::Delete, \ + interface) #endif // WRT_ENGINE_SRC_CONFIGURATION_WEBRUNTIME_DATABASE_H 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 6cdd425..1144bdc 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 @@ -31,7 +31,6 @@ namespace WrtDB { namespace WidgetConfig { - inline std::string GetWidgetBasePath(DPL::String tzPkgId) { return PathBuilder() 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 34d191e..a7cd866 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 @@ -39,7 +39,6 @@ #include namespace WrtDB { - /** * Widget's signature enum. * This enumerates signature type of widget. @@ -90,12 +89,13 @@ struct WidgetCertificateData // Common name field in certificate DPL::String strCommonName; - bool operator== (const WidgetCertificateData& certData) const { + bool operator== (const WidgetCertificateData& certData) const + { return certData.chainId == chainId && - certData.owner == owner && - certData.strCommonName == strCommonName && - certData.strMD5Fingerprint == strMD5Fingerprint && - certData.strSHA1Fingerprint == strSHA1Fingerprint; + certData.owner == owner && + certData.strCommonName == strCommonName && + certData.strMD5Fingerprint == strMD5Fingerprint && + certData.strSHA1Fingerprint == strSHA1Fingerprint; } }; @@ -115,11 +115,10 @@ struct WidgetRegisterInfo struct LocalizedIcon : public ConfigParserData::Icon { LocalizedIcon(const ConfigParserData::Icon& icon, - const LocaleSet& _availableLocales) : + const LocaleSet& _availableLocales) : ConfigParserData::Icon(icon), availableLocales(_availableLocales) - { - } + {} LocaleSet availableLocales; }; @@ -161,8 +160,7 @@ struct WidgetRegisterInfo isTestWidget(0), configInfo(), packagingType(PKG_TYPE_UNKNOWN) - { - } + {} WidgetType webAppType; WidgetType type; // TODO : This type will be removed. @@ -203,7 +201,7 @@ class IWacSecurity virtual bool isWacSigned() const = 0; virtual void getCertificateChainList(CertificateChainList& list, - CertificateSource source) const = 0; + CertificateSource source) const = 0; }; /** @@ -312,7 +310,8 @@ class WidgetDAOReadOnly * * @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. + * @exception WRT_CONF_ERR_EMDB_NO_RECORD - Can not find matching records in + * DB table. */ DbWidgetHandle getHandle() const; static DbWidgetHandle getHandle(const WidgetGUID GUID); @@ -323,7 +322,8 @@ class WidgetDAOReadOnly * * @return tzAppid; * @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. + * @exception WRT_CONF_ERR_EMDB_NO_RECORD - Can not find matching records in + * DB table. */ TizenAppId getTzAppId() const; @@ -336,7 +336,8 @@ class WidgetDAOReadOnly * * @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. + * @exception WRT_CONF_ERR_EMDB_NO_RECORD - Can not find matching records in + * DB table. */ WidgetPkgName getPkgName() const; @@ -373,7 +374,7 @@ class WidgetDAOReadOnly * @return WidgetType * @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. + * records in DB table. */ WidgetType getWidgetType() const; @@ -387,14 +388,14 @@ class WidgetDAOReadOnly */ WidgetGUID getGUID() const; - /** - * This method returns the App id of the widget. - * - * @return appid - * @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 App id of the widget. + * + * @return appid + * @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 getTizenAppId() const; /** @@ -514,8 +515,8 @@ class WidgetDAOReadOnly * DB table. */ WidgetCertificateCNList getKeyCommonNameList( - WidgetCertificateData::Owner owner, - WidgetCertificateData::Type type) const; + WidgetCertificateData::Owner owner, + WidgetCertificateData::Type type) const; /** * given a certificate owner (author / distributor) and type of certificate @@ -523,8 +524,8 @@ class WidgetDAOReadOnly * function returns list of matching fingerprints */ FingerPrintList getKeyFingerprints( - WidgetCertificateData::Owner owner, - WidgetCertificateData::Type type) const; + WidgetCertificateData::Owner owner, + WidgetCertificateData::Type type) const; /* * This method gets certificate data list for a widget from database. @@ -609,7 +610,7 @@ class WidgetDAOReadOnly */ static DbWidgetDAOReadOnlyList getWidgetList(); - /** + /** * This method removes a widget's information from EmDB. * * @see RegisterWidget() @@ -701,12 +702,12 @@ class WidgetDAOReadOnly /* This method gets the parameter list for resource. */ ResourceAttributeList getResourceAttribute( - const std::string &resourceId) const; + const std::string &resourceId) const; /* This method checks read only flag for given property */ DPL::OptionalInt checkPropertyReadFlag( - const PropertyDAOReadOnly::WidgetPropertyKey &key) const; + const PropertyDAOReadOnly::WidgetPropertyKey &key) const; /* This method gets widget property key list */ @@ -719,13 +720,11 @@ class WidgetDAOReadOnly /* This method get widget property value */ PropertyDAOReadOnly::WidgetPropertyValue getPropertyValue( - const PropertyDAOReadOnly::WidgetPropertyKey &key) const; + const PropertyDAOReadOnly::WidgetPropertyKey &key) const; LanguageTagList getLanguageTags() const; LanguageTagList getIconLanguageTags() const; - - WidgetLocalizedInfo getLocalizedInfo(const DPL::String& languageTag) const; std::string getCookieDatabasePath() const; // Local storage @@ -749,7 +748,7 @@ class WidgetDAOReadOnly * wrt-installer and wrt. */ CertificateChainList getWidgetCertificate( - CertificateSource source = SIGNATURE_DISTRIBUTOR) const; + CertificateSource source = SIGNATURE_DISTRIBUTOR) const; void getWidgetSettings(WidgetSettings& outWidgetSettings) const; @@ -760,7 +759,7 @@ class WidgetDAOReadOnly * @exception WRT_CONF_ERR_EMDB_FAILURE - Fail to query DB table. */ void getAppServiceList( - WidgetApplicationServiceList& outAppServiceList) const; + WidgetApplicationServiceList& outAppServiceList) const; /** * This method returns the type of the package. @@ -768,7 +767,7 @@ class WidgetDAOReadOnly * @return PackagingType * @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. + * records in DB table. */ PackagingType getPackagingType() const; @@ -784,13 +783,15 @@ class WidgetDAOReadOnly /** * @brief generateTizenId generates new package id * - * If widget do not supplies it's own tizen package id, this method can be used, + * If widget do not supplies it's own tizen package id, this method can be + * used, * although it should be removed in future. * * @return new tizen package id */ static TizenPkgId generatePkgId(); - static TizenPkgId generateTizenId() { + static TizenPkgId generateTizenId() + { return generatePkgId(); } @@ -823,7 +824,6 @@ class WidgetDAOReadOnly */ TizenPkgId getTizenPkgId() const; }; - } // namespace WrtDB #endif // _WRT_SRC_CONFIGURATION_WIDGET_DAO_READ_ONLY_H_ diff --git a/modules/widget_dao/include/dpl/wrt-dao-rw/feature_dao.h b/modules/widget_dao/include/dpl/wrt-dao-rw/feature_dao.h old mode 100755 new mode 100644 index c525e86..6ee312a --- a/modules/widget_dao/include/dpl/wrt-dao-rw/feature_dao.h +++ b/modules/widget_dao/include/dpl/wrt-dao-rw/feature_dao.h @@ -29,9 +29,9 @@ namespace WrtDB { namespace FeatureDAO { - FeatureHandle RegisterFeature(const PluginMetafileData::Feature &feature, - const DbPluginHandle pluginHandle); - void UnregisterFeature(FeatureHandle featureHandle); +FeatureHandle RegisterFeature(const PluginMetafileData::Feature &feature, + const DbPluginHandle pluginHandle); +void UnregisterFeature(FeatureHandle featureHandle); } // namespace FeatureDB } // namespace WrtDB diff --git a/modules/widget_dao/include/dpl/wrt-dao-rw/global_dao.h b/modules/widget_dao/include/dpl/wrt-dao-rw/global_dao.h index b624d21..21b66fe 100644 --- a/modules/widget_dao/include/dpl/wrt-dao-rw/global_dao.h +++ b/modules/widget_dao/include/dpl/wrt-dao-rw/global_dao.h @@ -26,7 +26,6 @@ #include namespace WrtDB { - class GlobalDAO : public GlobalDAOReadOnly { public: @@ -60,10 +59,8 @@ class GlobalDAO : public GlobalDAOReadOnly private: GlobalDAO() - { - } + {} }; - } // namespace WrtDB #endif /* WRT_SRC_CONFIGURATION_GLOBAL_DAO_H_ */ diff --git a/modules/widget_dao/include/dpl/wrt-dao-rw/plugin_dao.h b/modules/widget_dao/include/dpl/wrt-dao-rw/plugin_dao.h index 70d35f9..0b53eef 100644 --- a/modules/widget_dao/include/dpl/wrt-dao-rw/plugin_dao.h +++ b/modules/widget_dao/include/dpl/wrt-dao-rw/plugin_dao.h @@ -28,7 +28,6 @@ #include namespace WrtDB { - class PluginDAO : public PluginDAOReadOnly { public: @@ -36,28 +35,27 @@ class PluginDAO : public PluginDAOReadOnly PluginDAO(const std::string &libraryName); static DbPluginHandle registerPlugin( - const PluginMetafileData& metafile, - const std::string& pluginPath); + const PluginMetafileData& metafile, + const std::string& pluginPath); static void registerPluginImplementedObject( - const std::string& objectName, - DbPluginHandle pluginHandle); + const std::string& objectName, + DbPluginHandle pluginHandle); static void registerPluginRequiredObject( - const std::string& objectName, - DbPluginHandle pluginHandle); + const std::string& objectName, + DbPluginHandle pluginHandle); static void registerPluginLibrariesDependencies( - DbPluginHandle plugin, - const PluginHandleSetPtr& dependencies); + DbPluginHandle plugin, + const PluginHandleSetPtr& dependencies); static void setPluginInstallationStatus( - DbPluginHandle, - PluginInstallationState); + DbPluginHandle, + PluginInstallationState); static void unregisterPlugin(DbPluginHandle pluginHandle); }; - } // namespace WrtDB #endif /* WRT_SRC_CONFIGURATION_PLUGIN_DAO_H_ */ 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 318dfe5..faecc0d 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 @@ -26,11 +26,9 @@ #include namespace WrtDB { - struct WidgetRegisterInfo; //forward declaration namespace PropertyDAO { - void RemoveProperty(TizenAppId tzAppid, const PropertyDAOReadOnly::WidgetPropertyKey &key); @@ -41,7 +39,7 @@ void SetProperty(DbWidgetHandle widgetHandle, const PropertyDAOReadOnly::WidgetPropertyKey &key, const PropertyDAOReadOnly::WidgetPropertyValue &value, bool readOnly = false) - __attribute__((deprecated)); +__attribute__((deprecated)); /* This method sets widget property */ @@ -55,7 +53,6 @@ void SetProperty(TizenAppId tzAppid, */ void RegisterProperties(TizenAppId tzAppid, const WidgetRegisterInfo ®Info); - } // namespace PropertyDAO } // namespace WrtDB 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 4dda147..5f059db 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 @@ -38,7 +38,6 @@ #include namespace WrtDB { - class WidgetDAO : public WidgetDAOReadOnly { public: @@ -54,25 +53,28 @@ class WidgetDAO : public WidgetDAOReadOnly virtual ~WidgetDAO(); /** - * This method registers the widget information in the DB when it is installed. + * This method registers the widget information in the DB when it is + * installed. * * @see WidgetRegisterInfo * @see UnRegisterWidget() * @param[in] TizenAppId Widget app id that will be registered. - * @param[in] pWidgetRegisterInfo Specified the widget's information needed to be registered. + * @param[in] pWidgetRegisterInfo Specified the widget's information + * needed to be registered. * @param[in] wacSecurity Widget's security certificates. */ static void registerWidget( - const TizenAppId& tzAppId, - const WidgetRegisterInfo &widgetRegInfo, - const IWacSecurity &wacSecurity); + const TizenAppId& tzAppId, + const WidgetRegisterInfo &widgetRegInfo, + const IWacSecurity &wacSecurity); static DbWidgetHandle registerWidget( - const WidgetRegisterInfo &pWidgetRegisterInfo, - const IWacSecurity &wacSecurity) __attribute__((deprecated)); + const WidgetRegisterInfo &pWidgetRegisterInfo, + const IWacSecurity &wacSecurity) __attribute__((deprecated)); /** - * @brief registerWidgetGenerateTizenId Registers widget with auto-generated tizen id + * @brief registerWidgetGenerateTizenId Registers widget with auto-generated + * tizen id * * This function is disadviced and should be used only in tests. * Function is not thread-safe. @@ -82,23 +84,26 @@ class WidgetDAO : public WidgetDAOReadOnly * @return tzAppId generated */ static TizenAppId registerWidgetGeneratePkgId( - const WidgetRegisterInfo &pWidgetRegisterInfo, - const IWacSecurity &wacSecurity); + const WidgetRegisterInfo &pWidgetRegisterInfo, + const IWacSecurity &wacSecurity); /** - * This method re-registers the widget information to the DB when it is installed. + * This method re-registers the widget information to the DB when it is + * installed. * - * It performs unregistration and new registration of widget in db in one transaction. + * It performs unregistration and new registration of widget in db in one + * transaction. * * @see WidgetRegisterInfo * @param[in] tzAppId Widget tizen app id that will be registered. - * @param[in] pWidgetRegisterInfo Specified the widget's information needed to be registered. + * @param[in] pWidgetRegisterInfo Specified the widget's information + * needed to be registered. * @param[in] wacSecurity Widget's security certificates. */ static void registerOrUpdateWidget( - const TizenAppId & tzAppId, - const WidgetRegisterInfo &widgetRegInfo, - const IWacSecurity &wacSecurity); + const TizenAppId & tzAppId, + const WidgetRegisterInfo &widgetRegInfo, + const IWacSecurity &wacSecurity); /** * This method removes a widget's information from EmDB. @@ -108,22 +113,24 @@ class WidgetDAO : public WidgetDAOReadOnly */ static void unregisterWidget(const TizenAppId & tzAppId); - static void unregisterWidget(WrtDB::DbWidgetHandle handle) __attribute__((deprecated)); + static void unregisterWidget(WrtDB::DbWidgetHandle handle) __attribute__(( + deprecated)); /* This method removes widget property */ void removeProperty(const PropertyDAOReadOnly::WidgetPropertyKey &key); /** - * @brief registerExternalLocations Removes rows from WidgetExternalLocations + * @brief registerExternalLocations Removes rows from + * WidgetExternalLocations */ void unregisterAllExternalLocations(); /* This method sets widget property */ void setProperty(const PropertyDAOReadOnly::WidgetPropertyKey &key, - const PropertyDAOReadOnly::WidgetPropertyValue &value, - bool readOnly = false); + const PropertyDAOReadOnly::WidgetPropertyValue &value, + bool readOnly = false); /* set tzAppId */ @@ -135,9 +142,9 @@ class WidgetDAO : public WidgetDAOReadOnly */ void updateFeatureRejectStatus(const DbWidgetFeature &widgetFeature); - /* - * This method change security settings value - */ + /* + * This method change security settings value + */ void setSecurityPopupUsage(const SettingsType value); void setGeolocationUsage(const SettingsType value); void setWebNotificationUsage(const SettingsType value); @@ -147,71 +154,74 @@ class WidgetDAO : public WidgetDAOReadOnly private: //Methods used during widget registering static DbWidgetHandle registerWidgetInfo( - const TizenAppId & widgetName, - const WidgetRegisterInfo ®Info, - const IWacSecurity &wacSecurity, - const DPL::Optional handle = DPL::Optional()); + const TizenAppId & widgetName, + const WidgetRegisterInfo ®Info, + const IWacSecurity &wacSecurity, + const DPL::Optional handle = + DPL::Optional()); static void registerWidgetExtendedInfo( - DbWidgetHandle widgetHandle, - const WidgetRegisterInfo ®Info); + DbWidgetHandle widgetHandle, + const WidgetRegisterInfo ®Info); static void registerWidgetLocalizedInfo( - DbWidgetHandle widgetHandle, - const WidgetRegisterInfo ®Info); + DbWidgetHandle widgetHandle, + const WidgetRegisterInfo ®Info); static void registerWidgetIcons( - DbWidgetHandle widgetHandle, - const WidgetRegisterInfo ®Info); + DbWidgetHandle widgetHandle, + const WidgetRegisterInfo ®Info); static void registerWidgetStartFile( - DbWidgetHandle widgetHandle, - const WidgetRegisterInfo ®Info); + DbWidgetHandle widgetHandle, + const WidgetRegisterInfo ®Info); static void registerWidgetPreferences( - DbWidgetHandle widgetHandle, - const WidgetRegisterInfo ®Info); + DbWidgetHandle widgetHandle, + const WidgetRegisterInfo ®Info); static void registerWidgetFeatures( - DbWidgetHandle widgetHandle, - const WidgetRegisterInfo ®Info); + DbWidgetHandle widgetHandle, + const WidgetRegisterInfo ®Info); static void registerWidgetPrivilege( - DbWidgetHandle widgetHandle, - const WidgetRegisterInfo ®Info); + DbWidgetHandle widgetHandle, + const WidgetRegisterInfo ®Info); static void registerWidgetWindowModes( - DbWidgetHandle widgetHandle, - const WidgetRegisterInfo ®Info); + DbWidgetHandle widgetHandle, + const WidgetRegisterInfo ®Info); static void registerWidgetWarpInfo( - DbWidgetHandle widgetHandle, - const WidgetRegisterInfo ®Info); + DbWidgetHandle widgetHandle, + const WidgetRegisterInfo ®Info); static void registerWidgetCertificates( - DbWidgetHandle widgetHandle, - const IWacSecurity &wacSecurity); + DbWidgetHandle widgetHandle, + const IWacSecurity &wacSecurity); static void registerCertificatesChains( - DbWidgetHandle widgetHandle, - CertificateSource certificateSource, - const CertificateChainList &list); + DbWidgetHandle widgetHandle, + CertificateSource certificateSource, + const CertificateChainList &list); static void registerWidgetSettings( - DbWidgetHandle widgetHandle, - const WidgetRegisterInfo ®Info); + DbWidgetHandle widgetHandle, + const WidgetRegisterInfo ®Info); static void registerAppService( - DbWidgetHandle widgetHandle, - const WidgetRegisterInfo ®Info); + DbWidgetHandle widgetHandle, + const WidgetRegisterInfo ®Info); static void registerEncryptedResouceInfo( - DbWidgetHandle widgetHandle, - const WidgetRegisterInfo ®Info); + DbWidgetHandle widgetHandle, + const WidgetRegisterInfo ®Info); /** - * @brief registerExternalLocations Inserts new rows to WidgetExternalLocations + * @brief registerExternalLocations Inserts new rows to + * WidgetExternalLocations * @param externals list of files */ - static void registerExternalLocations(DbWidgetHandle widgetHandle, - const ExternalLocationList & externals); + static void registerExternalLocations( + DbWidgetHandle widgetHandle, + const ExternalLocationList & + externals); static void registerWidgetSecuritySettings(DbWidgetHandle widgetHandle); - static void registerWidgetInternal( - const TizenAppId & tzAppId, - const WidgetRegisterInfo &widgetRegInfo, - const IWacSecurity &wacSecurity, - const DPL::Optional handle = DPL::Optional()); + const TizenAppId & tzAppId, + const WidgetRegisterInfo &widgetRegInfo, + const IWacSecurity &wacSecurity, + const DPL::Optional handle = + DPL::Optional()); static void unregisterWidgetInternal( - const TizenAppId & tzAppId); + const TizenAppId & tzAppId); }; - } // namespace WrtDB #endif // WIDGET_DAO_H diff --git a/modules/widget_dao/orm/wrt_db_sql_generator.h b/modules/widget_dao/orm/wrt_db_sql_generator.h index a4d7da8..1b69679 100644 --- a/modules/widget_dao/orm/wrt_db_sql_generator.h +++ b/modules/widget_dao/orm/wrt_db_sql_generator.h @@ -17,7 +17,8 @@ * @file wrt_db_sql_generator.h * @author Bartosz Janiak (b.janiak@samsung.com) * @version 1.0 - * @brief Macro definitions for generating the SQL input file from database definition. + * @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. diff --git a/tests/common/include/loop_control.h b/tests/common/include/loop_control.h index 30aa6e8..b58fb5c 100644 --- a/tests/common/include/loop_control.h +++ b/tests/common/include/loop_control.h @@ -20,13 +20,10 @@ * @brief This file is the definitions of loop controlling utilities */ - #ifndef LOOP_CONTROL_H_ #define LOOP_CONTROL_H_ -namespace LoopControl -{ - +namespace LoopControl { void init_loop(int argc, char *argv[]); void wait_for_wrt_init(); void finish_wait_for_wrt_init(); @@ -36,7 +33,6 @@ 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 index eed375c..2eb85cb 100644 --- a/tests/common/src/loop_control.cpp +++ b/tests/common/src/loop_control.cpp @@ -28,9 +28,7 @@ #include #include - -namespace LoopControl -{ +namespace LoopControl { void init_loop(int argc, char *argv[]) { (void)argc; @@ -71,5 +69,4 @@ void *abstract_window() { return elm_win_add(NULL, "hello", ELM_WIN_BASIC); } - -}//end of LoopControl namespace +} //end of LoopControl namespace diff --git a/tests/dao/TestCases_CustomHandlerDAO.cpp b/tests/dao/TestCases_CustomHandlerDAO.cpp index fb1a465..97a4c9a 100644 --- a/tests/dao/TestCases_CustomHandlerDAO.cpp +++ b/tests/dao/TestCases_CustomHandlerDAO.cpp @@ -14,7 +14,7 @@ * limitations under the License. */ /** - * @file TestCases_CustomHandlerDAO.cpp + * @file TestCases_CustomHandlerDAO.cpp * @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) * @version 1.0 * @brief This file contains tests for custom handler dao class. @@ -29,8 +29,7 @@ using namespace CustomHandlerDB; RUNNER_TEST_GROUP_INIT(DAO) -namespace -{ +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"); @@ -41,7 +40,9 @@ 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) +void checkHandlersExistence(CustomHandlerDAOReadOnly& dao, + bool protocol, + bool content) { CustomHandlerDB::CustomHandlerPtr handler; handler = dao.getProtocolHandler(P_TARGET, P_URL); @@ -49,7 +50,6 @@ void checkHandlersExistence(CustomHandlerDAOReadOnly& dao, bool protocol, bool c handler = dao.getContentHandler(C_TARGET, C_URL); RUNNER_ASSERT_MSG((!!handler) == content, "Content handler check"); } - } // namespace RUNNER_TEST(custom_handler_empty_db_read) @@ -57,7 +57,6 @@ RUNNER_TEST(custom_handler_empty_db_read) CustomHandlerDAOReadOnly dao(DPL::String(L"test")); } - RUNNER_TEST(custom_handlers) { CustomHandlerDAOReadOnly dao_ro(L"test"); @@ -72,11 +71,11 @@ RUNNER_TEST(custom_handlers) p_handler.user_decision = Agreed; // initial check - checkHandlersExistence(dao_ro,false,false); + checkHandlersExistence(dao_ro, false, false); // Protocol handler registration dao_rw.registerProtocolHandler(p_handler); - checkHandlersExistence(dao_ro,true,false); + checkHandlersExistence(dao_ro, true, false); handler = dao_ro.getProtocolHandler(P_TARGET, P_URL); RUNNER_ASSERT(handler); @@ -86,7 +85,6 @@ RUNNER_TEST(custom_handlers) RUNNER_ASSERT(handler->title == P_TITLE); RUNNER_ASSERT(handler->user_decision == Agreed); - // Content handler registration CustomHandlerDB::CustomHandler c_handler; c_handler.target = C_TARGET; @@ -96,7 +94,7 @@ RUNNER_TEST(custom_handlers) c_handler.user_decision = DeclinedPermanently; dao_rw.registerContentHandler(c_handler); - checkHandlersExistence(dao_ro,true,true); + checkHandlersExistence(dao_ro, true, true); handler = dao_ro.getContentHandler(C_TARGET, C_URL); RUNNER_ASSERT(handler); @@ -108,13 +106,13 @@ RUNNER_TEST(custom_handlers) // Handler unregistration dao_rw.unregisterProtocolHandler(P_TARGET, P_URL); - checkHandlersExistence(dao_ro,false,true); + checkHandlersExistence(dao_ro, false, true); // Nonexistent unregistration dao_rw.unregisterContentHandler(L"blah", L"blah"); - checkHandlersExistence(dao_ro,false,true); + checkHandlersExistence(dao_ro, false, true); // Cleanup dao_rw.unregisterContentHandler(C_TARGET, C_URL); - checkHandlersExistence(dao_ro,false,false); + checkHandlersExistence(dao_ro, false, false); } diff --git a/tests/dao/TestCases_FeatureDAO.cpp b/tests/dao/TestCases_FeatureDAO.cpp index 26ea2bd..4f03a5a 100644 --- a/tests/dao/TestCases_FeatureDAO.cpp +++ b/tests/dao/TestCases_FeatureDAO.cpp @@ -14,7 +14,7 @@ * limitations under the License. */ /** - * @file TestCases_FeatureDAO.cpp + * @file TestCases_FeatureDAO.cpp * @author Pawel Sikorski (p.sikorski@samsung.com) * @version 1.0 * @brief This file contains tests for feature dao class. @@ -29,16 +29,16 @@ using namespace WrtDB; #define RUNNER_ASSERT_WHAT_EQUALS(in, test) \ - {std::string tmp(in); \ - RUNNER_ASSERT_MSG(tmp == test, "Equals: [" + tmp + "]");} + { 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 -*/ + * 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; @@ -47,7 +47,7 @@ RUNNER_TEST(feature_dao_test_register_features) std::string libraryName("nfp1"); PluginMetafileData pluginData; - pluginData.m_libraryName = libraryName; + pluginData.m_libraryName = libraryName; plHandle = PluginDAO::registerPlugin(pluginData, libraryPath); RUNNER_ASSERT(PluginDAO::isPluginInstalled(libraryName) == true); @@ -56,14 +56,14 @@ RUNNER_TEST(feature_dao_test_register_features) PluginMetafileData::Feature f; f.m_name = std::string("new_f1"); - FeatureHandle handle = FeatureDAO::RegisterFeature(f,plHandle); + 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"); + RUNNER_ASSERT_WHAT_EQUALS(dao.GetName(), "new_f1"); plHandle = dao.GetPluginHandle(); } @@ -73,7 +73,7 @@ RUNNER_TEST(feature_dao_test_register_features) PluginMetafileData::Feature f; f.m_name = std::string("new_f2"); - FeatureHandle handle = FeatureDAO::RegisterFeature(f,plHandle); + 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"); @@ -86,10 +86,11 @@ RUNNER_TEST(feature_dao_test_register_features) } /* -Name: feature_dao_test_get_feature_properties -Description: Checks properties of inserted features -Expected: properties of features should match values inserted to database directly -*/ + * 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) { { @@ -115,12 +116,12 @@ RUNNER_TEST(feature_dao_test_get_feature_properties) } /* -Name: feature_dao_test_feature_constructor_name -Description: - -Expected: - - -TODO: test -*/ + * Name: feature_dao_test_feature_constructor_name + * Description: - + * Expected: - + * + * TODO: test + */ RUNNER_TEST(feature_dao_test_feature_constructor_name) { std::list preinstalled; @@ -139,10 +140,10 @@ RUNNER_TEST(feature_dao_test_feature_constructor_name) } /* -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 -*/ + * 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(); @@ -150,10 +151,10 @@ RUNNER_TEST(feature_dao_test_feature_handle_list) } /* -Name: feature_dao_test_is_feature_installed -Description: Checks if installed features are showed correctly. -Expected: correct installed features should be present -*/ + * 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 @@ -165,31 +166,33 @@ RUNNER_TEST(feature_dao_test_is_feature_installed) preinstalled.push_back("feature4"); FOREACH(it, preinstalled) - RUNNER_ASSERT(FeatureDAOReadOnly::isFeatureInstalled(*it)); + RUNNER_ASSERT(FeatureDAOReadOnly::isFeatureInstalled(*it)); } //not installed { - RUNNER_ASSERT(FeatureDAOReadOnly::isFeatureInstalled("not_installed1")==false); - RUNNER_ASSERT(FeatureDAOReadOnly::isFeatureInstalled("plugin1") == false); + 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 -*/ + * 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 + { //check deviceCaps Feature f; f.setName("new_dev_f4"); f.setLibraryName("new_dev_f4 lib_name"); @@ -199,14 +202,14 @@ RUNNER_TEST(feature_dao_test_get_device_capab) devList.insert("new_dev_f4 devcap2"); FOREACH(it, devList) - f.addDeviceCapability(*it); + f.addDeviceCapability(*it); - FeatureHandle handle = FeatureDAO::RegisterFeature(f,"new_dev_f4 path"); + FeatureHandle handle = FeatureDAO::RegisterFeature(f, "new_dev_f4 path"); FeatureDAOReadOnly dao(handle); FeatureDAOReadOnly::DeviceCapabilitiesList gotList = - dao.GetDeviceCapabilities(); + dao.GetDeviceCapabilities(); RUNNER_ASSERT_MSG(gotList.size() == devList.size(), "deviceCaps wrong"); } @@ -214,10 +217,11 @@ RUNNER_TEST(feature_dao_test_get_device_capab) } /* -Name: feature_dao_test_is_device_capab_installed -Description: Checks if FeatureDAOReadOnly::isDeviceCapabilityInstalled works correctly. -Expected: correct capabilities should be present -*/ + * 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 @@ -228,7 +232,7 @@ RUNNER_TEST(feature_dao_test_is_device_capab_installed) preinstalled.push_back("devicecap4"); FOREACH(it, preinstalled) - RUNNER_ASSERT(FeatureDAOReadOnly::isDeviceCapabilityInstalled(*it)); + RUNNER_ASSERT(FeatureDAOReadOnly::isDeviceCapabilityInstalled(*it)); //not installed std::list notinstalled; @@ -238,7 +242,7 @@ RUNNER_TEST(feature_dao_test_is_device_capab_installed) notinstalled.push_back("ff"); FOREACH(it, notinstalled) - RUNNER_ASSERT(!FeatureDAOReadOnly::isDeviceCapabilityInstalled(*it)); + RUNNER_ASSERT(!FeatureDAOReadOnly::isDeviceCapabilityInstalled(*it)); } #undef RUNNER_ASSERT_WHAT_EQUALS diff --git a/tests/dao/TestCases_GlobalDAO.cpp b/tests/dao/TestCases_GlobalDAO.cpp index 0098eee..65cb9e0 100644 --- a/tests/dao/TestCases_GlobalDAO.cpp +++ b/tests/dao/TestCases_GlobalDAO.cpp @@ -14,7 +14,7 @@ * limitations under the License. */ /** - * @file TestCases_GlobalDAO.cpp + * @file TestCases_GlobalDAO.cpp * @author Pawel Sikorski (p.sikorski@samsung.com) * @version 1.0 * @brief This file contains tests for global dao class. @@ -32,19 +32,17 @@ using namespace WrtDB; - -namespace -{ +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 -*/ + * 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(); @@ -57,55 +55,55 @@ RUNNER_TEST(global_dao_developer_mode) } /* -Name: home_network_data_usage -Description: tests if HomeNetworkDataUsage is correctly set and get -Expected: received developer shoudl match the one was set -*/ + * 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::GetHomeNetworkDataUsage(); GlobalDAO::SetHomeNetworkDataUsage(GlobalDAO::CONNECT_AUTOMATICALLY); RUNNER_ASSERT_MSG(GlobalDAO::CONNECT_AUTOMATICALLY == - GlobalDAO::GetHomeNetworkDataUsage(), "Value not updated"); + GlobalDAO::GetHomeNetworkDataUsage(), "Value not updated"); GlobalDAO::SetHomeNetworkDataUsage(GlobalDAO::ALWAYS_ASK); RUNNER_ASSERT_MSG(GlobalDAO::ALWAYS_ASK == - GlobalDAO::GetHomeNetworkDataUsage(), "Value not updated"); + GlobalDAO::GetHomeNetworkDataUsage(), "Value not updated"); GlobalDAO::SetHomeNetworkDataUsage(GlobalDAO::NEVER_CONNECT); RUNNER_ASSERT_MSG(GlobalDAO::NEVER_CONNECT == - GlobalDAO::GetHomeNetworkDataUsage(), "Value not updated"); + GlobalDAO::GetHomeNetworkDataUsage(), "Value not updated"); GlobalDAO::SetHomeNetworkDataUsage(original); RUNNER_ASSERT_MSG(original == GlobalDAO::GetHomeNetworkDataUsage(), - "Value not updated"); + "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 -*/ + * 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::GetRoamingDataUsage(); GlobalDAO::SetRoamingDataUsage(GlobalDAO::CONNECT_AUTOMATICALLY); RUNNER_ASSERT_MSG(GlobalDAO::CONNECT_AUTOMATICALLY == - GlobalDAO::GetRoamingDataUsage(), "Value not updated"); + GlobalDAO::GetRoamingDataUsage(), "Value not updated"); GlobalDAO::SetRoamingDataUsage(GlobalDAO::ALWAYS_ASK); RUNNER_ASSERT_MSG(GlobalDAO::ALWAYS_ASK == - GlobalDAO::GetRoamingDataUsage(), "Value not updated"); + GlobalDAO::GetRoamingDataUsage(), "Value not updated"); GlobalDAO::SetRoamingDataUsage(GlobalDAO::NEVER_CONNECT); RUNNER_ASSERT_MSG(GlobalDAO::NEVER_CONNECT == - GlobalDAO::GetRoamingDataUsage(), "Value not updated"); + GlobalDAO::GetRoamingDataUsage(), "Value not updated"); GlobalDAO::SetRoamingDataUsage(original); RUNNER_ASSERT_MSG(original == GlobalDAO::GetRoamingDataUsage(), - "Value not updated"); + "Value not updated"); } diff --git a/tests/dao/TestCases_PluginDAO.cpp b/tests/dao/TestCases_PluginDAO.cpp index d737752..6309ad0 100644 --- a/tests/dao/TestCases_PluginDAO.cpp +++ b/tests/dao/TestCases_PluginDAO.cpp @@ -14,7 +14,7 @@ * limitations under the License. */ /** - * @file TestCases_PluginDAO.cpp + * @file TestCases_PluginDAO.cpp * @author Pawel Sikorski (p.sikorski@samsung.com) * @version 1.0 * @brief This file contains tests for feature dao class. @@ -32,16 +32,16 @@ using namespace WrtDB; #define RUNNER_ASSERT_WHAT_EQUALS(in, test) \ - {std::string tmp(in); \ - RUNNER_ASSERT_MSG(tmp == test, "Equals: [" + tmp + "]");} + { 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 -*/ + * 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) { { @@ -49,10 +49,13 @@ RUNNER_TEST(plugin_dao_test_register_plugins) std::string libraryName("np1"); PluginMetafileData pluginData; - pluginData.m_libraryName = libraryName; + pluginData.m_libraryName = libraryName; PluginHandle handle = PluginDAO::registerPlugin(pluginData, libraryPath); - PluginDAO::setPluginInstallationStatus(handle,PluginDAO::INSTALLATION_COMPLETED); + PluginDAO::setPluginInstallationStatus( + handle, + PluginDAO:: + INSTALLATION_COMPLETED); RUNNER_ASSERT(PluginDAO::isPluginInstalled(libraryName) == true); PluginDAO dao(handle); @@ -65,10 +68,13 @@ RUNNER_TEST(plugin_dao_test_register_plugins) std::string libraryName("np2"); PluginMetafileData pluginData; - pluginData.m_libraryName = libraryName; + pluginData.m_libraryName = libraryName; PluginHandle handle = PluginDAO::registerPlugin(pluginData, ""); - PluginDAO::setPluginInstallationStatus(handle,PluginDAO::INSTALLATION_COMPLETED); + PluginDAO::setPluginInstallationStatus( + handle, + PluginDAO:: + INSTALLATION_COMPLETED); RUNNER_ASSERT(PluginDAO::isPluginInstalled(libraryName) == true); PluginDAO dao(handle); @@ -77,11 +83,11 @@ RUNNER_TEST(plugin_dao_test_register_plugins) } /* -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 -*/ + * 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) { { @@ -89,7 +95,7 @@ RUNNER_TEST(plugin_dao_test_register_plugin_implemented_object) std::string libraryName("np3"); PluginMetafileData pluginData; - pluginData.m_libraryName = libraryName; + pluginData.m_libraryName = libraryName; PluginHandle handle = PluginDAO::registerPlugin(pluginData, libraryPath); @@ -110,10 +116,10 @@ RUNNER_TEST(plugin_dao_test_register_plugin_implemented_object) } /* -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 -*/ + * 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) { { @@ -121,14 +127,17 @@ RUNNER_TEST(plugin_dao_test_register_library_dependencies) std::string libraryName("np4"); PluginMetafileData pluginData; - pluginData.m_libraryName = libraryName; + pluginData.m_libraryName = libraryName; PluginHandle handle = PluginDAO::registerPlugin(pluginData, libraryPath); - PluginDAO::setPluginInstallationStatus(handle,PluginDAO::INSTALLATION_COMPLETED); + PluginDAO::setPluginInstallationStatus( + handle, + PluginDAO:: + INSTALLATION_COMPLETED); RUNNER_ASSERT(PluginDAO::isPluginInstalled(libraryName) == true); - PluginHandle depHandles[] = {117, 119}; + PluginHandle depHandles[] = { 117, 119 }; PluginHandleSetPtr dependencies(new PluginHandleSet); dependencies->insert(depHandles[1]); @@ -141,7 +150,8 @@ RUNNER_TEST(plugin_dao_test_register_library_dependencies) retDependencies = dao.getLibraryDependencies(); RUNNER_ASSERT( - retDependencies->size()==sizeof(depHandles)/sizeof(depHandles[0])); + retDependencies->size() == sizeof(depHandles) / + sizeof(depHandles[0])); RUNNER_ASSERT( retDependencies->find(depHandles[1]) != retDependencies->end()); RUNNER_ASSERT( @@ -150,10 +160,11 @@ RUNNER_TEST(plugin_dao_test_register_library_dependencies) } /* -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 -*/ + * 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) { { @@ -161,15 +172,18 @@ RUNNER_TEST(plugin_dao_test_register_required_object) std::string libraryName("np5"); PluginMetafileData pluginData; - pluginData.m_libraryName = libraryName; + pluginData.m_libraryName = libraryName; PluginHandle handle = PluginDAO::registerPlugin(pluginData, libraryPath); - PluginDAO::setPluginInstallationStatus(handle,PluginDAO::INSTALLATION_COMPLETED); + PluginDAO::setPluginInstallationStatus( + handle, + PluginDAO:: + INSTALLATION_COMPLETED); RUNNER_ASSERT(PluginDAO::isPluginInstalled(libraryName) == true); - const size_t numObjects =2; - std::string objectReq [numObjects]; + 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); @@ -179,16 +193,16 @@ RUNNER_TEST(plugin_dao_test_register_required_object) PluginDAO::getRequiredObjectsForPluginHandle(handle); RUNNER_ASSERT(objects->size() == numObjects - && objects->find(objectReq[0]) != objects->end() - && objects->find(objectReq[1]) != objects->end()); + && 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 -*/ + * 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) { { @@ -201,15 +215,15 @@ RUNNER_TEST(plugin_dao_test_is_library_installed) preinstalled.push_back("p5"); FOREACH(it, preinstalled) - RUNNER_ASSERT_MSG(PluginDAO::isPluginInstalled(*it), - std::string("Not found: ") + *it); + 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"); + 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, @@ -222,10 +236,10 @@ RUNNER_TEST(plugin_dao_test_is_library_installed) } /* -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 -*/ + * 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(); @@ -233,11 +247,11 @@ RUNNER_TEST(plugin_dao_test_get_plugin_handle_list) } /* -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 -*/ + * 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) { { @@ -270,19 +284,18 @@ RUNNER_TEST(plugin_dao_test_constructor_name) PluginDAO dao(*it); RUNNER_ASSERT_MSG(false, "should not be found"); } - Catch (PluginDAO::Exception::PluginNotExist) { + 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 -*/ + * 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) { { @@ -315,10 +328,10 @@ RUNNER_TEST(plugin_dao_test_get_plugin_properties) } /* -Name: plugin_dao_test_get_implemented_objects_for_plugin_handle_1 -Description: tests receiving from dao Implemented Objects -Expected: returned object is size 0 -*/ + * 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) { { @@ -333,15 +346,14 @@ RUNNER_TEST(plugin_dao_test_get_implemented_objects_for_plugin_handle_1) } /* -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 -*/ + * 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 = - { + std::set< std::string > preinstalled = { "" }; @@ -349,7 +361,8 @@ RUNNER_TEST(plugin_dao_test_get_implemented_objects_for_plugin_handle_2) auto dbHandle = dao.getPluginHandle(); auto objects = dao.getImplementedObjectsForPluginHandle(dbHandle); - //LogError("\n" << objects.size() << " " << preinstalled.size() << "\n"); + //LogError("\n" << objects.size() << " " << preinstalled.size() << + // "\n"); RUNNER_ASSERT(objects.size() == preinstalled.size()); @@ -361,15 +374,14 @@ RUNNER_TEST(plugin_dao_test_get_implemented_objects_for_plugin_handle_2) } /* -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 -*/ + * 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 = - { + std::set< std::string > preinstalled = { "Plugin_3_Object_A" }; @@ -386,15 +398,14 @@ RUNNER_TEST(plugin_dao_test_get_implemented_objects_for_plugin_handle_3) } /* -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 -*/ + * 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 = - { + std::set< std::string > preinstalled = { "Plugin_4_Object_A", "Plugin_4_Object_B", "Plugin_4_Object_C", @@ -413,15 +424,14 @@ RUNNER_TEST(plugin_dao_test_get_implemented_objects_for_plugin_handle_4) } /* -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 -*/ + * 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 = - { + std::set< std::string > preinstalled = { "Plugin_5_Object_B", }; @@ -437,5 +447,4 @@ RUNNER_TEST(plugin_dao_test_get_implemented_objects_for_plugin_handle_5) } } - #undef RUNNER_ASSERT_WHAT_EQUALS diff --git a/tests/dao/TestCases_PropertyDAO.cpp b/tests/dao/TestCases_PropertyDAO.cpp index 0024110..effd898 100644 --- a/tests/dao/TestCases_PropertyDAO.cpp +++ b/tests/dao/TestCases_PropertyDAO.cpp @@ -31,42 +31,45 @@ using namespace WrtDB; using namespace WrtDB::PropertyDAOReadOnly; -// Widgets used "tizenid201", "tizenid202", "tizenid203", 2003(saved by wrt_dao_tests_prepare_db.sh) +// Widgets used "tizenid201", "tizenid202", "tizenid203", 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 + "]");} + { 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);\ - } + { \ + 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 -*/ + * 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 + { //property list std::map prefsMap; prefsMap.insert(std::pair(L"tizenid201", 2)); prefsMap.insert(std::pair(L"tizenid202", 1)); prefsMap.insert(std::pair(L"tizenid203", 2)); - prefsMap.insert(std::pair(L"non_exists", 0)); //no widget + //no widget + prefsMap.insert(std::pair(L"non_exists", 0)); FOREACH(it, prefsMap) { PropertyDAOReadOnly::WidgetPreferenceList prefs = - PropertyDAOReadOnly::GetPropertyList(it->first); + PropertyDAOReadOnly::GetPropertyList(it->first); RUNNER_ASSERT(prefs.size() == it->second); } } - {//property key list + { //property key list WidgetPropertyKeyList orig_2000; orig_2000.push_back(DPL::FromUTF8String("key1_for_2000")); orig_2000.push_back(DPL::FromUTF8String("key2_for_2000")); @@ -80,11 +83,11 @@ RUNNER_TEST(property_dao_get_lists) std::map prefsKeyMap; prefsKeyMap.insert(std::pair( - L"tizenid201", &orig_2000)); + L"tizenid201", &orig_2000)); prefsKeyMap.insert(std::pair( - L"tizenid202", &orig_2001)); + L"tizenid202", &orig_2001)); prefsKeyMap.insert(std::pair( - L"tizenid203", &orig_2002)); + L"tizenid203", &orig_2002)); FOREACH(it_out, prefsKeyMap) { WidgetPropertyKeyList got = PropertyDAOReadOnly::GetPropertyKeyList( @@ -100,13 +103,15 @@ RUNNER_TEST(property_dao_get_lists) } /* -Name: property_dao_set_update_remove -Description: tests set new property for widget, updating property and removing it -Expected: given operation should works -*/ + * 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(L"tizenid201"); + WidgetPropertyKeyList keys = PropertyDAOReadOnly::GetPropertyKeyList( + L"tizenid201"); //ADD PropertyDAO::SetProperty(L"tizenid201", @@ -114,7 +119,8 @@ RUNNER_TEST(property_dao_set_update_remove) DPL::FromUTF8String("new_value1")); RUNNER_ASSERT_MSG( - keys.size() + 1 == PropertyDAOReadOnly::GetPropertyKeyList(L"tizenid201").size(), + keys.size() + 1 == + PropertyDAOReadOnly::GetPropertyKeyList(L"tizenid201").size(), "new property not added"); RUNNER_ASSERT_WHAT_EQUALS_OPTIONAL( PropertyDAOReadOnly::GetPropertyValue(L"tizenid201", @@ -126,7 +132,8 @@ RUNNER_TEST(property_dao_set_update_remove) DPL::FromUTF8String("new_key"), DPL::FromUTF8String("new_value2")); RUNNER_ASSERT_MSG( - keys.size() + 1 == PropertyDAOReadOnly::GetPropertyKeyList(L"tizenid201").size(), + keys.size() + 1 == + PropertyDAOReadOnly::GetPropertyKeyList(L"tizenid201").size(), "new property not added"); RUNNER_ASSERT_WHAT_EQUALS_OPTIONAL( PropertyDAOReadOnly::GetPropertyValue(L"tizenid201", @@ -137,27 +144,27 @@ RUNNER_TEST(property_dao_set_update_remove) PropertyDAO::RemoveProperty(L"tizenid201", DPL::FromUTF8String("new_key")); RUNNER_ASSERT_MSG( - keys.size() == PropertyDAOReadOnly::GetPropertyKeyList(L"tizenid201").size(), + keys.size() == PropertyDAOReadOnly::GetPropertyKeyList( + L"tizenid201").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 -*/ + * 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( - L"tizenid201", DPL::FromUTF8String("key1_for_2000")), - "value_for_key1_2000"); + PropertyDAOReadOnly::GetPropertyValue( + L"tizenid201", DPL::FromUTF8String("key1_for_2000")), + "value_for_key1_2000"); RUNNER_ASSERT_WHAT_EQUALS_OPTIONAL( - PropertyDAOReadOnly::GetPropertyValue( - L"tizenid201", DPL::FromUTF8String("key2_for_2000")), - "value_for_key2_2000"); + PropertyDAOReadOnly::GetPropertyValue( + L"tizenid201", 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 index 2f9533d..26280dd 100644 --- a/tests/dao/TestCases_WidgetDAO.cpp +++ b/tests/dao/TestCases_WidgetDAO.cpp @@ -14,7 +14,7 @@ * limitations under the License. */ /** - * @file TestCases_WidgetDAO.cpp + * @file TestCases_WidgetDAO.cpp * @author Pawel Sikorski (p.sikorski@samsung.com) * @version 1.0 * @brief This file contains tests for widget dao class. @@ -36,42 +36,55 @@ using namespace WrtDB; namespace { - class WacSecurityMock : public WrtDB::IWacSecurity { -public: + 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 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 {} + CertificateSource /*source*/) const {} WrtDB::WidgetCertificateDataList& getCertificateListRef() { return mList; } - void setRecognized(bool recognized) { mRecognized = recognized; } + void setRecognized(bool recognized) + { + mRecognized = recognized; + } void setDistributorSigned(bool distributorSigned) { mDistributorSigned = distributorSigned; } - void setWacSigned(bool wacSigned) { mWacSigned = wacSigned; } + void setWacSigned(bool wacSigned) + { + mWacSigned = wacSigned; + } -private: + private: WrtDB::WidgetCertificateDataList mList; // author signature verified bool mRecognized; @@ -79,12 +92,11 @@ private: bool mDistributorSigned; // distributor is wac bool mWacSigned; - }; TizenAppId _registerWidget(const WidgetRegisterInfo& regInfo, - const IWacSecurity& sec, - int line) + const IWacSecurity& sec, + int line) { TizenAppId tizenAppId; Try { @@ -97,50 +109,53 @@ TizenAppId _registerWidget(const WidgetRegisterInfo& regInfo, "(called from line " << line << ")"); auto current = WidgetDAO::getTizenAppidList(); - RUNNER_ASSERT_MSG(previous.size()+1 == current.size(), + RUNNER_ASSERT_MSG(previous.size() + 1 == current.size(), "(called from line " << line << ")"); - RUNNER_ASSERT_MSG(WidgetDAO::isWidgetInstalled(tizenAppId), - "(called from line " << line << " tizenAppId: " << tizenAppId << ")"); + RUNNER_ASSERT_MSG(WidgetDAO::isWidgetInstalled( + tizenAppId), + "(called from line " << line << " tizenAppId: " << + tizenAppId << ")"); } - Catch (WidgetDAO::Exception::AlreadyRegistered) { + Catch(WidgetDAO::Exception::AlreadyRegistered) { RUNNER_ASSERT_MSG( - false, - "Unexpected exception (called from line " << line << ")"); + false, + "Unexpected exception (called from line " << line << ")"); } return tizenAppId; } -#define REGISTER_WIDGET(regInfo, sec) _registerWidget((regInfo),(sec), __LINE__) - +#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 + "]");} + { 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);\ - } + { \ + 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 + "]"); \ - } + { \ + 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 -*/ + * 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; @@ -171,7 +186,7 @@ RUNNER_TEST(widget_dao_test_register_widget_empty_strings) locData.licenseFile = DPL::FromUTF8String(""); locData.licenseHref = DPL::FromUTF8String(""); regInfo.configInfo.localizedDataSet.insert( - std::make_pair(DPL::FromUTF8String("en"),locData)); + std::make_pair(DPL::FromUTF8String("en"), locData)); //userAgentLoc @@ -181,7 +196,7 @@ RUNNER_TEST(widget_dao_test_register_widget_empty_strings) icon.height = 10; LocaleSet locs; locs.insert(DPL::FromUTF8String("en")); - WidgetRegisterInfo::LocalizedIcon locIcon(icon,locs); + WidgetRegisterInfo::LocalizedIcon locIcon(icon, locs); regInfo.localizationData.icons.push_back(locIcon); //start file @@ -191,16 +206,16 @@ RUNNER_TEST(widget_dao_test_register_widget_empty_strings) WidgetRegisterInfo::LocalizedStartFile file; file.path = DPL::FromUTF8String(""); file.propertiesForLocales.insert( - std::make_pair(DPL::FromUTF8String("en"), prop)); + std::make_pair(DPL::FromUTF8String("en"), prop)); regInfo.localizationData.startFiles.push_back(file); //widget pref - ConfigParserData::Preference pref(DPL::FromUTF8String(""),false); + ConfigParserData::Preference pref(DPL::FromUTF8String(""), false); pref.value = DPL::FromUTF8String(""); regInfo.configInfo.preferencesList.insert(pref); //widget feature - ConfigParserData::Feature feat(DPL::FromUTF8String(""),false); + ConfigParserData::Feature feat(DPL::FromUTF8String(""), false); ConfigParserData::Param par(DPL::FromUTF8String((""))); par.value = DPL::FromUTF8String(""); feat.paramsList.insert(par); @@ -210,7 +225,7 @@ RUNNER_TEST(widget_dao_test_register_widget_empty_strings) regInfo.configInfo.windowModes.insert(DPL::FromUTF8String("")); //WARP info - ConfigParserData::AccessInfo access(DPL::FromUTF8String(""),true); + ConfigParserData::AccessInfo access(DPL::FromUTF8String(""), true); regInfo.configInfo.accessInfoSet.insert(access); //certificates @@ -225,14 +240,15 @@ RUNNER_TEST(widget_dao_test_register_widget_empty_strings) WacSecurityMock security; security.getCertificateListRef().push_back(cert); - REGISTER_WIDGET(regInfo,security); + 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 -*/ + * 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; @@ -244,14 +260,13 @@ RUNNER_TEST(widget_dao_test_twice_install_same_widget) 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 -*/ + * 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; @@ -259,8 +274,7 @@ RUNNER_TEST(widget_dao_test_register_widget_minimum_info) TizenAppId lastTizenAppId; - for (std::size_t number = 0; number < NUMBER_OF_WIDGETS; ++number) - { + for (std::size_t number = 0; number < NUMBER_OF_WIDGETS; ++number) { WidgetRegisterInfo regInfo; TizenAppId tizenAppId = REGISTER_WIDGET(regInfo, sec); @@ -272,17 +286,16 @@ RUNNER_TEST(widget_dao_test_register_widget_minimum_info) } /* -Name: widget_dao_test_register_widget_info -Description: Tests registeration of many widgets -Expected: all widgets should be registered in database -*/ + * 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) - { + for (std::size_t number = 0; number < NUMBER_OF_WIDGETS; ++number) { std::ostringstream str; str << "register_info_test_" << number; @@ -312,62 +325,59 @@ RUNNER_TEST(widget_dao_test_register_widget_info) 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( + // 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 -*/ + * 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) - { + 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.shareHref = str.str(); regInfo.configInfo.backgroundPage = L"background.html"; TizenAppId tizenAppId = REGISTER_WIDGET(regInfo, sec); WidgetDAO dao(tizenAppId); -// RUNNER_ASSERT_WHAT_EQUALS(dao.GetShareHref(), str.str()); + // RUNNER_ASSERT_WHAT_EQUALS(dao.GetShareHref(), str.str()); RUNNER_ASSERT_WHAT_EQUALS_OPTIONAL(dao.getBackgroundPage(), - "background.html"); + "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 -*/ + * 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) - { + 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 + 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()); @@ -376,10 +386,10 @@ RUNNER_TEST(widget_dao_test_register_widget_localized_info) 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)); + std::make_pair(DPL::FromUTF8String("en"), locDataEn)); } - {//PL + { //PL ConfigParserData::LocalizedData locDataPl; locDataPl.name = DPL::FromUTF8String(str_pl.str()); locDataPl.shortName = DPL::FromUTF8String(str_pl.str()); @@ -388,7 +398,7 @@ RUNNER_TEST(widget_dao_test_register_widget_localized_info) 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)); + std::make_pair(DPL::FromUTF8String("pl"), locDataPl)); } TizenAppId tizenAppId = REGISTER_WIDGET(regInfo, sec); @@ -397,9 +407,9 @@ RUNNER_TEST(widget_dao_test_register_widget_localized_info) RUNNER_ASSERT_MSG(dao.getLanguageTags().size() == 2, "language tags list invalid"); - {//EN + { //EN WidgetLocalizedInfo locInfo = - dao.getLocalizedInfo(DPL::FromUTF8String("en")); + dao.getLocalizedInfo(DPL::FromUTF8String("en")); RUNNER_ASSERT_WHAT_EQUALS_OPTIONAL(locInfo.name, str_en.str()); @@ -413,9 +423,9 @@ RUNNER_TEST(widget_dao_test_register_widget_localized_info) str_en.str()); } - {//PL + { //PL WidgetLocalizedInfo locInfo = - dao.getLocalizedInfo(DPL::FromUTF8String("pl")); + dao.getLocalizedInfo(DPL::FromUTF8String("pl")); RUNNER_ASSERT_WHAT_EQUALS_OPTIONAL(locInfo.name, str_pl.str()); @@ -432,11 +442,11 @@ RUNNER_TEST(widget_dao_test_register_widget_localized_info) } /* -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 -*/ + * 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; @@ -447,7 +457,7 @@ RUNNER_TEST(widget_dao_test_register_widget_icons) icon.height = 10; LocaleSet locs; locs.insert(DPL::FromUTF8String("en")); - WidgetRegisterInfo::LocalizedIcon locIcon(icon,locs); + WidgetRegisterInfo::LocalizedIcon locIcon(icon, locs); regInfo.localizationData.icons.push_back(locIcon); TizenAppId tizenAppId = REGISTER_WIDGET(regInfo, sec); @@ -458,9 +468,9 @@ RUNNER_TEST(widget_dao_test_register_widget_icons) 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) + 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); @@ -470,10 +480,10 @@ RUNNER_TEST(widget_dao_test_register_widget_icons) } /* -Name: widget_dao_test_register_widget_start_files -Description: Tests registeration of localized start files -Expected: no expectations as it should be removed -*/ + * 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; @@ -484,8 +494,8 @@ RUNNER_TEST(widget_dao_test_register_widget_start_files) 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)); + map1.insert(std::make_pair(DPL::FromUTF8String("en"), prop1)); + map1.insert(std::make_pair(DPL::FromUTF8String("pl"), prop1)); WidgetRegisterInfo::LocalizedStartFile file1; WidgetRegisterInfo::LocalizedStartFile file2; @@ -507,22 +517,22 @@ RUNNER_TEST(widget_dao_test_register_widget_start_files) } /* -Name: widget_dao_test_register_widget_features -Description: Tests registeration of features of widget -Expected: number of features should match (for given widget reginfo) -*/ + * 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("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); + regInfo.configInfo.featuresList.insert(*it); TizenAppId tizenAppId = REGISTER_WIDGET(regInfo, sec); @@ -530,16 +540,16 @@ RUNNER_TEST(widget_dao_test_register_widget_features) 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()); + // 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. -*/ + * 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; @@ -547,60 +557,130 @@ RUNNER_TEST(widget_dao_test_register_widget_security_settings) TizenAppId tizenAppId = REGISTER_WIDGET(regInfo, sec); WidgetDAO dao(tizenAppId); - 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"); + 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"); + 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"); + 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"); + 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"); + 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"); + 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"); + 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 -*/ + * 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; @@ -611,7 +691,7 @@ RUNNER_TEST(widget_dao_test_register_widget_win_modes) WidgetRegisterInfo regInfo; FOREACH(it, modes) - regInfo.configInfo.windowModes.insert(*it); + regInfo.configInfo.windowModes.insert(*it); TizenAppId tizenAppId = REGISTER_WIDGET(regInfo, sec); @@ -620,14 +700,14 @@ RUNNER_TEST(widget_dao_test_register_widget_win_modes) RUNNER_ASSERT_MSG(modes.size() == wins.size(), "wrong number of window modes"); FOREACH(it, wins) - RUNNER_ASSERT(modes.find(*it) != modes.end()); + 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 -*/ + * 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; @@ -641,7 +721,7 @@ RUNNER_TEST(widget_dao_test_register_widget_warp_info) WidgetRegisterInfo regInfo; FOREACH(it, orig) - regInfo.configInfo.accessInfoSet.insert(*it); + regInfo.configInfo.accessInfoSet.insert(*it); TizenAppId tizenAppId = REGISTER_WIDGET(regInfo, sec); @@ -652,17 +732,17 @@ RUNNER_TEST(widget_dao_test_register_widget_warp_info) RUNNER_ASSERT_MSG(out.size() == orig.size(), "wrong number of access info elem"); FOREACH(it, out){ - ConfigParserData::AccessInfo tmp(it->strIRI,it->bSubDomains); + 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 -*/ + * 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; @@ -690,32 +770,34 @@ RUNNER_TEST(widget_dao_test_register_widget_certificates) auto recListIt = recList.begin(); auto certListIt = certListRef.begin(); - for(;recListIt != recList.end() && certListIt != certListRef.end(); - ++recListIt,++certListIt) + 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); + certListIt->strMD5Fingerprint); RUNNER_ASSERT(recListIt->strSHA1Fingerprint == - certListIt->strSHA1Fingerprint); + certListIt->strSHA1Fingerprint); RUNNER_ASSERT(recListIt->type == certListIt->type); } // fingerprints RUNNER_ASSERT(dao.getKeyFingerprints(WidgetCertificateData::DISTRIBUTOR, - WidgetCertificateData::ENDENTITY).empty()); + WidgetCertificateData::ENDENTITY). + empty()); RUNNER_ASSERT(dao.getKeyFingerprints(WidgetCertificateData::AUTHOR, - WidgetCertificateData::ENDENTITY).empty()); + WidgetCertificateData::ENDENTITY). + empty()); RUNNER_ASSERT(dao.getKeyFingerprints(WidgetCertificateData::DISTRIBUTOR, - WidgetCertificateData::ROOT).empty()); + WidgetCertificateData::ROOT).empty()); FingerPrintList fingerprints = dao.getKeyFingerprints( WidgetCertificateData::AUTHOR, WidgetCertificateData::ROOT); - RUNNER_ASSERT(fingerprints.size() == certListRef.size()*2); + RUNNER_ASSERT(fingerprints.size() == certListRef.size() * 2); FOREACH(it, certListRef) { auto md5 = std::find(fingerprints.begin(), @@ -731,11 +813,13 @@ RUNNER_TEST(widget_dao_test_register_widget_certificates) // common names RUNNER_ASSERT(dao.getKeyCommonNameList(WidgetCertificateData::DISTRIBUTOR, - WidgetCertificateData::ENDENTITY).empty()); + WidgetCertificateData::ENDENTITY). + empty()); RUNNER_ASSERT(dao.getKeyCommonNameList(WidgetCertificateData::AUTHOR, - WidgetCertificateData::ENDENTITY).empty()); + WidgetCertificateData::ENDENTITY). + empty()); RUNNER_ASSERT(dao.getKeyCommonNameList(WidgetCertificateData::DISTRIBUTOR, - WidgetCertificateData::ROOT).empty()); + WidgetCertificateData::ROOT).empty()); FingerPrintList commonNames = dao.getKeyCommonNameList( WidgetCertificateData::AUTHOR, @@ -752,10 +836,10 @@ RUNNER_TEST(widget_dao_test_register_widget_certificates) } /* -Name: widget_dao_test_is_widget_installed -Description: Tests checking if widgets are installed -Expected: installed widgets should be stated as installed -*/ + * 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")); @@ -769,10 +853,10 @@ RUNNER_TEST(widget_dao_test_is_widget_installed) } /* -Name: widget_dao_test_unregister_widget -Description: Tests unregistering widgets -Expected: widget register informations should be successfully removed -*/ + * 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; @@ -789,10 +873,10 @@ RUNNER_TEST(widget_dao_test_unregister_widget) } /* -Name: widget_dao_test_register_or_update_widget -Description: Tests reregistering widgets -Expected: widget should be successfully replaced -*/ + * 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; @@ -809,23 +893,27 @@ RUNNER_TEST(widget_dao_test_register_or_update_widget) //first installation WidgetDAO::registerWidget(tizenAppId, regInfo, sec); - RUNNER_ASSERT_MSG(WidgetDAO::isWidgetInstalled(tizenAppId), "Widget is not registered"); + RUNNER_ASSERT_MSG(WidgetDAO::isWidgetInstalled( + tizenAppId), "Widget is not registered"); //success full update WidgetDAO::registerOrUpdateWidget(tizenAppId, regInfo2, sec); - RUNNER_ASSERT_MSG(WidgetDAO::isWidgetInstalled(tizenAppId), "Widget is not reregistered"); + RUNNER_ASSERT_MSG(WidgetDAO::isWidgetInstalled( + tizenAppId), "Widget is not reregistered"); WidgetDAO dao(tizenAppId); - 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"); + 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(tizenAppId); } /* -Name: widget_dao_test_get_widget_tizenAppId_list -Description: Tests getTizenAppidList API for backendlib -Expected: For all position in database should be returned one item in list -*/ + * Name: widget_dao_test_get_widget_tizenAppId_list + * Description: Tests getTizenAppidList API for backendlib + * Expected: For all position in database should be returned one item in list + */ RUNNER_TEST(widget_dao_test_get_widget_tizenAppId_list) { TizenAppIdList tizenAppIds = WidgetDAO::getTizenAppidList(); @@ -833,11 +921,11 @@ RUNNER_TEST(widget_dao_test_get_widget_tizenAppId_list) } /* -Name: widget_dao_test_get_widget_list -Description: Tests getTizenAppidList API for backendlib -Expected: For all position in database should be returned one item in list - Those item should contain valid tizenAppId -*/ + * Name: widget_dao_test_get_widget_list + * Description: Tests getTizenAppidList API for backendlib + * Expected: For all position in database should be returned one item in list + * Those item should contain valid tizenAppId + */ RUNNER_TEST(widget_dao_test_get_widget_list) { WidgetDAOReadOnlyList list = WidgetDAOReadOnly::getWidgetList(); @@ -847,10 +935,10 @@ RUNNER_TEST(widget_dao_test_get_widget_list) } /* -Name: widget_dao_test_get_widget_attributes -Description: Tests returning basic widget attributes by dao -Expected: Attributes should match values inserted into database -*/ + * 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) { { @@ -870,10 +958,11 @@ RUNNER_TEST(widget_dao_test_get_widget_attributes) } /* -Name: widget_dao_test_localization -Description: Tests inserting and returning localization info -Expected: Values inserted into database should match values received from database -*/ + * 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; @@ -886,7 +975,7 @@ RUNNER_TEST(widget_dao_test_localization) LocaleSet locs; locs.insert(DPL::FromUTF8String("en")); locs.insert(DPL::FromUTF8String("pl")); - WidgetRegisterInfo::LocalizedIcon locIcon(icon,locs); + WidgetRegisterInfo::LocalizedIcon locIcon(icon, locs); regInfo.localizationData.icons.push_back(locIcon); //start file @@ -901,9 +990,9 @@ RUNNER_TEST(widget_dao_test_localization) WidgetRegisterInfo::LocalizedStartFile file; file.path = DPL::FromUTF8String("path"); file.propertiesForLocales.insert( - std::make_pair(DPL::FromUTF8String("en"), prop_en)); + std::make_pair(DPL::FromUTF8String("en"), prop_en)); file.propertiesForLocales.insert( - std::make_pair(DPL::FromUTF8String("pl"), prop_pl)); + std::make_pair(DPL::FromUTF8String("pl"), prop_pl)); regInfo.localizationData.startFiles.push_back(file); // register widget @@ -922,7 +1011,9 @@ RUNNER_TEST(widget_dao_test_localization) // compare every icon with the origin auto locsIt = locs.begin(); auto iconIt = locList.begin(); - for(;locsIt!=locs.end() && iconIt!=locList.end();++locsIt,++iconIt) { + 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); @@ -934,7 +1025,7 @@ RUNNER_TEST(widget_dao_test_localization) int startFileId = dao.getStartFileList().front().startFileId; - FOREACH(it,fList) + FOREACH(it, fList) { RUNNER_ASSERT(it->appId == dao.getHandle()); auto propIt = file.propertiesForLocales.find(it->widgetLocale); @@ -946,10 +1037,11 @@ RUNNER_TEST(widget_dao_test_localization) } /* -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 -*/ + * 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; @@ -978,10 +1070,11 @@ RUNNER_TEST(widget_dao_test_wac_security) } /* -Name: widget_dao_test_register_scp -Description: Tests inserting and returning scp policy information -Expected: Value inserted into database should match values received from database -*/ + * Name: widget_dao_test_register_scp + * Description: Tests inserting and returning scp policy information + * Expected: Value inserted into database should match values received from + * database + */ RUNNER_TEST(widget_dao_test_register_scp) { WacSecurityMock sec; @@ -993,15 +1086,17 @@ RUNNER_TEST(widget_dao_test_register_scp) TizenAppId tizenAppId = REGISTER_WIDGET(regInfo, sec); WidgetDAO dao(tizenAppId); - RUNNER_ASSERT_WHAT_EQUALS_OPTIONAL(dao.getCspPolicy(), DPL::ToUTF8String(*policy)); + RUNNER_ASSERT_WHAT_EQUALS_OPTIONAL( + dao.getCspPolicy(), DPL::ToUTF8String(*policy)); } } /* -Name: widget_dao_test_register_csp_empty -Description: Tests inserting and returning empty csp policy -Expected: Value inserted into database should match values received from database -*/ + * Name: widget_dao_test_register_csp_empty + * Description: Tests inserting and returning empty csp policy + * Expected: Value inserted into database should match values received from + * database + */ RUNNER_TEST(widget_dao_test_register_csp_empty) { WacSecurityMock sec; diff --git a/tests/dao/tests_dao.cpp b/tests/dao/tests_dao.cpp index 5d0422f..73456db 100644 --- a/tests/dao/tests_dao.cpp +++ b/tests/dao/tests_dao.cpp @@ -14,7 +14,7 @@ * limitations under the License. */ /** - * @file tests_plugin_dao.cpp + * @file tests_plugin_dao.cpp * @author Pawel Sikorski (p.sikorski@samsung.com) * @version 1.0 * @brief This file contains tests for plugin dao class. @@ -30,7 +30,7 @@ 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"); + << ". Quitting"); return -1; } @@ -38,7 +38,8 @@ int main (int argc, char *argv[]) CustomHandlerDB::Interface::attachDatabaseRW(); LogInfo("Starting tests"); - int status = DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, argv); + int status = DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, + argv); CustomHandlerDB::Interface::detachDatabase(); WrtDB::WrtDatabase::detachFromThread(); diff --git a/tests/dpl/core/test_binary_queue.cpp b/tests/dpl/core/test_binary_queue.cpp index d955aab..add6ed2 100644 --- a/tests/dpl/core/test_binary_queue.cpp +++ b/tests/dpl/core/test_binary_queue.cpp @@ -28,7 +28,7 @@ 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; + delete[] buffer; return result; } @@ -78,7 +78,7 @@ RUNNER_TEST(BinaryQueue_InitialConsumeOne) { queue.Consume(1); } - Catch (DPL::BinaryQueue::Exception::OutOfData) + Catch(DPL::BinaryQueue::Exception::OutOfData) { return; } @@ -95,7 +95,7 @@ RUNNER_TEST(BinaryQueue_InitialFlattenConsumeOne) char data; queue.FlattenConsume(&data, 1); } - Catch (DPL::BinaryQueue::Exception::OutOfData) + Catch(DPL::BinaryQueue::Exception::OutOfData) { return; } @@ -112,7 +112,7 @@ RUNNER_TEST(BinaryQueue_InitialFlattenOne) char data; queue.Flatten(&data, 1); } - Catch (DPL::BinaryQueue::Exception::OutOfData) + Catch(DPL::BinaryQueue::Exception::OutOfData) { return; } @@ -279,41 +279,35 @@ RUNNER_TEST(BinaryQueue_AppendMoveTo) RUNNER_ASSERT(BinaryQueueToString(copy) == "abcdef"); } -class Visitor - : public DPL::BinaryQueue::BucketVisitor +class Visitor : + public DPL::BinaryQueue::BucketVisitor { -private: + private: int m_index; -public: - Visitor() - : m_index(0) - { - } + public: + Visitor() : + m_index(0) + {} virtual void OnVisitBucket(const void *buffer, size_t bufferSize) { const char *str = static_cast(buffer); - - if (m_index == 0) - { + + 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) - { + } else if (m_index == 1) { RUNNER_ASSERT(bufferSize == 2); RUNNER_ASSERT(str[0] == 'e'); RUNNER_ASSERT(str[1] == 'f'); - } - else - { + } else { RUNNER_FAIL; } - + ++m_index; } }; diff --git a/tests/dpl/core/test_fast_delegate.cpp b/tests/dpl/core/test_fast_delegate.cpp index 947cbe5..e502bda 100644 --- a/tests/dpl/core/test_fast_delegate.cpp +++ b/tests/dpl/core/test_fast_delegate.cpp @@ -46,42 +46,42 @@ void SimpleVoidFunction() class CBaseClass { -protected: + protected: const char *m_name; -public: - CBaseClass(const char *name) - : m_name(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); + << num << ", str = " << str); } int SimpleMemberFunctionReturnsInt(int num, const char *str) { - LogDebug("In SimpleMemberFunctionReturnsInt in " << m_name << ". Num=" - << num << ", str = " << 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); + << num << ", str = " << str); } virtual void SimpleVirtualFunction(int num, const char *str) { LogDebug("In SimpleVirtualFunction in " << m_name << ". Num=" - << num << ", str = " << str); + << num << ", str = " << str); } static void StaticMemberFunction(int num, const char *str) @@ -95,14 +95,12 @@ class COtherClass { double rubbish; // to ensure this class has non-zero size. -public: + public: virtual ~COtherClass() - { - } + {} virtual void UnusedVirtualFunction(void) - { - } + {} virtual void TrickyVirtualFunction(int num, const char *str) = 0; }; @@ -112,16 +110,16 @@ class VeryBigClass }; // This declaration ensures that we get a convoluted class heirarchy. -class CDerivedClass - : public VeryBigClass, - virtual public COtherClass, - virtual public CBaseClass +class CDerivedClass : + public VeryBigClass, + virtual public COtherClass, + virtual public CBaseClass { double m_somemember[8]; -public: - CDerivedClass() - : CBaseClass("Base of Derived") + public: + CDerivedClass() : + CBaseClass("Base of Derived") { m_somemember[0] = 1.2345; } @@ -134,14 +132,16 @@ public: virtual void AnotherUnusedVirtualFunction(int num, const char *str) { - LogDebug("In AnotherUnusedVirtualFunction in " << m_name << ". Num=" - << num << ", str = " << 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); + << num << ", str = " << str); } }; @@ -163,7 +163,6 @@ RUNNER_TEST(FastDelegate_Test) // 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"); @@ -185,7 +184,7 @@ RUNNER_TEST(FastDelegate_Test) // and const member functions (these only need a const class pointer). funclist[3].bind((const CBaseClass *) &a, - &CBaseClass::ConstMemberFunction); + &CBaseClass::ConstMemberFunction); funclist[4].bind(&a, &CBaseClass::ConstMemberFunction); @@ -222,25 +221,20 @@ RUNNER_TEST(FastDelegate_Test) const char *msg = "Looking for equal delegate"; - for (int i = 0; i < 12; i++) - { + 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) - { + 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]) - { + if (!funclist[i]) { LogDebug("Delegate is empty"); - } - else - { + } 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 index f698081..a5cd399 100644 --- a/tests/dpl/core/test_foreach.cpp +++ b/tests/dpl/core/test_foreach.cpp @@ -58,8 +58,7 @@ std::list temporaryList() { ++numberOfCallsToTemporaryList; std::list list; - for (size_t i = 0 ; i < testContainerSize ; i++) - { + for (size_t i = 0; i < testContainerSize; i++) { list.push_back(i); } return list; @@ -71,8 +70,7 @@ std::vector temporaryVector() { ++numberOfCallsToTemporaryVector; std::vector vector; - for (size_t i = 0 ; i < testContainerSize ; i++) - { + for (size_t i = 0; i < testContainerSize; i++) { vector.push_back(i); } return vector; @@ -84,8 +82,7 @@ std::set temporarySet() { ++numberOfCallsToTemporarySet; std::set set; - for (size_t i = 0 ; i < testContainerSize ; i++) - { + for (size_t i = 0; i < testContainerSize; i++) { set.insert(i); } return set; @@ -97,8 +94,7 @@ RUNNER_TEST(Foreach_std_containers) std::list list; std::set set; - for (size_t i = 0 ; i < testContainerSize ; i++) - { + for (size_t i = 0; i < testContainerSize; i++) { vector.push_back(i); list.push_back(i); set.insert(i); diff --git a/tests/dpl/core/test_log_unhandled_exception.cpp b/tests/dpl/core/test_log_unhandled_exception.cpp index 0403c28..9c3055c 100644 --- a/tests/dpl/core/test_log_unhandled_exception.cpp +++ b/tests/dpl/core/test_log_unhandled_exception.cpp @@ -26,28 +26,30 @@ RUNNER_TEST_GROUP_INIT(DPL) class MyException -{ -}; +{}; class MyDPLException { -public: + public: DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) DECLARE_EXCEPTION_TYPE(Base, MyException) }; -class MySTDException - : public std::exception +class MySTDException : + public std::exception { -public: - virtual const char* what()const throw() { return "my std exception occurred";} + public: + virtual const char* what() const throw() + { + return "my std exception occurred"; + } }; RUNNER_TEST(Log_Unknown_Exception) { UNHANDLED_EXCEPTION_HANDLER_BEGIN { -// throw MyException(); + // throw MyException(); } UNHANDLED_EXCEPTION_HANDLER_END RUNNER_ASSERT(true); @@ -57,7 +59,7 @@ RUNNER_TEST(Log_DPL_Exception) { UNHANDLED_EXCEPTION_HANDLER_BEGIN { -// Throw(MyDPLException::MyException); + // Throw(MyDPLException::MyException); } UNHANDLED_EXCEPTION_HANDLER_END RUNNER_ASSERT(true); @@ -67,7 +69,7 @@ RUNNER_TEST(Log_STD_Exception) { UNHANDLED_EXCEPTION_HANDLER_BEGIN { -// throw MySTDException(); + // 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 index b278f83..3fcc2be 100644 --- a/tests/dpl/core/test_once.cpp +++ b/tests/dpl/core/test_once.cpp @@ -51,10 +51,10 @@ RUNNER_TEST(Once_DoubleCall) RUNNER_ASSERT_MSG(g_counter == 1, "Counter value is: " << g_counter); } -class MyThread - : public DPL::Thread +class MyThread : + public DPL::Thread { -protected: + protected: virtual int ThreadEntry() { DPL::WaitForSingleHandle(m_event->GetHandle()); @@ -67,13 +67,12 @@ protected: ++*m_atom; } -public: - MyThread(DPL::WaitableEvent *event, DPL::Once *once, DPL::Atomic *atom) - : m_event(event), m_once(once), m_atom(atom) - { - } + public: + MyThread(DPL::WaitableEvent *event, DPL::Once *once, DPL::Atomic *atom) : + m_event(event), m_once(once), m_atom(atom) + {} -private: + private: DPL::WaitableEvent *m_event; DPL::Once *m_once; DPL::Atomic *m_atom; @@ -89,15 +88,15 @@ RUNNER_TEST(Once_MultiThreadCall) DPL::Once once; DPL::Atomic atom; - for (size_t i = 0; i< NUM_THREADS; ++i) - { + 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) + 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_fclose.cpp b/tests/dpl/core/test_scoped_fclose.cpp index dbdff95..3450c71 100644 --- a/tests/dpl/core/test_scoped_fclose.cpp +++ b/tests/dpl/core/test_scoped_fclose.cpp @@ -28,18 +28,16 @@ RUNNER_TEST_GROUP_INIT(DPL) -namespace -{ +namespace { FILE* MakeTmp() { FILE* result = NULL; - do - { + do { result = tmpfile(); } while (NULL != result && EINTR == errno); return result; } -}//anonymous namespace +} //anonymous namespace RUNNER_TEST(ScopedFClose_Zero) { diff --git a/tests/dpl/core/test_semaphore.cpp b/tests/dpl/core/test_semaphore.cpp index 854978e..3d689d1 100644 --- a/tests/dpl/core/test_semaphore.cpp +++ b/tests/dpl/core/test_semaphore.cpp @@ -29,33 +29,31 @@ RUNNER_TEST_GROUP_INIT(DPL) -class SemaphoreThread - : public DPL::Thread +class SemaphoreThread : + public DPL::Thread { int m_delta; int m_times; int *m_value; std::string m_semaphoreName; -public: + public: SemaphoreThread(int delta, int times, int *value, - const std::string &semaphoreName) - : m_delta(delta), - m_times(times), - m_value(value), - m_semaphoreName(semaphoreName) - { - } + const std::string &semaphoreName) : + m_delta(delta), + m_times(times), + m_value(value), + m_semaphoreName(semaphoreName) + {} -protected: + protected: virtual int ThreadEntry() { DPL::Semaphore semaphore(m_semaphoreName); - for (int i = 0; i < m_times; ++i) - { + for (int i = 0; i < m_times; ++i) { // Take scoped semaphore lock DPL::Semaphore::ScopedLock lock(&semaphore); *m_value += m_delta; diff --git a/tests/dpl/core/test_serialization.cpp b/tests/dpl/core/test_serialization.cpp index 8776fc8..b5bc99f 100644 --- a/tests/dpl/core/test_serialization.cpp +++ b/tests/dpl/core/test_serialization.cpp @@ -31,7 +31,8 @@ RUNNER_TEST_GROUP_INIT(DPL) // test stream class -class BinaryStream : public DPL::IStream { +class BinaryStream : public DPL::IStream +{ public: virtual void Read(size_t num, void * bytes) { @@ -50,7 +51,7 @@ class BinaryStream : public DPL::IStream { { readPosition = 0; } - virtual ~BinaryStream(){}; + virtual ~BinaryStream(){} private: std::vector data; @@ -58,7 +59,8 @@ class BinaryStream : public DPL::IStream { }; //test ISerializable class -class TestClass : public DPL::ISerializable { +class TestClass : public DPL::ISerializable +{ public: TestClass(int val, std::string str1, std::string str2) { @@ -67,18 +69,18 @@ class TestClass : public DPL::ISerializable { 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); - }; + 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); + DPL::Serialization::Serialize(stream, a); + DPL::Serialization::Serialize(stream, b); + DPL::Serialization::Serialize(stream, c); } virtual ~TestClass(){} virtual bool operator==(const TestClass& other) @@ -90,6 +92,7 @@ class TestClass : public DPL::ISerializable { c[1] == other.c[1] && c[2] == other.c[2]); } + private: int a; std::string b; @@ -102,17 +105,17 @@ RUNNER_TEST(Serialize_primitives) bool b = true; unsigned c = 23; BinaryStream stream; - DPL::Serialization::Serialize(stream,a); - DPL::Serialization::Serialize(stream,b); - DPL::Serialization::Serialize(stream,c); + DPL::Serialization::Serialize(stream, a); + DPL::Serialization::Serialize(stream, b); + DPL::Serialization::Serialize(stream, c); int test_int; - DPL::Deserialization::Deserialize(stream,test_int); + DPL::Deserialization::Deserialize(stream, test_int); RUNNER_ASSERT(test_int == a); bool test_bool; - DPL::Deserialization::Deserialize(stream,test_bool); + DPL::Deserialization::Deserialize(stream, test_bool); RUNNER_ASSERT(test_bool == b); unsigned test_unsigned; - DPL::Deserialization::Deserialize(stream,test_unsigned); + DPL::Deserialization::Deserialize(stream, test_unsigned); RUNNER_ASSERT(test_unsigned == c); } @@ -122,17 +125,17 @@ RUNNER_TEST(Serialize_primitive_pointers) bool b = true; unsigned c = 23; BinaryStream stream; - DPL::Serialization::Serialize(stream,&a); - DPL::Serialization::Serialize(stream,&b); - DPL::Serialization::Serialize(stream,&c); + DPL::Serialization::Serialize(stream, &a); + DPL::Serialization::Serialize(stream, &b); + DPL::Serialization::Serialize(stream, &c); int* test_int; - DPL::Deserialization::Deserialize(stream,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); + DPL::Deserialization::Deserialize(stream, test_bool); RUNNER_ASSERT(test_bool != NULL && *test_bool == b); unsigned* test_unsigned; - DPL::Deserialization::Deserialize(stream,test_unsigned); + DPL::Deserialization::Deserialize(stream, test_unsigned); RUNNER_ASSERT(test_unsigned != NULL && *test_unsigned == c); delete test_int; delete test_bool; @@ -144,13 +147,13 @@ 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); + DPL::Serialization::Serialize(stream, str1); + DPL::Serialization::Serialize(stream, str2); std::string test_str1; - DPL::Deserialization::Deserialize(stream,test_str1); + DPL::Deserialization::Deserialize(stream, test_str1); RUNNER_ASSERT(test_str1 == str1); std::string test_str2; - DPL::Deserialization::Deserialize(stream,test_str2); + DPL::Deserialization::Deserialize(stream, test_str2); RUNNER_ASSERT(test_str2 == str2); } @@ -159,13 +162,13 @@ 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); + DPL::Serialization::Serialize(stream, &str1); + DPL::Serialization::Serialize(stream, &str2); std::string* test_str1; - DPL::Deserialization::Deserialize(stream,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); + DPL::Deserialization::Deserialize(stream, test_str2); RUNNER_ASSERT(test_str2 != NULL && *test_str2 == str2); delete test_str1; delete test_str2; @@ -179,32 +182,32 @@ RUNNER_TEST(Serialize_containers) std::list list; list.push_back(true); list.push_back(false); - std::pair pair; + 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")); + 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); + 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); + 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); + 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); + 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); + 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)); @@ -212,12 +215,12 @@ RUNNER_TEST(Serialize_containers) RUNNER_TEST(Serialize_objects) { - TestClass a(123,"ASDGHUADB\n\n5679b^^()*","TEST_STRING"), - b(679,"HUSPIDNSAHDPA","\nASDSADASD\naDSADASD8"); + 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::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); @@ -228,31 +231,29 @@ 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)); + 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); + DPL::Deserialization::Deserialize(stream, test_map); RUNNER_ASSERT(map.size() == test_map.size()); - std::vector test_vec1,test_vec2; + 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) - { + 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) - { + for (i = 0; i < test_vec1.size(); ++i) { RUNNER_ASSERT((*test_vec1[i]) == (*test_vec2[i])); } } diff --git a/tests/dpl/core/test_string.cpp b/tests/dpl/core/test_string.cpp index e64ab73..25ede33 100644 --- a/tests/dpl/core/test_string.cpp +++ b/tests/dpl/core/test_string.cpp @@ -33,14 +33,13 @@ 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] = - { + 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, + 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, @@ -56,7 +55,6 @@ unsigned char GetBaseCode(int index) 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) @@ -65,8 +63,9 @@ int wbxml_base64_decode(const char *buffer, char **result) const char *bufin = NULL; char *bufout = NULL; - if ((buffer == NULL) || (result == NULL)) + if ((buffer == NULL) || (result == NULL)) { return 0; + } /* Initialize output buffer */ *result = NULL; @@ -78,33 +77,34 @@ int wbxml_base64_decode(const char *buffer, char **result) nbytesdecoded = ((nprbytes + 3) / 4) * 3; /* Malloc result buffer */ - if ((*result = (char*) malloc(nbytesdecoded + 1)) == NULL) + if ((*result = (char*) malloc(nbytesdecoded + 1)) == NULL) { return 0; + } memset(*result, 0, nbytesdecoded + 1); 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); + 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 > 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 > 2) { + *(bufout++) = + (char)(GetBaseCode(bufin[1]) << 4 | GetBaseCode(bufin[2]) >> 2); } - if (nprbytes > 3) - { + if (nprbytes > 3) { *(bufout++) = (char)(GetBaseCode(bufin[2]) << 6 | GetBaseCode(bufin[3])); } @@ -116,7 +116,7 @@ int wbxml_base64_decode(const char *buffer, char **result) //#define TEST_CONVERSION(in_string, out_string, buffer_type, function const char utf32Encoded[] = -"RDAAAI0wAABvMAAAazAAAHswAAB4MAAAaDAAAAAwAABhMAAAijAAAGwwAACLMAAAkjAAAAAwAACP\ + "RDAAAI0wAABvMAAAazAAAHswAAB4MAAAaDAAAAAwAABhMAAAijAAAGwwAACLMAAAkjAAAAAwAACP\ MAAASzAAAIgwAABfMAAAjDAAAF0wAAAAMAAAZDAAAG0wAABqMAAAiTAAAIAwAAAAMAAARjAAAJAw\ AABuMAAASjAAAE8wAACEMAAAfjAAAAAwAABRMAAAdTAAAFMwAABIMAAAZjAAAAAwAABCMAAAVTAA\ AE0wAACGMAAAgTAAAH8wAABXMAAAADAAAJEwAAByMAAAgjAAAFswAABZMAAACgAAANsFAADaBQAA\ @@ -152,7 +152,7 @@ YwAAAGgAAAAKAAAAlokAAM6RAAAhcQAAUJYAAONeAAAM/wAAl3oAABZZAAAJZwAAzYUAAClZAAAK\ AAAACgAAAAAAAAA="; const char utf8Encoded[] = -"44GE44KN44Gv44Gr44G744G444Go44CA44Gh44KK44Gs44KL44KS44CA44KP44GL44KI44Gf44KM\ + "44GE44KN44Gv44Gr44G744G444Go44CA44Gh44KK44Gs44KL44KS44CA44KP44GL44KI44Gf44KM\ 44Gd44CA44Gk44Gt44Gq44KJ44KA44CA44GG44KQ44Gu44GK44GP44KE44G+44CA44GR44G144GT\ 44GI44Gm44CA44GC44GV44GN44KG44KB44G/44GX44CA44KR44Gy44KC44Gb44GZCteb15og15TX\ qteo16HXpyDXoNek16Ug16LXnCDXkteV15bXnCDXp9eY158sINep15PXl9ejINeQ16og16bXkdeZ\ @@ -168,15 +168,12 @@ IM6zzrcsIM60z4HOsc+DzrrOtc67zq/Ots61zrkgz4XPgM6tz4Egzr3Pic64z4HOv8+NIM66z4XO\ vc+Mz4IKVmljdG9yIGphZ3QgenfDtmxmIEJveGvDpG1wZmVyIHF1ZXIgw7xiZXIgZGVuIGdyb8Of\ ZW4gU3lsdGVyIERlaWNoCuimlumHjueEoemZkOW7o++8jOeql+WkluacieiXjeWkqQoKAA=="; - - - const char asciiEncodedIso1[] = -"ISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZ\ + "ISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZ\ WltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fgA="; -const char asciiEncodedUtf32[] = -"IQAAACIAAAAjAAAAJAAAACUAAAAmAAAAJwAAACgAAAApAAAAKgAAACsAAAAsAAAALQAAAC4AAAAv\ +const char asciiEncodedUtf32[] = + "IQAAACIAAAAjAAAAJAAAACUAAAAmAAAAJwAAACgAAAApAAAAKgAAACsAAAAsAAAALQAAAC4AAAAv\ AAAAMAAAADEAAAAyAAAAMwAAADQAAAA1AAAANgAAADcAAAA4AAAAOQAAADoAAAA7AAAAPAAAAD0A\ AAA+AAAAPwAAAEAAAABBAAAAQgAAAEMAAABEAAAARQAAAEYAAABHAAAASAAAAEkAAABKAAAASwAA\ AEwAAABNAAAATgAAAE8AAABQAAAAUQAAAFIAAABTAAAAVAAAAFUAAABWAAAAVwAAAFgAAABZAAAA\ @@ -184,7 +181,6 @@ WgAAAFsAAABcAAAAXQAAAF4AAABfAAAAYAAAAGEAAABiAAAAYwAAAGQAAABlAAAAZgAAAGcAAABo\ AAAAaQAAAGoAAABrAAAAbAAAAG0AAABuAAAAbwAAAHAAAABxAAAAcgAAAHMAAAB0AAAAdQAAAHYA\ AAB3AAAAeAAAAHkAAAB6AAAAewAAAHwAAAB9AAAAfgAAAAAAAAA="; - RUNNER_TEST(String_ConverterFromASCII) { char* inStr = NULL; @@ -227,7 +223,8 @@ RUNNER_TEST(String_ConverterFromUTF8) RUNNER_TEST(String_ConverterFromUTF32) { wchar_t* inStr = NULL; - int inSize = wbxml_base64_decode(utf32Encoded, reinterpret_cast(&inStr)); + int inSize = + wbxml_base64_decode(utf32Encoded, reinterpret_cast(&inStr)); RUNNER_ASSERT(inSize > 0); RUNNER_ASSERT(NULL != inStr); char* outStr = NULL; @@ -242,10 +239,10 @@ RUNNER_TEST(String_ConverterFromUTF32) 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))); - + RUNNER_ASSERT(0 == + memcmp(inStr, &(utfString[0]), utfString.size() * + sizeof(wchar_t))); } free(inStr); @@ -259,11 +256,13 @@ void String_TokenizeReal(const DelimiterType& delimiter) DPL::Tokenize(str, delimiter, std::back_inserter(tokens)); std::vector expectedTokens; - for ( int i = 0 ; i < 5 ; i++ ) + for (int i = 0; i < 5; i++) { expectedTokens.push_back(L""); + } expectedTokens.push_back(L"abc"); - for ( int i = 0 ; i < 3 ; i++ ) + for (int i = 0; i < 3; i++) { expectedTokens.push_back(L""); + } RUNNER_ASSERT(expectedTokens == tokens); tokens.clear(); @@ -299,10 +298,10 @@ void TestInStreams( { typedef std::basic_string - String; + String; std::basic_istringstream - istream(argumentInString); + istream(argumentInString); int intValue = 0; double doubleValue = 0.0; float floatValue = 0.0; @@ -332,11 +331,11 @@ void TestOutStreams( { typedef std::basic_string - String; + String; std::basic_ostringstream - ostream; + ostream; int intValue = 1; double doubleValue = 1.1; @@ -360,9 +359,9 @@ 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"); + TestOutStreams >("test", "11.11.1test"); + TestOutStreams >(L"test", L"11.11.1test"); + TestOutStreams(L"test", L"11.11.1test"); } RUNNER_TEST(String_CompareCaseSensitive) diff --git a/tests/dpl/core/test_thread.cpp b/tests/dpl/core/test_thread.cpp index 202d468..da9aa99 100644 --- a/tests/dpl/core/test_thread.cpp +++ b/tests/dpl/core/test_thread.cpp @@ -29,9 +29,9 @@ bool g_wasFooDeleted; class Foo { -public: + public: int id; - Foo(int i=0): id(i) + Foo(int i = 0) : id(i) { LogInfo("Foo: ctor: " << id); } @@ -51,10 +51,10 @@ public: typedef DPL::ThreadLocalVariable TlsFoo; TlsFoo g_foo; -class FooThread - : public DPL::Thread +class FooThread : + public DPL::Thread { -protected: + protected: virtual int ThreadEntry() { LogInfo("In thread"); 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 index d045a39..cac41cc 100644 --- a/tests/dpl/db/orm/dpl_orm_test_db_sql_generator.h +++ b/tests/dpl/db/orm/dpl_orm_test_db_sql_generator.h @@ -17,7 +17,8 @@ * @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. + * @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. diff --git a/tests/dpl/db/test_orm.cpp b/tests/dpl/db/test_orm.cpp index d2e224f..e5aef09 100644 --- a/tests/dpl/db/test_orm.cpp +++ b/tests/dpl/db/test_orm.cpp @@ -27,7 +27,7 @@ const char* PATH_DB = "/opt/share/wrt/wrt-commons/tests/db/dpl_orm_test.db"; class SmartAttach { -public: + public: SmartAttach(bool autoattach = true) : m_interface(PATH_DB, @@ -50,13 +50,15 @@ public: { return &m_interface; } -private: + + private: DPL::DB::ThreadDatabaseSupport m_interface; bool m_autoattach; }; template -bool ContainerContentsEqual(const ContainerType1& container1, const ContainerType2& container2) +bool ContainerContentsEqual(const ContainerType1& container1, + const ContainerType2& container2) { using namespace DPL::DB::ORM::dpl_orm_test::TestTableInsert; typedef std::set Set1; @@ -65,14 +67,13 @@ bool ContainerContentsEqual(const ContainerType1& container1, const ContainerTyp Set2 set2(container2.begin(), container2.end()); for (typename Set1::iterator it = set1.begin(); - it != set1.end(); - it++) + it != set1.end(); + it++) { LogDebug("Set1 element: " << *it); } - for (typename Set2::iterator it = set2.begin(); it != set2.end(); it++) - { + for (typename Set2::iterator it = set2.begin(); it != set2.end(); it++) { LogDebug("Set2 element: " << *it); } @@ -102,31 +103,40 @@ RUNNER_TEST(ORM_SelectSingleValue) TestTable::Select select(interface.get()); select.Where(Equals(8)); int result; - RUNNER_ASSERT_MSG((result = *select.GetSingleValue()) == 6, "Got " << 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); + 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); + 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); + 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); + RUNNER_ASSERT_MSG((result = select.GetSingleValue( + )) == L"ten", "Got " << result); } //Where on each column @@ -134,31 +144,40 @@ RUNNER_TEST(ORM_SelectSingleValue) TestTable::Select select(interface.get()); select.Where(Equals(6)); int result; - RUNNER_ASSERT_MSG((result = *select.GetSingleValue()) == 6, "Got " << 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); + 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); + 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); + 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_ASSERT_MSG((result = select.GetSingleValue( + )) == L"ten", "Got " << result); } } @@ -211,7 +230,8 @@ RUNNER_TEST(ORM_SelectRowList) expected.Set_ColumnInt(3); expected.Set_ColumnInt2(4); expected.Set_ColumnText(L"five"); - RUNNER_ASSERT_MSG(*(result.begin()) == expected, "Got " << *(result.begin()) ); + RUNNER_ASSERT_MSG(*(result.begin()) == expected, "Got " << + *(result.begin()) ); } { @@ -226,7 +246,8 @@ RUNNER_TEST(ORM_SelectRowList) expected.Set_ColumnInt(8); expected.Set_ColumnInt2(9); expected.Set_ColumnText(L"ten"); - RUNNER_ASSERT_MSG(*(result.begin()) == expected, "Got " << *(result.begin()) ); + RUNNER_ASSERT_MSG(*(result.begin()) == expected, "Got " << + *(result.begin()) ); } { @@ -244,7 +265,8 @@ RUNNER_TEST(ORM_SelectRowList) expected2.Set_ColumnInt2(13); expected2.Set_ColumnText(L"fourteen"); - RUNNER_ASSERT(ContainerContentsEqual(makeList(expected1, expected2), result)); + RUNNER_ASSERT(ContainerContentsEqual(makeList(expected1, + expected2), result)); } } @@ -257,64 +279,79 @@ RUNNER_TEST(ORM_SelectValueList) { TestTable::Select select(interface.get()); select.Where(Is(DPL::Optional::Null)); - RUNNER_ASSERT(ContainerContentsEqual(select.GetValueList(), - makeList(99, 99))); + 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))); + 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")))); + 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))); + 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))); + 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))); + 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_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++ ) + 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++ ) + for (int i = 0; i < TEST_REPETITION; i++) { ORM_SelectSingleRow(); + } - for (int i = 0 ; i < TEST_REPETITION ; i++ ) + for (int i = 0; i < TEST_REPETITION; i++) { ORM_SelectRowList(); + } - for (int i = 0 ; i < TEST_REPETITION ; i++ ) + for (int i = 0; i < TEST_REPETITION; i++) { ORM_SelectValueList(); + } } } @@ -326,7 +363,9 @@ RUNNER_TEST(ORM_Insert) TestTableInsert::Select select1(interface.get()); std::list resultList = select1.GetValueList(); - RUNNER_ASSERT_MSG(resultList.size() == 0, "Returned list has wrong size: " << resultList.size()); + RUNNER_ASSERT_MSG( + resultList.size() == 0, "Returned list has wrong size: " << + resultList.size()); std::list list; TestTableInsert::Insert insert(interface.get()); @@ -341,7 +380,9 @@ RUNNER_TEST(ORM_Insert) list.push_back(row); { TestTableInsert::Select select2(interface.get()); - RUNNER_ASSERT_MSG(ContainerContentsEqual(select2.GetRowList(), list), "Returned list doesn't match."); + RUNNER_ASSERT_MSG(ContainerContentsEqual( + select2.GetRowList(), + list), "Returned list doesn't match."); } TestTableInsert::Insert insert2(interface.get()); @@ -355,7 +396,9 @@ RUNNER_TEST(ORM_Insert) list.push_back(row2); { TestTableInsert::Select select(interface.get()); - RUNNER_ASSERT_MSG(ContainerContentsEqual(select.GetRowList(), list), "Returned list doesn't match."); + RUNNER_ASSERT_MSG(ContainerContentsEqual( + select.GetRowList(), + list), "Returned list doesn't match."); } TestTableInsert::Insert insert3(interface.get()); @@ -370,7 +413,9 @@ RUNNER_TEST(ORM_Insert) list.push_back(row3); { TestTableInsert::Select select3(interface.get()); - RUNNER_ASSERT_MSG(ContainerContentsEqual(select3.GetRowList(), list), "Returned list doesn't match."); + RUNNER_ASSERT_MSG(ContainerContentsEqual( + select3.GetRowList(), + list), "Returned list doesn't match."); } TestTableInsert::Insert insert4(interface.get()); @@ -385,7 +430,9 @@ RUNNER_TEST(ORM_Insert) list.push_back(row4); { TestTableInsert::Select select4(interface.get()); - RUNNER_ASSERT_MSG(ContainerContentsEqual(select4.GetRowList(), list), "Returned list doesn't match."); + RUNNER_ASSERT_MSG(ContainerContentsEqual( + select4.GetRowList(), + list), "Returned list doesn't match."); } // restore original table state @@ -400,8 +447,7 @@ RUNNER_TEST(ORM_Insert) RUNNER_TEST(ORM_MultipleBindInsert) { - for ( int i = 0 ; i < TEST_REPETITION ; i++ ) - { + for (int i = 0; i < TEST_REPETITION; i++) { ORM_Insert(); } } @@ -412,32 +458,40 @@ RUNNER_TEST(ORM_Delete) using namespace DPL::DB::ORM; using namespace DPL::DB::ORM::dpl_orm_test; TestTableDelete::Select selectStart(interface.get()); - selectStart.OrderBy(DPL::TypeListDecl >()); + selectStart.OrderBy(DPL::TypeListDecl >()); 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()); + 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.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."); + 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.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."); + RUNNER_ASSERT_MSG(ContainerContentsEqual( + select.GetRowList(), + list), "Returned list doesn't match."); } { @@ -446,7 +500,9 @@ RUNNER_TEST(ORM_Delete) del.Execute(); TestTableDelete::Select select(interface.get()); - RUNNER_ASSERT_MSG(ContainerContentsEqual(select.GetRowList(), list), "Returned list doesn't match."); + RUNNER_ASSERT_MSG(ContainerContentsEqual( + select.GetRowList(), + list), "Returned list doesn't match."); } //act deletes @@ -454,11 +510,14 @@ RUNNER_TEST(ORM_Delete) list.remove(vector[1]); TestTableDelete::Delete del(interface.get()); - del.Where(And(Equals(6), Equals(L"ten"))); + 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."); + RUNNER_ASSERT_MSG(ContainerContentsEqual( + select.GetRowList(), + list), "Returned list doesn't match."); } { @@ -466,11 +525,14 @@ RUNNER_TEST(ORM_Delete) list.remove(vector[3]); TestTableDelete::Delete del(interface.get()); - del.Where(Is(DPL::Optional::Null)); + 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."); + RUNNER_ASSERT_MSG(ContainerContentsEqual( + select.GetRowList(), + list), "Returned list doesn't match."); } { @@ -478,12 +540,16 @@ RUNNER_TEST(ORM_Delete) del.Execute(); TestTableDelete::Select select(interface.get()); - RUNNER_ASSERT_MSG(select.GetRowList().size() == 0, "Returned list is not empty"); + 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++) + // 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); @@ -492,15 +558,16 @@ RUNNER_TEST(ORM_Delete) { TestTableDelete::Select select(interface.get()); - RUNNER_ASSERT_MSG(ContainerContentsEqual(select.GetRowList(), originalList), "Returned list doesn't match."); + RUNNER_ASSERT_MSG(ContainerContentsEqual( + select.GetRowList(), + originalList), + "Returned list doesn't match."); } - } RUNNER_TEST(ORM_MultipleBindDelete) { - for ( int i = 0 ; i < TEST_REPETITION ; i++ ) - { + for (int i = 0; i < TEST_REPETITION; i++) { ORM_Delete(); } } @@ -514,16 +581,28 @@ RUNNER_TEST(ORM_MultipleBindWhere) TestTable::Select select(interface.get()); int result; select.Where(Equals(8)); - RUNNER_ASSERT_MSG((result = *select.GetSingleValue()) == 6, "Got " << result); + RUNNER_ASSERT_MSG((result = + *select.GetSingleValue()) + == 6, "Got " << + result); select.Where(Equals(3)); - RUNNER_ASSERT_MSG((result = *select.GetSingleValue()) == 1, "Got " << result); + RUNNER_ASSERT_MSG((result = + *select.GetSingleValue()) + == 1, "Got " << + result); select.Where(Equals(8)); - RUNNER_ASSERT_MSG((result = *select.GetSingleValue()) == 6, "Got " << result); + RUNNER_ASSERT_MSG((result = + *select.GetSingleValue()) + == 6, "Got " << + result); select.Where(Equals(3)); - RUNNER_ASSERT_MSG((result = *select.GetSingleValue()) == 1, "Got " << result); + RUNNER_ASSERT_MSG((result = + *select.GetSingleValue()) + == 1, "Got " << + result); } { @@ -531,19 +610,23 @@ RUNNER_TEST(ORM_MultipleBindWhere) int result; select.Where(And(Equals(99), Equals(L"fourteen"))); - RUNNER_ASSERT_MSG((result = select.GetSingleValue()) == 13, "Got " << result); + 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); + 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); + 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); + RUNNER_ASSERT_MSG((result = select.GetSingleValue( + )) == 11, "Got " << result); } { @@ -551,22 +634,24 @@ RUNNER_TEST(ORM_MultipleBindWhere) int result; select.Where(And(Equals(L"fourteen"), Equals(99))); - RUNNER_ASSERT_MSG((result = select.GetSingleValue()) == 13, "Got " << result); + 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_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); + 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_ASSERT_MSG((result = select.GetSingleValue( + )) == 11, "Got " << result); } - } RUNNER_TEST(ORM_Update) @@ -619,7 +704,9 @@ RUNNER_TEST(ORM_Update) // CHECK TestTableInsert::Select select(interface.get()); - RUNNER_ASSERT_MSG(ContainerContentsEqual(select.GetRowList(), list), "Returned list doesn't match."); + RUNNER_ASSERT_MSG(ContainerContentsEqual( + select.GetRowList(), + list), "Returned list doesn't match."); } { // UPDATE - no rows @@ -633,7 +720,9 @@ RUNNER_TEST(ORM_Update) // CHECK TestTableInsert::Select select(interface.get()); - RUNNER_ASSERT_MSG(ContainerContentsEqual(select.GetRowList(), list), "Returned list doesn't match."); + RUNNER_ASSERT_MSG(ContainerContentsEqual( + select.GetRowList(), + list), "Returned list doesn't match."); } { // UPDATE - one row @@ -650,7 +739,9 @@ RUNNER_TEST(ORM_Update) // CHECK TestTableInsert::Select select(interface.get()); - RUNNER_ASSERT_MSG(ContainerContentsEqual(select.GetRowList(), list), "Returned list doesn't match."); + RUNNER_ASSERT_MSG(ContainerContentsEqual( + select.GetRowList(), + list), "Returned list doesn't match."); } { @@ -669,7 +760,9 @@ RUNNER_TEST(ORM_Update) // CHECK TestTableInsert::Select select(interface.get()); - RUNNER_ASSERT_MSG(ContainerContentsEqual(select.GetRowList(), list), "Returned list doesn't match."); + RUNNER_ASSERT_MSG(ContainerContentsEqual( + select.GetRowList(), + list), "Returned list doesn't match."); } // restore original table state @@ -684,8 +777,7 @@ RUNNER_TEST(ORM_Update) RUNNER_TEST(ORM_MultipleBindUpdate) { - for ( int i = 0 ; i < TEST_REPETITION ; i++ ) - { + for (int i = 0; i < TEST_REPETITION; i++) { ORM_Update(); } } @@ -699,15 +791,20 @@ RUNNER_TEST(ORM_transactions) RUNNER_TEST(ORM_MultiAttach) { SmartAttach interface(false); - RUNNER_ASSERT_MSG(!interface.get()->IsAttached(), "Is attached, but shouldn't be."); + 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."); + 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."); + 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."); + 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_ASSERT_MSG( + !interface.get()->IsAttached(), "Is attached, but shouldn't be."); } RUNNER_TEST(ORM_Join) @@ -716,18 +813,21 @@ RUNNER_TEST(ORM_Join) using namespace DPL::DB::ORM; using namespace DPL::DB::ORM::dpl_orm_test; - typedef DPL::TypeListDecl::Type JoinColumns; + 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>(); + select.Join(Equal()); + std::list > rowlist = + select.GetCustomRowList >(); - RUNNER_ASSERT_MSG(rowlist.size() == 5, "Invalid number of rows fetched: " << rowlist.size()); + RUNNER_ASSERT_MSG( + rowlist.size() == 5, "Invalid number of rows fetched: " << rowlist.size()); std::string text; std::ostringstream oss; @@ -736,24 +836,31 @@ RUNNER_TEST(ORM_Join) { cnt++; - text = DPL::ToUTF8String((*rowit).GetColumnData()); + 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()); + 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()); + 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()); + 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>(); + select2.Join(Equal()); + rowlist = select2.GetCustomRowList >(); RUNNER_ASSERT_MSG(rowlist.empty(), "Result should be empty but it is not!"); @@ -761,91 +868,131 @@ RUNNER_TEST(ORM_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()); + 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) { + if (cnt == 5) { cnt = 6; } - text = DPL::ToUTF8String((*rowit).GetColumnData()); + 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: " <()); + 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() << " iteration: " <::Type JoinTables2; + typedef DPL::TypeListDecl::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()); + 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()); + 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; + typedef DPL::TypeListDecl::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()); + 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()); + 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: " <()); + text = + DPL::ToUTF8String((*rowit).GetColumnData()); 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: " <, - OrderingDescending, - OrderingAscending >()); + select.OrderBy(DPL::TypeListDecl, + OrderingDescending, + OrderingAscending >()); std::list result = select.GetRowList(); std::list::const_iterator iter = result.begin(); { //1 row - RUNNER_ASSERT_MSG(*iter->Get_TestText33() == DPL::FromASCIIString("test 6"), "Wrong row 1 order"); + RUNNER_ASSERT_MSG(*iter->Get_TestText33() == + DPL::FromASCIIString( + "test 6"), "Wrong row 1 order"); RUNNER_ASSERT_MSG(iter->Get_TestID() == 10, "Wrong row 1 order"); iter++; } { //2 row - RUNNER_ASSERT_MSG(*iter->Get_TestText33() == DPL::FromASCIIString("test 5"), "Wrong row 2 order"); + RUNNER_ASSERT_MSG(*iter->Get_TestText33() == + DPL::FromASCIIString( + "test 5"), "Wrong row 2 order"); RUNNER_ASSERT_MSG(iter->Get_TestID() == 7, "Wrong row 2 order"); iter++; } { //3 row RUNNER_ASSERT_MSG(iter->Get_Value3() == 111, "Wrong row 3 order"); - RUNNER_ASSERT_MSG(*iter->Get_TestText33() == DPL::FromASCIIString("test 2"), "Wrong row 3 order"); + RUNNER_ASSERT_MSG(*iter->Get_TestText33() == + DPL::FromASCIIString( + "test 2"), "Wrong row 3 order"); RUNNER_ASSERT_MSG(iter->Get_TestID() == 2, "Wrong row 3 order"); iter++; } { //4 row RUNNER_ASSERT_MSG(iter->Get_Value3() == 111, "Wrong row 4 order"); - RUNNER_ASSERT_MSG(*iter->Get_TestText33() == DPL::FromASCIIString("test 1"), "Wrong row 4 order"); + RUNNER_ASSERT_MSG(*iter->Get_TestText33() == + DPL::FromASCIIString( + "test 1"), "Wrong row 4 order"); RUNNER_ASSERT_MSG(iter->Get_TestID() == 1, "Wrong row 4 order"); iter++; } { //5 row RUNNER_ASSERT_MSG(iter->Get_Value3() == 222, "Wrong row 5 order"); - RUNNER_ASSERT_MSG(*iter->Get_TestText33() == DPL::FromASCIIString("test 4"), "Wrong row 5 order"); + RUNNER_ASSERT_MSG(*iter->Get_TestText33() == + DPL::FromASCIIString( + "test 4"), "Wrong row 5 order"); RUNNER_ASSERT_MSG(iter->Get_TestID() == 6, "Wrong row 5 order"); iter++; } { //6 row RUNNER_ASSERT_MSG(iter->Get_Value3() == 222, "Wrong row 6 order"); - RUNNER_ASSERT_MSG(*iter->Get_TestText33() == DPL::FromASCIIString("test 3"), "Wrong row 6 order"); + RUNNER_ASSERT_MSG(*iter->Get_TestText33() == + DPL::FromASCIIString( + "test 3"), "Wrong row 6 order"); RUNNER_ASSERT_MSG(iter->Get_TestID() == 3, "Wrong row 6 order"); iter++; } diff --git a/tests/dpl/db/test_sql_connection.cpp b/tests/dpl/db/test_sql_connection.cpp index 246e77d..0cee018 100644 --- a/tests/dpl/db/test_sql_connection.cpp +++ b/tests/dpl/db/test_sql_connection.cpp @@ -35,16 +35,16 @@ RUNNER_TEST_GROUP_INIT(DPL) class AbstractSynchronizationObjectGenerator { -public: + public: virtual ~AbstractSynchronizationObjectGenerator() {} virtual DPL::DB::SqlConnection::SynchronizationObject *Create() = 0; }; -class NaiveSynchronizationObjectGenerator - : public AbstractSynchronizationObjectGenerator +class NaiveSynchronizationObjectGenerator : + public AbstractSynchronizationObjectGenerator { -public: + public: virtual DPL::DB::SqlConnection::SynchronizationObject *Create() { return new DPL::DB::NaiveSynchronizationObject(); @@ -53,15 +53,15 @@ public: void MassiveReadWriteTest(AbstractSynchronizationObjectGenerator *generator); -class StressGenerator - : public DPL::Thread +class StressGenerator : + public DPL::Thread { -private: + private: size_t m_prefix; std::string m_dbFileName; AbstractSynchronizationObjectGenerator *m_generator; -protected: + protected: virtual int ThreadEntry() { DPL::DB::SqlConnection connection( @@ -74,8 +74,7 @@ protected: connection.PrepareDataCommand( "SELECT COUNT(*) FROM test WHERE value=?"); - for (size_t i = 0; i < 10; ++i) - { + for (size_t i = 0; i < 10; ++i) { std::ostringstream valueStream; valueStream << "value_"; @@ -103,15 +102,14 @@ protected: return 0; } -public: + public: StressGenerator(size_t prefix, const std::string &dbFileName, - AbstractSynchronizationObjectGenerator *generator) - : m_prefix(prefix), - m_dbFileName(dbFileName), - m_generator(generator) - { - } + AbstractSynchronizationObjectGenerator *generator) : + m_prefix(prefix), + m_dbFileName(dbFileName), + m_generator(generator) + {} }; typedef std::shared_ptr ThreadPtr; @@ -127,16 +125,16 @@ void MassiveReadWriteTest(AbstractSynchronizationObjectGenerator *generator) const size_t STRESS_GENERATOR_COUNT = 5; ThreadPtr stressGenerators[STRESS_GENERATOR_COUNT]; - for (size_t i = 0; i < STRESS_GENERATOR_COUNT; ++i) - { + 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) + for (size_t i = 0; i < STRESS_GENERATOR_COUNT; ++i) { stressGenerators[i]->Quit(); + } connection.ExecCommand("DROP TABLE test;"); } @@ -149,27 +147,22 @@ RUNNER_TEST(SqlConnection_MassiveReadWrite_NaiveSynchronization) 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); + 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) + Catch(DPL::DB::SqlConnection::Exception::ConnectionBroken) { RUNNER_ASSERT(true); - } - catch (DPL::Exception) - { + } catch (DPL::Exception) { RUNNER_ASSERT_MSG(false, "Wrong exception found"); } } @@ -184,12 +177,10 @@ RUNNER_TEST(SqlConnection_Not_Connected) "connection should throw on accessing " "nonexistent file as a database"); } - Catch (DPL::DB::SqlConnection::Exception::ConnectionBroken) + Catch(DPL::DB::SqlConnection::Exception::ConnectionBroken) { RUNNER_ASSERT(true); - } - catch (DPL::Exception) - { + } catch (DPL::Exception) { RUNNER_ASSERT_MSG(false, "Wrong exception found"); } } @@ -205,15 +196,12 @@ RUNNER_TEST(SqlConnection_Null_Query) RUNNER_ASSERT_MSG(false, "Null pointer should not be accepted"); } - Catch (DPL::DB::SqlConnection::Exception::SyntaxError) + Catch(DPL::DB::SqlConnection::Exception::SyntaxError) { RUNNER_ASSERT(true); - } - catch (DPL::Exception) - { + } catch (DPL::Exception) { RUNNER_ASSERT_MSG(false, "Wrong exception found"); } - } RUNNER_TEST(SqlConnection_Bad_Query) @@ -226,12 +214,10 @@ RUNNER_TEST(SqlConnection_Bad_Query) connection.ExecCommand("Some stupid string"); RUNNER_ASSERT_MSG(false, "This string should not be accepted"); } - Catch (DPL::DB::SqlConnection::Exception::SyntaxError) + Catch(DPL::DB::SqlConnection::Exception::SyntaxError) { RUNNER_ASSERT(true); - } - catch (DPL::Exception) - { + } catch (DPL::Exception) { RUNNER_ASSERT_MSG(false, "Wrong exception found"); } } diff --git a/tests/dpl/dbus/dbus_test.cpp b/tests/dpl/dbus/dbus_test.cpp index 2ef9a1d..2e8d51b 100644 --- a/tests/dpl/dbus/dbus_test.cpp +++ b/tests/dpl/dbus/dbus_test.cpp @@ -23,11 +23,10 @@ #include "loop_control.h" #include "dbus_test.h" -DBusTest::DBusTest(const std::string& name) - : m_name(name), - m_status(Status::NONE) -{ -} +DBusTest::DBusTest(const std::string& name) : + m_name(name), + m_status(Status::NONE) +{} void DBusTest::run(unsigned int timeout) { @@ -39,8 +38,7 @@ void DBusTest::run(unsigned int timeout) LoopControl::wrt_start_loop(); - switch (m_status) - { + switch (m_status) { case Status::FAILED: throw DPL::Test::TestRunner::TestFailed(m_name.c_str(), __FILE__, diff --git a/tests/dpl/dbus/dbus_test.h b/tests/dpl/dbus/dbus_test.h index 9b5061e..3c7ffe9 100644 --- a/tests/dpl/dbus/dbus_test.h +++ b/tests/dpl/dbus/dbus_test.h @@ -30,9 +30,10 @@ DECLARE_GENERIC_EVENT_0(QuitEvent) DECLARE_GENERIC_EVENT_0(TimeoutEvent) class DBusTest : - private DPL::Event::Controller::Type> + private DPL::Event::Controller::Type> { -public: + public: enum class Status { NONE, @@ -51,7 +52,7 @@ public: void success(); void fail(const std::string& message = std::string()); -private: + private: void OnEventReceived(const TimeoutEvent& event); void OnEventReceived(const QuitEvent& event); @@ -62,7 +63,7 @@ private: class DBusTestManager : private DPL::Noncopyable { -public: + public: static DBusTestManager& getInstance(); DBusTest& getCurrentTest() const; @@ -70,7 +71,7 @@ public: void clear(); -private: + private: DBusTestManager(); DBusTest* m_test; diff --git a/tests/dpl/dbus/main.cpp b/tests/dpl/dbus/main.cpp index 55a8950..d06a4c0 100644 --- a/tests/dpl/dbus/main.cpp +++ b/tests/dpl/dbus/main.cpp @@ -29,7 +29,8 @@ int main(int argc, char *argv[]) LoopControl::init_loop(argc, argv); LogInfo("Running tests"); - int status = DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, argv); + 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 index dfb3c7e..1e5c608 100644 --- a/tests/dpl/dbus/test_cases.cpp +++ b/tests/dpl/dbus/test_cases.cpp @@ -40,17 +40,19 @@ 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!"; @@ -61,78 +63,64 @@ RUNNER_TEST_GROUP_INIT(DPL) RUNNER_TEST(AcquireSessionBus) { - try - { + try { DPL::DBus::Connection::sessionBus(); - } - catch (const DPL::DBus::Exception& ex) - { + } catch (const DPL::DBus::Exception& ex) { RUNNER_ASSERT_MSG(false, ex.DumpToString()); } } RUNNER_TEST(AcquireSystemBus) { - try - { + try { DPL::DBus::Connection::systemBus(); - } - catch (const DPL::DBus::Exception& ex) - { + } catch (const DPL::DBus::Exception& ex) { RUNNER_ASSERT_MSG(false, ex.DumpToString()); } } RUNNER_TEST(ParseNodeInfo) { - try - { + 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) - { + } catch (const DPL::DBus::Exception& ex) { RUNNER_ASSERT_MSG(false, ex.DumpToString()); } } RUNNER_TEST(InvokeRemoteMethod) { - try - { + try { auto connection = DPL::DBus::Connection::systemBus(); auto freedesktop = connection->createObjectProxy(dbusServiceName, - dbusObjectPath); + dbusObjectPath); auto getId = freedesktop->createMethodProxy (dbusInterfaceName, dbusMethodGetId); RUNNER_ASSERT(!getId().empty()); - } - catch (const DPL::DBus::Exception& ex) - { + } catch (const DPL::DBus::Exception& ex) { RUNNER_ASSERT_MSG(false, ex.DumpToString()); } } class RegisterServiceListener : - public DPL::Event::EventListener + public DPL::Event::EventListener { -public: + public: void OnEventReceived( - const DPL::DBus::ConnectionEvents::ServiceNameAcquiredEvent& event) + const DPL::DBus::ConnectionEvents::ServiceNameAcquiredEvent& event) { DBusTest& test = DBusTestManager::getInstance().getCurrentTest(); auto name = event.GetArg0(); - if (serviceName == name) - { + if (serviceName == name) { test.success(); - } - else - { + } else { test.fail("Acquired service name: " + name); } test.quit(); @@ -141,19 +129,17 @@ public: DBUS_TEST(RegisterService) { - try - { + try { RegisterServiceListener listener; auto connection = DPL::DBus::Connection::sessionBus(); connection->DPL::Event::EventSupport::AddListener(&listener); + ServiceNameAcquiredEvent>:: + AddListener(&listener); connection->registerService(serviceName); DBusTestManager::getInstance().getCurrentTest().run(DEFAULT_TIMEOUT); - } - catch (const DPL::DBus::Exception& ex) - { + } catch (const DPL::DBus::Exception& ex) { RUNNER_ASSERT_MSG(false, ex.DumpToString()); } } @@ -168,8 +154,7 @@ DBUS_TEST(RegisterService) */ DBUS_TEST(InvokeTestService) { - try - { + try { auto connection = DPL::DBus::Connection::sessionBus(); auto testService = connection->createObjectProxy(serviceName, objectPath); @@ -177,14 +162,12 @@ DBUS_TEST(InvokeTestService) (interfaceName, methodNameEcho); auto response = echo(challenge); - testService->createMethodProxy(interfaceName, methodNameQuit)(); + testService->createMethodProxy(interfaceName, methodNameQuit) (); RUNNER_ASSERT_MSG(response == challenge, "[challenge = " << challenge << ", response = " << response << "]"); - } - catch (const DPL::DBus::Exception& ex) - { + } 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 index bc2e3f8..510e4c5 100644 --- a/tests/dpl/dbus/test_service.cpp +++ b/tests/dpl/dbus/test_service.cpp @@ -33,22 +33,24 @@ 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: + private: void onMethodCall(GDBusConnection* /*connection*/, const gchar* /*sender*/, const gchar* /*objectPath*/, @@ -57,14 +59,11 @@ private: GVariant* parameters, GDBusMethodInvocation* invocation) { - if (methodNameEcho == methodName) - { + if (methodNameEcho == methodName) { LogDebug("Echo"); g_dbus_method_invocation_return_value(invocation, parameters); - } - else if (methodNameQuit == methodName) - { + } else if (methodNameQuit == methodName) { LogDebug("Quit"); g_dbus_method_invocation_return_value(invocation, NULL); LoopControl::wrt_end_loop(); diff --git a/tests/dpl/event/test_controller.cpp b/tests/dpl/event/test_controller.cpp index fe2a700..aa07167 100644 --- a/tests/dpl/event/test_controller.cpp +++ b/tests/dpl/event/test_controller.cpp @@ -34,23 +34,22 @@ RUNNER_TEST_GROUP_INIT(DPL) -class IntController - : public DPL::Event::Controller::Type> +class IntController : + public DPL::Event::Controller::Type> { -private: + private: int m_value; -protected: + protected: virtual void OnEventReceived(const int &event) { m_value = event; } -public: - IntController() - : m_value(-1) - { - } + public: + IntController() : + m_value(-1) + {} int Value() const { @@ -60,24 +59,23 @@ public: DECLARE_GENERIC_EVENT_1(DoneSignalEvent, DPL::WaitableEvent *) -class ThreadController - : public DPL::Event::Controller::Type> +class ThreadController : + public DPL::Event::Controller::Type> { -private: + private: DPL::Thread *m_value; -protected: + protected: virtual void OnEventReceived(const DoneSignalEvent &event) { m_value = DPL::Thread::GetCurrentThread(); event.GetArg0()->Signal(); } -public: - ThreadController() - : m_value(NULL) - { - } + public: + ThreadController() : + m_value(NULL) + {} DPL::Thread *Value() const { @@ -92,23 +90,59 @@ struct StrangeStruct double c; }; -class StrangeController - : public DPL::Event::Controller::Type> +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; } + 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) @@ -166,16 +200,21 @@ RUNNER_TEST(Controller_PostTimedEventToThread) RUNNER_ASSERT(controller.Value() == &thread); } -DECLARE_GENERIC_EVENT_2(TouchInThread, DPL::WaitableEvent *, DPL::Thread **) -DECLARE_GENERIC_EVENT_2(TouchedControllerSignal, DPL::WaitableEvent *, DPL::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> +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; + public: + typedef DPL::Event::Controller::Type> + PublicController; + typedef DPL::Event::Controller:: + Type> PrivateController; virtual void OnEventReceived(const TouchInThread &event) { @@ -183,7 +222,8 @@ public: PrivateController::Touch(); // Post signal - PrivateController::PostEvent(TouchedControllerSignal(event.GetArg0(), event.GetArg1())); + PrivateController::PostEvent(TouchedControllerSignal(event.GetArg0(), + event.GetArg1())); } virtual void OnEventReceived(const TouchedControllerSignal &event) @@ -209,7 +249,8 @@ RUNNER_TEST(Controller_TouchInThread) DPL::WaitableEvent waitHandle; DPL::Thread *touchedThread = NULL; - controller.PublicController::PostEvent(TouchInThread(&waitHandle, &touchedThread)); + controller.PublicController::PostEvent(TouchInThread(&waitHandle, + &touchedThread)); DPL::WaitForSingleHandle(waitHandle.GetHandle()); @@ -246,14 +287,21 @@ typedef std::vector ControllerList; typedef std::list ThreadList; DECLARE_GENERIC_EVENT_0(QuitEvent) -class QuitController - : public DPL::Event::Controller::Type>, - public DPL::ApplicationExt +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(); } + public: + explicit QuitController() : DPL::ApplicationExt(1, NULL, "test-app") + { + Touch(); + } + + protected: + virtual void OnEventReceived(const QuitEvent &) + { + Quit(); + } }; struct TestContext @@ -269,47 +317,49 @@ TestContextPtr testContextPtr; DECLARE_GENERIC_EVENT_0(StartSendEvent) DECLARE_GENERIC_EVENT_0(RandomEvent) -class TestController - : public DPL::Event::Controller::Type> +class TestController : + public DPL::Event::Controller::Type> { -public: - explicit TestController() { Touch(); } -protected: + 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()); + if (testContextPtr->g_ReceivedCounter == MaxEvents) { + testContextPtr->quitter.DPL::Event::ControllerEventHandler< + QuitEvent>::PostEvent(QuitEvent()); return; } } virtual void OnEventReceived(const StartSendEvent &) { - for (int i=0 ; ig_SentCounter > MaxEvents) - { + for (int i = 0; i < MaxEventsPerController; ++i) { + if (testContextPtr->g_SentCounter > MaxEvents) { return; } ++testContextPtr->g_SentCounter; int id = rand() % static_cast(testContextPtr->controllers.size()); - testContextPtr->controllers.at(id)->DPL::Event::ControllerEventHandler::PostEvent(RandomEvent()); + testContextPtr->controllers.at(id)->DPL::Event:: + ControllerEventHandler::PostEvent(RandomEvent()); } } }; RUNNER_TEST(Controllers_MultipleEvents) { - srand ( time(NULL) ); + srand(time(NULL) ); testContextPtr.reset(new TestContext()); testContextPtr->controllers.reserve(ControllersNumber); - for (int i = 0; i < ControllersNumber ; ++i) - { - if(testContextPtr->controllers.size() % ControllersPerThread ==0) - { + 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(); @@ -317,15 +367,17 @@ RUNNER_TEST(Controllers_MultipleEvents) 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) + 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()); + controller->DPL::Event::ControllerEventHandler:: + PostEvent(StartSendEvent()); } testContextPtr->quitter.Exec(); - RUNNER_ASSERT(testContextPtr->g_SentCounter == testContextPtr->g_ReceivedCounter); + 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 index af303f0..63c1631 100644 --- a/tests/dpl/event/test_event_support.cpp +++ b/tests/dpl/event/test_event_support.cpp @@ -32,36 +32,54 @@ DECLARE_GENERIC_EVENT_0(TestEvent) -class TestListener: public DPL::Event::EventListener +class TestListener : public DPL::Event::EventListener { -public: + public: explicit TestListener() : m_dummyVar(0) { } - void OnEventReceived(const TestEvent &) { m_dummyVar = 1; } - int GetDummyVar() const { return m_dummyVar; } - void ZeroDummyVar() { m_dummyVar = 0; } + void OnEventReceived(const TestEvent &) + { + m_dummyVar = 1; + } + int GetDummyVar() const + { + return m_dummyVar; + } + void ZeroDummyVar() + { + m_dummyVar = 0; + } -private: + private: int m_dummyVar; }; -class TestEventSupport - : public DPL::Event::EventSupport +class TestEventSupport : + public DPL::Event::EventSupport { -public: - void TestEmitEvent() { EmitEvent(TestEvent()); } + public: + void TestEmitEvent() + { + EmitEvent(TestEvent()); + } }; DECLARE_GENERIC_EVENT_0(QuitEvent) -class QuitController - : public DPL::Event::Controller::Type>, - public DPL::ApplicationExt +class QuitController : + public DPL::Event::Controller::Type>, + public DPL::ApplicationExt { -public: - QuitController() : DPL::ApplicationExt(1, NULL, "test-app") { Touch(); } + public: + QuitController() : DPL::ApplicationExt(1, NULL, "test-app") + { + Touch(); + } -protected: - virtual void OnEventReceived(const QuitEvent &) { Quit(); } + protected: + virtual void OnEventReceived(const QuitEvent &) + { + Quit(); + } }; RUNNER_TEST(EventSupport_DestroyBeforeProcessing) @@ -92,10 +110,10 @@ void OnDelegateTest(const int &k) g_delegateTest = k; } -class DelegateTestSupport - : public DPL::Event::EventSupport +class DelegateTestSupport : + public DPL::Event::EventSupport { -public: + public: void Test() { EmitEvent(7); diff --git a/tests/dpl/event/test_ic_delegate.cpp b/tests/dpl/event/test_ic_delegate.cpp index 34aea50..402c090 100644 --- a/tests/dpl/event/test_ic_delegate.cpp +++ b/tests/dpl/event/test_ic_delegate.cpp @@ -44,10 +44,10 @@ 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> +class ICTestController : + public DPL::Event::Controller::Type> { public: ICTestController() { } @@ -55,16 +55,16 @@ class ICTestController protected: virtual void OnEventReceived(const GetNothingEvent& event) { - event.GetArg0()(); //calling intercontext delegate + event.GetArg0() (); //calling intercontext delegate } virtual void OnEventReceived(const GetIntEvent& event) { - event.GetArg0()(IntVal); //calling intercontext delegate + event.GetArg0() (IntVal); //calling intercontext delegate } virtual void OnEventReceived(const GetIntAndStringEvent& event) { - event.GetArg0()(IntVal, StringVal); //calling intercontext delegate + event.GetArg0() (IntVal, StringVal); //calling intercontext delegate } }; @@ -77,8 +77,7 @@ struct TestResult m_int(-1), m_int2(-1), m_string("") - { - } + {} void TestEventsPassed() { @@ -133,7 +132,6 @@ class TestContextFreeClass : Thread::Quit(); } - void Wait() { LogDebug("Waiting for thread"); @@ -168,19 +166,22 @@ class TestContextFreeClass : GetNothingEvent getNothingEvent( makeICDelegate( &TestContextFreeClass::OnNothing)); - m_controller->DPL::Event::ControllerEventHandler::PostEvent( + m_controller->DPL::Event::ControllerEventHandler:: + PostEvent( getNothingEvent); GetIntEvent getIntEvent( makeICDelegate( &TestContextFreeClass::OnIntReceive)); - m_controller->DPL::Event::ControllerEventHandler::PostEvent( + m_controller->DPL::Event::ControllerEventHandler:: + PostEvent( getIntEvent); GetIntAndStringEvent getIntAndStringEvent( makeICDelegate( &TestContextFreeClass::OnIntAndStringReceive)); - m_controller->DPL::Event::ControllerEventHandler::PostEvent( + m_controller->DPL::Event::ControllerEventHandler + ::PostEvent( getIntAndStringEvent); return Thread::ThreadEntry(); @@ -244,8 +245,7 @@ RUNNER_TEST(ICDelegate_1) class TestContextFree; class TestRunnerInThread; -namespace -{ +namespace { const int ControllersPerThread = 40; const int ContextFreePerThread = 180; const int TestsPerController = 110; @@ -263,7 +263,6 @@ std::list frees; std::list ctrls; std::list frees_threads; std::list ctrls_threads; - } class TestContextFree : public DPL::Event::ICDelegateSupport @@ -273,8 +272,7 @@ class TestContextFree : public DPL::Event::ICDelegateSupport int eventsCount) : m_controller(controller), m_eventsCount(eventsCount) - { - } + {} void Wait() { @@ -282,7 +280,6 @@ class TestContextFree : public DPL::Event::ICDelegateSupport DPL::WaitForSingleHandle(m_waitable.GetHandle()); } - void OnNothing() { LogDebug("Got"); @@ -293,7 +290,8 @@ class TestContextFree : public DPL::Event::ICDelegateSupport makeICDelegate( &TestContextFree::OnIntAndStringReceive)); LogDebug("posting next event ..."); - m_controller->DPL::Event::ControllerEventHandler::PostEvent( + m_controller->DPL::Event::ControllerEventHandler< + GetIntAndStringEvent>::PostEvent( getIntAndStringEvent); LogDebug("posting next event done"); } else { @@ -312,7 +310,8 @@ class TestContextFree : public DPL::Event::ICDelegateSupport makeICDelegate( &TestContextFree::OnNothing)); LogDebug("posting next event ..."); - m_controller->DPL::Event::ControllerEventHandler::PostEvent( + m_controller->DPL::Event::ControllerEventHandler:: + PostEvent( getNothingEvent); LogDebug("posting next event done"); } else { @@ -332,7 +331,8 @@ class TestContextFree : public DPL::Event::ICDelegateSupport makeICDelegate( &TestContextFree::OnIntReceive)); LogDebug("posting next event ..."); - m_controller->DPL::Event::ControllerEventHandler::PostEvent( + m_controller->DPL::Event::ControllerEventHandler:: + PostEvent( getIntEvent); LogDebug("posting next event done"); } else { @@ -346,7 +346,8 @@ class TestContextFree : public DPL::Event::ICDelegateSupport GetNothingEvent getNothingEvent( makeICDelegate( &TestContextFree::OnNothing)); - m_controller->DPL::Event::ControllerEventHandler::PostEvent( + m_controller->DPL::Event::ControllerEventHandler:: + PostEvent( getNothingEvent); } @@ -355,7 +356,8 @@ class TestContextFree : public DPL::Event::ICDelegateSupport GetIntEvent getIntEvent( makeICDelegate( &TestContextFree::OnIntReceive)); - m_controller->DPL::Event::ControllerEventHandler::PostEvent( + m_controller->DPL::Event::ControllerEventHandler:: + PostEvent( getIntEvent); } @@ -364,7 +366,8 @@ class TestContextFree : public DPL::Event::ICDelegateSupport GetIntAndStringEvent getIntAndStringEvent( makeICDelegate( &TestContextFree::OnIntAndStringReceive)); - m_controller->DPL::Event::ControllerEventHandler::PostEvent( + m_controller->DPL::Event::ControllerEventHandler + ::PostEvent( getIntAndStringEvent); } @@ -399,8 +402,7 @@ class TestRunnerInThread : public DPL::Thread LogDebug("Thread starts"); { DPL::Mutex::ScopedLock lock(&mutex); - for (int i = 0; i < m_tests; ++i) - { + for (int i = 0; i < m_tests; ++i) { if (i % TestsPerController == 0) { if (ctrls.size() % ControllersPerThread == 0) { ThreadPtr thread(new DPL::Thread()); @@ -434,8 +436,7 @@ class TestRunnerInThread : public DPL::Thread RUNNER_TEST(ICDelegate_2) { LogDebug("Creating test threads"); - for (int i = 0; i < TestThreads; ++i) - { + for (int i = 0; i < TestThreads; ++i) { TestRunnerInThreadPtr ptr( new TestRunnerInThread(NumberOfEvents, TestsPerThread)); frees_threads.push_back(ptr); @@ -481,19 +482,23 @@ const int ReuseCount = 5; typedef DPL::Event::ICDelegate<> GetNothingDlpType; DECLARE_GENERIC_EVENT_1(ReuseCountEvent, GetNothingDlpType) -class ICReuseTestController -: public DPL::Event::Controller::Type> +class ICReuseTestController : + public DPL::Event::Controller::Type> { public: - ICReuseTestController() { m_reuseCount = 0; } + ICReuseTestController() + { + m_reuseCount = 0; + } protected: virtual void OnEventReceived(const ReuseCountEvent& event) { - event.GetArg0()(); //calling intercontext delegate - if(++m_reuseCount < ReuseCount){ + event.GetArg0() (); //calling intercontext delegate + if (++m_reuseCount < ReuseCount) { LogInfo("[Send] Reuse: " << m_reuseCount); - DPL::Event::ControllerEventHandler::PostEvent(event); + DPL::Event::ControllerEventHandler::PostEvent( + event); } } @@ -511,16 +516,26 @@ class ReuseTestContextFreeClass : m_reuseCount(0) { } - void Run() { Thread::Run(); } - void Quit() { Thread::Quit(); } - void Wait() { DPL::WaitForSingleHandle(m_waitable.GetHandle()); } + 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) + if (m_reuseCount == ReuseCount) { m_waitable.Signal(); + } } virtual int ThreadEntry() @@ -529,7 +544,8 @@ class ReuseTestContextFreeClass : makeICDelegate( &ReuseTestContextFreeClass::OnReuseReceive, DPL::Event::ICD::Reuse::Yes)); - m_controller->DPL::Event::ControllerEventHandler::PostEvent( + m_controller->DPL::Event::ControllerEventHandler:: + PostEvent( reuseEvent); return Thread::ThreadEntry(); diff --git a/tests/dpl/event/test_property.cpp b/tests/dpl/event/test_property.cpp index c095e5b..d3df904 100644 --- a/tests/dpl/event/test_property.cpp +++ b/tests/dpl/event/test_property.cpp @@ -41,48 +41,47 @@ 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*/) -{ -} +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 +class MyModel : + public DPL::Event::Model { -public: + public: ~MyModel() {} DPL::Event::Property - Caption; + Caption; DPL::Event::Property - Testproperty0; + Testproperty0; DPL::Event::Property - Testproperty1; + Testproperty1; DPL::Event::Property - Testproperty2; + Testproperty2; DPL::Event::Property Testproperty3; + DPL::Event::PropertyStorageCached> Testproperty3; DPL::Event::Property Testproperty4; + DPL::Event::PropertyStorageDynamic> 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) - { - } + DPL::Event::PropertyStorageDynamicCached> + 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; 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 index ad8443f..06b7294 100644 --- 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 @@ -34,7 +34,6 @@ namespace WrtDB { namespace Powder { - typedef std::set StringSet; //! Widget description struct Description @@ -68,7 +67,7 @@ struct Description //! \param[in] level POWDER content level //! \param[in] context POWDER context bool isContextValid(LevelEnum level, - const DPL::OptionalString& context) const; + const DPL::OptionalString& context) const; }; struct CategoryEntry @@ -81,8 +80,8 @@ struct Description //! \param[in] level POWDER content level //! \param[in] context POWDER context bool isCategoryValid(LevelEntry& reason, - LevelEnum level, - const DPL::OptionalString& context) const; + LevelEnum level, + const DPL::OptionalString& context) const; }; //! POWDER Category -> Category entry map for Widget @@ -106,7 +105,6 @@ struct Description } // namespace Powder namespace ChildProtection { - //! Blacklist with forbidden URLs //! It should be stored in WidgetDAO typedef std::vector BlackList; @@ -119,8 +117,7 @@ struct Record bool enabled; explicit Record(bool enabled) : enabled(enabled) - { - } + {} }; //! Powder processing @@ -147,10 +144,12 @@ struct PowderRules 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()); + explicit CategoryRule( + const DPL::String& category = DPL::String(), + Powder::Description::LevelEnum level = + Powder::Description::LevelUnknown, + const DPL::OptionalString& context = + DPL::OptionalString()); }; struct PowderResult @@ -169,10 +168,12 @@ struct PowderRules Valid //!< Description valid }; InvalidReason reason; - explicit PowderResult(InvalidReason reason = Valid, - const Powder::Description::LevelEntry& invalidDescription = - Powder::Description::LevelEntry(), - const CategoryRule& invalidRule = CategoryRule()); + explicit PowderResult( + InvalidReason reason = Valid, + const Powder::Description::LevelEntry& + invalidDescription = + Powder::Description::LevelEntry(), + const CategoryRule& invalidRule = CategoryRule()); }; typedef std::pair ResultPair; @@ -183,13 +184,14 @@ struct PowderRules //! \retval true rule is valid //! \retval false rule is invalid ResultPair isRuleValidForDescription(const CategoryRule& rule, - const Powder::Description& description) const; + 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; + const Powder::Description& description) const; //! It is the maximum age rating valid for child //! Uniform age is stored in WidgetDAO @@ -214,8 +216,7 @@ struct PowderRules PowderRules() : isAgeRatingRequired(false) - { - } + {} }; } // namespace ChildProtection @@ -237,8 +238,7 @@ class PluginMetafileData public: PluginMetafileData() - { - } + {} std::string m_libraryName; std::string m_featuresInstallURI; @@ -281,11 +281,10 @@ struct DbWidgetSize DPL::OptionalInt height; DbWidgetSize(DPL::OptionalInt w = DPL::OptionalInt::Null, - DPL::OptionalInt h = DPL::OptionalInt::Null) : + DPL::OptionalInt h = DPL::OptionalInt::Null) : width(w), height(h) - { - } + {} }; inline bool operator ==(const DbWidgetSize &objA, const DbWidgetSize &objB) @@ -360,24 +359,24 @@ struct DbWidgetFeature { DPL::String name; /// Feature name bool required; /// Whether feature is required - DbPluginHandle pluginId; /// Plugin id that implement this feature + 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) + const DbWidgetFeature &objB) { return objA.name.compare(objB.name) < 0; } inline bool operator==(const DbWidgetFeature &featureA, - const DbWidgetFeature &featureB) + const DbWidgetFeature &featureB) { return featureA.name == featureB.name && featureA.required == featureB.required && @@ -409,14 +408,12 @@ enum AppType class WidgetType { public: - WidgetType() - :appType(APP_TYPE_UNKNOWN) - { - } - WidgetType(const AppType type) - :appType(type) - { - } + WidgetType() : + appType(APP_TYPE_UNKNOWN) + {} + WidgetType(const AppType type) : + appType(type) + {} bool operator== (const AppType& other) const { return appType == other; @@ -425,9 +422,9 @@ class WidgetType { switch (appType) { #define X(x) case x: return #x; - X(APP_TYPE_UNKNOWN) - X(APP_TYPE_WAC20) - X(APP_TYPE_TIZENWEBAPP) + X(APP_TYPE_UNKNOWN) + X(APP_TYPE_WAC20) + X(APP_TYPE_TIZENWEBAPP) #undef X default: return "UNKNOWN"; @@ -436,7 +433,6 @@ class WidgetType AppType appType; }; - } // namespace WrtDB struct WidgetSetting @@ -447,12 +443,12 @@ struct WidgetSetting bool operator ==(const WidgetSetting& info) const { return (info.settingName == settingName && - info.settingValue == settingValue); + info.settingValue == settingValue); } bool operator !=(const WidgetSetting& info) const { return (info.settingName != settingName || - info.settingValue != settingValue); + info.settingValue != settingValue); } }; @@ -475,9 +471,9 @@ struct WidgetApplicationService bool operator== (const WidgetApplicationService& other) const { return src == other.src && - operation == other.operation && - scheme == other.scheme && - mime == other.mime; + operation == other.operation && + scheme == other.scheme && + mime == other.mime; } }; 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 index 5f58018..264c6e4 100644 --- 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 @@ -44,12 +44,10 @@ typedef DPL::OptionalString WidgetGUID; namespace ConfigParserData { - struct Icon { Icon(const DPL::String& src) : src(src) - { - } + {} DPL::String src; DPL::OptionalInt width; DPL::OptionalInt height; @@ -62,7 +60,6 @@ struct Icon }; } // namespace ConfigParserData namespace WrtDB { - typedef std::list StringList; struct WidgetLocalizedInfo @@ -96,7 +93,7 @@ class WidgetDAO protected: DbWidgetHandle m_widgetHandle; - + public: struct WidgetLocalizedIconRow { @@ -134,14 +131,13 @@ class WidgetDAO }; typedef std::list LocalizedStartFileList; - /** * This is a constructor. * * @param[in] widgetHandle application id of widget. */ - WidgetDAO(DbWidgetHandle widgetHandle) - : m_widgetHandle(widgetHandle) + WidgetDAO(DbWidgetHandle widgetHandle) : + m_widgetHandle(widgetHandle) {} /** @@ -154,9 +150,13 @@ class WidgetDAO * * @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. + * @exception WRT_CONF_ERR_EMDB_NO_RECORD - Can not find matching records in + * DB table. */ - DbWidgetHandle getHandle() const { return m_widgetHandle; } + DbWidgetHandle getHandle() const + { + return m_widgetHandle; + } DbWidgetHandle getHandle(const WidgetGUID GUID) const; static DbWidgetHandle getHandle(const DPL::String tizenAppId); @@ -219,12 +219,13 @@ class WidgetDAO 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; + 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 index 6dc2739..170aad7 100644 --- a/tests/dpl/localization/mockup_src/widget_dao.cpp +++ b/tests/dpl/localization/mockup_src/widget_dao.cpp @@ -33,10 +33,11 @@ #include namespace WrtDB { - -std::map WidgetDAO::s_startFileMap; -std::map WidgetDAO::s_localizedStartFileMap; -std::map WidgetDAO::s_pathMap; +std::map WidgetDAO::s_startFileMap; +std::map WidgetDAO::s_localizedStartFileMap; +std::map WidgetDAO::s_pathMap; DbWidgetHandle WidgetDAO::getHandle(const WidgetGUID /* GUID */) const { @@ -61,8 +62,8 @@ void WidgetDAO::setPath(const DPL::String &path) const } WidgetLocalizedInfo - WidgetDAO::getLocalizedInfo(const DPL::String& /* languageTag */) - const +WidgetDAO::getLocalizedInfo(const DPL::String& /* languageTag */) +const { LogError("Not implemented!"); return WidgetLocalizedInfo(); @@ -91,7 +92,9 @@ WidgetDAO::LocalizedStartFileList WidgetDAO::getLocalizedStartFileList() const return s_localizedStartFileMap[m_widgetHandle]; } -void WidgetDAO::setLocalizedStartFileList(const LocalizedStartFileList &list) const { +void WidgetDAO::setLocalizedStartFileList(const LocalizedStartFileList &list) +const +{ s_localizedStartFileMap[m_widgetHandle] = list; } @@ -104,5 +107,4 @@ void WidgetDAO::setStartFileList(const WidgetStartFileList &list) const { s_startFileMap[m_widgetHandle] = list; } - } // namespace WrtDB diff --git a/tests/dpl/localization/test_suite01.cpp b/tests/dpl/localization/test_suite01.cpp index b752bf5..d3cb174 100644 --- a/tests/dpl/localization/test_suite01.cpp +++ b/tests/dpl/localization/test_suite01.cpp @@ -30,8 +30,8 @@ #include namespace { - -WrtDB::LanguageTagList generateLanguageTags(){ +WrtDB::LanguageTagList generateLanguageTags() +{ WrtDB::LanguageTagList tags; tags.push_back(L"pl-pl"); tags.push_back(L"en-en"); @@ -40,9 +40,10 @@ WrtDB::LanguageTagList generateLanguageTags(){ } 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/"; - +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){ @@ -51,11 +52,13 @@ RUNNER_TEST(test01_getFilePathInWidgetPackageFromUrl){ //dao.setPath(widget1Path); auto result = W3CFileLocalization::getFilePathInWidgetPackageFromUrl( - widgetHandle, - languageTags, - L"widget://one"); + widgetHandle, + languageTags, + L"widget://one"); - RUNNER_ASSERT(*result == L"/opt/share/widget/tests/localization/widget1/locales/pl-en/one"); + RUNNER_ASSERT( + *result == + L"/opt/share/widget/tests/localization/widget1/locales/pl-en/one"); } RUNNER_TEST(test02_getFilePathInWidgetPackageFromUrl){ @@ -64,11 +67,13 @@ RUNNER_TEST(test02_getFilePathInWidgetPackageFromUrl){ //dao.setPath(widget2Path); auto result = W3CFileLocalization::getFilePathInWidgetPackageFromUrl( - widgetHandle, - languageTags, - L"widget://one"); + widgetHandle, + languageTags, + L"widget://one"); - RUNNER_ASSERT(*result == L"/opt/share/widget/tests/localization/widget2/locales/pl-en/one"); + RUNNER_ASSERT( + *result == + L"/opt/share/widget/tests/localization/widget2/locales/pl-en/one"); } RUNNER_TEST(test03_getFilePathInWidgetPackageFromUrl){ @@ -77,11 +82,13 @@ RUNNER_TEST(test03_getFilePathInWidgetPackageFromUrl){ //dao.setPath(widget2Path); auto result = W3CFileLocalization::getFilePathInWidgetPackageFromUrl( - widgetHandle, - languageTags, - L"widget://two"); + widgetHandle, + languageTags, + L"widget://two"); - RUNNER_ASSERT(*result == L"/opt/share/widget/tests/localization/widget2/locales/en-en/two"); + RUNNER_ASSERT( + *result == + L"/opt/share/widget/tests/localization/widget2/locales/en-en/two"); } RUNNER_TEST(test04_getFilePathInWidgetPackage){ @@ -90,9 +97,9 @@ RUNNER_TEST(test04_getFilePathInWidgetPackage){ //dao.setPath(widget1Path); auto result = W3CFileLocalization::getFilePathInWidgetPackage( - widgetHandle, - languageTags, - L"one"); + widgetHandle, + languageTags, + L"one"); RUNNER_ASSERT(*result == L"locales/pl-en/one"); } @@ -103,9 +110,9 @@ RUNNER_TEST(test05_getFilePathInWidgetPackage){ //dao.setPath(widget2Path); auto result = W3CFileLocalization::getFilePathInWidgetPackage( - widgetHandle, - languageTags, - L"two"); + widgetHandle, + languageTags, + L"two"); RUNNER_ASSERT(*result == L"locales/en-en/two"); } diff --git a/tests/dpl/test/runner_child.cpp b/tests/dpl/test/runner_child.cpp index f5ae79b..d911270 100644 --- a/tests/dpl/test/runner_child.cpp +++ b/tests/dpl/test/runner_child.cpp @@ -50,11 +50,11 @@ RUNNER_CHILD_TEST(t03_fail_timeout) RUNNER_CHILD_TEST(t04_fail) { - RUNNER_ASSERT_MSG(1, "This test should fail"); - RUNNER_ASSERT_MSG(1, "This test should fail"); - RUNNER_ASSERT_MSG(1, "This test should fail"); - RUNNER_ASSERT_MSG(1, "This test should fail"); - RUNNER_ASSERT_MSG(0, "This test should fail"); + RUNNER_ASSERT_MSG(1, "This test should fail"); + RUNNER_ASSERT_MSG(1, "This test should fail"); + RUNNER_ASSERT_MSG(1, "This test should fail"); + RUNNER_ASSERT_MSG(1, "This test should fail"); + RUNNER_ASSERT_MSG(0, "This test should fail"); } RUNNER_CHILD_TEST(t05_fail_child_died) diff --git a/tests/dpl/unused/test_caller.cpp b/tests/dpl/unused/test_caller.cpp index 17de24b..6f1a1ff 100644 --- a/tests/dpl/unused/test_caller.cpp +++ b/tests/dpl/unused/test_caller.cpp @@ -27,7 +27,8 @@ RUNNER_TEST_GROUP_INIT(DPL) // test stream class -class BinaryStream : public DPL::IStream { +class BinaryStream : public DPL::IStream +{ public: virtual void Read(size_t num, void * bytes) { @@ -46,7 +47,7 @@ class BinaryStream : public DPL::IStream { { readPosition = 0; } - virtual ~BinaryStream(){}; + virtual ~BinaryStream(){} private: std::vector data; @@ -71,27 +72,27 @@ static void void_func(int a) static struct VoidDelegate { - void operator()(int a) - { - called = a; - } + void operator()(int a) + { + called = a; + } } voidDelegate; static struct ReturnDelegate { - int operator()(int a) - { - return a; - } + int operator()(int a) + { + return a; + } } returnDelegate; RUNNER_TEST(Caller_function_void) { int a = 23; BinaryStream stream; - DPL::Serialization::Serialize(stream,a); + DPL::Serialization::Serialize(stream, a); called = 0; - DPL::Caller::Call(stream,void_func); + DPL::Caller::Call(stream, void_func); RUNNER_ASSERT(called == a); } @@ -100,9 +101,9 @@ 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); + DPL::Serialization::Serialize(stream, a); + DPL::Serialization::Serialize(stream, b); + int result = DPL::Caller::Call(stream, return_func); RUNNER_ASSERT(result == a); } @@ -111,8 +112,8 @@ RUNNER_TEST(Caller_delegate_void) int a = 23; BinaryStream stream; called = 0; - DPL::Serialization::Serialize(stream,a); - DPL::Caller::CallDelegate(stream,voidDelegate); + DPL::Serialization::Serialize(stream, a); + DPL::Caller::CallDelegate(stream, voidDelegate); RUNNER_ASSERT(called == a); } @@ -121,8 +122,8 @@ RUNNER_TEST(Caller_delegate_return) int a = 23; BinaryStream stream; called = 0; - DPL::Serialization::Serialize(stream,a); + DPL::Serialization::Serialize(stream, a); int result = 0; - DPL::Caller::CallDelegate(stream,returnDelegate,result); + 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 index 2c0accb..dd208b6 100644 --- a/tests/dpl/unused/test_crypto_hash.cpp +++ b/tests/dpl/unused/test_crypto_hash.cpp @@ -31,60 +31,87 @@ RUNNER_TEST_GROUP_INIT(DPL) RUNNER_TEST(CryptoHash_MD2) { - TEST_CRYPTO_HASH(DPL::Crypto::Hash::MD2, "sample_input_string", "c9f26439c9882cccc98467dbdf07b1fc"); + 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"); + 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"); + 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"); + 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"); + 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"); + 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"); + 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"); + 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"); + 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"); + 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"); + 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"); + 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 index 6340b57..3322413 100644 --- a/tests/dpl/unused/test_message_queue.cpp +++ b/tests/dpl/unused/test_message_queue.cpp @@ -32,41 +32,47 @@ DECLARE_GENERIC_EVENT_0(QuitEvent) -class QuitController - : public DPL::Controller::Type>, - public DPL::ApplicationExt +class QuitController : + public DPL::Controller::Type>, + public DPL::ApplicationExt { -public: - QuitController() : DPL::ApplicationExt(1, NULL, "test-app") { Touch(); } + public: + QuitController() : DPL::ApplicationExt(1, NULL, "test-app") + { + Touch(); + } -protected: - virtual void OnEventReceived(const QuitEvent &) { Quit(); } + protected: + virtual void OnEventReceived(const QuitEvent &) + { + Quit(); + } }; RUNNER_TEST_GROUP_INIT(DPL) -class CopyThread - : public DPL::Thread +class CopyThread : + public DPL::Thread { -private: + private: bool m_success; DPL::AbstractWaitableInput *m_input; DPL::AbstractWaitableOutput *m_output; std::size_t m_dataSize; -public: + public: CopyThread(DPL::AbstractWaitableInput *input, DPL::AbstractWaitableOutput *output, - std::size_t dataSize) - : m_success(true), - m_input(input), - m_output(output), - m_dataSize(dataSize) + std::size_t dataSize) : + m_success(true), + m_input(input), + m_output(output), + m_dataSize(dataSize) { LogInfo("Thread created"); } -protected: + protected: virtual int ThreadEntry() { LogInfo("Entering copy thread"); @@ -75,7 +81,7 @@ protected: { DPL::Copy(m_input, m_output, m_dataSize); } - Catch (DPL::CopyFailed) + Catch(DPL::CopyFailed) { m_success = false; @@ -93,7 +99,7 @@ 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; + delete[] buffer; return result; } @@ -108,31 +114,31 @@ RUNNER_TEST(MessageQueue_DoubleCopy) 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."; + "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); diff --git a/tests/dpl/unused/test_shm.cpp b/tests/dpl/unused/test_shm.cpp index e62a5ac..4f2d93a 100644 --- a/tests/dpl/unused/test_shm.cpp +++ b/tests/dpl/unused/test_shm.cpp @@ -59,8 +59,8 @@ const int SINGLE_PROCESS_REPEATS = 50; * 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; +const size_t EXPECTED_WAITABLE_TIMEOUT = 5 * 1000; +const size_t UNEXPECTED_WAITABLE_TIMEOUT = 30 * 1000; bool g_enumTestCorrect = false; bool g_enumTestIncorrect = false; @@ -72,11 +72,10 @@ void Wait(DPL::WaitableEvent& event, bool expectedTimeout = false) DPL::WaitableHandleIndexList list = DPL::WaitForSingleHandle( event.GetHandle(), expectedTimeout ? - EXPECTED_WAITABLE_TIMEOUT : UNEXPECTED_WAITABLE_TIMEOUT); + EXPECTED_WAITABLE_TIMEOUT : UNEXPECTED_WAITABLE_TIMEOUT); if (list.size() == 0) { LogDebug("...timeout."); - } - else { + } else { LogDebug("...signaled."); event.Reset(); } @@ -143,7 +142,7 @@ class ListeningController : template ListeningController::ListeningController( - DPL::WaitableEvent* waitable) : + DPL::WaitableEvent* waitable) : m_waitable(waitable) { Touch(); @@ -165,8 +164,7 @@ void ListeningController::OnEventReceived(const int& event) m_so = SharedObjectFactory::Create(SHM_KEY, SEM_NAME); OnEvent(event); m_waitable->Signal(); - } - else if (event == DESTROY_EVENT) { + } else if (event == DESTROY_EVENT) { LogDebug("Destroying shared object"); OnEvent(event); @@ -175,8 +173,7 @@ void ListeningController::OnEventReceived(const int& event) LogDebug("4"); m_waitable->Signal(); LogDebug("5"); - } - else { + } else { OnEvent(event); } } @@ -208,8 +205,7 @@ class TestSharedObject4 : public SharedObject protected: explicit TestSharedObject4(const std::string& semaphore) : SharedObject(semaphore) - { - } + {} private: void Init() @@ -218,9 +214,6 @@ class TestSharedObject4 : public SharedObject } friend class SharedObjectFactory; }; - - - } // anonymus namespace ////////////////////////////////////////////// @@ -260,15 +253,15 @@ RUNNER_TEST(SharedMemory_003_AccessByIndex) str.Embedded<3, TestTypeList::Element<3>::Type>::value[1] = 20; RUNNER_ASSERT( - (str.Embedded<0, TestTypeList::Element<0>::Type>::value) == 4); + (str.Embedded<0, TestTypeList::Element<0>::Type>::value) == 4); RUNNER_ASSERT( - (str.Embedded<1, TestTypeList::Element<1>::Type>::value) == 5); + (str.Embedded<1, TestTypeList::Element<1>::Type>::value) == 5); RUNNER_ASSERT( - (str.Embedded<2, TestTypeList::Element<2>::Type>::value) == 'd'); + (str.Embedded<2, TestTypeList::Element<2>::Type>::value) == 'd'); RUNNER_ASSERT( - (str.Embedded<3, TestTypeList::Element<3>::Type>::value[0]) == 1); + (str.Embedded<3, TestTypeList::Element<3>::Type>::value[0]) == 1); RUNNER_ASSERT( - (str.Embedded<3, TestTypeList::Element<3>::Type>::value[1]) == 20); + (str.Embedded<3, TestTypeList::Element<3>::Type>::value[1]) == 20); } ////////////////////////////////////////////// @@ -332,7 +325,7 @@ RUNNER_TEST(SharedMemory_010_BaseShmTest) Try { shm.Reset(SharedMemory::Create(SHM_KEY, false)); } - Catch (SharedMemory::Exception::NotFound) { + Catch(SharedMemory::Exception::NotFound) { shm.Reset(SharedMemory::Create(SHM_KEY, true, true)); } @@ -349,7 +342,7 @@ RUNNER_TEST(SharedMemory_010_BaseShmTest) Try { shm2.Reset(SharedMemory::Create(SHM_KEY, false)); } - Catch (SharedMemory::Exception::NotFound) { + Catch(SharedMemory::Exception::NotFound) { shm2.Reset(SharedMemory::Create(SHM_KEY, true, true)); } @@ -387,10 +380,10 @@ RUNNER_TEST(SharedMemory_020_SharedObjectTest) typedef SharedObject MySharedObj; MySharedObj::Ptr so = - SharedObjectFactory::Create(SHM_KEY, SEM_NAME); + SharedObjectFactory::Create(SHM_KEY, SEM_NAME); RUNNER_ASSERT((so->GetProperty<0, size_t>()) == 0); - so->SetProperty<0,size_t>(4); + so->SetProperty<0, size_t>(4); RUNNER_ASSERT((so->GetProperty<0, size_t>()) == 4); } @@ -420,11 +413,11 @@ 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'); + 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'); } ////////////////////////////////////////////// @@ -435,7 +428,10 @@ class VersionTestSO1 : public TestSharedObject explicit VersionTestSO1(const std::string& semaphore) : TestSharedObject(semaphore) {} - virtual SizeType GetVersion() const { return 1; } // from SharedObject + virtual SizeType GetVersion() const + { + return 1; + } // from SharedObject private: friend class SharedObjectFactory; @@ -447,7 +443,10 @@ class VersionTestSO2 : public TestSharedObject explicit VersionTestSO2(const std::string& semaphore) : TestSharedObject(semaphore) {} - virtual SizeType GetVersion() const { return 2; } // from SharedObject + virtual SizeType GetVersion() const + { + return 2; + } // from SharedObject private: friend class SharedObjectFactory; @@ -458,11 +457,11 @@ RUNNER_TEST(SharedMemory_022_InvalidVersionTest) RemoveIpcs(); // we need non existing shm std::shared_ptr sho = - SharedObjectFactory::Create(SHM_KEY, SEM_NAME); + SharedObjectFactory::Create(SHM_KEY, SEM_NAME); Try { std::shared_ptr sho2 = - SharedObjectFactory::Create(SHM_KEY, SEM_NAME); + SharedObjectFactory::Create(SHM_KEY, SEM_NAME); RUNNER_ASSERT_MSG(false, "Invalid shm version has been accepted"); } @@ -501,7 +500,10 @@ class MagicTestSO1 : public TestSharedObject TestSharedObject(semaphore) {} // from SharedObject - virtual MagicType GetMagicNumber() const { return 661; } + virtual MagicType GetMagicNumber() const + { + return 661; + } private: friend class SharedObjectFactory; @@ -514,7 +516,10 @@ class MagicTestSO2 : public TestSharedObject TestSharedObject(semaphore) {} // from SharedObject - virtual MagicType GetMagicNumber() const { return 662; } + virtual MagicType GetMagicNumber() const + { + return 662; + } private: friend class SharedObjectFactory; @@ -525,11 +530,11 @@ RUNNER_TEST(SharedMemory_024_InvalidMagicTest) RemoveIpcs(); // we need non existing shm std::shared_ptr sho = - SharedObjectFactory::Create(SHM_KEY, SEM_NAME); + SharedObjectFactory::Create(SHM_KEY, SEM_NAME); Try { std::shared_ptr sho2 = - SharedObjectFactory::Create(SHM_KEY, SEM_NAME); + SharedObjectFactory::Create(SHM_KEY, SEM_NAME); RUNNER_ASSERT_MSG(false, "Invalid shm magic number has been accepted"); } @@ -546,7 +551,10 @@ RUNNER_TEST(SharedMemory_024_InvalidMagicTest) class EnumTestSO1 : public TestSharedObject { public: - void SetWaitable(DPL::WaitableEvent* waitable) { m_waitable = waitable; } + void SetWaitable(DPL::WaitableEvent* waitable) + { + m_waitable = waitable; + } protected: explicit EnumTestSO1(const std::string& semaphore) : @@ -562,13 +570,11 @@ class EnumTestSO1 : public TestSharedObject void EnumTestSO1::PropertyChanged(size_t propertyEnum) { - if (propertyEnum == 1) - { + if (propertyEnum == 1) { LogDebug("Property enum " << propertyEnum << " correctly set"); g_enumTestCorrect = true; } - if (propertyEnum == 4) - { + if (propertyEnum == 4) { // This is bad. We only have 4 types LogError("Property enum " << propertyEnum << " should be skipped"); g_enumTestIncorrect = true; @@ -622,7 +628,7 @@ RUNNER_TEST(SharedMemory_025_InvalidEnumTest) // create writing shared object std::shared_ptr sho2 = - SharedObjectFactory::Create(SHM_KEY, SEM_NAME); + SharedObjectFactory::Create(SHM_KEY, SEM_NAME); DPL::WaitableHandleIndexList list; // write property and wait for confirmation @@ -662,9 +668,9 @@ void MultiThreadSO::TestAndSetProperty() { ScopedFlaggedLock lock(*this); - int value = PropertyRef<0,int>(); + int value = PropertyRef<0, int>(); DPL::Thread::MicroSleep(100); - SetPropertyInternal<0>(value+1); + SetPropertyInternal<0>(value + 1); } class ShmController : public ListeningController @@ -685,14 +691,12 @@ 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) { + } 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){ + } else if (event == 2) { m_so->TestAndSetProperty(); m_counter++; if (m_counter >= TEST_AND_SET_REPEATS) { @@ -714,41 +718,41 @@ RUNNER_TEST(SharedMemory_030_MultithreadTest) 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); + int value = sho->GetProperty<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 +class MyModel10 : public DPL::Model { public: - explicit MyModel10(const TestSharedObject4Ptr& shared_object) - : DPL::Model(), boolValue(this, shared_object) {} + explicit MyModel10(const TestSharedObject4Ptr& shared_object) : + DPL::Model(), boolValue(this, shared_object) {} SharedProperty - boolValue; + boolValue; }; /* * Listening controller */ -class ShmController3: public ListeningController +class ShmController3 : public ListeningController { public: explicit ShmController3(DPL::WaitableEvent* event) : @@ -771,14 +775,14 @@ 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)); + DPL::FastDelegate&)>( + this, + &ShmController3::OnValueChanged)); } else if (event == DESTROY_EVENT) { m_model->boolValue.RemoveListener( - DPL::FastDelegate&)>( - this, - &ShmController3::OnValueChanged)); + DPL::FastDelegate&)>( + this, + &ShmController3::OnValueChanged)); m_model.Reset(); } } @@ -820,7 +824,7 @@ RUNNER_TEST(SharedMemory_050_SharedProperty) ////////////////////////////////////////////// -class MyModel2: public DPL::Model +class MyModel2 : public DPL::Model { public: explicit MyModel2(const TestSharedObjectPtr& shared_object) : @@ -858,24 +862,23 @@ void SPController::OnEvent(const int event) m_model1.Reset(new MyModel2(m_so)); m_model2.Reset(new MyModel2(m_so2)); m_model1->counter.AddListener( - DPL::FastDelegate&)>( - this, - &SPController::OnValueChanged1)); + DPL::FastDelegate&)>( + this, + &SPController::OnValueChanged1)); m_model2->counter.AddListener( - DPL::FastDelegate&)>( - this, - &SPController::OnValueChanged2)); + DPL::FastDelegate&)>( + this, + &SPController::OnValueChanged2)); m_model1->counter.Set(1); - } - else if (event == DESTROY_EVENT) { + } else if (event == DESTROY_EVENT) { m_model1->counter.RemoveListener( - DPL::FastDelegate&)>( - this, - &SPController::OnValueChanged1)); + DPL::FastDelegate&)>( + this, + &SPController::OnValueChanged1)); m_model2->counter.RemoveListener( - DPL::FastDelegate&)>( - this, - &SPController::OnValueChanged2)); + DPL::FastDelegate&)>( + this, + &SPController::OnValueChanged2)); m_model1.Reset(); m_model2.Reset(); @@ -892,7 +895,7 @@ void SPController::OnValueChanged1(const DPL::PropertyEvent& event) LogDebug("[1] Value changed to " << event.value); m_repeats++; - m_model1->counter.Set(event.value+1); + m_model1->counter.Set(event.value + 1); } void SPController::OnValueChanged2(const DPL::PropertyEvent& event) @@ -904,7 +907,7 @@ void SPController::OnValueChanged2(const DPL::PropertyEvent& event) LogDebug("[2] Value changed to " << event.value); m_repeats++; - m_model2->counter.Set(event.value+1); + m_model2->counter.Set(event.value + 1); } RUNNER_TEST(SharedMemory_060_SingleProcess) @@ -923,7 +926,7 @@ RUNNER_TEST(SharedMemory_060_SingleProcess) // wait for destruction Wait(waitable); - int value = sho->GetProperty<0,int>(); + int value = sho->GetProperty<0, int>(); LogDebug("final value: " << value); @@ -933,11 +936,11 @@ RUNNER_TEST(SharedMemory_060_SingleProcess) ////////////////////////////////////////////// -class ListenerTestController: public ListeningController, - public ISharedObjectListener<0,int>, - public ISharedObjectListener<1,int>, - public ISharedObjectListener<2,char>, - public ISharedObjectListener<3,int[64]> +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) : @@ -954,7 +957,7 @@ class ListenerTestController: public ListeningController, const char& value, const void* info = NULL); virtual void ValueChanged(size_t propertyEnum, - const int(& value)[64], + const int(&value)[64], const void* info = NULL); }; @@ -965,17 +968,16 @@ 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) { + 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); + 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); } } @@ -984,7 +986,8 @@ void ListenerTestController::ValueChanged(size_t propertyEnum, const void* /*info*/) { LogDebug("ValueChanged(int) " << propertyEnum << " " << value); - if ((propertyEnum == 0 && value == 1) || (propertyEnum == 1 && value == 2)) + if ((propertyEnum == 0 && + value == 1) || (propertyEnum == 1 && value == 2)) { g_values[propertyEnum]++; if (g_values[propertyEnum] == 3) { @@ -998,8 +1001,7 @@ void ListenerTestController::ValueChanged(size_t propertyEnum, const void* /*info*/) { LogDebug("ValueChanged(char) " << propertyEnum << " " << value); - if (propertyEnum == 2 && value == 'c') - { + if (propertyEnum == 2 && value == 'c') { g_values[propertyEnum]++; if (g_values[propertyEnum] == 3) { m_waitable->Signal(); @@ -1008,12 +1010,11 @@ void ListenerTestController::ValueChanged(size_t propertyEnum, } void ListenerTestController::ValueChanged(size_t propertyEnum, - const int(& value)[64], + const int(&value)[64], const void* /*info*/) { LogDebug("ValueChanged(int[64]) " << propertyEnum << " " << value[5]); - if (propertyEnum == 3 && value[5] == 5) - { + if (propertyEnum == 3 && value[5] == 5) { g_values[propertyEnum]++; if (g_values[propertyEnum] == 3) { m_waitable->Signal(); @@ -1026,7 +1027,7 @@ RUNNER_TEST(SharedMemory_070_SharedObjectListeners) RemoveIpcs(); // setup global flags - for (size_t i=0;iSetProperty<0,int>(1); + sho->SetProperty<0, int>(1); Wait(waitable); RUNNER_ASSERT(g_values[0] == 3); - sho->SetProperty<1,int>(2); + sho->SetProperty<1, int>(2); Wait(waitable); RUNNER_ASSERT(g_values[1] == 3); - sho->SetProperty<2,char>('c'); + sho->SetProperty<2, char>('c'); Wait(waitable); RUNNER_ASSERT(g_values[2] == 3); int array[64]; - memset(array,64*sizeof(array[0]),0); + memset(array, 64 * sizeof(array[0]), 0); array[5] = 5; - sho->SetProperty<3,int[64]>(array); + sho->SetProperty<3, int[64]>(array); Wait(waitable); RUNNER_ASSERT(g_values[3] == 3); @@ -1092,9 +1093,15 @@ class DAO : public DPL::Noncopyable public: DAO() : m_boolValue(false) {} - void SetBoolValue(const bool& value) { m_boolValue = value; } + void SetBoolValue(const bool& value) + { + m_boolValue = value; + } - bool GetBoolValue() const { return m_boolValue; } + bool GetBoolValue() const + { + return m_boolValue; + } private: bool m_boolValue; @@ -1103,7 +1110,7 @@ class DAO : public DPL::Noncopyable /* * Model with property having set delegate defined */ -class MyModel3: public DPL::Model +class MyModel3 : public DPL::Model { public: typedef SharedPropertyExSetProperty( - true, - MyModel3::PropertyType::SetDelegate(&dao, &DAO::SetBoolValue)); + true, + MyModel3::PropertyType::SetDelegate(&dao, &DAO::SetBoolValue)); // check dao value RUNNER_ASSERT(dao.GetBoolValue() == true); @@ -1169,13 +1175,15 @@ class LazySharedObject : public SharedObject public: explicit LazySharedObject(const std::string& semaphore) : SharedObject(semaphore) - ,m_read(false) - { - } + , m_read(false) + {} void Init(); - bool IsRead() const { return m_read; } + bool IsRead() const + { + return m_read; + } private: friend class SharedObjectFactory; @@ -1235,7 +1243,6 @@ RUNNER_TEST(SharedMemory_100_LazyInit) RUNNER_ASSERT(sho3->IsRead() == true); RUNNER_ASSERT(value == 43); - } ////////////////////////////////////////////// @@ -1276,7 +1283,7 @@ RUNNER_TEST(SharedMemory_120_ConditionalSet) g_delegateCalls = 0; - RUNNER_ASSERT(0 == (sho->GetProperty<0,int>())); + RUNNER_ASSERT(0 == (sho->GetProperty<0, int>())); DPL::FastDelegate condition(&SetCondition); DPL::FastDelegate delegate(&SetDelegate); @@ -1286,23 +1293,23 @@ RUNNER_TEST(SharedMemory_120_ConditionalSet) succeeded = sho->ConditionalSetProperty<0>(-2, condition); RUNNER_ASSERT(succeeded); - RUNNER_ASSERT(-2 == (sho->GetProperty<0,int>())); + 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(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>())); + 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(10 == (sho->GetProperty<0, int>())); RUNNER_ASSERT(1 == g_delegateCalls); } @@ -1316,8 +1323,7 @@ class MTSharedObject : public SharedObject public: explicit MTSharedObject(const std::string& semaphore) : SharedObject(semaphore) - { - } + {} void Clear(); @@ -1372,10 +1378,10 @@ void SharedObjectSingleton::Destroy() * Listening controller */ class ShmController4 : public ListeningController, - public ISharedObjectListener<0,int>, - public ISharedObjectListener<1,int>, - public ISharedObjectListener<2,char>, - public ISharedObjectListener<3,int[64]> + public ISharedObjectListener<0, int>, + public ISharedObjectListener<1, int>, + public ISharedObjectListener<2, char>, + public ISharedObjectListener<3, int[64]> { public: enum { @@ -1397,7 +1403,7 @@ class ShmController4 : public ListeningController, const char& value, const void* info = NULL); virtual void ValueChanged(size_t propertyEnum, - const int(& value)[64], + const int(&value)[64], const void* info = NULL); bool NotRegistered(); @@ -1431,7 +1437,7 @@ void ShmController4::ValueChanged(size_t propertyEnum, } void ShmController4::ValueChanged(size_t propertyEnum, - const int(& value)[64], + const int(&value)[64], const void* /*info*/) { LogDebug("ValueChanged(int[64]) " << propertyEnum << " " << value[5]); @@ -1443,7 +1449,7 @@ void ShmController4::ValueChanged(size_t propertyEnum, void ShmController4::Sleep() { DPL::Thread::GetCurrentThread()->MiliSleep( - rand() % MAX_SINGLETON_LISTENER_DELAY); + rand() % MAX_SINGLETON_LISTENER_DELAY); } void ShmController4::OnEventReceived(const int& event) @@ -1463,26 +1469,26 @@ void ShmController4::OnEventReceived(const int& event) case ADD_LISTENERS: // add listener and notify - m_so->AddListener<0,int>(this); + m_so->AddListener<0, int>(this); Sleep(); - m_so->AddListener<1,int>(this); + m_so->AddListener<1, int>(this); Sleep(); - m_so->AddListener<2,char>(this); + m_so->AddListener<2, char>(this); Sleep(); - m_so->AddListener<3,int[64]>(this); + 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); + m_so->RemoveListener<0, int>(this); Sleep(); - m_so->RemoveListener<1,int>(this); + m_so->RemoveListener<1, int>(this); Sleep(); - m_so->RemoveListener<2,char>(this); + m_so->RemoveListener<2, char>(this); Sleep(); - m_so->RemoveListener<3,int[64]>(this); + m_so->RemoveListener<3, int[64]>(this); Sleep(); m_waitable->Signal(); break; @@ -1497,10 +1503,10 @@ void ShmController4::OnEventReceived(const int& event) } } -void MultipleWait(DPL::WaitableEvent (& event)[MAX_THREADS]); -void MultipleWait(DPL::WaitableEvent (& event)[MAX_THREADS]) +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); \ + << #property); \ RUNNER_ASSERT_MSG(false, "No listeners expected"); \ } \ - Catch (MTSharedObject::Exception::ListenerNotFound) { \ + Catch(MTSharedObject::Exception::ListenerNotFound) { \ RUNNER_ASSERT(true); \ } \ @@ -1534,12 +1540,12 @@ RUNNER_TEST(SharedMemory_130_SharedObjectSingleton) ShmController4* controller[MAX_THREADS]; DPL::WaitableEvent waitable[MAX_THREADS]; - const int array[64] = {0,1,2}; + 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); + 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); @@ -1596,7 +1602,7 @@ RUNNER_TEST(SharedMemory_130_SharedObjectSingleton) // remove listeners LogInfo("Removing listeners"); - for (size_t i=0;iPostEvent(ShmController4::REMOVE_LISTENERS); } // wait for listeners @@ -1604,16 +1610,16 @@ RUNNER_TEST(SharedMemory_130_SharedObjectSingleton) // 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'); + RUNNER_ASSERT((singleton->GetProperty<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); @@ -1625,10 +1631,10 @@ RUNNER_TEST(SharedMemory_130_SharedObjectSingleton) // 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) { + for (int i = MAX_THREADS - 1; i >= 0; --i) { controller[i]->PostEvent(DESTROY_EVENT); Wait(waitable[i]); - if (i==0) { + if (i == 0) { /* * Destroy singleton before thread that created it finishes. * This is to properly close all waitable handles opened by diff --git a/tests/dpl/unused/test_sql_connection.cpp b/tests/dpl/unused/test_sql_connection.cpp index 2c2fc4f..4525c98 100644 --- a/tests/dpl/unused/test_sql_connection.cpp +++ b/tests/dpl/unused/test_sql_connection.cpp @@ -20,12 +20,12 @@ * @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. - -*/ + * + * This test has been saved from original test_sql_connection.cpp in wrt-commons + * project. + * + */ #include diff --git a/tests/dpl/unused/test_task.cpp b/tests/dpl/unused/test_task.cpp index 94bd357..995f1cb 100644 --- a/tests/dpl/unused/test_task.cpp +++ b/tests/dpl/unused/test_task.cpp @@ -25,26 +25,25 @@ RUNNER_TEST_GROUP_INIT(DPL) -class MySingleTask - : public DPL::TaskDecl +class MySingleTask : + public DPL::TaskDecl { -protected: + protected: void StepOne() - { - } + {} -public: - MySingleTask() - : DPL::TaskDecl(this) + public: + MySingleTask() : + DPL::TaskDecl(this) { AddStep(&MySingleTask::StepOne); } }; -class MyMultiTask - : public DPL::MultiTaskDecl +class MyMultiTask : + public DPL::MultiTaskDecl { -protected: + protected: typedef DPL::MultiTaskDecl BaseType; void StepOne() @@ -62,9 +61,9 @@ protected: LogInfo("Step three"); } -public: - MyMultiTask() - : BaseType(this, 2) + public: + MyMultiTask() : + BaseType(this, 2) { BaseType::StepList depListStepThree; depListStepThree.push_back(&MyMultiTask::StepOne); @@ -83,11 +82,11 @@ public: RUNNER_TEST(Task_SingleTask) { MySingleTask task; - while (task.NextStep()); + while (task.NextStep()) {} } RUNNER_TEST(Task_MultiTask) { MyMultiTask task; - while (task.NextStep()); + while (task.NextStep()) {} } diff --git a/tests/dpl/utils/bash_utils.cpp b/tests/dpl/utils/bash_utils.cpp index f433fd8..c6a711c 100644 --- a/tests/dpl/utils/bash_utils.cpp +++ b/tests/dpl/utils/bash_utils.cpp @@ -28,11 +28,20 @@ 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"); + 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"); + 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"); + 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/widget_version.cpp b/tests/dpl/utils/widget_version.cpp index 2413b65..0d10117 100644 --- a/tests/dpl/utils/widget_version.cpp +++ b/tests/dpl/utils/widget_version.cpp @@ -75,12 +75,15 @@ RUNNER_TEST(WidgetVersion_M2_O0_nonwac_4) RUNNER_TEST(WidgetVersion_M2_O0_long) { - DPL::String raw(L"123456789012345678901234567890.98765432109876543210987654321"); + 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.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); @@ -254,12 +257,15 @@ RUNNER_TEST(WidgetVersion_Compare_2) RUNNER_TEST(WidgetVersion_Compare_3) { - RUNNER_ASSERT(WidgetVersion(L"1.00000000000000") >= WidgetVersion(L"1.0 test")); + 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_ASSERT(WidgetVersion( + L"19647963733338932479072098437089778943732432.00000000000000004324324324324321") + > WidgetVersion(L"4324324324324324324321.000432")); } RUNNER_TEST(WidgetVersion_Compare_5) @@ -274,5 +280,6 @@ RUNNER_TEST(WidgetVersion_Compare_6) RUNNER_TEST(WidgetVersion_Compare_7) { - RUNNER_ASSERT(WidgetVersion(L"000123000.0 notatest") == WidgetVersion(L"00123000.0 testtesttest")); + 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 index 31d5abe..6f8b3a8 100644 --- a/tests/dpl/utils/wrt_utility.cpp +++ b/tests/dpl/utils/wrt_utility.cpp @@ -62,17 +62,17 @@ RUNNER_TEST(wrt_utility_WrtUtilMakeDir) 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"); + "read, write, execute/search by owner"); RUNNER_ASSERT_MSG(st.st_mode & S_IXGRP, - "execute/search permission, group"); + "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 "); + "NO write permission, group "); RUNNER_ASSERT_MSG(st.st_mode & S_IXOTH, - "execute/search permission, others"); + "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 "); + "NO write permission, others "); } else { RUNNER_ASSERT_MSG(false, "Cannot stat folder"); } @@ -90,23 +90,25 @@ RUNNER_TEST(wrt_utility_WrtUtilMakeDir_PermissionError) if (p == NULL) { int error = errno; RUNNER_ASSERT_MSG(false, "Getting app user UID failed: " - << (error == 0 ? "No error detected" : strerror(error))); + << (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))); + << (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"); + 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))); + << (error == 0 ? "No error detected" : strerror(error))); } - } /** @@ -115,18 +117,18 @@ RUNNER_TEST(wrt_utility_WrtUtilMakeDir_PermissionError) */ RUNNER_TEST(wrt_utility_WrtUtilRemoveDir) { RUNNER_ASSERT_MSG(WrtUtilMakeDir("/tmp/test3/", 0755) == true, - "Could not set up directory for test"); + "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"); + 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; + int error = errno; RUNNER_ASSERT(error == ENOENT); return; } @@ -142,7 +144,7 @@ RUNNER_TEST(wrt_utility_WrtUtilRemoveDir_NoDirError) WrtUtilRemove("/tmp/NOT_EXISTING"); RUNNER_ASSERT_MSG(WrtUtilRemove("/tmp/NOT_EXISTING") == false, - "Removing non existing directory returned success"); + "Removing non existing directory returned success"); } RUNNER_TEST(wrt_utility_WrtUtilFileExists) diff --git a/uncrustify.cfg b/uncrustify.cfg new file mode 100644 index 0000000..2bf1d96 --- /dev/null +++ b/uncrustify.cfg @@ -0,0 +1,170 @@ +indent_align_string=true +indent_braces=false +indent_braces_no_func=false +indent_brace_parent=false +indent_namespace=false +indent_extern=false +indent_class=true +indent_class_colon=false +indent_else_if=false +indent_func_call_param=false +indent_func_def_param=false +indent_func_proto_param=false +indent_func_class_param=false +indent_func_ctor_var_param=false +indent_template_param=false +indent_func_param_double=false +indent_relative_single_line_comments=false +indent_col1_comment=true +indent_access_spec_body=false +indent_paren_nl=false +indent_comma_paren=false +indent_bool_paren=false +indent_square_nl=false +indent_preserve_sql=false +indent_align_assign=false +sp_balance_nested_parens=false +align_keep_tabs=false +align_with_tabs=false +align_on_tabstop=false +align_number_left=false +align_func_params=false +align_same_func_call_params=false +align_var_def_colon=false +align_var_def_attribute=false +align_var_def_inline=false +align_right_cmt_mix=false +align_on_operator=false +align_mix_var_proto=false +align_single_line_func=false +align_single_line_brace=false +align_nl_cont=false +align_left_shift=true +nl_collapse_empty_body=true +nl_assign_leave_one_liners=false +nl_class_leave_one_liners=false +nl_enum_leave_one_liners=false +nl_getset_leave_one_liners=false +nl_func_leave_one_liners=false +nl_if_leave_one_liners=false +nl_multi_line_cond=true +nl_multi_line_define=false +nl_before_case=false +nl_after_case=false +nl_after_return=false +nl_after_semicolon=true +nl_after_brace_open=false +nl_after_brace_open_cmt=false +nl_after_vbrace_open=false +nl_after_brace_close=false +nl_define_macro=false +nl_squeeze_ifdef=false +nl_ds_struct_enum_cmt=false +nl_ds_struct_enum_close_brace=false +nl_create_if_one_liner=false +nl_create_for_one_liner=false +nl_create_while_one_liner=false +ls_for_split_full=true +ls_func_split_full=true +nl_after_multiline_comment=false +eat_blanks_after_open_brace=true +eat_blanks_before_close_brace=true +mod_pawn_semicolon=false +mod_full_paren_if_bool=false +mod_remove_extra_semicolon=true +mod_sort_import=false +mod_sort_using=false +mod_sort_include=false +mod_move_case_break=false +mod_remove_empty_return=false +cmt_indent_multi=true +cmt_c_group=false +cmt_c_nl_start=false +cmt_c_nl_end=false +cmt_cpp_group=false +cmt_cpp_nl_start=false +cmt_cpp_nl_end=false +cmt_cpp_to_c=false +cmt_star_cont=true +cmt_multi_check_last=true +cmt_insert_before_preproc=false +pp_indent_at_level=false +pp_region_indent_code=false +pp_if_indent_code=false +pp_define_at_level=false +indent_columns=4 +indent_member=4 +indent_access_spec=-2 +code_width=80 +nl_max=2 +nl_before_access_spec=2 +cmt_width=80 +indent_with_tabs=0 +sp_arith=force +sp_assign=force +sp_enum_assign=force +sp_pp_concat=remove +sp_pp_stringify=remove +sp_bool=force +sp_compare=force +sp_paren_brace=force +sp_angle_paren=remove +sp_before_sparen=force +sp_inside_sparen=remove +sp_after_sparen=force +sp_sparen_brace=force +sp_before_semi=remove +sp_after_semi_for_empty=remove +sp_before_square=remove +sp_before_squares=remove +sp_inside_square=remove +sp_after_comma=force +sp_before_comma=remove +sp_after_class_colon=force +sp_before_class_colon=force +sp_before_case_colon=remove +sp_inside_braces=add +sp_inside_fparens=remove +sp_inside_fparen=remove +sp_func_call_paren=remove +sp_func_class_paren=remove +sp_else_brace=force +sp_brace_else=force +sp_catch_brace=force +sp_brace_catch=force +sp_try_brace=force +sp_before_dc=remove +sp_after_dc=remove +sp_not=remove +sp_inv=remove +sp_addr=remove +sp_member=remove +sp_deref=remove +sp_sign=remove +sp_incdec=remove +sp_cond_colon=force +sp_cond_question=force +sp_case_label=force +nl_assign_brace=remove +nl_if_brace=remove +nl_brace_else=remove +nl_elseif_brace=remove +nl_else_brace=remove +nl_else_if=remove +nl_try_brace=remove +nl_for_brace=remove +nl_catch_brace=remove +nl_brace_catch=remove +nl_while_brace=remove +nl_do_brace=remove +nl_brace_while=remove +nl_switch_brace=remove +nl_namespace_brace=remove +nl_class_brace=force +nl_fdef_brace=force +pos_class_comma=trail +pos_class_colon=trail +mod_full_brace_do=add +mod_full_brace_for=add +mod_full_brace_if=add +mod_full_brace_while=add diff --git a/uncrustify.sh b/uncrustify.sh new file mode 100755 index 0000000..49ad3cf --- /dev/null +++ b/uncrustify.sh @@ -0,0 +1 @@ +uncrustify -c uncrustify.cfg --no-backup `find . -regex "\(.*\.cpp\|.*\.h\|.*\.c\|.*\.cc\)" | grep -v "orm.h\|orm_generator.h\|3rdparty\|examples"` -- 2.7.4